diff --git a/dm/games/01006F8002326000/patches.py b/dm/games/01006F8002326000/patches.py index a4892787cc..56c0886327 100644 --- a/dm/games/01006F8002326000/patches.py +++ b/dm/games/01006F8002326000/patches.py @@ -233,5 +233,5 @@ def screen_shape(ctx): BINDING = [ {'what': "screen shape: the sizes, the view, the layouts' projection and their edge widgets (DM_SCREEN_ASPECT)", 'now': 'build', 'goal': 'game', 'purpose': 'rendering', 'why': "the output size is the host's, but where the game takes its sizes, its cameras and its layouts are this build's code", - 'blocked': 'the stubs have no function-matched form yet'}, + 'blocked': "the stubs have no function-matched form yet (Ocarina of Time's screen-shape stubs, function-matched others of its frame-step rule, are the model)"}, ] diff --git a/dm/games/0400486024DEC000/README.md b/dm/games/0400486024DEC000/README.md index 1487d7b177..dccb7e4941 100644 --- a/dm/games/0400486024DEC000/README.md +++ b/dm/games/0400486024DEC000/README.md @@ -14,6 +14,7 @@ A Switch 2 game: update v131072, SDK 22.2.8 (`Ounce`). Nintendo EPD's engine (se | `tex_flush_upload on`, `tex_dirty_upload on` | `game.tsv` | as Tears of the Kingdom: the CPU writes the terrain tiles' height (R32F), blend and hole (RGBA8) maps into textures after creating them. Without the keys those textures stay zero: flat blue holes in the ground around the path with grass floating in them, and grey stone where the console shows dirt | | `shader_groups`, `shader_note` | `game.tsv` | shaders grouped as `/Shader/`, `/Effect/`, `/Lib/`, `/UI/` | | `pad_layout full` | `game.tsv` | a 3D field and both sticks | +| `screen_aspect any`, screen-shape stubs | `game.tsv`, [`patches.py`](patches.py) (frame step rule, `others`) | the picture and the HUD take the window's or the screen's shape ([Screen shape](#screen-shape)) | Render conditions, which the host evaluates for every game ([Conditional rendering evaluated at replay](../../../docs/reference/rendering.md#conditional-rendering-evaluated-at-replay); until 2026-11-12 the profile key `render_cond`): agl clears a copy of the prepass depth again under a render condition the console skips. Run unconditionally, the opaque pass's `EQUAL` test fails everywhere ([PR 1299](https://github.com/seedds/nxnative/pull/1299)'s finding). @@ -80,6 +81,89 @@ Measured on an M6 Mac with 16 GB, headless, on one walk with camera turns (`walk - Why so much: the game's own memory is about the console's 9 GB application pool, and on the Mac its textures also exist as Metal textures, as Metal cannot sample the guest's block-linear storage. - Resolved in part ([#1831](https://github.com/seedds/nxnative/issues/1831)): render targets that move in the game's 305 MB pool and change size with its dynamic resolution still get a new Metal texture each time. Their memory is now recycled ([Render targets that move with the dynamic resolution](../../../docs/reference/rendering.md#render-targets-that-move-with-the-dynamic-resolution-get-new-metal-memory-each-time)). Since 04419bc2 the resolution moves, and on a 16 GB MacBook Air M4 the game stuttered (p95 99 ms) with GPU allocation near 15 GB. On an M6, while the resolution moved in the village, the target site added 455-521 MB to the residency set per 300 frames without recycling and 27-37 MB with it once heaps were waiting, and frame p90 went from 33-50 ms to 17-18 ms. Open: the live targets' steady total, about 2.1 GB in the village. They cannot share the pool's memory as on the console: the game keeps live targets in the part of the full-size scene target its resolution leaves unused, which only NVN's layout allows (PR #1453). [A report of a GPU driver panic](https://github.com/seedds/nxnative/pull/1299) lines up with this churn. The reporter's Mac has not been tested. +### For an iPhone or iPad build + +Current (2026-11-09): plays on an M1 iPad Pro (11-inch, 3rd generation, `iPad13,4`, 8 GB, iPadOS 27.0.1), docked, at 20 fps where its views are light. Built from upstream `main` 7ffa63cc with this branch, chain `dedc9391c30b`, the device's `env.txt` holding only `DM_LAUNCHER=0`, `DM_NVN_GPUPROF=every:600` and `DM_GUEST_FILE_MIN_FREE=2G` (none needed for play). Two 32-minute scripted runs from a save at the Great Deku Tree's entrance (camera turns and short steps, "Try Again" after a death). +- **Memory.** iOS gives the app 7.97 GB of room against the game's 9.00 GB pool, so the guest goes into files by itself ([the guest in files](../../../docs/reference/memory.md#ios-ends-the-app-once-the-guests-touched-pages-reach-its-memory-limit)): footprint 2.2-2.3 GB, headroom to the memory limit 5.87 GB at its lowest, 4.4 GB of guest pages on disk. Metal's working set is 5,461 MB: [textures in GPU-only memory share bytes](../../../docs/reference/memory.md#textures-in-gpu-only-memory-took-an-allocation-per-description) there by themselves, and the residency set holds 3.2 GB. With each render target in a recycled heap of its own, the set reached 5,184 MB at an outdoor save load and every command buffer failed out of memory. +- **Frame rate and GPU time.** At the Deku Tree's entrance: 20.0 fps in every 300-frame window of both runs (frame p50 50.0 ms, the frame step's 3-vsync hold; worst p95 51.0 and 66.6 ms), GPU 34-35 ms a frame (29 ms of work over 127 encoders, 205 MB of attachments loaded and 215 MB stored), game speed 0.97-1.00 after the load. Views deeper in that take 54-67 ms of GPU fall to 11-12 fps, and the game runs slow (game speed 0.53-0.61), as no hold is longer than 3 vsyncs. The title scene takes 61 ms of GPU, the game over screen 66-74 ms. Kokiri Forest by the owner's eye: 20 fps in handheld mode, 15 docked. +- **iPhone** (current, 2026-11-09): plays on an iPhone 17 (`iPhone18,3`, 8 GB, A19, iOS 26.6.1) from the owner's save in Kokiri Forest, with the launcher's 30 fps cap and Dynamic resolution on. Built from upstream `main` 04811a63 with this branch and, for testing, PRs #1842, #1901, #1942 and #1751, chain `39eb2f781d07`. iOS gives the app 5.96 GB of room (the iPad 7.97), Metal's working set is 5,461 MB. Before [the pool table left shader-code pools out](../../../docs/reference/memory.md#shader-code-pools-wired-by-the-raw-pool-table) it stuttered too much to play: the guest's file pages were read back all the time, 14-17 fps. Now 27 fps standing, 27-30 walking, frame p50 36.5 / p95 40 ms, GPU p50 32 ms, the guest file's page-ins at 100-400 every 10 s. Frames just over the cap's 33.3 ms are late: about 30 of 300 are dropped, a light stutter walking. The title, with its movie on its own clock, holds 30 fps. An earlier build without these fixes ended in a kernel panic after the save loaded (`wait for termination failed … AppleCentauriManager`). +- **Pacing at the launcher's 30 fps cap** (2026-11-10). The hold cannot rise above 2 vsyncs there, and frames of 36 ms took one 66.7 ms gap about every 11 frames on the 30 Hz link: iPhone walk in Kokiri Forest 30-33 per 300; M1 iPad at the Deku Tree save, dynamic resolution on, 22.8 per 300 at 27.9 fps. With late frames shown at the next vsync of a 60 Hz link at frame latency 2, the M1 iPad showed 27.7 fps with gaps of 33 / 50 ms (81 / 17%) and 0.2 of 66.7 ms per 300 ([why and the three runs](../../../docs/reference/frame-rate.md#late-frames-at-a-30-fps-cap-on-the-30-hz-display-link)). The owner found the camera turning smooth on the 30 Hz link and did not judge the new build by eye. Open: the iPad's title (40 ms frames) still shows uneven 29-50 ms gaps, and its movie gets a new picture on only about 210 of 300 game frames (`[codec] AV1 decoder` lines: about 600 dropped to the movie's clock per 300 frames), where the iPhone's 33 ms title gets one every frame. On the iPhone 17 with the change (Kokiri Forest, camera turns), the first gameplay at thermal 1 showed gaps of 33 / 50 ms (52 / 48%) and 1 longer one in 2,096, p99 50 ms, game time 0.999; at thermal 2 it ran CPU-bound at 13-22 fps (frames over 50 ms, footprint up to 3.2 GiB) and game time fell to 0.731, more than the 3 vsyncs a step can carry, which a hold of 3 would not change. +- **iPhone 17: GPU time and what limits the frame** (current, 2026-11-10). The owner's launcher settings (30 fps cap, dynamic resolution on, encoding on its own thread), Kokiri Forest from the owner's save, camera turns by `iphone_cam.sh` in the work folder. GPU frames from `DM_NVN_GPUPROF` with its CPU timeline: + + | Frame | Build | GPU span | GPU work | Gaps before a submission / inside one | Submissions, encoders | + |---|---|---|---|---|---| + | 3000 | before | 37.9 ms | 18.9 ms | 17.9 / 1.1 ms | 32, 152 | + | 3600 | before | 34.9 ms | 20.2 ms | 13.6 / 1.1 ms | 30, 153 | + | 8100 | after | 27.7 ms | 19.7 ms | 7.4 / 0.7 ms | 31, 153 | + | 9000 | after | 27.0 ms | 21.0 ms | 5.3 / 0.7 ms | 31, 164 | + | 12600 | after | 25.3 ms | 20.1 ms | 4.7 / 0.5 ms | 31, 160 | + | 13500 | after | 32.9 ms | 23.2 ms | 7.6 / 2.1 ms | 31, 156 | + + The gaps before each submission were the replay waiting for the encode thread at every submission's end: [the GPU idles before each submission while the replay waits for the encode thread](../../../docs/reference/rendering.md#the-gpu-idles-before-each-submission-while-the-replay-waits-for-the-encode-thread). What remains is the GPU waiting while the host translates a long submission (2-8 ms for some), whose first segment goes out only after 64 draws. GPU p50 in gameplay is 21-24 ms (median of the 300-frame timing windows), under the 33.3 ms the cap allows, so shader pull requests #1752 and #1833 were not tried. + - The frame is CPU-bound: 16-20 fps, frame p50 40-54 ms, p95 100-118 ms, 114-196 frames dropped per 300 (before the fix: 15.0 fps, p50 48.6 ms, 132 dropped; that run also built pipelines). The submit thread spends 18-25 ms of CPU a frame in 25-32 ms of wall clock (about 30 M cycles at 0.5 cycles per instruction), and the game's main thread yields 13,000-22,000 times a frame (5.5-9.4 ms). The phone reaches thermal state 1 after 44-64 s and 2 after 360-390 s; from then on about 30% of CPU time runs on performance cores, at a mean 1.5 GHz on the submit thread. The footprint grows from 0.7 GiB at the title to 3.2 GiB in play. + - A/B of the fix (`DM_NVN_SUB_DRAIN=ab`, `DM_AB=600`): uncapped, the frame step settles on the 3-vsync hold in both modes, mean frame p50 49.0 against 50.4 ms over 12 phase pairs; at the cap the title phases 33.3 against 36.6 ms. It removes about 37 waits a frame from the submit thread, but the frame rate is set by the CPU work. + - **Not this:** the command allocator pool. Its cap of 8 submissions in flight made the submit thread wait about 4 times a frame (3.4-8.2 ms). A cap of 128 (an A/B against 8) removed the waits but no frame time (gameplay frame p50 54.7 against 56.0 ms over 11 phase pairs), and each allocator keeps 8-13 MB, so the footprint grew from 3,230 to 3,535 MiB. Reverted. + - Open: the translation's CPU cost on the phone, the 1,260-1,710 samples-passed reports a frame written at the GPU's end, and the footprint's growth in play. +- **iPhone 17: through the Great Deku Tree** (current, 2026-11-10). The owner played from Kokiri Forest through the Great Deku Tree to the Kokiri Emerald on the iPhone 17, at the launcher's 30 fps cap with dynamic resolution on, on a build of [smaller textures](../../../docs/reference/memory.md#large-sampled-textures-leave-out-their-largest-level-on-small-devices), [upload staging released](../../../docs/reference/memory.md#upload-staging-kept-for-reuse-on-small-devices), [MetalFX for the game's upscaler](../../../docs/reference/rendering.md#a-games-own-upscaler-drawn-by-metalfx) and `DM_SCREEN_PIXELS=1` ([Screen shape](#screen-shape)), on an earlier base (branch `iphone-exp`, chain `39eb2f781d07`), with [PR #2241](https://github.com/seedds/nxnative/pull/2241)'s frame generation for part of it. The runs, each over frames 6,000-22,500 (300-frame windows; `$W/ipad/device/`); `r1_*` and `r2_*` are the camera script `m-run/iphone_cam.sh` in Kokiri Forest, landscape 2352x1080, with smaller textures on; `b2_*` are the owner's hand play, landscape 2120x976 with `DM_SCREEN_PIXELS=1`: + + | Run | What | fps | Frame p50 / p95 ms | GPU p50 ms | Late /300 | Windows over 60 ms | Page-ins | Resident MB | Footprint GB | Headroom MB | + |---|---|---|---|---|---|---|---|---|---|---| + | `r1_base` | the build as it is | 29.1 | 34.0 / 38.1 | 29.3 | 19 | 3 of 56 | 20,949 | 2,709 | 2.63 | 3,434 | + | `r1_reuse0` | `DM_NVN_UPLOAD_REUSE=0` | 29.2 | 34.0 / 37.6 | 29.8 | 18 | 1 of 56 | 14,861 | 2,584 | 2.51 | 3,559 | + | `r1_chunk256` | `DM_GUEST_FILE_CHUNK=256M` | 29.1 | 34.1 / 38.0 | 30.0 | 19 | 1 of 56 | 17,597 | 2,737 | 2.67 | 3,406 | + | `r1_nocomp0` | `DM_NVN_FAMILY_NOCOMPRESS=0` | 29.1 | 34.0 / 37.9 | 29.6 | 18 | 1 of 56 | 16,804 | 2,722 | 2.67 | 3,421 | + | `r2_mfx_game` | staging released, Game's upscaler: the game's | 29.0 | 34.0 / 39.2 | 28.0 | 20 | 3 of 56 | 21,677 | 2,705 | 2.64 | 3,438 | + | `r2_mfx_on` | Game's upscaler MetalFX, before the square-root shape: every variant refused, the game's shader ran | 29.0 | 34.1 / 38.2 | 30.2 | 20 | 2 of 56 | 18,012 | 2,729 | 2.66 | 3,414 | + | `b2_play1` | hand play, MetalFX drawing the upscaler | 27.8 | 34.4 / 37.6 | 25.8 | 7 | 7 of 56 | 192,408 | 3,208 | 3.12 | 2,935 | + | `b2_play2` | hand play with frame generation (#2241), the boss | 26.4 | 36.5 / 54.2 | 18.9 | 50 | 6 of 20 | 208,863 | 3,312 | 3.24 | 2,831 | + + The hand-played runs go through new scenes, so their page-ins and residency are not comparable with the scripted ones. + - **Not this:** `DM_GUEST_FILE_CHUNK=256M`, within noise. `DM_NVN_FAMILY_NOCOMPRESS=0`, no gain (attachments 133 / 149 MB loaded / stored a frame against 129 / 147 MB), and the rule it turns off keeps the M1 iPad from a GPU hang. + - **Frame generation** (#2241, run `b2_play2`): 9,000 frames generated, the history never started again; the boss fight at 29.3-29.9 fps of game frames, shown at 60, GPU 15-19 ms. About 1,300 presents were shown without a generated frame before them because they were late (2,081 by the run's end). + - **Open:** the movie cutscenes run at 15-18 fps: nn::ndve's movie network takes 35-70 ms of GPU a frame on the phone, so a cheaper movie path is needed (see also [PR #2240](https://github.com/seedds/nxnative/pull/2240), movie decoders on their own thread). The first visit to a scene state (Kokiri Forest after the boss) froze while pipelines were built on the submit thread: 1.4 s and 2.0 s in two 300-frame windows, with 746 textures uploaded in one frame. The `DM_NVN_CPUPROF` report is empty with the encode thread on ([PR #2197](https://github.com/seedds/nxnative/pull/2197) fixes it). `DM_MEMSTAT` wrote no file on iOS. +- **iPhone 17: ended entering Hyrule Field** (current, 2026-11-11, branch `iphone-mem` on `iphone-pso`). 67 minutes from Kokiri Forest, the owner's launcher settings: ended for `proc-thrashing` before the field's cutscene, 5.56 GB of the phone wired, 67 MB free, the app at 3.53 GB, the headroom still 2.7 GB ([the system ran out of memory](../../../docs/reference/memory.md#the-system-ran-out-of-memory-while-the-apps-headroom-still-read-27-gb)). The field's load (frames 9,753-9,765) added 2,023 MB to the residency set (`up_big_src` 732 MB, textures 306, pools 287, upload blocks 262), which stayed at 4.0 GB, and the guest's file pages were read back 6.1 GB in the last 90 s. + - The Mac reproduction (`m-run/field_run.sh`, `field_mem.sh` and `drive_mem.sh` in the work folder, a copy of the phone's save, the guest in files): the load from the title into the field's tunnel adds 5.3 GB to the set within 300 frames, at most 4.3 GB after one commit; the set levels off at 4.5-5.1 GB walking out to the bushes by the edge (5.8 GB in the reference run, which went back into the forest first). The duplicates the census gave (214-923 MB) were [a counting error](../../../docs/reference/memory.md#the-census-counted-a-resolution-familys-textures-each-at-its-own-size): 78-122 MB by allocation, all held by the game's own live texture objects. + - Host changes on the branch: [memory pressure trims and a system memory line](../../../docs/reference/memory.md#the-system-ran-out-of-memory-while-the-apps-headroom-still-read-27-gb), [a budget for an upload batch's reads over guest memory](../../../docs/reference/memory.md#an-upload-batchs-reads-over-guest-memory-had-no-budget) (it does not bind on the Mac: 226-233 MB at most at once). + - The phone run with them (`ipad/device/mem_1111a`, from the field save "Hyrule Field, 11:37", 10,500 frames): ended for proc-thrashing at frame 12,044 (below). Through the field's cutscene, across the field to the castle town at 20-24 fps (frame p50 33-38 ms); the system at 5.0-5.8 GB wired and 75-160 MB free, the residency set 3.2-3.96 GB, the headroom 2.75-3.5 GB. Two memory pressure warns at the castle town's load (75 and 114 MB free, 5.8 GB wired); their trims gave back 32 and 48 MB of staging, with no render-target heap waiting and 380-451 releases still behind the GPU: what the set holds is what the frames use. That load added 2.85 GB to the set within 300 frames, at most 4.19 GB after one commit; the upload reads stayed under their budget (226 MB at most at once, at the field's load). + - Back out on the field after the castle town (frames 11,400-12,040): a long load, then under 1 fps with the music playing on. A critical pressure event with 42 MB free and 6.19 GB wired, the residency set at 4.48 GB (3.2 GB after the first field load): each load leaves the set larger. The trims gave back 12-40 MB. The guest's file pages were read back 9.4 GB in one 10-s interval, and frames took 2-4 s, nearly all of it in submit (the encode thread's page faults). Then iOS ended it (`JetsamEvent-2026-11-11-151054`, frame 12,044, 11 minutes from the start): `proc-thrashing`, the app at 3,559 MB, 6,046 MB of the phone wired, 22 MB free, 1,161 processes ended in the event. The same death as the first run, sooner, from the same cause: the trim cannot shed what the set holds, so it is not fixed. + - Open: the castle town is not playable on the phone, under 10 fps (frame p50 56-66 ms, p95 120-220 ms): the guest's file pages are read back at 0.75-2.0 GB per 10 s (thrashing, more than before the death), and 13 pipeline bases compiled in the background for 54 s. This run began at the field save, not after an hour of play as the death did, so one survival does not settle it. What would lower the wired memory: the guest pools made resident (1.7-1.9 GB on the Mac, file pages on the phone), the render targets. + - **What the set holds across loads** (current, 2026-11-11, branch `iphone-mem2`). The Mac reproduction with the phone's settings (`DM_NVN_WINDOW_ALIAS=1 DM_NVN_TEX_DROP_MIP=1`, the guest in files, `m-run/drive_mem2.sh` in the work folder): the set grows on each area's first load and does not grow with going back and forth. 3.46 GB on the field; 4.23 GB after the first load into Kokiri Forest (the 12288x12288 Depth16 target's own 296 MB heap, too large for a span; textures uploaded from pools +149 MB; other targets outside the spans); then 4.26-4.28 GB in the forest and 4.37-4.39 GB in the tunnel over four round trips, 5-15 MB more each. The system's wired memory went from 6.4 to 7.2-7.5 GB. + - What grows: textures uploaded from the game's pools, 1,176 / 1,713 / 1,935 of them, 467 / 634 / 829 MB on the field, in the forest and back in the tunnel. All are named by live descriptors of texture objects the game has not finalized, in pools that still exist: the game keeps them, and on NVN they cost nothing beyond their pools, while here each is a Metal copy. 17-23 textures (10-12 MB) are named by nothing. Freeing the copies would be an eviction of host copies of live textures: the serial table, its packaged entry, the sharing table and the pool tables at once, with a re-upload at the next use. Not done. + - The guest pools in the set are the game's live pools (1.68-1.77 GB; the field's went down by 87 MB at the forest's load). Those only the raw pool table names, 710-778 MB, stay: a raw-memory shader may reach any of them through a pointer it loads, and nothing says beforehand which ([A read through a pointer to a buffer outside the residency set returns zeros](../../../docs/reference/memory.md#a-read-through-a-pointer-to-a-buffer-outside-the-residency-set-returns-zeros)), so no safe rule leaves them out. + - **The iPhone 17 with this build** (`ipad/device/mem2_1111`, after a phone restart, from "Hyrule Field, 11:37": the castle town, the temple and back, fights on the field, Lon Lon Ranch, then saved): not ended, no jetsam report, 11,400 frames in the log. Four memory pressure warns, no critical. The system at 5.7-6.27 GB wired, 54-75 MB free at the warns; the set at 4.0-4.3 GB, 4.66 GB at most (a warn). What the set held at the end (4.24 GB): guest pools made resident 2.08 GB (2.12 GB at the second warn, 909 MB of them named by the raw pool table only), textures uploaded from pools 0.79 GB (1.04 GB at most; they also go back down, to 0.59 GB, so the game finalizes some), targets outside the spans 0.70 GB, span heaps 252 MB. Frame p50 33 ms in the field's 300-frame windows, 49-89 ms in the heavy ones (p95 up to 677 ms, frames up to 3.9 s). The same wired memory as the run iOS ended (6.05 GB), so surviving this once does not show a fix: this build changes only what is measured. On the phone the guest pools, not the uploaded textures, are the largest part. + - **Branch `iphone-mem3`** (current, 2026-11-11): what the phone's set holds, by part. The 168 uploaded textures held by nothing were [re-uploads' spares](../../../docs/reference/memory.md#a-re-uploaded-textures-spare-stayed-resident-until-its-texture-object-went) (40 before any re-upload, 168 after 129), now retired after 3 s idle. The 909 MB of pools named by the raw pool table only stay: [no rule says beforehand which pools a raw-memory shader reaches](../../../docs/reference/memory.md#a-read-through-a-pointer-to-a-buffer-outside-the-residency-set-returns-zeros) (831 of the game's 851 such shaders take an address through a loaded pointer or a loop, and every frame runs about 185 of their draws). The uploaded textures nothing has used for 30 s are [freed at memory pressure](../../../docs/reference/memory.md#uploaded-textures-of-areas-the-game-has-left-stayed-in-the-residency-set): on the Mac's field, two trims freed 119 MB and 215 MB (set 3,487 → 3,163 MB). The Mac's route (`m-run/m3a`) had no re-upload and no spare; its drive lost step at the owl's talk, so it has no forest numbers. The phone runs with this branch: next. + - **The iPhone 17 with `iphone-mem3`** (current, 2026-11-12, `ipad/device/mem3_1111` and `ipad/device/mem3_drive`). Two runs of the owner's from "Hyrule Field, 11:37": the first stopped drawing at the castle entrance's load 181 s in, the sound playing on, the signs of [the residency commit frozen over the guest's files](../../../docs/reference/memory.md#the-residency-commit-froze-over-the-guests-files) (the app then went, maybe from a debugger attached to it); the second ended at frame 10,416 (520 s) at the castle gate with frames still coming, with no jetsam or crash report. That run's peaks were 6.12 GB wired, the set at 4.37 GB, two pressure warns (mem2's run: 6.22 GB, 4.66 GB, four warns). The next launch hung before its first log line until a SIGKILL, so the phone itself was in a bad state then. + - Then one process driven alone (`DM_CTL`, from the drawbridge autosave): 60 rounds of the castle town and the field with a `memtrim` before each load, 120 loads in 2.4 hours (177,611 frames). Not ended, every screenshot clean. 77 pressure warns, no critical; 206 trims freed 152,019 idle uploaded textures (42.9 GB in all, each made again at its next read). Wired at most 6.29 GB, free down to 33 MB, the set at most 4.43 GB (3.82 GB at the end). Frame p50 36-50 ms across the 300-frame windows (p95 median 71 ms, at most 167 ms). The trims do not set off the freeze. + - Open: what ended the owner's second run, and whether the first was the commit freeze (mlock is refused on mem2 too, 2,002 times in its run, so the commit still pages in some files itself). + - The phone's `line 4926: 64, 512 MB` back on the field was [31-64 linear targets over one 8 MB pool counted at the pool's size each](../../../docs/reference/memory.md#the-residency-sets-breakdowns-counted-each-texture-over-a-buffer-at-the-buffers-size), not memory. + - The white flash on the bushes by the edge shows on the Mac too, at frames with no load (`m-run/shots/m1_j.png`): [the foliage's single-frame white shapes](../../../docs/reference/shaders.md#position-invariance-across-shaders), not memory. +- **Metal 4 pipelines** (current, 2026-11-12): the profile sets `pso_mtl4 on`, so on iOS render pipelines go through MTL4Compiler with the [pipeline archive made offline](../../../docs/development.md#the-pipeline-archive-made-offline) and the hybrid pipelines. Through the `MTLDevice`, each render pipeline first drawn in a scene state the phone had never drawn compiled on the submit thread: on the iPhone 17 in Kokiri Forest after the first boss, about 17 pipelines of about 400 ms each made 8 frames of 0.17-1.26 s (6.0 s in all), every wait "hybrid off". The archive for `applegpu_g18p` holds every pair's pulling base (30,690) and a pipeline per compute shader (4,125): 3,501 MB, 28.5 minutes of `metal-tt` on the Mac. The launcher's Metal 4 pipelines setting (`DM_PSO_MTL4`) still overrides the key. +- **Not this:** no thread of the game makes a [clock wait](../../../docs/reference/threads.md#clock-waits-sleep-to-their-predicted-end) (no `clock waits up to frame` line in either run), so that rule's predicted sleep plays no part in its speed. +- **iPhone 17: the fall to 5-18 fps, by night and in a fairy fountain** (2026-11-14; the stalls resolved, the low clock open). The owner's play held 25-30 fps by day, then 5-10 fps in Hyrule Field and Kakariko Village by night and 12 fps in a fairy fountain of 640 draws (frames of 88 ms for 34-44 ms of GPU, the CPU nearly idle, the render size at its 943x434 floor), also after a restart. It is no more work at night: [the phone's GPU clock had fallen and the frame's submissions waited behind its first one](../../../docs/reference/frame-rate.md#a-frames-submissions-queued-behind-its-first-one-while-the-iphones-gpu-clock-is-low). From the save in the fountain, unattended (`iphone_drive_batch.sh`, camera turns only), 20 loads with each submission in its own command buffer: 6 began in the slow state and stayed in it, the others held 33.3 ms with `GPU p50` 30 ms (the governor's doing: 14 ms for the first 40 s after the load). Submissions merged into one command buffer (the fix), alternating with the old commits every 900 frames in one process: in the slow state frames of 42-45 ms (p90 51-55) against 54-70 ms (p90 75-94) and 5 command buffers a frame against 29; in a run that holds, 33.3 ms either way and `GPU p50` 28.6-29.1 against 30.1 ms. Open: in the slow state the game now runs at about 23 fps, its GPU time plus 4 ms, and the clock stays low (what is left of the host's share is the present's wait for its drawable in front of the next frame, 5 ms in the frames looked at); a day pair is missing, as the save is at night and this build was not played by day; Hyrule Field and Kakariko Village by night are not measured with it (the driver cannot walk there). +- Open: the GPU time of the heavy views on the M1 iPad (the frame leaves the GPU idle a quarter of the time, and its 110 render passes reload their attachments; on the iPhone 17 most of that idle time was the replay's wait, resolved above). A GPU hang after 18.5 minutes of play on an earlier build (`kIOGPUCommandBufferCallbackErrorHang`, then GPU access revoked): both hung command buffers held the Hi-Z task `a5288d0a6c4971fd` and its mesh `3439aaa071d868ae`, the draws of the M1 Mac's hangs in [PR #1842](https://github.com/seedds/nxnative/pull/1842). One kernel data abort on the iPad (2026-11-09 03:57) in kernel code that handles GPU-wired memory, cause unknown. Building for iOS on 7ffa63cc needs [PR #1906](https://github.com/seedds/nxnative/pull/1906) (`IOBluetooth` is linked otherwise). + +## Screen shape + +Current. With `screen_aspect any` (launcher *Picture shape*, `DM_SCREEN_ASPECT`, `auto` by default) the game renders in the shape of the Mac window, live while playing, any shape from 0.25 to 6 (`loader.c` `SCREEN_MIN` / `SCREEN_MAX`, only to keep out a window a few pixels high). On iOS it follows the space the picture has (`front_ios.m`, [iOS layouts](../../../docs/reference/rendering.md#ios-layouts-portrait-a-half-folded-duo-ipad-windows)): the screen in landscape; upright ([Rotation](../../../docs/settings.md#rotation) Portrait on an iPhone, or an iPad turned) the whole screen with the touch controls over its lower half ([Portrait layout](../../../docs/settings.md#portrait-layout) Full screen, the default; 0.46:1 on an iPhone 17), or the part above the controls (Picture above controls; 402x375 points, 1.07:1). The stubs are function-matched `others` of the frame-step rule in [`patches.py`](patches.py), found on v131072 `main` (build `e0f3ccfa…`): + +| Label | Function | What the stub does | +|---|---|---| +| `output size` | `main+0x1087f40`, the display settings' size setter | the requested size × the shape's factors (state +0xa4 / +0xa8), capped at 1.5× the pixels, each side a multiple of 8; copies the camera multipliers asked (+0xc4 / +0xc8) to the applied ones (+0xb8 / +0xbc). The crop, the scene's targets and the dynamic-resolution sizes follow | +| `window crop` | `main+0xe9a860`, setCrop | a crop beyond the window textures (2560x1440 at start) grows them; the next acquire re-creates them (`main+0x527fc0`) | +| `camera copy` | `main+0x33a8c0` (+0x2ec) | each frame the camera named "Main" hands its cached `sead::PerspectiveProjection` matrix here; rows x / y × the applied multipliers, the aspect beside it, in memory and in the registers the frustum code reads after | +| `display update` | `main+0x6502e0` (+0x18) | sets flag bit 17 when the loader's change count (+0xac) moved since the one applied (+0xc0): the game recomputes its size, so a resized window takes effect while playing | +| `hud upload` | `main+0x2d2ba0` (+0x4c) | the screen draw's copy of its uniform block (both orthographic matrices and the layout size): rows x / y × the HUD's multipliers, the size ÷ them, each frame | +| `layout size` | `main+0x583fd0`, the getter of a layout file's screen size | the size the HUD draws with, for the game's conversions between the layout space and the screen; the screen's init (`screen init`, `main+0x773b90`) still gets the file's | + +- **The rule.** Landscape wider than 16:9 keeps the vertical angle and shows more at the sides; between 1:1 and 16:9 it keeps the horizontal angle and shows more above and below. Upright takes the scale of the same screen turned landscape: its width gets what that screen's height gets, so turning a phone or a window keeps the characters' size and shows another part of the world, up to the upright cap below. The output keeps the requested height (wider) or width (taller), scaled down to 1.5× the requested pixels past that: an iPhone 17 upright (shape 0.460, with the upright cap) renders 1200x2600 for the game's handheld 1920x1080, about the panel's own pixels (device log `present: picture shape 1200x2600`), and the upscaler and the output-resolution passes run at that size. `DM_SCREEN_PIXELS` (0.5 to 1.5, opt-in; `loader.c` `screen_pixels_cap`) lowers that bound without a re-patch: the loader scales both size factors (+0xa4 / +0xa8) by one number so their product is the bound, and the stub keeps the shape, the multiple of 8 and the camera (`=1` upright: 976x2120 instead of 1200x2600, 34 % fewer pixels; in the iPhone 17's landscape, 2.17: 2120x976 instead of about 2352x1080). The owner played the iPhone 17 in landscape with `DM_SCREEN_PIXELS=1` (2026-11-10, runs `b2_play1` and `b2_play2`, 2120x976, with smaller textures, staging released and MetalFX for the upscaler): "very smoothly, practically locked 30 fps". No A/B against the default was run: the GPU time it saves is estimated at about 1-1.5 ms a frame from the upscaler's and the output passes' share, not measured, against the sharpness it costs (the presenter then scales 1.24× per side to the panel), so the default stays the stub's 1.5. +- **Why the first attempts changed nothing:** the projection is cached ([a camera that caches its matrix](../../../docs/reference/rendering.md#a-screen-shape-stub-on-the-projection-setter-changes-nothing-the-camera-caches-its-matrix)): `PerspectiveProjection::set`, `tanf` and the 16/9 literals do not run in play. Found with `DM_PROBE_FINDMAT` and the write watch on the render camera's matrix. +- **The HUD** (eui: layouts `UI/Layout2Archive/*.blarc.zs`). Every layout file holds a screen size of 3840x2160 (LayoutResData +0x200, file offset 0x2f8); each screen builds its orthographic projection from it once and copies it to the GPU each frame, so the HUD was drawn in a 16:9 space stretched over the output. The `hud upload` stub gives that space the output's shape at the HUD's pixel size: its multipliers are the camera's divided by the largest of them and 1, so in landscape the HUD keeps the size it has at 16:9 of the same height or width, and upright the whole 16:9 space still fits the width (smaller, nothing cut off). Checked on the Mac with live resizes (iPhone and iPad shapes upright and landscape, 1700x478, 16:9), the pause menu, the "A Open" prompt and the Kokiri Forest cutscene with its location card at 2.2. +- **Open: the HUD's edges.** eui places every pane about the screen's centre and does not anchor to its edges (a copy of PlayerStatus_00 made 4752 wide drew round hearts at their 16:9 place), so the HUD keeps its 16:9 arrangement in the middle: in wide shapes the hearts are at the 16:9 band's left edge, not the window's; upright the HUD sits around mid-height. The layouts mark their edge groups with 60x80 null panes at the space's edges (PlayerStatus_00's `N_ScaleL_00` at (-1920, 1078), `N_ScaleR_00` at (1920, 1078); MenuOverlay_00's at (0, ±1000)), and full-screen panes are exactly 3840x2160 at the centre (EventFade_00, LoadingFade_00, MenuBG_00): moving the first to the screen's edges and stretching the second needs eui's per-frame pane transform, not found yet. A pane instance (0xb0 bytes in the layout's array, layout +0x100) holds size +0x58, scale +0x60, rotation +0x68, translation +0x6c, a local rect +0x84..+0x90 and flags +0xa8, but no world matrix and no link to its record in the file. Until then the pause menu's backdrop and fades cover the 16:9 middle only, with the scene at the sides. +- **The upright cap** (current). Upright, the rule alone gave a phone (0.46:1) about 90° vertically against the game's 50° at 16:9, so parts of the world the game never shows (above Link's house) appeared unbuilt. The loader now holds an upright picture to the vertical angle of a square (79°), the width narrowing instead (`loader.c` `screen_upright_cap`; `DM_SCREEN_UPRIGHT_FOV`: `0` off, `1.777` the game's own angle). Portrait layout Full screen (0.46:1 on an iPhone) and a tall Mac window are capped; the picture above an iPhone's controls (1.07:1) is landscape and is not. The HUD's multipliers do not change with it. +- **The HUD upright** (current, nothing changed). The 16:9 HUD space fits the picture's width and sits at mid-height: full screen on an iPhone a 402x226-point band at mid-height, about where the controls' top edge is; above the controls one in the 402x375 picture. The `hud upload` stub can only scale that space as a whole, and larger would cut off its sides; moving the hearts and buttons to the picture's edges is the open item above. +- **Upright on the iPhone 17** (current, 2026-11-10; 3-minute runs to Kokiri Forest, `$W/ipad/device/pD_portrait_full`, `pE_portrait_split`, `pF_landscape`, and `pA`..`pC` before Portrait layout existed). Rotation Portrait turned the phone upright at launch (`front end: rotation portrait`). Portrait layout Full screen (`layout portrait full screen, controls over the picture`) rendered the whole screen's 0.46:1 as 1200x2600 (camera x 2.174 y 0.562, `upright cap`): Link in proportion and the trees above him fully built. Picture above controls rendered 1.072:1 (a 1824x1704 crop, camera x 1.000 y 0.603, not capped). Rotation Landscape gave 2352x1080 (2.178:1). Each run was in proportion, with the hearts at the left of the 16:9 band. The frame rate was the same upright and in landscape (13-21 fps at thermal state 2 in all six), so the shape costs nothing measurable. The screenshots are the game's texture: the touch controls over the full-screen picture are seen only on the phone. A first upright shape logs one `[RED] present crop out of bounds` (1824x1704 against 2560x1440): `window crop` grows the textures at setCrop, they are re-created at the next acquire, and the present between them is dropped. A single frame, so left as it is. +- **Open:** the title movie and other videos stay 16:9 with bars. + ## Saves The game autosaves into `slot_00` and `slot_01`, with `option.sav` and `account.sav`. The Load screen lists them and reloading works. A save's thumbnail is a 543x306 JPEG in `caption.sav`, made from a copy of a texture to a buffer. A manual save (Menu, System, Save) on the current build has the picture (slot 02, mean colour 138 / 123 / 86). The autosaves in the work folder's saves, made on older chains, hold a black one. Open: an autosave made on the current build has not been looked at. @@ -112,7 +196,7 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F - The "Navi" name label in the Great Deku Tree scene was missing on an earlier chain and has not been checked since. Not played yet: the Deku Tree dungeon, combat, later areas. Sound opens with no red line; movies and speech were not listened to. Physics issues reported in PR 1299 were not seen on this route (walking, the ladder, the camera). - Resolved: dotted horizontal rows across the picture in play, in fog and light (GitHub issue 1537): the agl_ndsr_vr networks' HMMA calls outside a chain overwrote an accumulator a chain held ([An HMMA outside a chain overwrote the chain's accumulator](../../../docs/reference/shaders.md#an-hmma-outside-a-chain-overwrote-the-chains-accumulator)), since chain 23a1ea1db092; found by bisecting chains on the Kokiri Forest autosave (0f510fd5's chain clean, bd9f422d's not). Under the game's upscaler they had also grown into white blotches: [LDSM reads rows other lanes stored](../../../docs/reference/shaders.md#ldsm-reads-rows-other-lanes-stored). - Open: GPU hangs in play ([#1326](https://github.com/seedds/nxnative/issues/1326), [#1605](https://github.com/seedds/nxnative/issues/1605)), repeatable in a Kokiri Forest conversation and the Impa escort on an M2 Pro and gone with the pipelines of task `a5288d0a6c4971fd` dropped ([#2011](https://github.com/seedds/nxnative/issues/2011)). They are not [threads returning before a barrier](../../../docs/reference/shaders.md#compute-threads-that-return-before-a-barrier): that task, the culling tasks `47f9b38490dcf9a2` and `99280b7b8aae78df` and mesh `3439aaa071d868ae` have no barrier in their bodies (none of the game's 520 task and mesh shaders has one). The lead in #2011 is pixel shader `bd09ab5fc4fd7680`'s light loop, which runs `min(count, 1000) + 1` times per pixel with per-tile counts the GPU reads. -- No iOS shader build or iPhone run has been done. Its memory use makes an iPhone unlikely as it stands. +- The iPhone 17 and the M1 iPad: [For an iPhone or iPad build](#for-an-iphone-or-ipad-build). ## Unused border corrections @@ -128,6 +212,7 @@ Its 37 kernels that correct samples, NDSR's network among them, gave about 0.25 ## Found on this game +- [A frame's submissions queued behind its first one while the iPhone's GPU clock is low](../../../docs/reference/frame-rate.md#a-frames-submissions-queued-behind-its-first-one-while-the-iphones-gpu-clock-is-low): the stalls resolved by merged submissions; the low clock itself open ([For an iPhone or iPad build](#for-an-iphone-or-ipad-build)). - [A clear pass on a large depth texture fails with `Insufficient Memory`](../../../docs/reference/memory.md#a-clear-pass-on-a-large-depth-texture-fails-with-insufficient-memory): resolved, its save load makes a 12288x12288 Depth16 (296 MB) and a 4096x4096 Depth32F, and on an M3 Pro the clear pass that zeroed them failed with `kIOGPUCommandBufferCallbackErrorOutOfMemory` and took the queue with it: about half the loads ended at the 32-failures stop (PR #2306). Depth textures are now zeroed by copies; the author's 203 runs on its build with copies (and a retry throttle not landed here) had no failure. Not seen on an M4 Pro. - [More finalized textures in use than their table held](../../../docs/reference/nvn-objects.md#more-finalized-textures-in-use-than-their-table-held): resolved; the reporters' long-session retest is open ([GitHub issue #2213](https://github.com/seedds/nxnative/issues/2213), [PR #2389](https://github.com/seedds/nxnative/pull/2389)). Frames of 100 to 490 ms for about ten seconds at a streamed area transition, 50 to 55 fps for five seconds after the pause menu, and in long sessions slow motion for a minute or two (10 to 25 fps, riding into Hyrule Field, Kakariko): the table of finalized textures thrashed at 512 entries on the submit thread, with the GPU at its usual time. - [Regression shader compilations grow the normal build cache](../../../docs/reference/packing.md#regression-shader-compilations-grow-the-normal-build-cache): resolved in cache and harness tests. Its normal build's `cas.db` held 40.8 GB; future regression writes use a separate bounded cache, while the existing mixed cache is preserved. @@ -138,7 +223,21 @@ Its 37 kernels that correct samples, NDSR's network among them, gave about 0.25 - [The blend helper's output reference on iOS](../../../docs/reference/shaders.md#the-blend-helpers-output-reference-on-ios): resolved, 22,296 of 42,848 Mac shaders failed to compile on macOS 26 ([GitHub issue #2272](https://github.com/seedds/nxnative/issues/2272)); the Mac compile now names the host's minimum macOS. - [A NaN colour under a zero blend weight](../../../docs/reference/shaders.md#a-nan-colour-under-a-zero-blend-weight): resolved, white clouds over the ground mist between Kokiri Forest and Hyrule Field and over the ferns at the camera in Kokiri Forest ([issue #1839](https://github.com/seedds/nxnative/issues/1839)). The mist shader `5ad65c0eefd09c7f` writes NaN at alpha 0 where its layer has density 0; NVIDIA's blender, with the option NVN's driver sets, adds nothing there, Apple's stored the NaN. - [A first start builds every base of the prewarm list before the first frame](../../../docs/reference/rendering.md#a-first-start-builds-every-base-of-the-prewarm-list-before-the-first-frame): the 450-475 s first-start prepare on an M5 Max; the Mac app now bundles the list's pipelines (`--prebake`, on by default) and it took 4.3 s. +- [Upload staging kept for reuse on small devices](../../../docs/reference/memory.md#upload-staging-kept-for-reuse-on-small-devices): on the iPhone 17, 125 MB less resident at the same speed. +- [A game's own upscaler drawn by MetalFX](../../../docs/reference/rendering.md#a-games-own-upscaler-drawn-by-metalfx) and [an upscaler's colour read from its code](../../../docs/reference/rendering.md#an-upscalers-colour-read-from-its-code): its `agl_ndsr_vr_light.pck` networks read a square-root-encoded input and place their rectangles in other push constants; with **Game's upscaler** MetalFX, the host squares the input and MetalFX scales it in HDR mode. On the iPhone 17 the 5 networks met were drawn by MetalFX (943x434 up to 1508x695 → 2120x976), and the 30 fps cap held. +- [Large sampled textures leave out their largest level on small devices](../../../docs/reference/memory.md#large-sampled-textures-leave-out-their-largest-level-on-small-devices): on the iPhone 17, 672 textures and 396 MB; page-ins 468,772 → 32,707 and 24.0 → 29.3 fps at the 30 fps cap. +- [A re-uploaded texture's spare stayed resident until its texture object went](../../../docs/reference/memory.md#a-re-uploaded-textures-spare-stayed-resident-until-its-texture-object-went): the iPhone 17's 168 uploaded textures held by nothing (123 MB), about 128 of them spares ([For an iPhone or iPad build](#for-an-iphone-or-ipad-build)). +- [Uploaded textures of areas the game has left stayed in the residency set](../../../docs/reference/memory.md#uploaded-textures-of-areas-the-game-has-left-stayed-in-the-residency-set): freed at memory pressure, 334 MB in two trims on the Mac's field. +- [The system ran out of memory while the app's headroom still read 2.7 GB](../../../docs/reference/memory.md#the-system-ran-out-of-memory-while-the-apps-headroom-still-read-27-gb): the iPhone 17 ended entering Hyrule Field; with the trim it went through the field to the castle town, then thrashed back on the field and was ended for proc-thrashing at 6,046 MB wired: not fixed. +- [The residency set's breakdowns counted each texture over a buffer at the buffer's size](../../../docs/reference/memory.md#the-residency-sets-breakdowns-counted-each-texture-over-a-buffer-at-the-buffers-size): resolved, the iPhone 17's 512 MB of linear targets over one 8 MB pool. +- [An upload batch's reads over guest memory had no budget](../../../docs/reference/memory.md#an-upload-batchs-reads-over-guest-memory-had-no-budget): 732 MB of them in the field's load on the iPhone 17. +- [The census counted a resolution family's textures each at its own size](../../../docs/reference/memory.md#the-census-counted-a-resolution-familys-textures-each-at-its-own-size): resolved, 1,131 MB of duplicates that were 78-122 MB. +- [The GPU idles before each submission while the replay waits for the encode thread](../../../docs/reference/rendering.md#the-gpu-idles-before-each-submission-while-the-replay-waits-for-the-encode-thread): resolved on the iPhone 17, about 30 submissions a frame, 13.6-17.9 ms of GPU gaps before submissions in a 35-38 ms span ([For an iPhone or iPad build](#for-an-iphone-or-ipad-build)). - [The 60 Hz link at 40 fps in fullscreen on a ProMotion screen](../../../docs/reference/frame-rate.md#the-60-hz-link-at-40-fps-in-fullscreen-on-a-promotion-screen): 40 fps in fullscreen on an M5 Pro MacBook Pro with the GPU at 10 ms of the 16.7, every present one 120 Hz refresh late and every other display-link tick skipped; the screen's fixed 60 Hz mode held 60.0 fps there and fullscreen now switches to it, with the 120 Hz link (59 fps) for screens with no such mode. +- [A screen-shape stub on the projection setter changes nothing: the camera caches its matrix](../../../docs/reference/rendering.md#a-screen-shape-stub-on-the-projection-setter-changes-nothing-the-camera-caches-its-matrix): the camera copy and the HUD's uniform block copy ([Screen shape](#screen-shape)). +- [Textures in GPU-only memory took an allocation per description](../../../docs/reference/memory.md#textures-in-gpu-only-memory-took-an-allocation-per-description): the M1 iPad's GPU out-of-memory failure at the outdoor save load. +- [The residency commit froze over the guest's files](../../../docs/reference/memory.md#the-residency-commit-froze-over-the-guests-files): resolved, the M1 iPad's freeze with sound and no picture. +- [A read through a pointer to a buffer outside the residency set returns zeros](../../../docs/reference/memory.md#a-read-through-a-pointer-to-a-buffer-outside-the-residency-set-returns-zeros): measured for its 3,344-3,563 pools that only the raw pool table keeps resident (892-1,210 MB on the iPhone 17); the same on the iPhone 17 and an M4 Mac, so they stay resident. - [The shader package and the shader map come from different splits](../../../docs/reference/packing.md#the-shader-package-and-the-shader-map-come-from-different-splits): resolved, a black screen with sound in a build through NX2Apple ([issue #1841](https://github.com/seedds/nxnative/issues/1841)); the present pass was translated from a terrain shader's record. Records now carry their keys, and the shader build finds them by key. - [Native mesh pipelines compiled at their first draw](../../../docs/reference/shaders.md#native-mesh-pipelines-compiled-at-their-first-draw): resolved. The foliage, shadows and enemies drawn with task and mesh shaders stalled at their first draw on a cold Metal cache (59.5 s of builds at the Kokiri Forest entry on an M5 Max, one frame of 42.9 s), as nothing recorded or kept their pipelines; `pso_manifest.tsv` now carries 164 `M` rows (Kokiri Forest, Hyrule Field, Castle Town, Hyrule Castle, and 41 from later play, Death Mountain Trail among it), and with the prepare step they are built before the first frame. Pipelines outside the list still stall once, then go into `pso_user.tsv`. With the first 123 alone, a cold first start (empty Metal cache and pipeline archive, M4 Pro) on a Death Mountain Trail save built 9 and 10 at their first draw in two runs, 2.7 and 4.2 s, frames of 1,775 and 1,657 ms; with all 164, none, worst frame 25.6 and 18.5 ms, the prepare step 29.6 and 29.3 s → 32.1 and 31.0 s. - [Early fragment tests from the control section](../../../docs/reference/shaders.md#early-fragment-tests-from-the-control-section): 746 of its 22,352 pixel shaders set the NVN2 flag (control +0x5b), none of them writes depth; before, no NVN2 shader got the attribute. @@ -159,6 +258,7 @@ Its 37 kernels that correct samples, NDSR's network among them, gave about 0.25 - [A streamed texture's first read drew its surface dark for one frame](../../../docs/reference/rendering.md#a-streamed-textures-first-read-drew-its-surface-dark-for-one-frame): resolved, the cliff beside the castle town wall in Hyrule Field darker for one frame as the game streamed it a sharper texture set ([issue #1969](https://github.com/seedds/nxnative/issues/1969), PR #2075); the first read now samples the texture's own colours, coarse, for that frame. Seen also in Kakariko Village and its graveyard on a MacBook Air M5 (three flashes in 8 minutes before, none in 4 after, by eye). - [Vertex shaders with layer entry points left out of the prebuild](../../../docs/reference/shaders.md#vertex-shaders-with-layer-entry-points-left-out-of-the-prebuild): resolved, a 230 ms frame at a camera turn in Hyrule Field. The effect vertex shaders (no stage inputs, layer entry points of their own) had no base in the bundled archive and were compiled at their first draw; with the fix (measured with PR #2065's form of it, the same bases as the reflection's `layer_out` gives) the archive holds 33,365 bases instead of 30,690, and the worst frame on the `field-run` route is 39 ms (M6). - [Unused border corrections retain sample registers](../../../docs/reference/rendering.md#unused-border-corrections-retain-sample-registers): about 1.5 ms of GPU a frame at 1080p ([measurements](#unused-border-corrections)). +- [A hold the GPU does not explain after a warm start's progress screen](../../../docs/reference/frame-rate.md#a-hold-the-gpu-does-not-explain-after-a-warm-starts-progress-screen): hold 1 → 3 on a progress screen's idle-GPU late frames after a warm start, then about 1,470 presents at 18 fps. - [Position invariance across shaders](../../../docs/reference/shaders.md#position-invariance-across-shaders): white shapes on plants and bushes for single frames in Kokiri Forest, from the foliage's mesh pre-pass and mesh colour pass rounding the position apart. - [gl_FragCoord.z against the depth stored for its own surface](../../../docs/reference/shaders.md#gl_fragcoordz-against-the-depth-stored-for-its-own-surface): the dark specks flickering in the ground mist (long-standing). The mist's own depth test (`5ad65c0eefd09c7f`, against its depth-only pass `4757b5b373a5406e`) rejected its own surface where Apple's GPU stored the depth one ulp under the fragment's z. Bisected by dropping fragment shaders: after mesh draws took the drop too (`skip_fs_draw`), the specks went with the mist or its depth-only pass, and when that pass wrote `[[position]].z` as depth. Resolved by the rewrite: no specks in play with its 39 rewritten shaders as an overlay (the player's check, 2026-11-09); a full library build on the new chain has not been run. @@ -184,6 +284,7 @@ Its 37 kernels that correct samples, NDSR's network among them, gave about 0.25 - [The GPU idles with the next command buffer already committed](../../../docs/reference/frame-rate.md#the-gpu-idles-with-the-next-command-buffer-already-committed): the 25-40 ms frames. - [The uniform copy thread's hand-off convoys on its mutex](../../../docs/reference/frame-rate.md#the-uniform-copy-threads-hand-off-convoys-on-its-mutex): resolved. On one host build (M4 Pro) the replay thread spent half its busy samples in `ubc_wait`, 221-333k instructions a draw and 23-57 ms of submit CPU a frame against 38.9k and 7.1 ms with `DM_NVN_UB_COPY_THREAD=0`; about 35 shadows a frame that `um_overlay` writes into are now copied on the submit thread (PR #2078). - [The 30 Hz display link in fullscreen on a fixed-rate screen](../../../docs/reference/frame-rate.md#the-30-hz-display-link-in-fullscreen-on-a-fixed-rate-screen): 66.7 ms frames at a 30 fps cap in fullscreen on a MacBook Air M4, with the frame-delta change that applies the cap. +- [Late frames at a 30 fps cap on the 30 Hz display link](../../../docs/reference/frame-rate.md#late-frames-at-a-30-fps-cap-on-the-30-hz-display-link): one 66.7 ms gap about every 11 frames at the launcher's 30 fps cap on an iPhone and an M1 iPad, and on ProMotion the frame latency the 60 Hz link needs. - [Pool tables and readback buffers made anew each frame](../../../docs/reference/memory.md#pool-tables-and-readback-buffers-made-anew-each-frame): about 1,500 residency changes per 300 frames. - [Pool tables patched instead of built whole](../../../docs/reference/nvn-objects.md#pool-tables-patched-instead-of-built-whole): the game registers something between most of its draws, its streamed textures map and unmap virtual pool runs dozens of times a second, finalized descriptors stay registered and textures take over each other's storage; each of these walked the 33,025-entry texture table again, about 53 s of a seven-minute walk. - [Pool shaders taken as depth readers](../../../docs/reference/rendering.md#pool-shaders-taken-as-depth-readers): about 80 extra passes a frame, and half the frames over budget. @@ -208,6 +309,7 @@ Its 37 kernels that correct samples, NDSR's network among them, gave about 0.25 - [Shaders report which textures they read through a pool](../../../docs/reference/memory.md#shaders-report-which-textures-they-read-through-a-pool) - [Repeated GPU out-of-memory failures end the game](../../../docs/reference/memory.md#repeated-gpu-out-of-memory-failures-end-the-game) - [Pools that hold shader code made resident to key the shaders](../../../docs/reference/memory.md#pools-that-hold-shader-code-made-resident-to-key-the-shaders): first reported here (222 pools, 334 MB on a build with other changes); on main the raw pool table makes those pools resident anyway (4,276 resident pools before the fix, 4,277 after, on the village walk). +- [Shader-code pools wired by the raw pool table](../../../docs/reference/memory.md#shader-code-pools-wired-by-the-raw-pool-table): the iPhone 17 read its guest file back all the time in Kokiri Forest (14-17 fps); with the 223 shader-code pools (317 MB) out of the table, 27-30 fps. - [Guest files keep the blocks of memory the game gave back](../../../docs/reference/memory.md#guest-files-keep-the-blocks-of-memory-the-game-gave-back): the iPad stopped at 5.0 GB free with 6.6 GB of guest files. - [A GPU whose access macOS revoked stops the game](../../../docs/reference/rendering.md#a-gpu-whose-access-macos-revoked-stops-the-game): after a GPU hang or page faults (issue #1326), nothing was drawn for about 70 s before the game aborted, and in full screen WindowServer's watchdog killed it. - [A texture ID with no texture kept its cached view](../../../docs/reference/rendering.md#a-texture-id-with-no-texture-kept-its-cached-view): the page faults at f3,677 and f4,851 with the render-target reclaim on. diff --git a/dm/games/0400486024DEC000/game.tsv b/dm/games/0400486024DEC000/game.tsv index 45ccc5ed9e..fa78ddb6b8 100644 --- a/dm/games/0400486024DEC000/game.tsv +++ b/dm/games/0400486024DEC000/game.tsv @@ -42,7 +42,13 @@ shader_note Ocarina of Time shaders fps_target 60 # ---- Graphics ---- +# Screen shape (patches.py, README "Screen shape"): the picture takes the window's or the screen's shape, any from 0.25 to 6, portrait included, and follows it while +# the game runs (DM_SCREEN_ASPECT, auto by default): wider shows more at the sides, taller more above and below; the HUD keeps its size +screen_aspect any draw_barriers game # As Tears of the Kingdom: the terrain's height, blend and hole maps are written by the CPU into textures after they are created. Without these keys they stay zero: holes in the ground and the wrong materials tex_flush_upload on tex_dirty_upload on +# The Metal 4 pipeline path on iOS, with the pipeline archive made offline (applegpu_g18p, the iPhone 17 family) and the hybrid pipelines: through the MTLDevice, a render pipeline +# first drawn in a scene state the phone had never drawn compiled on the submit thread, about 400 ms each on an iPhone 17 (Kokiri Forest after the first boss: frames of 0.25-1.26 s) +pso_mtl4 on diff --git a/dm/games/0400486024DEC000/patches.py b/dm/games/0400486024DEC000/patches.py index cade577a2e..64ca35e8d8 100644 --- a/dm/games/0400486024DEC000/patches.py +++ b/dm/games/0400486024DEC000/patches.py @@ -1,6 +1,6 @@ # The Legend of Zelda: Ocarina of Time (0400486024DEC000): the rewriter's patches of this game's own code. dm/tools/patch_nso.py loads every profile's patches.py; # MATCH_FRAME_STEP as described there ("Registered patches"). Patches of Nintendo SDK module builds are in dm/tools/sdk_patches.py -from nso_asm import ADRP, B +from nso_asm import ADDI, ADRP, B # The game's frame ratio. Once a frame the function at main+0x6e6be0 (v131072) divides its base rate (60.0, or 30.0 while bit 0 of [x21+0x24f] is set) by the int frame rate at # [x21+0x2c8] (fdiv s8,s1,s0 at +0xe4) and hands the result to the time object (main+0x3b4e300: ratio at +0x10, 1 / ratio at +0x14, round(60 / ratio) at +0x1c), which the game @@ -32,6 +32,7 @@ def frame_step(ctx): emit(0x1e201828); emit(B(here(), site + 4)) # orig: fdiv s8,s1,s0; back fs_put(site, [B(site, start)], 'frame ratio: the host\'s step × base rate / 60 instead of base rate / the game\'s frame rate (state page target fps; 0 = the game\'s ratio)') dynamic_resolution(ctx) + screen_shape(ctx) # The game's dynamic resolution (game__gfx__DynamicResolutionParam: LoadThreshold, ReduceCounterMax, IncreaseCounterMax and a list of levels, each a ResolutionReduceScale and a # Priority; on v131072 levels 0..9 at 0.75..0.333 of 2048x1152, 1536x864 to 683x384). Its update (main+0x805aa0) reads the frame's GPU load (about 0.2 ms a unit) into +0x8, subtracts @@ -71,10 +72,157 @@ def dynamic_resolution(ctx): fs_put(site, [B(site, start)], 'dynamic resolution level: 0 (full resolution), or with state +0x40 (DM_DYNAMIC_RESOLUTION) a climb on the load measured at each level') ctx.capabilities.add('DYNAMIC_RESOLUTION') +# Screen shape (game.tsv screen_aspect any; the loader writes state +0xa0 the ratio, 0 = 16:9, +0xa4 the width factor, +0xa8 the height factor: loader.c screen_any_write). +# The game's output size, the picture its upscaler writes and the window's crop (2048x1152 docked, 1536x864 or 1920x1080 handheld on v131072), is set in one place: the setter +# main+0x1087f40 (display settings x0, x1 -> {w, h}) stores it at +0x10, raises bit 21 of +0x8 when it changed (main+0x6502e0 then hands it to the window's setCrop, main+0xe9a860, +# which nvnWindowSetCrop takes at each present) and classifies it (+0x18: 640x480 .. 3840x2160, 7 for any other size, as 2048x1152 already is). Its two callers are the settings' +# init (main+0x1087b70, the size from its config struct) and the mode change (main+0x6502e0: a level's size × its scale, capped by a table). The dynamic resolution scales from the +# output height by one factor for both axes (main+0x31d3f64..), so its sizes follow the output's shape. The stub scales the requested size by the factors (the width for a wider +# screen, the height for a taller one); when that is more than 1.5 times the requested size's pixels (beyond 2.67:1 or 1.19:1, a portrait window) it scales both sides down to +# 1.5 times, so the pixel count stays in bounds whatever the shape. Each side is rounded to a multiple of 8, into state +0xe0 (scratch, never the caller's struct: the init passes +# its config), and the setter runs on it. It also copies the camera's multipliers for that shape (state +0xc4 / +0xc8, from the loader) to +0xb8 / +0xbc (0 at 16:9): the camera +# (camera_projection) follows the size the game renders at, not the shape the host asks for, as the game sets its size only at its init, at a mode change and when shape_change +# asks it to. A leaf: x9 / x10 / x16 / s16..s19 are free (the setter loads w8..w11 before it reads them; s16..s19 are caller-saved), x1 an argument it only reads +size_stub = ( # size_stub.s, assembled with clang; x16 the state page (the ADRP before it) + 0xbd40a210, 0x1e202208, 0x54000061, 0xf9005e1f, 0x1400001b, # ratio (+0xa0); 0 (16:9): no camera multipliers (+0xb8 = 0), the setter as it is + 0x29402829, 0x1e230132, 0x1e230153, 0x2d58c610, 0x2d174610, 0x2d54c610, # w, h; the camera's multipliers to +0xb8 / +0xbc; the size factors + 0x1e300a50, 0x1e310a71, # w × width factor, h × height factor + 0x1e330a52, 0x1e2f1013, 0x1e330a52, 0x1e310a13, 0x1e322260, 0x540000ad, # more than 1.5 × the requested pixels? + 0x1e331a52, 0x1e21c252, 0x1e320a10, 0x1e320a31, # both sides × sqrt(limit / pixels) + 0x1e390209, 0x11001129, 0x121d7129, 0x1e39022a, 0x1100114a, 0x121d714a, # each to a multiple of 8 + 0x291c2a09, 0x91038201) # into state +0xe0; x1 -> it +def screen_shape(ctx): + here, emit, fs_site, fs_put, FS_STATE_OFF = ctx.here, ctx.emit, ctx.site, ctx.put, ctx.state + site = ctx.others.get('output size') + if site is None: return # not found in this build (a red line from the locator): 16:9 + fs_site(site, '08244229') # ldp w8,w9,[x0,#0x10] + start = here(); emit(ADRP(16, here(), FS_STATE_OFF)) + for w in size_stub: emit(w) + emit(0x29422408); emit(B(here(), site + 4)) # ldp w8,w9,[x0,#0x10]; back + fs_put(site, [B(site, start)], 'output size: the requested size times the screen shape\'s width and height factors (state +0xa4 / +0xa8; +0xa0 0 = 16:9, as it is)') + window_size(ctx) + camera_projection(ctx) + hud(ctx) + +# The window textures. The game creates its three window textures at 2560x1440 (the window object's +0x8 / +0xc floats; defaults main+0xecbc80), and a crop larger than them +# (2048x1576 at 1.3:1, 2688x1152 at 21:9) cannot be presented. The game re-creates its window and textures from +0x8 / +0xc when +0xc8 is 1: main+0x527fc0, which the +# per-frame texture acquire (main+0x527f20, main+0x346c9b0) tail-calls and which returns at once while +0xc8 is 0. The stub at the entry of setCrop (main+0xe9a860, a leaf: +# win x0, x w1, y w2, w w3, h w4) raises +0x8 / +0xc to hold the crop when it does not fit and sets +0xc8, so the next frame's acquire re-creates the textures at that size. It +# only grows them: a later, smaller crop is presented from the larger textures without another re-creation +crop_stub = ( # crop.s, assembled with clang + 0x2d414410, 0x0b030029, 0x0b04004a, 0x1e230132, 0x1e230153, # the window's size; the crop's right and bottom edges + 0x1e306a52, 0x1e316a73, 0x1e302240, 0x54000061, 0x1e312260, 0x54000080, # the larger of each; both the same: as it is + 0x2d014c12, 0x52800029, 0x39032009) # the window's new size; +0xc8 = 1: re-create at the next acquire +def window_size(ctx): + here, emit, fs_site, fs_put = ctx.here, ctx.emit, ctx.site, ctx.put + site = ctx.others.get('window crop') + if site is None: return # not found in this build: crops beyond 2560x1440 are not presented + fs_site(site, '28008052') # mov w8,#1 + start = here() + for w in crop_stub: emit(w) + emit(0x52800028); emit(B(here(), site + 4)) # mov w8,#1; back + fs_put(site, [B(site, start)], 'window crop: the window textures grow to hold a crop beyond their size (+0x8 / +0xc, re-created at the next acquire through +0xc8)') + +# The camera's projection. Each frame the game finds the camera named "Main" and hands its view and its sead::PerspectiveProjection (x2: near +0x98, far +0x9c, fovy +0xa0, +# aspect +0xb0, the cached matrix at +0xc) to main+0x33a8c0, which copies the projection's matrix into the render camera (x19 +0x148, row major; main+0x33ab7c..0x33abac) and +# stores near / far / fovy / aspect beside it (+0x1c8..+0x1d4), then derives the frustum from the rows it holds in v4..v18. The projection's aspect is 16:9 whatever the output's +# shape (sead::PerspectiveProjection::set, tanf and the 16/9 literals do not run in play: found with DM_PROBE_FINDMAT and a write watch on the render camera's matrix). After +# the last row is stored the stub multiplies row 0 (x) and row 1 (y) by the camera's multipliers, in memory and in v4 / v5, and the aspect at +0x1d4 by y's over x's. The loader +# chooses them (loader.c screen_any_write): landscape wider than 16:9 keeps the vertical angle and shows more at the sides; landscape between 1:1 and 16:9 keeps the horizontal +# angle and shows more above and below; portrait takes the scale of the same screen turned landscape (its width gets what that one's height gets), so turning a phone or a window +# keeps the characters' size and shows another part of the world. They are those the output size was made with (state +0xb8 / +0xbc, copied by size_stub; 0 = 16:9), so the +# projection always matches the picture the game renders. The fcmp at main+0x33ab78 +# is still live (b.eq at +0x33abb0): the stub tests with cbz and keeps the flags. w9 (reloaded at +0x33abbc), v6 and v29 (written before they are read) are free +proj_stub = ( # proj.s, assembled with clang; x16 the state page (the ADRP before it) + 0xb940ba09, 0x340001c9, # the camera's x multiplier (+0xb8); 0 (16:9): as it is + 0xbd40ba06, 0xbd41d67d, 0x1e261bbd, 0xbd40be06, 0x1e260bbd, 0xbd01d67d, # aspect ÷ x multiplier × y multiplier + 0x4e0404c6, 0x6e26dca5, 0x3d800685, # row 1 × y multiplier + 0xbd40ba06, 0x4e0404c6, 0x6e26dc84, 0x3d800284) # row 0 × x multiplier +def camera_projection(ctx): + here, emit, fs_site, fs_put, FS_STATE_OFF = ctx.here, ctx.emit, ctx.site, ctx.put, ctx.state + fn = ctx.others.get('camera copy') + if fn is None: return # not found in this build (a red line from the locator): the projection stays 16:9 + site = fn + 0x2ec + fs_site(site, '920e803d') # str q18,[x20,#0x30]: the matrix's last row + start = here(); emit(0x3d800e92); emit(ADRP(16, here(), FS_STATE_OFF)) + for w in proj_stub: emit(w) + emit(B(here(), site + 4)) + fs_put(site, [B(site, start)], 'camera projection: matrix rows x / y times the camera multipliers the output size was made with, the aspect beside it (state +0xb8 / +0xbc; 0 = 16:9)') + shape_change(ctx) + +# A shape asked for while playing (a window resized): the display settings' update main+0x6502e0 (x0 the settings, the same object as the size setter's) recomputes the output size +# and hands it to the size setter (main+0x650600) when bit 17 (0x20000) of its flags (+0x8) is set, and clears the bit after; the mode change path sets it (main+0x6506a4). The +# stub, after the update loads its flags (ldp w11,w9,[x0,#8] at +0x18), compares the loader's change count (state +0xac) with the count last applied (+0xc0) and, when they +# differ, records it and sets bit 17 in w11, which the update stores back (main+0x650348) and tests (main+0x65036c): the size, and with it the crop, the targets and the camera +# (camera_projection), follow the new shape at the next update. w10 and w12 are written right after (+0x1c, +0x20); the flags are set again by the tst at +0x34 +trig_stub = ( # trig.s, assembled with clang; x16 the state page (the ADRP before it) + 0xb940ae0a, 0xb940c20c, 0x6b0c015f, 0x54000060, # the change count (+0xac) against the one applied (+0xc0); the same: as it is + 0xb900c20a, 0x320f016b) # recorded; flags bit 17: recompute the output size +def shape_change(ctx): + here, emit, fs_site, fs_put, FS_STATE_OFF = ctx.here, ctx.emit, ctx.site, ctx.put, ctx.state + fn = ctx.others.get('display update') + if fn is None: return # not found in this build: the shape follows only at start and at a mode change + site = fn + 0x18 + fs_site(site, '0b244129') # ldp w11,w9,[x0,#8] + start = here(); emit(0x2941240b); emit(ADRP(16, here(), FS_STATE_OFF)) + for w in trig_stub: emit(w) + emit(B(here(), site + 4)) + fs_put(site, [B(site, start)], 'screen shape change: the display update recomputes the output size when the loader\'s change count (state +0xac) moved since the last (+0xc0)') + +# The HUD and menus (eui, Nintendo's newer UI: layouts UI/Layout2Archive/*.blarc.zs). Every layout file holds its screen size, 3840x2160 (LayoutResData +0x200, file offset 0x2f8), and +# the game reads it in place through one getter (main+0x583fd0: [x0] + 0x200). A screen's init (main+0x773b90, a virtual) builds its orthographic projection from it (+-w/2, +# +-h/2, main+0x773f28) and keeps it in the screen's uniform block (+0x1b8: view-projection +8 and its y-flipped copy +0x48, column major, the size twice at +0x88, main+0x7741e0); +# each frame the screen's draw copies the block's 0x90 bytes into the frame's ring (main+0x2d2ba0, its memcpy at +0x48), so the HUD drew in a 16:9 space stretched over any +# output. The stub after that memcpy scales the copy's x / y rows by the HUD's multipliers and divides the size by them: the space takes the output's shape at the HUD's pixel +# size, at the next frame after a shape change and without touching the screen's block. A capture's block (main+0x154b660) holds its texture size beside the screen's and +# is left as it is. The HUD's multipliers are the camera's (state +0xb8 / +0xbc, those the output size was made with) divided by the largest of them and 1: in landscape the +# camera's, so the HUD keeps the size it has at 16:9 of the same height (wider) or width (taller); upright, the 16:9 space still fits the width, so nothing is cut off. The +# layouts place everything about the screen's centre (eui does not anchor panes to the screen's edges: a layout made 4752 wide in a copy of its file drew round hearts at +# their 16:9 place), so the HUD keeps its 16:9 arrangement in the middle; moving the edge groups (60x80 nulls at the space's edges, as PlayerStatus_00's N_ScaleL_00 at +# (-1920, 1078)) and stretching full-screen panes (3840x2160 at the centre: fades, menu backgrounds) is open (game note, Screen shape) +hud_upload = ( # hud.s, assembled with clang; x0 the copy (memcpy's result), x20 the block, x16 the state page (the ADRP before it) + 0xa948aa89, 0xeb0a013f, 0x54000441, 0xb4000429, 0xb940ba09, 0x340003e9, # the size twice (a screen's own projection) and a shape other than 16:9 + 0x2d574610, 0x1e316a12, 0x1e2e1013, 0x1e336a52, 0x1e321a10, 0x1e321a31, # the camera's multipliers / max(mx, my, 1) + 0x4f03f614, 0x6e040614, 0x6e0c0634, # (mx', my', 1, 1) + 0xad405815, 0x6e34deb5, 0x6e34ded6, 0xad005815, 0xad415815, 0x6e34deb5, 0x6e34ded6, 0xad015815, # both matrices' columns: rows x / y scaled + 0xad425815, 0x6e34deb5, 0x6e34ded6, 0xad025815, 0xad435815, 0x6e34deb5, 0x6e34ded6, 0xad035815, + 0x2d504c12, 0x1e301a52, 0x1e311a73, 0x2d104c12, 0x2d114c12) # the size / the multipliers, both copies +# The game's other conversions between the layout space and the screen (a pane's rect in screen coordinates, a 3D position's place on the HUD) read the same getter: the +# stub at its entry returns the size the HUD draws with (state +0xd0, scratch), except to the screen's init (its two calls, main+0x773ee0 / +0x773f24), whose projection the +# upload stub widens each frame. A leaf: x8..x10, x16 and s16..s21 are free +layout_size = ( # lsize.s, assembled with clang; x16 the state page, x10 the init's first return address (the ADRP / ADD before it) + 0xf9400008, 0x91080100, 0xb940ba09, 0x34000229, # the layout's size; 16:9: as it is + 0xeb0a03df, 0x540001e0, 0x9101114a, 0xeb0a03df, 0x54000180, # the screen's init: as it is + 0x2d404410, 0x2d574e12, 0x1e336a54, 0x1e2e1015, 0x1e356a94, 0x1e341a52, 0x1e341a73, # the HUD's multipliers + 0x1e321a10, 0x1e331a31, 0x91034200, 0x2d004410, 0xd65f03c0) # the size / them, into state +0xd0; x0 -> it +def hud(ctx): + here, emit, fs_site, fs_put, FS_STATE_OFF = ctx.here, ctx.emit, ctx.site, ctx.put, ctx.state + fn = ctx.others.get('hud upload') + if fn is not None: # not found in this build (a red line from the locator): the HUD stays 16:9, stretched over the output + site = fn + 0x4c + fs_site(site, 'e00315aa') # mov x0,x21 (after the memcpy) + start = here(); emit(ADRP(16, here(), FS_STATE_OFF)) + for w in hud_upload: emit(w) + emit(0xaa1503e0); emit(B(here(), site + 4)) # mov x0,x21; back + fs_put(site, [B(site, start)], 'HUD projection: the screen\'s uniform block copy takes the output\'s shape at the HUD\'s pixel size (state +0xb8 / +0xbc; 0 = 16:9)') + fn, init = ctx.others.get('layout size'), ctx.others.get('screen init') + if fn is None or init is None: return # the game's own layout size for its conversions + fs_site(fn, '080040f9') # ldr x8,[x0] + start = here(); emit(ADRP(16, here(), FS_STATE_OFF)); emit(ADRP(10, here(), init + 0x354)); emit(ADDI(10, 10, (init + 0x354) & 0xfff)) + for w in layout_size: emit(w) + fs_put(fn, [B(fn, start)], 'layout size: the size the HUD draws with for the game\'s conversions to and from the screen (state +0xd0), the screen\'s init as it is') + MATCH_FRAME_STEP = {'main': [ {'name': 'frame ratio from the host\'s step', 'size': 0x9b4, 'fingerprints': ['6ae2aff5344d14568e4dbaf93455e2d8278384bf892ed6c6eca87fef98fbcd1d'], 'stub': frame_step, # v131072 main+0x6e6be0 'others': {'dynamic resolution': {'size': 0x294, 'fingerprints': ['7af6ceb0aedf8e0c17dc08ce17fcd6a7cba6d394a0d09e3b504c6d668dc418e7']}, # v131072 main+0x8065e0 - 'dynamic resolution update': {'size': 0xb24, 'fingerprints': ['5a423697838976baf286cffa5e2ceef0d4e037abbcd9d371e90e9e702d61b3d4']}}}, # main+0x805aa0 + 'dynamic resolution update': {'size': 0xb24, 'fingerprints': ['5a423697838976baf286cffa5e2ceef0d4e037abbcd9d371e90e9e702d61b3d4']}, # main+0x805aa0 + 'output size': {'size': 0xd8, 'fingerprints': ['9e24f74affcfca6fb386818db0e5a9d4c9e3c57aee7b35c5afff3abed93a58a4']}, # main+0x1087f40 + 'camera copy': {'size': 0x1648, 'fingerprints': ['66a50abf2237dee694c40d6a2371071d62e91379d40b643869d680f597bfab02']}, # main+0x33a8c0 + 'display update': {'size': 0x554, 'fingerprints': ['c0cab0dbf6f0644635315a356f8fd23a4701515c4ab4775d52191835b1a12e3c']}, # main+0x6502e0 + 'window crop': {'size': 0x14, 'fingerprints': ['a6116ba396321af2dacdfc1b236bbf1103285a96b92db1c2c6cc3f1aed190f6d']}, # main+0xe9a860 + 'hud upload': {'size': 0x70, 'fingerprints': ['7cf489e6e9cc18b56c67f82ba4ca22e55abbd592d21309873d6803d19e0e7872']}, # main+0x2d2ba0 + 'screen init': {'size': 0x62c, 'fingerprints': ['103de33fb929cda858c2fbd57b726e6e1bca705bad66de872701819fbf5c6089']}, # main+0x773b90 + 'layout size': {'size': 0xc, 'fingerprints': ['d451096b59a2483a7e026bd2764333eecd505ea3aad2b3f8d902aa20ba5b02f7']}}}, # main+0x583fd0 ]} BINDING = [ @@ -84,4 +232,10 @@ def dynamic_resolution(ctx): {'what': 'dynamic resolution: full size, or a climb on the load measured at each level', 'now': 'game', 'goal': 'game', 'purpose': 'rendering', 'why': "the game's own dynamic-resolution level function and update, found by their functions' fingerprints on any build that keeps both; switchable (DM_DYNAMIC_RESOLUTION)", 'checked': 'v131072 main: one function with each fingerprint (the level function a leaf, x2..x11 / x16 / x17 / s0..s2 free), its callers, the update and the controller fields read by disassembly, the fields read in play (2026-11-08); the climb run natively against a model of the update and in play to full size (2026-11-09)'}, + {'what': 'screen shape: the output size, the window textures, the camera projection and a live shape change (screen_aspect any)', 'now': 'game', 'goal': 'game', 'purpose': 'rendering', + 'why': "the game's own size setter, setCrop, camera copy and display update, found by their functions' fingerprints on any build that keeps them; switchable (DM_SCREEN_ASPECT)", + 'checked': 'v131072 main: one function with each fingerprint, the sites and their free registers read by disassembly, the camera matrix and its writer found in play with DM_PROBE_FINDMAT and the write watch, the stubs run natively (test_oot_aspect.py) and on the Mac at six window shapes resized live (2026-11-09)'}, + {'what': "HUD: the screens' orthographic projection and the layout size take the output's shape", 'now': 'game', 'goal': 'game', 'purpose': 'rendering', + 'why': "the screen draw's uniform block copy and the layout-size getter, found by their functions' fingerprints with the screen init beside them", + 'checked': 'v131072 main: one function with each fingerprint, the block layout and its per-frame copy read by disassembly, the 3840x2160 size read in play with probes and changed in a copy of a layout file, the stubs run natively (test_oot_aspect.py) and on the Mac at six shapes, the pause menu and a cutscene (2026-11-09)'}, ] diff --git a/dm/games/0400486024DEC000/smoke.tsv b/dm/games/0400486024DEC000/smoke.tsv new file mode 100644 index 0000000000..9126c5d336 --- /dev/null +++ b/dm/games/0400486024DEC000/smoke.tsv @@ -0,0 +1,10 @@ +# Empty save to the title: the pipeline prepare of a cold start (265 s for 14,748 pipelines on an M4 in quick mode, no game frame meanwhile), the logos, then the title +# with its movie (compute-heavy: the frame step and the movie clock at work). No input. quick has no prebuild, so it pays the prepare too; the full mode prebuilds first. +save new +keys +secs 400 +quick 400 +reach 900@360 +window 340 50 +shots 350,385 +hang 30 diff --git a/dm/games/README.md b/dm/games/README.md index 4888adcaef..e8b91cd99b 100644 --- a/dm/games/README.md +++ b/dm/games/README.md @@ -233,7 +233,7 @@ One row per profile; the notes are each profile's `README.md`. | `stdalloc_cap` | With virtual address memory, the address space `StandardAllocator::Initialize(nullptr, size)` gets when `size` is more than the alias region has room for (`hle_svc.c` "StandardAllocator's address space", a gate the rewriter places by symbol in every `sdk`). Default `0`: the room, the alias region less the regions already made (at least the 62 MB node area) and 256 MB for the regions made after it. Needed when those need more (Absolum's .NET garbage collector takes 1.5 GB after its `malloc`): the NSP script's address region check sets it in a provisional or derived profile from what it measured, and checks a value set by hand. A request that fits is never changed | | `present_interval` | `game` (the default): frames are paced by the present interval the game sets, as on the Switch (a frame presented with interval 2 stays on screen for two display ticks; a game that keeps asking for 2 for a second gets the 30 fps target, and on iOS the display link then runs at 30 Hz; Mario 1.2.1 switches to 2 for single frames after a slow one; Engage asks for 2 on the Switch, and a rewriter cut on its 2.0.0 `main` makes it ask for 1, see `0100A6301214E000/game.tsv`). `display`: one frame per display tick whatever the game asks, which is only right for games whose logic does not count frames (D2R's runs on its own 25 Hz clock; Monster Train 2 asks for 2 and steps by Unity's frame time, so it runs at 60 fps: screenshots at the same moments match at 30 and 60 fps). `DM_PRESENT_INTERVAL=game` / `display` overrides it, also from `Documents/env.txt` | | `present_snap` | `on` / `off` (the default): present snapshots by default (`nvn_mtl.m` `mtl_snap_on`, a ring of 2 host textures): each present is copied and the game's swapchain texture is free at once, so the GPU does not idle between frames ([Present snapshots](../../docs/reference/frame-rate.md#present-snapshots-the-games-swapchain-texture-free-at-once)). A setting the game was tested with: the iOS launcher's **Frame buffering** defaults to it, and `DM_PRESENT_SNAP` / `Documents/env.txt` override it. Breath of the Wild sets it on | -| `pso_mtl4` | `on` / `off` (the default): on iOS, render pipelines through MTL4Compiler by default, with the pipeline archive, the prepare step, the hybrid pipelines and the prebuild (on by default on the Mac; `DM_PSO_MTL4=1` / `0` overrides). A setting the game was tested with on an iPhone. It also gives the app the [pipeline archive made offline](../../docs/development.md#the-pipeline-archive-made-offline) (`build_ipa.sh` builds it for the `pso_gpu` key's list when present, else for `g18p`, unless `DM_PSO_GPUS` says otherwise). An iOS build carries the pulling libraries (`_bp`) whatever this key says, since the launcher's Metal 4 pipelines toggle can turn the path on. Profiles with `pso_mtl4 off` get no archive unless a build override selects one. Breath of the Wild sets it on | +| `pso_mtl4` | `on` / `off` (the default): on iOS, render pipelines through MTL4Compiler by default, with the pipeline archive, the prepare step, the hybrid pipelines and the prebuild (on by default on the Mac; `DM_PSO_MTL4=1` / `0` overrides). A setting the game was tested with on an iPhone. It also gives the app the [pipeline archive made offline](../../docs/development.md#the-pipeline-archive-made-offline) (`build_ipa.sh` builds it for the `pso_gpu` key's list when present, else for `g18p`, unless `DM_PSO_GPUS` says otherwise). An iOS build carries the pulling libraries (`_bp`) whatever this key says, since the launcher's Metal 4 pipelines toggle can turn the path on. Profiles with `pso_mtl4 off` get no archive unless a build override selects one. Breath of the Wild and Ocarina of Time set it on | | `pso_gpu` | Optional, whitespace-separated GPU architectures: the ones the [pipeline archive made offline](../../docs/development.md#the-pipeline-archive-made-offline) is made for when the profile also sets `pso_mtl4 on`. The bases are made per GPU family and each family's archive costs its own `metal-tt` run, so a profile names exactly the devices it serves. 1-4 tokens, each alphanumeric, with or without the `applegpu_` prefix (for example `g18p applegpu_g19p`); `none` is not a value. Without this key, `pso_mtl4 on` keeps the A19 / A19 Pro default `g18p`; `pso_mtl4 off` gets no archive. The `DM_PSO_GPUS` switch / the NSP script's `--gpu` overrides the archive selection; this key does not enable Metal 4 pipelines | | `enc_thread` | `on` / `off` (the default): on the Mac, Metal encoding on its own thread by default, as on iOS for every game (`nvn_rec.h` `rec_on`; `DM_NVN_ENC_THREAD=1` / `0` and the launcher's Encode thread override it). For a game that waits on its fence every frame, whose submit thread would otherwise also encode before the wait: Need for Speed: Hot Pursuit Remastered's 60 fps frame took 18.1 ms with encoding on the submit thread and 16.7 on its own | | `fps_target` | Frame rate cap of the rewriter's frame step, for builds that have one (`FRAME_STEP` in the profile's `patches.py`: Tears of the Kingdom 1.4.3, Breath of the Wild 1.9.0, Hyrule Warriors: Age of Calamity 1.3.0, Paper Mario: The Thousand-Year Door 1.0.1, ASTRAL CHAIN 1.0.1), or the engine's own frame limit the host writes into game memory (`hle_fpslock.c`: Monster Hunter Rise 16.0.2, which also needs `present_interval display`; any Unreal Engine 4.2x / 5 build, its `t.MaxFPS` (or `ue_fps_cvar`) and `rhi.SyncInterval` or `nvn.SyncInterval`, found by name by the rewriter, so the game asks for present interval 1 itself, and its fixed frame rate `GEngine->FixedFrameRate`, found by its reflection entry and written while the engine's `bUseFixedFrameRate` is set (DRAGON BALL: Sparking! ZERO's battles, Pikmin 4); Luigi's Mansion 3 1.4.0, its frame limiter's milliseconds per frame, with `present_interval display`; Pokémon Brilliant Diamond 1.3.0, Unity's integer `Application.targetFrameRate`, also with `present_interval display`; EA SPORTS FC 27, Frostbite's simulation rate, found by name on any build, and on 1.8d.310c its frame regulator, also with `present_interval display`; Fire Emblem Fortune's Weave, a target frame rate the game steps by, found by its readers on any build, so the game asks for present interval 1 itself). `0` (the default): the game's own step. `30` / `60`: the host decides each frame's step in whole vsyncs and keeps the frame on screen that long (`hle_nvn.c` `fstep_tick`, `nvn_fstep.h`): 1 at a 60 cap, 2 when 60 does not hold or at a 30 cap (and while a prerendered movie plays), plus one vsync while the game is behind real time after a late frame. Presents follow that hold instead of the interval the game sets. `DM_FPS_TARGET` overrides it, also from `Documents/env.txt`; the log line `frame step: game time … of real time` checks the game's speed. A derived profile (`derive_profile`) whose `main` has no `FRAME_STEP` stubs, while the profile has them for other builds, gets `fps_target 0`: without the stubs the host would present every vsync and the game would run at double speed. On a main with neither a frame step nor an engine limit the host writes, the host keeps the game's own present interval whatever `fps_target` or `DM_FPS_TARGET` says (`hle_fpslock.c` `dm_fps_lock_engine`), except with `present_interval display`, where the cap is the present interval alone: a game whose only limit is its present interval and that steps by the time that passed (Red Dead Redemption) | @@ -247,6 +247,7 @@ One row per profile; the notes are each profile's `README.md`. | `device_api` | Optional, decided by the SDK version without it: the NVN API version `major.minor` that `nvnDeviceGetInteger` reports, 55.15 for SDK 11 and later (what Mario requires) and 53.313 for SDK 10 and older (`hle_nvn.c` `nvn_api`). Games check it and skip creating their device on a mismatch: Super Mario 3D World + Bowser's Fury (SDK 10) requires major 53 and minor ≥ 313. No profile sets it. `DM_NVN_API` overrides. Not part of the shader chain version (only `shader_*` keys are) | | `depth_mode` | `gl` (the default, NVN's near = −w) or `zero` (near = 0): the depth mode the game sets with `nvnDeviceSetDepthMode`, for the pipeline bases made before the game runs: the [pipeline archive made offline](../../docs/development.md#the-pipeline-archive-made-offline) for the iPhone (`main0` or `main0_z` vertex entries; built for a game with `pso_mtl4 on` or with `DM_PSO_GPUS`) and the NSP script's Mac prebuild (`DM_PSO_PREBUILD_DEPTH`). The host itself follows the mode the game sets; a wrong value only costs the device its own prebuild. The heap and address region checks of a provisional or derived profile set it when their boot reaches the game's call; without that call they leave it, as no call means unknown, not GL. Keep the key when the profile moves into `dm/games`: it is no shader input. Great Ace Attorney Chronicles, 13 Sentinels (both releases), Big Brain Academy, Link's Awakening, Engage, ASTRAL CHAIN, Luigi's Mansion 3 and Octopath Traveler 0 set `zero` | | `render_base` | The 3D views' base size, docked then handheld (`1600x900 1280x720`): what `DM_RENDER_SCALE` scales. `settings.py` writes it into the render scale's row of `launcher.json` as `base`, so a front end can show the setting in pixels. Only for a game with a render scale stub, and only a size its note documents. The slider's top is the stub's largest scale, which the rewriter writes as `RENDER_SCALE` in the fixups table (1.0, or 3.0 for Hades II, whose stub also raises its 1280x720) | +| `screen_aspect` | `off` (the default), `on` or `any`: the profile's stubs render the game in the screen's shape (`DM_SCREEN_ASPECT`, launcher setting *Picture shape*; `game.py` `DM_GAME_SCREEN_ASPECT` 0 / 1 / 2). `on` (Breath of the Wild, Animal Crossing: New Horizons): taller than 16:9 only, 1.3 to 1.77, set at the start; the host gives the game a taller output and layout size (`loader.c`, state +0x48..+0x9c). `any` (Ocarina of Time): any shape from 0.25 to 6, portrait included, followed while the game runs: the loader writes the ratio, size factors, a change count and the camera's multipliers (state +0xa0..+0xc8, `loader.c` `screen_any_write`) and the stubs scale the game's own output size, camera and HUD; the present shows the game's crop in its own shape | | `op_mode` | The operation mode the game sees at start: `console` (the default, docked) or `handheld`. Super Mario Galaxy and Captain Toad: Treasure Tracker use `handheld`: docked, their pointer is the Joy-Con gyro, which the host does not have; handheld, it is the touch screen, which the iPhone front end feeds with the touches no gamepad control takes (in the 3D layout, outside the right third of the screen, which is the right stick; `DmGamepad.m`). Handheld also renders at 720p. `DM_OPMODE=0` / `1` overrides, also from `Documents/env.txt` | | `perf_mode` | `follow` (the default): the performance mode follows the operation mode (Boost docked, Normal handheld); `boost`: Boost whatever the operation mode (`hle_oe.c`), a combination a Switch 1 never reports, so a profile choice. Rhythm Heaven Groove plays handheld with Boost: docked means a TV to the game, which then asks for a latency calibration, and only Boost gives its 1920x1080 draw size (handheld Normal draws 1280x720) | | `pad_layout` | The iPhone virtual gamepad's layout on first launch: `simple` (the default) = 2D (left stick, A/B/X/Y, shoulders, − / +), `full` = 3D (adds a D-pad, a right stick and L3 / R3; the right stick is not drawn: a touch landing in the right third of the screen on no control holds it, centred where it lands), `touch` = Tap (no control but the layout button: every touch goes to the game's touch screen; needs `op_mode handheld`, Balatro). The layout button at the top centre goes to the next layout in game (Tap only in handheld mode) and the app remembers the player's choice (`DmGamepad.m`) | diff --git a/dm/games/game.py b/dm/games/game.py index b7c198fd62..297f1d3468 100644 --- a/dm/games/game.py +++ b/dm/games/game.py @@ -101,8 +101,9 @@ def by_build(main_id): # the profile whose build rows register this main build return next((g for g in all_games() if any(b.get('main') == main_id for b in g.builds().values())), None) -# agl's upscaler network (NDSR), by where the shader map found each key: the compute shaders of agl_ndsr.pck (Donkey Kong Bananza's 24 in its release library, Splatoon Raiders' 20 in its debug one) -UPSCALER_SOURCE = re.compile(r'/agl_ndsr\.pck#') +# agl's upscaler network (NDSR), by where the shader map found each key: the compute shaders of agl_ndsr.pck (Donkey Kong Bananza's 24 in its release library, Splatoon Raiders' 20 in its debug one), +# and of its variable-ratio packs agl_ndsr_vr.pck and agl_ndsr_vr_light.pck (Ocarina of Time: 59 in all three; the host draws only the variants whose colour it reads, nvn_mtl.m up_mfx_color) +UPSCALER_SOURCE = re.compile(r'/agl_ndsr(_vr)?(_light)?\.pck#') def upscaler_keys(g): @@ -236,7 +237,7 @@ def header_one(g): f'#define DM_GAME_LAUNCH_PARAM {q(g.get("launch_param", ""))}', # what oe::TryPopLaunchParameter hands over once (hle_oe.c; a program another program of the application launches: Super Mario 3D All-Stars) f'#define DM_GAME_MEM_MAP_LIMIT {int(mml == "on")}', f'#define DM_GAME_STDALLOC_CAP {int(g.get("stdalloc_cap", "0"), 0):#x}ull', # StandardAllocator's address space with virtual address memory (hle_svc.c); 0 = what the alias region has room for - f'#define DM_GAME_SCREEN_ASPECT {("off", "on").index(g.get("screen_aspect", "off"))}', # stubs that follow a screen taller than 16:9 (DM_SCREEN_ASPECT): off / on + f'#define DM_GAME_SCREEN_ASPECT {("off", "on", "any").index(g.get("screen_aspect", "off"))}', # stubs that follow the screen's shape (DM_SCREEN_ASPECT): off / on (taller than 16:9, set at the start) / any (any shape from 0.25 to 6, followed while the game runs) f'#define DM_GAME_DISPLAY_VERSIONS {vers}', f'#define DM_GAME_PRESENT_DISPLAY {int(pi == "display")}', f'#define DM_GAME_CORE_PREEMPT {int(cp == "on")}', diff --git a/dm/games/settings.py b/dm/games/settings.py index 506134421a..2351629f78 100644 --- a/dm/games/settings.py +++ b/dm/games/settings.py @@ -110,7 +110,7 @@ def offered(v, n): # value=label?cond&cond: an option only some games or platf if need not in table: sys.exit(f'settings.tsv:{n}: needs names a variable no row sets: {m["needs"]}') can = table[need] if can is not None and want not in can: sys.exit(f'settings.tsv:{n}: needs a value {need} never takes: {want} (it takes {", ".join(sorted(can))})') - if not shown(cond, n): continue + if not all(shown(c, n) for c in cond.split('&')): continue # every condition of & s = {'env': var, 'kind': kind, 'section': section, 'label': label, 'note': note, 'default': value(default, n), **m} if var == 'DM_RENDER_SCALE' and base: s['base'] = base # the render scale in pixels, for the console mode chosen if kind == 'choice': diff --git a/dm/games/settings.tsv b/dm/games/settings.tsv index 15f4824107..1e8151fd5b 100644 --- a/dm/games/settings.tsv +++ b/dm/games/settings.tsv @@ -8,7 +8,7 @@ # default a value (a toggle's: 1 on, 0 off); DM_GAME_: the host's own default from the game profile (game_profile.h, game.py); build:: the IPA build's setting (build_ipa.sh) # | selects the platform's default before resolving a profile macro or build variable # shown always; DM_GAME_!= or ==; fixups:: main's rewriter table has that key (a stub in the game's build, patch_nso.py); languages>1 (more than one to pick, so also when the control data lists none); gfxapi:: the packer's GFXAPI; -# platform:: the app's platform (SETTINGS_PLATFORM, ios when unset), for a switch only that platform's front end reads +# platform:: the app's platform (SETTINGS_PLATFORM, ios when unset), for a switch only that platform's front end reads; &: all of them # section Game, Controls or Performance: a heading on the single settings screen. Rows appear in table order within each section # Reset to tested defaults clears all launcher choices; values fixed by an env file stay # label, note the setting's name and the line under it (may be empty; only for a setting with a cost: latency, memory, heat) @@ -23,6 +23,8 @@ DM_UPSCALER choice game=Game's own,metalfx=MetalFX game DM_GAME_UPSCALER_N!=0 Ga DM_LANG choice languages build:DM_LANG languages>1 Game Game language level=basic DM_FULLSCREEN choice 0=Window,1=Fullscreen 0 platform:mac Game Display mode level=basic DM_PICTURE_FIT choice fit=Fit,fill=Fill fit platform:ios Game Picture Fill crops the game's 16:9 picture to cover the screen. Health bars, subtitles or maps near the edges can be cut off. A full-screen picture without cropping needs a patch for each game. +DM_ROTATION choice auto=Automatic,landscape=Landscape,portrait=Portrait auto platform:ios Game Rotation +DM_PORTRAIT_LAYOUT choice full=Full screen,split=Picture above controls full DM_GAME_SCREEN_ASPECT==2&platform:ios Game Portrait layout DM_SHOW_FPS toggle - build:DM_SHOW_FPS platform:ios Game Frame-rate counter DM_TOUCH_HAPTICS toggle - 1 platform:ios Controls Touch feedback DM_RUMBLE toggle - 1 always Controls Game rumble level=basic @@ -30,7 +32,8 @@ DM_RUMBLE_GAIN range 0:3:0.1 1.0 always Controls Rumble strength needs=DM_RUMBL DM_RUMBLE_MIN range 0:0.9:0.05 0 always Controls Rumble cutoff DM_PAD_PRESS_TO_JOIN toggle - 0 always Controls Press a button to join DM_SW2 toggle - 0 platform:mac Controls Switch 2 controllers Plays Joy-Con 2 and Pro Controller 2 over Bluetooth: hold Sync on one during the game to pair it. macOS asks once for Bluetooth access. -DM_SCREEN_ASPECT choice auto=Match screen?platform:ios,1.43=iPhone Duo screen (1.43:1),0=16:9 (Switch) auto|0 DM_GAME_SCREEN_ASPECT!=0 Game Picture shape Renders about a quarter more pixels: a little slower and warmer. +DM_SCREEN_ASPECT choice auto=Match screen?platform:ios,1.43=iPhone Duo screen (1.43:1),0=16:9 (Switch) auto|0 DM_GAME_SCREEN_ASPECT==1 Game Picture shape Renders about a quarter more pixels: a little slower and warmer. +DM_SCREEN_ASPECT choice auto=Match screen?platform:ios,auto=Match window?platform:mac,1.777=16:9 (Switch) auto DM_GAME_SCREEN_ASPECT==2 Game Picture shape Match fills the screen or the window, wider or taller, with no bars: the picture shows more at the sides or above and below. 16:9 shows the Switch picture. DM_PRESENT_SNAP toggle - DM_GAME_PRESENT_SNAP gfxapi:nvn Performance Frame buffering Up to one frame more display latency. DM_PSO_MTL4 toggle - DM_GAME_PSO_MTL4|1 gfxapi:nvn Performance Metal 4 pipelines Keeps a pipeline archive; uses more memory. DM_PSO_PREBUILD toggle - 1 gfxapi:nvn Performance Pipeline prebuild The first start waits a few minutes for it, once. needs=DM_PSO_MTL4=1 diff --git a/dm/gfx/nvn/hle_nvn.c b/dm/gfx/nvn/hle_nvn.c index a4d838a0d1..a12b9277ef 100644 --- a/dm/gfx/nvn/hle_nvn.c +++ b/dm/gfx/nvn/hle_nvn.c @@ -260,7 +260,7 @@ NVN(nvnMemoryPoolInitialize, NVNboolean, NVNmemoryPool *p, const NVNmemoryPoolBu const pool_builder_t *s = (const pool_builder_t *)b; pool_t *o = (pool_t *)p; o->magic = MAGIC('P', 'O', 'O', 'L'); o->flags = s->flags; o->mem = s->mem; o->size = s->size; o->vp = NULL; o->vmode = 0; if (!o->mem && (o->flags & 0x200)) { uint8_t *vr = vpool_reserve(o); if (vr) o->mem = vr; } // a virtual pool's own address range until its first mapping decides (see MapVirtual) - else if (o->mem) { mtl_pool_add(o->mem, o->size); nvn_dirty_add_range(o->mem, o->size); } + else if (o->mem) { mtl_pool_add(o->mem, o->size); mtl_pool_tag(o->mem, (uint32_t)o->flags); nvn_dirty_add_range(o->mem, o->size); } if (o->mem && !(o->flags & 0x200)) dm_device_share(o->mem, o->size, 1); // the GPU maps the storage: the host refuses to unmap it until Finalize, as Horizon does (hle_svc.c) if (!o->mem && !(o->flags & 0x200)) LOG("[RED] MemoryPoolInitialize: non-virtual pool has no storage flags=%#x size=%#llx", o->flags, o->size); if (getenv("DM_NVN_VLOG")) { LOG("[nvn] MemoryPool %p mem=%p size=%#llx flags=%#x", (void *)p, (void *)o->mem, (unsigned long long)o->size, o->flags); void dm_backtrace(uint64_t fp); dm_backtrace((uint64_t)__builtin_frame_address(0)); } @@ -283,8 +283,16 @@ NVN(nvnMemoryPoolFlushMappedRange, void, const NVNmemoryPool *p, ptrdiff_t off, ft_flush(o->mem + off, n); } // A GPU address exists only once the driver has given one: here, by a buffer (nvnBufferInitialize) or by a texture (nvnTextureGetTextureAddress). Raw global memory can reach only what these name (mtl_pool_addressed) -static void pool_mark_addressed(const pool_t *o) { static __thread const uint8_t *last; if (o->mem && o->mem != last) { last = o->mem; mtl_pool_addressed(o->mem, o->size); } } -NVN(nvnMemoryPoolGetBufferAddress, NVNbufferAddress, const NVNmemoryPool *p) { pool_mark_addressed((const pool_t *)p); return (NVNbufferAddress)((const pool_t *)p)->mem; } +static void pool_mark_addressed(const pool_t *o) { static __thread const uint8_t *last; if (o->mem && o->mem != last) { last = o->mem; mtl_pool_addressed_by(o->mem, o->size, 0); } } +// A shader-code pool's own address (NVN_MEMORY_POOL_FLAGS_SHADER_CODE, 0x40; not virtual) is asked for to place programs: nvnProgramSetShaders takes code addresses. The GPU never reads that code, +// as the shaders run translated and their constants are copied into the host's buffers, so it does not put the pool into the raw pool table (kind 4), where it would be resident and its pages wired. +// Ocarina of Time on the iPhone: 223 such pools, 317 MB, wired for nothing on an 8 GB device that pages the guest's files out. A buffer made in the pool still puts it in (nvnBufferInitialize) +static void code_pool_addressed(const pool_t *o) { static __thread const uint8_t *last; if (o->mem && o->mem != last) { last = o->mem; mtl_pool_addressed_by(o->mem, o->size, 4); } } +NVN(nvnMemoryPoolGetBufferAddress, NVNbufferAddress, const NVNmemoryPool *p) { + const pool_t *o = (const pool_t *)p; + if ((o->flags & 0x240) == 0x40) code_pool_addressed(o); else pool_mark_addressed(o); + return (NVNbufferAddress)o->mem; +} // ---------- Descriptor pools ---------- // One ID space per pool. In NVN a texture or sampler ID indexes the pool the command buffer has bound (SetTexturePool / SetSamplerPool), and two pools may use the same IDs. The replay keeps @@ -626,7 +634,7 @@ NVN(nvnTextureGetSamples, int, const NVNtexture *t) { return CTX(t)->d.samples; NVN(nvnTextureGetMemoryPool, NVNmemoryPool *, const NVNtexture *t) { return (NVNmemoryPool *)CTX(t)->pool; } NVN(nvnTextureGetMemoryOffset, ptrdiff_t, const NVNtexture *t) { return (ptrdiff_t)CTX(t)->off; } // The GPU address of the texture's storage (DRAGON QUEST XI S, Unreal Engine 4.18, asks for it at start): pool address + offset, the same address space as nvnMemoryPoolGetBufferAddress -NVN(nvnTextureGetTextureAddress, NVNtextureAddress, const NVNtexture *t) { const tex_t *o = CTX(t); if (o->pool) mtl_pool_addressed(o->pool->mem + o->off, o->L.size ? o->L.size : 1); return o->pool ? (NVNtextureAddress)(o->pool->mem + o->off) : 0; } +NVN(nvnTextureGetTextureAddress, NVNtextureAddress, const NVNtexture *t) { const tex_t *o = CTX(t); if (o->pool) mtl_pool_addressed_by(o->pool->mem + o->off, o->L.size ? o->L.size : 1, 2); return o->pool ? (NVNtextureAddress)(o->pool->mem + o->off) : 0; } // The size of a texture's ZCull save area (SaveZCullData / RestoreZCullData). The host does no ZCull and never touches the area, but games allocate it from their own pools, and NVN // does not report 0. Cuphead (Unity 2017.4) allocates one per depth target (main+0x1948060) from its pool allocator, which gives a zero-size request the offset of a live block; its // map of allocations then loses that block (the zero-size one's size overwrites it, and freeing the zero-size one deletes it), and the block's own free later pushes a garbage-sized @@ -1836,7 +1844,8 @@ static int link_wait(const win_t *o, uint64_t timeout_ns); __attribute__((weak)) void dm_main_yield_stats(uint64_t *n, uint64_t *ns) { *n = 0; *ns = 0; } // The host's hle_thread.c provides the ground truth; 0 in graphics unit tests __attribute__((weak)) uint32_t dm_guest_work_qos(unsigned *count) { if (count) *count = 0; return QOS_CLASS_UNSPECIFIED; } int mtl_probe_ramp_on(void); // nvn_mtl.m: DM_FSTEP_PROBE_RAMP (default on; ab with DM_AB) -__attribute__((weak)) void dm_yield_top(char *out, size_t n) { if (n) snprintf(out, n, "-"); } // hle_thread.c: the threads that yielded most since the last call; none in graphics unit tests +__attribute__((weak)) void dm_yield_top(char *out, size_t n) { if (n) snprintf(out, n, "-"); } +__attribute__((weak)) void dm_clock_top(char *out, size_t n) { if (n) out[0] = 0; } // hle_thread.c: the threads that made most clock waits since the last call // hle_thread.c: the threads that yielded most since the last call; none in graphics unit tests __attribute__((weak)) void dm_thread_cpu(char *out, size_t n, double secs) { (void)secs; if (n) snprintf(out, n, "-"); } // hle_thread.c: guest-thread CPU by Switch priority band since the last call void mtl_res_stats(char *out, size_t n); void mtl_barrier_stats(uint64_t *skip, uint64_t *full); @@ -1934,6 +1943,7 @@ static double g_pres_exp[TWIN], g_pres_exp_last; // how long that frame should // The hold (60 Hz vsyncs) each present was given, by present number. On-screen intervals are read 8 presents late, so each is judged against the holds of its own presents: // with the frame step at 2 vsyncs every frame stays 33.3 ms, which is not a dropped frame static uint8_t g_hold_ring[16]; +static _Atomic int g_fs_fine; // nvn_fstep.fine (fstep_tick): frames late at hold 2, the longest a 30 fps cap allows, each shown at the next vsync after its hold (nvn_game_fps) static int fstep_hz(void); static double pres_expect_ms(uint64_t n) { // the interval between presents n - 1 and n shows frame n - 1: the display link holds it for its own present's hold, the Mac pacer spaces present n by n's, so the larger of the two int k = g_hold_ring[n % 16] > g_hold_ring[(n - 1) % 16] ? g_hold_ring[n % 16] : g_hold_ring[(n - 1) % 16]; @@ -1986,7 +1996,8 @@ static void power_line(uint64_t frame) { if (dg + dc + du + dn != pdg + pdc + pdu + pdn) LOG("[nvn] compute dispatches up to frame %llu: %llu after a barrier of the game's, %llu after a copy's range, %llu in the full order (a binding with no range), %llu with no barrier (DM_NVN_DISPATCH_BARRIER)", frame, (unsigned long long)(dg - pdg), (unsigned long long)(dc - pdc), (unsigned long long)(du - pdu), (unsigned long long)(dn - pdn)); pdg = dg; pdc = dc; pdu = du; pdn = dn; - char rs[400]; mtl_res_stats(rs, sizeof rs); static uint64_t pbs, pbf; uint64_t bs, bf; mtl_barrier_stats(&bs, &bf); + { char ck[400]; dm_clock_top(ck, sizeof ck); if (ck[0]) LOG("[nvn] clock waits up to frame %llu: %s", frame, ck); } + char rs[1400]; mtl_res_stats(rs, sizeof rs); static uint64_t pbs, pbf; uint64_t bs, bf; mtl_barrier_stats(&bs, &bf); uint64_t mtl_cut_count(void), mtl_copy_cut_count(void), mtl_blit_splits(void); void mtl_ubd_stats(uint64_t *, uint64_t *); static uint64_t pcut, pccut, pbsp, pud, puc; uint64_t cut = mtl_cut_count(), ccut = mtl_copy_cut_count(), bsp = mtl_blit_splits(), ud, uc; mtl_ubd_stats(&ud, &uc); void mtl_ubp_stats(uint64_t *, uint64_t *, uint64_t *); static uint64_t ppm, ppr, ppf; uint64_t pm, pr, pf_; mtl_ubp_stats(&pm, &pr, &pf_); void mtl_lc_stats(uint64_t *, uint64_t *); static uint64_t plt, pll; uint64_t lt, ll; mtl_lc_stats(<, &ll); @@ -2035,15 +2046,16 @@ static void tsummary(uint64_t frame) { } LOG("[nvn] timing up to frame %llu:%s", frame, line); { void mtl_pso_line(char *, size_t); char pl[1024]; mtl_pso_line(pl, sizeof pl); LOG("[nvn] pipelines up to frame %llu: %s", frame, pl); } - double tgt = 1000.0 / mtl_fps_target(); // milliseconds one frame should take: 16.7 at 60 fps, 33.3 when the game itself asks for 30 (the over-time / dropped-frame counts below use it) + double tgt = 1000.0 / (atomic_load(&g_fs_fine) ? 30 : mtl_fps_target()); // milliseconds one frame should take: 16.7 at 60 fps, 33.3 when the game itself asks for 30 or at a 30 cap whose late frames the 60 Hz link shows (the over-time / dropped-frame counts below use it) { unsigned n = g_tn[0] < TWIN ? g_tn[0] : TWIN, over = 0; double v[TWIN]; // frame interval gets its own line (M1 baseline): number of frames longer than one frame period in this window and p99 if (n) { memcpy(v, g_tw[0], n * sizeof *v); qsort(v, n, sizeof *v, dcmp); for (unsigned i = 0; i < n; i++) over += v[i] > tgt; LOG("[nvn] frame interval up to frame %llu: >%.1fms %u / %u frames, p99 %.2f ms", frame, tgt, over, n, v[(n * 99) / 100 < n ? (n * 99) / 100 : n - 1]); } } - { unsigned n = g_presn < TWIN ? g_presn : TWIN, k = 0, drop = 0, discard = 0; double v[TWIN]; // on-screen present: dropped frame = on screen longer than its hold × 1.5 (pres_expect_ms) or discarded - for (unsigned i = 0; i < n; i++) { double x = g_pres_iv[i]; if (x < 0) { drop++; discard++; } else if (x > 0) { v[k++] = x; drop += x > g_pres_exp[i] * 1.5; } } + { unsigned n = g_presn < TWIN ? g_presn : TWIN, k = 0, drop = 0, discard = 0, over[3] = {0}; double v[TWIN], vs = 1000.0 / fstep_hz(); // on-screen present: dropped frame = on screen longer than its hold × 1.5 (pres_expect_ms) or discarded + // over: intervals at their hold, one vsync longer and two or more longer (at hold 2: 33.3 / 50 / 66.7 ms and more; a frame late at hold 2 shows 50 ms on the 60 Hz link, 66.7 on the 30 Hz one) + for (unsigned i = 0; i < n; i++) { double x = g_pres_iv[i]; if (x < 0) { drop++; discard++; } else if (x > 0) { v[k++] = x; drop += x > g_pres_exp[i] * 1.5; over[x < g_pres_exp[i] + 0.5 * vs ? 0 : x < g_pres_exp[i] + 1.5 * vs ? 1 : 2]++; } } task_vm_info_data_t vi; mach_msg_type_number_t vc = TASK_VM_INFO_COUNT; double fp = task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&vi, &vc) == KERN_SUCCESS ? vi.phys_footprint / 1048576.0 : -1; double br = dm_brightness_now(); // footprint / brightness are carried on the on-screen present row: does not depend on the tick-entry observation gate (camp runs have it too) - if (k) { qsort(v, k, sizeof *v, dcmp); LOG("[nvn] on-screen up to frame %llu: %u frames, dropped %u (discarded %u), p99 %.2f ms; footprint %.0f MiB; brightness %.2f; thermal %d", frame, k + discard, drop, discard, v[(k * 99) / 100 < k ? (k * 99) / 100 : k - 1], fp, br, dm_thermal_now()); } + if (k) { qsort(v, k, sizeof *v, dcmp); LOG("[nvn] on-screen up to frame %llu: %u frames, dropped %u (discarded %u), p99 %.2f ms; intervals at the hold / one vsync longer / two or more %u / %u / %u; footprint %.0f MiB; brightness %.2f; thermal %d", frame, k + discard, drop, discard, v[(k * 99) / 100 < k ? (k * 99) / 100 : k - 1], over[0], over[1], over[2], fp, br, dm_thermal_now()); } g_presn = 0; } power_line(frame); { static uint64_t prev[6], pf; uint64_t v[6]; mtl_vbuf_stats(&v[0], &v[1], &v[2], &v[3], &v[4], &v[5]); @@ -2067,6 +2079,7 @@ static void tsummary(uint64_t frame) { py = cy; pk = ck; pw = cw; } pi = ci; pc = cc; pd = dr_; pf = frame; } uint64_t up, re, es = mtl_pkg_edge_skips(), fa, pr, op, oc; mtl_pkg_stats(&up, &re); nvn_dirty_stats(&fa, &pr); nvn_dirty_open_stats(&op, &oc); + { uint64_t sh, st, sm; mtl_spare_stats(&sh, &st, &sm); LOG("[nvn] packaged textures' spares: held %llu, retired idle or at memory pressure %llu, %llu MB", sh, st, sm); } LOG("[nvn] packaged textures: first uploads %llu, re-uploads on pool content change %llu, writes beside a texture only (not re-uploaded) %llu; write-protection faults %llu, pages unprotected before host writes %llu, opened for pool buffers %llu (changed while open %llu); missed %llu (cumulative); CPU-written textures alive %u", up, re, es, fa, pr, op, oc, mtl_pkg_miss(), mtl_cpu_tex_count()); memset(g_tn, 0, sizeof g_tn); } @@ -2254,13 +2267,16 @@ static int fps_present_cap(void) { static nvn_fstep g_fs; // present thread only static nvn_fgpu g_fg; // the GPU time at kmin and at the current hold (nvn_fstep_gpu_slowed) static _Atomic int g_fs_k; // the hold presentation follows (0 = not decided yet) -// The display link runs at 30 Hz at a 30 cap, except while the game fixes its own step at 1 (BotW's VFR override) +// The display link runs at 30 Hz at a 30 cap, except while the game fixes its own step at 1 (BotW's VFR override) and while frames are late at hold 2 (nvn_fstep.h fine): the 30 Hz link +// shows a late frame only on its next tick, 66.7 ms after the one before, where the 60 Hz link, which holds each frame its two vsyncs (g_link_hold_until, nvn_mtl.m), shows it at the next +// vsync, 50 ms. Ocarina of Time on an iPhone at the launcher's 30 fps cap (frames 36.5 ms) got 33 intervals of 66.7 ms in each 300 on the 30 Hz link int nvn_fps_high_now(void) { return atomic_load(&g_fs_k) == 1 ? 120 : 60; } // hle_fpslock.c: the target of the next game frame, from the hold in force // The rate of vi::GetDisplayVsyncEvent (hle_sdk16.c, nvn_mtl.m mtl_link_wait_vsync): the Switch's 60 Hz, or 120 while 120 fps is on and its hold is one tick of 1/120 s. A game that // waits for the next vblank each frame is held to the event's rate whatever the present cap: Unity's NVN device waits until its vblank time (set from the event) passes // (The Rogue Prince of Persia: main+0x14f65f0), so at 120 every frame came two ticks late and the hold fell back to 60. The hold's trial at 120 must already have the event at 120 int nvn_vsync_hz(void) { return fps_high() && atomic_load(&g_fs_k) == 1 && atomic_load(&g_high_cap) == 120 ? 120 : 60; } -int nvn_game_fps(void) { int c = fps_present_cap(); if (c) return c == 30 && atomic_load(&g_fs_k) == 1 && fstep_on() ? 60 : c; uint64_t s = atomic_load(&g_itv2_since); return g_hz > 0 && !g_display_mode && s && now_ns() >= s + 1000000000ull ? 30 : 60; } +int nvn_fstep_fine(void) { return atomic_load(&g_fs_fine); } // nvn_mtl.m link_latency: the 60 Hz link's lead while it shows a 30 fps cap's late frames +int nvn_game_fps(void) { int c = fps_present_cap(); if (c) return c == 30 && (atomic_load(&g_fs_k) == 1 || atomic_load(&g_fs_fine)) && fstep_on() ? 60 : c; uint64_t s = atomic_load(&g_itv2_since); return g_hz > 0 && !g_display_mode && s && now_ns() >= s + 1000000000ull ? 30 : 60; } static void present_cfg(const win_t *o) { if (g_hz >= 0) return; // The interval mode comes from the game profile (present_interval, default game): whether frames follow the present interval the game sets depends on whether the game's logic counts frames, which differs per game. Environment variables override it, and can override the fixed 60 Hz. @@ -2354,23 +2370,36 @@ static int fstep_hold(void) { } return h; } +// The longest hold the frame step may give at cap c (nvn_fstep_next's kmax), and why it may go no higher, for the log: a 30 fps cap's display link runs at 30 Hz, where a hold of 3 +// would take two ticks (66.7 ms), so it holds 2 and late frames are shown at the next vsync instead (nvn_fstep.h fine) +static int fstep_kmax(int c, const char **why) { + int kmin = fstep_hz() / c; + if (fps_high()) { *why = "120 fps: the game steps by its target, so a late frame steps down to 60 and no further"; return 2; } + if (!fstep_hold()) { *why = "fps_hold off: frames are not held longer than the cap's vsyncs"; return kmin; } + if (kmin >= 2) { *why = "the 30 fps cap's display link runs at 30 Hz, where a hold of 3 would take 66.7 ms; late frames are shown at the next vsync of a 60 Hz link instead"; return 2; } + *why = "the games' own interval logic uses 1-3"; return FSTEP_MAX; +} // Once per present, before this frame's period is taken: the time since the previous frame's start (shown) and the frame's cost decide this frame's hold and the next frame's step. // Cost = max(CPU: the time between the frames' starts without the pacing wait, GPU: the latest finished frame's GPU time), in vsyncs static void fstep_tick(const win_t *o, int c) { static uint64_t prev, t0, v0, fixed_sum, held[FSTEP_MAX + 1]; static int nlog; const double v = 1e9 / fstep_hz(); uint64_t st = g_fs_start ? g_fs_start : now_ns(), pw = g_fs_wait; g_fs_start = g_fs_wait = 0; - double shown = prev ? (st - prev) / v : 0, gpu = 0; prev = st; - for (uint64_t f = g_frame; f-- > 0 && g_frame - f <= 8;) { double g = mtl_gpu_ms(f); if (g >= 0) { gpu = g * 1e6 / v; break; } } + double shown = prev ? (st - prev) / v : 0, gpu = 0; prev = st; int gpu_on = 0; + for (uint64_t f = g_frame; f-- > 0 && g_frame - f <= 8;) { double g = mtl_gpu_ms(f); if (g >= 0) { gpu = g * 1e6 / v; gpu_on = 1; break; } } + static uint64_t pdraw; uint64_t npass, ndraw; mtl_stats(&npass, &ndraw); // the draws encoded since the last tick: what the GPU reference measured (nvn_fstep.h FSTEP_GPU_WORK) + double draws = pdraw && ndraw > pdraw ? (double)(ndraw - pdraw) : 0; pdraw = ndraw; + static uint64_t pdisp; static int pdisp_ok; uint64_t ndisp = mtl_dispatches(); // and the dispatches (none is a count too) + double disps = pdisp_ok ? (double)(ndisp - pdisp) : -1; pdisp = ndisp; pdisp_ok = 1; double cpu = shown - pw / v, cost = cpu > gpu ? cpu : gpu; - int kmin = fstep_hz() / c, kmax = fps_high() ? 2 : !fstep_hold() ? kmin : kmin >= 2 ? 2 : FSTEP_MAX, k0 = g_fs.k, // at 120 fps a late frame must step down whatever fps_hold says: the game steps by the target - kmin0 = g_fs.kmin, probe0 = g_fs.probe; + const char *kwhy; int kmin = fstep_hz() / c, kmax = fstep_kmax(c, &kwhy), k0 = g_fs.k; // at 120 fps a late frame must step down whatever fps_hold says: the game steps by the target + int kmin0 = g_fs.kmin, probe0 = g_fs.probe; int fixed = dm_fps_state ? (int)__atomic_load_n((uint32_t *)(dm_fps_state + 0x24), __ATOMIC_RELAXED) : 0; uint64_t probes0 = g_fs.probes, failed0 = g_fs.failed; // A screen whose rate is not a multiple of 60 (144, 165 Hz) shows the link's 1/60 s ticks on their nearest refreshes (nvn_mtl.m link_range), so a frame on time can show for one // refresh more than its hold: a cheap 50 ms frame shows 54.5 ms at 165 Hz, which counted as late kept the hold at 20 fps for good int hz = front_screen_max_fps(); g_fs.shown_slack = hz > fstep_hz() && hz % fstep_hz() && mtl_link_active() ? (double)fstep_hz() / hz : 0; - int cslow = fstep_cpu_slowed(o->presents), gslow = nvn_fstep_gpu_slowed(&g_fg, gpu, k0 ? k0 : kmin, kmin, probe0) && dm_thermal_now() <= 1 && !dm_low_power_now(); // same gates as the CPU's + int cslow = fstep_cpu_slowed(o->presents), gslow = nvn_fstep_gpu_slowed2(&g_fg, gpu, draws, disps, k0 ? k0 : kmin, kmin, probe0) && dm_thermal_now() <= 1 && !dm_low_power_now(); // same gates as the CPU's // Present snapshots (nvn_mtl.m snap_take): the game runs up to a frame ahead of the screen, so a frame whose work runs long is absorbed instead of shown late, and its cost is // no evidence against the hold (Breath of the Wild in Zora's Domain stepped to 30 at a GPU time of 0.75 vsyncs: the frame's CPU time held its waits on its own GPU work). // Lateness is then what the screen shows: the on-screen interval of the frame 8 presents back against its hold (pres_expect_ms), late by a quarter or dropped @@ -2390,21 +2419,32 @@ static void fstep_tick(const win_t *o, int c) { g_fs.per_vsync = fstep_hz() / 60; g_fs.smax = dm_fps_step_max; // the stub's largest step (Mario Kart World: 2): frames held longer than the game steps would play in slow motion g_fs.no_payback = fps_high(); // at 120 fps the game steps by its target, not by the step: a late frame is slow motion, so three raise the hold whatever the average + g_fs.gpu_on = gpu_on; g_fs.gpu = gpu; // an idle GPU's late frames do not step up; a hold the GPU does not explain is probed (nvn_fstep.h) int n = nvn_fstep_next(&g_fs, shown, cost, kmin, kmax, fixed, cslow || gslow); if (dm_fps_state) __atomic_store_n((uint32_t *)(dm_fps_state + 0x20), (uint32_t)n, __ATOMIC_RELAXED); atomic_store(&g_fs_k, g_fs.k); + int fine = g_fs.fine && c == 30 && !fps_high(), fine0 = atomic_exchange(&g_fs_fine, fine); // only a 30 fps cap's link runs slower than the vsyncs + static int nfine; + if (fine != fine0 && nfine < 40) { + if (fine) LOG("[nvn] frame step: frames late at hold %d, the longest the 30 fps cap allows (cost %.2f, GPU %.2f vsyncs): each is shown at the next vsync (a 60 Hz display link: 50 ms) instead of a 30 Hz link's next tick (66.7 ms), at present %llu%s", g_fs.k, cost, gpu, (unsigned long long)o->presents, ++nfine == 40 ? "; further changes only counted below" : ""); + else LOG("[nvn] frame step: %s: the 30 fps cap's own 30 Hz display link again at present %llu%s", c != 30 ? "the cap is no longer 30 fps" : fixed ? "the game fixes its own step" : g_fs.k < kmax ? "the hold may rise again" : "no late frame for 8 s", (unsigned long long)o->presents, ++nfine == 40 ? "; further changes only counted below" : ""); + } held[g_fs.k]++; if (fixed) fixed_sum += (uint64_t)n; // the stubs count only the host's steps static int fixed_was, nfix; if (fixed != fixed_was && nfix < 40) { nfix++; if (fixed) LOG("[nvn] frame step: the game fixes its own step at %d vsyncs at present %llu", fixed, (unsigned long long)o->presents); else LOG("[nvn] frame step: the game hands the step back to the host at present %llu", (unsigned long long)o->presents); } fixed_was = fixed; if (k0 && g_fs.k != k0 && nlog < 40) { - char why[160], held[48] = ""; int w = snprintf(why, sizeof why, "probe"); + char why[256], held[48] = ""; int w = snprintf(why, sizeof why, "probe"); if (cslow) w += snprintf(why + w, sizeof why - w, ", CPU %d%% on performance cores", g_fs_pshare); + if (w >= (int)sizeof why) w = sizeof why - 1; if (gslow) w += snprintf(why + w, sizeof why - w, ", GPU %.2f× its time at hold %d", g_fg.cur / g_fg.ref, kmin); - if (nvn_fstep_same(&g_fs)) snprintf(why + w, sizeof why - w, ", cost %.2f× the cost that held hold %d", g_fs.ccur / g_fs.cref, kmin); + if (w >= (int)sizeof why) w = sizeof why - 1; + if (nvn_fstep_same(&g_fs)) w += snprintf(why + w, sizeof why - w, ", cost %.2f× the cost that held hold %d", g_fs.ccur / g_fs.cref, kmin); + if (w >= (int)sizeof why) w = sizeof why - 1; // snprintf returns the length it would have written + if (g_fs.uprobe) snprintf(why + w, sizeof why - w, ", GPU fits a shorter hold, frames not waiting in the pacing"); if (g_fs.k > k0 && g_fs.cref > 0) snprintf(held, sizeof held, "; hold %d held at %.2f", kmin, g_fs.cref); // what a probe compares the longer hold's cost with LOG("[nvn] frame step: hold %d → %d %s at present %llu (%s; cost %.2f, GPU %.2f%s)%s", k0, g_fs.k, fps_high() ? "ticks of 1/120 s" : "vsyncs", (unsigned long long)o->presents, - fixed ? "the game's own step" : kmin0 > FSTEP_MAX ? "the game's own step ended" : kmin != kmin0 ? "the cap changed" : g_fs.k > k0 ? "3 late frames" : g_fs.probes != probes0 ? why : "trial", cost, gpu, held, ++nlog == 40 ? "; further changes only counted below" : ""); + fixed ? "the game's own step" : kmin0 > FSTEP_MAX ? "the game's own step ended" : kmin != kmin0 ? "the cap changed" : g_fs.k > k0 ? (g_fs.up_idle ? "30 late frames, some with the GPU idle" : "3 late frames") : g_fs.probes != probes0 ? why : "trial", cost, gpu, held, ++nlog == 40 ? "; further changes only counted below" : ""); } if (probe0 == 1 && g_fs.probe != 1 && !fixed && nlog < 40) // whether the controller raised the clock for the shorter deadline LOG("[nvn] frame step: the probe %s at present %llu (CPU %d%% on performance cores)%s", g_fs.probe == 2 ? "held" : "failed", (unsigned long long)o->presents, g_fs_pshare, ++nlog == 40 ? "; further changes only counted below" : ""); @@ -2414,9 +2454,10 @@ static void fstep_tick(const win_t *o, int c) { if (o->presents % 1800 == 0) { LOG("[nvn] 120 fps: held 1 / 2 ticks %llu / %llu frames, %llu late, %llu up / %llu down (%llu probes, %llu failed trials)", (unsigned long long)held[1], (unsigned long long)held[2], (unsigned long long)g_fs.late, (unsigned long long)g_fs.ups, (unsigned long long)g_fs.downs, (unsigned long long)g_fs.probes, (unsigned long long)g_fs.failed); memset(held, 0, sizeof held); } } else if (o->presents % 1800 == 0) { // game time against real time (1.000 = normal speed; lower when a device cannot hold 20 fps or after long stalls) uint64_t vs = __atomic_load_n((uint64_t *)(dm_fps_state + 0x30), __ATOMIC_RELAXED) + fixed_sum, t = now_ns(); - if (t0) LOG("[nvn] frame step: game time %.2f s in %.2f s (%.3f of real time); held 1 / 2 / 3 vsyncs %llu / %llu / %llu frames, %llu late, %llu vsyncs paid back, %.0f dropped, %llu up / %llu down (%llu probes, %llu failed trials)", + char fn[96] = ""; if (kmax == 2 && kmin == 2) snprintf(fn, sizeof fn, ", now %s (switched to the next vsync %llu× so far)", g_fs.fine ? "at the next vsync" : "on the 30 Hz link", (unsigned long long)g_fs.fines); + if (t0) LOG("[nvn] frame step: game time %.2f s in %.2f s (%.3f of real time); held 1 / 2 / 3 vsyncs %llu / %llu / %llu frames, %llu late, %llu vsyncs paid back, %.0f dropped, %llu up / %llu down (%llu probes, %llu failed trials); cap %d fps, hold at most %d vsyncs: %s%s", (vs - v0) / 60.0, (t - t0) / 1e9, (vs - v0) / 60.0 / ((t - t0) / 1e9), (unsigned long long)held[1], (unsigned long long)held[2], (unsigned long long)held[3], - (unsigned long long)g_fs.late, (unsigned long long)g_fs.paid, g_fs.dropped, (unsigned long long)g_fs.ups, (unsigned long long)g_fs.downs, (unsigned long long)g_fs.probes, (unsigned long long)g_fs.failed); + (unsigned long long)g_fs.late, (unsigned long long)g_fs.paid, g_fs.dropped, (unsigned long long)g_fs.ups, (unsigned long long)g_fs.downs, (unsigned long long)g_fs.probes, (unsigned long long)g_fs.failed, c, kmax, kwhy, fn); t0 = t; v0 = vs; memset(held, 0, sizeof held); } } @@ -2440,7 +2481,8 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) { if (fps_high()) high_cap_tick(); if (dm_fps_state) __atomic_store_n((uint32_t *)(dm_fps_state + 4), (uint32_t)dm_movie_playing(), __ATOMIC_RELAXED); // the stubs' copy of the movie state (hle.h) int c = fps_step_cap(); - if (dm_fps_state) { static int was; if (c != was) { LOG("[nvn] frame step cap %d → %d fps at present %llu%s", was, c, (unsigned long long)o->presents, c == 30 && was == 60 ? (dm_movie_playing() ? " (movie playing)" : thermal_capped() ? " (thermal state serious)" : "") : ""); was = c; } } + if (dm_fps_state) { static int was; if (c != was) { char kw[256] = ""; const char *kwhy; if (c) snprintf(kw, sizeof kw, ": hold at most %d vsyncs, %s", fstep_kmax(c, &kwhy), kwhy); // the cap and why the hold may not rise above it, so a log shows both at once + LOG("[nvn] frame step cap %d → %d fps at present %llu%s%s", was, c, (unsigned long long)o->presents, c == 30 && was == 60 ? (dm_movie_playing() ? " (movie playing)" : thermal_capped() ? " (thermal state serious)" : "") : "", kw); was = c; } } if (c) fstep_tick(o, c); dm_fps_lock_tick(); // after the frame step: at 120 fps the target follows the hold just decided static uint64_t prev_in, prev_out, prev_pass, prev_draw; @@ -2602,7 +2644,7 @@ NVN(nvnBufferInitialize, NVNboolean, NVNbuffer *buf, const NVNbufferBuilder *b) // compressing encoder (when the pause menu opens, and near a save commit): the buffer's one use is a texture-to-buffer copy of the picture's own extent, which lies inside the pool. Not an error by itself: one line. if ((uint64_t)bb->off + bb->size > bb->pool->size) ONCE_LOG("BufferInitialize: a buffer reaches past the end of its pool (offset %#llx size %#llx pool %#llx); only an access that leaves the pool is an error, and it is reported where it happens", (unsigned long long)bb->off, (unsigned long long)bb->size, (unsigned long long)bb->pool->size); *(buf_t *)buf = (buf_t){.magic = MAGIC('B', 'U', 'F', 0), .pool = bb->pool, .off = bb->off, .size = bb->size}; - pool_mark_addressed(bb->pool); + pool_mark_addressed(bb->pool); mtl_pool_addressed_by(bb->pool->mem + bb->off, bb->size ? bb->size : 1, 1); OLOG("BufferInitialize %p pool=%p off=%#llx size=%#llx", (void *)buf, (const void *)bb->pool, (unsigned long long)bb->off, (unsigned long long)bb->size); return 1; } @@ -2715,6 +2757,7 @@ static void vrun_set(struct vpool *v, uint64_t lo, uint64_t hi, int mapped) { } if (mapped) { nl[nn++] = (struct vrun){mlo, mhi}; add[na] = v->base + mlo; asz[na++] = mhi - mlo; } if (nd || na) mtl_pool_replace(del, nd, add, asz, na); + for (int i = 0; i < na; i++) mtl_pool_tag(add[i], (uint32_t)v->pool->flags | 0x80000000u); // res_top: a virtual pool's mapped run free(del); for (int a = 1; a < nn; a++) for (int b = a; b > 0 && nl[b].lo < nl[b - 1].lo; b--) { struct vrun t = nl[b]; nl[b] = nl[b - 1]; nl[b - 1] = t; } if (nn > v->nrun && nn >= 1024 && !(nn & (nn - 1))) LOG("[nvn] virtual pool %p: %d separate mapped runs", (const void *)v->pool, nn); @@ -2843,7 +2886,7 @@ NVN(nvnMemoryPoolMapVirtual, NVNboolean, NVNmemoryPool *p, int n, const NVNmappi if (o->mem && o->mem != base) { LOG("[RED] MapVirtual: non-contiguous mapping (true sparse) not implemented: virtual pool %p already maps to %p, this request wants %p", (void *)o, (void *)o->mem, (void *)base); return 0; } if (!o->mem) LOG("[nvn] MapVirtual: the storage of virtual pool %p (%#llx bytes) points at physical pool %p + %#llx", (void *)o, (unsigned long long)o->size, (const void *)ph, (unsigned long long)(r[i].poff - r[i].voff)); o->mem = base; - mtl_pool_addressed(o->mem, o->size); // an address may have been given out before it had storage + mtl_pool_addressed_by(o->mem, o->size, 3); // an address may have been given out before it had storage } return 1; } diff --git a/dm/gfx/nvn/nvn_fstep.h b/dm/gfx/nvn/nvn_fstep.h index 404fc7fdf9..74e0768c3f 100644 --- a/dm/gfx/nvn/nvn_fstep.h +++ b/dm/gfx/nvn/nvn_fstep.h @@ -25,6 +25,21 @@ // rise set k to kmin with no grace, so three frames late while the clock rose stepped up again, with cref dropped at the cap change and a GPU reference taken at the 30 fps // cap: neither the fit trial (a GPU-bound cost near FSTEP_FIT) nor a probe brought kmin back (t_fstep: the movie and thermal cap cases). A cref kept from before the cap // starts a probe only when the cost at the longer hold is within FSTEP_SAME of it, and a failed probe doubles the hold-off as any other does. +// The caller may report each frame's GPU time (gpu_on, gpu). A late frame whose GPU was idle (under FSTEP_GPU_IDLE: a loading or progress screen, the first frames after a +// pipeline prepare) does not count toward the 3 late frames of a step up: nothing is being drawn, so the lateness is the CPU's startup or load work, which the debt rule +// absorbs, not what the scene costs (FSTEP_RUN late frames in a row step up whatever the GPU). Ocarina of Time stepped 1 → 2 → 3 at presents 9 and 12 of a warm start (cost 1.92 and 5.57 vsyncs, GPU 0.02 and 0.01) while a 118 s archive write ran. +// And a longer hold that the GPU does not explain is probed: FSTEP_RUN frames in a row at a hold above kmin whose GPU time fits k − 1 and that waited for nothing in the +// host's pacing (cost within FSTEP_LATE of the time shown) start a probe after the hold-off. Such a game waits for its frames outside the window's acquire (Ocarina of +// Time: no pacing wait at any hold, its frame time all counted as work), so its cost is the hold itself whatever the hold is, never fits k − 1, and the fit trial never comes: +// it stayed at hold 3 (18 fps, work 50 ms, GPU 12.5 ms) for about 1,470 presents where hold 1 held at 16.6 ms before. A game whose CPU really needs the longer hold fails the +// probe; these probes have their own hold-off (uhold), doubled after each one fails up to FSTEP_UHOLD_MAX (60 s), so such a game pays one failed probe a minute at most +// and not one every 8 s. Late frames with the GPU idle still step up after FSTEP_RUN of them in a row: a CPU-heavy scene that draws almost nothing is not a load. +// Late frames at the longest hold allowed (kmax: 2 at a 30 fps cap, or kmin with fps_hold off) cannot step up. The caller's display link at the cap's rate (30 Hz) can then only +// show a late frame on its next tick, 66.7 ms after the one before: Ocarina of Time on an iPhone at the launcher's 30 fps cap (frames 36.5 ms, GPU 32 ms) left one tick in 9 empty, +// 33 intervals of 66.7 ms in each 300 and the rest 33.3, at 27 fps. So the same late frames that would step up (3 in a row, or FSTEP_RUN with the GPU idle among them) set fine: +// the caller then shows each frame at the next vsync after its hold instead (a 60 Hz link that holds each frame its k vsyncs), 33.3 or 50 ms and never 66.7, still never faster +// than the cap. fine ends after FSTEP_HOLD_MAX vsyncs with no such late frame (a scene that fits again; a late frame now and then does not flap the link), when the hold may rise +// again (the cap rose) and while the game fixes its own step. #pragma once #include #include @@ -46,6 +61,8 @@ // second half cost at most 1 − FSTEP_RAMP of its first half, and had a late frame (a window on time is judged as a trial), starts another, up to FSTEP_PROBE_MAX frames in all #define FSTEP_RAMP 0.05 // the fall in cost from one half of a grace window to the next that shows the clock still rising (the per-frame noise of a 25 ms frame is 4%, of 15 frames 1%) #define FSTEP_PROBE_MAX 180 // grace frames a probe may take in all (3 s at 60 fps): a clock that keeps rising without reaching the hold is not waited for longer +#define FSTEP_GPU_IDLE 0.05 // GPU time (in the frame's unit) under which nothing is being drawn: 0.8 ms at 60 fps (Ocarina of Time's progress screen 0.2–0.3 ms, its scenes 12 ms) +#define FSTEP_UHOLD_MAX 3600.0 // the longest hold-off before a probe of a hold the GPU does not explain (nvn_fstep_unpaced), doubled after each such probe fails: 60 s typedef struct { int k, step; // vsyncs each frame stays on screen; the step handed to the game for the next frame (k, or k + 1 while paying back) @@ -63,33 +80,44 @@ typedef struct { double run, crun, cref; // vsyncs at kmin in a row; the cost of its frames on time (running mean; not during a probe's trial, whose frames run while the clock rises); // crun when the last run of FSTEP_HOLD_MAX or more ended in a step up or a cap change (0 = none yet) double ccur; int ck, cn; // the cost of the frames on time at the longer hold ck (running mean) and their count + int gpu_on; double gpu; // set by the caller before each call, then cleared: 1 = gpu is the frame's GPU time (the latest finished frame's, in the unit of shown); 0 = not reported + int urun; // frames in a row at a hold above kmin whose GPU time fits k − 1 and that waited for nothing in the host's pacing (nvn_fstep_unpaced) + int ilate_run, uprobe; // late frames in a row, those with the GPU idle included; 1 = the probe running was started by nvn_fstep_unpaced alone + int up_idle; // 1 = the last step up came from FSTEP_RUN late frames with the GPU idle among them (for the caller's log) + double uhold; // vsyncs since the last step up before such a probe: 1 s, doubled after each one fails up to FSTEP_UHOLD_MAX, back to 1 s when kmin holds int ckmin; // the kmin run, crun and cref belong to double cref_at[FSTEP_MAX + 1]; // cref of each kmin, kept while another kmin is in force double over[FSTEP_RUN], over_sum; int over_i, over_k; // the last FSTEP_RUN frames at the hold over_k: shown − k of each (clamped), their sum; the next slot double last_cost[3]; // the last three frames' costs, oldest first int smax; // set by the caller: the largest step the game takes (its stub's STEP_MAX; 0 = FSTEP_MAX) int no_payback; // set by the caller: 1 = the game does not take the step (120 fps: it steps by its target), so three late frames raise the hold whatever the average - uint64_t late, paid, ups, downs, failed, probes; double dropped; // statistics for the log + int fine; double fine_ok; // 1 = frames are late at kmax, shown at the next vsync after their hold; vsyncs since the last late frame while fine (FSTEP_HOLD_MAX ends it) + uint64_t late, paid, ups, downs, failed, probes, fines; double dropped; // statistics for the log (fines: times fine was set) } nvn_fstep; // Whether the cost at the longer hold is the cost that held kmin (a probe without a slowed report) static inline int nvn_fstep_same(const nvn_fstep *s) { return s->cref > 0 && s->cn >= FSTEP_RUN && s->ccur <= FSTEP_SAME * s->cref; } +// Whether the longer hold is one the GPU does not explain while the frames' time is all the game's own (a probe without a slowed report) +static inline int nvn_fstep_unpaced(const nvn_fstep *s) { return s->urun >= FSTEP_RUN; } // Once per frame. shown: real time since the previous frame's start, in vsyncs; cost: the frame's work, max(CPU, GPU), in vsyncs (a GPU that cannot keep up makes frames late too); kmin: 1 at a 60 fps cap, 2 at 30; // kmax: the longest hold (FSTEP_MAX; 2 at a 30 fps cap, where the display link runs at 30 Hz and holds only even counts); fixed: a step the game has set itself (BotW's // VFR override; 0 = none), which the host then holds as it is; slow: the CPU runs below its speed for reasons other than heat, so a cost above k − 1 is no evidence // against kmin (probes). Returns the step for the next frame; s->k is how long that frame stays on screen static inline int nvn_fstep_next(nvn_fstep *s, double shown, double cost, int kmin, int kmax, int fixed, int slow) { - const double hold0 = FSTEP_HOLD0 * (s->per_vsync ? s->per_vsync : 1), hold_max = FSTEP_HOLD_MAX * (s->per_vsync ? s->per_vsync : 1); + const double hold0 = FSTEP_HOLD0 * (s->per_vsync ? s->per_vsync : 1), hold_max = FSTEP_HOLD_MAX * (s->per_vsync ? s->per_vsync : 1), + uhold_max = FSTEP_UHOLD_MAX * (s->per_vsync ? s->per_vsync : 1); if (kmin < 1) kmin = 1; const int smax = s->smax > 0 && s->smax < FSTEP_MAX ? s->smax : FSTEP_MAX; if (kmax > smax) kmax = smax; if (kmin > smax) kmin = smax; if (kmax < kmin) kmax = kmin; if (!s->hold) s->hold = hold0; + if (!s->uhold) s->uhold = hold0; + int gpu_on = s->gpu_on; double gpu = s->gpu; s->gpu_on = 0; s->gpu = 0; // cleared on every return if (fixed > 0) { // the game's own step: speed is right by construction, nothing to pay back s->k = s->step = fixed < smax ? fixed : smax; - s->debt = 0; s->late_run = s->fit_run = s->trial = s->probe = s->grace = 0; s->run = 0; + s->debt = 0; s->late_run = s->ilate_run = s->fit_run = s->trial = s->probe = s->grace = 0; s->run = 0; s->fine = 0; s->kmin = FSTEP_MAX + 1; // when it ends, k starts again from kmin return s->step; } @@ -105,18 +133,23 @@ static inline int nvn_fstep_next(nvn_fstep *s, double shown, double cost, int km s->since += shown; int cap_probe = kmin < s->kmin && s->kmin <= FSTEP_MAX && s->k > kmin; if (cap_probe) { // the cap rose: a probe at once, whose grace covers the clocks still set for the longer hold - s->k = kmin; s->probes++; s->trial = FSTEP_RUN; s->probe = 1; s->grace = FSTEP_GRACE; s->fit_run = s->late_run = 0; s->pa = s->pb = 0; s->plate = s->ptotal = 0; + s->k = kmin; s->probes++; s->trial = FSTEP_RUN; s->probe = 1; s->uprobe = 0; s->grace = FSTEP_GRACE; s->fit_run = s->late_run = s->ilate_run = 0; s->pa = s->pb = 0; s->plate = s->ptotal = 0; } else if (kmin < s->kmin || s->k < kmin) s->k = kmin; // the game's own step ended, or the cap fell if (s->k > kmax) s->k = kmax; s->kmin = kmin; int scr = s->screen; s->screen = 0; + int idle = gpu_on && gpu < FSTEP_GPU_IDLE; // nothing drawn: a late frame is load or startup work, not the scene's cost int late = scr ? scr == 2 : shown > held + FSTEP_LATE + s->shown_slack || cost > held + FSTEP_LATE, grace = s->grace > 0; if (grace && !cap_probe) { // the completed frame at the old cap does not consume the new hold's grace if (s->grace > FSTEP_GRACE / 2) s->pa += cost; else s->pb += cost; s->plate += late; s->ptotal++; if (!--s->grace && s->ramp && s->plate && s->ptotal + FSTEP_GRACE <= FSTEP_PROBE_MAX && s->pb <= (1 - FSTEP_RAMP) * s->pa) { s->grace = FSTEP_GRACE; s->pa = s->pb = 0; s->plate = 0; } // still getting cheaper: another window } - if (late) { s->late++; s->late_run = grace ? 0 : s->late_run + 1; s->fit_run = 0; } else s->late_run = 0; + // A late frame with the GPU idle neither counts toward the 3 nor ends their run; FSTEP_RUN late frames in a row step up whatever the GPU (a CPU-heavy scene, not a load) + if (late) { s->late++; s->late_run = grace ? 0 : s->late_run + !idle; s->ilate_run = grace ? 0 : s->ilate_run + 1; s->fit_run = 0; } else s->late_run = s->ilate_run = 0; + // The frame waited for nothing in the host's pacing while held longer than kmin, and its GPU time fits a shorter hold: the hold is not what the GPU needs (nvn_fstep_unpaced) + // (k − 1, not kmin: the GPU clock falls at a longer hold, so a GPU that fits kmin there may read above it; a GPU that really needs the hold fails the probe) + s->urun = held > kmin && s->k == held && gpu_on && gpu <= FSTEP_FIT * (held - 1) && cost >= shown - FSTEP_LATE ? s->urun + 1 : 0; // The cost of the frames on time (a hitch is not what the scene costs): at kmin, and at the longer hold if (kmin != s->ckmin) { // another cap: its run starts over, and what held it before comes back if (s->ckmin >= 1 && s->ckmin <= FSTEP_MAX) { @@ -136,20 +169,27 @@ static inline int nvn_fstep_next(nvn_fstep *s, double shown, double cost, int km } // A rate below k over the last FSTEP_RUN frames (the slots not filled yet since the hold changed count as on time); the screen's verdict (present snapshots) is its own int short_of_k = scr || s->no_payback || s->over_sum > FSTEP_LATE * FSTEP_RUN; - if (s->late_run >= 3 && s->k < kmax && short_of_k) { // step up to the cost of the cheapest of the three late frames, at least one vsync + if ((s->late_run >= 3 || s->ilate_run >= FSTEP_RUN) && s->k < kmax && short_of_k) { // step up to the cost of the cheapest of the three late frames, at least one vsync double c3 = s->last_cost[0] < s->last_cost[1] ? s->last_cost[0] : s->last_cost[1]; if (s->last_cost[2] < c3) c3 = s->last_cost[2]; int want = (int)ceil(c3 - 0.05); if (want < s->k + 1) want = s->k + 1; if (want > kmax) want = kmax; - if (s->trial || (s->probe == 2 && s->since < hold_max)) { s->failed++; s->trial = 0; s->hold = s->hold * 2 < hold_max ? s->hold * 2 : hold_max; } - else if (s->probe == 2) s->hold = hold0; // the probe's run at kmin lasted - if (held == kmin && s->run >= hold_max) s->cref = s->crun; // kmin held 8 s at this cost - s->k = want; s->ups++; s->late_run = s->fit_run = 0; s->since = 0; s->probe = 0; + if (s->trial || (s->probe == 2 && s->since < hold_max)) { + s->failed++; s->trial = 0; s->hold = s->hold * 2 < hold_max ? s->hold * 2 : hold_max; + if (s->uprobe) s->uhold = s->uhold * 2 < uhold_max ? s->uhold * 2 : uhold_max; // a CPU that needs the hold: probed ever more rarely + } else if (s->probe == 2) s->hold = s->uhold = hold0; // the probe's run at kmin lasted + if (held == kmin && s->run >= hold_max) { s->cref = s->crun; s->uhold = hold0; } // kmin held 8 s at this cost + s->up_idle = s->late_run < 3; + s->k = want; s->ups++; s->late_run = s->ilate_run = s->fit_run = s->urun = 0; s->since = 0; s->probe = s->uprobe = 0; } else if (s->trial && !grace && !--s->trial) { if (s->probe) { s->probe = 2; s->since = 0; } else s->hold = hold0; } // the trial held (a probe's run at kmin is judged at the next step up) + // Late at the longest hold allowed: shown at the next vsync, as the hold cannot rise (fine above) + if (s->k >= kmax && (s->late_run >= 3 || s->ilate_run >= FSTEP_RUN)) { if (!s->fine) s->fines++; s->fine = 1; s->fine_ok = 0; } + else if (s->fine) { s->fine_ok = late && !idle ? 0 : s->fine_ok + shown; if (s->k < kmax || s->fine_ok >= hold_max) s->fine = 0; } if (!late) s->fit_run = s->k > kmin && cost <= FSTEP_FIT * (s->k - 1) ? s->fit_run + 1 : 0; if (s->fit_run >= FSTEP_RUN && s->since >= s->hold && !s->trial) { s->k--; s->downs++; s->trial = FSTEP_RUN; s->fit_run = 0; } - else if ((slow || nvn_fstep_same(s)) && s->k > kmin && s->since >= s->hold && !s->trial) { // probe: straight to kmin, so the controller sees the whole deadline - s->k = kmin; s->downs++; s->probes++; s->trial = FSTEP_RUN; s->probe = 1; s->grace = FSTEP_GRACE; s->fit_run = s->late_run = 0; s->pa = s->pb = 0; s->plate = s->ptotal = 0; + else if ((slow || nvn_fstep_same(s) || (nvn_fstep_unpaced(s) && s->since >= s->uhold)) && s->k > kmin && s->since >= s->hold && !s->trial) { // probe: straight to kmin, so the controller sees the whole deadline + s->uprobe = !slow && !nvn_fstep_same(s); + s->k = kmin; s->downs++; s->probes++; s->trial = FSTEP_RUN; s->probe = 1; s->grace = FSTEP_GRACE; s->fit_run = s->late_run = s->ilate_run = 0; s->pa = s->pb = 0; s->plate = s->ptotal = 0; // urun ends with the next frame at kmin (kept for the caller's log) } s->step = s->k + (s->debt >= 1 && s->k < smax); s->paid += s->step > s->k; @@ -161,18 +201,42 @@ static inline int nvn_fstep_next(nvn_fstep *s, double shown, double cost, int km // FSTEP_GPU_SLOW times its time at kmin and it alone does not fit k − 1 (a GPU at 3 ms of 17, 6 times its time on a loading screen, is not what holds a frame back). // The reference is not updated during a probe's trial (its frames run while the clock is still rising), so a failed probe leaves it as it was. It is kept for each kmin: one // learned at a 30 fps cap is the GPU time at the clock that cap left (lowered for 30 fps, and under the thermal cap for the heat), and taken as hold 1's after the cap rose it -// made the same work at hold 2 look not slowed +// made the same work at hold 2 look not slowed. +// The comparison holds only for the same work: a clock that fell shows as the same draws taking longer. The draws a frame encodes are kept beside each reference (dref_at) and at +// the longer hold (dcur); when both are known, the GPU counts as slowed only while they are within FSTEP_GPU_WORK of each other. Ocarina of Time on an M4 Air ran its title and +// loading screen at hold 1 (GPU 0.2 vsyncs, 2-60 draws), then gameplay at hold 2 (1.4 vsyncs, 700-900 draws, 1.3 at hold 1): against the loading screen's reference the GPU +// read 6 times slowed, and the host probed hold 1 every few seconds (32 probes in 66 s, all failed), each failure's late frames stepping it on to hold 3 (20 fps). +// Compute dispatches are work too, which draws do not see: Ocarina of Time's title spends 61 ms of an M1 iPad's GPU on its movie network's 14 dispatches with 20-80 draws, and its +// hold-1 reference came from the boot screens (0.4 ms, 22 draws, no dispatch), so the title read as a GPU slowed 9.9 times and probed hold 1 every 3-6 s, none held. The +// dispatches a frame encodes are kept the same way (cref_at, ccur; counted as dispatches + 1, so a frame with none is known), and both must match #define FSTEP_GPU_SLOW 1.3 // GPU time at the longer hold against its time at kmin #define FSTEP_GPU_N 30 // frames at the longer hold before the comparison counts -typedef struct { double ref, cur; int n, k; double ref_at[FSTEP_MAX + 1]; } nvn_fgpu; // GPU time at kmin (running mean; of every kmin in ref_at); at the current hold k and its frame count -static inline int nvn_fgpu_slow(const nvn_fgpu *g) { return g->n >= FSTEP_GPU_N && g->ref > 0 && g->cur >= FSTEP_GPU_SLOW * g->ref && g->cur > FSTEP_FIT * (g->k - 1); } -// Once per frame, with the frame's GPU time (vsyncs; 0 = none finished yet) and the hold and probe state (nvn_fstep.probe) it ran under -static inline int nvn_fstep_gpu_slowed(nvn_fgpu *g, double gpu, int k, int kmin, int probe) { +#define FSTEP_GPU_WORK 1.5 // draws at the longer hold against the reference's, either way, that still count as the same work (one scene's views vary by about 1.3) +typedef struct { double ref, cur; int n, k; double ref_at[FSTEP_MAX + 1]; double dref, dcur, dref_at[FSTEP_MAX + 1]; double cref, ccur, cref_at[FSTEP_MAX + 1]; } nvn_fgpu; // GPU time at kmin + // (running mean; of every kmin in ref_at); at the current hold k and its frame count; the draws and the dispatches + 1 a frame encodes beside each (0 = not known) +static inline int nvn_fgpu_near(double a, double b) { return a <= 0 || b <= 0 || (b <= FSTEP_GPU_WORK * a && a <= FSTEP_GPU_WORK * b); } +static inline int nvn_fgpu_same_work(const nvn_fgpu *g) { return nvn_fgpu_near(g->dref, g->dcur) && nvn_fgpu_near(g->cref, g->ccur); } +static inline int nvn_fgpu_slow(const nvn_fgpu *g) { return g->n >= FSTEP_GPU_N && g->ref > 0 && g->cur >= FSTEP_GPU_SLOW * g->ref && g->cur > FSTEP_FIT * (g->k - 1) && nvn_fgpu_same_work(g); } +// Once per frame, with the frame's GPU time (vsyncs; 0 = none finished yet), its draws (0 = not counted), its dispatches (< 0 = not counted) and the hold and probe state +// (nvn_fstep.probe) it ran under +static inline int nvn_fstep_gpu_slowed2(nvn_fgpu *g, double gpu, double draws, double disps, int k, int kmin, int probe) { if (kmin < 1 || kmin > FSTEP_MAX) return 0; // no reference slot for it (hle_nvn.c passes 1 or 2) - g->ref = g->ref_at[kmin]; + double cw = disps >= 0 ? disps + 1 : 0; + g->ref = g->ref_at[kmin]; g->dref = g->dref_at[kmin]; g->cref = g->cref_at[kmin]; if (gpu <= 0) return nvn_fgpu_slow(g); - if (k <= kmin) { if (probe != 1) g->ref = g->ref_at[kmin] = g->ref > 0 ? g->ref + (gpu - g->ref) / 32 : gpu; g->n = 0; g->k = k; return 0; } + if (k <= kmin) { + if (probe != 1) { + g->ref = g->ref_at[kmin] = g->ref > 0 ? g->ref + (gpu - g->ref) / 32 : gpu; + if (draws > 0) g->dref = g->dref_at[kmin] = g->dref > 0 ? g->dref + (draws - g->dref) / 32 : draws; + if (cw > 0) g->cref = g->cref_at[kmin] = g->cref > 0 ? g->cref + (cw - g->cref) / 32 : cw; + } + g->n = 0; g->k = k; return 0; + } if (k != g->k) { g->k = k; g->n = 0; } - g->cur = g->n ? g->cur + (gpu - g->cur) / 8 : gpu; g->n++; + g->cur = g->n ? g->cur + (gpu - g->cur) / 8 : gpu; + if (draws > 0) g->dcur = g->n && g->dcur > 0 ? g->dcur + (draws - g->dcur) / 8 : draws; + if (cw > 0) g->ccur = g->n && g->ccur > 0 ? g->ccur + (cw - g->ccur) / 8 : cw; + g->n++; return nvn_fgpu_slow(g); } +static inline int nvn_fstep_gpu_slowed(nvn_fgpu *g, double gpu, double draws, int k, int kmin, int probe) { return nvn_fstep_gpu_slowed2(g, gpu, draws, -1, k, kmin, probe); } // dispatches not counted diff --git a/dm/gfx/nvn/nvn_mtl.h b/dm/gfx/nvn/nvn_mtl.h index fb9fb002d7..2738426a72 100644 --- a/dm/gfx/nvn/nvn_mtl.h +++ b/dm/gfx/nvn/nvn_mtl.h @@ -15,6 +15,8 @@ void bf_want_note(const char *key); // Memory pool: [mem, mem+size) is expanded outward to page boundaries to build a zero-copy buffer; look up the buffer and offset by GPU address (= CPU address) void mtl_pool_add(const void *mem, uint64_t size); void mtl_pool_addressed(const void *mem, uint64_t size); // the game holds a GPU address in this range, so raw global memory may reach it +void mtl_pool_addressed_by(const void *mem, uint64_t size, int kind); // the same, with who gave it out (0 pool, 1 buffer: its range, the table takes the whole pool, 2 texture, 3 virtual mapping), for res_top; 4: a shader-code pool's own address, which keeps it out of the table +void mtl_pool_tag(const void *mem, uint32_t tag); // res_top: the pool's flags (bit 31: a mapped run of a virtual pool) void mtl_pool_del(const void *mem); void mtl_pool_replace(const void *const *del, int ndel, const void *const *add, const uint64_t *size, int nadd); // in one step for every lookup (a sparse pool's runs, hle_nvn.c vrun_set) void dm_gfx_addr_note(uint64_t a, char *note, size_t n); // what the graphics layer knows of an address (the crash dump, red lines) diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index a66eaad09e..e5dcc16cce 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -278,13 +278,107 @@ static void ws_report(uint64_t frame, uint64_t frames) { if (n && o < sizeof line - 160) o += snprintf(line + o, sizeof line - o, " %s %.2f/frame (blocked %.2f, %.3f ms);", ws_name[i], (double)n / frames, (double)b / frames, ns / 1e6 / frames); } MLOG("[waits] up to frame %llu, per frame:%s", (unsigned long long)frame, o ? line : " none"); } +// DM_NVN_GPUPROF's CPU timeline: while a frame is profiled, the host's CPU side is logged beside its encoders' GPU stamps, so a gap between two encoders says what the GPU waited +// for: each submission's encoding (its begin to its end on the replay thread), each real commit to the queue (from before its uniform-copy wait to the commit's return; the encode +// thread makes it), every blocking CPU wait for the GPU by its wait-ledger site (the game's SyncWait, the allocator, ...), and the NVN queue worker parked with nothing it can +// replay (no work, or the first job of each queue held by an event or sync wait). Mach ticks: Metal 4's counter-heap timestamps are the same clock (measured on an M-series Mac: +// a stamp falls between the commit's and the completion's mach_absolute_time), so the report places them on the encoders' timeline with no conversion +enum { GT_SUB, GT_COMMIT, GT_WAIT, GT_QPARK, GT_MAX = 2048 }; +typedef struct { uint64_t t0, t1, a, b; uint32_t kind; } gt_ev; +static gt_ev g_gt[GT_MAX]; static _Atomic int g_gt_n, g_gt_on; +static uint64_t g_sub_serial; static uint32_t g_seg; // tentative: defined with the submission state below +static _Atomic uint64_t g_sub_cmt; // the last submission whose commit the encode thread has made (its fence; with no encode thread, the last committed: mtl_sub_commit) +static inline void gt_put(uint32_t kind, uint64_t t0, uint64_t a, uint64_t b) { + if (__builtin_expect(!atomic_load_explicit(&g_gt_on, memory_order_relaxed), 1)) return; + int i = atomic_fetch_add_explicit(&g_gt_n, 1, memory_order_relaxed); if (i < GT_MAX) g_gt[i] = (gt_ev){t0, mach_absolute_time(), a, b, kind}; +} +// The NVN queue worker (nvn_queue.inc) parked from t0 until now: why (0 no work queued, 1 an event wait, 2 a sync wait) and the held queue's serial +void mtl_gp_note_park(uint64_t t0, unsigned why, uint64_t queue) { gt_put(GT_QPARK, t0, why, queue); } +// A main command buffer's commit feedback, kept as blocks: the feedback of several submissions can then ride on one commit (nvn_rec.h, submissions merged into one command buffer) +@interface DmCommitFB : NSObject { @public NSMutableArray *blocks; } +- (void)addFeedbackHandler:(void (^)(id))b; +@end +@implementation DmCommitFB +- (instancetype)init { if ((self = [super init])) blocks = [NSMutableArray array]; return self; } +- (void)addFeedbackHandler:(void (^)(id))b { [blocks addObject:[b copy]]; } +@end +// The feedback one merged submission's blocks get: the command buffer's error and that submission's own part of its GPU time +@interface DmPartFB : NSObject { @public double t0, t1; NSError *err; } +@end +@implementation DmPartFB +- (CFTimeInterval)GPUStartTime { return t0; } +- (CFTimeInterval)GPUEndTime { return t1; } +- (NSError *)error { return err; } +@end +static MTL4CommitOptions *commit_opts(DmCommitFB *fb) { + if (!fb) return nil; + MTL4CommitOptions *o = [MTL4CommitOptions new]; NSArray *bl = fb->blocks; + [o addFeedbackHandler:^(id f) { for (void (^b)(id) in bl) b(f); }]; + return o; +} +static id g_ts_heap; // tentative: defined with the segment timestamps below #include "nvn_rec.h" // deferred encoding (DM_NVN_ENC_THREAD) static NSHashTable *g_res_objects; +static char g_tex_range_key; // res_top: a GPU-made texture's storage (guest address, NVN size, pool flags) +static char g_tex_up_key; // mem_census: an uploaded texture's storage, as g_tex_range_key +static NSMapTable *g_res_line; // res_top: the source line that put each object in the set static _Atomic unsigned g_image_heap_n, g_big_n; // g_big_n: large pools in chunks, whose buffers overlap (BIG_MIN) static inline MTL4VisibilityOptions resource_vis(void) { return MTL4VisibilityOptionDevice | (g_image_heap_n || g_big_n ? MTL4VisibilityOptionResourceAlias : 0); } // Residency churn by call site (the power line every 300 frames, mtl_res_stats): each commit with changes is a kernel call whose cost grows with what was added or removed enum { RS_SITES = 16 }; static struct { int line; uint64_t n, bytes; } g_rs_site[RS_SITES]; static uint64_t g_rs_rm, g_rs_commits, g_rs_commit_ns; +// What is in the set now by the line that added it (adds less removals), and what it was at the last residency line: a load's leftovers show as a line whose bytes stay up after it. +// The phone's set grew 3.2 → 3.9 → 4.5 GB over two loads of Ocarina of Time and nothing said by which line +enum { RS_LIVE = 48 }; static struct { int line; int64_t n, bytes, last; } g_rs_live[RS_LIVE]; +// The bytes an object adds to the set: a texture made over a buffer (a linear texture over its pool's buffer, tex_linear) is that buffer's memory, which the set counts once (measured: +// an 8 MB buffer and 31 textures over it read 8 MB in allocatedSize), though each texture's allocatedSize gives the whole buffer. Counted per texture, Ocarina of Time's 31-64 linear +// targets over one 8 MB pool read 248-512 MB that the set does not hold (the iPhone 17's "line 4926: 64, 512 MB" back on the field) +static uint64_t res_bytes(id o) { return [(id)o conformsToProtocol:@protocol(MTLTexture)] && ((id)o).buffer ? 0 : o.allocatedSize; } +static void rs_live_add(int line, int64_t n, int64_t bytes) { // under g_res_mu + int k = 0; while (k < RS_LIVE - 1 && g_rs_live[k].line && g_rs_live[k].line != line) k++; + g_rs_live[k].line = line; g_rs_live[k].n += n; g_rs_live[k].bytes += bytes; +} #define res_add(r) res_add_at((r), __LINE__) +// File pages under a shared buffer that joins the set are wired through the CPU's fault path (mlock) before the commit, and given back after it, when the commit holds them for the GPU. +// The commit wires an added buffer's pages itself, and pages a file in from the GPU driver's wiring path (IOGPUResourceGroupUpdateResources → the VM → APFS pagein). With the guest's +// memory in files (DM_GUEST_FILE) on the M1 iPad, that page-in waited for good on an APFS lock held for writing by a launchd thread (its background I/O queue), which itself had stopped +// 4 ms after it and never ran again: the game froze with sound and no picture, the encode thread in res_commit, guest threads that touched the files stuck in their faults (a sysdiagnose +// spindump, 2026-11-08). Hundreds of thousands of ordinary page-ins of the same files never hung, so the pages are brought in and held that way first, and the commit finds them resident. +// What launchd's thread waited for is not known (the kernel had no symbols): memory.md, "The residency commit froze over the guest's files". Anonymous memory and Metal's own buffers are not +// file-backed and are left alone. Under g_res_mu +typedef struct { void *p; size_t n; } fwire_t; static fwire_t *g_fwire; static size_t g_nfwire, g_cfwire; static uint64_t g_fwire_n, g_fwire_bytes, g_fwire_ns, g_fwire_fail; +static int range_file_backed(const void *p, size_t n) { + vm_address_t a = (vm_address_t)p, e = a + n; natural_t depth = 0; // vm_region_recurse_64: mach_vm.h is not in the iOS SDK + while (a < e) { + vm_address_t r = a; vm_size_t sz = 0; vm_region_submap_info_data_64_t info; mach_msg_type_number_t c = VM_REGION_SUBMAP_INFO_COUNT_64; + if (vm_region_recurse_64(mach_task_self(), &r, &sz, &depth, (vm_region_recurse_info_t)&info, &c) || r >= e) return 0; + if (info.is_submap) { depth++; continue; } + if (info.external_pager) return 1; + a = r + sz; + } + return 0; +} +static void file_wire(id r) { + if (![(id)r conformsToProtocol:@protocol(MTLBuffer)]) return; + id b = (id)r; + if (b.storageMode != MTLStorageModeShared || !b.length) return; + uintptr_t pg = (uintptr_t)getpagesize(), lo = (uintptr_t)b.contents & ~(pg - 1), hi = ((uintptr_t)b.contents + b.length + pg - 1) & ~(pg - 1); + if (!range_file_backed((void *)lo, hi - lo)) return; + uint64_t t0 = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + if (mlock((void *)lo, hi - lo)) { // the commit pages them in itself, as before + if (!g_fwire_fail++) MLOG("[RED] residency: file pages under a buffer of %.1f MB could not be wired before the commit (mlock errno %d); the commit pages them in itself", (hi - lo) / 1048576.0, errno); + return; + } + g_fwire_ns += clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - t0; g_fwire_n++; g_fwire_bytes += hi - lo; + if (g_nfwire == g_cfwire) { // the list file_unwire undoes; a range it cannot hold is unwired at once (the commit pages it in itself, as before) + size_t n = g_cfwire ? 2 * g_cfwire : 64; void *grown = realloc(g_fwire, n * sizeof *g_fwire); + if (!grown) { munlock((void *)lo, hi - lo); return; } + g_fwire = grown; g_cfwire = n; + } + g_fwire[g_nfwire].p = (void *)lo; g_fwire[g_nfwire++].n = hi - lo; +} +static uint64_t g_fwire_peak, g_res_peak; // since the last residency line: the most file-backed bytes wired before one commit, the largest set after a commit +static _Atomic uint64_t g_ubs_live, g_ubs_peak; // bytes of the upload batches' buffers over guest memory (up_big_src) in the set now, and the most at once since the last residency line +static void file_unwire(fwire_t *fw, size_t n) { for (size_t i = 0; i < n; i++) munlock(fw[i].p, fw[i].n); free(fw); } // a range the game has mapped anew meanwhile fails, harmlessly // Both run on guest threads too (pool_res from mtl_addr, uploads), whose implicit autorelease pools never drain; containsObject: / removeObject: on a weak NSHashTable leave the object // autoreleased in the calling thread's pool (measured in a standalone test: the object outlived its last strong reference until the thread ended), so each has a pool of its own static void res_q_put(id r, int add) { // Caller holds g_res_mu @@ -298,9 +392,13 @@ static void res_add_at(id allocation, int line) { @autoreleasepoo pthread_mutex_lock(&g_res_mu); if (!g_res_objects) g_res_objects = [NSHashTable weakObjectsHashTable]; if ([g_res_objects containsObject:r]) { pthread_mutex_unlock(&g_res_mu); return; } // already resident (a shared texture resolved again): marking the set dirty would cost a commit that changes nothing - { int k = 0; while (k < RS_SITES - 1 && g_rs_site[k].line && g_rs_site[k].line != line) k++; g_rs_site[k].line = line; g_rs_site[k].n++; g_rs_site[k].bytes += r.allocatedSize; } + { int k = 0; while (k < RS_SITES - 1 && g_rs_site[k].line && g_rs_site[k].line != line) k++; g_rs_site[k].line = line; g_rs_site[k].n++; g_rs_site[k].bytes += res_bytes(r); } + file_wire(r); // before its change is queued: the commit that applies the change takes this range with it and gives it back after (res_commit) res_q_put(r, 1); [g_res_objects addObject:r]; + if (!g_res_line) g_res_line = [NSMapTable weakToStrongObjectsMapTable]; + [g_res_line setObject:@(line) forKey:r]; + rs_live_add(line, 1, (int64_t)res_bytes(r)); pthread_mutex_unlock(&g_res_mu); } } static void res_remove(id r) { @autoreleasepool { @@ -310,6 +408,7 @@ static void res_remove(id r) { @autoreleasepool { if (![g_res_objects containsObject:r]) { pthread_mutex_unlock(&g_res_mu); return; } res_q_put(r, 0); [g_res_objects removeObject:r]; + rs_live_add([[g_res_line objectForKey:r] intValue], -1, -(int64_t)res_bytes(r)); g_rs_rm++; pthread_mutex_unlock(&g_res_mu); } } @@ -352,9 +451,11 @@ @interface NvRecycledHeap : NSObject { @public id heap; } @end @implementation NvRecycledHeap - (void)dealloc { rh_wait(heap); } @end -@interface NvImageHeap : NSObject { @public id heap; } @end // a resolution family's heap (image_texture) +// A resolution family's heap (image_texture), or with window set a heap over a span of GPU-only memory (window_texture), whose textures sit at their own offsets: a span's +// heap goes with its last texture instead of waiting in the recycled list, where its 36 MB would serve only a texture at least two thirds as large +@interface NvImageHeap : NSObject { @public id heap; int window; } @end @implementation NvImageHeap -- (void)dealloc { rh_wait(heap); atomic_fetch_sub(&g_image_heap_n, 1); } +- (void)dealloc { if (window) res_remove(heap); else rh_wait(heap); atomic_fetch_sub(&g_image_heap_n, 1); } @end static char g_image_heap_owner_key, g_rh_owner_key; // A placement heap of at least `size` bytes: the smallest waiting one up to half as large again, or a new one an eighth larger (its exact size with the switch off). nil if Metal @@ -404,19 +505,80 @@ - (void)dealloc { rh_wait(heap); atomic_fetch_sub(&g_image_heap_n, 1); } || (t->d.flags & (NVN_TEXTURE_FLAGS_DISPLAY | NVN_TEXTURE_FLAGS_VIDEO_DECODE | NVN_TEXTURE_FLAGS_LINEAR | NVN_TEXTURE_FLAGS_SPARSE | NVN_TEXTURE_FLAGS_LINEAR_RENDER_TARGET))) return nil; return rh_place(d); } -// When a submission begins: heaps that waited RH_IDLE_NS, and the oldest past RH_CAP bytes, leave the residency set and are freed -static void rh_trim(void) { - if (!g_rh_n) return; - uint64_t now = clock_gettime_nsec_np(CLOCK_MONOTONIC); void *drop[64]; unsigned nd = 0; - os_unfair_lock_lock(&g_rh_lk); - while (g_rh_n && nd < 64) { - unsigned old = 0; for (unsigned i = 1; i < g_rh_n; i++) if (g_rh[i].t < g_rh[old].t) old = i; - if (now - g_rh[old].t < RH_IDLE_NS && g_rh_bytes <= RH_CAP) break; - drop[nd++] = g_rh[old].heap; g_rh_bytes -= g_rh[old].size; g_rh[old] = g_rh[--g_rh_n]; - } - os_unfair_lock_unlock(&g_rh_lk); - for (unsigned i = 0; i < nd; i++) { id h = CFBridgingRelease(drop[i]); res_remove(h); } - if (nd) atomic_fetch_add(&g_rh_trimmed, nd); +// When a submission begins: heaps that waited RH_IDLE_NS, and the oldest past RH_CAP bytes, leave the residency set and are freed; all of them when memory is short (mem_trim). → bytes freed +static uint64_t rh_trim_n(int all, unsigned *n_out) { + if (!g_rh_n) return 0; + uint64_t now = clock_gettime_nsec_np(CLOCK_MONOTONIC), bytes = 0; unsigned n = 0; + for (;;) { + void *drop[64]; unsigned nd = 0; + os_unfair_lock_lock(&g_rh_lk); + while (g_rh_n && nd < 64) { + unsigned old = 0; for (unsigned i = 1; i < g_rh_n; i++) if (g_rh[i].t < g_rh[old].t) old = i; + if (!all && now - g_rh[old].t < RH_IDLE_NS && g_rh_bytes <= RH_CAP) break; + drop[nd++] = g_rh[old].heap; bytes += g_rh[old].size; g_rh_bytes -= g_rh[old].size; g_rh[old] = g_rh[--g_rh_n]; + } + int more = all && g_rh_n; + os_unfair_lock_unlock(&g_rh_lk); + for (unsigned i = 0; i < nd; i++) { id h = CFBridgingRelease(drop[i]); res_remove(h); } + n += nd; + if (!more || !nd) break; + } + if (n) atomic_fetch_add(&g_rh_trimmed, n); + if (n_out) *n_out = n; + return bytes; +} +static void rh_trim(void) { rh_trim_n(0, NULL); } +// The whole system's memory (host_statistics64), in MB: what the per-app headroom misses. An iPhone 17 ended the app for proc-thrashing in Ocarina of Time with 67 MB free and 5.56 GB of its +// 8 GB wired while os_proc_available_memory still read 2.7 GB (memory.md, "The system ran out of memory while the app's headroom still read 2.7 GB"). file: file-backed pages in memory +// (the guest's files among them, DM_GUEST_FILE), which the kernel reads back in after it takes them +typedef struct { uint64_t total, free, wired, compressed, file, purgeable; int ok; } sys_mem_t; +static sys_mem_t sys_mem(void) { + sys_mem_t m = {0}; vm_statistics64_data_t v; mach_msg_type_number_t n = HOST_VM_INFO64_COUNT; uint64_t total = 0; size_t tl = sizeof total; + if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&v, &n) != KERN_SUCCESS) return m; + sysctlbyname("hw.memsize", &total, &tl, NULL, 0); + uint64_t pg = vm_kernel_page_size; + m.total = total >> 20; m.free = ((uint64_t)v.free_count + v.speculative_count) * pg >> 20; m.wired = (uint64_t)v.wire_count * pg >> 20; + m.compressed = (uint64_t)v.compressor_page_count * pg >> 20; m.file = (uint64_t)v.external_page_count * pg >> 20; m.purgeable = (uint64_t)v.purgeable_count * pg >> 20; m.ok = 1; + return m; +} +// Memory pressure (DISPATCH_SOURCE_TYPE_MEMORYPRESSURE): the system says when its free memory runs low, warn then critical, before it ends processes. Each event is logged with the +// system's figures, and asks the submit thread for a trim at the next submission's start (mem_trim, after the upload code): what no frame needs any more goes, and nothing waits on the +// GPU there. On iOS warn and critical trim, on the Mac critical only (it can swap). DM_NVN_MEM_PRESSURE=0 logs only, 1 trims at warn, 2 at critical +static _Atomic int g_mp_want; // the level a trim was asked at (1 warn, 2 critical), taken by mem_trim +static _Atomic uint64_t g_mp_n[3], g_mp_trims, g_mp_freed; // events by level (0 back to normal), trims made, bytes they gave back +static int mp_act_level(void) { + static int lv = -1; + if (lv < 0) { const char *e = getenv("DM_NVN_MEM_PRESSURE"); lv = e && *e ? atoi(e) : (TARGET_OS_IPHONE ? 1 : 2); if (lv < 0 || lv > 2) lv = 2; } + return lv; +} +static void mem_pressure_said(char *b, size_t n) { + snprintf(b, n, "memory pressure events warn %llu, critical %llu, back to normal %llu; trims %llu, %llu MB given back", (unsigned long long)atomic_load(&g_mp_n[1]), (unsigned long long)atomic_load(&g_mp_n[2]), + (unsigned long long)atomic_load(&g_mp_n[0]), (unsigned long long)atomic_load(&g_mp_trims), (unsigned long long)(atomic_load(&g_mp_freed) >> 20)); +} +static void res_report(const char *why, int kind); +static void mem_pressure_event(int lv) { // lv: 0 normal, 1 warn, 2 critical (the source's handler; a test calls it directly) + atomic_fetch_add(&g_mp_n[lv], 1); + sys_mem_t m = sys_mem(); char room[32] = "none"; +#if TARGET_OS_IPHONE + snprintf(room, sizeof room, "%llu MB", (unsigned long long)(os_proc_available_memory() >> 20)); +#endif + int act = lv && mp_act_level() && lv >= mp_act_level(); + MLOG("[mem] memory pressure %s: system free %llu MB, wired %llu MB, compressed %llu MB, file-backed %llu MB; residency set %llu MB; headroom %s; %s", lv == 2 ? "critical" : lv ? "warn" : "back to normal", + (unsigned long long)m.free, (unsigned long long)m.wired, (unsigned long long)m.compressed, (unsigned long long)m.file, (unsigned long long)(g_res ? g_res.allocatedSize >> 20 : 0), room, + act ? "trimming at the next submission" : lv ? "no trim at this level here" : ""); + if (act) { int cur = atomic_load(&g_mp_want); while (lv > cur && !atomic_compare_exchange_weak(&g_mp_want, &cur, lv)) {} } + if (lv) res_report(lv == 2 ? "[mem] memory pressure critical" : "[mem] memory pressure warn", lv); +} +static void mem_pressure_start(void) { + static dispatch_source_t src; + src = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYPRESSURE, 0, DISPATCH_MEMORYPRESSURE_NORMAL | DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_CRITICAL, + dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)); + if (!src) { MLOG("[RED] memory pressure: no dispatch source; memory is not trimmed on pressure"); return; } + dispatch_source_set_event_handler(src, ^{ @autoreleasepool { + unsigned long d = dispatch_source_get_data(src); + mem_pressure_event(d & DISPATCH_MEMORYPRESSURE_CRITICAL ? 2 : d & DISPATCH_MEMORYPRESSURE_WARN ? 1 : 0); + } }); + dispatch_resume(src); } // The R32 storage under a 32-bit colour texture that takes image atomics (tex_upgrade): resident as long as the colour view over it lives, which is what the game's names hold @interface NvAtomicRaw : NSObject { @public id raw; } @end @@ -448,31 +610,41 @@ static void res_check(id r, const char *what, int reg) { MLOG("[RED] missing residency #%d: %s slot %d %s %p (parent chain %d deep) allocated %lu B storage mode %lu%s", nbad, what, reg, is_tex ? "texture" : "buffer", (__bridge void *)a, hops, (unsigned long)a.allocatedSize, (unsigned long)a.storageMode, t ? [NSString stringWithFormat:@" format %lu %lux%lu type %lu usage %#lx", (unsigned long)t.pixelFormat, (unsigned long)t.width, (unsigned long)t.height, (unsigned long)t.textureType, (unsigned long)t.usage].UTF8String : ""); } } +static void res_report(const char *why, int kind); // Applies and commits every change made before the call. A change another thread's commit took is in the set when this returns too: that commit holds g_res_commit_mu until it is // done. Each change holds its allocation until it is committed, so a removed one stays alive until it has left the set static void res_commit(void) { @autoreleasepool { + uint64_t z = 0; pthread_mutex_lock(&g_res_commit_mu); pthread_mutex_lock(&g_res_mu); res_op *q = g_res_q; size_t n = g_res_qn; g_res_q = NULL; g_res_qn = g_res_qcap = 0; + fwire_t *fw = g_fwire; size_t nfw = g_nfwire; g_fwire = NULL; g_nfwire = g_cfwire = 0; // the file pages wired for exactly these changes + { uint64_t b = 0; for (size_t i = 0; i < nfw; i++) b += fw[i].n; if (b > g_fwire_peak) g_fwire_peak = b; } pthread_mutex_unlock(&g_res_mu); if (n) { uint64_t t0 = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); for (size_t i = 0; i < n; i++) { if (q[i].add) [g_res addAllocation:(__bridge id)q[i].o]; else [g_res removeAllocation:(__bridge id)q[i].o]; } [g_res commit]; - uint64_t dt = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - t0; - pthread_mutex_lock(&g_res_mu); g_rs_commits++; g_rs_commit_ns += dt; pthread_mutex_unlock(&g_res_mu); + uint64_t dt = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - t0; z = g_res.allocatedSize; // the set after the commit, read under g_res_commit_mu + pthread_mutex_lock(&g_res_mu); g_rs_commits++; g_rs_commit_ns += dt; if (z > g_res_peak) g_res_peak = z; pthread_mutex_unlock(&g_res_mu); } + file_unwire(fw, nfw); // after the commit that made those buffers resident; under g_res_commit_mu, so a later commit cannot run before them pthread_mutex_unlock(&g_res_commit_mu); for (size_t i = 0; i < n; i++) CFRelease(q[i].o); free(q); + // What the set is made of, once, when it first passes three quarters of Metal's working set: a device that later fails with GPU out-of-memory has said it before (the M1 iPad's + // 5,461 MB is passed going outside in Ocarina of Time), and one that does not still tells what to cut. Checked after each commit: read only at the 300-frame line, the iPhone 17's + // set passed 4.4 GB of its 4,096 MB line between two lines and was back under it at each + static _Atomic int told; if (z && g_dev && z > g_dev.recommendedMaxWorkingSetSize / 4 * 3 && !atomic_exchange(&told, 1)) res_report("[mem] the residency set passed three quarters of Metal's working set", 0); } } static int res_pending(void) { pthread_mutex_lock(&g_res_mu); int n = g_res_qn != 0; pthread_mutex_unlock(&g_res_mu); return n; } // What the residency set holds: totals by kind and the largest objects. At the first GPU out-of-memory error (the error names none of them), and for DM_CTL "restop" (hle_hid.c). The set holds // the game's pools (shared buffers over guest memory), textures, heaps and staging alike +static void res_top_pools(const char *why); static void res_top(const char *why) { @autoreleasepool { enum { N = 24 }; id top[N] = {nil}; uint64_t total = 0, n = 0, kind[4] = {0}, count[4] = {0}; pthread_mutex_lock(&g_res_mu); - for (id o in g_res_objects.allObjects) { uint64_t z = o.allocatedSize; total += z; n++; + for (id o in g_res_objects.allObjects) { uint64_t z = res_bytes(o); total += z; n++; int k = [(id)o conformsToProtocol:@protocol(MTLTexture)] ? 0 : [(id)o conformsToProtocol:@protocol(MTLHeap)] ? 1 : ((id)o).storageMode == MTLStorageModeShared ? 2 : 3; kind[k] += z; count[k]++; for (int q = 0; q < N; q++) if (!top[q] || z > top[q].allocatedSize) { for (int j = N - 1; j > q; j--) top[j] = top[j - 1]; top[q] = o; break; } } @@ -480,6 +652,18 @@ static void res_top(const char *why) { @autoreleasepool { MLOG("%s: the residency set holds %llu objects, %llu MB (Metal's recommended working set %llu MB, GPU allocated %llu MB): textures %llu, %llu MB; heaps %llu, %llu MB; shared buffers %llu, %llu MB; private buffers %llu, %llu MB; the largest:", why, (unsigned long long)n, (unsigned long long)(total >> 20), (unsigned long long)(g_dev.recommendedMaxWorkingSetSize >> 20), (unsigned long long)(g_dev.currentAllocatedSize >> 20), (unsigned long long)count[0], (unsigned long long)(kind[0] >> 20), (unsigned long long)count[1], (unsigned long long)(kind[1] >> 20), (unsigned long long)count[2], (unsigned long long)(kind[2] >> 20), (unsigned long long)count[3], (unsigned long long)(kind[3] >> 20)); + { // by the source line that added each (res_add), textures and buffers apart + enum { NL = 24 }; struct { int line, tex; uint64_t n, b; } bl[NL]; int nl = 0; + pthread_mutex_lock(&g_res_mu); + for (id o in g_res_objects.allObjects) { int line = [[g_res_line objectForKey:o] intValue], tx = [(id)o conformsToProtocol:@protocol(MTLTexture)]; + int i = 0; while (i < nl && (bl[i].line != line || bl[i].tex != tx)) i++; if (i == nl && nl < NL) { bl[nl].line = line; bl[nl].tex = tx; bl[nl].n = bl[nl].b = 0; nl++; } + if (i < NL) { bl[i].n++; bl[i].b += res_bytes(o); } } + pthread_mutex_unlock(&g_res_mu); + char line[1400] = ""; size_t lo = 0; + for (int i = 0; i < nl && lo < sizeof line; i++) lo += snprintf(line + lo, sizeof line - lo, "%sline %d %s %llu, %llu MB", i ? "; " : "", bl[i].line, bl[i].tex ? "textures" : "other", (unsigned long long)bl[i].n, (unsigned long long)(bl[i].b >> 20)); + MLOG("%s: residency by the line that added it: %s", why, line); + } + res_top_pools(why); for (int k = 0; k < N && top[k]; k++) { id o = top[k]; if ([o conformsToProtocol:@protocol(MTLTexture)]) { id t = o; MLOG(" texture %lux%lux%lu format %lu levels %lu%s: %llu MB", (unsigned long)t.width, (unsigned long)t.height, (unsigned long)MAX(t.depth, t.arrayLength), (unsigned long)t.pixelFormat, (unsigned long)t.mipmapLevelCount, t.isSparse ? " (sparse)" : "", (unsigned long long)(t.allocatedSize >> 20)); } else if ([o conformsToProtocol:@protocol(MTLHeap)]) MLOG(" heap: %llu MB", (unsigned long long)(((id)o).size >> 20)); @@ -487,6 +671,7 @@ static void res_top(const char *why) { @autoreleasepool { } } void mem_census(const char *why); void dm_gfx_restop(void) { res_top("DM_CTL restop"); mem_census("DM_CTL restop"); } +void dm_gfx_memtrim(void) { int cur = atomic_load(&g_mp_want); while (cur < 1 && !atomic_compare_exchange_weak(&g_mp_want, &cur, 1)) {} MLOG("DM_CTL memtrim: a memory pressure trim at the next submission's start"); } // Going on helps nobody once command buffers keep failing: no frame reaches the window, and each attempt asks the driver to wire more. A host left running like that on a 16 GB Mac took the whole // system down, hung for hours and then a kernel panic in IOGPUGroupMemory at 14.7 GB wired. So 32 failures within a minute end the game static void res_top_once(NSError *err) { @@ -508,9 +693,31 @@ void mtl_res_stats(char *out, size_t n) { for (int i = 0; i < 4 && o < n; i++) { int best = -1; for (int k = 0; k < RS_SITES; k++) if (g_rs_site[k].n && (best < 0 || g_rs_site[k].bytes > g_rs_site[best].bytes)) best = k; if (best < 0) break; o += snprintf(out + o, n - o, "%sline %d: %llu, %.0f MB", i ? ", " : "", g_rs_site[best].line, (unsigned long long)g_rs_site[best].n, g_rs_site[best].bytes / 1048576.0); g_rs_site[best].n = 0; } if (o < n) snprintf(out + o, n - o, "), removed %llu, %lu allocations in the set (%.0f MB)", (unsigned long long)g_rs_rm, set_n, set_mb); + { o = strlen(out); if (o < n) snprintf(out + o, n - o, ", at most %.0f MB after a commit", g_res_peak / 1048576.0); } + if (g_fwire_n + g_fwire_fail) { o = strlen(out); if (o < n) snprintf(out + o, n - o, ", file-backed buffers wired before their commit %llu, %.0f MB, %.1f ms, at most %.0f MB before one commit (refused %llu)", (unsigned long long)g_fwire_n, g_fwire_bytes / 1048576.0, g_fwire_ns / 1e6, g_fwire_peak / 1048576.0, (unsigned long long)g_fwire_fail); } + { uint64_t pk = atomic_exchange(&g_ubs_peak, atomic_load(&g_ubs_live)); if (pk) { o = strlen(out); if (o < n) snprintf(out + o, n - o, ", upload reads over guest memory at most %.0f MB at once", pk / 1048576.0); } } + g_fwire_n = g_fwire_bytes = g_fwire_ns = g_fwire_peak = 0; g_res_peak = (uint64_t)(set_mb * 1048576.0); // set_mb: the set's size main reads under g_res_commit_mu memset(g_rs_site, 0, sizeof g_rs_site); g_rs_rm = g_rs_commits = g_rs_commit_ns = 0; + { // in the set now by the line that added it, the largest first, with the change since the last residency line + int ord[RS_LIVE], no = 0; for (int k = 0; k < RS_LIVE; k++) if (g_rs_live[k].line && (g_rs_live[k].bytes || g_rs_live[k].last)) ord[no++] = k; + for (int i = 0; i < no; i++) for (int j = i + 1; j < no; j++) if (g_rs_live[ord[j]].bytes > g_rs_live[ord[i]].bytes) { int x = ord[i]; ord[i] = ord[j]; ord[j] = x; } + o = strlen(out); if (o < n) o += snprintf(out + o, n - o, ", in the set by line (change since the last line):"); + for (int i = 0; i < no && i < 8 && o < n; i++) { int k = ord[i]; + o += snprintf(out + o, n - o, "%s line %d %lld, %.0f MB (%+.0f)", i ? "," : "", g_rs_live[k].line, (long long)g_rs_live[k].n, g_rs_live[k].bytes / 1048576.0, (g_rs_live[k].bytes - g_rs_live[k].last) / 1048576.0); } + for (int k = 0; k < RS_LIVE; k++) g_rs_live[k].last = g_rs_live[k].bytes; + } pthread_mutex_unlock(&g_res_mu); } +// res_top and mem_census off the caller's thread: res_commit runs with g_mu held on some paths, and the census takes it. kind 0 once (the three-quarters line), 1 / 2 a memory pressure warn / +// critical, each at most once a minute. A device that is ended for its wired memory (proc-thrashing, the iPhone 17) never fails a command buffer, so these are what its log says of the set +static void res_report(const char *why, int kind) { + static _Atomic uint64_t last[3]; + uint64_t now = clock_gettime_nsec_np(CLOCK_MONOTONIC), was = atomic_load(&last[kind]); + if (kind && was && now - was < 60000000000ull) return; + if (!atomic_compare_exchange_strong(&last[kind], &was, now)) return; + char *w = strdup(why); + dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ @autoreleasepool { res_top(w); mem_census(w); free(w); } }); +} @interface NvDeferredRelease : NSObject { @public id object; uint64_t fence; int keep_resident; } @end @implementation NvDeferredRelease @end @@ -630,7 +837,7 @@ static void want_note(want_list *w, const char *key) { void bf_want_note(const char *key) { want_note(&g_bf_want, key); } // ---------- Memory pools ---------- -typedef struct { uintptr_t lo, hi; uintptr_t base; __unsafe_unretained id buf; uint64_t gpu; const void *key; int res; uint64_t born; uintptr_t end; uint64_t unk; uint32_t n_tex_reads, n_other; } pool_ent; // res: already in the residency set (on demand, see pool_res); born: when it was added (ns); end, unk: a large pool's chunk (see BIG_MIN); n_tex_reads / n_other: lookups by texture uploads / by anything else (mem_census) +typedef struct { uintptr_t lo, hi; uintptr_t base; __unsafe_unretained id buf; uint64_t gpu; const void *key; int res; uint64_t born; uintptr_t end; uint64_t unk; uint32_t n_tex_reads, n_other; uint32_t tag; } pool_ent; // res: already in the residency set (on demand, see pool_res); born: when it was added (ns); end, unk: a large pool's chunk (see BIG_MIN); n_tex_reads / n_other: lookups by texture uploads / by anything else (mem_census) static pool_ent *g_pools; static int g_npool, g_cap; static int g_pidx_ok, g_plast = -1; // whether the address→pool index is valid, the last hit (pool_find) static NSMutableArray *g_keep; // Holds the buffer references (pool_ent has non-owning pointers) @@ -676,6 +883,8 @@ static void udc_selftest(void) { MLOG("UDC self-check %s %s %lux%lu first value %08x, values differing from it %lu / %lu", g_dev.name.UTF8String, depth ? "Depth32F_S8" : "RGBA8", (unsigned long)w, (unsigned long)h, px[0], (unsigned long)bad, (unsigned long)(w * h)); } } +#include "nvn_res_probe.inc" // DM_RES_PROBE=1: what an access through a pointer to a buffer outside the residency set gets, on this device (mtl_init) +static void res_probe_say(const char *s) { MLOG("[res-probe] %s", s); } void mtl_init(void) { if (g_dev) return; const char *vbc = getenv("DM_NVN_VBUF_CACHE"); g_vbuf_cache = !(vbc && !strcmp(vbc, "0")); @@ -687,6 +896,7 @@ void mtl_init(void) { g_dev = MTLCreateSystemDefaultDevice(); if (!g_dev) MDIE("no Metal device"); if (!g_dev.hasUnifiedMemory) MDIE("needs a unified-memory device (zero-copy memory pools)"); + mem_pressure_start(); g_q = [g_dev newCommandQueue]; // A device without Metal 4 (the paravirtualized GPU of a virtual Mac, such as GitHub's macos-26 runner: no residency set, no MTL4CommandQueue) cannot run the NVN layer. The GL and // Vulkan layers draw on classic queues of their own and need only the device (mtl_device_classic): there the classic part starts and presents are dropped, which is all a @@ -721,6 +931,7 @@ void mtl_init(void) { if (!g_dev.supportsBCTextureCompression) MDIE("the Metal device %s has no BC texture formats, which the games' textures use and the host does not decompress: an iPhone needs an A17 Pro or later, an iPad an M1 or later", g_dev.name.UTF8String); [g_q addResidencySet:g_res]; [g_q4 addResidencySet:g_res]; + if (getenv("DM_RES_PROBE") && atoi(getenv("DM_RES_PROBE")) > 0) res_probe(g_dev, 2, res_probe_say); // diagnostic, before the game: its own queue and residency set { void crash_set_wait_dump(void (*fn)(void)); void mtl_wait_state_dump(void); crash_set_wait_dump(mtl_wait_state_dump); } g_alloc_n = 3; for (int i = 0; i < 3; i++) { @@ -850,6 +1061,32 @@ void mtl_pool_addressed(const void *mem, uint64_t size) { } pthread_mutex_unlock(&g_mu); } +// Diagnostic (res_top): the addressed ranges again, by who gave the address out: 0 a pool's address (nvnMemoryPoolGetBufferAddress), 1 a buffer (its own range, though the +// table above takes its whole pool), 2 a texture (nvnTextureGetTextureAddress), 3 a virtual pool's mapping. Under g_mu +typedef struct { struct { uintptr_t lo, hi; } *r; int n, cap; } rng_tab; +static rng_tab g_addrk[4]; +static void rng_put(rng_tab *t, uintptr_t lo, uintptr_t hi) { + int a = 0, b = t->n; while (a < b) { int m = (a + b) / 2; if (t->r[m].hi < lo) a = m + 1; else b = m; } + int j = a; while (j < t->n && t->r[j].lo <= hi) { lo = MIN(lo, t->r[j].lo); hi = MAX(hi, t->r[j].hi); j++; } + if (j == a && t->n == t->cap) { t->cap = t->cap ? t->cap * 2 : 256; t->r = realloc_or_die(t->r, (size_t)t->cap * sizeof *t->r, "the addressed range table by kind"); } + if (j != a + 1) memmove(t->r + a + 1, t->r + j, (size_t)(t->n - j) * sizeof *t->r); + t->n += 1 - (j - a); t->r[a].lo = lo; t->r[a].hi = hi; +} +static uint64_t rng_overlap(const rng_tab *t, uintptr_t lo, uintptr_t hi) { + int a = 0, b = t->n; while (a < b) { int m = (a + b) / 2; if (t->r[m].hi <= lo) a = m + 1; else b = m; } + uint64_t z = 0; for (int i = a; i < t->n && t->r[i].lo < hi; i++) z += MIN(hi, t->r[i].hi) - MAX(lo, t->r[i].lo); + return z; +} +static rng_tab g_addr_code; // shader-code pools whose own address was asked for (kind 4, hle_nvn.c nvnMemoryPoolGetBufferAddress), kept out of the table. Under g_mu +void mtl_pool_addressed_by(const void *mem, uint64_t size, int kind) { + if (kind == 4) { + pthread_mutex_lock(&g_mu); int first = !g_addr_code.n; rng_put(&g_addr_code, (uintptr_t)mem, (uintptr_t)mem + size); pthread_mutex_unlock(&g_mu); + if (first) MLOG("raw global memory: shader-code pools whose address the game asks for stay out of the pool table, so nothing makes them resident for its sake (first %p, %llu KB)", mem, (unsigned long long)(size >> 10)); + return; + } + if (kind != 1) mtl_pool_addressed(mem, size); + pthread_mutex_lock(&g_mu); if (kind >= 0 && kind < 4) rng_put(&g_addrk[kind], (uintptr_t)mem, (uintptr_t)mem + size); pthread_mutex_unlock(&g_mu); +} // On-demand residency of memory pools: putting a zero-copy buffer into the residency set makes iOS read the whole pool into memory and pin it as wired, even a pool the game never uses // (they measured on a 17 Pro Max a 512 MB render-target pool addressed 0 times in a run, with about 530 MB more device wired memory; a 4 GB A14 was ended by the system within seconds of launch because of it). // So a pool is not put into the residency set when created; it is put in, and the residency set committed on the spot, the first time the GPU gets its address through mtl_addr / mtl_gpu_addr -- these are the only two ways the GPU gets pool addresses, @@ -865,10 +1102,66 @@ static void pool_res(int i) { // pools' buffers do at shared pages; GPU addresses are not contiguous across them, so a lookup must say how far it reads. One that does not know (length 1: an indirect draw's index buffer, a raw storage // address) gets BIG_UNKNOWN past its address. Raw global memory, whose pool table the shader walks by itself, takes the whole pool: big_full enum { BIG_MIN = 512u << 20, BIG_S = 16u << 20, BIG_UNKNOWN = 64u << 20, BIG_MAX = 32 }; -typedef struct { uintptr_t lo, hi, a, b; const void *mem; int *chunk, full; NSMutableArray *old; } big_pool; // chunk: stride → g_pools index + 1; full: the whole pool's entry + 1; old: buffers a longer chunk replaced, alive with the pool +typedef struct { uintptr_t lo, hi, a, b; const void *mem; int *chunk, full; NSMutableArray *old; uint32_t tag; } big_pool; // chunk: stride → g_pools index + 1; full: the whole pool's entry + 1; old: buffers a longer chunk replaced, alive with the pool static big_pool g_big[BIG_MAX]; static int g_nbig; static id pool_buf(uintptr_t a, uintptr_t b); // a pool's zero-copy buffer over [a, b), made over writable pages (below) static int big_of(uint64_t addr) { for (int i = 0; i < g_nbig; i++) if (addr >= g_big[i].lo && addr < g_big[i].hi) return i; return -1; } +// Diagnostic (res_top): the pool's flags, or a virtual pool's for one of its mapped runs (bit 31) +void mtl_pool_tag(const void *mem, uint32_t tag) { + pthread_mutex_lock(&g_mu); + for (int i = 0; i < g_npool; i++) if (g_pools[i].key == mem) g_pools[i].tag = tag; + for (int k = 0; k < g_nbig; k++) if (g_big[k].mem == mem) g_big[k].tag = tag; + pthread_mutex_unlock(&g_mu); +} +static _Atomic uint64_t g_win_n, g_win_bytes, g_win_fit[4], g_win_fit_b[4]; // textures placed / bytes; not placed by reason (0 no size, 1 Metal larger than its scaled NVN range, 2 past the window, 3 heap refused) +static void res_top_pools(const char *why) { + { // the memory pools in it: in the raw pool table or not, looked up by anything but texture uploads or not, by who gave an address in them, by pool flags + uint64_t cn[4] = {0}, cb[4] = {0}, mn[16] = {0}, mb[16] = {0}, mcov[16][4] = {{0}}, vn = 0, vb = 0, rn = 0, rb = 0; struct { uint32_t tag; uint64_t n, b, ln, lb; } tg[12]; int ntg = 0; + pthread_mutex_lock(&g_mu); + for (int i = 0; i < g_npool; i++) { pool_ent *p = &g_pools[i]; if (!p->res) continue; + uint64_t z = p->hi - p->lo; int raw = addr_meets(p->lo, p->hi), c = raw << 1 | (p->n_other != 0); cn[c]++; cb[c] += z; rn++; rb += z; + int m = 0; uint64_t cov[4]; for (int k = 0; k < 4; k++) { cov[k] = rng_overlap(&g_addrk[k], p->lo, p->hi); if (cov[k]) m |= 1 << k; } + mn[m]++; mb[m] += z; for (int k = 0; k < 4; k++) mcov[m][k] += cov[k]; + if (p->tag >> 31) { vn++; vb += z; } + int j = 0; while (j < ntg && tg[j].tag != p->tag) j++; if (j == ntg && ntg < 12) { tg[ntg].tag = p->tag; tg[ntg].n = tg[ntg].b = tg[ntg].ln = tg[ntg].lb = 0; ntg++; } if (j < 12) { tg[j].n++; tg[j].b += z; if (p->n_other) { tg[j].ln++; tg[j].lb += z; } } } + uint64_t ak[4] = {0}; for (int k = 0; k < 4; k++) for (int i = 0; i < g_addrk[k].n; i++) ak[k] += g_addrk[k].r[i].hi - g_addrk[k].r[i].lo; + uint64_t code_n = 0, code_b = 0; for (int i = 0; i < g_addr_code.n; i++) if (!addr_meets(g_addr_code.r[i].lo, g_addr_code.r[i].hi)) { code_n++; code_b += g_addr_code.r[i].hi - g_addr_code.r[i].lo; } + pthread_mutex_unlock(&g_mu); + MLOG("%s: resident memory pools %llu, %llu MB: in the raw pool table and looked up otherwise %llu, %llu MB; in the table only %llu, %llu MB; not in it, looked up %llu, %llu MB; neither %llu, %llu MB; mapped runs of virtual pools %llu, %llu MB; addressed in all (MB): pools %llu, buffers %llu, textures %llu, virtual mappings %llu; shader-code ranges kept out of the table %llu, %llu MB", why, + (unsigned long long)rn, (unsigned long long)(rb >> 20), (unsigned long long)cn[3], (unsigned long long)(cb[3] >> 20), (unsigned long long)cn[2], (unsigned long long)(cb[2] >> 20), (unsigned long long)cn[1], (unsigned long long)(cb[1] >> 20), (unsigned long long)cn[0], (unsigned long long)(cb[0] >> 20), + (unsigned long long)vn, (unsigned long long)(vb >> 20), (unsigned long long)(ak[0] >> 20), (unsigned long long)(ak[1] >> 20), (unsigned long long)(ak[2] >> 20), (unsigned long long)(ak[3] >> 20), + (unsigned long long)code_n, (unsigned long long)(code_b >> 20)); + char line[1400] = ""; size_t lo = 0; + for (int m = 0; m < 16 && lo < sizeof line; m++) if (mn[m]) lo += snprintf(line + lo, sizeof line - lo, "%s[%s%s%s%s] %llu, %llu MB (buffers' ranges %llu MB, textures' %llu MB)", lo ? "; " : "", m & 1 ? "P" : "", m & 2 ? "B" : "", m & 4 ? "T" : "", m & 8 ? "V" : "", (unsigned long long)mn[m], (unsigned long long)(mb[m] >> 20), (unsigned long long)(mcov[m][1] >> 20), (unsigned long long)(mcov[m][2] >> 20)); + MLOG("%s: resident memory pools by who gave an address in them (P pool, B buffer, T texture, V virtual mapping): %s", why, line); + { // GPU-made textures in the set: by the memory pool holding their storage, NVN bytes summed against the union of their storage (what aliasing as on NVN would keep) + enum { NQ = 48 }; struct { const void *key; uint32_t flags; uint64_t n, metal, nvn, uni, psize; NSMutableArray *r; } q[NQ]; int nq = 0; + NSArray *objs; pthread_mutex_lock(&g_res_mu); objs = g_res_objects.allObjects; pthread_mutex_unlock(&g_res_mu); + pthread_mutex_lock(&g_mu); + for (id o in objs) { if (![o conformsToProtocol:@protocol(MTLTexture)]) continue; NSArray *rg = objc_getAssociatedObject(o, &g_tex_range_key); if (!rg) continue; + uint64_t a = [rg[0] unsignedLongLongValue], z = [rg[1] unsignedLongLongValue]; uint32_t fl = [rg[2] unsignedIntValue]; + const void *key = NULL; uint64_t ps = 0; int b = big_of(a); + if (b >= 0) { key = g_big[b].mem; ps = g_big[b].hi - g_big[b].lo; } else for (int i = 0; i < g_npool; i++) if (a >= g_pools[i].lo && a < g_pools[i].hi) { key = g_pools[i].key; ps = g_pools[i].hi - g_pools[i].lo; break; } + int j = 0; while (j < nq && (q[j].key != key || q[j].flags != fl)) j++; + if (j == nq && nq < NQ) { q[nq].key = key; q[nq].flags = fl; q[nq].n = q[nq].metal = q[nq].nvn = q[nq].uni = 0; q[nq].psize = ps; q[nq].r = [NSMutableArray array]; nq++; } + if (j < NQ) { q[j].n++; q[j].metal += ((id)o).allocatedSize; q[j].nvn += z; [q[j].r addObject:@[@(a), @(a + z)]]; } } + pthread_mutex_unlock(&g_mu); + for (int a = 0; a < nq; a++) for (int b = a + 1; b < nq; b++) if (q[b].metal > q[a].metal) { __typeof__(q[0]) x = q[a]; q[a] = q[b]; q[b] = x; } + lo = 0; + for (int j = 0; j < nq && j < 12 && lo < sizeof line; j++) { + [q[j].r sortUsingComparator:^NSComparisonResult(NSArray *x, NSArray *y) { return [x[0] compare:y[0]]; }]; + uint64_t end = 0; for (NSArray *r in q[j].r) { uint64_t a = [r[0] unsignedLongLongValue], e = [r[1] unsignedLongLongValue]; if (e <= end) continue; q[j].uni += e - MAX(a, end); end = e; } + lo += snprintf(line + lo, sizeof line - lo, "%spool %p (%llu MB) texture pool flags %#x: %llu textures, Metal %llu MB, NVN %llu MB, union %llu MB", j ? "; " : "", q[j].key, (unsigned long long)(q[j].psize >> 20), q[j].flags, + (unsigned long long)q[j].n, (unsigned long long)(q[j].metal >> 20), (unsigned long long)(q[j].nvn >> 20), (unsigned long long)(q[j].uni >> 20)); } + MLOG("%s: GPU-made textures in the set by the pool that holds their storage: %s", why, line); + MLOG("%s: GPU-only memory windows (window_texture): %llu textures placed, %llu MB; kept apart: no size %llu (%llu MB), Metal larger than 9/8 of NVN %llu (%llu MB), past the window %llu (%llu MB), heap refused %llu", why, + (unsigned long long)g_win_n, (unsigned long long)(g_win_bytes >> 20), (unsigned long long)g_win_fit[0], (unsigned long long)(g_win_fit_b[0] >> 20), (unsigned long long)g_win_fit[1], (unsigned long long)(g_win_fit_b[1] >> 20), + (unsigned long long)g_win_fit[2], (unsigned long long)(g_win_fit_b[2] >> 20), (unsigned long long)g_win_fit[3]); + } + lo = 0; for (int j = 0; j < ntg && lo < sizeof line; j++) lo += snprintf(line + lo, sizeof line - lo, "%s%#x: %llu, %llu MB (looked up otherwise %llu, %llu MB)", j ? "; " : "", tg[j].tag, (unsigned long long)tg[j].n, (unsigned long long)(tg[j].b >> 20), (unsigned long long)tg[j].ln, (unsigned long long)(tg[j].lb >> 20)); + MLOG("%s: resident memory pools by flags (bit 31: a virtual pool's mapped run): %s", why, line); + } +} // A pool to put into the table: its zero-copy buffer is made first, outside g_mu (pool_new_prep; it may retry for seconds), and the entry goes in under g_mu (pool_new_put), so a change // of several pools can be one step for every lookup (mtl_pool_replace) typedef struct { const void *mem; uint64_t size; uintptr_t lo, hi, a, b; __strong id buf; } pool_new; // buf nil: in chunks (a large pool) @@ -997,7 +1290,7 @@ static int big_new(big_pool *b, uintptr_t lo, uintptr_t hi, uintptr_t end, uint6 if (!buf) { MLOG("[RED] memory pool %p: the zero-copy buffer over %#lx..%#lx was refused", b->mem, (unsigned long)lo, (unsigned long)end); return -1; } if (g_npool == g_cap) { g_cap = g_cap ? g_cap * 2 : 64; g_pools = realloc_or_die(g_pools, g_cap * sizeof *g_pools, "the memory pool table"); } g_pidx_ok = 0; atomic_fetch_add(&g_pool_gen, 1); - g_pools[g_npool++] = (pool_ent){lo < b->lo ? b->lo : lo, hi > b->hi ? b->hi : hi, lo, buf, buf.gpuAddress, b->mem, 0, clock_gettime_nsec_np(CLOCK_MONOTONIC), end > b->hi ? b->hi : end, unk}; + g_pools[g_npool++] = (pool_ent){lo < b->lo ? b->lo : lo, hi > b->hi ? b->hi : hi, lo, buf, buf.gpuAddress, b->mem, 0, clock_gettime_nsec_np(CLOCK_MONOTONIC), end > b->hi ? b->hi : end, unk, 0, 0, b->tag}; [g_keep addObject:buf]; return g_npool - 1; } @@ -1477,12 +1770,22 @@ void mtl_prepare(void) { } static void sub_cut_begin(void); static void ts_sub_begin(void), ts_boundary(void); static int ts_on(void); static void gmem_commit_patch(void); // the raw pool table words of the arguments encoded so far follow the pools (gmem_slot_note) +static uint64_t g_gt_sub0; // DM_NVN_GPUPROF's timeline: when this submission's encoding began +static uint64_t g_gt_queue; // the NVN queue being replayed (mtl_queue_activate) +static void mem_trim(void); +static uint64_t spare_trim(int all, unsigned *n_out); +static uint32_t g_use_now = 1; static _Thread_local int t_pool_walk; // t_pool_walk: a pool walk's lookups, which are no use +static unsigned g_evict_why[5]; // the last trim's packages (pkg_evict_idle): considered, used within PKG_IDLE_S, of a kind not freed (sparse, placed, a view), GPU-written, held (pin, sharing table, takeover) // seconds of CLOCK_MONOTONIC + 1, set at each submission's start: the clock of the texture IDs' and packages' last uses (g_tid_used, NvPkg used_s) void mtl_sub_begin(void) { + g_gt_sub0 = mach_absolute_time(); mtl_init(); g_sub_serial++; g_seg = 0; if (g_pkg_kept) { g_pkg_kept = 0; nvn_dirty_touch(); } seg_clk_put(g_sclk); g_sclk = NULL; sub_cut_begin(); defer_drain(); rh_trim(); + g_use_now = (uint32_t)(clock_gettime_nsec_np(CLOCK_MONOTONIC) / 1000000000ull) + 1; // the clock of the texture IDs' last uses (g_tid_used) + spare_trim(0, NULL); // packaged textures' spares no re-upload took + mem_trim(); // memory pressure asked for one (mem_pressure_event) defer_reset(); mtl_prepare(); // done by then in the submit entry; the replay tool (nvn_replay) reaches it here warm_claim(); @@ -1583,12 +1886,16 @@ static inline void m4_end(id e) { // A render pass line also gives what it loaded and stored of its attachments (KB, the bandwidth ledger's view: DontCare stores are not counted) and the Metal pixel formats of // colour attachment 0 and of the depth / stencil attachment (0: none) enum { GP_MAX = 4096 }; // the largest timestamp heap Metal makes -typedef struct { char kind; uint16_t w, h; uint8_t nc, depth, loads; uint32_t draws, seg; uint64_t pass; uint32_t ld_kb, st_kb; uint16_t cfmt, dfmt; } gp_lab; // seg: the command buffer (segment) of the submission it is in +typedef struct { char kind; uint16_t w, h; uint8_t nc, depth, loads; uint32_t draws, seg; uint64_t pass; uint32_t ld_kb, st_kb; uint16_t cfmt, dfmt; uint32_t sub; } gp_lab; // seg: the command buffer (segment) of the submission it is in; sub: the submission (g_sub_serial) static id g_gp_heap; static gp_lab g_gp_lab[GP_MAX / 2]; static int g_gp_n, g_gp_state, g_gp_cur = -1; static long g_gp_f0 = -2, g_gp_f1, g_gp_every; static uint64_t g_gp_frame; +// DM_NVN_GPUPROF_GEOM=1 (with DM_NVN_GPUPROF) also stamps each render pass where its vertex and its mesh stages finish (a second heap, at the pass's end), and the pass line gives +// "geom ": the time from the pass's start to the later of the two, inside the pass. On a tile-based GPU a pass's vertex, object and mesh work (binning) runs ahead of most of its +// fragment work, so geom against the rest splits a pass's time between geometry and pixels. Relaxed like the other stamps: a guide, not an exact boundary +static id g_gp_gheap; static int g_gp_geom = -1; static const void *g_gp_e; // the encoder g_gp_cur belongs to: m4_end also ends the upload / diagnostics / present encoders, which may end while a profiled pass is open (#531) static _Atomic int g_gp_busy; // a periodic profile's report has not been printed yet: the heap is still being read static uint64_t g_bw_load, g_bw_store, g_gp_bw_l0, g_gp_bw_s0; // the bandwidth ledger (defined with the pass statistics below) and its values at the last render pass end -static uint64_t g_stat_pass, g_stat_draw; static _Atomic uint64_t g_cur_frame; static uint32_t g_seg; static uint32_t g_gp_copies, g_gp_disp, g_gp_ubd; // copies / dispatches encoded (for the compute encoders' labels) +static uint64_t g_stat_pass, g_stat_draw, g_stat_disp; static _Atomic uint64_t g_cur_frame; static uint32_t g_seg; static uint32_t g_gp_copies, g_gp_disp, g_gp_ubd; // copies / dispatches encoded (for the compute encoders' labels) static int gp_active(void) { if (__builtin_expect(g_gp_f0 == -1, 1)) return 0; if (g_gp_f0 == -2) { const char *e = getenv("DM_NVN_GPUPROF"); @@ -1599,14 +1906,21 @@ static int gp_active(void) { if (g_gp_every > 0) return f > 0 && f % g_gp_every == 0; return f >= g_gp_f0 && f <= g_gp_f1; } -static void gp_report(int n, gp_lab *lab, uint64_t frame); +typedef struct { int n, ngt; gp_lab *lab; gt_ev *gt; uint64_t frame; } gp_snap; +static void gp_report(gp_snap s); +// The profiled frame is over: its labels and CPU timeline are copied for the report, which runs once its last command buffer completes, and the heap is busy until then +static gp_snap gp_close(void) { + atomic_store(&g_gt_on, 0); int ngt = atomic_load(&g_gt_n); if (ngt > GT_MAX) ngt = GT_MAX; + gp_snap r = {g_gp_n, ngt, malloc(sizeof(gp_lab) * (g_gp_n ? g_gp_n : 1)), malloc(sizeof(gt_ev) * (ngt ? ngt : 1)), g_gp_frame}; + memcpy(r.lab, g_gp_lab, sizeof(gp_lab) * r.n); memcpy(r.gt, g_gt, sizeof(gt_ev) * ngt); + g_gp_state = 2; atomic_store(&g_gp_busy, 1); return r; +} static void gp_periodic_finish(void) { // on the submit thread, before the next frame's first encoder can touch the heap if (!g_gp_every || g_gp_state != 1 || g_gp_frame == atomic_load(&g_cur_frame)) return; - int n = g_gp_n; gp_lab *lab = malloc(sizeof *lab * (n ? n : 1)); memcpy(lab, g_gp_lab, sizeof *lab * n); uint64_t frame = g_gp_frame; - g_gp_state = 2; atomic_store(&g_gp_busy, 1); + gp_snap snap = gp_close(); static MTLSharedEventListener *listener; if (!listener) listener = [MTLSharedEventListener new]; // g_fence covers all submissions of the sampled frame. No GPU wait or extra command buffer is needed, including for every:1. - [g_ev notifyListener:listener atValue:g_fence block:^(id event, uint64_t value) { (void)event; (void)value; gp_report(n, lab, frame); }]; + [g_ev notifyListener:listener atValue:g_fence block:^(id event, uint64_t value) { (void)event; (void)value; gp_report(snap); }]; } static id g_ts_heap; static int g_ts_pend = -1; // ts_on; pend: the boundary the next encoder writes (ts_stamp) static void gp_begin(id e, char kind, MTL4RenderPassDescriptor *d) { // right after an encoder of the main command buffer is made @@ -1618,9 +1932,13 @@ static void gp_begin(id e, char kind, MTL4RenderPassDescriptor *d) { // right if (!gp_active() || g_gp_state == 2) return; if (!g_gp_heap) { MTL4CounterHeapDescriptor *hd = [MTL4CounterHeapDescriptor new]; hd.type = MTL4CounterHeapTypeTimestamp; hd.count = GP_MAX; NSError *er = nil; g_gp_heap = [g_dev newCounterHeapWithDescriptor:hd error:&er]; if (!g_gp_heap) { MLOG("[RED] GPUPROF: no counter heap: %s", er.description.UTF8String); g_gp_f0 = -1; return; } } - if (!g_gp_state) { g_gp_state = 1; g_gp_n = 0; g_gp_frame = atomic_load(&g_cur_frame); [g_gp_heap invalidateCounterRange:NSMakeRange(0, GP_MAX)]; } + if (g_gp_geom < 0) { const char *ge = getenv("DM_NVN_GPUPROF_GEOM"); g_gp_geom = ge && atoi(ge) > 0; if (g_gp_geom) MLOG("DM_NVN_GPUPROF_GEOM: render passes also stamped where their vertex and mesh stages finish"); } + if (g_gp_geom && !g_gp_gheap) { MTL4CounterHeapDescriptor *hd = [MTL4CounterHeapDescriptor new]; hd.type = MTL4CounterHeapTypeTimestamp; hd.count = GP_MAX; NSError *er = nil; + g_gp_gheap = [g_dev newCounterHeapWithDescriptor:hd error:&er]; if (!g_gp_gheap) { MLOG("[RED] GPUPROF_GEOM: no counter heap: %s", er.description.UTF8String); g_gp_geom = 0; } } + if (!g_gp_state) { g_gp_state = 1; g_gp_n = 0; g_gp_frame = atomic_load(&g_cur_frame); [g_gp_heap invalidateCounterRange:NSMakeRange(0, GP_MAX)]; if (g_gp_geom) [g_gp_gheap invalidateCounterRange:NSMakeRange(0, GP_MAX)]; + atomic_store(&g_gt_n, 0); atomic_store(&g_gt_on, 1); if (g_gt_sub0) gt_put(GT_SUB, g_gt_sub0, g_sub_serial, g_gt_queue | 1ull << 63); } // the timeline opens with the submission being encoded (its end not reached: bit 63) if (2 * g_gp_n + 2 > GP_MAX) return; - gp_lab l = {kind, 0, 0, 0, 0, 0, kind == 'R' ? (uint32_t)g_stat_draw : g_gp_copies, g_seg, g_stat_pass, 0, 0, 0, 0}; if (kind != 'R') { l.w = (uint16_t)g_gp_disp; l.h = (uint16_t)g_gp_ubd; } + gp_lab l = {kind, 0, 0, 0, 0, 0, kind == 'R' ? (uint32_t)g_stat_draw : g_gp_copies, g_seg, g_stat_pass, 0, 0, 0, 0, (uint32_t)g_sub_serial}; if (kind != 'R') { l.w = (uint16_t)g_gp_disp; l.h = (uint16_t)g_gp_ubd; } if (d) { for (int i = 0; i < 8; i++) { MTLRenderPassColorAttachmentDescriptor *c = d.colorAttachments[i]; if (!c.texture) continue; if (!l.nc) l.cfmt = (uint16_t)c.texture.pixelFormat; l.nc++; l.w = (uint16_t)MAX(c.texture.width >> c.level, 1); l.h = (uint16_t)MAX(c.texture.height >> c.level, 1); l.loads += c.loadAction == MTLLoadActionLoad; } MTLRenderPassDepthAttachmentDescriptor *z = d.depthAttachment; @@ -1636,21 +1954,47 @@ static void gp_end(id e) { // right before that encoder ends int k = g_gp_cur; g_gp_cur = -1; g_gp_e = NULL; if (g_gp_lab[k].kind == 'R') { g_gp_lab[k].ld_kb = (uint32_t)((g_bw_load - g_gp_bw_l0) >> 10); g_gp_lab[k].st_kb = (uint32_t)((g_bw_store - g_gp_bw_s0) >> 10); } // since the previous pass end (rp_end); sd_finish has set the stores if (g_gp_lab[k].kind == 'R') g_gp_lab[k].draws = (uint32_t)g_stat_draw - g_gp_lab[k].draws; else { g_gp_lab[k].draws = g_gp_copies - g_gp_lab[k].draws; g_gp_lab[k].w = (uint16_t)(g_gp_disp - g_gp_lab[k].w); g_gp_lab[k].h = (uint16_t)(g_gp_ubd - g_gp_lab[k].h); } + if (g_gp_lab[k].kind == 'R' && g_gp_geom > 0) { // where this pass's geometry work finishes (DM_NVN_GPUPROF_GEOM) + [(id)e writeTimestampWithGranularity:MTL4TimestampGranularityRelaxed afterStage:MTLRenderStageVertex intoHeap:g_gp_gheap atIndex:2 * k]; + [(id)e writeTimestampWithGranularity:MTL4TimestampGranularityRelaxed afterStage:MTLRenderStageMesh intoHeap:g_gp_gheap atIndex:2 * k + 1]; } if (g_gp_lab[k].kind == 'R') [(id)e writeTimestampWithGranularity:MTL4TimestampGranularityRelaxed afterStage:MTLRenderStageFragment intoHeap:g_gp_heap atIndex:2 * k + 1]; else [(id)e writeTimestampWithGranularity:MTL4TimestampGranularityRelaxed intoHeap:g_gp_heap atIndex:2 * k + 1]; } -static void gp_report(int n, gp_lab *lab, uint64_t frame) { // the frame's last command buffer has completed - NSData *r = [g_gp_heap resolveCounterRange:NSMakeRange(0, 2 * n)]; const uint64_t *t = r.bytes; if (!t) { free(lab); atomic_store(&g_gp_busy, 0); return; } +static int gt_cmp(const void *x, const void *y) { const gt_ev *a = x, *b = y; return a->t0 < b->t0 ? -1 : a->t0 > b->t0; } +static void gp_report(gp_snap snap) { // the frame's last command buffer has completed + int n = snap.n; const gp_lab *lab = snap.lab; uint64_t frame = snap.frame; + NSData *r = [g_gp_heap resolveCounterRange:NSMakeRange(0, 2 * n)]; const uint64_t *t = r.bytes; if (!t) { free(snap.lab); free(snap.gt); atomic_store(&g_gp_busy, 0); return; } + NSData *gr = g_gp_geom > 0 ? [g_gp_gheap resolveCounterRange:NSMakeRange(0, 2 * n)] : nil; const uint64_t *gt = gr.bytes; // DM_NVN_GPUPROF_GEOM's stamps, two per encoder double tick_ns = 1e9 / (double)[g_dev queryTimestampFrequency], tot[2] = {0}, span = 0; uint64_t t0 = 0, t1 = 0, ld = 0, st = 0; int np = 0; for (int i = 0; i < n; i++) { uint64_t a = t[2 * i], b = t[2 * i + 1]; if (!a || !b || b < a) continue; double us = (b - a) * tick_ns / 1e3; const gp_lab *l = &lab[i]; tot[l->kind != 'R'] += us; if (!t0 || a < t0) t0 = a; if (b > t1) t1 = b; if (l->kind == 'R') { np++; ld += l->ld_kb; st += l->st_kb; - MLOG("[gpuprof] F%llu %4d %8.1f us render pass %llu %ux%u colors %u depth %u loads %u draws %u start %+.1f seg %u load %u KB store %u KB fmt %u/%u", (unsigned long long)frame, i, us, (unsigned long long)l->pass, l->w, l->h, l->nc, l->depth, l->loads, l->draws, (a - t[0]) * tick_ns / 1e3, l->seg, l->ld_kb, l->st_kb, l->cfmt, l->dfmt); } - else MLOG("[gpuprof] F%llu %4d %8.1f us compute / copy after pass %llu start %+.1f seg %u copies %u (uniform updates %u) dispatches %u", (unsigned long long)frame, i, us, (unsigned long long)l->pass, (a - t[0]) * tick_ns / 1e3, l->seg, l->draws, l->h, l->w); } + char geom[32] = ""; // the later of the vertex and mesh stamps that falls inside the pass; none when neither does + if (gt) { uint64_t g = 0; for (int j = 0; j < 2; j++) { uint64_t v = gt[2 * i + j]; if (v >= a && v <= b && v > g) g = v; } + if (g) snprintf(geom, sizeof geom, " geom %.1f", (g - a) * tick_ns / 1e3); } + MLOG("[gpuprof] F%llu %4d %8.1f us render pass %llu %ux%u colors %u depth %u loads %u draws %u start %+.1f seg %u load %u KB store %u KB fmt %u/%u%s sub %u", (unsigned long long)frame, i, us, (unsigned long long)l->pass, l->w, l->h, l->nc, l->depth, l->loads, l->draws, (a - t[0]) * tick_ns / 1e3, l->seg, l->ld_kb, l->st_kb, l->cfmt, l->dfmt, geom, l->sub); } + else MLOG("[gpuprof] F%llu %4d %8.1f us compute / copy after pass %llu start %+.1f seg %u copies %u (uniform updates %u) dispatches %u sub %u", (unsigned long long)frame, i, us, (unsigned long long)l->pass, (a - t[0]) * tick_ns / 1e3, l->seg, l->draws, l->h, l->w, l->sub); } span = (t1 - t0) * tick_ns / 1e3; MLOG("[gpuprof] frame %llu: render %.2f ms, compute / copy %.2f ms over %d encoders (%d render passes, attachments load %.1f MB store %.1f MB), first start to last end %.2f ms", (unsigned long long)frame, tot[0] / 1e3, tot[1] / 1e3, n, np, ld / 1024.0, st / 1024.0, span / 1e3); - free(lab); atomic_store(&g_gp_busy, 0); + // The CPU timeline (gt_put), on the encoders' clock: microseconds from the frame's first stamp + if (snap.ngt && n && t[0]) { + mach_timebase_info_data_t tb; mach_timebase_info(&tb); double cpu_ns = (double)tb.numer / tb.denom; + #define GT_US(v) (((double)(int64_t)((v) - t[0])) * cpu_ns / 1e3) + qsort(snap.gt, (size_t)snap.ngt, sizeof *snap.gt, gt_cmp); + static const char *const park[3] = {"no work queued", "an event wait holds queue", "a sync wait holds queue"}; + for (int i = 0; i < snap.ngt; i++) { const gt_ev *e = &snap.gt[i]; char what[160]; + switch (e->kind) { + case GT_SUB: snprintf(what, sizeof what, "submission %llu (NVN queue %llu) encoded%s", (unsigned long long)e->a, (unsigned long long)(e->b & ~(1ull << 63)), e->b >> 63 ? " (still encoding when the profile began)" : ""); break; + case GT_COMMIT: if (e->b == UINT32_MAX) snprintf(what, sizeof what, "commit of an upload batch of submission %llu", (unsigned long long)e->a); + else snprintf(what, sizeof what, "commit of submission %llu segment %llu (from before its uniform-copy wait)", (unsigned long long)e->a, (unsigned long long)e->b); break; + case GT_WAIT: snprintf(what, sizeof what, "CPU wait for fence %llu: %s", (unsigned long long)e->b, e->a < WS_N ? ws_name[e->a] : "?"); break; + default: snprintf(what, sizeof what, "NVN queue worker parked: %s", park[e->a < 3 ? e->a : 0]); if (e->a) snprintf(what + strlen(what), sizeof what - strlen(what), " %llu", (unsigned long long)e->b); break; } + MLOG("[gpuprof] F%llu cpu %+.1f..%+.1f us %s", (unsigned long long)frame, GT_US(e->t0), GT_US(e->t1), what); } + MLOG("[gpuprof] F%llu cpu timeline: %d events%s; this report at %+.1f us (after the last end %+.1f: the CPU and GPU clocks agree when it is later)", (unsigned long long)frame, snap.ngt, snap.ngt == GT_MAX ? " (the limit: later ones lost)" : "", GT_US(mach_absolute_time()), (t1 - t[0]) * tick_ns / 1e3); + #undef GT_US + } + free(snap.lab); free(snap.gt); atomic_store(&g_gp_busy, 0); } static inline id enc_r_begin_pass(MTL4RenderPassDescriptor *d) { g_cm_enc++; cm_enc_mark(2); // the draw passes (rp_begin_ex); see barrier_game id e = [g_cb renderCommandEncoderWithDescriptor:d]; cm_enc_mark(0); @@ -2491,7 +2835,7 @@ uint64_t mtl_sub_commit(void) { if (ws_on()) for (int i = 0; i < n; i++) { int k = g_post[i].kind == 2 ? (g_post[i].type == 0 || g_post[i].type == 0x10 ? 3 : 4) : g_post[i].kind == 3 ? (g_post[i].mode == VIS_REPORT ? 2 : 0) : 1; atomic_fetch_add(&g_ws_post[k], 1); } // 1 event, 2 samples passed, 3 timestamp, 4 other counter if (n) memcpy(ops, g_post, n * sizeof *ops); NSArray *commit_blocks = [g_commit_blocks copy]; - MTL4CommitOptions *o = [MTL4CommitOptions new]; + DmCommitFB *o = [DmCommitFB new]; atomic_fetch_add(&g_seg_inflight, 1); [o addFeedbackHandler:^(id f) { (void)f; atomic_fetch_sub(&g_seg_inflight, 1); for (dispatch_block_t block in commit_blocks) block(); }]; uint64_t gpu_f = atomic_load(&g_cur_frame); gpu_tag_begin(gpu_f); @@ -2516,13 +2860,20 @@ uint64_t mtl_sub_commit(void) { }]; void arena_commit(uint64_t fence); arena_commit(fence); res_commit(); - if (g_gp_state == 1 && !gp_active()) { int gn = g_gp_n; gp_lab *gl = malloc(sizeof(gp_lab) * (gn ? gn : 1)); memcpy(gl, g_gp_lab, sizeof(gp_lab) * gn); uint64_t gf = g_gp_frame; g_gp_state = 2; atomic_store(&g_gp_busy, 1); - [o addFeedbackHandler:^(id f) { (void)f; gp_report(gn, gl, gf); }]; } + if (g_gp_state == 1 && !gp_active()) { gp_snap snap = gp_close(); [o addFeedbackHandler:^(id f) { (void)f; gp_report(snap); }]; } [g_cb endCommandBuffer]; - rec_commit(g_cb, o); g_cbgen++; // the stores it holds come before any later upload batch (gsb_held) + rec_commit(g_cb, o, 1); g_cbgen++; // the stores it holds come before any later upload batch (gsb_held) if (!lost_test) rec_signal(g_ev, fence); - rec_drain(); + // With the encode thread the records go to it and the replay goes on with the next submission: what comes after it on the queue is a record too (the next submission's commits, + // upload batches, snapshot copies), a CPU wait for the GPU waits for the fence's signal behind this commit, and a present of the game's own texture waits for this note + // (sub_commit_wait). The replay used to wait for the encode thread here: Ocarina of Time makes about 30 submissions a frame (one at each event signal), and on the iPhone the GPU + // sat idle before most of them while the replay waited and then translated the next one (13.6 of 14.8 ms of gaps in a 35 ms frame; docs/reference/rendering.md) + // DM_NVN_SUB_DRAIN=1 waits for the encode thread here as before (ab: alternates with the DM_AB phases, for measurement) + static int drain = -1; if (drain < 0) drain = sw_mode("DM_NVN_SUB_DRAIN", 0); + if (rec_on() && g_rb_started) { rec_t *r = rec_put(RO_NOTE, 0); r->a[0] = (uint64_t)(uintptr_t)&g_sub_cmt; r->a[1] = fence; if (drain && sw_on(drain)) rec_drain(); else rec_publish(); } + else atomic_store(&g_sub_cmt, fence); g_alloc_fence[g_alloc_cur] = fence; + gt_put(GT_SUB, g_gt_sub0, g_sub_serial, g_gt_queue); g_cb = nil; atomic_store(&g_sub_on, 0); // after ++g_fence and the last encoding: a buffer retired from now on waits for this fence at most defer_idle_commit(); // a feedback handler that drained since this submission's own commit saw it open @@ -2531,6 +2882,8 @@ uint64_t mtl_sub_commit(void) { return fence; } +// A present of the game's own texture waits for the submissions before it (g_sub_cmt), as the display command buffer goes to the queue directly and must come after the work that drew the picture +static void sub_commit_wait(uint64_t fence) { if (fence && rec_on()) rec_note_wait(&g_sub_cmt, fence); } uint64_t mtl_completed_fence(void) { return atomic_load_explicit(&g_done,memory_order_acquire); } uint64_t mtl_last_fence(void) { return g_fence; } int mtl_last_commit_error(void) { return atomic_load(&g_last_commit_error); } @@ -2543,11 +2896,12 @@ static void post_early(uint64_t fence) { } static int mtl_wait_at(uint64_t fence, uint64_t timeout_ns, int site) { if (g_done >= fence) { if (ws_on()) ws_put(site, 0, 0); return 1; } - uint64_t w0 = ws_t0(); + uint64_t w0 = ws_t0(), gt0 = atomic_load_explicit(&g_gt_on, memory_order_relaxed) ? mach_absolute_time() : 0; // gt0: DM_NVN_GPUPROF's timeline if ((site == WS_SYNC || site == WS_SYNC_NEWEST || site == WS_ACQ) && fast_wake() && g_ev && fence <= g_fence) { // the game's own wait: wake on the GPU's signal (rec_signal(g_ev, fence) after each submission) uint64_t ms = timeout_ns / 1000000ull; if (ms > 3600000ull) ms = 3600000ull; if ([g_ev waitUntilSignaledValue:fence timeoutMS:ms]) post_early(fence); int ok = g_done >= fence; + if (gt0) gt_put(GT_WAIT, gt0, (uint64_t)site, fence); if (ws_on()) { ws_put(site, w0, 1); ws_wake(fence); } if (ok || timeout_ns < 1000000ull) return ok; // The event and feedback waits share a finite budget; a timeout must not buy another full wait. @@ -2578,6 +2932,7 @@ static int mtl_wait_at(uint64_t fence, uint64_t timeout_ns, int site) { } int ok = g_done >= fence; pthread_mutex_unlock(&g_mu); + if (gt0) gt_put(GT_WAIT, gt0, (uint64_t)site, fence); if (ws_on()) { ws_put(site, w0, 1); if (site == WS_SYNC_NEWEST || site == WS_SYNC || site == WS_ACQ) ws_wake(fence); } return ok; } @@ -2602,7 +2957,7 @@ static void mtl_finish_gpu_at(int site) { // ================= Render replay ================= #include "../../host/front.h" -static int g_red_once[168]; // one past the highest key: a new key raises this, and the macro refuses to compile otherwise +static int g_red_once[169]; // one past the highest key: a new key raises this, and the macro refuses to compile otherwise #define RED_ONCE(k, ...) do { _Static_assert((k) < sizeof g_red_once / sizeof *g_red_once, "a RED_ONCE key past g_red_once: raise its size"); if (!g_red_once[k]++) MLOG("[RED] " __VA_ARGS__); } while (0) // NVN vertex streams 0–15 → Metal vertex buffer slots: 0–13 go to 16–29 (30 is the constant fallback buffer), 14 and 15 to 14 and 15. Metal has only the 31 slots 0–30; translated shaders use only buffer(0) (the argument buffer), // and the host's own vertex functions read no vertex buffers. 13 Sentinels uses stream 15, and the old 16 + stream went out of range (Metal assertion: buffer index (31) must be < 31) @@ -2693,7 +3048,8 @@ void mtl_tex_init(const tex_t *t) { // Host record of a packaged texture: the current MTLTexture, the upload stamp, and the global write generation at the last check // spare: the texture the last re-upload replaced, kept resident and written by the next re-upload once the GPU has passed spare_fence (a texture the CPU rewrites every frame, a movie frame, // alternates between two textures instead of allocating one per frame: Link's Awakening's title movie made and freed an 8 MB texture a frame) -@interface NvPkg : NSObject { @public id tex, spare, view; uint64_t stamp, seen, hash, spare_fence, vgen, vseen, sub, own, lost_gen; const void *span; int sparse, vbase, part; uint8_t *edge[2]; uint32_t edge_n[2], stored; id ps; id eb; } @end // hash: full hash of the uploaded content under DM_NVN_DIRTYCHECK; span: its tracked range (nvn_dirty_span, NULL = untracked); +// used_s: g_use_now at its last resolution (tex_mtl_); mem / size: its storage (pkg_evict_idle). spare_t: when the spare became one. A spare no re-upload took within g_spare_idle_ns, or any spare at memory pressure, is retired (spare_trim) +@interface NvPkg : NSObject { @public id tex, spare, view; uint64_t stamp, seen, hash, spare_fence, spare_t, vgen, vseen, sub, own, lost_gen, size; uintptr_t mem; uint32_t used_s; const void *span; int sparse, vbase, part; uint8_t *edge[2]; uint32_t edge_n[2], stored; id ps; id eb; } @end // hash: full hash of the uploaded content under DM_NVN_DIRTYCHECK; span: its tracked range (nvn_dirty_span, NULL = untracked); // sparse: in a sparse virtual pool, read through its page table (hle_nvn.c nvn_sparse_*), vgen the page table's generation at the upload and vseen at the last look; view: what it is bound as (sparse_view) // ps: its placement sparse texture (NvSparse, sparse_make), which tex is: mapped and uploaded tile by tile (sparse_sync) // edge: the uploaded bytes of the storage's first and last host pages where other data shares them (pkg_edges_take); in eb from the first GPU store into its storage on (pkg_edges_gpu), @@ -2705,6 +3061,31 @@ @interface NvPkg : NSObject { @public id tex, spare, view; uint64_t @implementation NvPkg - (void)dealloc { defer_obj_release(tex); defer_obj_release(spare); if (eb) defer_obj_release(eb); else { free(edge[0]); free(edge[1]); } } @end +// Spares that waited for good. A spare pays only for a texture the CPU rewrites again soon (a movie frame); one re-upload of a streamed texture left its old texture resident until the +// texture object was finalized, held by nothing but its NvPkg. On the iPhone 17, as Ocarina of Time's re-uploads on pool content change went from 0 to 129, the uploaded textures the +// census found held by nothing went from 40 (6 MB) to 168 (123 MB): it looked for the NvPkg, not its textures. The packages that have one are listed here (weak), and at a submission's start a +// spare older than g_spare_idle_ns (3 s) is retired as a spare the next re-upload cannot take is (defer_obj_release: after the submissions that used it complete, and only once no serial entry +// holds it), the package's next re-upload making a new texture. At memory pressure (mem_trim) every spare goes. Submit thread only, as are re-uploads +static uint64_t g_spare_idle_ns = 3000000000ull; +static NSHashTable *g_spare_pkgs; static uint64_t g_spare_last; static _Atomic uint64_t g_spare_trimmed, g_spare_trimmed_bytes, g_spare_held; // held: spares left after the last walk (the report) +static void spare_note(NvPkg *pk) { if (!g_spare_pkgs) g_spare_pkgs = [NSHashTable weakObjectsHashTable]; pk->spare_t = clock_gettime_nsec_np(CLOCK_MONOTONIC); [g_spare_pkgs addObject:pk]; } +static uint64_t spare_trim(int all, unsigned *n_out) { @autoreleasepool { + unsigned n = 0; uint64_t b = 0, now = clock_gettime_nsec_np(CLOCK_MONOTONIC); + if (!g_spare_pkgs.count || (!all && now - g_spare_last < 250000000ull)) { if (n_out) *n_out = 0; return 0; } + g_spare_last = now; + NSMutableArray *gone = nil; + uint64_t held = 0; + for (NvPkg *pk in g_spare_pkgs) { + if (pk->spare && !all && now - pk->spare_t < g_spare_idle_ns) { held++; continue; } + if (pk->spare) { n++; b += pk->spare.heap ? 0 : pk->spare.allocatedSize; defer_obj_release(pk->spare); pk->spare = nil; } + if (!gone) gone = [NSMutableArray array]; + [gone addObject:pk]; + } + for (NvPkg *pk in gone) [g_spare_pkgs removeObject:pk]; + atomic_fetch_add(&g_spare_trimmed, n); atomic_fetch_add(&g_spare_trimmed_bytes, b); atomic_store(&g_spare_held, held); + if (n_out) *n_out = n; + return b; +} } // Packaged textures by storage and description. Engines make many texture objects over one texture's bytes, each with a serial of its own: Ocarina of Time's 32,768 registered IDs name 3,607 storages, // 2.0 GB, and an upload per serial took 6 GB, past what a 16 GB Mac can keep wired once the pools are added. A new serial with the same storage and description takes the same NvPkg, so its // dirty-page checks and re-uploads are one. Weak: the serials' entries own it, and a table entry never keeps one alive. Under g_smu; a pool's entries go when it is finalized (mtl_alias_drop_pool) @@ -2880,6 +3261,32 @@ static int tex_atomic_alias(id base) { // In-place upgrade: when the original texture was not created with PixelFormatView (off by default, to keep Apple GPU lossless compression) but a different-format view is needed, create a new one with the original spec + PixelFormatView, copy over every slice × level, and replace the registration. // Count: across the 4 screens character select / camp / wilderness / combat, 17473 textures needed a different-format view 0 times, so this is a fallback and does not rely on predicting which textures need it // The same upgrade adds render-target usage for a whole-level clear (clear_tex) of a texture made without it: Monster Hunter Rise clears a 32x80 packaged one +// Smaller textures on small devices (docs/reference/memory.md, "Large sampled textures leave out their largest level on small devices"). Where Metal's working set is under 6 GB (the +// iPhone 17 and the M1 iPad: 5,461 MB), a large texture made from the game's data (pkg_upload_) leaves out its largest level: the Metal texture is half the size with one level fewer, +// and its level k holds the game's level k+1. Sampled with normalized coordinates, it gives the same texel density from the next level; only the closest views lose detail. Only +// sampling may see it: tex_mtl hands it out only to the sampled-texture path (treg_tex, t_drop_ok), and every other use (attachments, copies, image slots, readbacks, upgrades) makes the +// texture whole first (tex_undrop), after which it stays whole (g_drop_full). Shaders that fetch texels, ask the size or pick an explicit level read the smaller texture. DM_NVN_TEX_DROP_MIP=0/1 +// forces it off or on +enum { DROP_MIN = 512 }; // both sides at least this, and 2 levels or more +// Small devices: Metal's working set under 6 GB (the iPhone 17 and the M1 iPad, 5,461 MB; 8 GB Macs too). The rule for smaller textures here and for upload staging released (up_reuse) +static int small_working_set(uint64_t working_set) { return working_set && working_set < (6ull << 30); } +static int drop_wants(uint64_t working_set) { return small_working_set(working_set); } +static int g_drop_on = -1; +static int drop_on(void) { + if (g_drop_on < 0) { const char *e = getenv("DM_NVN_TEX_DROP_MIP"); g_drop_on = e && *e ? atoi(e) > 0 : drop_wants(g_dev ? g_dev.recommendedMaxWorkingSetSize : 0); + if (g_drop_on) MLOG("large sampled textures leave out their largest level (DM_NVN_TEX_DROP_MIP%s): sides of %d and more, 2 levels or more", e && *e ? "" : ", Metal's working set under 6 GB", DROP_MIN); } + return g_drop_on; +} +static char g_drop_key; // set on a dropped Metal texture (and carried by tex_upgrade) +static __thread int t_drop_ok; // tex_mtl's caller samples the texture (treg_tex) +static __thread int t_drop_off; // pkg_upload_ makes the texture whole (tex_undrop) +static NSMutableSet *g_drop_full; // storage of textures made whole again: they stay whole (submit thread) +static uint64_t g_drop_n, g_drop_bytes, g_drop_full_n, g_drop_cand_n[4], g_drop_cand_b[4]; +static uint64_t g_drop_no[8]; static uint32_t g_drop_no_flags; // first uploads of 256 and more that no rule lets drop, by the first rule they fail (pkg_upload_), and the flags of those refused for flags // dropped, bytes saved, made whole; candidates by largest side 256 / 512 / 1024 / 2048+ +static struct { int line; uint64_t n; } g_drop_why[8]; +static int tex_dropped(id m) { return m && (objc_getAssociatedObject(m, &g_drop_key) || (m.parentTexture && objc_getAssociatedObject(m.parentTexture, &g_drop_key))); } +// A sampled view of a dropped texture: from level 0 it starts at Metal level 0 with one level fewer (at least one), from level k at Metal level k-1 +static void drop_levels(NSUInteger *l0, NSUInteger *nl) { if (*l0) (*l0)--; else if (*nl > 1) (*nl)--; } static id tex_upgrade(const tex_t *t, id asked, MTLTextureUsage add, MTLPixelFormat view_pf) { id holder = tex_get(t->serial); // The serial holds an sRGB / linear view (tex_mtl_) of the asked texture, or the asked texture is that view: the parent is upgraded and the view made again on it, so the pair keeps sharing its bytes @@ -2904,6 +3311,7 @@ static int tex_atomic_alias(id base) { if (upgraded) { res_add(raw); NvAtomicRaw *own = [NvAtomicRaw new]; own->raw = raw; objc_setAssociatedObject(upgraded, &g_atomic_raw_key, own, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } } else upgraded = backing ? [backing newTextureWithDescriptor:d offset:base.bufferOffset bytesPerRow:base.bufferBytesPerRow] : [g_dev newTextureWithDescriptor:d]; if (!upgraded) { RED_ONCE(45, "texture upgrade failed ser=%llu format %lu → %lu usage %#lx", t->serial, (unsigned long)base.pixelFormat, (unsigned long)view_pf, (unsigned long)d.usage); return base; } + if (objc_getAssociatedObject(base, &g_drop_key)) objc_setAssociatedObject(upgraded, &g_drop_key, @1, OBJC_ASSOCIATION_RETAIN_NONATOMIC); // a sampled view's format: still dropped if (!reinterpret) res_add(upgraded); id upgraded_view = nil; id b = backing ? nil : blit(); // shared backing already contains the pixels; copying it onto itself would overlap @@ -2961,11 +3369,19 @@ static void up_wait_zero(_Atomic int *v, int site) { #define UP_BLOCK_SIZE (32u * 1024u * 1024u) // Each upload slot keeps its staging resident until its next batch (up_begin waits for the previous batch). Grow the first block to the slot's previous batch demand, not just its first texture: // a small first texture followed by a large one otherwise allocates and retires a fresh 32 MB overflow every frame. Keep one overflow as well, at most 64 MB per slot / 192 MB across all three. -// Bursts beyond that budget and individual uploads larger than UP_BLOCK_SIZE still use temporary blocks, retired only after their GPU work. DM_NVN_UPLOAD_REUSE=0 keeps the original one-block policy. +// Bursts beyond that budget and individual uploads larger than UP_BLOCK_SIZE still use temporary blocks, retired only after their GPU work. Small devices (small_working_set, as smaller +// textures) keep the original one-block policy, each batch's staging released once its GPU work is done: in play a game uploads 1-6 MB per 300 frames, and on the iPhone 17 the retained +// blocks cost Ocarina of Time 125 MB of resident memory for no speed (docs/reference/memory.md, "Upload staging kept for reuse on small devices"). DM_NVN_UPLOAD_REUSE=0 / 1 forces either #define UP_SLOT_BLOCK (4u * 1024u * 1024u) static __strong id g_up_slot_blk[3], g_up_slot_over[3]; static unsigned g_up_cur_slot; static size_t g_up_slot_want[3], g_up_batch_bytes; static int g_up_over_used; -static int up_reuse(void) { static int on = -1; if (on < 0) { const char *e = getenv("DM_NVN_UPLOAD_REUSE"); on = !e || atoi(e); } return on; } +static int up_reuse_wants(uint64_t working_set) { return !small_working_set(working_set); } +static int up_reuse(void) { + static int on = -1; + if (on < 0) { const char *e = getenv("DM_NVN_UPLOAD_REUSE"); on = e && *e ? atoi(e) > 0 : up_reuse_wants(g_dev ? g_dev.recommendedMaxWorkingSetSize : 0); + if (!on && !(e && *e)) MLOG("upload staging is released after each batch, not kept for reuse (Metal's working set under 6 GB; DM_NVN_UPLOAD_REUSE=1 keeps it)"); } + return on; +} static int up_retained(id b, unsigned slot) { return b && (b == g_up_slot_blk[slot] || b == g_up_slot_over[slot]); } typedef struct { __unsafe_unretained id src; @@ -2986,6 +3402,12 @@ static void up_wait_zero(_Atomic int *v, int site) { // texture larger than the budget gets its own block (uploads are not tiled here). static size_t g_up_staging_bytes; #define UP_BATCH_BYTES (128u * 1024u * 1024u) +// The same for the batch's zero-copy buffers over guest memory (up_big_src): each joins the residency set, which wires its pages, until the batch completes. With the guest's memory in +// files (iOS, DM_GUEST_FILE) those are file pages, wired first by file_wire. Uncounted, Ocarina of Time's field load put 732 MB of them in the set on an iPhone 17 within seconds, 1,022 MB +// of file pages wired before the commits, and the phone, 5.56 GB wired of 8, ended the app for thrashing. Past this budget the batch is flushed at the next texture's start, and up_begin +// waits for a slot of three: at most about three budgets are wired at once. DM_NVN_UPLOAD_SRC_MB sets it (0: no budget) +static size_t g_up_big_batch; // bytes of up_big_src buffers in the open batch +static size_t up_big_budget(void) { static long mb = -1; if (mb < 0) { const char *e = getenv("DM_NVN_UPLOAD_SRC_MB"); mb = e && *e ? atol(e) : 96; if (mb < 0) mb = 96; } return (size_t)mb << 20; } // The upload command buffer was discarded by the system (dropped along during GPU error recovery; the first frame on entering Travincal drops one every run): the objects of this batch of textures are built and the timestamps updated, but the content was never written in, @@ -3021,6 +3443,7 @@ static void up_flush(void) { NSMutableArray *staging = g_up_keep; if (g_up_block && !up_retained(g_up_block, slot)) [staging addObject:g_up_block]; NSMutableArray *views = g_up_views; g_up_views = nil; + uint64_t big = g_up_big_batch; g_up_big_batch = 0; g_up_keep = nil; g_up_block = nil; g_up_block_off = g_up_block_size = g_up_staging_bytes = 0; NSMutableSet *targets = [NSMutableSet setWithArray:g_up_texs]; for (int i = 0; i < g_nup_blits; i++) if (g_up_blits[i].dst) [targets addObject:g_up_blits[i].dst]; @@ -3041,6 +3464,7 @@ static void up_flush(void) { @autoreleasepool { for (id obj in staging) res_remove(obj); [staging removeAllObjects]; + atomic_fetch_sub(&g_ubs_live, big); [views removeAllObjects]; // upload-only integer views share their targets' residency res_commit(); } @@ -3141,6 +3565,33 @@ static void up_diag(void) { @autoreleasepool { g_up_block_off += need; return g_up_block; } +// Memory pressure asked for a trim (mem_pressure_event): at a submission's start, on the submit thread, which owns the upload slots, before anything of the submission is encoded. What goes +// is what no frame needs and nothing waits for: the recycled render-target heaps waiting for a target (rh_trim_n), the upload slots' staging blocks of slots with no batch open or in flight +// (made again at the next upload), and the deferred releases whose submissions have completed. Each trim is logged with what it freed and the system's free memory after it +static uint64_t pkg_evict_idle(unsigned *n_out); +static void mem_trim(void) { + int lv = atomic_exchange(&g_mp_want, 0); + if (!lv) return; + uint64_t t0 = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + unsigned rn = 0; uint64_t rb = rh_trim_n(1, &rn); + unsigned sn = 0; uint64_t sb = spare_trim(1, &sn); // every packaged texture's spare (NvPkg) + unsigned en = 0; uint64_t eb = pkg_evict_idle(&en); // uploaded textures nothing used for 30 s + unsigned un = 0; uint64_t ub = 0; + for (unsigned s = 0; s < 3; s++) { + if ((g_up_cb && s == g_up_cur_slot) || atomic_load(&g_up_alloc_busy[s])) continue; // a batch open in this slot or still on the GPU + __strong id *bs[2] = {&g_up_slot_blk[s], &g_up_slot_over[s]}; + for (int k = 0; k < 2; k++) if (*bs[k] && *bs[k] != g_up_block) { un++; ub += (*bs[k]).length; defer_obj_release(*bs[k]); *bs[k] = nil; } + } + pthread_mutex_lock(&g_deferred_mu); unsigned long d0 = (unsigned long)g_deferred.count; pthread_mutex_unlock(&g_deferred_mu); + defer_drain(); + pthread_mutex_lock(&g_deferred_mu); unsigned long d1 = (unsigned long)g_deferred.count; pthread_mutex_unlock(&g_deferred_mu); + res_commit(); + atomic_fetch_add(&g_mp_trims, 1); atomic_fetch_add(&g_mp_freed, rb + sb + eb + ub); + sys_mem_t m = sys_mem(); + MLOG("[mem] memory pressure trim (%s): recycled render-target heaps %u, %llu MB; packaged textures' spares %u, %llu MB; uploaded textures idle 30 s %u, %llu MB (of %u packages: used lately %u, sparse / placed / a view %u, GPU-written %u, held %u); upload staging blocks %u, %llu MB (freed when their submission completes); deferred releases drained %lu, still waiting for the GPU %lu; %.1f ms; system free %llu MB, wired %llu MB, residency set %llu MB", + lv == 2 ? "critical" : "warn", rn, (unsigned long long)(rb >> 20), sn, (unsigned long long)(sb >> 20), en, (unsigned long long)(eb >> 20), g_evict_why[0], g_evict_why[1], g_evict_why[2], g_evict_why[3], g_evict_why[4], un, (unsigned long long)(ub >> 20), d0 > d1 ? d0 - d1 : 0, d1, (clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - t0) / 1e6, + (unsigned long long)m.free, (unsigned long long)m.wired, (unsigned long long)(g_res ? g_res.allocatedSize >> 20 : 0)); +} // Deswizzle parameter blocks: 64 bytes per cell, cut sequentially from a 64 KB shared-storage block; a full block is replaced by a new one, and the old block is released lazily by fence static id g_up_pblock; static size_t g_up_pblock_off; @@ -3245,17 +3696,21 @@ static void rb_swap_rows(uint8_t *p, size_t wb, size_t rows, size_t nz, size_t r // nil elsewhere (or if it is refused: the caller looks the address up as usual). The GPU only reads it, so it is made over the pages the upload has just protected, not through pool_buf, // which would make them writable again and the texture count as written at once static uint64_t g_up_src_made; // source buffers made (t_upload_src) -static id up_big_src(uint64_t addr, uint64_t len, uint64_t *off) { +static id up_big_src(uint64_t addr, uint64_t len, uint64_t *off, int may_split) { // may_split: called at a texture's start, so the batch may be flushed first (up_big_budget) // Not once the raw memory table holds the whole pool (big_full): the lookup finds that buffer. Ocarina of Time's first scene made 4,664 of these in one batch, 2.1 GB counted against the working set for pages already wired pthread_mutex_lock(&g_mu); int k = big_of(addr), in = k >= 0 && !g_big[k].full; if (k < 0 && len) { int i = pool_find(addr, len); in = i >= 0 && !g_pools[i].res && !addr_meets(g_pools[i].lo, g_pools[i].hi); } pthread_mutex_unlock(&g_mu); if (!in || !len) return nil; uintptr_t pg = (uintptr_t)getpagesize(), a = (uintptr_t)addr & ~(pg - 1), b = ((uintptr_t)addr + len + pg - 1) & ~(pg - 1); + if (may_split && g_up_big_batch && up_big_budget() && g_up_big_batch + (b - a) > up_big_budget()) { up_flush(); up_begin(); } id buf = [g_dev newBufferWithBytesNoCopy:(void *)a length:b - a options:MTLResourceStorageModeShared deallocator:nil]; if (!buf) return nil; g_up_src_made++; res_add(buf); [g_up_keep addObject:buf]; *off = (uint64_t)addr - a; + g_up_big_batch += b - a; + uint64_t live = atomic_fetch_add(&g_ubs_live, b - a) + (b - a), pk = atomic_load(&g_ubs_peak); + while (live > pk && !atomic_compare_exchange_weak(&g_ubs_peak, &pk, live)) {} return buf; } // A re-upload read every layer and level of a texture from guest memory when one page of it was written. Ocarina of Time fills a 1800x1380x8 RGBA8 array (38.5 MB) layer by layer @@ -3284,7 +3739,30 @@ static void rb_swap_rows(uint8_t *p, size_t wb, size_t rows, size_t nz, size_t r d.usage |= keep & (MTLTextureUsageRenderTarget | MTLTextureUsagePixelFormatView); int rb_shift = rb_packed_shift(t->d.format); // the RGB565 family is repacked into Metal's order on the CPU (rb_packed_shift) int linear = (t->d.flags & (NVN_TEXTURE_FLAGS_LINEAR | NVN_TEXTURE_FLAGS_LINEAR_RENDER_TARGET)) != 0; // linear storage no view could take (linear_fit): its rows are copied on the CPU - int direct = !linear && !rb_shift && stamp && direct_upload_on() && g_nvn_deswz_gpu && !(t->pool && nvn_sparse_pool(t->pool)) && nvn_deswz_gpu_direct_supported(&t->d); + // Smaller textures on small devices (drop_on): a sampled 2D texture of the game's data, of 2 levels or more, leaves out its largest level; nothing made to be rendered into. The image flag + // does not keep it whole: Ocarina of Time gives it to its material textures (611 of 766 refused at its title for that), and a shader can write one only through an image slot, which + // makes it whole first (img_binding → tex_undrop), as an attachment does + unsigned drop = 0; + // The first rule a texture fails, counted for the memory report (g_drop_no): 0 type, 1 levels, 2 samples / linear / CPU repack, 3 sparse pool, 4 render-target or write usage, 5 flags, 6 depth, 7 made whole before + int no = -1; + if (drop_on() && !t_drop_off && !reuse) { + no = !(d.textureType == MTLTextureType2D || d.textureType == MTLTextureType2DArray) ? 0 : d.mipmapLevelCount < 2 ? 1 : (d.sampleCount != 1 || linear || rb_shift) ? 2 + : (t->pool && nvn_sparse_pool(t->pool)) ? 3 : (d.usage & MTLTextureUsageRenderTarget) ? 4 + : (t->d.flags & (NVN_TEXTURE_FLAGS_COMPRESSIBLE | NVN_TEXTURE_FLAGS_DISPLAY | NVN_TEXTURE_FLAGS_VIDEO_DECODE)) ? 5 + : (d.pixelFormat == MTLPixelFormatDepth16Unorm || d.pixelFormat == MTLPixelFormatDepth32Float || d.pixelFormat == MTLPixelFormatDepth32Float_Stencil8 || d.pixelFormat == MTLPixelFormatStencil8) ? 6 + : [g_drop_full containsObject:@((uintptr_t)t->mem)] ? 7 : -1; + if (no >= 0 && MAX(t->d.width, t->d.height) >= 256) { g_drop_no[no]++; if (no == 5) g_drop_no_flags |= t->d.flags; } + } + if (drop_on() && !t_drop_off && (d.textureType == MTLTextureType2D || d.textureType == MTLTextureType2DArray) && d.mipmapLevelCount >= 2 && d.sampleCount == 1 && !linear && !rb_shift + && !(t->pool && nvn_sparse_pool(t->pool)) && !(d.usage & MTLTextureUsageRenderTarget) && !(t->d.flags & (NVN_TEXTURE_FLAGS_COMPRESSIBLE | NVN_TEXTURE_FLAGS_DISPLAY | NVN_TEXTURE_FLAGS_VIDEO_DECODE)) + && d.pixelFormat != MTLPixelFormatDepth16Unorm && d.pixelFormat != MTLPixelFormatDepth32Float && d.pixelFormat != MTLPixelFormatDepth32Float_Stencil8 && d.pixelFormat != MTLPixelFormatStencil8 && ![g_drop_full containsObject:@((uintptr_t)t->mem)]) { + unsigned side = MAX(t->d.width, t->d.height), k = side >= 2048 ? 3 : side >= 1024 ? 2 : side >= 512 ? 1 : 0; + int bw0, bh0, bpb0 = nvn_fmt_bpb(t->d.format, &bw0, &bh0); unsigned ly = d.textureType == MTLTextureType2DArray ? (unsigned)d.arrayLength : 1; + uint64_t top = bpb0 ? (uint64_t)((t->d.width + bw0 - 1) / bw0) * bpb0 * ((t->d.height + bh0 - 1) / bh0) * ly : 0; // what the largest level takes + if (side >= 256 && !reuse) { g_drop_cand_n[k]++; g_drop_cand_b[k] += top; } + if (t->d.width >= DROP_MIN && t->d.height >= DROP_MIN) { drop = 1; d.width = MAX(d.width >> 1, 1u); d.height = MAX(d.height >> 1, 1u); d.mipmapLevelCount -= 1; if (!reuse) g_drop_bytes += top; } + } + int direct = !drop && !linear && !rb_shift && stamp && direct_upload_on() && g_nvn_deswz_gpu && !(t->pool && nvn_sparse_pool(t->pool)) && nvn_deswz_gpu_direct_supported(&t->d); if (direct) d.usage |= MTLTextureUsageShaderWrite | MTLTextureUsagePixelFormatView; id mt = reuse && reuse.pixelFormat == d.pixelFormat && reuse.width == d.width && reuse.height == d.height && reuse.mipmapLevelCount == d.mipmapLevelCount && reuse.textureType == d.textureType && (reuse.usage & d.usage) == d.usage @@ -3294,22 +3772,25 @@ static void rb_swap_rows(uint8_t *p, size_t wb, size_t rows, size_t nz, size_t r MLOG("large texture ser=%llu %ux%ux%u format %#x target %d levels %u: %llu MB%s", (unsigned long long)t->serial, t->d.width, t->d.height, t->d.depth, t->d.format, t->d.target, t->d.levels, (unsigned long long)(mt.allocatedSize >> 20), t->pool && nvn_sparse_pool(t->pool) ? ", in a sparse virtual pool" : t->pool && (t->pool->flags & NVN_MEMORY_POOL_FLAGS_VIRTUAL) ? ", in a virtual pool" : ""); } if (g_allocprof > 0) { static int n; if (n++ < 30 || n % 500 == 0) MLOG("new texture (%s) #%d ser=%llu %ux%ux%u format %#x target %d levels %u storage %p", __func__, n, (unsigned long long)t->serial, t->d.width, t->d.height, t->d.depth, t->d.format, t->d.target, t->d.levels, (void *)t->mem); } + if (t->pool && t->mem && mt != reuse) objc_setAssociatedObject(mt, &g_tex_up_key, @[@((uint64_t)(uintptr_t)t->mem), @(t->L.size), @(t->pool->flags)], OBJC_ASSOCIATION_RETAIN_NONATOMIC); // the census: its storage res_add(mt); // Both first upload and re-upload register residency here (Metal 4 does not make resources resident automatically; a missed registration = GPU address page fault) + if (drop) { objc_setAssociatedObject(mt, &g_drop_key, @1, OBJC_ASSOCIATION_RETAIN_NONATOMIC); if (!reuse) g_drop_n++; } int sparse = t->pool && nvn_sparse_pool(t->pool); if (stamp) { // no stamp: a one-time upload of content the CPU will not change (tex_init_fill), with no write tracking *stamp = nvn_dirty_now(); if (sparse) nvn_sparse_protect(t->pool, (uint64_t)(uintptr_t)t->mem, t->L.size); else nvn_dirty_protect(t->mem, t->L.size); } int bw, bh, bpb = nvn_fmt_bpb(t->d.format, &bw, &bh); unsigned layers = (t->d.target == 4 || t->d.target == 9) ? t->d.depth : t->d.target == 8 ? 6 : t->d.target == 3 ? t->d.height : 1; // a cube array's depth counts layer-faces (tex_desc) - // Taken after the stamp and the protect: a write that lands from here on faults and is found at the next look + // Taken after the stamp and the protect: a write that lands from here on faults and is found at the next look. A texture that leaves out its largest level (drop) is read + // whole: pkg_written and the copies count Metal levels from the game's level 0 uint8_t *need = NULL; unsigned nimg = (unsigned)d.mipmapLevelCount * layers, nup = 0; - if (prev && prev != mt && stamp && !sparse && !linear && bpb && d.sampleCount <= 1 && prev.pixelFormat == mt.pixelFormat && prev.textureType == mt.textureType && prev.sampleCount == mt.sampleCount + if (prev && prev != mt && stamp && !sparse && !linear && !drop && bpb && d.sampleCount <= 1 && prev.pixelFormat == mt.pixelFormat && prev.textureType == mt.textureType && prev.sampleCount == mt.sampleCount && prev.width == mt.width && prev.height == mt.height && prev.depth == mt.depth && prev.arrayLength == mt.arrayLength && prev.mipmapLevelCount == mt.mipmapLevelCount) need = pkg_written(t, span, since, (unsigned)d.mipmapLevelCount, layers, &nup); if (need && nup == nimg) { free(need); need = NULL; } if (need && taken) *taken = nimg - nup; size_t total = 0; - for (unsigned l = 0; l < d.mipmapLevelCount; l++) { + for (unsigned l = drop; l < d.mipmapLevelCount + drop; l++) { // the game's levels: from 1 for a dropped texture, Metal level l - drop uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1; unsigned n = layers; if (need) { n = 0; for (unsigned y = 0; y < layers; y++) n += need[l * layers + y]; } total += (size_t)((w + bw - 1) / bw) * bpb * ((h + bh - 1) / bh) * z * n; @@ -3318,7 +3799,7 @@ static void rb_swap_rows(uint8_t *p, size_t wb, size_t rows, size_t nz, size_t r void *mb; uint64_t mo; // A texture in a large pool (BIG_MIN) or one that holds only textures is read through a buffer of its own, held by the upload batch: a one-time read must not leave that memory wired for good id upsrc = nil; unsigned src_batch = 0; // the upload batch that holds upsrc (g_up_seq) - if (!linear && !rb_shift && !sparse && g_nvn_deswz_gpu) { up_begin(); src_batch = g_up_seq; upsrc = up_big_src((uint64_t)t->mem, t->L.size, &mo); if (upsrc) mb = (__bridge void *)upsrc; } + if (!linear && !rb_shift && !sparse && g_nvn_deswz_gpu) { up_begin(); upsrc = up_big_src((uint64_t)t->mem, t->L.size, &mo, 1); src_batch = g_up_seq; if (upsrc) mb = (__bridge void *)upsrc; } // up_big_src may flush and begin a batch (its budget) t_tex_upload_lookup = 1; int use_gpu = !linear && !rb_shift && !sparse && g_nvn_deswz_gpu && (upsrc || mtl_addr((uint64_t)t->mem, t->L.size, &mb, &mo)); // a sparse pool's texture is gathered through its page table on the CPU t_tex_upload_lookup = 0; @@ -3346,16 +3827,16 @@ static void rb_swap_rows(uint8_t *p, size_t wb, size_t rows, size_t nz, size_t r id stg = up_alloc(total ? total : 16, &stg_off); // up_alloc may have flushed the batch that held the first source buffer: only then the new batch needs one of its own. Made for every texture, each staged upload from a large pool // put its storage twice into the residency set (Switch Sports Resort's first court frame: 855 textures, 1.8 GB of source buffers for 908 MB of storage; t_upload_src) - if (upsrc && g_up_seq != src_batch) { uint64_t mo2; id u2 = up_big_src((uint64_t)t->mem, t->L.size, &mo2); if (u2) { upsrc = u2; mb = (__bridge void *)u2; mo = mo2; } } + if (upsrc && g_up_seq != src_batch) { uint64_t mo2; id u2 = up_big_src((uint64_t)t->mem, t->L.size, &mo2, 0); if (u2) { upsrc = u2; mb = (__bridge void *)u2; mo = mo2; } } size_t off = 0; int enc_ok = g_up_ce != nil, nb0 = g_nup_blits; - for (unsigned l = 0; enc_ok && l < d.mipmapLevelCount; l++) { + for (unsigned l = drop; enc_ok && l < d.mipmapLevelCount + drop; l++) { uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1; size_t pitch = (size_t)((w + bw - 1) / bw) * bpb, rows = (h + bh - 1) / bh; for (unsigned y = 0; y < layers; y++) { if (need && !need[l * layers + y]) { up_copy_add(prev, MTLSizeMake(w, h, z), mt, y, l); continue; } size_t poff; id params = up_param_alloc(&poff); // Metal 4 has no setBytes: the parameter block of each deswizzle is cut from a shared block (no new GPU buffer each time) if (nvn_deswz_gpu_encode_m4(g_up_ce, g_up_ct, params, poff, (__bridge id)mb, mo, &t->d, l, y, stg, stg_off + off, pitch)) { enc_ok = 0; break; } - up_blit_add(stg, stg_off + off, pitch, pitch * rows, MTLSizeMake(w, h, z), mt, y, l); + up_blit_add(stg, stg_off + off, pitch, pitch * rows, MTLSizeMake(w, h, z), mt, y, l - drop); off += pitch * rows * z; } } @@ -3381,7 +3862,7 @@ static void rb_swap_rows(uint8_t *p, size_t wb, size_t rows, size_t nz, size_t r res_add(stg); [g_up_keep addObject:stg]; size_t off = 0; int zb = zblock_on() && t->d.format >= 0x79 && t->d.format <= 0x94; if (zb) { g_zb_ser = t->serial; g_zb_n = (int)MIN(d.mipmapLevelCount, 16u); memset(g_zb, 0, sizeof g_zb); memset(g_zb_tot, 0, sizeof g_zb_tot); } - for (unsigned l = 0; l < d.mipmapLevelCount; l++) { + for (unsigned l = drop; l < d.mipmapLevelCount + drop; l++) { uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1; size_t pitch = (size_t)((w + bw - 1) / bw) * bpb, rows = (h + bh - 1) / bh; for (unsigned y = 0; y < layers; y++) { @@ -3395,7 +3876,7 @@ static void rb_swap_rows(uint8_t *p, size_t wb, size_t rows, size_t nz, size_t r if (zb && l < 16) { const uint64_t *q = (const uint64_t *)((const uint8_t *)stg.contents + off); size_t nb = pitch * rows * z / 16; for (size_t i = 0; i < nb; i++) g_zb[l] += !(q[2 * i] | q[2 * i + 1]); g_zb_tot[l] += (uint32_t)nb; } - up_blit_add(stg, off, pitch, pitch * rows, MTLSizeMake(w, h, z), mt, y, l); + up_blit_add(stg, off, pitch, pitch * rows, MTLSizeMake(w, h, z), mt, y, l - drop); off += pitch * rows * z; } } @@ -4266,7 +4747,6 @@ static void cpu_unc_drop(void) { free(ser); } static id tex_mtl_(const tex_t *ct); -static id tex_mtl(const tex_t *ct) { AP_B; id r = tex_mtl_(ct); AP_E(4); return r; } // Diagnostic DM_NVN_REUPLOADS=1: a line for each re-upload of a texture taken from its storage (the first 400): its shape and size, how much of it was read from guest memory // (pkg_written), the time it took on the submit thread, the frame and the submission (a frame's replay is many, and each looks at the pages once), the pages written since its upload and where the first of them lies, // and the GPU writes stored into its storage since then (gsb_swz) @@ -4285,6 +4765,27 @@ static void reup_note(const NvPkg *pk, const tex_t *t, unsigned taken, uint64_t (unsigned long long)t->serial, t->d.width, t->d.height, t->d.depth, t->d.format, t->d.target, t->d.levels, t->L.size / 1048576.0, u, ns / 1e6, (unsigned long long)atomic_load(&g_cur_frame), (unsigned long long)g_sub_serial, w, pk->stored); } +// A dropped texture (drop_on) put to a use other than sampling is made whole on the spot, and stays whole: uploaded again with every level into its packaged record, which every +// serial and texture ID that names it follows (own_note, as tex_upgrade's replacement does). line: the caller's, counted in the memory report. Off the submit thread it is handed out as +// it is (only the submit thread uploads; the present thread only shows render targets) +static id tex_undrop(const tex_t *t, id r, int line) { + if (!tex_dropped(r) || (atomic_load(&g_sub_thread_set) && !on_sub_thread())) return r; + id h = tex_get(t->serial); NvPkg *pk = [h isKindOfClass:[NvPkg class]] ? h : nil; + if (!pk || pk->sparse || pk->ps) return r; + if (!g_drop_full) g_drop_full = [NSMutableSet set]; + [g_drop_full addObject:@((uintptr_t)t->mem)]; + uint64_t st, lg = atomic_load(&g_up_lost_gen); t_drop_off = 1; id nt = pkg_upload(t, &st, nil, pk->tex.usage, nil, NULL, 0, NULL); t_drop_off = 0; + if (!nt) { RED_ONCE(168, "a texture that left out its largest level could not be made whole again (ser=%llu %ux%u format %#x): kept smaller", (unsigned long long)t->serial, t->d.width, t->d.height, t->d.format); return r; } + id old = pk->tex; pk->tex = nt; pk->stored = 0; pk->part = 0; pk->lost_gen = lg; defer_obj_release(old); // read whole + if (pk->spare) { defer_obj_release(pk->spare); pk->spare = nil; } // of the smaller shape + pk->stamp = pk->seen = st; pk->span = nvn_dirty_span(t->mem, t->L.size); if (dirtycheck()) pk->hash = full_hash(t->mem, t->L.size); + own_note(t->serial); g_drop_full_n++; + int k = 0; while (k < 7 && g_drop_why[k].line && g_drop_why[k].line != line) k++; + if (!g_drop_why[k].n++) { g_drop_why[k].line = line; MLOG("a texture that left out its largest level is made whole for a use other than sampling (tex_mtl at line %d): ser=%llu %ux%u format %#x levels %u", line, (unsigned long long)t->serial, t->d.width, t->d.height, t->d.format, t->d.levels); } + return nt; +} +static id tex_mtl_at(const tex_t *ct, int line) { AP_B; id r = tex_mtl_(ct); if (r && g_drop_n && !t_drop_ok) r = tex_undrop(ct, r, line); AP_E(4); return r; } +#define tex_mtl(ct) tex_mtl_at((ct), __LINE__) // A sparse texture is bound from its first level whose pages, and those of every smaller level, are all mapped: a view of levels [r, n) samples as with a minimum LOD of r. // The translator drops TEX's LOD clamp and residency predicate, so Monster Hunter Rise's streamed textures were sampled at levels it had not mapped yet; those read 0, which ASTC // decodes as its error colour (magenta clothes on the title screen). Single-layer 2D textures only; the view follows each upload, as the mappings change only with one @@ -4301,6 +4802,109 @@ static void sparse_view(NvPkg *pk, const tex_t *t) { if (r != (unsigned)pk->vbase) { static int nl; if (nl++ < 6) MLOG("sparse texture ser=%llu %ux%u: sampled from level %u of %u (finer levels not mapped)", (unsigned long long)t->serial, t->d.width, t->d.height, r, n); } pk->vbase = (int)r; } +// GPU-only memory as on NVN: textures whose storage lies in a CPU_NO_ACCESS pool are placed in a placement heap that stands for an aligned span (window) of guest addresses, each at +// its own address's offset in it, so textures that share bytes on NVN share them here and the GPU memory they take is bounded by the spans used, not by the descriptions made. +// Ocarina of Time keeps its render targets in virtual pools (flags 0x2a1) over one 305 MB physical pool and describes the same bytes as targets of other sizes and formats from +// pass to pass and as its dynamic resolution moves: walking in Link's house, 400 Metal textures of 793 MB stood for 89 MB of NVN storage, and on an 8 GB iPad the residency set +// passed the GPU's working set going outside (docs/reference/memory.md). A texture goes there only if its Metal size fits within its NVN size and its offset meets Metal's alignment, +// so textures that do not overlap on NVN do not overlap here; any other keeps its own allocation (image_texture, then a texture of its own). A window heap lives while one of its +// textures does, and is made only once it saves memory: when a texture shares bytes with one made apart over its span, or those pass its size. Its memory starts as zeros: a texture over bytes no earlier texture of the window covered is zero-filled as before; one over covered bytes inherits them, as on NVN, +// and is not filled, as a fill would wipe a live alias in the earlier upload batch +enum { WIN_SHIFT = 25, WIN_SIZE = 1u << WIN_SHIFT }; // 32 MB spans +// Metal's size for a texture can pass NVN's (an RGBA8 1024x1024 target: 4,227,072 bytes against 4,194,304, its compression metadata), so the heap is the span scaled by 9/8 and a +// texture sits at its NVN offset scaled the same way (rounded up to Metal's alignment): it fits if it ends within its scaled NVN range +#define WIN_SCALE(x) ((uint64_t)(x) * 9 / 8) +#define WIN_HEAP ((NSUInteger)WIN_SCALE(WIN_SIZE)) +static NSMapTable *g_win; // window index → NvImageHeap (weak), under g_win_mu +static pthread_mutex_t g_win_mu = PTHREAD_MUTEX_INITIALIZER; +static char g_win_cov_key; // the owner's covered ranges (NSMutableData of rng_tab entries; under g_win_mu) +// On only where Metal's working set is too small for the render targets' separate heaps (rh_texture), which keep each texture's own layout and are the default elsewhere: a game +// that packs live targets into the part of a full-size target its current resolution leaves unused relies on NVN's layout (PR #1453), so sharing is the small device's choice, not +// everyone's. The numbers, Ocarina of Time on the M1 iPad (8 GB, working set 5,461 MB): with the separate heaps the residency set reached 5,184 MB at the outdoor save load (544 +// heaps, 1,384 MB, over 1,455 MB of textures) and every command buffer then failed out of memory; sharing held 4.3 GB outdoors for 30 minutes. So the separate heaps need about +// 5.2 GB plus what play outdoors adds (the set grew by up to 950 MB over a two-minute walk before sharing): under 8 GB of working set (8 GB devices: 5.3-5.5 GB) sharing is on; +// a 16 GB Mac (12,124 MB on an M4) keeps the separate heaps. DM_NVN_WINDOW_ALIAS=0 / 1 forces it off / on +enum { WIN_AUTO_BELOW_MB = 8192 }; +static int window_wants(uint64_t working_set) { return working_set && working_set < ((uint64_t)WIN_AUTO_BELOW_MB << 20); } +static int window_on(void) { + static int v = -1; + if (v < 0) { + const char *e = getenv("DM_NVN_WINDOW_ALIAS"); uint64_t ws = g_dev ? g_dev.recommendedMaxWorkingSetSize : 0; + v = e && *e ? atoi(e) > 0 : window_wants(ws); + MLOG("textures in GPU-only memory %s (window_texture; Metal's working set %llu MB, %s)", v ? "share bytes in a heap per 32 MB span" : "keep allocations of their own", + (unsigned long long)(ws >> 20), e && *e ? "DM_NVN_WINDOW_ALIAS" : v ? "under 8192 MB" : "8192 MB or more"); + } + return v; +} +static int window_ok(const tex_t *t) { + return t && t->pool && t->pool->mem && t->mem && (t->pool->flags & NVN_MEMORY_POOL_FLAGS_CPU_NO_ACCESS) && !nvn_sparse_pool(t->pool) && !t->has_layout && !t->d.stride + && !(t->d.flags & IMAGE_NOT_SHARED) && t->d.samples <= 1 && t->L.size && window_on(); +} +// Eligible textures made apart while a span has no heap: their bytes, by span, so a heap is made only once it saves memory (a span with a few small targets keeps them as they are) +static NSMutableDictionary *g_win_live; // under g_win_mu +static NSMutableDictionary *g_win_apart; // span → its textures made apart (weak NvWinLive), under g_win_mu +@interface NvWinLive : NSObject { @public uint64_t win, size; uintptr_t lo, hi; } @end +@implementation NvWinLive +- (void)dealloc { pthread_mutex_lock(&g_win_mu); NSNumber *k = @(win); uint64_t v = [g_win_live[k] unsignedLongLongValue]; v = v > size ? v - size : 0; if (v) g_win_live[k] = @(v); else [g_win_live removeObjectForKey:k]; pthread_mutex_unlock(&g_win_mu); } +@end +static char g_win_live_key; +static void window_note(id mt, const tex_t *t, uint64_t win, uint64_t size) { // mt was made apart over span win: count it until it goes + if (!mt || !size) return; + NvWinLive *l = [NvWinLive new]; l->win = win; l->size = size; l->lo = (uintptr_t)t->mem; l->hi = l->lo + t->L.size; + pthread_mutex_lock(&g_win_mu); if (!g_win_live) { g_win_live = [NSMutableDictionary dictionary]; g_win_apart = [NSMutableDictionary dictionary]; } + g_win_live[@(win)] = @([g_win_live[@(win)] unsignedLongLongValue] + size); + NSHashTable *ap = g_win_apart[@(win)]; if (!ap) g_win_apart[@(win)] = ap = [NSHashTable weakObjectsHashTable]; [ap addObject:l]; + pthread_mutex_unlock(&g_win_mu); + objc_setAssociatedObject(mt, &g_win_live_key, l, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} +// → the texture placed in its span's heap, or nil: then *note_size, if set, is what the caller notes (window_note) for the texture it makes apart +static id window_texture(const tex_t *t, MTLTextureDescriptor *gd, int *fill, uint64_t *note_win, uint64_t *note_size) { + *fill = 1; *note_size = 0; + if (!window_ok(t) || gd.storageMode != MTLStorageModePrivate) return nil; + // Without GPU-optimized contents. Textures that overlap here read each other's bytes, which on NVN mean the same thing (one block-linear layout) and in Metal do not: another + // description's writes leave a lossless-compressed texture's metadata invalid, and reading it is undefined. On the M1 iPad Ocarina of Time's GPU hung that way + // (kIOGPUCommandBufferCallbackErrorHang, a white flash, then GPU access revoked) turning the camera by Link's house, where its passes load targets that another format + // wrote over the same bytes in the same frame. Plain contents read as wrong values, as NVN's would after another format, but nothing the GPU can fail on + MTLTextureDescriptor *d = [gd copy]; d.allowGPUOptimizedContents = NO; + MTLSizeAndAlign need = [g_dev heapTextureSizeAndAlignWithDescriptor:d]; + // A span is keyed by its index times 2; one across a span's end tries the spans offset by half a span (odd keys). Textures in different heaps do not share bytes, as before + uintptr_t a = (uintptr_t)t->mem, rel = 0; uint64_t win = 0, lo = 0; int why = 0; + for (int half = 0; half < 2; half++) { + uintptr_t b = a - (half ? WIN_SIZE / 2 : 0); rel = b & (WIN_SIZE - 1); win = (uint64_t)(b >> WIN_SHIFT) << 1 | (uint64_t)half; + lo = need.align ? (WIN_SCALE(rel) + need.align - 1) / need.align * need.align : 0; // its NVN range scaled: containment and overlaps as on NVN + why = !need.size || !need.align ? 0 : lo + need.size > WIN_SCALE(rel + t->L.size) ? 1 : lo + need.size > WIN_HEAP ? 2 : -1; + if (why != 2) break; + } + if (why >= 0) { atomic_fetch_add(&g_win_fit[why], 1); atomic_fetch_add(&g_win_fit_b[why], need.size); return nil; } + pthread_mutex_lock(&g_win_mu); + if (!g_win) g_win = [NSMapTable strongToWeakObjectsMapTable]; + NvImageHeap *owner = [g_win objectForKey:@(win)]; + if (!owner && [g_win_live[@(win)] unsignedLongLongValue] + need.size <= WIN_HEAP) { // apart, until a heap would save memory: the span's live textures pass its size, or this one shares bytes with one of them + int shares = 0; for (NvWinLive *l in g_win_apart[@(win)]) if (l->lo < a + t->L.size && a < l->hi) { shares = 1; break; } + if (!shares) { pthread_mutex_unlock(&g_win_mu); *note_win = win; *note_size = need.size; return nil; } + } + if (!owner) { + MTLHeapDescriptor *hd = [MTLHeapDescriptor new]; hd.type = MTLHeapTypePlacement; hd.size = WIN_HEAP; + hd.storageMode = MTLStorageModePrivate; hd.cpuCacheMode = d.cpuCacheMode; hd.hazardTrackingMode = d.hazardTrackingMode; + id heap = [g_dev newHeapWithDescriptor:hd]; + if (!heap) { pthread_mutex_unlock(&g_win_mu); atomic_fetch_add(&g_win_fit[3], 1); atomic_fetch_add(&g_win_fit_b[3], need.size); return nil; } + owner = [NvImageHeap new]; owner->heap = heap; owner->window = 1; atomic_fetch_add(&g_image_heap_n, 1); + objc_setAssociatedObject(owner, &g_win_cov_key, [NSMutableData data], OBJC_ASSOCIATION_RETAIN_NONATOMIC); + [g_win setObject:owner forKey:@(win)]; + static int nl; if (nl++ < 8) MLOG("GPU-only memory %#llx..%#llx: textures there share a %lu MB placement heap at their own offsets (window_texture)", (unsigned long long)(((win >> 1) << WIN_SHIFT) + (win & 1) * WIN_SIZE / 2), (unsigned long long)(((win >> 1) << WIN_SHIFT) + (win & 1) * WIN_SIZE / 2 + WIN_SIZE), (unsigned long)(WIN_HEAP >> 20)); + } + id mt = [owner->heap newTextureWithDescriptor:d offset:lo]; + if (mt) { // covered before: inherit the bytes; else zero-fill (fill stays 1) + NSMutableData *cov = objc_getAssociatedObject(owner, &g_win_cov_key); rng_tab tab = {cov.mutableBytes, (int)(cov.length / sizeof *tab.r), (int)(cov.length / sizeof *tab.r)}; + if (rng_overlap(&tab, lo, lo + need.size)) *fill = 0; + rng_tab grown = {NULL, 0, 0}; for (int i = 0; i < tab.n; i++) rng_put(&grown, tab.r[i].lo, tab.r[i].hi); rng_put(&grown, lo, lo + need.size); + [cov setLength:0]; if (grown.n) [cov appendBytes:grown.r length:(size_t)grown.n * sizeof *grown.r]; free(grown.r); + objc_setAssociatedObject(mt, &g_image_heap_owner_key, owner, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + atomic_fetch_add(&g_win_n, 1); atomic_fetch_add(&g_win_bytes, need.size); + } + pthread_mutex_unlock(&g_win_mu); + return mt; +} static uint64_t g_texinfo_ser[8]; static int g_texinfo_n; // Distinct compressible image descriptions at one NVN address alias physical memory, even while all their descriptor objects are live (LM3's resolution families). // Single-description storage keeps the ordinary allocation. Families share an exact-sized placement heap, found through the existing alias table rather than a pool-lifetime owner. @@ -4323,7 +4927,7 @@ static void sparse_view(NvPkg *pk, const tex_t *t) { NvImageHeap *o = objc_getAssociatedObject(other, &g_image_heap_owner_key); // Metal omits ShaderAtomic from usage; tex_desc gives every writable R32 integer image that capability. MTLTextureUsage usage = other.usage | (tex_atomic_capable(other) ? MTLTextureUsageShaderAtomic : 0); - if (o && o->heap.size >= need.size && usage == d.usage && (!owner || o->heap.size < owner->heap.size)) owner = o; + if (o && !o->window && o->heap.size >= need.size && usage == d.usage && (!owner || o->heap.size < owner->heap.size)) owner = o; }); if (!owner) for (uint32_t i = 0; i < g_image_desc.cap; i++) if (g_image_desc.vals[i]) { const tex_t *other = g_image_desc.vals[i]; @@ -4420,6 +5024,7 @@ static void sparse_view(NvPkg *pk, const tex_t *t) { if (!pk) { id made = nil; NvSparse *ps = sparse_make(t, 0, &made); if (ps) { pk = [NvPkg new]; pk->ps = ps; pk->tex = made; pk->sparse = 1; sparse_sync(ps, t, 1); tex_put(t->serial, pk); return pk->tex; } } if (pk) { // Already uploaded: check the covered pages only if there has been a guest write since the last check + if (!t_pool_walk) pk->used_s = g_use_now; // a walk's lookup is not a use // Off the submit thread (the present thread) it is used as it is: only the submit thread may upload (up_owner_check), and a present shows the content as of when the game // queued it, which present_enqueue resolved there. Its pages are not looked at here, so the submit thread's next look still finds a write since (pk->seen stays) if (atomic_load(&g_sub_thread_set) && !on_sub_thread()) return pk->view ? pk->view : pk->tex; @@ -4467,11 +5072,11 @@ static void sparse_view(NvPkg *pk, const tex_t *t) { if (pk->spare && pk->spare != nt) defer_obj_release(pk->spare); // still in use, or of another shape: retired as before if (pk->sparse) sparse_view(pk, t); zb_report(t, pk->sparse ? (unsigned)pk->vbase : 0, "re-upload"); - pk->spare = old; pk->spare_fence = g_fence + 1; own_note(t->serial); pk->stamp = st; pk->vgen = pk->vseen = vg; pk->span = nvn_dirty_span(t->mem, t->L.size); pk->seen = st; g_pkg_reuploads++; if (dirtycheck() && !pk->sparse) pk->hash = full_hash(t->mem, t->L.size); pkg_edges_take(pk, t); } + pk->spare = old; pk->spare_fence = g_fence + 1; spare_note(pk); own_note(t->serial); pk->stamp = st; pk->vgen = pk->vseen = vg; pk->span = nvn_dirty_span(t->mem, t->L.size); pk->seen = st; g_pkg_reuploads++; if (dirtycheck() && !pk->sparse) pk->hash = full_hash(t->mem, t->L.size); pkg_edges_take(pk, t); } return pk->view ? pk->view : pk->tex; } pk = [NvPkg new]; - pk->sparse = t->pool && nvn_sparse_pool(t->pool); pk->vgen = pk->vseen = nvn_sparse_gen(); + pk->sparse = t->pool && nvn_sparse_pool(t->pool); pk->vgen = pk->vseen = nvn_sparse_gen(); pk->used_s = g_use_now; pk->mem = (uintptr_t)t->mem; pk->size = t->L.size; pk->lost_gen = atomic_load(&g_up_lost_gen); if (!pk->sparse) { pk->sub = g_sub_serial; pk->own = nvn_dirty_own_writes(); } pk->tex = pkg_upload(t, &pk->stamp, nil, 0, nil, NULL, 0, NULL); @@ -4546,9 +5151,12 @@ static void sparse_view(NvPkg *pk, const tex_t *t) { if (!mt) { MTLTextureDescriptor *d = tex_desc(t, 0); if (!d) return nil; - mt = image_texture(t, d); + int wfill = 1; uint64_t wwin = 0, wsize = 0; mt = window_texture(t, d, &wfill, &wwin, &wsize); // on a small device only (window_on) + if (mt) { res_add(mt); if (wfill && !tex_init_fill(t, mt)) tex_zero_fill(mt); } + if (!mt) mt = image_texture(t, d); if (!mt) { mt = rh_texture(t, d); if (!mt) mt = [g_dev newTextureWithDescriptor:d]; if (mt) { res_add(mt); if (!tex_init_fill(t, mt)) tex_zero_fill(mt); } } + if (mt && wsize) window_note(mt, t, wwin, wsize); if (!mt) { RED_ONCE(2, "failed to create MTLTexture %ux%u format %#x target %d", t->d.width, t->d.height, t->d.format, t->d.target); return nil; } } if (mt.allocatedSize >= (256u << 20)) { static int nb; if (nb++ < 20) // the textures that take most of the GPU's memory (a GPU out-of-memory error says nothing of which) @@ -4557,6 +5165,7 @@ static void sparse_view(NvPkg *pk, const tex_t *t) { if (g_allocprof > 0) { static int n; if (n++ < 30 || n % 500 == 0) MLOG("new texture (%s) #%d ser=%llu %ux%ux%u format %#x target %d levels %u storage %p", __func__, n, (unsigned long long)t->serial, t->d.width, t->d.height, t->d.depth, t->d.format, t->d.target, t->d.levels, (void *)t->mem); } if (getenv("DM_NVN_TEXCPU") && t->pool && !(t->pool->flags & NVN_MEMORY_POOL_FLAGS_CPU_NO_ACCESS)) MLOG("non-swizzled texture on a CPU-visible pool ser=%llu %ux%ux%u format %#x target %d levels %u texture flags %#x pool flags %#x storage %p", (unsigned long long)t->serial, t->d.width, t->d.height, t->d.depth, t->d.format, t->d.target, t->d.levels, t->d.flags, t->pool->flags, (void *)t->mem); res_add(mt); + if (t->pool && t->mem) objc_setAssociatedObject(mt, &g_tex_range_key, @[@((uint64_t)(uintptr_t)t->mem), @(t->L.size), @(t->pool->flags)], OBJC_ASSOCIATION_RETAIN_NONATOMIC); // res_top: its storage // The takeover of the storage, the entry and the serial's publication in one hold (nvn_owner.m). A texture another thread registered under the key since the lookup above is the // one the storage's serials share: this one is retired id got = own_alias_publish(t->serial, &ak, mt); @@ -4567,9 +5176,13 @@ static void sparse_view(NvPkg *pk, const tex_t *t) { // Purpose: pin down "crashes with no log". The system gives no notice before killing a process for memory, so only readouts left beforehand can show which number kept climbing. // Called by the frame hook every 300 frames; printed only when resident or GPU allocated changed by ≥ 64 MB since the last line, otherwise one line every 3000 frames; capped at 400 lines per game. All integers (the frame hook runs on the guest thread's small stack, so no floating-point formatting) void mtl_mem_stat(unsigned long long frame, unsigned long long rss_mb) { - static unsigned long long last_rss, last_gpu, last_frame; static int lines; unsigned long long gpu = (unsigned long long)(g_dev.currentAllocatedSize >> 20); - unsigned long long dr = rss_mb > last_rss ? rss_mb - last_rss : last_rss - rss_mb, dg = gpu > last_gpu ? gpu - last_gpu : last_gpu - gpu; - if (lines >= 400 || (lines && dr < 64 && dg < 64 && frame - last_frame < 3000)) return; lines++; last_rss = rss_mb; last_gpu = gpu; last_frame = frame; + static unsigned long long last_rss, last_gpu, last_frame, last_wired; static int lines; unsigned long long gpu = (unsigned long long)(g_dev.currentAllocatedSize >> 20); + sys_mem_t sm = sys_mem(); + unsigned long long dr = rss_mb > last_rss ? rss_mb - last_rss : last_rss - rss_mb, dg = gpu > last_gpu ? gpu - last_gpu : last_gpu - gpu, dw = sm.wired > last_wired ? sm.wired - last_wired : last_wired - sm.wired; + // Also when the system's wired memory moved by 256 MB or a memory pressure event came (the phone's death showed no line in its last 1,300 frames: nothing of the app's own had moved). + // Not on low free memory alone: the Mac keeps little free, which would print every time + static uint64_t last_ev; uint64_t ev = atomic_load(&g_mp_n[0]) + atomic_load(&g_mp_n[1]) + atomic_load(&g_mp_n[2]); + if (lines >= 400 || (lines && dr < 64 && dg < 64 && dw < 256 && ev == last_ev && frame - last_frame < 3000)) return; lines++; last_rss = rss_mb; last_gpu = gpu; last_frame = frame; last_wired = sm.wired; last_ev = ev; pthread_mutex_lock(&g_deferred_mu); unsigned long nd = (unsigned long)g_deferred.count; pthread_mutex_unlock(&g_deferred_mu); pthread_mutex_lock(&g_res_mu); unsigned long nr = (unsigned long)g_res_objects.count; pthread_mutex_unlock(&g_res_mu); int live = 0, peak = 0, cap = 0; nvn_dirty_stat(&live, &peak, &cap); @@ -4587,6 +5200,10 @@ void mtl_mem_stat(unsigned long long frame, unsigned long long rss_mb) { #endif MLOG("memory up to frame %llu: resident %llu MB, GPU allocated %llu MB, deferred-release queue %lu, residency set %lu, serial objects %u, memory pools %d (resident %d; peak %d / tracking table capacity %d; freed but alive %lu, %llu MB), shared textures %u (%u of them unreferenced; evicted with pools %llu, on storage takeover %llu in total), texture re-uploads %llu in total, per-frame arena blocks created %llu in total, finalized textures still referenced %u (small table, %llu put in total), retired but held by a serial %u, recycled texture heaps made %llu, reused %llu, freed %llu, waiting %u (%llu MB); headroom to the system memory limit %s", frame, rss_mb, gpu, nd, nr, ns, live, pres, peak, cap, dead_n, dead_mb, ashared, aorph, (unsigned long long)as.evicted, (unsigned long long)as.taken, (unsigned long long)g_pkg_reuploads, (unsigned long long)g_arena_made, nghost, (unsigned long long)ghost_puts, nwait, (unsigned long long)g_rh_made, (unsigned long long)g_rh_reused, (unsigned long long)g_rh_trimmed, rh_n, (unsigned long long)(rh_bytes >> 20), avail); + if (sm.ok) { char pl[160]; mem_pressure_said(pl, sizeof pl); + MLOG("system memory at frame %llu: free %llu MB, wired %llu MB, compressed %llu MB, file-backed %llu MB, purgeable %llu MB, of %llu MB; residency set %llu MB; %s", frame, + (unsigned long long)sm.free, (unsigned long long)sm.wired, (unsigned long long)sm.compressed, (unsigned long long)sm.file, (unsigned long long)sm.purgeable, (unsigned long long)sm.total, + (unsigned long long)(g_res ? g_res.allocatedSize >> 20 : 0), pl); } { void mtl_vc_stats(unsigned *, uint64_t *, uint64_t *), mtl_tb2_stats(uint64_t *, uint64_t *, uint64_t *, uint64_t *, uint64_t *); uint64_t mtl_tex_mis_count(void); unsigned vn; uint64_t vh, vm, tb, tm, tf, tc, tcb; mtl_vc_stats(&vn, &vh, &vm); mtl_tb2_stats(&tb, &tm, &tf, &tc, &tcb); MLOG("texture views by texture (vc_get): %u textures hold cached views; %llu views reused, %llu made in total; texture buffers bound as 2D rows for wrapped 1D fetches %llu times, %llu made, %llu failed, %llu copied into aligned rows (%llu MB) " @@ -4613,8 +5230,18 @@ void mtl_mem_stat(unsigned long long frame, unsigned long long rss_mb) { MLOG("GPU allocation growth by op: op%d %llu MB, op%d %llu MB, op%d %llu MB, op%d %llu MB", top[0], g_ap_bytes[top[0]] >> 20, top[1], g_ap_bytes[top[1]] >> 20, top[2], g_ap_bytes[top[2]] >> 20, top[3], g_ap_bytes[top[3]] >> 20); } { void mtl_gmem_words(uint64_t *, uint64_t *, uint64_t *); uint64_t gw, go, gb; mtl_gmem_words(&gw, &go, &gb); if (gw) MLOG("raw pool table words at commit: %llu, of them %llu held an older table than the current one and %llu the current one behind the pools", (unsigned long long)gw, (unsigned long long)go, (unsigned long long)gb); } + if (g_drop_on > 0) { // smaller textures (drop_on): what was saved, what was made whole and where, and what each threshold would take (candidates by their largest side) + char why[160] = ""; size_t o = 0; for (int k = 0; k < 8 && g_drop_why[k].n && o < sizeof why - 24; k++) o += (size_t)snprintf(why + o, sizeof why - o, "%sline %d: %llu", k ? ", " : "", g_drop_why[k].line, (unsigned long long)g_drop_why[k].n); + MLOG("[mem] large sampled textures without their largest level: %llu, %llu MB saved; made whole again %llu (%s); candidates by largest side 256: %llu, %llu MB; 512: %llu, %llu MB; 1024: %llu, %llu MB; 2048+: %llu, %llu MB", + (unsigned long long)g_drop_n, (unsigned long long)(g_drop_bytes >> 20), (unsigned long long)g_drop_full_n, o ? why : "none", + (unsigned long long)g_drop_cand_n[0], (unsigned long long)(g_drop_cand_b[0] >> 20), (unsigned long long)g_drop_cand_n[1], (unsigned long long)(g_drop_cand_b[1] >> 20), + (unsigned long long)g_drop_cand_n[2], (unsigned long long)(g_drop_cand_b[2] >> 20), (unsigned long long)g_drop_cand_n[3], (unsigned long long)(g_drop_cand_b[3] >> 20)); + MLOG("[mem] large sampled textures kept whole, by the first rule they fail (256 and more): type %llu, one level %llu, samples / linear / repack %llu, sparse pool %llu, render-target usage %llu, flags %llu (%#x), depth %llu, made whole before %llu", + (unsigned long long)g_drop_no[0], (unsigned long long)g_drop_no[1], (unsigned long long)g_drop_no[2], (unsigned long long)g_drop_no[3], (unsigned long long)g_drop_no[4], (unsigned long long)g_drop_no[5], g_drop_no_flags, (unsigned long long)g_drop_no[6], (unsigned long long)g_drop_no[7]); + } } void mtl_pkg_stats(uint64_t *uploads, uint64_t *reuploads) { *uploads = g_pkg_uploads; *reuploads = g_pkg_reuploads; } +void mtl_spare_stats(uint64_t *held, uint64_t *trimmed, uint64_t *trimmed_mb) { *held = atomic_load(&g_spare_held); *trimmed = atomic_load(&g_spare_trimmed); *trimmed_mb = atomic_load(&g_spare_trimmed_bytes) >> 20; } uint64_t mtl_pkg_edge_skips(void) { return g_pkg_edge_skips; } uint64_t mtl_pkg_miss(void) { return g_pkg_miss; } void mtl_vc_drop(uint64_t ser); @@ -6348,9 +6975,13 @@ void mtl_prog_snapshot(prog_t *copy,const prog_t *source) { typedef struct { tex_t t; int ok; view_t v; int has_v; void *view; uint64_t view_id, view_rid, view_ser, view_dirty, view_stamp; const void *view_span; int view_pkg; // view_pkg: CPU-written (packaged); only those depend on guest writes (view_dirty) void *alt, *alt_of; uint64_t alt_rid; uint8_t alt_type; // alt: compatible view used when the shader's declared type differs from view (tex_fit), alt_of = the view it was built from void *im, *im_of; uint64_t im_rid; // im: the view an image slot reads in the shader's pixel class (img_fit), im_of = the view it was built from - int prev, next, retired, gone; uint64_t transient_sub; uint8_t tt1; // prev / next: descriptor index + 1, by texture serial; gone: its memory pool was finalized (treg_drop_pool_views) + int prev, next, retired, gone; uint64_t transient_sub; uint8_t tt1, evicted; // prev / next: descriptor index + 1, by texture serial; gone: its memory pool was finalized (treg_drop_pool_views) void *stand; uint64_t stand_rid, stand_sum, reg_frame; uint8_t stand_tt1, stand_no; } treg_t; // stand: what its pool table entries hold while its texture is not made (pool_stand; retained), stand_tt1 its texture type + 1, stand_no: it can have none; reg_frame: the frame of the registration +// evicted: its packaged texture's copy was freed at memory pressure (pkg_evict_idle): a pool walk leaves it its stand-in or the dummy until a shader reads it or something else makes it static treg_t *g_treg; static int g_ntreg; +// When each texture ID was last used, in seconds of the host's clock (g_use_now, set at each submission's start): a bind that resolves it (tex_fast_rid, not a pool walk's) or a shader's +// read through a pool (pool_seen_scan, from the read bitmap, which is cleared every POOL_SEEN_EPOCH_S so a read sets its bit again). What pkg_evict_idle judges idleness by +static uint32_t g_tid_used[1 << 20]; static nvn_hmap g_treg_serial = {.klen = 8}; // serial → first registered descriptor index + 1, under g_rmu // Texture ID views are valid for an epoch (view_ser), not for every serial table change: ser_sync takes the notes (own_note) and sends only the IDs registered with a noted serial // down the slow path; a change without a note starts a new epoch, which sends them all (what every g_ser_gen bump did before). A battle map in Fire Emblem: Fortune's Weave changes a @@ -6615,7 +7246,7 @@ void mtl_reg_tex(int tid, const tex_t *t, const view_t *v) { treg_unlink(id_); treg_drop_views(rr); treg_drop_stand(rr); rr->tt1 = 0; rr->reg_frame = atomic_load(&g_cur_frame); rr->ok = t != NULL; if (t) rr->t = *t; rr->has_v = v != NULL; if (v) rr->v = *v; - rr->retired = 0; rr->transient_sub = 0; + rr->retired = 0; rr->transient_sub = 0; rr->evicted = 0; if (t && t->serial) { rr->retired = !own_tex_live(t->serial); rr->next = (int)(uintptr_t)nvn_hm_get(&g_treg_serial, &t->serial); @@ -6685,7 +7316,7 @@ static MTLTextureType ttype(int target, int fallback) { static int g_queue_origin_ll; // SET_WINDOW_ORIGIN's raster flip is queue state, independent of later device-origin changes. void mtl_set_queue_origin_lower_left(int on) { g_queue_origin_ll = on != 0; } void mtl_set_tex_pool_n(int n) { g_tpool_n = n; } -static id treg_tex(const treg_t *r) { return r->gone ? tex_made(&r->t) : tex_mtl(&r->t); } // Caller holds g_rmu +static id treg_tex(const treg_t *r) { if (r->gone) return tex_made(&r->t); t_drop_ok++; id m = tex_mtl(&r->t); t_drop_ok--; return m; } // sampled: may be dropped (drop_on) // Caller holds g_rmu // The upload stamp of the packaged texture an ID's view was made from (tex_by_id's guest-write shortcut); none for sparse ones (their page table changes too) or another base. Caller holds g_rmu static void treg_pkg_stamp(treg_t *rp, id base) { rp->view_span = NULL; if (!rp->view_pkg) return; @@ -6767,6 +7398,7 @@ static int treg_swizzle(const treg_t *r, MTLPixelFormat base_pf, int in_place, u sg = treg_ep(); } NSUInteger l0 = r.v.set_levels ? r.v.base_level : 0, nl = r.v.set_levels && r.v.nlevels ? r.v.nlevels : base.mipmapLevelCount - l0; + if (r.v.set_levels && g_drop_n && tex_dropped(base)) { drop_levels(&l0, &nl); if (!r.v.nlevels) nl = base.mipmapLevelCount - MIN(l0, base.mipmapLevelCount); } // the game's level k is Metal's k-1 if (l0 >= base.mipmapLevelCount) { RED_ONCE(109, "texture view id %d starts at mip %lu beyond %lu levels", tid, (unsigned long)l0, (unsigned long)base.mipmapLevelCount); return nil; } // A level count past the texture's levels is cut to those it has, as deko3d's Tegra descriptor writer clips the maximum level (Echoes of Wisdom: levels 1 + 7 of a seven-level texture, // which Metal's validation refuses) @@ -6969,6 +7601,7 @@ static void img_fit_upgrade(void) { } static inline __attribute__((always_inline)) uint64_t tex_fast_rid(int tid, void **out) { uint64_t ep = treg_ep(); // first, as in tex_fast + if (!t_pool_walk && (unsigned)tid < (1u << 20)) g_tid_used[tid] = g_use_now; if (tid > 0 && tid < g_ntreg && g_treg[tid].ok && g_treg[tid].view && g_treg[tid].view_ser == ep && (!g_treg[tid].view_pkg || g_treg[tid].view_dirty == nvn_dirty_now())) { if (out) *out = g_treg[tid].view; return g_treg[tid].view_rid; } id t = tex_by_id(tid); if (out) *out = (__bridge void *)t; if (t && tid > 0 && tid < g_ntreg && (__bridge void *)t == g_treg[tid].view) return g_treg[tid].view_rid; // the view tex_by_id kept: its resource ID without a message per ID (pool_gpu) @@ -7420,6 +8053,7 @@ static void queue_program_preserve(void) { S.cprog=index[5]<0?NULL:&q->programs[index[5]]; S.prog=bind_stages(NULL,0); args_dirty_all(); } void mtl_queue_activate(uint64_t serial) { // caller holds the submission lock + g_gt_queue = serial; if (g_active_queue && g_active_queue->serial == serial) return; if (g_active_queue) { g_active_queue->s = S; g_active_queue->r = R; g_active_queue->rc_skip=g_rc_skip; } queue_state *q = g_queue_states; @@ -10444,6 +11078,11 @@ static void pool_first_read(int id_, uint64_t f) { (unsigned long long)f, id_, r->stand ? (stale ? "its stand-in, written since" : "its stand-in") : r->stand_no ? "the dummy (no stand-in for it)" : "the dummy", (unsigned long long)t->serial, t->d.width, t->d.height, t->d.format, t->d.target, t->d.levels, t->d.flags, (unsigned long long)(pool_tex_size(t) >> 10), (unsigned long long)(f - r->reg_frame), r->has_v, r->v.set_format, r->v.format, r->v.set_levels, r->v.base_level, r->v.nlevels, r->v.set_layers, r->v.min_layer, r->v.nlayers, r->v.set_target, r->v.target, r->v.set_swizzle); } +// The read bitmap is cumulative (g_seen_done), which says what to make, not what is still read. So every POOL_SEEN_EPOCH_S the shaders' copy of the bits already folded in is cleared: a shader +// sets an ID's bit again at its next read, which stamps the ID's use (g_tid_used) at the next scan, and a bit set between the scan's read and the clear is lost for that one read. g_seen_ep holds +// the bits seen since the clear +enum { POOL_SEEN_EPOCH_S = 10 }; +static uint32_t g_seen_ep[POOL_SEEN_WORDS], g_seen_ep_t; static void pool_seen_scan(void) { if (!g_seen_buf || g_seen_sub == g_sub_serial) return; g_seen_sub = g_sub_serial; @@ -10455,6 +11094,11 @@ static void pool_seen_scan(void) { (unsigned long long)f, (unsigned long long)g_stand_made, g_stand_ns / 1e6, (unsigned long long)g_stand_picked, (unsigned long long)g_stand_done, (unsigned long long)g_stand_live, g_nstand_heap, (unsigned)(STAND_HEAP >> 20), (unsigned long long)g_stand_full, g_stand_todo_n, (unsigned long long)g_first_stand, g_first_stale ? [NSString stringWithFormat:@" (%llu written since the stand-in was made)", (unsigned long long)g_first_stale].UTF8String : "", (unsigned long long)g_first_dummy, (unsigned long long)g_first_dummy_big); } } const uint32_t *w = (const uint32_t *)g_seen_buf.contents; unsigned words = MIN((unsigned)g_ntreg / 32 + 1, (unsigned)POOL_SEEN_WORDS); + for (unsigned i = 0; i < words; i++) { uint32_t again = w[i] & ~g_seen_ep[i]; if (!again) continue; g_seen_ep[i] |= again; + for (uint32_t bits = again; bits; bits &= bits - 1) g_tid_used[i * 32 + (unsigned)__builtin_ctz(bits)] = g_use_now; } + if (g_use_now - g_seen_ep_t >= POOL_SEEN_EPOCH_S) { // only the bits already folded in (g_seen_done): a fresh one is still to be taken below + g_seen_ep_t = g_use_now; memset(g_seen_ep, 0, words * 4); + uint32_t *bw = (uint32_t *)g_seen_buf.contents; for (unsigned i = 0; i < words; i++) if (bw[i] & g_seen_done[i]) bw[i] &= ~g_seen_done[i]; } for (unsigned i = 0; i < words; i++) { uint32_t fresh = w[i] & ~g_seen_done[i]; if (fresh) { g_seen_done[i] |= fresh; g_seen_todo[i] |= fresh; for (uint32_t bits = fresh; bits; bits &= bits - 1) { pool_ds_note((int)i * 32 + __builtin_ctz(bits)); pool_first_read((int)i * 32 + __builtin_ctz(bits), f); } } @@ -10503,16 +11147,82 @@ static uint64_t pool_entry(int samp, int dtt, int id_, uint64_t limit, int *gone if (r->gone) { ++*gone; return 0; } if (!r->view && !tex_storage_live(&r->t)) { ++*gone; *dead = 1; return 0; } if (!r->view && pool_unwritten_target(&r->t)) return 0; // dummy until a pass writes it (its new texture is noted: own_note) + if (r->evicted && !r->view && !pool_seen(id_) && !tex_get(r->t.serial) && !pkg_shared(&r->t)) return pool_stand(id_, dtt); // freed at memory pressure: made again when a shader reads it, not up front if (!r->view && pool_tex_size(&r->t) > limit && !pkg_shared(&r->t) && !tex_get(r->t.serial) && !(pool_seen(id_) && g_walk_req < POOL_REQ_BYTES)) { ++*left; *left_req += pool_seen(id_); return pool_stand(id_, dtt); } // a texture a shader read is made whatever the budget, so it reads its stand-in or the dummy for a few frames at most if (r->tt1 && r->tt1 - 1 != dtt) return 0; // an ID of another texture type, seen before (the table holds only its own type): nothing to look up or charge (the idea is from PR 1428) if (!r->view && !pkg_shared(&r->t)) { g_walk_spent += pool_tex_size(&r->t); if (pool_seen(id_)) g_walk_req += pool_tex_size(&r->t); } - void *tv = NULL; uint64_t tr = tex_fast_rid(id_, &tv); + void *tv = NULL; t_pool_walk = 1; uint64_t tr = tex_fast_rid(id_, &tv); t_pool_walk = 0; // a walk's lookup is not a use (g_tid_used) if (!tv) return 0; MTLTextureType got = ((__bridge id)tv).textureType; g_treg[id_].tt1 = (uint8_t)got + 1; if (got != (MTLTextureType)dtt) return 0; if (g_treg[id_].retired && g_treg[id_].transient_sub == g_sub_serial) *transient = 1; return tr; } +// Memory pressure: the Metal copies of uploaded textures nothing has used for PKG_IDLE_S. On NVN such a texture costs nothing beyond its pool; here it is a Metal copy, and a game keeps the +// texture objects of an area it has left: on the iPhone 17 these copies held 0.6-1.0 GB of Ocarina of Time's residency set, all named by live descriptors of texture objects the game had +// not finalized. A package (NvPkg) goes when no texture ID naming one of its serials was used for PKG_IDLE_S (a bind's lookup, a shader's read through a pool: g_tid_used) and nothing +// resolved it either (used_s), when it is no sparse, placed or bound-as-view texture, the GPU never wrote its storage (gws_owned) nor stored its own writes into it (stored: the storage is +// then the content, so the next use uploads it again) and no pin, sharing-table entry or serial that took its texture over holds it. Everything that names the copy lets go at once: its serials' entries (live and finalized), its +// storage's sharing entry (g_pkg_share), each texture ID's views, the view cache, and the IDs' entries in the pool tables, which their next use patches to the dummy (a draw already encoded +// keeps the old table and the texture: it is retired through deferred release, after the submissions that used it). A pool walk leaves the ID its stand-in (pool_stand) or the dummy until a shader reads it (treg_t evicted), +// and the first read after the eviction finds that for a frame, as any texture's first read does; a bind makes it again at once. Hence at memory pressure only (mem_trim). Submit thread +enum { PKG_IDLE_S = 30 }; +static _Atomic uint64_t g_evict_n, g_evict_bytes; +static uint64_t pkg_evict_idle(unsigned *n_out) { @autoreleasepool { + unsigned n = 0; uint64_t bytes = 0; uint32_t now = g_use_now; + if (n_out) *n_out = 0; + // The packages, each once, with the newest use of the IDs that name their serials + NSMutableArray *pkgs = [NSMutableArray array]; NSHashTable *seen = [NSHashTable hashTableWithOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality]; + nvn_hmap last = {.klen = sizeof(uintptr_t)}; // package address → newest use + nvn_hmap byser_m = {.klen = 8}, *byser = &byser_m, *lastp = &last; // serial → its package (a live entry before a ghost one, as a lookup resolves), not retained: the tables hold them under g_smu. + // The block reaches both maps through pointers: a block captures a local struct as a copy + os_unfair_lock_lock(&g_rmu); pthread_mutex_lock(&g_smu); + own_each_locked(^(uint64_t serial, id o, int ghost) { + if (![o isKindOfClass:[NvPkg class]]) return; + if (!ghost || !nvn_hm_get(byser, &serial)) nvn_hm_put(byser, &serial, (__bridge void *)o); + if ([seen containsObject:o]) return; + [seen addObject:o]; [pkgs addObject:o]; uintptr_t k = (uintptr_t)(__bridge void *)o; nvn_hm_put(lastp, &k, (void *)(uintptr_t)(((NvPkg *)o)->used_s + 1ull)); }); + for (int i = 1; i < g_ntreg && i < (1 << 20); i++) { treg_t *r = &g_treg[i]; if (!r->ok || !r->t.serial) continue; + id o = (__bridge id)nvn_hm_get(byser, &r->t.serial); + if (!o) continue; + uintptr_t k = (uintptr_t)(__bridge void *)o, u = (uintptr_t)nvn_hm_get(&last, &k); + if (u && g_tid_used[i] + 1ull > u) nvn_hm_put(&last, &k, (void *)(uintptr_t)(g_tid_used[i] + 1ull)); } + pthread_mutex_unlock(&g_smu); os_unfair_lock_unlock(&g_rmu); + free(byser_m.keys); free(byser_m.vals); + NSHashTable *victims = [NSHashTable hashTableWithOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality]; + memset(g_evict_why, 0, sizeof g_evict_why); g_evict_why[0] = (unsigned)pkgs.count; + for (NvPkg *pk in pkgs) { uintptr_t k = (uintptr_t)(__bridge void *)pk, u = (uintptr_t)nvn_hm_get(&last, &k); + if (!u || now - (uint32_t)(u - 1) < PKG_IDLE_S) { g_evict_why[1]++; continue; } + if (pk->sparse || pk->ps || pk->view || !pk->tex || pk->tex.heap || !pk->mem || !pk->size) { g_evict_why[2]++; continue; } + if (pk->stored || gws_owned(pk->mem, pk->mem + pk->size)) { g_evict_why[3]++; continue; } + [victims addObject:pk]; } + free(last.keys); free(last.vals); + if (!victims.count) return 0; // (g_evict_why[4] stays 0) + // Let go of them together. g_rmu before g_smu, as everywhere + nvn_hmap gone_ser = {.klen = 8}; + os_unfair_lock_lock(&g_rmu); pthread_mutex_lock(&g_smu); + NSUInteger was0 = victims.count; + { NSUInteger was = was0; // a pin, the sharing table or a serial that took its texture over (cpu_unc_drop) holds it (nvn_owner.m) + for (NvPkg *pk in victims.allObjects) if (tex_object_pinned(pk) || own_shared_locked(pk->tex) || entry_holds((__bridge void *)pk->tex)) [victims removeObject:pk]; + g_evict_why[4] = (unsigned)(was - victims.count); } + nvn_hmap *gs = &gone_ser; + own_drop_where_locked(^int(id o) { return [victims containsObject:o]; }, ^(uint64_t serial) { nvn_hm_put(gs, &serial, (void *)1); }); // their serials' entries, live and finalized + { uint32_t ns = 0; alias_key *ks = NULL; + for (uint32_t i = 0; i < g_pkg_share.cap; i++) { NvPkgRef *r = (__bridge NvPkgRef *)g_pkg_share.vals[i]; if (!r) continue; NvPkg *p = r->pkg; if (!p || ![victims containsObject:p]) continue; + alias_key *nk = realloc(ks, (ns + 1) * sizeof *ks); if (!nk) break; ks = nk; memcpy(&ks[ns++], g_pkg_share.keys + (size_t)i * g_pkg_share.klen, sizeof *ks); } + for (uint32_t j = 0; j < ns; j++) hm_del_id(&g_pkg_share, &ks[j]); + free(ks); } + for (NvPkg *pk in victims) { n++; bytes += pk->tex.allocatedSize + (pk->spare && !pk->spare.heap ? pk->spare.allocatedSize : 0); } + pthread_mutex_unlock(&g_smu); + for (int i = 1; i < g_ntreg; i++) { treg_t *r = &g_treg[i]; if (!r->ok || !r->t.serial || !nvn_hm_get(&gone_ser, &r->t.serial)) continue; + treg_drop_views(r); r->evicted = 1; reg_bump(i, 0); pool_seen_clear(i); } // not read since: a shader's next read makes it again (pool_seen_scan) // the pool tables take the ID again at their next use, as a copy (pool_gpu): draws already encoded keep the old table and the texture + for (uint32_t i = 0; i < gone_ser.cap; i++) if (gone_ser.vals[i]) { uint64_t ser; memcpy(&ser, gone_ser.keys + (size_t)i * 8, 8); vc_set *v = nvn_hm_del(&g_vc, &ser); if (v) vc_set_free(v); } + os_unfair_lock_unlock(&g_rmu); + free(gone_ser.keys); free(gone_ser.vals); + atomic_fetch_add(&g_evict_n, n); atomic_fetch_add(&g_evict_bytes, bytes); + if (n_out) *n_out = n; + return bytes; +} } static uint64_t pool_gpu(int samp, int dtt, int dpf, int base, __unsafe_unretained id *out) { pool_seen_scan(); uint64_t rg = atomic_load(&g_reg_gen), sg = samp ? 0 : atomic_load(&g_ser_gen); // a sampler table follows registrations alone @@ -10636,6 +11346,7 @@ static uint64_t pool_gpu(int samp, int dtt, int dpf, int base, __unsafe_unretain static id img_binding(int tid, const nvn_rbind *b, uint64_t *rid, int *real) { void *tv = NULL; *rid = tid ? tex_fast_rid(tid, &tv) : 0; id t = (__bridge id)tv; + if (t && g_drop_n && tex_dropped(t) && tid > 0 && tid < g_ntreg && g_treg[tid].ok) { (void)tex_mtl(&g_treg[tid].t); tv = NULL; *rid = tex_fast_rid(tid, &tv); t = (__bridge id)tv; } // an image slot reads texels: made whole (tex_undrop) int swz_only = t && !(t.usage & MTLTextureUsageShaderWrite) && (t.parentTexture.usage & MTLTextureUsageShaderWrite); if (t && (b->rw || b->atom) && !(t.usage & MTLTextureUsageShaderWrite) && !swz_only) { const tex_t *tt = tid > 0 && tid < g_ntreg && g_treg[tid].ok ? &g_treg[tid].t : NULL; @@ -13697,7 +14408,7 @@ static void mdi_wait(void) { if (g_blit) { enc_b_end(g_blit); g_blit = nil; } up_flush(); res_commit(); [g_cb endCommandBuffer]; - rec_commit(g_cb, nil); g_cbgen++; + rec_commit(g_cb, nil, 0); g_cbgen++; if (!g_mdi_ev) g_mdi_ev = [g_dev newSharedEvent]; rec_signal(g_mdi_ev, ++g_mdi_v); rec_drain(); uint64_t w0 = ws_t0(); int ok = [g_mdi_ev waitUntilSignaledValue:g_mdi_v timeoutMS:10000]; if (ws_on()) ws_put(WS_MDI, w0, 1); @@ -14532,7 +15243,7 @@ static int dispatch_own(void) { return v; } static id dispatch_enc(void) { - id e = blit_open(); g_gp_disp++; + id e = blit_open(); g_gp_disp++; g_stat_disp++; if (g_blit_ops) blit_barrier(); g_bw_lo[0] = 0; g_bw_hi[0] = ~0ull; g_bw_n = 1; g_br_n = 0; g_blit_ops = 1; // recorded as "everything written": the next copy or dispatch gets a barrier if (!g_blit_ct) { [e setArgumentTable:g_ct]; g_blit_ct = 1; } @@ -15401,7 +16112,7 @@ static void sub_cut(void) { uint32_t k = g_seg++; seg_clk *sc = NULL; // reports encoded so far keep this segment's GPU times (seg_ts) if (seg_ts()) { if (!g_sclk) { g_sclk = calloc(1, sizeof *g_sclk); if (!g_sclk) MDIE("segment clock allocation failed"); atomic_store(&g_sclk->refs, 1); } sc = g_sclk; atomic_fetch_add(&sc->refs, 1); if (k < SEG_CLK_N) sc->cm[sc->ncm++] = (uint16_t)k; } // this command buffer ends with segment k (seg_idle_before) cbs_list *cbs = cbs_take(); uint64_t cbs_fence = g_fence + 1; cbs_fly_put(cbs_fence, cbs); - MTL4CommitOptions *o = [MTL4CommitOptions new]; + DmCommitFB *o = [DmCommitFB new]; atomic_fetch_add(&g_seg_inflight, 1); [o addFeedbackHandler:^(id cb) { atomic_fetch_sub(&g_seg_inflight, 1); @@ -15414,7 +16125,7 @@ static void sub_cut(void) { gmem_commit_patch(); res_commit(); [g_cb endCommandBuffer]; - rec_commit(g_cb, o); g_cbgen++; + rec_commit(g_cb, o, 0); g_cbgen++; if (rec_on()) rec_publish(); // the segment reaches the encode thread now, not when its block of records fills g_cb = rec_cb_new(); [g_cb beginCommandBufferWithAllocator:g_alloc4[g_alloc_cur]]; // one allocator encodes several command buffers in sequence; it is reset only once its fence (the last segment) has passed, when a later submission starts @@ -16159,17 +16870,21 @@ static MTLViewport present_viewport(double pw, double ph, double dw, double dh) } // The shape the picture is shown in, whatever part of the texture it comes from. The Switch's compositor stretches a buffer's crop to the layer, so a crop only picks texels: Super // Mario Galaxy 2 draws its storybook cutscenes anamorphically into 1200x960 of a 1920x1080 swapchain (800x640 handheld). The layer fills the display, 16:9, unless the game sized it -// (vi::CreateLayer with a size, hle_vi.c). A screen taller than 16:9 (DM_SCREEN_ASPECT, loader.c) counts only for a texture of its shape: only builds with screen-shape stubs render it. +// (vi::CreateLayer with a size, hle_vi.c). A screen of another shape than 16:9 (DM_SCREEN_ASPECT, loader.c) counts only for a crop or a texture of its shape: only builds with +// screen-shape stubs render it. Breath of the Wild presents a whole texture of the taller shape; Ocarina of Time a crop of that shape inside larger window textures (the game's +// window keeps its texture size and moves its crop, as it does between docked and handheld). static _Atomic uint64_t g_layer_shape, g_screen_shape; // w | h << 32, 0 = none void mtl_present_layer(uint32_t w, uint32_t h) { atomic_store(&g_layer_shape, (uint64_t)w | (uint64_t)h << 32); } void mtl_present_screen(uint32_t w, uint32_t h) { atomic_store(&g_screen_shape, (uint64_t)w | (uint64_t)h << 32); } -static void present_shape(id src, double *w, double *h) { +static void present_shape(id src, const int crop[4], double *w, double *h) { uint64_t v = atomic_load(&g_screen_shape); - if (v && fabs(((double)src.width / src.height) / ((double)(uint32_t)v / (double)(v >> 32)) - 1) < 0.01) { *w = src.width; *h = src.height; return; } + double sr = v ? (double)(uint32_t)v / (double)(v >> 32) : 0; + if (v && crop && crop[2] > 0 && crop[3] > 0 && fabs(((double)crop[2] / crop[3]) / sr - 1) < 0.01) { *w = crop[2]; *h = crop[3]; return; } + if (v && fabs(((double)src.width / src.height) / sr - 1) < 0.01) { *w = src.width; *h = src.height; return; } v = atomic_load(&g_layer_shape); *w = v ? (double)(uint32_t)v : 1920; *h = v ? (double)(v >> 32) : 1080; } -static MTLViewport present_fit(id src, double dw, double dh) { double w, h; present_shape(src, &w, &h); return present_viewport(w, h, dw, dh); } +static MTLViewport present_fit(id src, const int crop[4], double dw, double dh) { double w, h; present_shape(src, crop, &w, &h); return present_viewport(w, h, dw, dh); } // The valid source rectangle of a present (x, y, width, height; the crop of nvnWindowSetCrop, zero = the whole texture); 0 when it lies outside the texture static int present_crop_rect(id src, const int crop[4], NSUInteger r[4]) { r[0] = 0; r[1] = 0; r[2] = src.width; r[3] = src.height; @@ -16190,7 +16905,7 @@ static int present_encode(id cb, id src, id sc; id in, out, read; NSUInteger key[5]; int refused; } up_mfx_scaler; // key: input w, h, output w, h, sRGB input; in: the RGBA16F input; out: the output (RGBA16F, or RGBA8Unorm for sRGB input); read: what the game's image is drawn from (out, or its sRGB view) enum { UP_MFX_SCALERS = 4 }; static up_mfx_scaler g_up_mfx[UP_MFX_SCALERS]; static int g_up_mfx_next; @@ -16305,12 +17023,27 @@ static int up_mfx_on(void) { // Bananza's all encode linear input (0.0031308, 1 / 2.4 as floats) and come in threes: no decode at the end (the output stays encoded), a decode clamped to 0-1, a decode up to 128. Splatoon Raiders' all read colour that is encoded // already and come in twos: no decode, a decode clamped to 0-1 (as half floats: 0.04045, 2.4 and 1 / 12.92 rounded to 0.0404358, 2.3984375 and 0.0774536). Only the variants with linear output are drawn, in these two shapes; a variant // with encoded output, or any other shape (no pack has shown one), keeps the game's shader. A constant counts from 8 uses, far fewer than a curve per channel of every output tile: two bytes also match by chance -enum { UP_COLOR_UNREAD, UP_COLOR_LINEAR, UP_COLOR_SRGB, UP_COLOR_KEEP }; // linear in and out: HDR mode; sRGB in, linear out: perceptual mode, then decoded; UP_COLOR_KEEP, UP_COLOR_UNREAD: the game's shader +// Ocarina of Time's agl_ndsr_vr_light.pck has no sRGB curve on its way in: its pre-pass stores the square root of the colour (RGB9E5), and the network adds its residual to that in +// square-root space and decodes it with a signed square, x * |x| (HMUL2 R, R, |R|: 32-36 in each variant, on every output texel's channels), then writes it unclamped (HDR range, alpha 1). +// Its variants come in twos as well: that output as it is (linear, UP_COLOR_SQRT), or encoded to sRGB after it (0.0031308, 1 / 2.4 as floats: kept). The single-precision squares +// (FMUL R, R, |R|) of agl_ndsr_vr.pck are not taken: that pack has Bananza's rectangles and a mode word of its own (c[24] word 19), and no game has dispatched one of its networks +enum { UP_COLOR_UNREAD, UP_COLOR_LINEAR, UP_COLOR_SRGB, UP_COLOR_KEEP, UP_COLOR_SQRT }; // linear in and out: HDR mode; sRGB in, linear out: perceptual mode, then decoded; square-root-encoded in, linear out: squared, then HDR mode; UP_COLOR_KEEP, UP_COLOR_UNREAD: the game's shader static int up_mfx_uses(const void *code, size_t n, const void *v, size_t w) { const uint8_t *p = code, *end = p + n; int hits = 0; while (hits < 8 && (p = memmem(p, end - p, v, w))) { hits++; p += w; } return hits == 8; } +// Whether the code holds 8 signed squares in half precision: HMUL2 Rd, Ra, |Ra| with the same halves on both sides. Ampere's 16-byte instructions: opcode bits 0-11 (0x232, register +// operands), Ra bits 24-31 (not RZ), Rb bits 32-39, Rb's halves bits 60-61, |Rb| bit 62, -Rb bit 63, Ra's - and || bits 72-73, Ra's halves bits 74-75 +static int up_mfx_squares(const void *code, size_t n) { + const uint8_t *p = code; int hits = 0; + for (size_t o = 0; o + 16 <= n && hits < 8; o += 16) { + uint64_t lo, hi; memcpy(&lo, p + o, 8); memcpy(&hi, p + o + 8, 8); + unsigned ra = (unsigned)(lo >> 24 & 0xff), rb = (unsigned)(lo >> 32 & 0xff); + if ((lo & 0xfff) == 0x232 && ra == rb && ra != 0xff && lo >> 62 == 1 && !(hi >> 8 & 3) && (lo >> 60 & 3) == (hi >> 10 & 3)) hits++; + } + return hits == 8; +} static int up_mfx_color(const void *code, size_t n) { #define UP_F32(x) ({ float f_ = (x); up_mfx_uses(code, n, &f_, 4); }) #define UP_F16(x) ({ __fp16 f_ = (x); up_mfx_uses(code, n, &f_, 2); }) @@ -16318,7 +17051,8 @@ static int up_mfx_color(const void *code, size_t n) { int enc16 = UP_F16(0.41650390625f) || UP_F16(0.416748046875f), dec16 = UP_F16(0.040435791015625f) && UP_F16(2.3984375f) && UP_F16(0.07745361328125f); // enc16 (1 / 2.4 either way rounded): no pack has it; it must not read as encoded input #undef UP_F32 #undef UP_F16 - return enc32 && dec32 && !enc16 && !dec16 ? UP_COLOR_LINEAR : dec16 && !enc16 && !enc32 && !dec32 ? UP_COLOR_SRGB : UP_COLOR_KEEP; + return enc32 && dec32 && !enc16 && !dec16 ? UP_COLOR_LINEAR : dec16 && !enc16 && !enc32 && !dec32 ? UP_COLOR_SRGB : + !enc32 && !dec32 && !enc16 && !dec16 && up_mfx_squares(code, n) ? UP_COLOR_SQRT : UP_COLOR_KEEP; } // Whether cs is one of the game's upscaler shaders (DM_GAME_UPSCALER_KEYS: comma-separated 16-digit keys) static int up_mfx_named(NvShader *cs) { @@ -16329,14 +17063,15 @@ static void up_mfx_read_color(NvShader *cs, const NVNshaderData *sd) { if (cs->up_color || !DM_GAME_UPSCALER_N || !up_mfx_on() || !up_mfx_named(cs)) return; uint32_t nctl, ncode = 0; if (sd->control) nvn_ctl_lens(sd->control, &nctl, &ncode); cs->up_color = sd->data && ncode && ncode < (1u << 24) ? up_mfx_color((const void *)(uintptr_t)sd->data, ncode) : UP_COLOR_KEEP; - MLOG("upscaler %s: %s", cs->key, cs->up_color == UP_COLOR_LINEAR ? "linear input and output, MetalFX in HDR mode" : cs->up_color == UP_COLOR_SRGB ? "sRGB-encoded input, linear output, MetalFX in perceptual mode" : "neither of the colour shapes MetalFX draws; the game's shader runs"); + MLOG("upscaler %s: %s", cs->key, cs->up_color == UP_COLOR_LINEAR ? "linear input and output, MetalFX in HDR mode" : cs->up_color == UP_COLOR_SRGB ? "sRGB-encoded input, linear output, MetalFX in perceptual mode" : + cs->up_color == UP_COLOR_SQRT ? "square-root-encoded input, linear output, squared and MetalFX in HDR mode" : "none of the colour shapes MetalFX draws; the game's shader runs"); } // Whether cs is one of the game's upscaler shaders, the player chose MetalFX and its colour is one MetalFX draws static int up_mfx_wanted(NvShader *cs) { if (cs->up_mfx) return cs->up_mfx == 1; cs->up_mfx = 2; if (!DM_GAME_UPSCALER_N || !up_mfx_on()) return 0; - if (up_mfx_named(cs) && (cs->up_color == UP_COLOR_LINEAR || cs->up_color == UP_COLOR_SRGB)) cs->up_mfx = 1; + if (up_mfx_named(cs) && (cs->up_color == UP_COLOR_LINEAR || cs->up_color == UP_COLOR_SRGB || cs->up_color == UP_COLOR_SQRT)) cs->up_mfx = 1; return cs->up_mfx == 1; } static up_mfx_scaler *up_mfx_scaler_for(NSUInteger iw, NSUInteger ih, NSUInteger ow, NSUInteger oh, int srgb) { @@ -16373,6 +17108,53 @@ static int up_mfx_rect(const uint32_t v[4], NSUInteger w, NSUInteger h, NVNcopyR if (v[0] > INT_MAX || v[1] > INT_MAX || rw > INT_MAX || rh > INT_MAX || (uint64_t)v[0] + rw > w || (uint64_t)v[1] + rh > h) return 0; *r = (NVNcopyRegion){(int)v[0], (int)v[1], 0, (int)rw, (int)rh, 1}; return 1; } +// The rectangles of a variable-ratio variant (UP_COLOR_SQRT) from its 32 push-constant words, inside an iw x ih texture and an ow x oh image. It writes texel (x, y) of an output +// of words 24 x 25 texels (each thread group a tile of words 18 x 19) at (x + word 4, y + word 5), and samples its base at ((x, y) + 0.5) times floats 26, 27 in the texture's +// normalized coordinates, its network's taps at whole texels from texel 0, 0: the input starts at the texture's origin and is float 26 x output width x texture width wide +// (and so high). An input that is not whole texels (within 1/16), or does not fit, refuses +static int up_mfx_rect_vr(const uint32_t v[32], NSUInteger iw, NSUInteger ih, NSUInteger ow, NSUInteger oh, NVNcopyRegion *ir, NVNcopyRegion *orr) { + if (!v[24] || !v[25]) return 0; + const uint32_t o[4] = {v[4], v[5], v[24] - 1, v[25] - 1}; + if (!up_mfx_rect(o, ow, oh, orr)) return 0; + float su, sv; memcpy(&su, &v[26], 4); memcpy(&sv, &v[27], 4); + double fw = (double)su * v[24] * iw, fh = (double)sv * v[25] * ih; + if (!isfinite(fw) || !isfinite(fh) || fw < 0.5 || fh < 0.5 || fw > iw + 0.0625 || fh > ih + 0.0625) return 0; + double rw = round(fw), rh = round(fh); + if (fabs(fw - rw) > 0.0625 || fabs(fh - rh) > 0.0625) return 0; + *ir = (NVNcopyRegion){0, 0, 0, (int)rw, (int)rh, 1}; return 1; +} +// A square-root-encoded input rectangle drawn into the scaler's RGBA16F texture at the origin, decoded as the network decodes it (x * |x|, sign kept), alpha 1 as the network writes +static int up_mfx_square(id s, id d, const NVNcopyRegion *sr) { + static id ps; static id at; static int failed; + if (failed) return 0; + if (!ps) { + static const char *src = + "#include \nusing namespace metal;\n" + "struct V { float4 p [[position]]; };\n" + "vertex V vs(uint id [[vertex_id]]) { float2 uv = float2((id << 1) & 2, id & 2); V o; o.p = float4(uv * float2(2, -2) + float2(-1, 1), 0, 1); return o; }\n" + "fragment float4 fs(V in [[stage_in]], texture2d t [[texture(0)]], constant uint2 *o [[buffer(0)]]) { float3 c = t.read(uint2(in.p.xy) + *o, 0).rgb; return float4(c * abs(c), 1); }\n"; + NSError *e = nil; id lib = [g_dev newLibraryWithSource:@(src) options:nil error:&e]; + MTLRenderPipelineDescriptor *pd = [MTLRenderPipelineDescriptor new]; + pd.vertexFunction = [lib newFunctionWithName:@"vs"]; pd.fragmentFunction = [lib newFunctionWithName:@"fs"]; pd.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA16Float; + if (pd.vertexFunction && pd.fragmentFunction) ps = [g_dev newRenderPipelineStateWithDescriptor:pd error:&e]; + MTL4ArgumentTableDescriptor *ad = [MTL4ArgumentTableDescriptor new]; ad.maxTextureBindCount = 1; ad.maxBufferBindCount = 1; + if (ps) at = rec_table([g_dev newArgumentTableWithDescriptor:ad error:&e]); + if (!ps || !at) { failed = 1; ps = nil; MLOG("[RED] upscaler: cannot create the squaring draw (%s); square-root-encoded variants keep the game's shader", e.localizedDescription.UTF8String); return 0; } + } + id pb; size_t po = arena_alloc(16, &pb); + if (!pb) return 0; + uint32_t *p = (uint32_t *)((uint8_t *)pb.contents + po); p[0] = (uint32_t)sr->xoffset; p[1] = (uint32_t)sr->yoffset; + MTL4RenderPassDescriptor *rp = [MTL4RenderPassDescriptor new]; + rp.colorAttachments[0].texture = d; rp.colorAttachments[0].loadAction = MTLLoadActionDontCare; rp.colorAttachments[0].storeAction = MTLStoreActionStore; // d is the rectangle's size: every texel drawn + rp_end(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; } + ser_gate(); id en = enc_r_begin(rp); + [en setArgumentTable:at atStages:MTLRenderStageFragment]; + [at setTexture:s.gpuResourceID atIndex:0]; [at setAddress:pb.gpuAddress + po atIndex:0]; + [en setViewport:(MTLViewport){0, 0, sr->width, sr->height, 0, 1}]; + [en setRenderPipelineState:ps]; [en drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; enc_r_end(en); + args_dirty_all(); g_pso_dirty = g_dss_dirty = 1; + return 1; +} // The dispatch of upscaler cs as MetalFX's spatial scaler from its texture slot's rectangle to its image slot's (see above): 1 when drawn, 0 to run the shader static int up_mfx_encode(NvShader *cs) { int ti = -1, oi = -1; @@ -16390,25 +17172,34 @@ static int up_mfx_encode(NvShader *cs) { out = ok ? img_binding(tout, &cs->rf.b[oi], &rid, &real) : nil; if (!real) out = nil; os_unfair_lock_unlock(&g_rmu); - uint32_t v[8]; memcpy(v, S.push[1], sizeof v); + uint32_t v[32]; memcpy(v, S.push[1], sizeof v); NVNcopyRegion ir, orr; + int srgb = cs->up_color == UP_COLOR_SRGB, sq = cs->up_color == UP_COLOR_SQRT; if (!in || !out || in == out || in.textureType != MTLTextureType2D || out.textureType != MTLTextureType2D || in.sampleCount != 1 || out.sampleCount != 1 || - fmt_int_or_ds(in.pixelFormat) || fmt_int_or_ds(out.pixelFormat) || mtl_fmt_block(out.pixelFormat) || !up_mfx_rect(v, in.width, in.height, &ir) || !up_mfx_rect(v + 4, out.width, out.height, &orr) || - orr.width < ir.width || orr.height < ir.height || (orr.width == ir.width && orr.height == ir.height)) { g_up_mfx_kept++; return 0; } - int srgb = cs->up_color == UP_COLOR_SRGB; + fmt_int_or_ds(in.pixelFormat) || fmt_int_or_ds(out.pixelFormat) || mtl_fmt_block(out.pixelFormat)) { g_up_mfx_kept++; return 0; } + if (sq ? !up_mfx_rect_vr(v, in.width, in.height, out.width, out.height, &ir, &orr) : !up_mfx_rect(v, in.width, in.height, &ir) || !up_mfx_rect(v + 4, out.width, out.height, &orr)) { + static int once; if (sq && !once++) { float su, sv; memcpy(&su, &v[26], 4); memcpy(&sv, &v[27], 4); + MLOG("[RED] upscaler %s: rectangles that do not fit (output %ux%u at %u,%u, input scale %g, %g of %lux%lu → %lux%lu); the game's shader runs", cs->key, v[24], v[25], v[4], v[5], su, sv, + (unsigned long)in.width, (unsigned long)in.height, (unsigned long)out.width, (unsigned long)out.height); } + g_up_mfx_kept++; return 0; + } + if (orr.width < ir.width || orr.height < ir.height || (orr.width == ir.width && orr.height == ir.height)) { g_up_mfx_kept++; return 0; } up_mfx_scaler *e = up_mfx_scaler_for((NSUInteger)ir.width, (NSUInteger)ir.height, (NSUInteger)orr.width, (NSUInteger)orr.height, srgb); if (!e) { g_up_mfx_kept++; return 0; } id sc = e->sc; - // Straight in and out when MetalFX can take the game's textures as they are; through the scaler's own textures otherwise - int direct = !srgb && (NSUInteger)ir.width == in.width && (NSUInteger)ir.height == in.height && out.storageMode == MTLStorageModePrivate && - in.pixelFormat == MTLPixelFormatRGBA16Float && out.pixelFormat == MTLPixelFormatRGBA16Float && !ir.xoffset && !ir.yoffset && !orr.xoffset && !orr.yoffset && (NSUInteger)orr.width == out.width && - (NSUInteger)orr.height == out.height && (in.usage & sc.colorTextureUsage) == sc.colorTextureUsage && (out.usage & sc.outputTextureUsage) == sc.outputTextureUsage; - if (!direct && !(out.usage & MTLTextureUsageRenderTarget)) { g_up_mfx_kept++; return 0; } + // Straight in and out when MetalFX can take the game's textures as they are; through the scaler's own textures otherwise. Square-root-encoded input is always squared into the + // scaler's texture first, and its linear result goes straight out when the image can take it + int whole_out = out.storageMode == MTLStorageModePrivate && out.pixelFormat == MTLPixelFormatRGBA16Float && !orr.xoffset && !orr.yoffset && (NSUInteger)orr.width == out.width && + (NSUInteger)orr.height == out.height && (out.usage & sc.outputTextureUsage) == sc.outputTextureUsage; + int direct = !srgb && !sq && whole_out && (NSUInteger)ir.width == in.width && (NSUInteger)ir.height == in.height && in.pixelFormat == MTLPixelFormatRGBA16Float && !ir.xoffset && !ir.yoffset && + (in.usage & sc.colorTextureUsage) == sc.colorTextureUsage; + int straight_out = direct || (sq && whole_out); + if (!straight_out && !(out.usage & MTLTextureUsageRenderTarget)) { g_up_mfx_kept++; return 0; } zskip_del(dout.serial); rp_end(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; } ubd_land_compute(); NVNcopyRegion at0 = {0, 0, 0, ir.width, ir.height, 1}, at0o = {0, 0, 0, orr.width, orr.height, 1}; - id color = direct ? in : e->in, result = direct ? out : e->out; - if (!direct && !copy_t2t_draw(in, color, 0, 0, 0, 0, &ir, &at0, 0, 0)) { g_up_mfx_kept++; return 0; } // into RGBA16F at the origin (a nearest draw: same size) + id color = direct ? in : e->in, result = straight_out ? out : e->out; + if (!direct && !(sq ? up_mfx_square(in, color, &ir) : copy_t2t_draw(in, color, 0, 0, 0, 0, &ir, &at0, 0, 0))) { g_up_mfx_kept++; return 0; } // into RGBA16F at the origin (a nearest draw: same size) id ce = [g_cb computeCommandEncoder]; // as dlss_eval: MetalFX opens encoders of its own, which take no barrier [ce barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageBlit visibilityOptions:resource_vis()]; [ce barrierAfterStages:MTLStageBlit beforeQueueStages:MTLStageAll visibilityOptions:resource_vis()]; @@ -16419,13 +17210,14 @@ static int up_mfx_encode(NvShader *cs) { [sc encodeToCommandBuffer:cb]; }); g_last_end_relaxed = 0; // the next pass waits for the scaler whole (enc_r_begin_pass) - if (!direct && !copy_t2t_draw(e->read, out, 0, 0, 0, 0, &at0o, &orr, 0, 0)) { + if (!straight_out && !copy_t2t_draw(e->read, out, 0, 0, 0, 0, &at0o, &orr, 0, 0)) { args_dirty_all(); g_up_mfx_kept++; return 0; // only the scratch image was scaled; the game's shader can still produce the output } args_dirty_all(); if (!g_up_mfx_n++) MLOG("upscaler: first dispatch of %s drawn by MetalFX, %dx%d at %d,%d of %lux%lu (format %lu) → %dx%d at %d,%d of %lux%lu (format %lu)%s", cs->key, ir.width, ir.height, ir.xoffset, ir.yoffset, (unsigned long)in.width, (unsigned long)in.height, (unsigned long)in.pixelFormat, orr.width, orr.height, orr.xoffset, orr.yoffset, (unsigned long)out.width, (unsigned long)out.height, - (unsigned long)out.pixelFormat, direct ? ", straight" : srgb ? ", through RGBA16F, decoded from sRGB" : ", through RGBA16F"); + (unsigned long)out.pixelFormat, direct ? ", straight" : srgb ? ", through RGBA16F, decoded from sRGB" : + sq ? (straight_out ? ", squared from its square-root encoding, straight out" : ", squared from its square-root encoding, through RGBA16F") : ", through RGBA16F"); return 1; } // The present pass: src's valid rectangle drawn into dst (the drawable, or a screenshot's texture) as present_encode draws it, through MetalFX first where fx_encode takes it @@ -16434,7 +17226,7 @@ static int present_encode_m4(id cb, id src, id tex = present_raw_src(src), up = fx ? fx_encode(fx, cb, tex, r, vp, dst.pixelFormat, fx == &g_fx_present) : nil; if (up) { tex = up; r[0] = r[1] = 0; r[2] = up.width; r[3] = up.height; } // the scaled picture, the viewport's size: drawn 1:1 @@ -16517,7 +17309,7 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t if (!src) { RED_ONCE(8, "present texture could not get an MTLTexture"); return 0; } // The picture's shape for the front end's layout (front.h front_picture_shape): reported when its width / height changes by more than 0.1 %, not on a size change of the same // shape (1280x720 handheld, 1920x1080 docked) - { static double last; double w, h; present_shape(src, &w, &h); double a = w / h; + { static double last; double w, h; present_shape(src, crop, &w, &h); double a = w / h; if (fabs(a - last) > last * 0.001) { last = a; MLOG("present: picture shape %.0fx%.0f (%.3f:1) for the front end's layout", w, h, a); front_picture_shape((int)w, (int)h); } } // A texture made on first resolution joins the residency set (res_add), which a submission commits; a window texture presented before any submission has used it was still // outside the committed set when the display command buffer sampled it. Super Smash Bros. Ultimate presents its window texture in its first frames before drawing into it: @@ -16632,7 +17424,7 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t // Swapchain texture return: before AcquireTexture gets a texture it waits for the ticket of that texture's previous present to be processed (mtl_present_wait), after which the commands the game draws into it // are necessarily ordered after that blit on the GPU queue. #define PQ 8 -typedef struct { tex_t t; double period; uint64_t frame; int crop[4]; double t_in; uint64_t ev_val, snap_v; } pq_item; // snap_v: the snapshot copy this present shows (snap_commit_wait) // t_in: the time the game handed this frame into the present queue (CACurrentMediaTime); ev_val: see g_ext_ev +typedef struct { tex_t t; double period; uint64_t frame; int crop[4]; double t_in; uint64_t ev_val, snap_v, sub_v; } pq_item; // snap_v: the snapshot copy this present shows (snap_commit_wait); sub_v: the submissions a present of the game's own texture follows (sub_commit_wait) // t_in: the time the game handed this frame into the present queue (CACurrentMediaTime); ev_val: see g_ext_ev // External producer (the Vulkan layer, dm/gfx/vk) renders on its own queue and signals this event when a frame's rendering is done: the present of that frame waits for the value on g_q4 static id g_ext_ev; static void ext_wait(uint64_t v) { if (v && g_ext_ev) [g_q4 waitForEvent:g_ext_ev value:v]; } @@ -16704,7 +17496,7 @@ - (void)metalDisplayLink:(CAMetalDisplayLink *)link needsUpdate:(CAMetalDisplayL pthread_cond_broadcast(&g_pq_cv); pthread_mutex_unlock(&g_pq_mu); int submitted; - ext_wait(it.ev_val); snap_commit_wait(it.snap_v); + ext_wait(it.ev_val); snap_commit_wait(it.snap_v); sub_commit_wait(it.sub_v); @autoreleasepool { submitted = present_now(&it.t, it.period, it.frame, ticket, it.crop, update.drawable, update.targetPresentationTimestamp); mtl_tex_unpin(it.t.serial); } g_link_hold_until = submitted && it.period > 0.025 ? update.targetPresentationTimestamp + it.period : 0; if (!submitted) { @@ -16745,9 +17537,14 @@ static CAFrameRateRange link_range(int mode) { // and why a fixed-rate screen still has about 20 ms more presentation delay with the link at either latency, remain open (docs/reference/frame-rate.md) __attribute__((weak)) int front_fullscreen(void) { return 0; } // front_mac.m; graphics unit tests and iOS have none __attribute__((weak)) int front_screen_variable_refresh(void) { return 0; } // front_mac.m; graphics unit tests and iOS have none +// Latency 2 also while the 60 Hz link shows the late frames of a 30 fps cap at the next vsync (hle_nvn.c nvn_fstep_fine): at latency 1 it calls back 16.5 ms before the target +// time and takes a frame whose GPU work is still running, so on a ProMotion screen the present lands one 120 Hz refresh late and the link skips its next tick; the acquire, which +// counts ticks, then held each frame 50 ms (Ocarina of Time's title on an M1 iPad: 40 ms frames, 25 → 20 fps) or the screen showed them 33 / 38 / 42 ms apart. Latency 2 is the +// 33 ms lead the 30 Hz link has at latency 1, so the input lag is that of the cap's own link. +__attribute__((weak)) int nvn_fstep_fine(void) { return 0; } // hle_nvn.c; graphics unit tests have no frame step // CAMetalDisplayLink accepts only 1 or 2. Compare its readback with the supported request, or an oversized override rewrites and logs every frame. -static int link_latency(void) { return g_present_latency > 0 ? MIN(g_present_latency, 2) : front_fullscreen() && front_screen_variable_refresh() ? 2 : 1; } -static const char *link_latency_why(void) { return g_present_latency > 0 ? "DM_PRESENT_LATENCY" : !front_fullscreen() ? "window" : front_screen_variable_refresh() ? "fullscreen, variable refresh" : "fullscreen, fixed refresh"; } +static int link_latency(void) { return g_present_latency > 0 ? MIN(g_present_latency, 2) : (front_fullscreen() && front_screen_variable_refresh()) || nvn_fstep_fine() ? 2 : 1; } +static const char *link_latency_why(void) { return g_present_latency > 0 ? "DM_PRESENT_LATENCY" : nvn_fstep_fine() ? "late frames of a 30 fps cap at the next vsync" : !front_fullscreen() ? "window" : front_screen_variable_refresh() ? "fullscreen, variable refresh" : "fullscreen, fixed refresh"; } // The 30 Hz link at a 30 fps target, except in fullscreen on a fixed-rate screen. There the link skipped ticks: Ocarina of Time at a 30 fps cap on a MacBook Air M4 (60 Hz) got // 16.5-25 callbacks a second over stretches of 300 frames, also on frames with under 1 ms of GPU, and each skipped tick kept a frame on screen 66.7 ms (a 180 s walk: 388 and 996 // frames over 50 ms; 3-4 in a window, where the same link held 30.0). Why is open (docs/reference/frame-rate.md). The 60 Hz link paces the 30 through the present interval, as it @@ -16844,7 +17641,7 @@ static void present_drop_for_suspend(void) { uint64_t ticket = ++g_pq_read; g_classic_busy = 1; pthread_mutex_unlock(&g_pq_mu); int submitted; - ext_wait(it.ev_val); snap_commit_wait(it.snap_v); + ext_wait(it.ev_val); snap_commit_wait(it.snap_v); sub_commit_wait(it.sub_v); @autoreleasepool { submitted = present_now(&it.t, it.period, it.frame, ticket, it.crop, nil, 0); mtl_tex_unpin(it.t.serial); } pthread_mutex_lock(&g_pq_mu); g_classic_busy = 0; pthread_cond_broadcast(&g_pq_cv); pthread_mutex_unlock(&g_pq_mu); if (!submitted) { @@ -17015,7 +17812,7 @@ static uint64_t present_enqueue(const tex_t *t, double period, const int crop[4] mtl_tex_pin(t->serial); pthread_mutex_lock(&g_pq_mu); while (g_pq_in - g_pq_done >= PQ) pthread_cond_wait(&g_pq_cv, &g_pq_mu); // Wait only when the queue is full; normally AcquireTexture blocks first - pq_item *it = &g_pq[g_pq_in % PQ]; *it = (pq_item){*t, period, atomic_load(&g_cur_frame), {0}, CACurrentMediaTime(), ev_val, ss ? g_snap[slot].ev : 0}; + pq_item *it = &g_pq[g_pq_in % PQ]; *it = (pq_item){*t, period, atomic_load(&g_cur_frame), {0}, CACurrentMediaTime(), ev_val, ss ? g_snap[slot].ev : 0, !ss && !ev_val && on_sub_thread() ? g_fence : 0}; if (crop) memcpy(it->crop, crop, sizeof it->crop); // The current frame's state is enqueued with the ticket number, rather than reading the mutable window late on the present thread uint64_t tk = ++g_pq_in; if (ss) { g_snap[slot].ticket = tk; atomic_fetch_add(&g_snap_next, 1); if (copy) *copy = g_snap[slot].ev; } @@ -17076,6 +17873,7 @@ void mtl_present_wait(uint64_t tk) { // Wait until all queued presents have been processed (used by mtl_finish = nvnQueueFinish etc.): goes through mtl_present_wait, so there is still a fallback when the display link stops (real device: the game called QueueFinish once while the display link was stopped, // and this used to wait here without a timeout; nobody took the 3 queued frames and the game stalled; those two runs on Mac did not hit this call) void mtl_present_flush(void) { pthread_mutex_lock(&g_pq_mu); uint64_t h = g_pq_in; pthread_mutex_unlock(&g_pq_mu); mtl_present_wait(h); } +uint64_t mtl_dispatches(void) { return g_stat_disp; } // compute dispatches encoded so far, the game's and the host's (the frame step's work measure, nvn_fstep.h) void mtl_stats(uint64_t *passes, uint64_t *draws) { *passes = g_stat_pass; *draws = g_stat_draw; cp_report(); } void mtl_args_stats(uint64_t *enc, uint64_t *reuse, uint64_t *patch) { *enc = g_stat_args_enc; *reuse = g_stat_args_reuse; *patch = g_stat_args_patch; } void mtl_vbuf_stats(uint64_t *resolve, uint64_t *reuse, uint64_t *set, uint64_t *skip, uint64_t *copies, uint64_t *copy_bytes) { @@ -17165,11 +17963,13 @@ void mem_census(const char *why) { @autoreleasepool { // registered descriptors: their views' bases, and per storage address the distinct bases NSMapTable *by_mem = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality valueOptions:NSPointerFunctionsStrongMemory]; NSMapTable *by_flags = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality valueOptions:NSPointerFunctionsStrongMemory]; // texture flags | pool flags << 32 + NSCountedSet *v_live = [NSCountedSet set], *v_ret = [NSCountedSet set]; // the descriptors whose views name each base texture (live / retired), for the holders line os_unfair_lock_lock(&g_rmu); uint64_t nreg = 0, nretired = 0; for (int i = 1; i < g_ntreg; i++) { treg_t *r = &g_treg[i]; if (!r->ok) continue; nreg++; nretired += r->retired; void *vs[3] = {r->view, r->alt, r->im}; for (int k = 0; k < 3; k++) if (vs[k]) { id b = census_base((__bridge id)vs[k]); if (!b) continue; [r->retired ? named_ret : named addObject:(__bridge id)(__bridge void *)b]; + [r->retired ? v_ret : v_live addObject:b]; if (k == 0 && r->t.mem) { const void *key = r->t.mem; NSHashTable *set = [by_mem objectForKey:(__bridge id)key]; if (!set) { set = [NSHashTable hashTableWithOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality]; [by_mem setObject:set forKey:(__bridge id)key]; } [set addObject:(__bridge id)(__bridge void *)b]; @@ -17181,7 +17981,7 @@ void mem_census(const char *why) { @autoreleasepool { uint64_t n_ret = 0, b_ret = 0, n_named = 0, b_named = 0, n_wait = 0, b_wait = 0, n_none = 0, b_none = 0, n_buf = 0, b_buf = 0; enum { NF = 24 }; struct { unsigned long pf; uint64_t n, b; } fm[NF] = {{0}}; int nfm = 0; pthread_mutex_lock(&g_res_mu); - for (id o in g_res_objects.allObjects) { uint64_t z = o.allocatedSize; + for (id o in g_res_objects.allObjects) { uint64_t z = res_bytes(o); if (z <= 65536) { int tx = [(id)o conformsToProtocol:@protocol(MTLTexture)], sh = ((id)o).storageMode == MTLStorageModeShared; small_n[tx][sh]++; small_b[tx][sh] += z; } if (![(id)o conformsToProtocol:@protocol(MTLTexture)]) { n_buf++; b_buf += z; continue; } id t = (id)o; if (t.parentTexture) continue; @@ -17191,9 +17991,88 @@ void mem_census(const char *why) { @autoreleasepool { else if ([waiting containsObject:(__bridge id)(__bridge void *)t]) { n_wait++; b_wait += z; } else { n_none++; b_none += z; } } pthread_mutex_unlock(&g_res_mu); - uint64_t dup_addr = 0, dup_tex = 0, dup_b = 0; + // The memory a group takes beyond its largest allocation, counting each allocation once: textures placed in one heap (a resolution family's, a span's) share its bytes, so a group's + // placed textures count by their heaps. Summing each texture's allocatedSize counted a family of 36 sizes in one 15 MB heap as 490 MB (Ocarina of Time at the field's edge: 1,131 MB + // reported, 1,089 MB of it family members) + uint64_t dup_addr = 0, dup_tex = 0, dup_b = 0, dup_naive = 0; for (id key in by_mem) { NSHashTable *set = [by_mem objectForKey:key]; if (set.count < 2) continue; dup_addr++; - uint64_t biggest = 0, sum = 0; for (id b in set) { uint64_t z = ((id)b).allocatedSize; sum += z; if (z > biggest) biggest = z; } dup_tex += set.count - 1; dup_b += sum - biggest; } + uint64_t biggest = 0, sum = 0, nbig = 0, nsum = 0; NSHashTable *seen = [NSHashTable hashTableWithOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality]; + for (id b in set) { uint64_t z = b.allocatedSize; nsum += z; if (z > nbig) nbig = z; + id h = b.heap; if (h) { if ([seen containsObject:h]) continue; [seen addObject:h]; z = h.size; } + sum += z; if (z > biggest) biggest = z; } + dup_tex += set.count - 1; dup_b += sum - biggest; dup_naive += nsum - nbig; } + { // Who holds the textures of those groups: s a live serial (g_by_serial), g a finalized one (the ghost ring), p a pin, a the sharing table, v a live descriptor's view, r only a retired + // one's; R in the residency set (itself or its heap); and where its memory is: h a recycled heap of its own (rh_texture), f a resolution family's heap, w a span's heap, - its own + enum { NM = 32 }; struct { char k[16]; uint64_t n, b; } hm[NM]; int nhm = 0; + NSMutableArray *all = [NSMutableArray array]; for (id key in by_mem) { NSHashTable *set = [by_mem objectForKey:key]; if (set.count >= 2) for (id t in set) [all addObject:t]; } + char (*ks)[16] = calloc(all.count ? all.count : 1, 16); + pthread_mutex_lock(&g_smu); + for (NSUInteger i = 0; i < all.count; i++) { id t = all[i]; const void *p = (__bridge const void *)t; char *k = ks[i]; int o = 0; + if (serial_table_holds(p)) k[o++] = 's'; + if (own_ghost_holds_locked(p)) k[o++] = 'g'; + if (tex_object_pinned(t)) k[o++] = 'p'; + if (own_shared_locked(t)) k[o++] = 'a'; + k[o] = 0; } + uint64_t age_n[4] = {0}, age_b[4] = {0}; // their sharing-table entries by submissions since a lookup last found them: under ALIAS_IDLE, under 300, more, never recorded + { NSHashTable *in = [NSHashTable hashTableWithOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality]; for (id t in all) [in addObject:t]; + uint64_t *an = age_n, *ab = age_b; // (a block cannot capture an array) + own_alias_each_locked(^(const alias_key *ak2, id o) { if (![in containsObject:o]) return; + uint64_t seen = own_alias_seen_locked(ak2), age = g_fence + 1 - seen; + int c = !seen ? 3 : age < ALIAS_IDLE ? 0 : age < 300 ? 1 : 2; an[c]++; ab[c] += ((id)o).allocatedSize; }); } + pthread_mutex_unlock(&g_smu); + MLOG("%s census: their sharing-table entries by submissions since last found: under %d %llu, %llu MB; under 300 %llu, %llu MB; more %llu, %llu MB; never %llu, %llu MB", why, ALIAS_IDLE, + (unsigned long long)age_n[0], (unsigned long long)(age_b[0] >> 20), (unsigned long long)age_n[1], (unsigned long long)(age_b[1] >> 20), (unsigned long long)age_n[2], (unsigned long long)(age_b[2] >> 20), (unsigned long long)age_n[3], (unsigned long long)(age_b[3] >> 20)); + pthread_mutex_lock(&g_res_mu); + for (NSUInteger i = 0; i < all.count; i++) { id t = all[i]; char *k = ks[i]; size_t o = strlen(k); + if ([v_live countForObject:t]) k[o++] = 'v'; else if ([v_ret countForObject:t]) k[o++] = 'r'; + if ([g_res_objects containsObject:t.heap ? (id)t.heap : (id)t]) k[o++] = 'R'; + NvImageHeap *ih = objc_getAssociatedObject(t, &g_image_heap_owner_key); + k[o++] = objc_getAssociatedObject(t, &g_rh_owner_key) ? 'h' : ih ? (ih->window ? 'w' : 'f') : '-'; k[o] = 0; } + pthread_mutex_unlock(&g_res_mu); + for (NSUInteger i = 0; i < all.count; i++) { int j = 0; while (j < nhm && strcmp(hm[j].k, ks[i])) j++; + if (j == nhm) { if (nhm == NM) continue; memcpy(hm[nhm].k, ks[i], 16); hm[nhm].n = hm[nhm].b = 0; nhm++; } + hm[j].n++; hm[j].b += ((id)all[i]).allocatedSize; } + free(ks); + for (int i = 0; i < nhm; i++) for (int j = i + 1; j < nhm; j++) if (hm[j].b > hm[i].b) { __typeof__(hm[0]) x = hm[i]; hm[i] = hm[j]; hm[j] = x; } + char hl[900]; size_t ho = 0; for (int i = 0; i < nhm && ho < sizeof hl; i++) ho += snprintf(hl + ho, sizeof hl - ho, "%s%s %llu, %llu MB", i ? "; " : "", hm[i].k, (unsigned long long)hm[i].n, (unsigned long long)(hm[i].b >> 20)); + MLOG("%s census: textures at storage addresses with several, by holder (s live serial, g finalized serial, p pin, a sharing table, v live descriptor, r retired descriptor; R resident; memory h own recycled heap, f family heap, w span heap, - own): %s", why, nhm ? hl : "none"); + } + { // Every texture in the set by the line that added it and who holds it (the letters of the line above), and whether the memory pool its storage lies in still exists (P) or was + // finalized (x), or no storage is recorded (-). A texture left over from an area the game has left would be held by something here while its pool is gone + enum { NK = 40 }; struct { int line; char k[16]; uint64_t n, b; } hk[NK]; int nhk = 0; uint64_t nview = 0; + NSArray *objs; pthread_mutex_lock(&g_res_mu); objs = g_res_objects.allObjects; pthread_mutex_unlock(&g_res_mu); + NSMutableArray *tx = [NSMutableArray array]; for (id o in objs) if ([o conformsToProtocol:@protocol(MTLTexture)]) { id t = o; if (t.buffer || t.parentTexture) nview++; else [tx addObject:t]; } + NSUInteger nt = tx.count; char (*ks)[16] = calloc(nt ? nt : 1, 16); int *ln = calloc(nt ? nt : 1, sizeof *ln); + pthread_mutex_lock(&g_smu); + // A packaged texture's serial entries hold its NvPkg, not the texture: k its current texture through a live serial, K through a finalized one only, e its spare (the texture + // the last re-upload replaced, see NvPkg) + NSHashTable *pk_live = [NSHashTable hashTableWithOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality], + *pk_ghost = [NSHashTable hashTableWithOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality], + *pk_spare = [NSHashTable hashTableWithOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality]; + own_each_locked(^(uint64_t serial, id o, int ghost) { (void)serial; if (![o isKindOfClass:[NvPkg class]]) return; NvPkg *pg = o; + if (pg->tex) [ghost ? pk_ghost : pk_live addObject:pg->tex]; + if (pg->spare) [pk_spare addObject:pg->spare]; }); + for (NSUInteger i = 0; i < nt; i++) { id t = tx[i]; const void *p = (__bridge const void *)t; char *k = ks[i]; int o = 0; + if (serial_table_holds(p)) k[o++] = 's'; + if ([pk_live containsObject:t]) k[o++] = 'k'; else if ([pk_ghost containsObject:t]) k[o++] = 'K'; + if ([pk_spare containsObject:t]) k[o++] = 'e'; + if (own_ghost_holds_locked(p)) k[o++] = 'g'; + if (tex_object_pinned(t)) k[o++] = 'p'; + if (own_shared_locked(t)) k[o++] = 'a'; + if ([v_live countForObject:t]) k[o++] = 'v'; else if ([v_ret countForObject:t]) k[o++] = 'r'; + k[o] = 0; } + pthread_mutex_unlock(&g_smu); + pthread_mutex_lock(&g_res_mu); for (NSUInteger i = 0; i < nt; i++) ln[i] = [[g_res_line objectForKey:tx[i]] intValue]; pthread_mutex_unlock(&g_res_mu); + for (NSUInteger i = 0; i < nt; i++) { id t = tx[i]; NSArray *rg = objc_getAssociatedObject(t, &g_tex_range_key); if (!rg) rg = objc_getAssociatedObject(t, &g_tex_up_key); + size_t o = strlen(ks[i]); ks[i][o++] = ' '; ks[i][o++] = !rg ? '-' : mtl_addr_known([rg[0] unsignedLongLongValue], MAX([rg[1] unsignedLongLongValue], 1ull)) ? 'P' : 'x'; ks[i][o] = 0; + int j = 0; while (j < nhk && (hk[j].line != ln[i] || strcmp(hk[j].k, ks[i]))) j++; + if (j == nhk) { if (nhk == NK) continue; hk[nhk].line = ln[i]; memcpy(hk[nhk].k, ks[i], 16); hk[nhk].n = hk[nhk].b = 0; nhk++; } + hk[j].n++; hk[j].b += t.heap ? 0 : t.allocatedSize; } + free(ks); free(ln); + for (int i = 0; i < nhk; i++) for (int j = i + 1; j < nhk; j++) if (hk[j].b > hk[i].b) { __typeof__(hk[0]) x = hk[i]; hk[i] = hk[j]; hk[j] = x; } + char hl[1400]; size_t ho = 0; for (int i = 0; i < nhk && i < 24 && ho < sizeof hl; i++) ho += snprintf(hl + ho, sizeof hl - ho, "%sline %d [%s] %llu, %llu MB", i ? "; " : "", hk[i].line, hk[i].k, (unsigned long long)hk[i].n, (unsigned long long)(hk[i].b >> 20)); + MLOG("%s census: textures in the set by the line that added them, holder (s live serial, k / K a live / only a finalized serial's packaged texture, e a packaged texture's spare, g finalized serial, p pin, a sharing table, v live descriptor, r retired descriptor) and their storage's pool (P live, x finalized, - none recorded; placed textures count 0, their heaps apart): %s; views and textures over buffers %llu", why, hl, (unsigned long long)nview); + } { // the largest groups: each Metal texture over one storage address, so a reader can tell views made as copies from different images that reuse the memory NSMutableArray *groups = [NSMutableArray array]; for (id key in by_mem) { NSHashTable *set = [by_mem objectForKey:key]; if (set.count >= 2) { [groups addObject:set]; objc_setAssociatedObject(set, &census_flags_key, [by_flags objectForKey:key], OBJC_ASSOCIATION_RETAIN_NONATOMIC); } } @@ -17211,9 +18090,9 @@ void mem_census(const char *why) { @autoreleasepool { } for (int i = 0; i < nfm; i++) for (int j = i + 1; j < nfm; j++) if (fm[j].b > fm[i].b) { __typeof__(fm[0]) x = fm[i]; fm[i] = fm[j]; fm[j] = x; } char line[900]; size_t o = 0; for (int i = 0; i < nfm && i < 12 && o < sizeof line; i++) o += snprintf(line + o, sizeof line - o, "%s%lu: %llu, %llu MB", i ? "; " : "", fm[i].pf, (unsigned long long)fm[i].n, (unsigned long long)(fm[i].b >> 20)); - MLOG("%s census: textures named by serials, sharing or live descriptors' views %llu, %llu MB; only by retired descriptors' views %llu, %llu MB; only in the deferred-release queue %llu, %llu MB; named by nothing %llu, %llu MB; buffers %llu, %llu MB; descriptors %llu (%llu retired); storage addresses with several Metal textures %llu (%llu extra textures, %llu MB)", + MLOG("%s census: textures named by serials, sharing or live descriptors' views %llu, %llu MB; only by retired descriptors' views %llu, %llu MB; only in the deferred-release queue %llu, %llu MB; named by nothing %llu, %llu MB; buffers %llu, %llu MB; descriptors %llu (%llu retired); storage addresses with several Metal textures %llu (%llu extra textures, %llu MB beyond each address's largest allocation, a heap counted once; %llu MB by each texture's own size)", why, (unsigned long long)n_named, (unsigned long long)(b_named >> 20), (unsigned long long)n_ret, (unsigned long long)(b_ret >> 20), (unsigned long long)n_wait, (unsigned long long)(b_wait >> 20), (unsigned long long)n_none, (unsigned long long)(b_none >> 20), - (unsigned long long)n_buf, (unsigned long long)(b_buf >> 20), (unsigned long long)nreg, (unsigned long long)nretired, (unsigned long long)dup_addr, (unsigned long long)dup_tex, (unsigned long long)(dup_b >> 20)); + (unsigned long long)n_buf, (unsigned long long)(b_buf >> 20), (unsigned long long)nreg, (unsigned long long)nretired, (unsigned long long)dup_addr, (unsigned long long)dup_tex, (unsigned long long)(dup_b >> 20), (unsigned long long)(dup_naive >> 20)); MLOG("%s census: textures by Metal format: %s", why, line); MLOG("%s census: residency objects of 64 KB or less: buffers shared %llu (%llu KB), private %llu (%llu KB); textures shared %llu (%llu KB), private %llu (%llu KB)", why, (unsigned long long)small_n[0][1], (unsigned long long)(small_b[0][1] >> 10), (unsigned long long)small_n[0][0], (unsigned long long)(small_b[0][0] >> 10), diff --git a/dm/gfx/nvn/nvn_obj.h b/dm/gfx/nvn/nvn_obj.h index b3bcc47479..9ca1388b2f 100644 --- a/dm/gfx/nvn/nvn_obj.h +++ b/dm/gfx/nvn/nvn_obj.h @@ -295,6 +295,7 @@ void mtl_sub_index(const uint64_t *h, int n); // Start of submission: build th void xv_test_counts(int *dc, int *viol); int mtl_gpu_span(uint64_t f, uint64_t *t0, uint64_t *t1); // The frame's earliest GPUStart / latest GPUEnd (mach absolute time, ns); returns 0 if not all complete or there is no GPU time void mtl_stats(uint64_t *passes, uint64_t *draws); +uint64_t mtl_dispatches(void); void mtl_args_stats(uint64_t *enc, uint64_t *reuse, uint64_t *patch); void mtl_use_stats(uint64_t *call, uint64_t *skip); uint64_t mtl_ds_omit(void); // Cumulative number of passes with no depth attachment because the lookahead proved depth-stencil unused @@ -320,6 +321,7 @@ void mtl_tex_release(tex_t *t); void mtl_tex_pin(uint64_t serial); void mtl_tex_unpin(uint64_t serial); void mtl_pkg_stats(uint64_t *uploads, uint64_t *reuploads); +void mtl_spare_stats(uint64_t *held, uint64_t *trimmed, uint64_t *trimmed_mb); // packaged textures holding a spare now; spares retired so far (spare_trim) and their MB unsigned mtl_cpu_tex_count(void); // live textures the CPU writes (retired snapshots are excluded) uint64_t mtl_pkg_edge_skips(void); // packaged texture checks that found only writes beside the texture (pkg_edges_clean) uint64_t mtl_pkg_miss(void); diff --git a/dm/gfx/nvn/nvn_owner.h b/dm/gfx/nvn/nvn_owner.h index fb2f1533bf..9a6c740bf6 100644 --- a/dm/gfx/nvn/nvn_owner.h +++ b/dm/gfx/nvn/nvn_owner.h @@ -127,6 +127,9 @@ int own_note_at(uint64_t gen, uint64_t *serial); // the serial n typedef struct { uint32_t live, live_cap, ghost, retire_wait; uint64_t ghost_puts; } own_stats; own_stats own_stats_locked(void); void own_each_locked(void (^fn)(uint64_t serial, id o, int ghost)); +// Every entry, live or ghost, whose object gone() names goes (each serial noted, its ring slot freed, its object dropped as serial_del drops it); each(serial) is told of +// each. The replay layer's eviction of idle uploaded textures at memory pressure (nvn_mtl.m pkg_evict_idle). → how many went +uint32_t own_drop_where_locked(int (^gone)(id o), void (^each)(uint64_t serial)); // ---- What the replay layer provides (nvn_mtl.m). Called with g_smu held void own_hook_drop(id o, int keep_resident); // an object the owner lets go: released after the submission in flight (keep_resident: it stays in the residency set, as something else holds it) @@ -137,6 +140,8 @@ uint64_t own_hook_frame(void); // the frame being replayed (pres const void *own_live_ref_locked(uint64_t k); int serial_table_holds(const void *o); // a live entry or a texture pin holds o (or a view of it) int entry_holds(const void *o); // that, or a ghost entry +int own_ghost_holds_locked(const void *o); // a ghost entry holds o (or a view of it): the replay layer's census +uint64_t own_alias_seen_locked(const alias_key *k); // the submission of k's last lookup (0: none recorded): the census int tex_object_pinned(id o); int own_shared_locked(id o); // the sharing table holds o id own_alias_get_locked(const alias_key *k); diff --git a/dm/gfx/nvn/nvn_owner.m b/dm/gfx/nvn/nvn_owner.m index 1f504c2ba9..e8ec93ae52 100644 --- a/dm/gfx/nvn/nvn_owner.m +++ b/dm/gfx/nvn/nvn_owner.m @@ -66,6 +66,7 @@ int own_note_at(uint64_t gen, uint64_t *serial) { int serial_table_holds(const void *o) { uintptr_t k = (uintptr_t)o; return nvn_hm_get(&g_by_serial_held, &k) != NULL; } int entry_holds(const void *o) { uintptr_t k = (uintptr_t)o; return serial_table_holds(o) || (g_ghost_held.n && nvn_hm_get(&g_ghost_held, &k)); } +int own_ghost_holds_locked(const void *o) { uintptr_t k = (uintptr_t)o; return g_ghost_held.n && nvn_hm_get(&g_ghost_held, &k) != NULL; } int tex_object_pinned(id o) { uintptr_t key = (uintptr_t)(__bridge void *)o; return o && nvn_hm_get(&g_tex_pin_objects, &key) != NULL; } int own_object_free(id o) { pthread_mutex_lock(&g_smu); int r = !entry_holds((__bridge void *)o); pthread_mutex_unlock(&g_smu); return r; } @@ -166,6 +167,7 @@ static void alias_put(const alias_key *k, id o, uint64_t seen) { // an entry k if (!g_alias_set) g_alias_set = CFSetCreateMutable(NULL, 0, NULL); hm_put_id(&g_alias, k, o); alias_index(k, 1); CFSetAddValue(g_alias_set, (__bridge const void *)o); if (seen) alias_seen(k, seen); } +uint64_t own_alias_seen_locked(const alias_key *k) { return (uint64_t)(uintptr_t)nvn_hm_get(&g_alias_seen, k); } id own_alias_get_locked(const alias_key *k) { return hm_get_id(&g_alias, k); } id own_alias_peek(const alias_key *k) { pthread_mutex_lock(&g_smu); id o = hm_get_id(&g_alias, k); pthread_mutex_unlock(&g_smu); return o; } void own_alias_put_locked(const alias_key *k, id o, uint64_t seen) { alias_put(k, o, seen); } @@ -430,6 +432,19 @@ void own_each_locked(void (^fn)(uint64_t serial, id o, int ghost)) { uint64_t k; memcpy(&k, tables[j]->keys + (size_t)i * 8, 8); fn(k, (__bridge id)tables[j]->vals[i], j); } } +uint32_t own_drop_where_locked(int (^gone)(id o), void (^each)(uint64_t serial)) { + uint32_t n = 0; + for (int j = 0; j < 2; j++) { // the keys first, then the deletes (a delete moves entries) + nvn_hmap *t = j ? &g_ghost : &g_by_serial; uint64_t *ks = NULL; uint32_t nk = 0; + for (uint32_t i = 0; i < t->cap; i++) { + if (!t->vals[i] || !gone((__bridge id)t->vals[i])) continue; + uint64_t *nks = realloc(ks, (nk + 1) * sizeof *ks); if (!nks) ODIE("the dropped serials"); ks = nks; memcpy(&ks[nk++], t->keys + (size_t)i * 8, 8); + } + for (uint32_t i = 0; i < nk; i++) { if (j) ghost_del_locked(ks[i]); else live_del_locked(ks[i]); if (each) each(ks[i]); } + n += nk; free(ks); + } + return n; +} static void expect_one(CFMutableDictionaryRef want, id o) { // o, and each texture it is a view of, once more for (; o; o = [o respondsToSelector:@selector(parentTexture)] ? ((id)o).parentTexture : nil) CFDictionarySetValue(want, (__bridge const void *)o, (const void *)((uintptr_t)CFDictionaryGetValue(want, (__bridge const void *)o) + 1)); diff --git a/dm/gfx/nvn/nvn_queue.inc b/dm/gfx/nvn/nvn_queue.inc index bdb2beb5f0..755b50223b 100644 --- a/dm/gfx/nvn/nvn_queue.inc +++ b/dm/gfx/nvn/nvn_queue.inc @@ -109,16 +109,18 @@ static void nq_cost_end(nq_cost c) { atomic_fetch_add(&g_sub_instr,ins-c.instr); atomic_fetch_add(&g_cum_sub_instr,ins-c.instr); atomic_fetch_add(&g_cum_sub_cyc,cyc-c.cycles); atomic_fetch_add(&g_cum_sub_sys_ns,thr_sys_ns()-c.sys); } +void mtl_gp_note_park(uint64_t t0,unsigned why,uint64_t queue); // nvn_mtl.m: DM_NVN_GPUPROF's CPU timeline static void *nq_worker(void *unused) { (void)unused; pthread_setname_np("NVN queue replay"); pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE,0); uint64_t frame=UINT64_MAX; + uint64_t park0=0,park_q=0; unsigned park_why=0; // parked since park0 (mach ticks) and why: 0 no work queued, 1 an event wait, 2 a sync wait holds queue park_q (the first held) for(;;) { pthread_mutex_lock(&nq_mu); nq_queue *q=NULL; nq_node *n=NULL; nq_job *j=NULL; for(;;) { scan_again:; if(nq_test_held) { pthread_cond_wait(&nq_cv,&nq_mu); continue; } - int mapped_event_wait=0; + int mapped_event_wait=0; unsigned held_why=0; uint64_t held_q=0; for(q=nq_queues;q;q=q->next) { j=q->first; if(!j) continue; n=j->first; if(!n) { nq_publish(j->receipt,q->physical); q->first=j->next; if(!q->first) q->last=NULL; nq_put(j->receipt); @@ -136,14 +138,14 @@ static void *nq_worker(void *unused) { else if(t-n->wait_since>5000000000ull && !n->wait_said) { static _Atomic int said; n->wait_said=1; if(atomic_fetch_add(&said,1)<8) LOG("[RED] queue %llu: an event wait has held it %.1f s: word %p is %#x, waiting for %s %#x; a GPU write of it is %s",(unsigned long long)q->serial,(t-n->wait_since)/1e9,(void *)n->event, atomic_load_explicit((_Atomic uint32_t *)n->event,memory_order_acquire),n->mode==0?"equal to":"at least",n->value,predecessor>mtl_completed_fence()?"queued, not completed":"not queued"); } - n->waiting=1; mapped_event_wait=1; continue; } + n->waiting=1; mapped_event_wait=1; if(!held_why) { held_why=1; held_q=q->serial; } continue; } } if(n->kind==NQ_SYNC) { if(n->receipt && !n->receipt->published) { uint64_t t=now_ns(); if(!n->wait_since) n->wait_since=t; else if(t-n->wait_since>5000000000ull && !n->wait_said) { static _Atomic int said; n->wait_said=1; if(atomic_fetch_add(&said,1)<8) LOG("[RED] queue %llu: a sync wait has held it %.1f s: the fence it waits for (receipt %p) is not published yet",(unsigned long long)q->serial,(t-n->wait_since)/1e9,(void *)n->receipt); } - continue; } + if(!held_why) { held_why=2; held_q=q->serial; } continue; } // Targets are immutable snapshots. One Metal queue orders an encoded producer before this continuation. A sync not yet fenced when the wait was submitted // (wait_kind 0) is a snapshot of nothing to wait for, and the wait passes. Sparking! ZERO, on one NVN queue, waits on a sync before that queue's own first // fence of it at its first load, which runs on the console; parked here, the fence behind the wait never published and its SyncWait stalled the game (#1808) @@ -151,11 +153,14 @@ static void *nq_worker(void *unused) { break; } if(q) break; + if(park0 && (held_why!=park_why || held_q!=park_q)) { mtl_gp_note_park(park0,park_why,park_q); park0=0; } + if(!park0) { park0=mach_absolute_time(); park_why=held_why; park_q=held_q; } // NVN events can also be changed by plain stores through mapped pool memory. // A bounded notification poll only while such a word is awaited complements API/callback wakes. if(mapped_event_wait) { struct timespec tick={0,1000000}; pthread_cond_timedwait_relative_np(&nq_cv,&nq_mu,&tick); } else pthread_cond_wait(&nq_cv,&nq_mu); } + if(park0) { mtl_gp_note_park(park0,park_why,park_q); park0=0; } j->first=n->next; if(!j->first) j->last=NULL; // Round-robin ready queues: a continually fed independent producer cannot starve another queue. if(q->next) { nq_queue **link=&nq_queues; while(*link!=q) link=&(*link)->next; *link=q->next; nq_queue *tail=nq_queues; while(tail->next) tail=tail->next; tail->next=q; q->next=NULL; } diff --git a/dm/gfx/nvn/nvn_rec.h b/dm/gfx/nvn/nvn_rec.h index b008d3da47..0a4f4da0ca 100644 --- a/dm/gfx/nvn/nvn_rec.h +++ b/dm/gfx/nvn/nvn_rec.h @@ -130,26 +130,112 @@ static void rec_note_wait(_Atomic uint64_t *p, uint64_t v) { // ---------- The encode thread ---------- static id g_rx_cb, g_rx_enc; // the encode thread's real command buffer and open encoder +// ---------- Submissions committed together ---------- +// A submission's commit is held while the GPU still runs a main command buffer committed earlier: its command buffer is ended and kept, the next submissions' go into command buffers +// of their own, and the held ones reach the queue in one commit call, in order. A game that splits its frame at every event signal makes many small submissions (Ocarina of Time 22 +// to 30 a frame, each cut again at its waits, signals and fences by the queue scheduler), and they all reach the queue within a few milliseconds, behind the frame's first one. +// Command buffers queued behind running work are the condition for the kernel's stall (docs/reference/frame-rate.md, "The GPU idles with the next command buffer already +// committed"): on the iPhone 17, with the GPU at a low clock, the second command buffer of a frame started 22 to 37 ms after the first had ended in three frames of four, the GPU then +// read 55 to 75 % busy and its governor never raised the clock again (5 to 12 fps where the same scene holds 30). The held ones are committed when the GPU runs out of work (at the end +// of an encoder), when nothing more is recorded for about half a millisecond, when the submit thread drains the encode thread, and before anything else goes to the queue (an +// upload batch, a snapshot copy, a queue operation, a signal of its own): each command buffer keeps its place among those exactly as when it was committed on its own. A first version +// put the next submissions into the held command buffer itself; an upload batch recorded inside a submission then went to the queue after the draws of that submission recorded +// before it, which sampled the textures before their upload (pink and dark flashes on the iPhone, and a GPU error and recovery). Each held submission's feedback gets its own part of +// the commit's GPU time, from the stamp its successor's first encoder writes (ts_sub_begin) where there is one, so a counter report that falls back to its command buffer's times +// (rep_ticks) reads what it read on its own. DM_NVN_SUB_MERGE=0 commits every submission on its own again (ab: alternates with the DM_AB phases, for measurement) +enum { RX_PEND_MAX = 48 }; +static id g_rx_held_cb[RX_PEND_MAX]; static DmCommitFB *g_rx_fb[RX_PEND_MAX]; static id g_rx_stamp_heap[RX_PEND_MAX]; static int g_rx_stamp[RX_PEND_MAX], g_rx_npend; // the held submissions, oldest first; stamp: the heap slot of the boundary after it (-1: none) +static int g_rx_after, g_rx_want_stamp; // the last record was a held commit (or its signal or note); the next boundary stamp is the last held submission's end +static uint64_t g_rx_ubc; // the newest uniform shadow the held submissions read (ubc_wait at the commit) +static struct { uint64_t v; _Atomic uint64_t *p; } g_rx_post[2 * RX_PEND_MAX + 4]; static id g_rx_post_ev[2 * RX_PEND_MAX + 4]; static int g_rx_npost; // the signals (an event) and notes that followed held commits: made after the real one, in order +static _Atomic int g_rx_fly, g_rx_held, g_rx_drain; // main command buffers committed and not reported back; commits are held (rec_drain waits for them); rec_drain callers waiting +static uint64_t g_rx_merged, g_rx_cbs; static int g_rx_last_nb; // submissions held and committed with a later one; commit calls of main command buffers; command buffers in the last one +static int sw_mode(const char *name, int dflt); static inline int sw_on(int m); +static int rx_merge_on(void) { + static int v = -1; + if (v < 0) { const char *e = getenv("DM_NVN_SUB_MERGE"); v = e && !strncmp(e, "ab", 2) ? sw_mode("DM_NVN_SUB_MERGE", 0) : !(e && !strcmp(e, "0")); + if (!v) MLOG("DM_NVN_SUB_MERGE=0: every submission is committed on its own"); } + return sw_on(v); +} +static double rx_stamp_s(id heap, int slot) { // a boundary stamp in seconds on the Mach clock, as a commit feedback's GPU times are; 0 when it was not written + if (!heap || slot < 0) return 0; + NSData *d = [(id)heap resolveCounterRange:NSMakeRange((NSUInteger)slot, 1)]; const MTL4TimestampHeapEntry *en = d.bytes; + if (!en || d.length < sizeof *en || !en->timestamp) return 0; + MTLTimestamp cpu = 0, gpu = 0; [g_dev sampleTimestamps:&cpu gpuTimestamp:&gpu]; + static double scale; if (!scale) { uint64_t hz = [g_dev queryTimestampFrequency]; scale = hz ? 1e9 / (double)hz : 1; } + double ago = (double)gpu - (double)en->timestamp * scale; + return cpu && ago >= 0 && ago < 2e9 ? ((double)cpu - ago) / 1e9 : 0; +} +// One commit call: the held command buffers, then (cur) the encode thread's own, ended by the caller, with its feedback own (nil: none). The held ones' feedback comes first +static void rx_commit(int cur, DmCommitFB *own, uint64_t ubc) { + int n = g_rx_npend, nb = n + (cur != 0), cnt = nb; if (!nb) return; + id buffers[RX_PEND_MAX + 1]; + NSMutableArray *fbs = [NSMutableArray arrayWithCapacity:(NSUInteger)cnt], *heaps = [NSMutableArray arrayWithCapacity:(NSUInteger)(n ? n : 1)]; NSMutableData *st = [NSMutableData dataWithLength:(NSUInteger)(n ? n : 1) * sizeof(int)]; int *sl = st.mutableBytes; + for (int i = 0; i < n; i++) { buffers[i] = g_rx_held_cb[i]; [fbs addObject:g_rx_fb[i]]; [heaps addObject:g_rx_stamp_heap[i] ?: (id)NSNull.null]; sl[i] = g_rx_stamp[i]; g_rx_held_cb[i] = nil; g_rx_fb[i] = nil; g_rx_stamp_heap[i] = nil; } + if (cur) { buffers[n] = g_rx_cb; [fbs addObject:own ?: (id)NSNull.null]; } + if (g_rx_ubc > ubc) ubc = g_rx_ubc; + g_rx_ubc = 0; g_rx_npend = 0; g_rx_want_stamp = 0; atomic_store(&g_rx_held, 0); + ubc_wait(ubc); // the uniform shadows these command buffers read + MTL4CommitOptions *o = [MTL4CommitOptions new]; + atomic_fetch_add(&g_rx_fly, 1); + [o addFeedbackHandler:^(id f) { + atomic_fetch_sub(&g_rx_fly, 1); + if (cnt == 1) { if (fbs[0] != NSNull.null) for (void (^b)(id) in ((DmCommitFB *)fbs[0])->blocks) b(f); return; } + double t[RX_PEND_MAX + 2]; const int *ss = st.bytes; t[0] = f.GPUStartTime; t[cnt] = f.GPUEndTime; + for (int i = 1; i < cnt; i++) { double at = i - 1 < n && heaps[(NSUInteger)(i - 1)] != NSNull.null ? rx_stamp_s(heaps[(NSUInteger)(i - 1)], ss[i - 1]) : 0; t[i] = at > 0 && at >= t[0] && at <= t[cnt] ? at : -1; } + for (int i = cnt - 1; i >= 1; i--) if (t[i] < 0 || t[i] > t[i + 1]) t[i] = t[i + 1]; // no stamp (an encoder with no work writes none): the submission ends where the next known boundary is + for (int i = 0; i < cnt; i++) { if (fbs[(NSUInteger)i] == NSNull.null) continue; DmPartFB *part = [DmPartFB new]; part->t0 = t[i]; part->t1 = t[i + 1]; part->err = f.error; + for (void (^b)(id) in ((DmCommitFB *)fbs[(NSUInteger)i])->blocks) b((id)part); } + }]; + pthread_mutex_lock(&g_res_commit_mu); + [g_q4 commit:buffers count:(NSUInteger)nb options:o]; + pthread_mutex_unlock(&g_res_commit_mu); + if (cur) g_rx_cb = nil; + g_rx_cbs++; g_rx_merged += (uint64_t)n; g_rx_last_nb = nb; + for (int i = 0; i < g_rx_npost; i++) { // what followed the held commits + if (g_rx_post_ev[i]) { [g_q4 signalEvent:g_rx_post_ev[i] value:g_rx_post[i].v]; g_rx_post_ev[i] = nil; } + else { _Atomic uint64_t *np = g_rx_post[i].p; pthread_mutex_lock(&g_note_mu); if (g_rx_post[i].v > atomic_load(np)) atomic_store(np, g_rx_post[i].v); pthread_cond_broadcast(&g_note_cv); pthread_mutex_unlock(&g_note_mu); } + } + g_rx_npost = 0; + if (g_rx_cbs % 20000 == 0) MLOG("held submissions: %llu commits of main command buffers so far, %llu submissions committed with a later one (DM_NVN_SUB_MERGE)", (unsigned long long)g_rx_cbs, (unsigned long long)g_rx_merged); +} +static void rx_flush(void) { if (g_rx_npend) rx_commit(0, nil, 0); } // the held command buffers go to the queue now static void rec_exec(const rec_t *r) { const uint64_t *a = r->a; id e = g_rx_enc; + int after = g_rx_after; if (r->op != RO_SIGNAL && r->op != RO_NOTE) g_rx_after = 0; switch (r->op) { case RO_CB_NEW: g_rx_cb = [g_dev newCommandBuffer]; break; case RO_CB_BEGIN: [(id)g_rx_cb beginCommandBufferWithAllocator:rec_id(a[0])]; break; case RO_CB_END: [(id)g_rx_cb endCommandBuffer]; break; case RO_CB_BLOCK: ((void (^)(id))rec_id(a[0]))(g_rx_cb); break; - case RO_COMMIT: case RO_COMMIT_REAL: { - if (r->op == RO_COMMIT) ubc_wait(a[2]); // the uniform shadows this command buffer reads - id buffers[] = {r->op == RO_COMMIT ? g_rx_cb : rec_id(a[1])}; MTL4CommitOptions *o = rec_id(a[0]); + case RO_COMMIT: { // a main command buffer (ended): a[0] its feedback, a[2] its uniform shadows, a[3] / a[4] submission and segment, a[5] the submission ends with it + uint64_t gt0 = atomic_load_explicit(&g_gt_on, memory_order_relaxed) ? mach_absolute_time() : 0; + DmCommitFB *fb = rec_id(a[0]); + if (a[5] && fb && g_rx_npend < RX_PEND_MAX && atomic_load(&g_rx_fly) > 0 && !atomic_load(&g_rx_drain) && rx_merge_on()) { // held: the GPU has work + g_rx_held_cb[g_rx_npend] = g_rx_cb; g_rx_fb[g_rx_npend] = fb; g_rx_stamp[g_rx_npend] = -1; g_rx_stamp_heap[g_rx_npend] = nil; g_rx_npend++; if (a[2] > g_rx_ubc) g_rx_ubc = a[2]; + g_rx_cb = nil; g_rx_after = 1; g_rx_want_stamp = 1; atomic_store(&g_rx_held, 1); + break; } + rx_commit(1, fb, a[2]); + if (gt0) gt_put(GT_COMMIT, gt0, a[3], a[4]); // DM_NVN_GPUPROF's timeline: submission, segment + break; } + case RO_COMMIT_REAL: { // an upload batch, a snapshot copy: a whole command buffer, after everything recorded before it + uint64_t gt0 = atomic_load_explicit(&g_gt_on, memory_order_relaxed) ? mach_absolute_time() : 0; + rx_flush(); + id buffers[] = {rec_id(a[1])}; MTL4CommitOptions *o = rec_id(a[0]); pthread_mutex_lock(&g_res_commit_mu); // apart from the residency set's commit, as the present snapshot's queue commit (nvn_mtl.m res_commit) if (o) [g_q4 commit:buffers count:1 options:o]; else [g_q4 commit:buffers count:1]; pthread_mutex_unlock(&g_res_commit_mu); - if (r->op == RO_COMMIT) g_rx_cb = nil; + if (gt0) gt_put(GT_COMMIT, gt0, a[3], UINT32_MAX); // (an upload batch: no segment) break; } - case RO_SIGNAL: [g_q4 signalEvent:rec_id(a[0]) value:a[1]]; break; - case RO_Q_BLOCK: ((void (^)(void))rec_id(a[0]))(); break; + case RO_SIGNAL: + if (after && g_rx_npend && g_rx_npost < (int)(sizeof g_rx_post / sizeof *g_rx_post)) { g_rx_post_ev[g_rx_npost] = rec_id(a[0]); g_rx_post[g_rx_npost].v = a[1]; g_rx_post[g_rx_npost++].p = NULL; g_rx_after = 1; break; } // its command buffer is not committed yet + rx_flush(); [g_q4 signalEvent:rec_id(a[0]) value:a[1]]; break; + case RO_Q_BLOCK: rx_flush(); ((void (^)(void))rec_id(a[0]))(); break; case RO_RE_BEGIN: g_rx_enc = [(id)g_rx_cb renderCommandEncoderWithDescriptor:rec_id(a[0])]; break; case RO_CE_BEGIN: g_rx_enc = [(id)g_rx_cb computeCommandEncoder]; break; - case RO_END: [(id)e endEncoding]; g_rx_enc = nil; break; + case RO_END: [(id)e endEncoding]; g_rx_enc = nil; g_rx_want_stamp = 0; + if (g_rx_npend && (!atomic_load(&g_rx_fly) || atomic_load(&g_rx_drain))) rx_flush(); // the GPU has run out of work (or the submit thread waits): the held ones go to it + break; case RO_BAR_QUEUE: [(id)e barrierAfterQueueStages:a[0] beforeStages:a[1] visibilityOptions:a[2]]; break; case RO_BAR_AFTER_STAGES: [(id)e barrierAfterStages:a[0] beforeQueueStages:a[1] visibilityOptions:a[2]]; break; case RO_BAR_ENCODER: [(id)e barrierAfterEncoderStages:a[0] beforeEncoderStages:a[1] visibilityOptions:a[2]]; break; @@ -197,9 +283,15 @@ static void rec_exec(const rec_t *r) { case RO_T_TEX: [(id)rec_id(a[0]) setTexture:(MTLResourceID){a[1]} atIndex:a[2]]; break; case RO_T_SAMP: [(id)rec_id(a[0]) setSamplerState:(MTLResourceID){a[1]} atIndex:a[2]]; break; case RO_LABEL: [(id)e setLabel:rec_id(a[0])]; break; - case RO_R_TS: [(id)e writeTimestampWithGranularity:a[1] afterStage:a[2] intoHeap:rec_id(a[0]) atIndex:a[3]]; break; - case RO_C_TS: [(id)e writeTimestampWithGranularity:a[1] intoHeap:rec_id(a[0]) atIndex:a[2]]; break; - case RO_NOTE: { _Atomic uint64_t *p = (_Atomic uint64_t *)(uintptr_t)a[0]; pthread_mutex_lock(&g_note_mu); if (a[1] > atomic_load(p)) atomic_store(p, a[1]); pthread_cond_broadcast(&g_note_cv); pthread_mutex_unlock(&g_note_mu); break; } + case RO_R_TS: [(id)e writeTimestampWithGranularity:a[1] afterStage:a[2] intoHeap:rec_id(a[0]) atIndex:a[3]]; + if (g_rx_want_stamp && g_rx_npend && rec_id(a[0]) == (id)g_ts_heap) { g_rx_stamp_heap[g_rx_npend - 1] = rec_id(a[0]); g_rx_stamp[g_rx_npend - 1] = (int)a[3]; g_rx_want_stamp = 0; } // the submission's begin stamp: where the deferred one before it ends + break; + case RO_C_TS: [(id)e writeTimestampWithGranularity:a[1] intoHeap:rec_id(a[0]) atIndex:a[2]]; + if (g_rx_want_stamp && g_rx_npend && rec_id(a[0]) == (id)g_ts_heap) { g_rx_stamp_heap[g_rx_npend - 1] = rec_id(a[0]); g_rx_stamp[g_rx_npend - 1] = (int)a[2]; g_rx_want_stamp = 0; } + break; + case RO_NOTE: { _Atomic uint64_t *p = (_Atomic uint64_t *)(uintptr_t)a[0]; + if (after && g_rx_npend && g_rx_npost < (int)(sizeof g_rx_post / sizeof *g_rx_post)) { g_rx_post_ev[g_rx_npost] = nil; g_rx_post[g_rx_npost].v = a[1]; g_rx_post[g_rx_npost++].p = p; g_rx_after = 1; break; } // noted once its command buffer is committed + pthread_mutex_lock(&g_note_mu); if (a[1] > atomic_load(p)) atomic_store(p, a[1]); pthread_cond_broadcast(&g_note_cv); pthread_mutex_unlock(&g_note_mu); break; } default: MDIE("deferred encoding: unknown record %u", r->op); } for (uint32_t i = 0; i < r->nobj; i++) if (a[i]) CFRelease((CFTypeRef)(uintptr_t)a[i]); @@ -209,7 +301,17 @@ static void *rec_thread(void *arg) { pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0); for (;;) { pthread_mutex_lock(&g_rb_mu); - while (!g_rb_head) { g_rb_sleeping = 1; pthread_cond_wait(&g_rb_work, &g_rb_mu); g_rb_sleeping = 0; } + while (!g_rb_head) { + if (g_rx_npend) { // held commits and nothing more to encode: a short wait for the next submission while the GPU still has work, then they go + for (int k = 0; k < 3 && !g_rb_head && atomic_load(&g_rx_fly) > 0 && !atomic_load(&g_rx_drain); k++) { struct timespec ts = {0, 150000}; g_rb_sleeping = 1; pthread_cond_timedwait_relative_np(&g_rb_work, &g_rb_mu, &ts); g_rb_sleeping = 0; } + if (g_rb_head) break; + g_rb_busy = 1; pthread_mutex_unlock(&g_rb_mu); + @autoreleasepool { rx_flush(); } + pthread_mutex_lock(&g_rb_mu); g_rb_busy = 0; if (!g_rb_head) pthread_cond_broadcast(&g_rb_idle); + continue; + } + g_rb_sleeping = 1; pthread_cond_wait(&g_rb_work, &g_rb_mu); g_rb_sleeping = 0; + } rec_blk *b = g_rb_head; g_rb_head = b->next; if (!g_rb_head) g_rb_tail = NULL; g_rb_busy = 1; pthread_mutex_unlock(&g_rb_mu); @autoreleasepool { for (int i = 0; i < b->n; i++) rec_exec(&b->r[i]); } @@ -248,7 +350,9 @@ static void rec_drain(void) { rec_publish(); uint64_t w0 = ws_t0(); int blocked = 0; pthread_mutex_lock(&g_rb_mu); - while (g_rb_head || g_rb_busy) { blocked = 1; pthread_cond_wait(&g_rb_idle, &g_rb_mu); } + atomic_fetch_add(&g_rx_drain, 1); if (g_rb_sleeping) pthread_cond_signal(&g_rb_work); // held commits go now (DM_NVN_SUB_MERGE) + while (g_rb_head || g_rb_busy || atomic_load(&g_rx_held)) { blocked = 1; struct timespec ts = {0, 2000000}; pthread_cond_timedwait_relative_np(&g_rb_idle, &g_rb_mu, &ts); if (g_rb_sleeping) pthread_cond_signal(&g_rb_work); } + atomic_fetch_sub(&g_rx_drain, 1); pthread_mutex_unlock(&g_rb_mu); if (ws_on()) ws_put(WS_DRAIN, w0, blocked); } @@ -366,15 +470,17 @@ static void rec_cb_block(id cb, void (^block)(id)) { } static id rec_table(id t) { if (!rec_on() || !t) return t; DmRecTable *s = [DmRecTable new]; s->real = t; return s; } // The replay's main command buffer: committed once the uniform shadows queued so far are made (ubc_wait) -static void rec_commit(id cb, MTL4CommitOptions *o) { - if ([cb isKindOfClass:[DmRecCB class]]) { rec_t *r = rec_put(RO_COMMIT, 1); r->a[0] = rec_obj(o); r->a[2] = ubc_head(); return; } +static void rec_commit(id cb, DmCommitFB *fb, int end) { // end: the submission ends with this command buffer (the encode thread may keep it open for the next one: merged submissions) + if ([cb isKindOfClass:[DmRecCB class]]) { rec_t *r = rec_put(RO_COMMIT, 1); r->a[0] = rec_obj(fb); r->a[2] = ubc_head(); r->a[3] = g_sub_serial; r->a[4] = g_seg; r->a[5] = (uint64_t)end; return; } + uint64_t gt0 = atomic_load_explicit(&g_gt_on, memory_order_relaxed) ? mach_absolute_time() : 0; ubc_wait(ubc_head()); - id buffers[] = {cb}; + id buffers[] = {cb}; MTL4CommitOptions *o = commit_opts(fb); if (o) [g_q4 commit:buffers count:1 options:o]; else [g_q4 commit:buffers count:1]; + if (gt0) gt_put(GT_COMMIT, gt0, g_sub_serial, g_seg); } // An upload batch: its place in the queue is after what is recorded so far (it reads no uniform shadow) static void rec_commit_upload(id cb, MTL4CommitOptions *o) { - if (rec_on() && g_rb_started) { rec_t *r = rec_put(RO_COMMIT_REAL, 2); r->a[0] = rec_obj(o); r->a[1] = rec_obj(cb); return; } + if (rec_on() && g_rb_started) { rec_t *r = rec_put(RO_COMMIT_REAL, 2); r->a[0] = rec_obj(o); r->a[1] = rec_obj(cb); r->a[3] = g_sub_serial; return; } id buffers[] = {cb}; if (o) [g_q4 commit:buffers count:1 options:o]; else [g_q4 commit:buffers count:1]; } diff --git a/dm/gfx/nvn/nvn_res_probe.inc b/dm/gfx/nvn/nvn_res_probe.inc new file mode 100644 index 0000000000..248d4195a2 --- /dev/null +++ b/dm/gfx/nvn/nvn_res_probe.inc @@ -0,0 +1,137 @@ +// What an Apple GPU does when a shader reads or writes through a pointer to a buffer outside the residency set (docs/reference/memory.md, "A read through a pointer to a buffer outside +// the residency set returns zeros"). The raw pool table (nvn_mtl.m gmem_map) hands shaders the GPU addresses of memory pools, which they reach through pointers loaded from memory, out +// of Metal's sight; whether a pool could stay out of the residency set until a shader needs it depends on what such an access does. Each case: a no-copy shared buffer over page-aligned +// memory (as a pool wraps the game's pages), one word per 4 KiB page filled, its GPU address in a resident argument buffer; a kernel copies the words through that pointer into a +// resident output buffer (or writes through it). A Metal 4 queue with the residency set on the queue, as the host has it. Its own queue, set and allocator: it runs before the game, or +// alone (dm/gfx/tests/t_res_absent.m; the host with DM_RES_PROBE=1, mtl_init). say() gets one line per case; returns 0 when a resident control went wrong +#include +#include +#include +static const char *const kResProbeSrc = + "#include \n" + "using namespace metal;\n" + "struct P { device uint *p; };\n" + "kernel void rd(constant P &a [[buffer(0)]], device uint *out [[buffer(1)]], constant uint &n [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n" + " if (i < n) out[i] = a.p[i * 1024u];\n" + "}\n" + "kernel void wr(constant P &a [[buffer(0)]], device uint *out [[buffer(1)]], constant uint &n [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n" + " if (i < n) { a.p[i * 1024u] = 0xC0DE0000u | i; out[i] = 1u; }\n" + "}\n"; +enum { RP_WORDS = 4096 }; // pages touched per case: 16 MiB of buffer +typedef struct { id dev; id q; id res; id alloc; id at; id rd, wr; } rp_ctx; +typedef struct { int faulted; char err[400]; } rp_run; +typedef enum { RP_ANON, RP_FILE, RP_FILE_CACHE } rp_mem; +static uint32_t rp_pat(uint32_t i) { return 0xA5000000u | i; } +static rp_run rp_dispatch(rp_ctx *c, id pso, id target, id out) { + rp_run r = {0}; + id args = [c->dev newBufferWithLength:16 options:MTLResourceStorageModeShared], nb = [c->dev newBufferWithLength:16 options:MTLResourceStorageModeShared]; + *(uint64_t *)args.contents = target.gpuAddress; *(uint32_t *)nb.contents = RP_WORDS; + memset(out.contents, 0xEE, out.length); + [c->res addAllocation:args]; [c->res addAllocation:nb]; [c->res addAllocation:out]; [c->res commit]; + [c->alloc reset]; + id cb = [c->dev newCommandBuffer]; + [cb beginCommandBufferWithAllocator:c->alloc]; + id e = [cb computeCommandEncoder]; + [c->at setAddress:args.gpuAddress atIndex:0]; [c->at setAddress:out.gpuAddress atIndex:1]; [c->at setAddress:nb.gpuAddress atIndex:2]; + [e setArgumentTable:c->at]; [e setComputePipelineState:pso]; + [e dispatchThreads:MTLSizeMake(RP_WORDS, 1, 1) threadsPerThreadgroup:MTLSizeMake(64, 1, 1)]; + [e endEncoding]; [cb endCommandBuffer]; + dispatch_semaphore_t done = dispatch_semaphore_create(0); rp_run *rp = &r; + MTL4CommitOptions *o = [MTL4CommitOptions new]; + [o addFeedbackHandler:^(id f) { + if (f.error) { NSError *u = f.error.userInfo[NSUnderlyingErrorKey]; rp->faulted = 1; + snprintf(rp->err, sizeof rp->err, "%s%s%s", f.error.description.UTF8String, u ? " | underlying: " : "", u ? u.description.UTF8String : ""); } + dispatch_semaphore_signal(done); + }]; + const id cbs[1] = {cb}; + [c->q commit:cbs count:1 options:o]; + if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC))) { r.faulted = 2; snprintf(r.err, sizeof r.err, "no feedback within 10 s"); } + [c->res removeAllocation:args]; [c->res removeAllocation:nb]; [c->res removeAllocation:out]; [c->res commit]; + return r; +} +static void *rp_mem_new(rp_mem k, size_t n, int *fd_out) { + *fd_out = -1; + if (k == RP_ANON) { void *p = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); return p == MAP_FAILED ? NULL : p; } + char path[1024]; snprintf(path, sizeof path, "%s/dm_res_probe.XXXXXX", NSTemporaryDirectory().UTF8String); // 16 MiB, removed at once + int fd = mkstemp(path); if (fd < 0) return NULL; + unlink(path); + if (ftruncate(fd, (off_t)n)) { close(fd); return NULL; } + if (k == RP_FILE_CACHE) for (uint32_t i = 0; i < RP_WORDS; i++) { uint32_t v = rp_pat(i); if (pwrite(fd, &v, 4, (off_t)i * 4096) != 4) { close(fd); return NULL; } } // in the page cache only + void *p = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); // the game's memory is a shared file mapping too where it goes into files (iOS) + if (p == MAP_FAILED) { close(fd); return NULL; } + *fd_out = fd; return p; +} +// history: 0 never resident; 1 resident for a commit that read it, then removed; 2 resident (a control); 3 never resident, another buffer over the same pages resident; +// 4 as 1, then 32 other commits; 5 as 1, then 2 s; 6 read while not resident, then made resident and read again +static int rp_case(rp_ctx *c, const char *name, rp_mem k, int history, int write, void (*say)(const char *)) { + char line[700]; size_t n = (size_t)RP_WORDS * 4096; int fd; void *p = rp_mem_new(k, n, &fd); + if (!p) { snprintf(line, sizeof line, "%-34s could not map memory", name); say(line); return 1; } + if (k != RP_FILE_CACHE) for (uint32_t i = 0; i < RP_WORDS; i++) ((uint32_t *)p)[i * 1024u] = rp_pat(i); + id b = [c->dev newBufferWithBytesNoCopy:p length:n options:MTLResourceStorageModeShared deallocator:nil]; + id out = [c->dev newBufferWithLength:RP_WORDS * 4 options:MTLResourceStorageModeShared], twin = nil; + char pre[160] = ""; + if (history == 1 || history == 4 || history == 5) { + [c->res addAllocation:b]; [c->res commit]; rp_dispatch(c, c->rd, b, out); [c->res removeAllocation:b]; [c->res commit]; + if (history == 4) { id o2 = [c->dev newBufferWithLength:n options:MTLResourceStorageModeShared]; [c->res addAllocation:o2]; [c->res commit]; for (int j = 0; j < 32; j++) rp_dispatch(c, c->rd, o2, out); [c->res removeAllocation:o2]; [c->res commit]; } + if (history == 5) sleep(2); + } else if (history == 2) { [c->res addAllocation:b]; [c->res commit]; } + else if (history == 3) { twin = [c->dev newBufferWithBytesNoCopy:p length:n options:MTLResourceStorageModeShared deallocator:nil]; [c->res addAllocation:twin]; [c->res commit]; } + else if (history == 6) { + rp_run cold = rp_dispatch(c, c->rd, b, out); int got = 0; for (uint32_t i = 0; i < RP_WORDS; i++) got += ((uint32_t *)out.contents)[i] == rp_pat(i); + snprintf(pre, sizeof pre, " (before it was resident: %s, data %d)", cold.faulted ? "FAULT" : "ok", got); + [c->res addAllocation:b]; [c->res commit]; + } + rp_run r = rp_dispatch(c, write ? c->wr : c->rd, b, out); + int good = 0, zero = 0, other = 0, untouched = 0; + for (uint32_t i = 0; i < RP_WORDS; i++) { + uint32_t v = ((uint32_t *)out.contents)[i]; + if (write) { uint32_t m = ((uint32_t *)p)[i * 1024u]; if (m == (0xC0DE0000u | i)) good++; else if (m == 0) zero++; else other++; } + else if (v == 0xEEEEEEEEu) untouched++; else if (v == rp_pat(i)) good++; else if (v == 0) zero++; else other++; + } + snprintf(line, sizeof line, "%-34s %-5s %s %d/%d, zero %d, other %d, output unwritten %d%s%s%s", name, r.faulted == 1 ? "FAULT" : r.faulted == 2 ? "HANG" : "ok", + write ? "landed" : "data", good, RP_WORDS, zero, other, untouched, pre, r.faulted ? " | error: " : "", r.faulted ? r.err : ""); + say(line); + if (history == 2 || history == 6) [c->res removeAllocation:b]; + if (twin) [c->res removeAllocation:twin]; + [c->res commit]; + b = nil; twin = nil; out = nil; munmap(p, n); if (fd >= 0) close(fd); + return history != 2 || (!r.faulted && good == RP_WORDS); +} +static int res_probe(id dev, int rounds, void (*say)(const char *)) { @autoreleasepool { + char line[300]; + if (!dev || ![dev supportsFamily:MTLGPUFamilyMetal4]) { say("no Metal 4 device: skipped"); return 1; } + rp_ctx c = {.dev = dev}; NSError *err = nil; + MTLResidencySetDescriptor *rd = [MTLResidencySetDescriptor new]; rd.initialCapacity = 64; + c.res = [dev newResidencySetWithDescriptor:rd error:&err]; + MTL4CommandQueueDescriptor *qd = [MTL4CommandQueueDescriptor new]; static dispatch_queue_t fq; if (!fq) fq = dispatch_queue_create("dm.res-probe.feedback", DISPATCH_QUEUE_SERIAL); // kept for good, as the host keeps its own (g_feedback_q): freed with the probe's queue it was released once too often + qd.feedbackQueue = fq; + c.q = [dev newMTL4CommandQueueWithDescriptor:qd error:&err]; + if (c.q && c.res) [c.q addResidencySet:c.res]; + c.alloc = [dev newCommandAllocator]; + MTL4ArgumentTableDescriptor *atd = [MTL4ArgumentTableDescriptor new]; atd.maxBufferBindCount = 4; + c.at = [dev newArgumentTableWithDescriptor:atd error:&err]; + id lib = [dev newLibraryWithSource:@(kResProbeSrc) options:nil error:&err]; + if (lib) { c.rd = [dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@"rd"] error:&err]; c.wr = [dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@"wr"] error:&err]; } + if (!c.q || !c.res || !c.alloc || !c.at || !c.rd || !c.wr) { snprintf(line, sizeof line, "could not set up Metal 4: %s", err.localizedDescription.UTF8String); say(line); return 0; } + snprintf(line, sizeof line, "%s, working set %llu MB, %d pages touched per case", dev.name.UTF8String, (unsigned long long)(dev.recommendedMaxWorkingSetSize >> 20), RP_WORDS); say(line); + int ok = 1; + for (int round = 0; round < rounds; round++) { + snprintf(line, sizeof line, "round %d", round + 1); say(line); + ok &= rp_case(&c, "control: resident, read", RP_ANON, 2, 0, say); + ok &= rp_case(&c, "anon, never resident, read", RP_ANON, 0, 0, say); + ok &= rp_case(&c, "anon, evicted, read", RP_ANON, 1, 0, say); + ok &= rp_case(&c, "anon, twin resident, read", RP_ANON, 3, 0, say); + ok &= rp_case(&c, "anon, evicted + 32 commits, read", RP_ANON, 4, 0, say); + ok &= rp_case(&c, "anon, evicted + 2 s, read", RP_ANON, 5, 0, say); + ok &= rp_case(&c, "anon, made resident late, read", RP_ANON, 6, 0, say); + ok &= rp_case(&c, "file, never resident, read", RP_FILE, 0, 0, say); + ok &= rp_case(&c, "file via pwrite, never res., read", RP_FILE_CACHE, 0, 0, say); + ok &= rp_case(&c, "anon, never resident, write", RP_ANON, 0, 1, say); + ok &= rp_case(&c, "file, never resident, write", RP_FILE, 0, 1, say); + ok &= rp_case(&c, "control: resident, write", RP_ANON, 2, 1, say); + } + ok &= rp_case(&c, "control after the cases", RP_ANON, 2, 0, say); // does the queue still work (a fault may revoke the process's GPU access) + [c.q removeResidencySet:c.res]; // Metal traps when a set still attached to a queue is freed + say(ok ? "done: controls correct" : "FAIL: a resident control went wrong"); + return ok; +} } diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile index 9f557c1db8..ce5609197d 100644 --- a/dm/gfx/tests/Makefile +++ b/dm/gfx/tests/Makefile @@ -25,6 +25,9 @@ host_msl_force: FW=-framework Metal -framework MetalFX -framework Foundation -framework QuartzCore -framework ImageIO -framework CoreGraphics -framework UniformTypeIdentifiers # Host crash.c is linked in as well: the write-protect unit tests go through the same page-fault hook as production # Tests that #include nvn_mtl.m link the rest of the NVN layer beside it (hle_nvn.c: memory pools, sparse pools, serials) and the host's large stack, with weak stubs of what they need of the host (t_host_stubs.c) +# Textures in GPU-only memory sharing a heap per span (nvn_mtl.m window_on) turn on by themselves where Metal's working set is under 8 GB: the tests run as on a larger Mac +# wherever they run, and t_window_alias turns the spans on itself +export DM_NVN_WINDOW_ALIAS ?= 0 MTL_T_DEP=../nvn/hle_nvn.c ../../host/crash.c ../../host/hle_bigstack.c t_host_stubs.c $(GFX) $(GFX_H) MTL_T_SRC=../nvn/hle_nvn.c ../../host/crash.c ../../host/hle_bigstack.c t_host_stubs.c $(filter-out ../nvn/nvn_mtl.m,$(GFX)) # The run list: every t_*.c and t_*.m but those in NOT_RUN. `make run` builds them all (in parallel with -j), then runs them one after another, each through its check_ @@ -166,6 +169,8 @@ check_t_tex_fit_root: t_tex_fit_root MTL_DEBUG_LAYER=1 ./t_tex_fit_root t_addr_known: t_addr_known.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_addr_known.m $(MTL_T_SRC) $(FW) +t_file_wire: t_file_wire.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_file_wire.m $(MTL_T_SRC) $(FW) t_pool_chunks: t_pool_chunks.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_pool_chunks.m $(MTL_T_SRC) $(FW) t_pool_retire: t_pool_retire.m $(MTL_T_DEP) @@ -237,6 +242,8 @@ t_ub: t_ub.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_ub.m $(MTL_T_SRC) $(FW) t_gpuprof: t_gpuprof.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_gpuprof.m $(MTL_T_SRC) $(FW) +t_sub_overlap: t_sub_overlap.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_sub_overlap.m $(MTL_T_SRC) $(FW) t_dispatch_own: t_dispatch_own.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_dispatch_own.m $(MTL_T_SRC) $(FW) .PHONY: check_t_dispatch_own @@ -287,7 +294,7 @@ t_upload_slots: t_upload_slots.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_upload_slots.m $(MTL_T_SRC) $(FW) .PHONY: check_t_upload_slots check_t_upload_slots: t_upload_slots - MTL_DEBUG_LAYER=1 ./t_upload_slots + DM_NVN_UPLOAD_REUSE=1 MTL_DEBUG_LAYER=1 ./t_upload_slots DM_NVN_UPLOAD_REUSE=0 MTL_DEBUG_LAYER=1 ./t_upload_slots t_sbw: t_sbw.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_sbw.m $(MTL_T_SRC) $(FW) @@ -299,6 +306,12 @@ t_ubp_running: t_ubp_running.m $(MTL_T_DEP) .PHONY: check_t_ubp_running check_t_ubp_running: t_ubp_running ./t_ubp_running +t_pkg_evict: t_pkg_evict.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_pkg_evict.m $(MTL_T_SRC) $(FW) +check_t_pkg_evict: RUN_ENV = MTL_DEBUG_LAYER=1 +t_pkg_spare: t_pkg_spare.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_pkg_spare.m $(MTL_T_SRC) $(FW) +check_t_pkg_spare: RUN_ENV = MTL_DEBUG_LAYER=1 t_direct_upload: t_direct_upload.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_direct_upload.m $(MTL_T_SRC) $(FW) .PHONY: check_t_direct_upload @@ -325,7 +338,7 @@ check_t_geometry_mesh: t_geometry_mesh @set -e; work=$$(mktemp -d); trap 'rm -rf "$$work"' EXIT; python3 test_dmsh_geometry.py --fixture "$$work"; MTL_DEBUG_LAYER=1 ./t_geometry_mesh "$$work"; DM_NVN_GEO_MESH_RUN=0 MTL_DEBUG_LAYER=1 ./t_geometry_mesh "$$work"; DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_geometry_mesh "$$work" .PHONY: check_t_feedback check_t_feedback: t_feedback - @set -e; work=$$(mktemp -d); trap 'rm -rf "$$work"' EXIT; python3 test_dmsh_fetch.py --fixture "$$work"; MTL_DEBUG_LAYER=1 ./t_feedback "$$work" + @set -e; work=$$(mktemp -d); trap 'rm -rf "$$work"' EXIT; python3 test_dmsh_fetch.py --fixture "$$work"; MTL_DEBUG_LAYER=1 ./t_feedback "$$work"; DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_feedback "$$work" t_mip_extent: t_mip_extent.m ../nvn/hle_nvn.c ../../host/crash.c ../../host/hle_bigstack.c t_host_stubs.c $(GFX) $(GFX_H) clang $(CFLAGS) -fobjc-arc -o $@ t_mip_extent.m ../../host/crash.c ../../host/hle_bigstack.c t_host_stubs.c $(filter-out ../nvn/nvn_mtl.m,$(GFX)) $(FW) .PHONY: check_t_mip_extent @@ -501,9 +514,16 @@ check_t_partial_upload: RUN_ENV = MTL_DEBUG_LAYER=1 t_srgb_alias: t_srgb_alias.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_srgb_alias.m $(MTL_T_SRC) $(FW) check_t_srgb_alias: RUN_ENV = MTL_DEBUG_LAYER=1 +t_window_alias: t_window_alias.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_window_alias.m $(MTL_T_SRC) $(FW) +.PHONY: check_t_window_alias +check_t_window_alias: t_window_alias + DM_NVN_WINDOW_ALIAS=1 DM_NVN_RT_RECYCLE=0 DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_window_alias + DM_NVN_WINDOW_ALIAS=1 DM_NVN_RT_RECYCLE=0 DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_window_alias t_image_alias: t_image_alias.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_image_alias.m $(MTL_T_SRC) $(FW) .PHONY: check_t_image_alias +# t_image_alias checks the same-offset families (image_texture) a texture falls back to when its span's heap cannot take it: with the spans off, as every test runs (DM_NVN_WINDOW_ALIAS above) check_t_image_alias: t_image_alias DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_image_alias DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_image_alias @@ -657,3 +677,9 @@ check_t_pool_standin: t_pool_standin MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=0 ./t_pool_standin MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 ./t_pool_standin MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=0 DM_NVN_POOL_STANDIN=0 ./t_pool_standin + +t_tex_drop_mip: t_tex_drop_mip.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_tex_drop_mip.m $(MTL_T_SRC) $(FW) +check_t_tex_drop_mip: RUN_ENV = MTL_DEBUG_LAYER=1 +t_res_absent: t_res_absent.m ../nvn/nvn_res_probe.inc + clang -O1 -g -Wall -fobjc-arc -o $@ t_res_absent.m -framework Metal -framework Foundation diff --git a/dm/gfx/tests/nvn_replay.m b/dm/gfx/tests/nvn_replay.m index 27e6752ca6..4bbfce5a06 100644 --- a/dm/gfx/tests/nvn_replay.m +++ b/dm/gfx/tests/nvn_replay.m @@ -11,8 +11,10 @@ #include #include #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_addr_known.m b/dm/gfx/tests/t_addr_known.m index 15994d41b7..23f1e704a4 100644 --- a/dm/gfx/tests/t_addr_known.m +++ b/dm/gfx/tests/t_addr_known.m @@ -41,6 +41,24 @@ int main(void) { @autoreleasepool { CHECK("asking makes no chunk and nothing resident", g_npool == np0 && g_pool_res_n == rb0); CHECK("mtl_addr makes a chunk for the same range", mtl_addr(bb + (100u << 20), 4096, &mb, &mo) && g_npool == np0 + 1); mtl_pool_del(big); + + // The raw pool table (gmem_map) and shader-code pools: hle_nvn.c nvnMemoryPoolGetBufferAddress reports a shader-code pool's own address as kind 4, which keeps the pool out of + // the table, so nothing makes it resident and wires its pages for the table's sake; a buffer made in it (kind 0, then 1) puts it in, as does any other pool's address + uint8_t *code = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0), *data = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); + if (code == MAP_FAILED || data == MAP_FAILED) abort(); + uint64_t cb = (uint64_t)(uintptr_t)code, db = (uint64_t)(uintptr_t)data; + mtl_pool_add(code, n); mtl_pool_tag(code, 0x64); mtl_pool_add(data, n); mtl_pool_tag(data, 0x24); + mtl_pool_addressed_by(code, n, 4); mtl_pool_addressed_by(data, n, 0); + #define IN_TABLE(b) ({ id t_ = gmem_map(); const uint8_t *e_ = (const uint8_t *)t_.contents; int in_ = 0; \ + for (int k = 1; k < DMSH_GMEM_MAP_ENTRIES && !in_; k++) { uint64_t r_[2]; memcpy(r_, e_ + (size_t)k * DMSH_GMEM_MAP_ENTRY, sizeof r_); in_ = r_[0] <= (b) && (b) < r_[1]; } in_; }) + CHECK("a shader-code pool's own address keeps it out of the raw pool table", !IN_TABLE(cb + 4096)); + CHECK("so the table makes it not resident", !pool_resident(cb)); + CHECK("another pool's address puts it in the table", IN_TABLE(db + 4096)); + CHECK("and makes it resident", pool_resident(db)); + mtl_pool_addressed_by(code + 8192, 4096, 0); mtl_pool_addressed_by(code + 8192, 4096, 1); // what nvnBufferInitialize reports for a buffer in the code pool + CHECK("a buffer in the shader-code pool puts it in the table", IN_TABLE(cb + 4096)); + CHECK("and makes it resident", pool_resident(cb)); + mtl_pool_del(code); mtl_pool_del(data); printf("t_addr_known: %d checks, %d failed\n", checks, failed); return failed != 0; } } diff --git a/dm/gfx/tests/t_capture_live.m b/dm/gfx/tests/t_capture_live.m index bfbb6d0270..f87d033117 100644 --- a/dm/gfx/tests/t_capture_live.m +++ b/dm/gfx/tests/t_capture_live.m @@ -6,8 +6,10 @@ // ./t_capture_live #import #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_copy_alias.m b/dm/gfx/tests/t_copy_alias.m index 24254f2b06..9dafab322e 100644 --- a/dm/gfx/tests/t_copy_alias.m +++ b/dm/gfx/tests/t_copy_alias.m @@ -1,7 +1,9 @@ // Copies through distinct Metal buffers and sparse guest aliases must see earlier GPU writes. #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_cpu_tex.m b/dm/gfx/tests/t_cpu_tex.m index 0888da9d8b..c879ab0e83 100644 --- a/dm/gfx/tests/t_cpu_tex.m +++ b/dm/gfx/tests/t_cpu_tex.m @@ -2,8 +2,10 @@ // not in it staying cheap with thousands of consecutive serials in it (a CFSet that hashed serials as numbers probed a whole bucket run per miss: half of Batman: Arkham Knight's // rendering thread with 6,442 CPU-written textures) #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_feedback.m b/dm/gfx/tests/t_feedback.m index eec36761a8..bfa2ff67cc 100644 --- a/dm/gfx/tests/t_feedback.m +++ b/dm/gfx/tests/t_feedback.m @@ -472,6 +472,9 @@ static void cut_boundary_case(void) { tex_t colour; target(&colour, 99810); id rep = [g_dev newBufferWithLength:64 options:MTLResourceStorageModeShared]; res_add(rep); CHECK(ts_on(), "segment mode has a timestamp heap"); + // nothing of the cases before this one may still be on its way: a submission the encode thread kept open for the next one (merged submissions) reports back a moment later than + // one committed at once, and the case counts g_seg_inflight itself + rec_drain(); for (int i = 0; i < 20000 && atomic_load(&g_seg_inflight); i++) usleep(100); state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); R.has_rt = 1; R.rt.n = 1; R.rt.color[0] = &colour; clear(MTLClearColorMake(0, 0, 0, 1)); rp_end(); @@ -492,6 +495,56 @@ static void cut_boundary_case(void) { CHECK(r0[1] && r1[1] > r0[1], "two reports in one command buffer read two times"); } +// With Metal encoding on its own thread, submissions that reach it while the GPU still runs an earlier command buffer are held and go to the queue in one commit call (nvn_rec.h, +// held submissions): their notes and signals follow it, and each one's reports still read its own part of the GPU time. Anything else for the queue recorded inside a later +// submission (an upload batch, here a queue block) goes after the held ones and before that submission's own command buffer, as when each was committed on its own: the first +// version continued the next submission in the held command buffer, and an upload recorded inside it went to the GPU after the draws recorded before it. The encode thread is held +// by a queue block until the submissions are recorded, and "an earlier command buffer runs" is the counter raised by hand +static void merge_case(void) { + if (!rec_on()) return; + tex_t colour; target(&colour, 99820); + id rep = [g_dev newBufferWithLength:64 options:MTLResourceStorageModeShared]; res_add(rep); + rec_drain(); for (int i = 0; i < 20000 && (atomic_load(&g_rx_fly) || atomic_load(&g_seg_inflight)); i++) usleep(100); + uint64_t cbs0 = g_rx_cbs, merged0 = g_rx_merged; + dispatch_semaphore_t gate = dispatch_semaphore_create(0); + atomic_fetch_add(&g_rx_fly, 1); + rec_queue_block(^{ dispatch_semaphore_wait(gate, DISPATCH_TIME_FOREVER); }); rec_publish(); + uint64_t f[3]; + for (int k = 0; k < 3; k++) { + state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); + R.has_rt = 1; R.rt.n = 1; R.rt.color[0] = &colour; + clear(MTLClearColorMake(k == 0, k == 1, k == 2, 1)); rp_end(); + mtl_sub_counter((uint64_t)rep.contents + 16 * (uint64_t)k, 0); // a timestamp at the end of its (only) segment: its command buffer's end, or its own part of a shared one + f[k] = mtl_sub_commit(); + } + dispatch_semaphore_signal(gate); + // (polled, not waited for: a waiter that wakes on the queue's signal completes the records itself, with its own clock for every report: post_early) + for (int i = 0; i < 50000 && g_done < f[2]; i++) usleep(100); + CHECK(g_done >= f[2], "three submissions behind running work complete"); + atomic_fetch_sub(&g_rx_fly, 1); + rec_drain(); + CHECK(g_rx_merged - merged0 == 3 && g_rx_cbs - cbs0 == 1, "they went to the queue in one commit"); + CHECK(atomic_load(&g_sub_cmt) >= f[2], "their commit notes are passed"); + uint64_t r[3][2]; memcpy(r, rep.contents, sizeof r); + CHECK(r[0][1] && r[1][1] >= r[0][1] && r[2][1] >= r[1][1] && r[2][1] > r[0][1], "each one's report reads its own end, not the shared command buffer's"); + // a queue operation recorded inside the next submission, after its first pass: the held submission goes to the queue before it, and that submission's own command buffer, + // which holds the pass, after it (an upload batch flushed in the middle of a submission is committed before the draws it serves, wherever in the submission they were recorded) + rec_drain(); for (int i = 0; i < 20000 && (atomic_load(&g_rx_fly) || atomic_load(&g_seg_inflight)); i++) usleep(100); + cbs0 = g_rx_cbs; merged0 = g_rx_merged; __block uint64_t held_at_block = ~0ull; __block int pend_at_block = -1, nb_at_block = -1; + atomic_fetch_add(&g_rx_fly, 1); + rec_queue_block(^{ dispatch_semaphore_wait(gate, DISPATCH_TIME_FOREVER); }); rec_publish(); + state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); R.has_rt = 1; R.rt.n = 1; R.rt.color[0] = &colour; clear(MTLClearColorMake(1, 1, 0, 1)); rp_end(); uint64_t fa = mtl_sub_commit(); + state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); R.has_rt = 1; R.rt.n = 1; R.rt.color[0] = &colour; clear(MTLClearColorMake(0, 1, 1, 1)); rp_end(); + rec_queue_block(^{ held_at_block = g_rx_cbs; pend_at_block = g_rx_npend; nb_at_block = g_rx_last_nb; }); rec_publish(); + clear(MTLClearColorMake(1, 0, 1, 1)); rp_end(); uint64_t fb2 = mtl_sub_commit(); + dispatch_semaphore_signal(gate); + atomic_fetch_sub(&g_rx_fly, 1); + CHECK(mtl_wait(fb2, 5000000000ull), "the submissions around a queue operation complete"); + rec_drain(); + CHECK(pend_at_block == 0 && held_at_block == cbs0 + 1 && g_rx_merged - merged0 >= 1 && fa < fb2, "the held submission was committed before the queue operation ran"); + CHECK(nb_at_block == 1, "and alone: the next submission's pass recorded before the queue operation was not in that commit"); +} + // Output-mapping-only fixture (no rewritable sample): main0 writes magenta to color(0); main0_f remaps // that output through OM_0_k. Specialized with OM_0_1, attachment 1 is magenta and attachment 0 stays the clear colour. static void om_case(const char *dir) { @@ -727,6 +780,7 @@ int main(int argc, char **argv) { @autoreleasepool { pool_depth_case(); reuse_tables_case(); cut_boundary_case(); + merge_case(); printf("feedback snapshot: %d checks, %d failed\n", checks, failed); return failed != 0; } } diff --git a/dm/gfx/tests/t_file_wire.m b/dm/gfx/tests/t_file_wire.m new file mode 100644 index 0000000000..80ccc9a5e3 --- /dev/null +++ b/dm/gfx/tests/t_file_wire.m @@ -0,0 +1,84 @@ +// A shared buffer over file-backed pages joins the residency set with its pages already resident, wired through the CPU's fault path (mlock) before the commit, and that wiring +// is given back once the commit has made the pages resident for the GPU. With the guest's memory in files (DM_GUEST_FILE) the commit itself paged the file in from the GPU +// driver's wiring path, and on the M1 iPad that page-in waited for good on an APFS lock held by a launchd thread, itself waiting: the game froze with sound and no picture +// (docs/reference/memory.md, "The residency commit froze over the guest's files"). Anonymous memory is not touched +#include "../nvn/nvn_mtl.m" +#include +void *front_metal_layer(void) { return NULL; } +module_t *module_of(const void *p) { (void)p; return NULL; } +module_t *g_mod; int g_nmod; +void svc_thread_dump(void) {} +uint64_t now_ns(void) { return bp_now(); } +static int checks, failed; +#define CHECK(label, c) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s (line %d)\n", label, __LINE__); } } while (0) +// The smallest and largest user wiring count over [p, p + n) +static void wired(const void *p, size_t n, unsigned *lo, unsigned *hi) { + mach_vm_address_t a = (mach_vm_address_t)p, e = a + n; *lo = ~0u; *hi = 0; + while (a < e) { + mach_vm_size_t sz = 0; natural_t depth = 0; vm_region_submap_info_data_64_t info; mach_msg_type_number_t c = VM_REGION_SUBMAP_INFO_COUNT_64; + if (mach_vm_region_recurse(mach_task_self(), &a, &sz, &depth, (vm_region_recurse_info_t)&info, &c) || a >= e) break; + if (info.user_wired_count < *lo) *lo = info.user_wired_count; + if (info.user_wired_count > *hi) *hi = info.user_wired_count; + a += sz; + } +} +static int all_resident(const void *p, size_t n) { + size_t pg = getpagesize(), np = n / pg; char *v = malloc(np); int ok = !mincore(p, n, v); + for (size_t i = 0; ok && i < np; i++) ok = v[i] & MINCORE_INCORE; + free(v); return ok; +} +static int in_set(id b) { pthread_mutex_lock(&g_res_mu); int r = [g_res_objects containsObject:b]; pthread_mutex_unlock(&g_res_mu); return r; } +int main(void) { @autoreleasepool { + mtl_init(); + size_t pg = getpagesize(), n = 256 * pg; + char path[] = "/tmp/t_file_wire.XXXXXX"; int fd = mkstemp(path); if (fd < 0) abort(); unlink(path); + if (ftruncate(fd, (off_t)n)) abort(); + uint8_t *m = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (m == MAP_FAILED) abort(); + memset(m, 0x5a, n / 2); // half written, half holes + msync(m, n, MS_SYNC); msync(m, n, MS_INVALIDATE); // written out and dropped: the next touch is a page-in + mprotect(m + 16 * pg, 16 * pg, PROT_READ); // as the write tracking leaves a texture's pages + unsigned lo, hi; + + id b = [g_dev newBufferWithBytesNoCopy:m length:n options:MTLResourceStorageModeShared deallocator:nil]; + res_add(b); + wired(m, n, &lo, &hi); + CHECK("the file pages are user-wired once res_add returns, before the commit", lo == 1 && hi == 1); + CHECK("and resident: the commit has nothing to page in", all_resident(m, n)); + CHECK("the buffer is in the set", in_set(b)); + res_commit(); + wired(m, n, &lo, &hi); + CHECK("the commit gives the user wiring back", lo == 0 && hi == 0); + CHECK("the bytes are the file's", m[0] == 0x5a && m[n - 1] == 0); + + // Wiring someone else holds over the range is left as it was (mlock counts) + mlock(m, 8 * pg); + id b2 = [g_dev newBufferWithBytesNoCopy:m length:n options:MTLResourceStorageModeShared deallocator:nil]; + res_add(b2); res_commit(); + wired(m, 8 * pg, &lo, &hi); + CHECK("an mlock taken outside stays", lo == 1 && hi == 1); + munlock(m, 8 * pg); + + // Added twice before one commit: wired once, given back once + id b3 = [g_dev newBufferWithBytesNoCopy:m + 128 * pg length:64 * pg options:MTLResourceStorageModeShared deallocator:nil]; + res_add(b3); res_add(b3); + wired(m + 128 * pg, 64 * pg, &lo, &hi); + CHECK("a second res_add of a buffer in the set wires nothing more", lo == 1 && hi == 1); + res_commit(); + wired(m + 128 * pg, 64 * pg, &lo, &hi); + CHECK("and the commit leaves nothing wired", lo == 0 && hi == 0); + + // Anonymous memory: no wiring at all + uint8_t *a = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); if (a == MAP_FAILED) abort(); + id ab = [g_dev newBufferWithBytesNoCopy:a length:n options:MTLResourceStorageModeShared deallocator:nil]; + res_add(ab); + wired(a, n, &lo, &hi); + CHECK("an anonymous range is not wired by res_add", hi == 0); + res_commit(); + id own = [g_dev newBufferWithLength:n options:MTLResourceStorageModeShared]; + res_add(own); res_commit(); + CHECK("a buffer Metal allocated goes in as before", in_set(own)); + + res_remove(b); res_remove(b2); res_remove(b3); res_remove(ab); res_remove(own); res_commit(); + printf("t_file_wire: %d checks, %d failed\n", checks, failed); + return failed != 0; +} } diff --git a/dm/gfx/tests/t_fstep.c b/dm/gfx/tests/t_fstep.c index eb42729014..062276c839 100644 --- a/dm/gfx/tests/t_fstep.c +++ b/dm/gfx/tests/t_fstep.c @@ -21,6 +21,17 @@ static void run(sim *m, int n, double w, int kmin, int kmax, int fixed) { // A hitch that steps hold 1 up: six frames of 1.6 vsyncs (pipeline compiles), 3.6 vsyncs behind in the last 30 frames, more than FSTEP_LATE a frame on average. Three such // frames among frames on time are paid back by the step and keep hold 1 (below) static void hitch(sim *m) { run(m, 6, 1.6, 1, 3, 0); } +// Frames with the GPU time reported (nvn_fstep gpu_on): CPU work cpu and GPU time gpu (vsyncs). paced = 1: the frame waits out its hold in the host's pacing, so its cost is +// max(cpu, gpu); paced = 0: the game waits for its frames elsewhere (Ocarina of Time), so the whole time shown is its cost +static void rung(sim *m, int n, double cpu, double gpu, int paced, int kmin, int kmax) { + for (int i = 0; i < n; i++) { + int k = m->s.k ? m->s.k : kmin, step = m->next ? m->next : kmin; + double w = cpu > gpu ? cpu : gpu, shown = w > k ? w : k; + m->real += shown; m->game += step; + m->s.gpu_on = 1; m->s.gpu = gpu; + m->next = nvn_fstep_next(&m->s, shown, paced ? w : shown, kmin, kmax, 0, m->slow); + } +} int main(void) { { // 120 fps (hle_nvn.c fps_high): kmin 1, kmax 2, in ticks of 1/120 s. The target follows the hold, so a hold above what frames take is the game at the right speed @@ -210,7 +221,7 @@ int main(void) { for (int i = 0; i < 2000; i++) { double w = i < 600 ? 0.86 : i < 603 ? 1.25 : m.s.k >= 2 ? 1.5 : at1++ < 20 ? 1.5 : 0.86; stepped |= i >= 603 && m.s.k == 2; - m.slow = nvn_fstep_gpu_slowed(&g, w, m.s.k ? m.s.k : 1, 1, m.s.probe); + m.slow = nvn_fstep_gpu_slowed(&g, w, 0, m.s.k ? m.s.k : 1, 1, m.s.probe); run(&m, 1, w, 1, 3, 0); } snprintf(b, sizeof b, "GPU clock follows the hold (BotW): one probe back to hold 1 that holds (k %d, probes %llu, failed %llu)", m.s.k, (unsigned long long)m.s.probes, (unsigned long long)m.s.failed); @@ -220,19 +231,67 @@ int main(void) { } { // a heavier scene at the same clock: 0.86 at hold 1, then 1.12 (19 ms) for good, which is 1.3 times less than enough to call the GPU slowed sim m = {0}; nvn_fgpu g = {0}; - for (int i = 0; i < 2000; i++) { double w = i < 600 ? 0.86 : 1.12; m.slow = nvn_fstep_gpu_slowed(&g, w, m.s.k ? m.s.k : 1, 1, m.s.probe); run(&m, 1, w, 1, 3, 0); } + for (int i = 0; i < 2000; i++) { double w = i < 600 ? 0.86 : 1.12; m.slow = nvn_fstep_gpu_slowed(&g, w, 0, m.s.k ? m.s.k : 1, 1, m.s.probe); run(&m, 1, w, 1, 3, 0); } check(m.s.k == 2 && m.s.probes == 0, "heavier scene, GPU 0.86 → 1.12 at hold 2: not slowed, no probe"); } { // a loading screen: the GPU at 0.03, then lag on the CPU steps to 2, where the GPU takes 0.17 (5.7 times as much but 3 ms): the CPU holds the frame back, not the GPU sim m = {0}; nvn_fgpu g = {0}; int slowed = 0; - for (int i = 0; i < 1200; i++) { double gp = i < 600 || m.s.k == 1 ? 0.03 : 0.17, w = i < 600 ? 0.5 : 1.3; m.slow = nvn_fstep_gpu_slowed(&g, gp, m.s.k ? m.s.k : 1, 1, m.s.probe); slowed |= m.slow; run(&m, 1, w, 1, 3, 0); } + for (int i = 0; i < 1200; i++) { double gp = i < 600 || m.s.k == 1 ? 0.03 : 0.17, w = i < 600 ? 0.5 : 1.3; m.slow = nvn_fstep_gpu_slowed(&g, gp, 0, m.s.k ? m.s.k : 1, 1, m.s.probe); slowed |= m.slow; run(&m, 1, w, 1, 3, 0); } check(m.s.k == 2 && !slowed && m.s.probes == 0, "GPU 0.03 → 0.17 under CPU lag: a GPU at 3 ms is not called slowed, no probe"); } + { // Ocarina of Time on an M4 Air: the title and the loading screen run at hold 1 for 20 s (GPU 0.2 vsyncs, 30 draws); gameplay has 900 draws, 1.3 vsyncs at hold 1 and 1.4 at + // hold 2, where the clock is lower. The hold-1 reference measured other work: the GPU at hold 2 is not slowed, and no probe goes back to hold 1, which cannot hold + for (int known = 1; known >= 0; known--) { + sim m = {0}; nvn_fgpu g = {0}; int slowed = 0; + for (int i = 0; i < 3000; i++) { + int play = i >= 1200, k = m.s.k ? m.s.k : 1; double w = !play ? 0.2 : k >= 2 ? 1.4 : 1.3; + m.slow = nvn_fstep_gpu_slowed(&g, w, known ? (play ? 900 : 30) : 0, k, 1, m.s.probe); slowed |= play && m.slow; + run(&m, 1, play ? w : 0.5, 1, 3, 0); + } + if (known) { snprintf(b, sizeof b, "GPU reference from a loading screen (30 draws), gameplay at 900: not slowed, no probe (k %d, probes %llu, failed %llu)", m.s.k, (unsigned long long)m.s.probes, (unsigned long long)m.s.failed); + check(m.s.k == 2 && !slowed && m.s.probes == 0, b); } + else { snprintf(b, sizeof b, " without draw counts the same run is called slowed and probes (probes %llu, failed %llu)", (unsigned long long)m.s.probes, (unsigned long long)m.s.failed); + check(slowed && m.s.probes > 0, b); } + } + { // Ocarina of Time's title on an M1 iPad: the boot screens set the hold-1 reference (GPU 0.03 vsyncs, 50 draws, no dispatch), then the title's movie network adds + // 14 dispatches and 3.6 vsyncs at the same draws. Counted dispatches tell the work apart: not slowed, no probe; without them it probes hold 1 again and again + for (int known = 1; known >= 0; known--) { + sim m = {0}; nvn_fgpu g = {0}; int slowed = 0; + for (int i = 0; i < 3000; i++) { + int title = i >= 300, k = m.s.k ? m.s.k : 1; double w = title ? 3.6 : 0.03; + m.slow = nvn_fstep_gpu_slowed2(&g, w, 50, known ? (title ? 14 : 0) : -1, k, 1, m.s.probe); slowed |= title && m.slow; + run(&m, 1, title ? w : 0.5, 1, 3, 0); + } + if (known) { snprintf(b, sizeof b, "title's dispatches against a boot-screen reference with none: not slowed, no probe (k %d, probes %llu)", m.s.k, (unsigned long long)m.s.probes); + check(m.s.k == 3 && !slowed && m.s.probes == 0, b); } + else { snprintf(b, sizeof b, " without dispatch counts the same run is called slowed and probes (probes %llu, failed %llu)", (unsigned long long)m.s.probes, (unsigned long long)m.s.failed); + check(slowed && m.s.probes > 0, b); } + } + sim m = {0}; nvn_fgpu g = {0}; int at1 = 0, stepped = 0; // the same draws and dispatches at both holds: still a clock that fell (BotW's run below, with 14 dispatches) + for (int i = 0; i < 2000; i++) { + double w = i < 600 ? 0.86 : i < 603 ? 1.25 : m.s.k >= 2 ? 1.5 : at1++ < 20 ? 1.5 : 0.86; + stepped |= i >= 603 && m.s.k == 2; + m.slow = nvn_fstep_gpu_slowed2(&g, w, i % 3 ? 4900 : 4700, 14, m.s.k ? m.s.k : 1, 1, m.s.probe); + run(&m, 1, w, 1, 3, 0); + } + snprintf(b, sizeof b, " the same draws and dispatches at both holds: one probe back to hold 1 that holds (k %d, probes %llu)", m.s.k, (unsigned long long)m.s.probes); + check(stepped && m.s.k == 1 && m.s.probes == 1 && m.s.failed == 0, b); + } + sim m = {0}; nvn_fgpu g = {0}; int at1 = 0, stepped = 0; // the same work at both holds is still a clock that fell (BotW above, with its draw counts) + for (int i = 0; i < 2000; i++) { + double w = i < 600 ? 0.86 : i < 603 ? 1.25 : m.s.k >= 2 ? 1.5 : at1++ < 20 ? 1.5 : 0.86; + stepped |= i >= 603 && m.s.k == 2; + m.slow = nvn_fstep_gpu_slowed(&g, w, i % 3 ? 4900 : 4700, m.s.k ? m.s.k : 1, 1, m.s.probe); + run(&m, 1, w, 1, 3, 0); + } + snprintf(b, sizeof b, " the same draws at both holds (4,700-4,900): one probe back to hold 1 that holds (k %d, probes %llu)", m.s.k, (unsigned long long)m.s.probes); + check(stepped && m.s.k == 1 && m.s.probes == 1 && m.s.failed == 0, b); + } { // the GPU stays slow at hold 1 too: each probe fails, the reference stays the hold-1 time from before, and the probes spread out sim m = {0}; nvn_fgpu g = {0}; double last = 0, gaps[4]; int ng = 0; uint64_t probes = 0; for (int i = 0; i < 6000 && ng < 4; i++) { double w = i < 600 ? 0.86 : i < 603 ? 1.25 : 1.5; - m.slow = nvn_fstep_gpu_slowed(&g, w, m.s.k ? m.s.k : 1, 1, m.s.probe); + m.slow = nvn_fstep_gpu_slowed(&g, w, 0, m.s.k ? m.s.k : 1, 1, m.s.probe); run(&m, 1, w, 1, 3, 0); if (m.s.probes != probes) { probes = m.s.probes; gaps[ng++] = m.real - last; last = m.real; } } @@ -328,7 +387,7 @@ int main(void) { int kmin = i >= 600 && i < rise ? 2 : 1, kmax = kmin == 2 ? 2 : 3, k = m.s.k ? m.s.k : kmin; since1 = k == 1 ? since1 + 1 : 0; double w = k >= 2 ? 1.5 : i < rise ? 0.86 : c == 2 ? 1.3 : since1 <= 10 || (c == 1 && i < rise + 60) ? 1.5 : 0.86; - m.slow = nvn_fstep_gpu_slowed(&g, w, k, kmin, m.s.probe); + m.slow = nvn_fstep_gpu_slowed(&g, w, 0, k, kmin, m.s.probe); run(&m, 1, w, kmin, kmax, 0); if (i == rise - 1) ups = m.s.ups; if (i >= n - 600) at1 += m.s.k == 1; @@ -395,6 +454,83 @@ int main(void) { check(first_len == want[c] && m.s.k == 2 && m.s.failed == 1, b); } } + { // Ocarina of Time on a warm start (2026-11-08, run hu_fog): the first frames after a 162 s pipeline prepare ran 2–7 vsyncs with the GPU idle (0.01–0.02 vsyncs) while an + // archive write ran, and stepped the hold 1 → 2 → 3; its frames wait outside the host's pacing, so their cost is the hold and it stayed at 3 (20 fps) for 1,470 presents + sim m = {0}; rung(&m, 8, 0.4, 0.01, 0, 1, 3); + static const double burst[] = {1.9, 4.5, 7.0, 5.6, 4.6, 6.6, 5.4, 4.8, 7.0}; + for (int i = 0; i < 9; i++) rung(&m, 1, burst[i], 0.01, 0, 1, 3); + snprintf(b, sizeof b, "late frames with the GPU idle (a progress screen after a prepare) do not step up (k %d, ups %llu)", m.s.k, (unsigned long long)m.s.ups); + check(m.s.k == 1 && m.s.ups == 0, b); + rung(&m, 600, 0.8, 0.75, 0, 1, 3); + check(m.s.k == 1 && m.s.ups == 0, " then the scene (GPU 0.75, frames not waiting in the pacing) holds hold 1"); + } + { // the same game stepped to 3 by a real hitch (three frames of 3.5 vsyncs with the GPU busy): at hold 3 its cost is the hold, the GPU 0.75 fits hold 1, so a probe + // brings hold 1 back within 2 s instead of never (no fit trial: the cost never fits k − 1) + sim m = {0}; rung(&m, 600, 0.8, 0.75, 0, 1, 3); rung(&m, 3, 3.5, 0.75, 0, 1, 3); + check(m.s.k == 3, "self-paced game, a hitch with the GPU busy: hold 3"); + double t0 = m.real, back = -1; + for (int i = 0; i < 1200 && back < 0; i++) { rung(&m, 1, 0.8, 0.75, 0, 1, 3); if (m.s.k == 1) back = m.real - t0; } + rung(&m, 1200, 0.8, 0.75, 0, 1, 3); + snprintf(b, sizeof b, " its hold the GPU does not explain is probed: hold 1 after %.0f vsyncs, and it stays (k %d, probes %llu, failed %llu)", back, m.s.k, (unsigned long long)m.s.probes, (unsigned long long)m.s.failed); + check(back > 0 && back <= 120 && m.s.k == 1 && m.s.probes == 1 && m.s.failed == 0, b); + } + { // a CPU-bound game (1.4 vsyncs of CPU, GPU 0.3) waits out hold 2 in the pacing: its cost explains the hold, so no probe + sim m = {0}; rung(&m, 60, 0.5, 0.3, 1, 1, 3); rung(&m, 1200, 1.4, 0.3, 1, 1, 3); + snprintf(b, sizeof b, "CPU-bound game paced at hold 2 (cost 1.4, GPU 0.3): stays at 2, no probes (k %d, probes %llu)", m.s.k, (unsigned long long)m.s.probes); + check(m.s.k == 2 && m.s.probes == 0, b); + } + { // a CPU-bound game at 3.2 vsyncs (late even at hold 3, so no pacing wait), GPU 0.3: the probes fail and spread out 1 → 2 → 4 → 8 s + sim m = {0}; rung(&m, 60, 0.5, 0.3, 1, 1, 3); rung(&m, 30, 3.2, 0.3, 1, 1, 3); + double last = m.real, gaps[4] = {-1, -1, -1, -1}; int ng = 0; uint64_t probes = m.s.probes; + for (int i = 0; i < 6000 && ng < 4; i++) { rung(&m, 1, 3.2, 0.3, 1, 1, 3); if (m.s.probes != probes) { probes = m.s.probes; gaps[ng++] = m.real - last; last = m.real; } } + snprintf(b, sizeof b, "CPU-bound game at 3.2 vsyncs: probes %.0f, %.0f, %.0f, %.0f vsyncs apart; %llu failed", gaps[0], gaps[1], gaps[2], gaps[3], (unsigned long long)m.s.failed); + check(ng == 4 && gaps[1] >= 120 && gaps[2] >= 240 && gaps[3] >= 480 && m.s.failed >= 3, b); + } + { // the same self-paced game, but its GPU clock falls at hold 3 (GPU 0.75 at hold 1, 1.0 at hold 3): GPU time that fits k − 1 still starts the probe + sim m = {0}; rung(&m, 600, 0.8, 0.75, 0, 1, 3); rung(&m, 3, 3.5, 1.0, 0, 1, 3); + for (int i = 0; i < 2400; i++) rung(&m, 1, 0.8, m.s.k > 1 ? 1.0 : 0.75, 0, 1, 3); + snprintf(b, sizeof b, "self-paced game whose GPU clock falls at the longer hold: probed back to hold 1 and stays (k %d, probes %llu, failed %llu)", m.s.k, (unsigned long long)m.s.probes, (unsigned long long)m.s.failed); + check(m.s.k == 1 && m.s.probes == 1 && m.s.failed == 0, b); + } + { // a CPU-heavy scene that draws almost nothing (CPU 1.5 vsyncs, GPU 0.01, paced): its late frames are not a load, so FSTEP_RUN of them in a row still step up to 2 + sim m = {0}; rung(&m, 60, 0.5, 0.01, 1, 1, 3); rung(&m, 3000, 1.5, 0.01, 1, 1, 3); + snprintf(b, sizeof b, "CPU-heavy scene with the GPU idle: steps up once and holds 2 (k %d, ups %llu, late %llu)", m.s.k, (unsigned long long)m.s.ups, (unsigned long long)m.s.late); + check(m.s.k == 2 && m.s.ups == 1 && m.s.late <= 40, b); + } + { // a self-paced game whose CPU needs hold 2 (CPU 1.5, GPU 0.3; 20,000 frames, about 11 minutes): the unpaced probes fail and their hold-off grows to 60 s + sim m = {0}; rung(&m, 60, 0.5, 0.3, 0, 1, 3); rung(&m, 20000, 1.5, 0.3, 0, 1, 3); + snprintf(b, sizeof b, "self-paced game that needs hold 2: at most one probe a minute after the first few (k %d, probes %llu, failed %llu)", m.s.k, (unsigned long long)m.s.probes, (unsigned long long)m.s.failed); + check(m.s.k == 2 && m.s.probes <= 16 && m.s.failed == m.s.probes, b); + } + { // a host-paced CPU-bound game at 2.95 vsyncs (pacing wait under FSTEP_LATE at hold 3): 20,000 frames, about 17 minutes: probes at most once a minute after the first few, the game within 1.5% of real time (one failed probe every 8 s: 5.5% slow) + sim m = {0}; rung(&m, 60, 0.5, 0.3, 1, 1, 3); rung(&m, 30, 2.95, 0.3, 1, 1, 3); + double r0 = m.real, g0 = m.game; rung(&m, 20000, 2.95, 0.3, 1, 1, 3); + snprintf(b, sizeof b, "host-paced game at 2.95 vsyncs: game/real %.3f (probes %llu, failed %llu)", (m.game - g0) / (m.real - r0), (unsigned long long)m.s.probes, (unsigned long long)m.s.failed); + check((m.game - g0) / (m.real - r0) >= 0.985 && m.s.probes <= 24, b); + } + { // a 30 fps cap (kmin = kmax = 2) whose frames run late (Ocarina of Time on an iPhone: 36.5 ms, GPU 32 ms): the hold cannot rise, so the frame step asks the caller to show each late + // frame at the next vsync (nvn_fstep.fine: the 60 Hz display link) instead of the next tick of the cap's 30 Hz link, and returns to it once the frames fit for FSTEP_HOLD_MAX + sim m = {0}; rung(&m, 120, 1.2, 1.0, 1, 2, 2); + check(m.s.k == 2 && !m.s.fine, "30 fps cap, frames that fit hold 2: the cap's own link"); + rung(&m, 2, 2.19, 1.92, 1, 2, 2); check(!m.s.fine, " two late frames are not yet a scene that does not fit"); + rung(&m, 1, 2.19, 1.92, 1, 2, 2); check(m.s.fine && m.s.k == 2 && m.s.fines == 1, " the third: late frames show at the next vsync, the hold stays 2"); + double r0 = m.real, g0 = m.game; rung(&m, 1800, 2.19, 1.92, 1, 2, 2); + snprintf(b, sizeof b, " 1,800 late frames: stays at the next vsync, game time %.3f of real time (switches %llu)", (m.game - g0) / (m.real - r0), (unsigned long long)m.s.fines); + check(m.s.fine && m.s.fines == 1 && (m.game - g0) / (m.real - r0) > 0.99, b); + rung(&m, 200, 1.2, 1.0, 1, 2, 2); check(m.s.fine, " frames that fit for 400 vsyncs keep it (no flapping)"); + rung(&m, 60, 1.2, 1.0, 1, 2, 2); check(!m.s.fine, " after 8 s of frames that fit, the cap's own link again"); + for (int i = 0; i < 20; i++) { rung(&m, 1, 2.3, 2.0, 1, 2, 2); rung(&m, 49, 1.2, 1.0, 1, 2, 2); } + check(!m.s.fine && m.s.fines == 1, " a single late frame every 50 does not switch"); + sim i = {0}; rung(&i, 120, 1.2, 1.0, 1, 2, 2); rung(&i, 20, 2.5, 0.01, 1, 2, 2); + check(!i.s.fine, "30 fps cap, 20 late frames with the GPU idle (a load): the cap's own link"); + rung(&i, 20, 2.5, 0.01, 1, 2, 2); check(i.s.fine, " 30 in a row are a CPU-heavy scene, as for a step up"); + sim u = {0}; rung(&u, 120, 0.5, 0.4, 1, 1, 3); rung(&u, 600, 2.19, 1.92, 1, 1, 3); + check(u.s.k == 3 && !u.s.fine, "60 fps cap, 36.5 ms frames: the hold rises to 3, no fine pacing needed"); + sim f = {0}; rung(&f, 120, 1.2, 1.0, 1, 2, 2); rung(&f, 10, 2.19, 1.92, 1, 2, 2); run(&f, 1, 2.19, 2, 2, 2); + check(!f.s.fine, "the game fixing its own step ends it"); + sim c = {0}; rung(&c, 120, 1.2, 1.0, 1, 2, 2); rung(&c, 10, 2.19, 1.92, 1, 2, 2); rung(&c, 1, 0.8, 0.7, 1, 1, 3); + check(!c.s.fine, "the cap rising (the hold may rise again) ends it"); + } printf("== %d checks, %d failed ==\n", checks, fail); return fail != 0; } diff --git a/dm/gfx/tests/t_gpuprof.m b/dm/gfx/tests/t_gpuprof.m index 8a0f96edaf..1bcf221782 100644 --- a/dm/gfx/tests/t_gpuprof.m +++ b/dm/gfx/tests/t_gpuprof.m @@ -43,10 +43,17 @@ - (void)complete { @end // A draw pass answers only the render encoder's timestamp selector, an upload encoder only the compute one: a stamp sent to the wrong kind throws, as Metal 4's encoders do. @interface ProfileRender : NSObject -@property int stamps; @property NSUInteger last; +@property int stamps, geom; @property NSUInteger last; @property MTLRenderStages geom_stages; @end @implementation ProfileRender -- (void)writeTimestampWithGranularity:(MTL4TimestampGranularity)g afterStage:(MTLRenderStages)s intoHeap:(id)h atIndex:(NSUInteger)i { (void)g; (void)s; (void)h; _stamps++; _last = i; } +- (void)writeTimestampWithGranularity:(MTL4TimestampGranularity)g afterStage:(MTLRenderStages)s intoHeap:(id)h atIndex:(NSUInteger)i { (void)g; _stamps++; _last = i; if (h && h == (id)g_gp_gheap) { _geom++; _geom_stages |= s; } } +@end +@interface ProfileQueue : NSObject +@property int commits; +@end +@implementation ProfileQueue +- (void)commit:(id const *)b count:(NSUInteger)n { (void)b; (void)n; _commits++; } +- (void)commit:(id const *)b count:(NSUInteger)n options:(id)o { (void)b; (void)n; (void)o; _commits++; } @end @interface ProfileCompute : NSObject @property int stamps; @@ -85,5 +92,31 @@ int main(void) { @autoreleasepool { @try { gp_end(upload); } @catch (NSException *x) { CHECK(0, "another queue's encoder got the open pass's timestamp"); } CHECK(upload.stamps == 0 && g_gp_cur == k, "another queue's encoder does not close the open pass"); gp_end(pass); CHECK(pass.stamps == 2 && pass.last == 2 * (NSUInteger)k + 1 && g_gp_cur < 0, "the pass's own end writes its end stamp"); + CHECK(pass.geom == 0, "without DM_NVN_GPUPROF_GEOM a pass writes no geometry stamps"); + // DM_NVN_GPUPROF_GEOM: a pass's end also stamps where its vertex and mesh stages finish, in the second heap, before its fragment end stamp + g_gp_gheap = (id)[ProfileHeap new]; g_gp_geom = 1; ProfileRender *gpass = [ProfileRender new]; + gp_begin(gpass, 'R', nil); int k2 = g_gp_cur; gp_end(gpass); + CHECK(gpass.stamps == 4 && gpass.geom == 2 && gpass.geom_stages == (MTLRenderStageVertex | MTLRenderStageMesh), "a pass's end stamps its vertex and mesh stages"); + CHECK(gpass.last == 2 * (NSUInteger)k2 + 1, "the fragment end stamp still comes last, at the pass's own index"); + // The CPU timeline: recorded only while a frame is profiled, through the real wait and commit paths, and handed to the report with the labels + if (g_gp_state == 1) { gp_snap open = gp_close(); free(open.lab); free(open.gt); atomic_store(&g_gp_busy, 0); } // the pass frame above, left open + g_gp_every = 1; g_gp_state = 0; g_gp_geom = 0; + atomic_store(&g_gt_n, 0); + g_done = 0; mtl_wait_at(5, 1000000ull, WS_ALLOC); CHECK(atomic_load(&g_gt_n) == 0, "no timeline is kept outside a profiled frame"); + g_sub_serial = 41; g_gt_queue = 7; g_gt_sub0 = mach_absolute_time(); + atomic_store(&g_cur_frame, 20); gp_begin(nil, 'C', nil); gp_end(nil); + CHECK(atomic_load(&g_gt_on) && atomic_load(&g_gt_n) == 1 && g_gt[0].kind == GT_SUB && g_gt[0].a == 41 && g_gt[0].b == (7 | 1ull << 63), "the timeline opens with the submission being encoded"); + CHECK(g_gp_lab[g_gp_n - 1].sub == 41, "an encoder's label names its submission"); + uint64_t w0 = mach_absolute_time(); mtl_wait_at(5, 2000000ull, WS_ALLOC); // a fence the GPU never reaches: the wait times out after 2 ms + CHECK(atomic_load(&g_gt_n) == 2 && g_gt[1].kind == GT_WAIT && g_gt[1].a == WS_ALLOC && g_gt[1].b == 5 && g_gt[1].t0 >= w0 && g_gt[1].t1 > g_gt[1].t0, "a blocking wait is placed on the timeline with its site and fence"); + ProfileQueue *queue = [ProfileQueue new]; g_q4 = (id)queue; g_seg = 3; g_rec = 0; + rec_commit((id)[NSObject new], nil); + CHECK(queue.commits == 1 && atomic_load(&g_gt_n) == 3 && g_gt[2].kind == GT_COMMIT && g_gt[2].a == 41 && g_gt[2].b == 3, "a commit is placed on the timeline with its submission and segment"); + mtl_gp_note_park(mach_absolute_time(), 1, 9); + CHECK(atomic_load(&g_gt_n) == 4 && g_gt[3].kind == GT_QPARK && g_gt[3].a == 1 && g_gt[3].b == 9, "the queue worker's park is placed on the timeline"); + gp_snap snap = gp_close(); + CHECK(snap.ngt == 4 && snap.n == 1 && snap.frame == 20 && !atomic_load(&g_gt_on), "closing the frame hands its timeline to the report and stops recording"); + mtl_wait_at(5, 1000000ull, WS_ALLOC); CHECK(atomic_load(&g_gt_n) == 4, "nothing is recorded after the frame closed"); + gp_report(snap); CHECK(!atomic_load(&g_gp_busy), "the report frees the heap"); printf("t_gpuprof: %d checks, %d failed\n", checks, failed); return failed != 0; } } diff --git a/dm/gfx/tests/t_large_mdi.m b/dm/gfx/tests/t_large_mdi.m index 36183ebb13..9bacda0bda 100644 --- a/dm/gfx/tests/t_large_mdi.m +++ b/dm/gfx/tests/t_large_mdi.m @@ -1,8 +1,10 @@ // Issue #941: the last live indirect draw paints the target. The count is written on the GPU after recording. #import #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_linear_readback.m b/dm/gfx/tests/t_linear_readback.m index 87ac1654d4..f33ee832a0 100644 --- a/dm/gfx/tests/t_linear_readback.m +++ b/dm/gfx/tests/t_linear_readback.m @@ -1,8 +1,10 @@ // NVN linear image storage: GPU image writes must be visible through the memory-pool CPU mapping. // Synthetic 160x90 RGBA8_SRGB IMAGE|LINEAR textures use a valid 640-byte row pitch. A linear texture whose rows no view can take (DM_TBUF_ALIGN=64) is uploaded at its stride. #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_link_ticks.m b/dm/gfx/tests/t_link_ticks.m index 9cdee02a5a..a0d0c4e176 100644 --- a/dm/gfx/tests/t_link_ticks.m +++ b/dm/gfx/tests/t_link_ticks.m @@ -19,8 +19,10 @@ static int test_clock_gettime(clockid_t clock, struct timespec *t) { #define clock_gettime test_clock_gettime #define pthread_cond_timedwait test_pthread_cond_timedwait #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #undef pthread_cond_timedwait #undef clock_gettime #define g_ft g_ft_hle diff --git a/dm/gfx/tests/t_mesh_first_use.m b/dm/gfx/tests/t_mesh_first_use.m index 415838a1ef..def78eb1dc 100644 --- a/dm/gfx/tests/t_mesh_first_use.m +++ b/dm/gfx/tests/t_mesh_first_use.m @@ -3,8 +3,10 @@ // A mesh shader with no task draws more workgroups than Metal's mesh grid holds (DMSH_MESH_GRID) through its object // function's blocks (dmsh_meshstage.py main0_o), directly and indirectly: every workgroup draws its own pixel once. #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_mip_extent.m b/dm/gfx/tests/t_mip_extent.m index bab3bcf737..7fb4d504e5 100644 --- a/dm/gfx/tests/t_mip_extent.m +++ b/dm/gfx/tests/t_mip_extent.m @@ -1,8 +1,10 @@ // Real NVN recording entry → production Metal replay; each mip of 8x6 is hand-calculated independently; with no viewport set, an explicit viewport is not used to dodge it. // nvn_mtl.m's nvn_game_fps is a weak default and hle_nvn.c gives the strong definition; in one translation unit the weak one is renamed (as in t_present_crop.m) #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle // both files have a static g_ft, so hle_nvn.c's is renamed too (as in t_present_crop.m) #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_pkg_evict.m b/dm/gfx/tests/t_pkg_evict.m new file mode 100644 index 0000000000..bac52cad0b --- /dev/null +++ b/dm/gfx/tests/t_pkg_evict.m @@ -0,0 +1,75 @@ +// Memory pressure frees the Metal copies of uploaded textures nothing used for 30 s (pkg_evict_idle): the copy leaves the residency set, its texture ID's pool table entry reads the dummy, +// a pool walk does not make it again up front, and a shader's next read through the pool does. A texture used lately, one the GPU wrote and a pinned one stay +#include "../nvn/nvn_mtl.m" +void *front_metal_layer(void) { return NULL; } +module_t *module_of(const void *p) { (void)p; return NULL; } +module_t *g_mod; int g_nmod; +void svc_thread_dump(void) {} +uint64_t now_ns(void) { return bp_now(); } +static int checks, failed; +#define CHECK(label, c) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s (line %d)\n", label, __LINE__); } } while (0) +static void finish(void) { CHECK("submission completes", mtl_wait(mtl_sub_commit(), 5000000000ull)); CHECK("GPU has no submission error", !mtl_last_commit_error()); } +static int resident(id o) { pthread_mutex_lock(&g_res_mu); int r = [g_res_objects containsObject:o]; pthread_mutex_unlock(&g_res_mu); return r; } +static uint32_t clock_s(void) { return (uint32_t)(clock_gettime_nsec_np(CLOCK_MONOTONIC) / 1000000000ull) + 1; } +enum { NT = 4, ID0 = 401 }; // 0 idle, 1 used lately, 2 written by the GPU, 3 pinned +static uint64_t entry(int id_, uint64_t *dummy) { // the pool table's entry for id_ after a walk, in a submission of its own + __unsafe_unretained id tb = nil; uint64_t v; + mtl_sub_begin(); os_unfair_lock_lock(&g_rmu); + pool_gpu(0, MTLTextureType2D, 0, 0, &tb); + const uint64_t *e = (const uint64_t *)((const uint8_t *)tb.contents + DMSH_POOL_HEAD); uint32_t n = *(const uint32_t *)tb.contents; + v = e[id_]; if (dummy) *dummy = e[n]; + os_unfair_lock_unlock(&g_rmu); finish(); + return v; +} +int main(void) { @autoreleasepool { + mtl_init(); + size_t one = 1u << 20, poolsize = NT * one; uint8_t *mem = NULL; if (posix_memalign((void **)&mem, getpagesize(), poolsize)) abort(); memset(mem, 0x5a, poolsize); + pool_t pool = {.magic = MAGIC('P', 'O', 'O', 'L'), .mem = mem, .size = poolsize, .flags = NVN_MEMORY_POOL_FLAGS_CPU_UNCACHED | NVN_MEMORY_POOL_FLAGS_GPU_CACHED}; + mtl_pool_add(mem, poolsize); nvn_dirty_add_range(mem, poolsize); + tex_t t[NT]; + for (int i = 0; i < NT; i++) { + t[i] = (tex_t){.magic = MAGIC('T', 'E', 'X', 0), .has_layout = 1, .serial = 88100 + (uint64_t)i, .pool = &pool, .mem = mem + (size_t)i * one, .off = (int64_t)(i * one)}; + t[i].d = (nvn_texdesc){.target = NVN_TEXTURE_TARGET_2D, .format = NVN_FORMAT_RGBA8, .width = 256, .height = 256, .depth = 1, .levels = 1, .samples = 1}; nvn_tex_layout(&t[i].d, &t[i].L); + mtl_tex_init(&t[i]); mtl_reg_tex(ID0 + i, &t[i], NULL); + } + (void)pool_seen_gpu(); + // A shader reads all four through the pool: each is made + for (int i = 0; i < NT; i++) ((uint32_t *)g_seen_buf.contents)[(ID0 + i) / 32] |= 1u << ((ID0 + i) % 32); + uint64_t dummy = 0, made[NT]; + (void)entry(ID0, &dummy); + for (int i = 0; i < NT; i++) { made[i] = entry(ID0 + i, NULL); CHECK("a read texture is made", made[i] && made[i] != dummy); } + NvPkg *pk[NT]; __weak id copy[NT]; + for (int i = 0; i < NT; i++) { pk[i] = tex_get(t[i].serial); CHECK("uploaded as a package", [pk[i] isKindOfClass:[NvPkg class]] && pk[i]->tex && resident(pk[i]->tex)); copy[i] = pk[i]->tex; } + pthread_mutex_lock(&g_gws_mu); gws_set((uintptr_t)t[2].mem, (uintptr_t)t[2].mem + t[2].L.size); pthread_mutex_unlock(&g_gws_mu); // the GPU wrote texture 2's storage + mtl_tex_pin(t[3].serial); + // 40 s since anything used 0, 2 and 3; 1 was used just now + uint32_t old = clock_s() - 40; + for (int i = 0; i < NT; i++) { g_tid_used[ID0 + i] = i == 1 ? clock_s() : old; pk[i]->used_s = i == 1 ? clock_s() : old; } + uint64_t was_n = g_evict_n; + pk[0] = pk[1] = pk[2] = pk[3] = nil; + atomic_store(&g_mp_want, 2); + mtl_sub_begin(); finish(); // the trim runs at the submission's start + CHECK("one texture freed", g_evict_n == was_n + 1); + CHECK("the idle texture's serial no longer resolves to its copy", tex_get(t[0].serial) == nil); + CHECK("the used, GPU-written and pinned ones stay", tex_get(t[1].serial) && tex_get(t[2].serial) && tex_get(t[3].serial)); + CHECK("its texture ID is marked", g_treg[ID0].evicted && !g_treg[ID0].view && !pool_seen(ID0)); + mtl_sub_begin(); finish(); mtl_drain(); + @autoreleasepool { id c = copy[0]; CHECK("the freed copy left the residency set", !c || !resident(c)); } + @autoreleasepool { id c = copy[1]; CHECK("the used one is still resident", c && resident(c)); } + // The walk leaves it the dummy (it would make a texture this small up front), the others keep theirs + CHECK("the table entry reads the dummy", entry(ID0, NULL) == dummy); + CHECK("again at the next walk", entry(ID0, NULL) == dummy && tex_get(t[0].serial) == nil); + CHECK("the used texture's entry is unchanged", entry(ID0 + 1, NULL) == made[1]); + // A shader reads it: made again at the next scan + ((uint32_t *)g_seen_buf.contents)[ID0 / 32] |= 1u << (ID0 % 32); + uint64_t back = entry(ID0, NULL); + CHECK("a read makes it again", back && back != dummy && [tex_get(t[0].serial) isKindOfClass:[NvPkg class]]); + // Without memory pressure nothing goes + for (int i = 0; i < NT; i++) g_tid_used[ID0 + i] = old; + was_n = g_evict_n; mtl_sub_begin(); finish(); + CHECK("no pressure, no eviction", g_evict_n == was_n && tex_get(t[0].serial)); + mtl_tex_unpin(t[3].serial); + for (int i = 0; i < NT; i++) { mtl_reg_tex(ID0 + i, NULL, NULL); mtl_tex_release(&t[i]); } + mtl_drain(); mtl_alias_drop_pool(&pool); nvn_dirty_remove_range(mem); mtl_pool_del(mem); mtl_drain(); free(mem); + printf("t_pkg_evict: %d checks, %d failed\n", checks, failed); return failed != 0; +} } diff --git a/dm/gfx/tests/t_pkg_spare.m b/dm/gfx/tests/t_pkg_spare.m new file mode 100644 index 0000000000..7e1edab96b --- /dev/null +++ b/dm/gfx/tests/t_pkg_spare.m @@ -0,0 +1,65 @@ +// A packaged texture's spare (NvPkg): the texture a re-upload replaced stays resident for a quick second re-upload, and leaves the residency set once it has waited +// g_spare_idle_ns with no re-upload taking it, or at a memory pressure trim, after the submissions that used it completed (spare_trim) +#include "../nvn/nvn_mtl.m" +void *front_metal_layer(void) { return NULL; } +module_t *module_of(const void *p) { (void)p; return NULL; } +module_t *g_mod; int g_nmod; +void svc_thread_dump(void) {} +uint64_t now_ns(void) { return bp_now(); } +static int checks, failed; +#define CHECK(label, c) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s\n", label); } } while (0) +static void finish(void) { CHECK("submission completes", mtl_wait(mtl_sub_commit(), 5000000000ull)); CHECK("GPU has no submission error", !mtl_last_commit_error()); } +static int resident(id o) { pthread_mutex_lock(&g_res_mu); int r = [g_res_objects containsObject:o]; pthread_mutex_unlock(&g_res_mu); return r; } +static void write_content(tex_t *t, void *mem, size_t n, unsigned round) { + dm_guest_write_prepare(mem, n); + uint32_t *p = malloc((size_t)t->d.width * t->d.height * 4); + for (unsigned i = 0; i < t->d.width * t->d.height; i++) p[i] = i * 2654435761u + round; + CHECK("swizzle succeeds", !nvn_swizzle(&t->d, 0, 0, p, t->d.width * 4, t->mem)); + free(p); +} +// One packaged texture re-uploaded once; then `how` lets its spare go: 0 idle past the limit, 1 a memory pressure trim, 2 a re-upload soon after (kept and reused) +static void run(int how) { + tex_t t = {.magic = MAGIC('T', 'E', 'X', 0), .has_layout = 1}; static uint64_t serial = 77100; t.serial = serial++; + t.d = (nvn_texdesc){.target = NVN_TEXTURE_TARGET_2D, .format = NVN_FORMAT_RGBA8, .width = 256, .height = 256, .depth = 1, .levels = 1, .samples = 1}; nvn_tex_layout(&t.d, &t.L); + size_t poolsize = (t.L.size + 4096 + getpagesize() - 1) & ~(size_t)(getpagesize() - 1); void *mem = NULL; if (posix_memalign(&mem, getpagesize(), poolsize)) abort(); memset(mem, 0, poolsize); + pool_t pool = {.magic = MAGIC('P', 'O', 'O', 'L'), .mem = mem, .size = poolsize, .flags = NVN_MEMORY_POOL_FLAGS_CPU_UNCACHED | NVN_MEMORY_POOL_FLAGS_GPU_CACHED}; t.pool = &pool; t.mem = (uint8_t *)mem + 4096; + mtl_pool_add(mem, poolsize); nvn_dirty_add_range(mem, poolsize); + write_content(&t, mem, poolsize, 0); + mtl_sub_begin(); id first = tex_mtl(&t); finish(); + CHECK("first upload resolves", first != nil); + write_content(&t, mem, poolsize, 1); + uint64_t re = g_pkg_reuploads; + mtl_sub_begin(); id second = tex_mtl(&t); finish(); + CHECK("a write re-uploads", g_pkg_reuploads == re + 1 && second && second != first); + NvPkg *pk = tex_get(t.serial); + CHECK("the package keeps the old texture as its spare", [pk isKindOfClass:[NvPkg class]] && pk->spare == first); + CHECK("the spare is resident", resident(first)); + __weak id weak_first = first; first = nil; + if (how == 2) { + write_content(&t, mem, poolsize, 2); + mtl_sub_begin(); id third = tex_mtl(&t); finish(); + CHECK("a re-upload within the limit reuses the spare", third == weak_first); + CHECK("and the second texture becomes the spare", pk->spare == second); + } else { + uint64_t trimmed = g_spare_trimmed; + if (how == 0) { g_spare_idle_ns = 0; g_spare_last = 0; } else atomic_store(&g_mp_want, 2); + mtl_sub_begin(); finish(); + CHECK("the spare was retired", g_spare_trimmed > trimmed && pk->spare == nil); // a pressure trim also takes the earlier case's spares + mtl_sub_begin(); finish(); // its submission completed: the next start drains it + mtl_drain(); + @autoreleasepool { id f = weak_first; CHECK("the retired spare left the residency set", !f || !resident(f)); } + CHECK("the current texture stays resident", resident(second) && pk->tex == second); + CHECK("the current texture still resolves", tex_mtl(&t) == second); + g_spare_idle_ns = 3000000000ull; + write_content(&t, mem, poolsize, 3); + mtl_sub_begin(); id third = tex_mtl(&t); finish(); + CHECK("the next re-upload makes a new texture", third && third != second && pk->spare == second); + } + pk = nil; second = nil; + mtl_tex_release(&t); mtl_drain(); mtl_alias_drop_pool(&pool); nvn_dirty_remove_range(mem); mtl_pool_del(mem); mtl_drain(); free(mem); +} +int main(void) { @autoreleasepool { + mtl_init(); + for (int how = 0; how < 3; how++) run(how); + printf("t_pkg_spare: %d checks, %d failed\n", checks, failed); return failed != 0; +} } diff --git a/dm/gfx/tests/t_pool_notes.m b/dm/gfx/tests/t_pool_notes.m index 8af3b9d877..5b85b06cef 100644 --- a/dm/gfx/tests/t_pool_notes.m +++ b/dm/gfx/tests/t_pool_notes.m @@ -5,8 +5,10 @@ // what a table built whole holds. // Ocarina of Time maps and unmaps virtual pool runs dozens of times a second and registers something between most of its draws; each of those walked its 33,025-entry texture table #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_present_crop.m b/dm/gfx/tests/t_present_crop.m index ee10e11145..9cb043b62e 100644 --- a/dm/gfx/tests/t_present_crop.m +++ b/dm/gfx/tests/t_present_crop.m @@ -1,8 +1,10 @@ // Present crop regression: colored 8×8 texture, closed-form RGBA expectations; real Metal rendering, no dependence on the game or on cross-run determinism. // nvn_mtl.m's nvn_game_fps is a weak default and hle_nvn.c gives the strong definition; in one translation unit that is a redefinition, so the weak one is renamed (this test does not look at the frame-rate target) #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle // both files have a static g_ft (nvn_mtl.m's fragment argument table, hle_nvn.c's textures a flush can mark CPU-written), so hle_nvn.c's is renamed too #include "../nvn/hle_nvn.c" #undef g_ft @@ -253,7 +255,7 @@ int main(void) { @autoreleasepool { for(int y=0;y=crop54[2]||y>=crop54[3]],4); [sw replaceRegion:MTLRegionMake2D(0,0,TW,TH) mipmapLevel:0 withBytes:sp bytesPerRow:TW*4];free(sp);res_add(sw);res_commit(); double sa,sb; - mtl_present_layer(0,0);present_shape(sw,&sa,&sb);EXPECT("no sized layer: the display's width",1920,(int)sa);EXPECT("no sized layer: the display's height",1080,(int)sb); + mtl_present_layer(0,0);present_shape(sw,NULL,&sa,&sb);EXPECT("no sized layer: the display's width",1920,(int)sa);EXPECT("no sized layer: the display's height",1080,(int)sb); for(int m4=0;m4<2;m4++) { int outH[2]={H,40}; // 16:9 fills; a 16:10 canvas keeps the bars above and below for(int k=0;k<2;k++) { @@ -267,12 +269,30 @@ int main(void) { @autoreleasepool { EXPECT(k?"5:4 crop on a 16:10 canvas: 16:9 of red, black above and below":"5:4 crop on a 16:9 canvas: all red, no side bars",0,bad);free(o);res_remove(ot); } } - mtl_present_layer(4,3);present_shape(sw,&sa,&sb);EXPECT("a sized layer gives its own shape",4*(int)sb,3*(int)sa);mtl_present_layer(0,0); + mtl_present_layer(4,3);present_shape(sw,NULL,&sa,&sb);EXPECT("a sized layer gives its own shape",4*(int)sb,3*(int)sa);mtl_present_layer(0,0); MTLTextureDescriptor *td2=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:1920 height:1344 mipmapped:NO];td2.storageMode=MTLStorageModePrivate;td2.usage=MTLTextureUsageShaderRead; id tall=[g_dev newTextureWithDescriptor:td2]; - present_shape(tall,&sa,&sb);EXPECT("a taller texture without DM_SCREEN_ASPECT: 16:9",1080,(int)sb); - mtl_present_screen(1920,1344);present_shape(tall,&sa,&sb);EXPECT("DM_SCREEN_ASPECT: a texture that follows it keeps the taller shape",1344,(int)sb); - present_shape(sw,&sa,&sb);EXPECT("DM_SCREEN_ASPECT: a 16:9 texture of a build without stubs stays 16:9",1080,(int)sb);mtl_present_screen(0,0); + present_shape(tall,NULL,&sa,&sb);EXPECT("a taller texture without DM_SCREEN_ASPECT: 16:9",1080,(int)sb); + mtl_present_screen(1920,1344);present_shape(tall,NULL,&sa,&sb);EXPECT("DM_SCREEN_ASPECT: a texture that follows it keeps the taller shape",1344,(int)sb); + present_shape(sw,NULL,&sa,&sb);EXPECT("DM_SCREEN_ASPECT: a 16:9 texture of a build without stubs stays 16:9",1080,(int)sb);mtl_present_screen(0,0); + // A crop of the screen's shape inside larger window textures (Ocarina of Time keeps its window textures and moves its crop): the picture takes the crop's shape, wider or + // taller than 16:9; a crop of another shape, or no screen shape set, keeps 16:9 (the crop only picks texels) + { const int wide[4]={0,0,56,24}; + mtl_present_screen(7,3);present_shape(sw,wide,&sa,&sb);EXPECT("a wider screen: a crop of its shape, width",56,(int)sa);EXPECT("a wider screen: a crop of its shape, height",24,(int)sb); + present_shape(sw,crop54,&sa,&sb);EXPECT("a wider screen: a crop of another shape stays 16:9",1080,(int)sb); + mtl_present_screen(5,4);present_shape(sw,crop54,&sa,&sb);EXPECT("a taller screen: a crop of its shape, width",40,(int)sa);EXPECT("a taller screen: a crop of its shape, height",32,(int)sb); + mtl_present_screen(0,0);present_shape(sw,wide,&sa,&sb);EXPECT("no screen shape: a wide crop stays 16:9",1080,(int)sb); + // drawn: the 5:4 crop under a 5:4 screen fills a 5:4 canvas (all red, no bars), on the classic and the Metal 4 present + mtl_present_screen(5,4); + for(int m4=0;m4<2;m4++){ + MTLTextureDescriptor *od=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:50 height:40 mipmapped:NO];od.storageMode=MTLStorageModeShared;od.usage=MTLTextureUsageRenderTarget; + id ot=[g_dev newTextureWithDescriptor:od];res_add(ot);res_commit(); + if(m4)present_offscreen_wait(sw,crop54,ot);else{id cb=[g_q commandBuffer];present_encode(cb,sw,ot,crop54);[cb commit];[cb waitUntilCompleted];} + uint8_t *o=malloc(50*40*4);[ot getBytes:o bytesPerRow:50*4 fromRegion:MTLRegionMake2D(0,0,50,40) mipmapLevel:0];int bad=0; + for(int i=0;i<50*40;i++)bad+=memcmp(o+4*i,colors[0],4)!=0;free(o);res_remove(ot); + EXPECT(m4?"Metal 4: a crop of the screen's shape fills a canvas of that shape":"classic: a crop of the screen's shape fills a canvas of that shape",0,bad); + } + mtl_present_screen(0,0); } // The front end's layout and the mouse follow the same shape, not the crop's (front_picture_shape): a real present of the 5:4 crop tex_t st={.magic=MAGIC('T', 'E', 'X', 0), .serial =10002};st.d.width=TW;st.d.height=TH;st.d.depth=st.d.levels=1;st.d.format=NVN_FORMAT_RGBA8;st.d.target=NVN_TEXTURE_TARGET_2D;serial_put(st.serial,sw); win_t w3={.ntex=1};w3.tex[0]=(NVNtexture *)&st;set((NVNwindow *)&w3,crop54[0],crop54[1],crop54[2],crop54[3]); diff --git a/dm/gfx/tests/t_present_snap.m b/dm/gfx/tests/t_present_snap.m index 081010dc92..821b6df0e5 100644 --- a/dm/gfx/tests/t_present_snap.m +++ b/dm/gfx/tests/t_present_snap.m @@ -1,7 +1,9 @@ // Snapshot lifecycle: real NVN acquire/present/suspend, real Metal copies, and controlled encoder/GPU delays. #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_queue_lifetime.m b/dm/gfx/tests/t_queue_lifetime.m index 1e0b22ca9b..f9e63cf628 100644 --- a/dm/gfx/tests/t_queue_lifetime.m +++ b/dm/gfx/tests/t_queue_lifetime.m @@ -1,8 +1,10 @@ // Submitted commands own their CPU descriptors. Pool storage and shader code stay // alive while a wait parks the queue; only program/texture objects are reused. #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_queue_origin.m b/dm/gfx/tests/t_queue_origin.m index d0e5d89076..6e48c1fa33 100644 --- a/dm/gfx/tests/t_queue_origin.m +++ b/dm/gfx/tests/t_queue_origin.m @@ -2,8 +2,10 @@ // used to construct later viewports can change independently. Check actual // culling and front_facing pixels while alternating two queues on one device. #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_readback.m b/dm/gfx/tests/t_readback.m index 22a50245c5..6351d0c0dc 100644 --- a/dm/gfx/tests/t_readback.m +++ b/dm/gfx/tests/t_readback.m @@ -1,8 +1,10 @@ // NVN readback contract: a pending clear must reach both GPU buffer copies and CPU reads. // Expected 8x4 RGBA values are literal bytes, independent of the Metal replay's state. #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_render_counter_overlap.m b/dm/gfx/tests/t_render_counter_overlap.m index 914a05a507..9166c617cc 100644 --- a/dm/gfx/tests/t_render_counter_overlap.m +++ b/dm/gfx/tests/t_render_counter_overlap.m @@ -5,8 +5,10 @@ // (it did in 3 of 60 runs); the predicates, which the host's encode-time values decide, are checked. #include "game_profile.h" #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_render_enable_queue.m b/dm/gfx/tests/t_render_enable_queue.m index b90ec2fffd..f64bed0fdd 100644 --- a/dm/gfx/tests/t_render_enable_queue.m +++ b/dm/gfx/tests/t_render_enable_queue.m @@ -2,8 +2,10 @@ // Every path uses public NVN recording; the last case gates only GPU completion. #include "game_profile.h" #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_res_absent.m b/dm/gfx/tests/t_res_absent.m new file mode 100644 index 0000000000..2b3dd5f378 --- /dev/null +++ b/dm/gfx/tests/t_res_absent.m @@ -0,0 +1,15 @@ +// What a shader reading or writing through a pointer to a buffer outside the residency set gets (dm/gfx/nvn/nvn_res_probe.inc; docs/reference/memory.md, "A read through a pointer +// to a buffer outside the residency set returns zeros"). It reports; it fails only when a resident control is wrong, so the result is the log, not the exit code. +// ./t_res_absent [rounds]. On a device, the host runs the same probe at start with DM_RES_PROBE=1 +#import +#import +#include +#include +#include +#include "../nvn/nvn_res_probe.inc" +static void say(const char *s) { printf("%s\n", s); fflush(stdout); } +int main(int argc, char **argv) { @autoreleasepool { + int ok = res_probe(MTLCreateSystemDefaultDevice(), argc > 1 ? atoi(argv[1]) : 2, say); + printf("t_res_absent: %s\n", ok ? "done" : "FAIL"); + return !ok; +} } diff --git a/dm/gfx/tests/t_rt_lifetime.m b/dm/gfx/tests/t_rt_lifetime.m index aba5af14ca..59ef1d3b25 100644 --- a/dm/gfx/tests/t_rt_lifetime.m +++ b/dm/gfx/tests/t_rt_lifetime.m @@ -1,8 +1,10 @@ // Queue bindings outlive completed command recordings. Exercise the public NVN // interface and verify pixels after the caller reuses the recording's memory. #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_rt_recycle.m b/dm/gfx/tests/t_rt_recycle.m index 49af5a6961..97d7c45e9e 100644 --- a/dm/gfx/tests/t_rt_recycle.m +++ b/dm/gfx/tests/t_rt_recycle.m @@ -92,11 +92,37 @@ int main(void) { @autoreleasepool { CHECK(tex_mtl(&g) && !tex_mtl(&g).heap, "a block-compressed texture (an asset, never rendered to) keeps its own allocation"); mtl_tex_release(&e); mtl_tex_release(&f); mtl_tex_release(&g); mtl_alias_drop_pool(&cpu); mtl_alias_drop_pool(&pool); settle(); } - unsigned before = waiting(); + { // memory pressure (mem_pressure_event, mem_trim): a warn does nothing on the Mac, a critical frees every waiting heap at the next submission's start, however fresh, + // and the idle upload slots' staging blocks + tex_t g = target(&pool, 95007, 0, 640, 360); mtl_tex_init(&g); id tg = tex_mtl(&g); + __weak id gh = tg.heap; tg = nil; mtl_tex_release(&g); mtl_alias_drop_pool(&pool); settle(); + unsigned w0 = waiting(); uint64_t t0 = g_rh_trimmed; + CHECK(w0 == 3, "three heaps wait, one of them just freed (its target took a waiting heap and gave it back)"); + size_t off; up_begin(); (void)up_alloc(1 << 20, &off); up_flush(); mtl_sub_commit(); mtl_drain(); dispatch_sync(g_feedback_q, ^{}); // a slot's staging block, its batch done + int slot_blocks = 0; for (int i = 0; i < 3; i++) slot_blocks += g_up_slot_blk[i] != nil; + CHECK(slot_blocks >= 1, "an upload slot keeps its staging block"); + mem_pressure_event(1); mtl_sub_begin(); + CHECK(TARGET_OS_IPHONE || waiting() == w0, "a warn leaves the Mac's waiting heaps alone"); + mtl_sub_commit(); mtl_drain(); mem_pressure_event(2); mtl_sub_begin(); + slot_blocks = 0; for (int i = 0; i < 3; i++) slot_blocks += g_up_slot_blk[i] != nil; + CHECK(waiting() == 0 && g_rh_trimmed == t0 + w0 && g_rh_bytes == 0, "a critical frees every waiting heap at the next submission's start"); + CHECK(!gh || !resident(gh), "the fresh heap leaves the residency set too"); + CHECK(slot_blocks == 0, "the idle upload slots give back their staging blocks"); + CHECK(atomic_load(&g_mp_trims) == 1 && atomic_load(&g_mp_n[2]) == 1, "the trim is counted"); + mtl_sub_commit(); mtl_drain(); mtl_sub_begin(); + } + { // the heaps of the checks below again + tex_t h[3]; unsigned hw[3] = {640, 1280, 160}, hh[3] = {360, 720, 90}; + for (int i = 0; i < 3; i++) { h[i] = target(&pool, 95010 + i, (uint64_t)i << 23, hw[i], hh[i]); mtl_tex_init(&h[i]); (void)tex_mtl(&h[i]); } + for (int i = 0; i < 3; i++) mtl_tex_release(&h[i]); + mtl_alias_drop_pool(&pool); settle(); + first_heap = nil; + } + unsigned before = waiting(); uint64_t trimmed0 = g_rh_trimmed; CHECK(before == 3, "three heaps wait"); os_unfair_lock_lock(&g_rh_lk); for (unsigned i = 0; i < g_rh_n; i++) g_rh[i].t -= RH_IDLE_NS; os_unfair_lock_unlock(&g_rh_lk); mtl_sub_commit(); mtl_drain(); mtl_sub_begin(); // rh_trim - CHECK(waiting() == 0 && g_rh_trimmed == before && g_rh_bytes == 0, "heaps that waited too long are freed when a submission begins"); + CHECK(waiting() == 0 && g_rh_trimmed == trimmed0 + before && g_rh_bytes == 0, "heaps that waited too long are freed when a submission begins"); CHECK(!first_heap || !resident(first_heap), "and leave the residency set"); { // a same-pass feedback snapshot is placed in recycled memory, and its heap waits once the snapshot goes int fresh = 0; uint64_t made = g_rh_made; fb_cache_t *e = fb_snap(95007, 0, 0, MTLPixelFormatRGBA16Float, 640, 360, 1, &fresh); diff --git a/dm/gfx/tests/t_sparse_tiles.m b/dm/gfx/tests/t_sparse_tiles.m index 4526c2acb9..685236d35a 100644 --- a/dm/gfx/tests/t_sparse_tiles.m +++ b/dm/gfx/tests/t_sparse_tiles.m @@ -5,8 +5,10 @@ // its last place and each new place reads the memory (the CPU's fill behind a GPU-written place, the GPU's write to the memory as a buffer), a tile cut by the level's edge shares nothing, and a // new pool over the same memory never finds the old pool's tile. #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #include "../nvn/nvn_mtl.m" #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_sub_overlap.m b/dm/gfx/tests/t_sub_overlap.m new file mode 100644 index 0000000000..646736b326 --- /dev/null +++ b/dm/gfx/tests/t_sub_overlap.m @@ -0,0 +1,49 @@ +// With Metal encoding on its own thread (DM_NVN_ENC_THREAD), a submission's end hands its records to the encode thread and returns: the replay translates the next submission while +// the encode thread finishes this one. It used to wait for the encode thread (rec_drain) at the end of every submission, and Ocarina of Time makes about 30 a frame (one at each event +// signal), so on the iPhone the GPU sat idle before most of them (13.6 of 14.8 ms of gaps in a 35 ms frame). What needs the work committed waits for the submission's note +// (g_sub_cmt): a present of the game's own texture (no snapshot), before its display command buffer. The encode thread is held inside a submission by a queue block here. +#include "../nvn/nvn_mtl.m" +void *front_metal_layer(void) { return NULL; } +module_t *module_of(const void *p) { (void)p; return NULL; } +module_t *g_mod; int g_nmod; +void svc_thread_dump(void) {} +uint64_t now_ns(void) { return bp_now(); } +static int checks, failed; +#define CHECK(name, ok) do { int pass = !!(ok); checks++; failed += !pass; printf("%s: %s\n", name, pass ? "PASS" : "FAIL"); } while (0) + +static dispatch_semaphore_t g_gate, g_sub_done, g_wait_done; +static _Atomic uint64_t g_fence_out; +static void *submit_thread(void *arg) { // one submission whose encoding the gate holds + (void)arg; @autoreleasepool { + state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); + dispatch_semaphore_t gate = g_gate; rec_queue_block(^{ dispatch_semaphore_wait(gate, DISPATCH_TIME_FOREVER); }); + atomic_store(&g_fence_out, mtl_sub_commit()); dispatch_semaphore_signal(g_sub_done); + } return NULL; +} +static void *present_wait_thread(void *arg) { sub_commit_wait((uint64_t)(uintptr_t)arg); dispatch_semaphore_signal(g_wait_done); return NULL; } + +int main(void) { @autoreleasepool { + alarm(20); setbuf(stdout, NULL); + setenv("DM_NVN_ENC_THREAD", "1", 1); setenv("DM_PRESENT_SNAP", "0", 1); + mtl_init(); + state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); uint64_t f0 = mtl_sub_commit(); + CHECK("a submission completes on the GPU", mtl_wait(f0, 2000000000ull)); + CHECK("its commit note is passed", atomic_load(&g_sub_cmt) >= f0); + + g_gate = dispatch_semaphore_create(0); g_sub_done = dispatch_semaphore_create(0); g_wait_done = dispatch_semaphore_create(0); + pthread_t th; pthread_create(&th, NULL, submit_thread, NULL); + long returned = dispatch_semaphore_wait(g_sub_done, dispatch_time(DISPATCH_TIME_NOW, 500 * NSEC_PER_MSEC)) == 0; + CHECK("the submission returns while the encode thread is still encoding it", returned); + uint64_t f1 = returned ? atomic_load(&g_fence_out) : f0 + 1; + CHECK("its commit note is not passed before the encode thread commits it", atomic_load(&g_sub_cmt) < f1); + pthread_t pw; pthread_create(&pw, NULL, present_wait_thread, (void *)(uintptr_t)f1); + CHECK("a present of the game's texture waits for that commit", dispatch_semaphore_wait(g_wait_done, dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC)) != 0); + dispatch_semaphore_signal(g_gate); + if (!returned) dispatch_semaphore_wait(g_sub_done, DISPATCH_TIME_FOREVER); + pthread_join(th, NULL); + CHECK("the present goes on once the encode thread has committed it", dispatch_semaphore_wait(g_wait_done, dispatch_time(DISPATCH_TIME_NOW, 2000 * NSEC_PER_MSEC)) == 0); + pthread_join(pw, NULL); + CHECK("the held submission completes on the GPU", mtl_wait(atomic_load(&g_fence_out), 2000000000ull)); + CHECK("its commit note is passed", atomic_load(&g_sub_cmt) >= atomic_load(&g_fence_out)); + printf("t_sub_overlap: %d checks, %d failed\n", checks, failed); return failed != 0; +} } diff --git a/dm/gfx/tests/t_tex_drop_mip.m b/dm/gfx/tests/t_tex_drop_mip.m new file mode 100644 index 0000000000..85aaa60f0f --- /dev/null +++ b/dm/gfx/tests/t_tex_drop_mip.m @@ -0,0 +1,122 @@ +// Smaller textures on small devices (nvn_mtl.m DM_NVN_TEX_DROP_MIP, docs/reference/memory.md): where Metal's working set is under 6 GB, a large sampled texture made from the game's +// data leaves out its largest level, so Metal level k holds the game's level k+1. Only sampling sees it: any other use makes it whole again. Checks: the device rule; level k of a +// dropped texture equals the guest's level k+1, by the CPU and by the GPU deswizzle (the direct path writes every level, so a dropped texture is staged instead); a re-upload after a +// guest write stays dropped and shows the new data; small, single-level and render-target textures are not dropped, image-flagged ones are; a use other than sampling makes the texture whole with +// every level and it stays whole; a sampled view's levels shift by one. Forced on (g_drop_on) wherever it runs +#include "../nvn/nvn_mtl.m" +void *front_metal_layer(void) { return NULL; } +module_t *module_of(const void *p) { (void)p; return NULL; } +module_t *g_mod; int g_nmod; +void svc_thread_dump(void) {} +uint64_t now_ns(void) { return bp_now(); } +static int checks, failed; +#define CHECK(label, c) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s (line %d)\n", label, __LINE__); } } while (0) +static void finish(void) { CHECK("submission completes", mtl_wait(mtl_sub_commit(), 5000000000ull)); CHECK("GPU has no submission error", !mtl_last_commit_error()); } + +typedef struct { tex_t t; pool_t pool; void *mem; size_t size; uint8_t *ref[16]; size_t ref_n[16]; unsigned bpp; } gtex; +// A swizzled texture in a CPU-visible pool, each level and layer filled with its own pattern (ref holds the linear bytes) +static void gtex_new(gtex *g, uint64_t serial, int target, int format, unsigned bpp, unsigned w, unsigned h, unsigned layers, unsigned levels, int flags) { + memset(g, 0, sizeof *g); + g->t = (tex_t){.magic = MAGIC('T', 'E', 'X', 0), .has_layout = 1, .serial = serial}; + g->t.d = (nvn_texdesc){.target = target, .format = format, .flags = flags, .width = w, .height = h, .depth = layers, .levels = levels, .samples = 1}; + nvn_tex_layout(&g->t.d, &g->t.L); g->bpp = bpp; + g->size = (g->t.L.size + 4096 + getpagesize() - 1) & ~(size_t)(getpagesize() - 1); + if (posix_memalign(&g->mem, getpagesize(), g->size)) abort(); + memset(g->mem, 0, g->size); + g->pool = (pool_t){.magic = MAGIC('P', 'O', 'O', 'L'), .mem = g->mem, .size = g->size, .flags = NVN_MEMORY_POOL_FLAGS_CPU_UNCACHED | NVN_MEMORY_POOL_FLAGS_GPU_CACHED}; + g->t.pool = &g->pool; g->t.mem = (uint8_t *)g->mem + 4096; + mtl_pool_add(g->mem, g->size); nvn_dirty_add_range(g->mem, g->size); +} +static void gtex_fill(gtex *g, uint32_t seed) { + dm_guest_write_prepare(g->mem, g->size); + for (unsigned l = 0; l < g->t.d.levels; l++) { + unsigned w = MAX(g->t.d.width >> l, 1u), h = MAX(g->t.d.height >> l, 1u), layers = g->t.d.target == NVN_TEXTURE_TARGET_2D ? 1 : g->t.d.depth; + size_t n = (size_t)w * h * g->bpp; free(g->ref[l]); g->ref[l] = malloc(n * layers); g->ref_n[l] = n; + for (unsigned a = 0; a < layers; a++) { + uint8_t *p = g->ref[l] + n * a; + for (size_t i = 0; i < n; i++) p[i] = (uint8_t)(i * 131u + l * 61u + a * 17u + seed * 7u + (i >> 9)); + CHECK("reference swizzle succeeds", !nvn_swizzle(&g->t.d, l, a, p, w * g->bpp, g->t.mem)); + } + } +} +// Does level `ml` of the Metal texture hold the guest's level `gl` (every layer)? +static int level_is(id m, unsigned ml, gtex *g, unsigned gl) { + unsigned w = MAX(g->t.d.width >> gl, 1u), h = MAX(g->t.d.height >> gl, 1u), layers = (unsigned)m.arrayLength; + if (MAX(m.width >> ml, 1u) != w || MAX(m.height >> ml, 1u) != h) return 0; + size_t n = (size_t)w * h * g->bpp; + id b = [g_dev newBufferWithLength:n * layers options:MTLResourceStorageModeShared]; res_add(b); + for (unsigned a = 0; a < layers; a++) enc_b_copy_texture_buffer(blit(), m, a, ml, MTLOriginMake(0, 0, 0), MTLSizeMake(w, h, 1), b, n * a, w * g->bpp, n); + finish(); mtl_sub_begin(); + int ok = !memcmp(b.contents, g->ref[gl], n * layers); + res_remove(b); return ok; +} +static id sampled(tex_t *t) { t_drop_ok++; id m = tex_mtl(t); t_drop_ok--; finish(); mtl_sub_begin(); return m; } +static id used(tex_t *t) { id m = tex_mtl(t); finish(); mtl_sub_begin(); return m; } + +static void dropped_case(const char *name, int target, int format, unsigned bpp, unsigned w, unsigned h, unsigned layers, unsigned levels, int direct, uint64_t serial) { + g_direct_upload_on = direct; + gtex g; gtex_new(&g, serial, target, format, bpp, w, h, layers, levels, 0); gtex_fill(&g, 1); + uint64_t n0 = g_drop_n, d0 = g_direct_uploads; + id m = sampled(&g.t); + char msg[160]; + snprintf(msg, sizeof msg, "%s: dropped, half size with one level fewer", name); + CHECK(msg, m && g_drop_n == n0 + 1 && m.width == w / 2 && m.height == h / 2 && m.mipmapLevelCount == levels - 1); + snprintf(msg, sizeof msg, "%s: the direct GPU deswizzle is not used for a dropped texture", name); + CHECK(msg, g_direct_uploads == d0); + int shift = 1; for (unsigned l = 0; m && l + 1 < levels; l++) shift &= level_is(m, l, &g, l + 1); + snprintf(msg, sizeof msg, "%s: Metal level k holds the guest's level k+1", name); + CHECK(msg, shift); + // A guest write: re-uploaded, still dropped, with the new data + gtex_fill(&g, 2); + id r = sampled(&g.t); + snprintf(msg, sizeof msg, "%s: a re-upload after a guest write stays dropped and shows the new data", name); + CHECK(msg, r && r.width == w / 2 && r.mipmapLevelCount == levels - 1 && level_is(r, 0, &g, 1)); + // A use other than sampling: made whole, every level, and it stays whole for sampling too + uint64_t f0 = g_drop_full_n; + id u = used(&g.t); + int whole = u && u.width == w && u.height == h && u.mipmapLevelCount == levels && g_drop_full_n == f0 + 1; + for (unsigned l = 0; whole && l < levels; l++) whole &= level_is(u, l, &g, l); + snprintf(msg, sizeof msg, "%s: a use other than sampling makes it whole with every level", name); + CHECK(msg, whole); + id s = sampled(&g.t); + snprintf(msg, sizeof msg, "%s: once made whole, it stays whole when sampled and after a guest write", name); + gtex_fill(&g, 3); id s2 = sampled(&g.t); + CHECK(msg, s && s.width == w && s.mipmapLevelCount == levels && s2 && s2.width == w && level_is(s2, 0, &g, 0)); +} +static void kept_case(const char *name, int target, int format, unsigned bpp, unsigned w, unsigned h, unsigned levels, int flags, uint64_t serial) { + gtex g; gtex_new(&g, serial, target, format, bpp, w, h, 1, levels, flags); gtex_fill(&g, 1); + uint64_t n0 = g_drop_n; + id m = sampled(&g.t); + char msg[160]; snprintf(msg, sizeof msg, "%s: not dropped", name); + CHECK(msg, m && g_drop_n == n0 && m.width == w && m.mipmapLevelCount == levels); +} +// The image flag does not keep a texture whole (Ocarina of Time gives it to its material textures): sampled it is dropped; put to any other use (an image slot goes through tex_mtl +// as this does) it is made whole, and keeps the write usage +static void image_case(uint64_t serial) { + gtex g; gtex_new(&g, serial, NVN_TEXTURE_TARGET_2D, NVN_FORMAT_RGBA8, 4, 512, 512, 1, 3, NVN_TEXTURE_FLAGS_IMAGE); gtex_fill(&g, 1); + uint64_t n0 = g_drop_n; id m = sampled(&g.t); + CHECK("an image-flagged texture is dropped when sampled", m && g_drop_n == n0 + 1 && m.width == 256 && m.mipmapLevelCount == 2 && level_is(m, 0, &g, 1)); + id u = used(&g.t); + CHECK("an image-flagged texture is made whole, with its write usage, for any other use", u && u.width == 512 && u.mipmapLevelCount == 3 && (u.usage & MTLTextureUsageShaderWrite) && level_is(u, 0, &g, 0)); +} +int main(void) { @autoreleasepool { + CHECK("the M1 iPad's and the iPhone 17's working set (5,461 MB) is in", drop_wants(5461ull << 20)); + CHECK("6 GB of working set or more, or none known, keeps every level", !drop_wants(6144ull << 20) && !drop_wants(12124ull << 20) && !drop_wants(0)); + // A sampled view's levels: from level 0 → from Metal level 0, one fewer; from level k > 0 → from Metal level k-1, the same count + { NSUInteger l0 = 0, nl = 4; drop_levels(&l0, &nl); CHECK("a view from level 0 starts at Metal level 0 with one level fewer", l0 == 0 && nl == 3); } + { NSUInteger l0 = 2, nl = 3; drop_levels(&l0, &nl); CHECK("a view from level 2 starts at Metal level 1 with as many levels", l0 == 1 && nl == 3); } + { NSUInteger l0 = 0, nl = 1; drop_levels(&l0, &nl); CHECK("a view of level 0 alone reads Metal level 0 (the guest's level 1)", l0 == 0 && nl == 1); } + mtl_init(); mtl_sub_begin(); + g_drop_on = 1; + dropped_case("RGBA8 2D 512x512, 4 levels, CPU path", NVN_TEXTURE_TARGET_2D, NVN_FORMAT_RGBA8, 4, 512, 512, 1, 4, 0, 991000); + dropped_case("RGBA8 2D 1024x512, 3 levels, GPU deswizzle", NVN_TEXTURE_TARGET_2D, NVN_FORMAT_RGBA8, 4, 1024, 512, 1, 3, 1, 991100); + dropped_case("RGBA16F 2D array 512x512x3, 3 levels, direct upload asked", NVN_TEXTURE_TARGET_2D_ARRAY, NVN_FORMAT_RGBA16F, 8, 512, 512, 3, 3, 1, 991200); + kept_case("RGBA8 2D 256x256, 4 levels (under the threshold)", NVN_TEXTURE_TARGET_2D, NVN_FORMAT_RGBA8, 4, 256, 256, 4, 0, 991300); + kept_case("RGBA8 2D 512x512, 1 level", NVN_TEXTURE_TARGET_2D, NVN_FORMAT_RGBA8, 4, 512, 512, 1, 0, 991400); + kept_case("RGBA8 2D 512x512, 3 levels, compressible (a render target)", NVN_TEXTURE_TARGET_2D, NVN_FORMAT_RGBA8, 4, 512, 512, 3, NVN_TEXTURE_FLAGS_COMPRESSIBLE, 991500); + image_case(991600); + g_drop_on = 0; + kept_case("RGBA8 2D 512x512, 4 levels, switch off", NVN_TEXTURE_TARGET_2D, NVN_FORMAT_RGBA8, 4, 512, 512, 4, 0, 991700); + printf("t_tex_drop_mip: %d checks, %d failed\n", checks, failed); + return failed != 0; +} } diff --git a/dm/gfx/tests/t_upload_slots.m b/dm/gfx/tests/t_upload_slots.m index 425038d777..cf1833020e 100644 --- a/dm/gfx/tests/t_upload_slots.m +++ b/dm/gfx/tests/t_upload_slots.m @@ -1,5 +1,6 @@ // Exercise staging reuse with several batches in flight. Distinct edge bytes // in every allocation detect aliasing within a batch and reuse before a read. +// The Makefile runs it with reuse forced on and off; the device rule (small working sets release staging) is checked directly. #include "../nvn/nvn_mtl.m" void *front_metal_layer(void) { return NULL; } module_t *module_of(const void *p) { (void)p; return NULL; } @@ -29,6 +30,8 @@ static void batch(unsigned batch, const size_t *sizes, unsigned count, id input = [g_dev newBufferWithLength:BYTES options:MTLResourceStorageModeShared]; id output = [g_dev newBufferWithLength:BYTES options:MTLResourceStorageModeShared]; res_add(input); res_add(output); diff --git a/dm/gfx/tests/t_upload_src.m b/dm/gfx/tests/t_upload_src.m index c4a36f721a..63297c6935 100644 --- a/dm/gfx/tests/t_upload_src.m +++ b/dm/gfx/tests/t_upload_src.m @@ -52,6 +52,7 @@ static void upload_all(upl *u, int n, uint64_t *made, unsigned *batches) { } int main(void) { @autoreleasepool { + setenv("DM_NVN_UPLOAD_SRC_MB", "0", 1); // no budget on an upload batch's reads (up_big_src): only staging splits the batches here; t_upload_budget tests the budget mtl_init(); CHECK("GPU deswizzle is available", g_nvn_deswz_gpu); uint8_t *mem = mmap(NULL, POOL_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); diff --git a/dm/gfx/tests/t_upscaler_mfx.m b/dm/gfx/tests/t_upscaler_mfx.m index f7875d36a3..3c8d0d6c53 100644 --- a/dm/gfx/tests/t_upscaler_mfx.m +++ b/dm/gfx/tests/t_upscaler_mfx.m @@ -2,7 +2,8 @@ // 1920x1080 image is replaced by the spatial scaler, which fills the whole image with the texture's colour; equal sizes, another shader, and DM_UPSCALER unset // (the last run) leave the dispatch to the shader. Runs under any profile: the named shader is the profile's first upscaler (DM_GAME_UPSCALER_KEYS), and a profile with // none swaps no shader; the MetalFX draw itself (up_mfx_encode) does not look at the key. The colour (up_mfx_color) comes from synthetic code holding the curves' constants: a variant with sRGB input -// comes out decoded to linear, and one whose output stays encoded is left to its shader +// comes out decoded to linear, and one whose output stays encoded is left to its shader. Ocarina of Time's variable-ratio variants (UP_COLOR_SQRT: signed squares in half precision, no curve) +// take their rectangles from other push-constant words (up_mfx_rect_vr) and their square-root-encoded input comes out squared #include "../nvn/nvn_mtl.m" void *front_metal_layer(void) { return NULL; } module_t *module_of(const void *p) { (void)p; return NULL; } @@ -49,6 +50,21 @@ static int color_of(const float *f32, int n32, const float *f16, int n16) { } return up_mfx_color(code, sizeof code); } +// The same with signed squares among them: HMUL2 R4, R2, |R2| (lo, hi: the halves selected, or'ed in), nsq of them, from byte 2048 +static int color_sq(const float *f32, int n32, int nsq, uint64_t lo_or, uint64_t hi_or) { + uint8_t code[4096]; size_t o = 0; + for (int i = 0; i < (int)sizeof code; i++) code[i] = (uint8_t)(i * 37 + 11); + for (int r = 0; r < 12; r++) for (int i = 0; i < n32; i++) { memcpy(code + o, &f32[i], 4); o += 16; } + for (int i = 0; i < nsq; i++) { + uint64_t lo = 0x232ull | 4ull << 16 | 2ull << 24 | 2ull << 32 | 1ull << 62 | lo_or, hi = hi_or; + memcpy(code + 2048 + 16 * i, &lo, 8); memcpy(code + 2048 + 16 * i + 8, &hi, 8); + } + return up_mfx_color(code, sizeof code); +} +static void push_vr(unsigned ox, unsigned oy, unsigned ow, unsigned oh, float su, float sv) { // a variable-ratio variant's c[24]: output origin (words 4, 5), size (24, 25), input scale (26, 27) + uint32_t *w = (uint32_t *)S.push[1]; memset(w, 0, 32 * 4); + w[4] = ox; w[5] = oy; w[24] = ow; w[25] = oh; memcpy(&w[26], &su, 4); memcpy(&w[27], &sv, 4); +} static NvShader *upscaler(const char *key) { NvShader *s = [NvShader new]; snprintf(s->key, sizeof s->key, "%s", key); s->up_color = UP_COLOR_LINEAR; s->rf.nb = 2; s->rf.b[0] = (nvn_rbind){.kind = NVN_RB_TEX, .dtt = MTLTextureType2D, .dpf = NVN_DPF_FLOAT, .reg = 0}; @@ -66,6 +82,23 @@ int main(void) { @autoreleasepool { CHECK(color_of(dec, 2, NULL, 0) == UP_COLOR_KEEP, "a shape no pack has shown (a decode in floats, no encode): the shader runs"); CHECK(color_of(NULL, 0, (const float[4]){0.040435791015625f, 2.3984375f, 0.07745361328125f, enc16[0]}, 4) == UP_COLOR_KEEP, "a half float encode must not read as encoded input: the shader runs"); CHECK(up_mfx_color(rare, sizeof rare) == UP_COLOR_KEEP, "a constant used once is chance, not a curve"); + CHECK(color_sq(NULL, 0, 12, 0, 0) == UP_COLOR_SQRT, "signed squares and no curve: square-root-encoded input, linear output (Ocarina of Time's agl_ndsr_vr_light)"); + CHECK(color_sq(NULL, 0, 12, 2ull << 60, 2ull << 10) == UP_COLOR_SQRT, "signed squares of the high halves count too"); + CHECK(color_sq(enc, 2, 12, 0, 0) == UP_COLOR_KEEP, "signed squares, then an sRGB encode: the output stays encoded, the shader runs"); + CHECK(color_sq(NULL, 0, 7, 0, 0) == UP_COLOR_KEEP, "fewer than 8 signed squares are chance"); + CHECK(color_sq(NULL, 0, 12, 1ull << 63, 0) == UP_COLOR_KEEP, "x * -|x| is not the decode"); + CHECK(color_sq(NULL, 0, 12, 0, 2ull << 10) == UP_COLOR_KEEP, "a low half times a high half is not a square"); + CHECK(color_sq(NULL, 0, 12, 1ull << 32, 0) == UP_COLOR_KEEP, "two registers multiplied are not a square"); + { // the rectangles of a variable-ratio variant: 640x360 of a 976x548 texture from its origin → 1280x720 at 13, 9 of a 1920x1080 image + NVNcopyRegion ir = {0}, orr = {0}; uint32_t w[32] = {0}; float su = 640.0f / (976 * 1280), sv = 360.0f / (548 * 720); + w[4] = 13; w[5] = 9; w[24] = 1280; w[25] = 720; memcpy(&w[26], &su, 4); memcpy(&w[27], &sv, 4); + CHECK(up_mfx_rect_vr(w, 976, 548, 1920, 1080, &ir, &orr) && !ir.xoffset && !ir.yoffset && ir.width == 640 && ir.height == 360 && orr.xoffset == 13 && orr.yoffset == 9 && + orr.width == 1280 && orr.height == 720, "a variable-ratio variant's rectangles: the input from the texture's origin, the output at its origin"); + w[24] = 1920; CHECK(!up_mfx_rect_vr(w, 976, 548, 1920, 1080, &ir, &orr), "an output past the image refuses"); w[24] = 1280; + su = 640.5f / (976 * 1280); memcpy(&w[26], &su, 4); CHECK(!up_mfx_rect_vr(w, 976, 548, 1920, 1080, &ir, &orr), "an input that is not whole texels refuses"); + su = 1000.0f / (976 * 1280); memcpy(&w[26], &su, 4); CHECK(!up_mfx_rect_vr(w, 976, 548, 1920, 1080, &ir, &orr), "an input wider than its texture refuses"); + w[25] = 0; CHECK(!up_mfx_rect_vr(w, 976, 548, 1920, 1080, &ir, &orr), "an empty output refuses"); + } const char *up = getenv("DM_UPSCALER"); int on = up && !strcmp(up, "metalfx"); tex_t in = texture(77, 960, 540, NVN_FORMAT_RGBA16F), out = texture(78, 1920, 1080, NVN_FORMAT_RGBA16F), same = texture(79, 960, 540, NVN_FORMAT_RGBA16F); out.d.flags |= NVN_TEXTURE_FLAGS_IMAGE; same.d.flags |= NVN_TEXTURE_FLAGS_IMAGE; @@ -129,6 +162,24 @@ int main(void) { @autoreleasepool { CHECK(up_mfx_encode(named), "linear input after sRGB at the same sizes"); CHECK(mtl_wait(mtl_sub_commit(), 5000000000ull) && !mtl_last_commit_error(), "the second linear submission completes"); CHECK(matches(written, colour, MTLRegionMake2D(0, 0, 1920, 1080), black), "the same sizes in linear colour are not decoded: each colour has its own scaler"); + // Square-root-encoded input, linear output (Ocarina of Time): the whole texture into the whole image, straight out, then a packed subrectangle with a highlight + // into an offset rectangle, both squared + named->up_color = UP_COLOR_SQRT; + const float squared[4] = {0.25f, 0.0625f, 0.5625f, 1.0f}, hdr_sq[4] = {2.25f, 0.25f, 0.0625f, 1.0f}; + fill(tex_mtl(&in), MTLClearColorMake(colour[0], colour[1], colour[2], colour[3])); fill(written, MTLClearColorMake(0, 0, 0, 1)); + push_vr(0, 0, 1920, 1080, 1.0f / 1920, 1.0f / 1080); S.tex[5][0] = 701; S.img[5][1] = 702; mtl_sub_begin(); + CHECK(up_mfx_encode(named), "MetalFX takes square-root-encoded input"); + CHECK(mtl_wait(mtl_sub_commit(), 5000000000ull) && !mtl_last_commit_error(), "the square-root submission completes"); + CHECK(matches(written, squared, MTLRegionMake2D(0, 0, 1920, 1080), black), "the square-root-encoded input comes out squared"); + fill(tex_mtl(&packed), MTLClearColorMake(1.5, 0.5, 0.25, 1)); fill(written, MTLClearColorMake(0, 0, 0, 1)); + push_vr(13, 9, 1280, 720, 640.0f / (976 * 1280), 360.0f / (548 * 720)); S.tex[5][0] = 704; mtl_sub_begin(); + CHECK(up_mfx_encode(named), "MetalFX takes a packed square-root-encoded subrectangle"); + CHECK(mtl_wait(mtl_sub_commit(), 5000000000ull) && !mtl_last_commit_error(), "the packed square-root submission completes"); + CHECK(matches(written, hdr_sq, MTLRegionMake2D(13, 9, 1280, 720), black), "the packed input comes out squared, above 1.0 too, in its destination rectangle only"); + push_vr(13, 9, 1280, 720, 640.5f / (976 * 1280), 360.0f / (548 * 720)); mtl_sub_begin(); { uint64_t k0 = g_up_mfx_kept; + CHECK(!up_mfx_encode(named) && g_up_mfx_kept == k0 + 1, "an input that is not whole texels leaves the dispatch to the shader"); } + mtl_wait(mtl_sub_commit(), 5000000000ull); + named->up_color = UP_COLOR_LINEAR; NvShader *encoded_out = upscaler(key); encoded_out->up_color = UP_COLOR_KEEP; CHECK(!up_mfx_wanted(encoded_out), "a named shader whose output stays encoded is left to its shader"); S.tex[5][0] = 701; diff --git a/dm/gfx/tests/t_wait_event.m b/dm/gfx/tests/t_wait_event.m index c620a49970..2d321e5999 100644 --- a/dm/gfx/tests/t_wait_event.m +++ b/dm/gfx/tests/t_wait_event.m @@ -1,10 +1,12 @@ // Contract fixture: real public NVN lookup -> recording -> QueueSubmit -> Metal replay. // An event wait gates GPU work, but never blocks CPU submission or another NVN queue. #define nvn_game_fps nvn_game_fps_mtl_default +#define nvn_fstep_fine nvn_fstep_fine_mtl_default #define nvn_event_publish_gpu event_test_publish #include "../nvn/nvn_mtl.m" #undef nvn_event_publish_gpu #undef nvn_game_fps +#undef nvn_fstep_fine #define g_ft g_ft_hle #include "../nvn/hle_nvn.c" #undef g_ft diff --git a/dm/gfx/tests/t_window_alias.m b/dm/gfx/tests/t_window_alias.m new file mode 100644 index 0000000000..39dd558275 --- /dev/null +++ b/dm/gfx/tests/t_window_alias.m @@ -0,0 +1,104 @@ +// Textures in GPU-only memory share bytes as on NVN: descriptions of other sizes and formats over overlapping storage of a CPU_NO_ACCESS pool are placed in one placement heap per +// 32 MB span of guest addresses, each at its own address's offset scaled by 9/8 (window_texture). Ocarina of Time: 400 Metal textures of 793 MB stood for 89 MB of NVN storage +// (docs/reference/memory.md). A span gets its heap only once the textures made apart over it pass the heap's size. The spans are on by themselves only where Metal's working set +// is under 8 GB (window_wants); the check target turns them on with DM_NVN_WINDOW_ALIAS=1. Run with DM_NVN_WINDOW_ALIAS=0 it shows the old behaviour, every description an +// allocation of its own, and fails +#include "../nvn/nvn_mtl.m" +void *front_metal_layer(void) { return NULL; } +module_t *module_of(const void *p) { (void)p; return NULL; } +module_t *g_mod; int g_nmod; +void svc_thread_dump(void) {} +uint64_t now_ns(void) { return bp_now(); } +static int checks, failed; +#define CHECK(c, label) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s (line %d)\n", label, __LINE__); } } while (0) + +static tex_t target(pool_t *pool, uint64_t serial, uint64_t off, unsigned w, unsigned h, int format) { + tex_t t = {.magic=MAGIC('T','E','X',0), .serial=serial, .pool=pool, .mem=pool->mem+off, .off=(int64_t)off}; + t.d = (nvn_texdesc){.target=NVN_TEXTURE_TARGET_2D, .format=format, .flags=NVN_TEXTURE_FLAGS_COMPRESSIBLE, .width=w, .height=h, .depth=1, .levels=1, .samples=1}; + nvn_tex_layout(&t.d, &t.L); return t; +} +static id read_image(id t) { + NSUInteger row=t.width*4, bytes=row*t.height; + id b=[g_dev newBufferWithLength:bytes options:MTLResourceStorageModeShared]; res_add(b); + enc_b_copy_texture_buffer(blit(), t, 0, 0, MTLOriginMake(0,0,0), MTLSizeMake(t.width,t.height,1), b, 0, row, bytes); + mtl_sub_commit(); mtl_drain(); CHECK(!mtl_last_commit_error(), "image read completes without GPU error"); + res_remove(b); mtl_sub_begin(); return b; +} +static void fill(id t, uint32_t seed) { + NSUInteger bytes=t.width*t.height*4; + id b=[g_dev newBufferWithLength:bytes options:MTLResourceStorageModeShared]; + uint32_t *p=b.contents; for (NSUInteger i=0;i t, uint32_t seed) { + id b=read_image(t); uint32_t *p=b.contents; int ok=1; + for (NSUInteger i=0;i t) { id b=read_image(t); uint32_t *p=b.contents; int ok=1; for (NSUInteger i=0;i weak_heap; + if (posix_memalign(&mem, WIN_SIZE, 2*WIN_SIZE) || posix_memalign(&cmem, 16384, 16<<20)) abort(); + memset(mem, 0, 2*WIN_SIZE); memset(cmem, 0, 16<<20); + @autoreleasepool { + mtl_sub_begin(); + pool_t gpu={.magic=MAGIC('P','O','O','L'), .flags=NVN_MEMORY_POOL_FLAGS_CPU_NO_ACCESS|NVN_MEMORY_POOL_FLAGS_GPU_CACHED|NVN_MEMORY_POOL_FLAGS_COMPRESSIBLE, .mem=mem, .size=2*WIN_SIZE}; + pool_t cpu={.magic=MAGIC('P','O','O','L'), .flags=NVN_MEMORY_POOL_FLAGS_CPU_CACHED|NVN_MEMORY_POOL_FLAGS_GPU_CACHED|NVN_MEMORY_POOL_FLAGS_COMPRESSIBLE, .mem=cmem, .size=16<<20}; + // 48 descriptions over the first 8 MB of the window, of other sizes and formats, as a game's passes and its dynamic resolution make them + enum { N=48 }; tex_t a[N]; id m[N]; + uint64_t before=g_dev.currentAllocatedSize; + for (int i=0;i>20), (unsigned long long)(delta>>20)); + CHECK(!m[0].heap, "the first texture of a span keeps its own allocation: a heap would not save memory yet"); + int first=-1; for (int i=0;iwindow) first=i; } // before it, same-offset families may share heaps of their own (image_texture) + int one=first>0; for (int i=first>0?first:N;i0; for (int i=first>0?first:N;i0; for (int i=first>0?first:N;i0 && [g_res_objects containsObject:m[first].heap] && ![g_res_objects containsObject:m[N-1]], "the heap is resident, its textures through it"); + // Bytes are shared as on NVN: a texture over storage another wrote reads it; storage that does not overlap is untouched + tex_t x=target(&gpu, 971000, 16u<<20, 256, 256, NVN_FORMAT_RGBA8), y=target(&gpu, 971001, 16u<<20, 256, 256, NVN_FORMAT_RGBA8UI), z=target(&gpu, 971002, 20u<<20, 256, 256, NVN_FORMAT_RGBA8); + mtl_tex_init(&x); mtl_tex_init(&z); id tx=tex_mtl(&x), tz=tex_mtl(&z); + CHECK(tx.heap && tx.heap==m[N-1].heap && tz.heap==tx.heap, "later textures of the span join its heap"); + CHECK(zero(tx) && zero(tz), "storage no texture covered before starts as zeros"); + fill(tx, 0x5a5a1234); fill(tz, 0x0f0f9876); + mtl_tex_init(&y); id ty=tex_mtl(&y); + CHECK(ty.heap==tx.heap && ty.heapOffset==tx.heapOffset && ty!=tx, "another format over the same storage is another texture over the same bytes"); + CHECK(holds(ty, 0x5a5a1234), "a description made over written storage inherits its bytes (no zero fill over a live alias)"); + CHECK(holds(tz, 0x0f0f9876) && holds(tx, 0x5a5a1234), "storage that does not overlap keeps its own bytes"); + // The second span has no heap for one texture; CPU-visible pools, linear textures and textures past their span's end keep allocations of their own + tex_t w=target(&gpu, 971010, WIN_SIZE+(1u<<20), 512, 512, NVN_FORMAT_RGBA8); mtl_tex_init(&w); + CHECK(!tex_mtl(&w).heap, "a lone texture in another span keeps its own allocation (no heap is made for it)"); + tex_t c=target(&cpu, 971020, 0, 512, 512, NVN_FORMAT_RGBA8); mtl_tex_init(&c); + CHECK(!tex_mtl(&c).heap, "a CPU-visible pool's texture keeps its own allocation"); + tex_t l=target(&gpu, 971030, 24u<<20, 128, 64, NVN_FORMAT_RGBA8); l.d.flags|=NVN_TEXTURE_FLAGS_LINEAR; nvn_tex_layout(&l.d, &l.L); mtl_tex_init(&l); + CHECK(!tex_mtl(&l).heap || tex_mtl(&l).heap!=tx.heap, "a linear texture stays out of the span's heap"); + // One across a span's end goes to the spans offset by half a span, made once they save memory too: two overlapping descriptions there share the second span's heap + tex_t e=target(&gpu, 971040, WIN_SIZE-(64u<<10), 1024, 1024, NVN_FORMAT_RGBA8), e2=target(&gpu, 971041, WIN_SIZE-(64u<<10), 1000, 1000, NVN_FORMAT_R32F); mtl_tex_init(&e); mtl_tex_init(&e2); + id te=tex_mtl(&e), te2=tex_mtl(&e2); + CHECK(te.heap!=tx.heap && te2.heap && te2.heap!=tx.heap, "a texture across a span's end does not go to that span's heap"); + CHECK(te2.heap && (te.heap==te2.heap || !te.heap), "overlapping textures across the span's end share the offset span's heap"); + te=te2=nil; + // The heap lives while one of its textures does + weak_heap=tx.heap; + for (int i=0;i 0 && h > 0) g_picture_aspect = (double)w / h; } +// The game view's width / height (front.h front_view_aspect; 0 before the window), and the shape changes handed to the host once a resize has settled (dm_screen_view_changed): +// a live resize steps through many sizes, and each new shape makes a profile with screen_aspect any lay its picture out again +static _Atomic double g_view_aspect; static uint64_t g_view_change; // g_view_change: main thread +double front_view_aspect(void) { return g_view_aspect; } +static void view_shape(NSSize px) { + double a = px.width / px.height; if (a == g_view_aspect) return; + g_view_aspect = a; uint64_t n = ++g_view_change; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 300 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ if (n == g_view_change) dm_screen_view_changed(a); }); +} @interface DmGameView : NSView @end @implementation DmGameView - (void)mouseDown:(NSEvent *)e { [self mouseDragged:e]; } @@ -641,6 +650,7 @@ - (void)fitDrawable { l.contentsScale = self.window.backingScaleFactor; NSSize px = [self convertSizeToBacking:self.bounds.size]; if (px.width < 1 || px.height < 1 || CGSizeEqualToSize(l.drawableSize, px)) return; l.drawableSize = px; LOG("front end: drawable %.0fx%.0f", px.width, px.height); + view_shape(px); } - (void)setFrameSize:(NSSize)s { [super setFrameSize:s]; [self fitDrawable]; } - (void)viewDidChangeBackingProperties { [super viewDidChangeBackingProperties]; [self fitDrawable]; } diff --git a/dm/host/hle_codec_video.c b/dm/host/hle_codec_video.c index 47120c47e7..bf69cec7dd 100644 --- a/dm/host/hle_codec_video.c +++ b/dm/host/hle_codec_video.c @@ -60,6 +60,7 @@ typedef struct { uint32_t epoch; // counts Stop / Flush: the pictures of a packet taken before one are dropped struct { uint8_t *data; uint64_t size; int64_t ts; uint8_t eos; } q[CV_HOLD]; uint32_t qhead, qcount; // the packets taken and not yet decoded, in order (copies) cv_times st, all; // decode times of the current run of CV_STAT packets and of the runs before it + int64_t clk_ts, fill_ts; uint64_t clk_ns, fill_ns, dropped; // the movie clock (cv_due): a picture's time and the host time it went into a buffer; the last picture put in and when } cv_dec; static cv_dec *g_cv[16]; @@ -112,13 +113,41 @@ static void pool_native_write(cv_pool *p, uint32_t i, const vpx_image_t *im) { free(tmp); } static int cv_pending(const cv_dec *d) { return d->nheld + (int)d->qcount + d->busy; } // what the decoder holds for the client: packets not yet decoded and pictures no released buffer has taken (decoder lock held) +// The movie's clock for a player that takes one picture per game frame. Ocarina of Time's title player reads one picture each frame and never skips: on the console the title runs +// at 60, its movies' rate, but under the host's frame step it runs at 20-30 fps and the 60 fps movie played at a half to a third of its speed. The cause is the game's player, so +// the decoder answers for it: when a released buffer takes a picture, the held pictures behind the movie's clock are dropped and the one nearest it goes in, as a console that +// keeps the movie's rate would have shown it. The clock is the time of a picture put in plus the host time since; it starts again (no catch-up) at the first picture, after +// 200 ms with none put in (the player paused) and when the stream's time goes back (a new stream or a loop). A player that keeps up never loses a picture: the next one is +// always due one picture later. Times are the client's own unit: only a stream whose pictures step by 4-100 ms read as nanoseconds (OoT's WebM times, milliseconds in ns) is +// clocked; any other unit is left as it was. Called with the decoder locked; returns the pictures dropped +#define CV_CLK_GAP 200000000ull +static int cv_due(cv_dec *d) { + uint64_t now = now_ns(); int n = 0; + if (!d->clk_ns || now - d->fill_ns > CV_CLK_GAP || d->held_ts[0] < d->fill_ts) { d->clk_ts = d->held_ts[0]; d->clk_ns = now; } + else { + int64_t due = d->clk_ts + (int64_t)(now - d->clk_ns); + while (d->nheld > 1 && !d->held_eos[0] && d->held_ts[1] > d->held_ts[0] && d->held_ts[1] - d->held_ts[0] >= 4000000 && d->held_ts[1] - d->held_ts[0] <= 100000000 && + d->held_ts[1] <= due + (d->held_ts[1] - d->held_ts[0]) / 2) { // the picture nearest the clock: "the last one not after it" flips between one and three pictures on rounded times + vpx_img_free(d->held[0]); + memmove(d->held, d->held + 1, sizeof d->held[0] * (CV_HOLD - 1)); memmove(d->held_ts, d->held_ts + 1, sizeof d->held_ts[0] * (CV_HOLD - 1)); + memmove(d->held_eos, d->held_eos + 1, CV_HOLD - 1); d->nheld--; n++; + } + } + d->fill_ts = d->held_ts[0]; d->fill_ns = now; + if (n && !d->dropped) LOG("[codec] %s decoder %u: the player reads slower than the movie's rate: pictures behind the movie's clock are dropped", k_cv_name[d->codec], d->id); + d->dropped += n; + if (n && d->dropped % 600 < (uint64_t)n) LOG("[codec] %s decoder %u: %llu pictures dropped to the movie's clock, %llu put in", k_cv_name[d->codec], d->id, (unsigned long long)d->dropped, (unsigned long long)d->pictures); + return n; +} // Pictures and end of stream into the released buffers, in order (decoder lock held). decoded: the decoder's thread calls, with the pictures of the packet it has just decoded: -// a buffer they go into was waiting for them -static void fill(cv_dec *d, int decoded) { - int had = d->nheld; +// a buffer they go into was waiting for them. Returns the pictures dropped to the movie's clock (cv_due): they make room for a packet as one taken does, so a client that sends +// one packet per signal gets the signal (ready's took) +static int fill(cv_dec *d, int decoded) { + int had = d->nheld, dropped = 0; while (d->pcount && (d->nheld || d->eos_pending)) { uint32_t i = d->pend[d->phead]; d->phead = (d->phead + 1) % CV_BUFS; d->pcount--; typeof(d->buf[0]) *b = &d->buf[i]; + if (d->nheld) dropped += cv_due(d); if (d->nheld) { vpx_image_t *im = d->held[0]; int64_t ts = d->held_ts[0]; uint8_t eos = d->held_eos[0]; memmove(d->held, d->held + 1, sizeof d->held[0] * (CV_HOLD - 1)); memmove(d->held_ts, d->held_ts + 1, sizeof d->held_ts[0] * (CV_HOLD - 1)); @@ -133,6 +162,7 @@ static void fill(cv_dec *d, int decoded) { spt_fire(d, i); } if (had >= CV_HOLD && d->nheld < CV_HOLD) pthread_cond_signal(&d->work); // the decoder's thread waited for room for its next packet's pictures + return dropped; } // The event says a packet can come: it rises when one was taken (took) or room came back (before: cv_pending before the change), not at every release (decoder lock held). // Mario Tennis Fever's player counts each signal as one packet it may send: raised at every release, its count grew while a seek held back the samples (a skipped cutscene), @@ -355,7 +385,7 @@ static Result cv_dec_reset(void *t) { for (uint32_t k = 0; k < d->qcount; k++) free(d->q[(d->qhead + k) % CV_HOLD].data); d->qhead = d->qcount = 0; for (int i = 0; i < d->nheld; i++) vpx_img_free(d->held[i]); - d->nheld = 0; d->eos_pending = 0; + d->nheld = 0; d->eos_pending = 0; d->clk_ns = 0; // the movie clock starts again at the next picture (cv_due) d->epoch++; d->reopen = 1; cv_stat_sum(d); pthread_cond_signal(&d->work); // it may have waited for room @@ -393,7 +423,7 @@ static vpx_image_t *av1_to_i420(const mav1_picture *p) { // the decoder's NV12 return c; } // A packet's pictures on their way from the codec to the pictures waiting (held). The packet's last one is kept back until the packet ends, as it carries an end of stream -typedef struct { cv_dec *d; uint32_t epoch; vpx_image_t *last; int64_t last_ts; int stop; uint64_t waited; } cv_out; // stop: a Stop / Flush or Finalize came; waited: time spent waiting for room +typedef struct { cv_dec *d; uint32_t epoch; vpx_image_t *last; int64_t last_ts; int stop; uint64_t waited; int dropped; } cv_out; // stop: a Stop / Flush or Finalize came; waited: time spent waiting for room; dropped: pictures dropped to the movie's clock (fill) // Room for one more waiting picture (decoder lock held, on the decoder's thread): a release makes some (fill). 0 when a Stop / Flush or Finalize came instead static int cv_room(cv_dec *d, cv_out *o) { if (d->nheld >= CV_HOLD && !d->quit && o->epoch == d->epoch) { @@ -413,7 +443,7 @@ static void cv_put(cv_out *o, vpx_image_t *c, int64_t ts) { if (o->last) { cv_dec *d = o->d; pthread_mutex_lock(&d->mu); - if (cv_room(d, o)) { cv_hold(d, o->last, o->last_ts, 0); fill(d, 1); } else { vpx_img_free(o->last); o->stop = 1; } + if (cv_room(d, o)) { cv_hold(d, o->last, o->last_ts, 0); o->dropped += fill(d, 1); } else { vpx_img_free(o->last); o->stop = 1; } pthread_mutex_unlock(&d->mu); } o->last = c; o->last_ts = ts; @@ -471,9 +501,9 @@ static void *cv_worker(void *arg) { if (d->quit || o.epoch != d->epoch) { if (o.last) vpx_img_free(o.last); if (d->quit) break; } // Finalize, or a Stop / Flush since the packet was taken: its pictures are dropped else { if (o.last) cv_hold(d, o.last, o.last_ts, p.eos); else if (p.eos) d->eos_pending = 1; - fill(d, 1); + o.dropped += fill(d, 1); } - ready(d, before, 0); + ready(d, before, o.dropped); cv_stat(d, dt); } pthread_mutex_unlock(&d->mu); @@ -483,8 +513,12 @@ static void *cv_worker(void *arg) { // A refusal (CV_BUSY, nn::codec 3603) is the decoder's defined answer, not a fault: NintendoSDK_movie's detail::SubmitDecoderInputBuffer turns exactly that result into its // own retry code 0x7a, which VideoDecoder::DecodeAsync hands back to the player, and aborts on any other failure (Ocarina of Time's subsdk0 +0x10fd20, +0x103840). So it is // logged plainly +// DM_MOVIE_TRACE (as hle_movie.c): each packet the client submits and each picture's properties it reads, with the picture's time and the host clock, to tell a player that follows its +// movie's clock from one that takes a picture per game frame +static int cv_trace(void) { static int on = -1; if (on < 0) on = getenv("DM_MOVIE_TRACE") != NULL; return on; } static Result cv_dec_submit(uint64_t *out, void *t, const void *data, uint64_t size, int64_t ts, bool eos) { cv_dec *d = cv_of(t); if (!d) return CV_R(2004); + if (cv_trace()) LOG("[codec] %s submit time %lld size %llu%s at %.3f ms", k_cv_name[d->codec], (long long)ts, (unsigned long long)size, eos ? " eos" : "", now_ns() / 1e6); dm_host_mutex_lock(&d->mu); uint8_t *copy = NULL; if (cv_pending(d) >= CV_HOLD || (size && !(copy = malloc((size_t)size)))) { @@ -517,7 +551,7 @@ static void cv_dec_rel(void *t, uint32_t i, cv_sync sync) { if (d->pcount < CV_BUFS) { d->pend[(d->phead + d->pcount) % CV_BUFS] = i; d->pcount++; } if (d->fcount < 8) { d->fifo[(d->fhead + d->fcount) % 8] = i; d->fcount++; } else LOG("[RED] nn::codec: acquirable queue full at release %u", i); int before = cv_pending(d); - fill(d, 0); ready(d, before, 0); + int dropped = fill(d, 0); ready(d, before, dropped); pthread_mutex_unlock(&d->mu); } static Result cv_dec_props(uint16_t *w, uint16_t *h, uint16_t *cw, uint16_t *ch, int64_t *ts, bool *eos, void *t, uint32_t i) { @@ -526,6 +560,7 @@ static Result cv_dec_props(uint16_t *w, uint16_t *h, uint16_t *cw, uint16_t *ch, int ok = d->buf[i].filled; if (ok) { *w = *cw = d->buf[i].w; *h = *ch = d->buf[i].h; *ts = d->buf[i].ts; *eos = d->buf[i].eos != 0; } pthread_mutex_unlock(&d->mu); + if (ok && cv_trace()) LOG("[codec] %s picture index %u time %lld read at %.3f ms", k_cv_name[d->codec], i, (long long)*ts, now_ns() / 1e6); return ok ? 0 : CV_NONE; } static Result cv_dec_encrypted(void) { static int once; if (!once++) LOG("[RED] nn::codec: an encrypted input buffer: protected streams are not served"); return CV_R(2004); } diff --git a/dm/host/hle_hid.c b/dm/host/hle_hid.c index 764015e113..ab6ff8fe70 100644 --- a/dm/host/hle_hid.c +++ b/dm/host/hle_hid.c @@ -250,6 +250,7 @@ static void *ctl_main(void *arg) { if (!strcmp(line, "restop")) { void dm_gfx_restop(void); dm_gfx_restop(); continue; } // what the residency set holds (nvn_mtl.m res_top) if (!strncmp(line, "addr ", 5)) { void dm_gfx_addr_note(uint64_t a, char *note, size_t n); char note[600]; uint64_t a = strtoull(line + 5, NULL, 16); // what the host knows of a guest address dm_gfx_addr_note(a, note, sizeof note); LOG("DM_CTL: addr %#llx:%s", (unsigned long long)a, note[0] ? note : " nothing known"); continue; } + if (!strcmp(line, "memtrim")) { void dm_gfx_memtrim(void); dm_gfx_memtrim(); continue; } // a memory pressure trim at the next submission, as a warn asks on iOS (nvn_mtl.m mem_trim) if (!strncmp(line, "texraw ", 7)) { void dm_gfx_texraw(uint64_t serial, const char *path); char *e2; uint64_t s = strtoull(line + 7, &e2, 10); while (*e2 == ' ') e2++; dm_gfx_texraw(s, e2); continue; } if (!strncmp(line, "bufsnap ", 8)) { // bufsnap : guest memory as the GPU left it right after that shader's next dispatch (nvn_mtl.m dm_gfx_bufsnap) void dm_gfx_bufsnap(const char *key, uint64_t a, size_t n, const char *path); char key[32] = {0}, path[512] = {0}; unsigned long long a = 0, n = 0; diff --git a/dm/host/hle_oe.c b/dm/host/hle_oe.c index b5264cf26a..d4a57ad1bf 100644 --- a/dm/host/hle_oe.c +++ b/dm/host/hle_oe.c @@ -64,6 +64,13 @@ void dm_set_opmode(int m) { // called by the front end (overheat downgrade etc if (g_ntf_opmode) mq_push(MSG_OPMODE); if (g_ntf_perfmode) mq_push(MSG_PERFMODE); } +// The picture's shape changed (loader.c, a profile with screen_aspect any following its window): the notifications a console sends when the display changes, docked to handheld, +// with the mode unchanged, so the game queries its display again and lays its picture out for the new shape as it does for a mode change (Ocarina of Time resizes its targets then) +void dm_display_changed(void) { + LOG("oe: display changed (picture shape): operation mode notification%s", g_ntf_opmode ? "" : " not enabled by the game"); + if (g_ntf_opmode) mq_push(MSG_OPMODE); + if (g_ntf_perfmode) mq_push(MSG_PERFMODE); +} // FocusState: 1 InFocus, 2 OutOfFocus, 3 Background. The front end calls dm_focus_set (iOS lifecycle / Mac window losing focus) static _Atomic int g_focus = 1; static _Atomic uint64_t g_focus_in_ns; // the front end's state; time of its most recent entry into InFocus // Focus handling mode the game set (-1: none). The SDK's oe::SetFocusHandlingMode (SDK 18 sdk+0x3c5770) turns it into am's SetFocusHandlingMode(notify, ?, suspend) and diff --git a/dm/host/hle_thread.c b/dm/host/hle_thread.c index f67b76581e..0684a0a46d 100644 --- a/dm/host/hle_thread.c +++ b/dm/host/hle_thread.c @@ -74,13 +74,14 @@ typedef struct thr { int closed, sync_refs; // Reclaim only after handle close, thread exit and the final synchronization wait reference uint64_t nsvc; // SVC count (for the state dump) uint64_t nyield, nyield_seen, nbackoff, nbackoff_seen; // Yields (SleepThread 0/-1/-2) and those the back-off turned into short sleeps, with both counts at the last power report (dm_yield_top) - uint64_t nclkyield, nclkyield_seen; // Yields of clock waits (thr_yield), and their count at the last power report + uint64_t nclkyield, nclkyield_seen, nclkyield_rep; // Yields of clock waits (thr_yield), and their count at the last power report uint64_t nspin, nspin_seen, spin_site; const char *spin_mod; // Spin wait passes (dm_spin_wait; those that yield count in nyield too) and where the last one was uint64_t srun_svc, srun_t0, spin_ret; // Current spin wait: nsvc at its passes, when it began, when the last pass returned uint64_t cpu_seen_us; // CPU time (µs) at the last power report (dm_thread_cpu) uint64_t yrun_svc, yrun_t0, yrun_sig, yrun_sig2, poll_ret; // Current run of yields: nsvc of the last yield, when the run began, and the caller's x19–x28 at the last two yields (a run lasts while no other SVC comes between two yields and those registers match one of the last two, thr_yield); when the last yield or short timed-out wait returned (poll_wait_begin) uint64_t yrun_clk; // dm_clock_reads at the last yield: a pass that read the clock since makes the yield a clock wait (thr_yield) uint64_t cw_sig, cw_run, cw_last, cw_end, cw_per, cw_per2, cw_wake, ncwpred, ncwpred_seen; // The clock wait followed (clock_wait): its x19–x28, the run it was last seen in, when its last yield returned, + uint64_t ncwfirst, cw_late_sum, cw_late_max, ncwfirst_seen, ncwpred_rep, cw_late_seen; // predicted sleeps whose wait had ended at the first poll after them, how late those sleeps woke (sum, max), at the last report (dm_clock_top) int cw_ok, cw_pred, cw_after, cw_trip; // when its last wait ended, the last two periods between ends, when the predicted sleep ended, predicted sleeps (and at the last power report); periods in a row that matched, a predicted sleep in this run, yields after it, waits in a row that ended at the first poll after it mach_port_t mport; // Host thread port (to get CPU time) _Atomic int qos_pending; // SetThreadPriority from another thread changed prio: the thread applies the new class at its next SVC (only a thread can set its own QoS) @@ -862,6 +863,7 @@ static void clock_wait(thr_t *me, uint64_t sig, uint64_t now, int predict) { if (me->cw_sig && now - me->cw_last < 1000000000ull) { yield_for(me, now - me->yrun_t0, 1); return; } // another clock wait: the followed loop is still in use me->cw_sig = sig; me->cw_end = me->cw_per = me->cw_per2 = 0; me->cw_ok = me->cw_pred = me->cw_trip = 0; } else { + if (me->cw_pred && !me->cw_after) me->ncwfirst++; if (me->cw_pred && !me->cw_after) { // the last wait ended at the first poll after its predicted sleep: maybe late // once: the period learned from waits the back-off ended carries their lateness (up to 250 µs, and nanosleep's quarter): predict it shorter; // twice in a row: the period changed, learn it again @@ -880,7 +882,9 @@ static void clock_wait(thr_t *me, uint64_t sig, uint64_t now, int predict) { uint64_t per = me->cw_per2 && me->cw_per2 < me->cw_per ? me->cw_per2 : me->cw_per, dl = me->cw_end + per; // the shorter of the last two periods if (dl > now + 2 * CW_MARGIN) { me->nbackoff++; me->ncwpred++; me->sleeping = 1; sleep_precise(dl - CW_MARGIN); me->sleeping = 0; - me->cw_pred = 1; me->cw_wake = now_ns(); return; + me->cw_pred = 1; me->cw_wake = now_ns(); + { uint64_t late = me->cw_wake > dl - CW_MARGIN ? me->cw_wake - (dl - CW_MARGIN) : 0; me->cw_late_sum += late; if (late > me->cw_late_max) me->cw_late_max = late; } + return; } } } else if (me->cw_pred) { // polling after the predicted sleep @@ -974,6 +978,21 @@ void dm_yield_top(char *out, size_t n) { pthread_mutex_unlock(&G); if (!o && n) snprintf(out, n, "none"); } +// The threads that made most clock waits since the last call (the power line every 300 frames, hle_nvn.c), at most two: "handle name: N yields, M predicted sleeps (ended at the first +// poll after it K; the sleeps woke late by mean / max µs), period P ms". A wait that had ended by the first poll after its predicted sleep was slept through: it ended before the sleep did +void dm_clock_top(char *out, size_t n) { + thr_t *top[2] = {0}; uint64_t c[2] = {0}; + pthread_mutex_lock(&G); + for (thr_t *t = g_all; t; t = t->all) { uint64_t k = t->nclkyield - t->nclkyield_rep; if (k > c[0]) { top[1] = top[0]; c[1] = c[0]; top[0] = t; c[0] = k; } else if (k > c[1]) { top[1] = t; c[1] = k; } } + size_t o = 0; char nb[32]; if (n) out[0] = 0; + for (int i = 0; i < 2 && top[i] && o < n; i++) { thr_t *t = top[i]; + uint64_t pr = t->ncwpred - t->ncwpred_rep, fi = t->ncwfirst - t->ncwfirst_seen, ls = t->cw_late_sum - t->cw_late_seen; + o += snprintf(out + o, n - o, "%s%#x '%s' %llu yields, %llu predicted sleeps (wait over at the first poll after it %llu; woke late by %.0f / %.0f us), period %.2f ms", i ? ", " : "", t->handle, thr_name(t, nb, sizeof nb), + (unsigned long long)c[i], (unsigned long long)pr, (unsigned long long)fi, pr ? ls / 1e3 / (double)pr : 0.0, t->cw_late_max / 1e3, t->cw_per / 1e6); + } + for (thr_t *t = g_all; t; t = t->all) { t->nclkyield_rep = t->nclkyield; t->ncwpred_rep = t->ncwpred; t->ncwfirst_seen = t->ncwfirst; t->cw_late_seen = t->cw_late_sum; t->cw_late_max = 0; } + pthread_mutex_unlock(&G); +} // CPU time of the guest threads since the last call, by Switch priority band (<= 44: the main thread's level and above; 45-59; >= 60) and the three busiest threads with their priority. // For the power line (hle_nvn.c power_line): it shows which threads a priority-to-QoS mapping would move and how much CPU they use. secs = the window length void dm_thread_cpu(char *out, size_t n, double secs) { diff --git a/dm/host/loader.c b/dm/host/loader.c index ce63ce79cd..b9b40b81ca 100644 --- a/dm/host/loader.c +++ b/dm/host/loader.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include "hle.h" @@ -314,6 +315,99 @@ static void install_fps_state(module_t *m) { dm_fps_state = m->base + m->fps_state_off; g_fps_mod = m->name; dm_fps_step_max = (int)m->step_max; if (m->render_scale_max > 1) g_render_scale_max = (float)m->render_scale_max; } +// Screen shape for a profile whose stubs take any shape (game.tsv screen_aspect any, DM_GAME_SCREEN_ASPECT 2: Ocarina of Time's patches.py), wider or taller than 16:9, and follow it +// while the game runs. State +0xa0 float the screen's width / height (0 = 16:9: the stubs run the game's own code), +0xa4 float the width factor (the ratio over 16:9, at least 1), +// +0xa8 float the height factor (16:9 over the ratio, at least 1; both lowered by one number under DM_SCREEN_PIXELS: screen_pixels_cap), +0xac u32 a count bumped at each change, +0xc4 / +0xc8 floats the camera's x / y multipliers (below). A wider screen keeps the game's height and vertical angle and shows more +// at the sides; a taller one keeps its width and horizontal angle and shows more above and below, whatever the shape, as a PC game in a window does: a portrait window too (the +// profile's stubs keep the picture's pixel count in bounds and grow the window textures). The bounds below only keep a degenerate window (a few pixels high) out +#define SCREEN_MIN 0.25 +#define SCREEN_MAX 6.0 +static int g_screen_follow; // DM_SCREEN_ASPECT auto (the default): the front end's view gives the shape, now and when it changes +static double g_screen_ratio = -1; // what the state page holds (0 = 16:9), -1 = not written yet +__attribute__((weak)) double front_view_aspect(void) { return 0; } // front.h: the game view's width / height, 0 = no view (a run with no window); front_mac.m, front_ios.m +static pthread_mutex_t g_screen_mu = PTHREAD_MUTEX_INITIALIZER; // the game's start (main.c) and the front end's main thread both write the shape +static void screen_any_write_(double a, const char *why); +static void screen_any_write(double a, const char *why) { pthread_mutex_lock(&g_screen_mu); screen_any_write_(a, why); pthread_mutex_unlock(&g_screen_mu); } +// The camera's x / y multipliers for a shape (state +0xc4 / +0xc8; 0 = 16:9). Landscape: wider than 16:9 keeps the vertical angle (x × 16:9 / r), narrower keeps the horizontal one +// (y × r / 16:9). Portrait takes the scale of the same screen turned landscape, its width getting what that one's height gets: a phone or a window turned keeps the characters' +// size and shows another part of the world. Their ratio y / x is always r × 9 / 16, the projection's aspect over 16:9's +static void screen_camera(double r, float c[2]) { + double l = r >= 1 ? r : 1 / r, xl = l >= 16.0 / 9 ? 16.0 / 9 / l : 1, yl = l >= 16.0 / 9 ? 1 : l * 9 / 16; + c[0] = r == 0 ? 1 : r >= 1 ? (float)xl : (float)(yl * 16 / 9); c[1] = r == 0 ? 1 : r >= 1 ? (float)yl : (float)(xl * 9 / 16); +} +// Upright, the vertical angle is capped (DM_SCREEN_UPRIGHT_FOV, read once): an upright screen shows no more height than a picture of that shape (default 1, a square) would, its +// width narrowing instead. A phone upright with the rule above sees about 90° vertically (Ocarina's fovy 50° at 16:9, 79° at 1:1), past what the game ever shows: above Link's +// house the world is not built. 0 turns the cap off; another shape from 0.25 to 6 moves it (1.777: the game's own vertical angle; under 1 only screens taller than it are held). +// Landscape is never capped. The y multiplier is raised to the cap's and x follows it, so the projection keeps the screen's aspect +static double g_upright_cap = -1; +static double screen_upright_cap(void) { + if (g_upright_cap >= 0) return g_upright_cap; + const char *e = getenv("DM_SCREEN_UPRIGHT_FOV"); double v = 1; + if (e && *e) { + char *end; v = strtod(e, &end); + if (end == e || *end || !(v == 0 || (v >= SCREEN_MIN && v <= SCREEN_MAX))) { LOG("[RED] DM_SCREEN_UPRIGHT_FOV=%s: 0 (off) or a width / height from 0.25 to 6; keeping 1", e); v = 1; } + else LOG("%s: upright vertical angle %s (DM_SCREEN_UPRIGHT_FOV)", g_fps_mod, v ? "held to that shape's" : "not capped"); + } + return g_upright_cap = v; +} +// The picture's pixels in a shape other than 16:9 (DM_SCREEN_PIXELS, read once): at most that many times those of the size the game asks for, 0.5 to 1.5. Unset (or 1.5) the +// profile's stub alone bounds them (Ocarina of Time's output size: 1.5, so a phone upright renders 1200x2600 for the game's handheld 1920x1080, and the upscaler and the +// output-resolution passes run at that size). Lower, both size factors (+0xa4 / +0xa8) are scaled by one number so their product is the bound: the stub keeps the shape and +// rounds each side to a multiple of 8 as before, under its own bound (1.0 upright: 976x2120). The camera (+0xc4 / +0xc8) and the shape are unchanged: the same picture with +// fewer pixels, which the presenter scales to the view +static double g_screen_pixels = -1; +static double screen_pixels_cap(void) { + if (g_screen_pixels >= 0) return g_screen_pixels; + const char *e = getenv("DM_SCREEN_PIXELS"); double v = 0; + if (e && *e) { + char *end; v = strtod(e, &end); + if (end == e || *end || !(v >= 0.5 && v <= 1.5)) { LOG("[RED] DM_SCREEN_PIXELS=%s: 0.5 to 1.5 times the game's own pixels; keeping the profile's bound", e); v = 0; } + else if (v == 1.5) v = 0; // the stub's own bound + } + return g_screen_pixels = v; +} +static void screen_any_write_(double a, const char *why) { + if (!dm_fps_state) return; + double r = a < SCREEN_MIN ? SCREEN_MIN : a > SCREEN_MAX ? SCREEN_MAX : a; + if (fabs(r / (16.0 / 9.0) - 1) < 0.005) r = 0; // 16:9 within half a percent: the game's own picture + if (r == g_screen_ratio) return; + float f[3] = {(float)r, r ? (float)fmax(r * 9 / 16, 1) : 1, r ? (float)fmax(16 / (9 * r), 1) : 1}; + double px = screen_pixels_cap(), area = (double)f[1] * f[2]; int fewer = 0; + if (r && px && area > px) { double s = sqrt(px / area); f[1] = (float)(f[1] * s); f[2] = (float)(f[2] * s); fewer = 1; } // screen_pixels_cap + memcpy(dm_fps_state + 0xa0, f, sizeof f); + // +0xc4 / +0xc8: the camera's x / y multipliers (the projection's rows; screen_camera), upright capped (screen_upright_cap). The size stub copies them with the size it sets + // (patches.py screen_shape), and the HUD's follow from them + float c[2]; screen_camera(r, c); double cap = screen_upright_cap(); int capped = 0; + { float k[2]; + if (r && cap && r < 1 && r < cap) { screen_camera(cap, k); if (c[1] < k[1]) { c[1] = k[1]; c[0] = (float)(k[1] * 16 / (9 * r)); capped = 1; } } } + memcpy(dm_fps_state + 0xc4, c, sizeof c); + uint32_t gen; memcpy(&gen, dm_fps_state + 0xac, 4); gen++; memcpy(dm_fps_state + 0xac, &gen, 4); + extern void mtl_present_screen(uint32_t w, uint32_t h); mtl_present_screen(r ? (uint32_t)(r * 10000 + 0.5) : 0, r ? 10000 : 0); // the picture's shape for a crop of that shape (nvn_mtl.m present_shape) + int first = g_screen_ratio < 0; g_screen_ratio = r; + if (r) { + LOG("%s: screen shape %.3f (%s%s): %s, picture %.3f x %.3f of 16:9, camera x %.3f y %.3f%s", g_fps_mod, r, why, a != r && a > 0 ? ", held to 0.25..6" : "", + r > 16.0 / 9 ? "more at the sides" : "more above and below", f[1], f[2], c[0], c[1], capped ? ", upright cap" : ""); + if (fewer) LOG("%s: picture held to %.2f of the game's pixels (DM_SCREEN_PIXELS)", g_fps_mod, px); + } else LOG("%s: screen shape 16:9 (%s)", g_fps_mod, why); + if (capped) LOG("%s: upright: vertical angle held to a %.2f picture's (DM_SCREEN_UPRIGHT_FOV)", g_fps_mod, cap); + if (!first) { void dm_display_changed(void); dm_display_changed(); } // the game lays its picture out again (hle_oe.c) +} +static void screen_any_apply(const char *as) { + if (!as || !*as || !strcmp(as, "auto")) { // the default: follow the view (16:9 until there is one) + g_screen_follow = 1; double v = front_view_aspect(); screen_any_write(v > 0 ? v : 16.0 / 9.0, v > 0 ? "the window's shape" : "no window yet"); + return; + } + char *end; double a = strtod(as, &end); + if (!strcmp(as, "0")) a = 16.0 / 9.0; + else if (end == as || *end || !(a >= SCREEN_MIN && a <= SCREEN_MAX)) { LOG("[RED] DM_SCREEN_ASPECT=%s: auto, 0 or a width / height (0.25 to 6); keeping 16:9", as); a = 16.0 / 9.0; } + screen_any_write(a, "DM_SCREEN_ASPECT"); +} +// front.h: the front end's game view changed shape (a window resized, full screen, a rotated or resized iPad window). Followed only under DM_SCREEN_ASPECT auto by a profile with +// screen_aspect any; a fixed DM_SCREEN_ASPECT keeps its shape +void dm_screen_view_changed(double aspect) { + if (DM_GAME_SCREEN_ASPECT != 2 || !g_screen_follow || g_screen_ratio < 0 || !(aspect > 0)) return; + screen_any_write(aspect, "the window's shape"); +} // The settings in the state page, written when the game starts (main.c, after host loading): on iOS the loading runs at app launch, before the launcher has set DM_FPS_TARGET and // DM_RENDER_SCALE (Launcher.swift), and nothing reads the page before the game runs void dm_fps_state_apply(void) { @@ -336,7 +430,8 @@ void dm_fps_state_apply(void) { // (Breath of the Wild 1.9.0's patches.py) render that shape: the output keeps its width (1920) and takes the height that gives the ratio, a multiple of 48 so the // 2/3-size layout space (1280 wide) stays whole: 1.43 → 1920x1344 and 1280x896. State +0x48 u32 output height, +0x4c u32 layout height, +0x50 its float; 0 = 16:9 const char *as = getenv("DM_SCREEN_ASPECT"); - if (as && *as && strcmp(as, "0") && strcmp(as, "auto")) { // 0: 16:9; auto: the iOS front end resolves it to the screen's shape (a Mac window has none) + if (DM_GAME_SCREEN_ASPECT == 2) screen_any_apply(as); // a profile whose stubs take any shape (screen_aspect any): below + else if (as && *as && strcmp(as, "0") && strcmp(as, "auto")) { // 0: 16:9; auto: the iOS front end resolves it to the screen's shape (a Mac window has none) char *end; float a = strtof(as, &end); if (end == as || *end || !(a >= 1.3f && a < 1.77f)) LOG("[RED] DM_SCREEN_ASPECT=%s: a width / height from 1.3 to 1.77; keeping 16:9", as); else { diff --git a/dm/host/probe.c b/dm/host/probe.c index 745c78b17f..138b4b8366 100644 --- a/dm/host/probe.c +++ b/dm/host/probe.c @@ -16,6 +16,7 @@ #include #include #include +#include void crash_set_trap_hook(int (*fn)(ucontext_t *uc)); #if !TARGET_OS_IPHONE // Syntax module:offset[@x0 offset]. Put a brk at the guest address; on hit print x0..x3 (and the readable strings they point to) and a backtrace, then execute the original instruction from a trampoline slot and jump back. @@ -107,6 +108,7 @@ static void probe_dump_once(void) { fwrite(m->base + strtoull(o, 0, 16), 1, strtoull(n, 0, 16), fp); fclose(fp); LOG("probe dump %s+%s length %s → %s", mod, o, n, f ? f : def); } +static void watch_from_hit(ucontext_t *uc); // DM_PROBE_WATCH=@xN+: armed from the first printed probe hit (below) static int probe_hit(ucontext_t *uc) { // Registered by probe_install with the SIGTRAP branch of crash.c uint64_t pc = uc->uc_mcontext->__ss.__pc; for (int i = 0; i < g_nprobe; i++) if (g_probe[i].at == pc) { @@ -126,11 +128,13 @@ static int probe_hit(ucontext_t *uc) { // Registered by probe_install with the if (!strstr(nm, g_hw.want)) { uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot; return 1; } } probe_dump_once(); + watch_from_hit(uc); flockfile(stderr); // One block per hit when threads hit at once { extern uint64_t g_t0_ns; uint64_t now_ns(void); uint32_t thr_cur_handle(void); ++g_probe[i].hits; fprintf(stderr, "[dm] PROBE %s #%u [%.4fs] F=%llu T=%x", g_probe[i].name, g_probe_every ? g_probe[i].seen : g_probe[i].hits, (now_ns() - g_t0_ns) / 1e9, (unsigned long long)frame, thr_cur_handle()); } for (int r = 0; r < 8; r++) { uint64_t v = uc->uc_mcontext->__ss.__x[r]; fprintf(stderr, " x%d=%#llx", r, v); probe_str(v); } for (int r = 19; r < 24; r++) fprintf(stderr, " x%d=%#llx", r, uc->uc_mcontext->__ss.__x[r]); if (getenv("DM_PROBE_ALL")) for (int r = 8; r < 19; r++) fprintf(stderr, " x%d=%#llx", r, uc->uc_mcontext->__ss.__x[r]); // also print x8–x18 + if (getenv("DM_PROBE_FP")) for (int r = 0; r < 8; r++) { float f; memcpy(&f, &uc->uc_mcontext->__ns.__v[r], 4); fprintf(stderr, " s%d=%g", r, f); } // also print s0–s7 (float arguments) fprintf(stderr, " lr=%#llx", uc->uc_mcontext->__ss.__lr); { uint64_t x8 = uc->uc_mcontext->__ss.__x[8]; Dl_info di; fprintf(stderr, " x8=%#llx", x8); // x8: indirect call targets are often here (probe placed before blr x8) if (dladdr((void *)x8, &di) && di.dli_sname) fprintf(stderr, " (%s+%#lx)", di.dli_sname, (unsigned long)(x8 - (uint64_t)di.dli_saddr)); } @@ -145,9 +149,9 @@ static int probe_hit(ucontext_t *uc) { // Registered by probe_install with the fputc('=', stderr); for (int k = 0; k < 16; k++) fprintf(stderr, "%02x", b[k]); } } fputc('\n', stderr); - { static long xd = -2; if (xd == -2) { const char *e = getenv("DM_PROBE_X2"); xd = e ? strtol(e, 0, 16) : -1; } // DM_PROBE_X2=bytes: also print the memory x2 points to (to read object fields) - if (xd > 0) { uint64_t at = uc->uc_mcontext->__ss.__x[2]; uint8_t b[512]; vm_size_t got = 0; long n = xd > 512 ? 512 : xd; - if (!vm_read_overwrite(mach_task_self(), at, n, (vm_address_t)b, &got)) { fprintf(stderr, "[dm] [x2]:"); for (long k = 0; k < (long)got; k += 8) { uint64_t v; memcpy(&v, b + k, 8); fprintf(stderr, "%s%llx", k % 32 ? " " : "\n[dm] ", (unsigned long long)v); } fputc('\n', stderr); } } } + { static long xd = -2, xr = 2; if (xd == -2) { const char *e = getenv("DM_PROBE_X2"); xd = e ? strtol(e, 0, 16) : -1; e = getenv("DM_PROBE_XREG"); if (e) xr = strtol(e, 0, 10) & 31; } // DM_PROBE_X2=bytes: also print the memory x2 points to (to read object fields); DM_PROBE_XREG=N: xN's instead + if (xd > 0) { uint64_t at = uc->uc_mcontext->__ss.__x[xr]; uint8_t b[512]; vm_size_t got = 0; long n = xd > 512 ? 512 : xd; + if (!vm_read_overwrite(mach_task_self(), at, n, (vm_address_t)b, &got)) { fprintf(stderr, "[dm] [x%ld]:", xr); for (long k = 0; k < (long)got; k += 8) { uint64_t v; memcpy(&v, b + k, 8); fprintf(stderr, "%s%llx", k % 32 ? " " : "\n[dm] ", (unsigned long long)v); } fputc('\n', stderr); } } } if (g_probe[i].hreg >= 0) probe_heapwalk(uc->uc_mcontext->__ss.__x[g_probe[i].hreg]); dm_backtrace(uc->uc_mcontext->__ss.__fp); funlockfile(stderr); @@ -184,6 +188,7 @@ static void probe_add(module_t *m, uint64_t off, long dump, probe_fn fn) { // (a store in that millisecond goes unseen). STEINS;GATE RE:BOOT: the engine object's page takes bursts of stores every frame, and a watch that unprotected the page for each fault missed // the one that matters; this one found it at once (main+0x389e90, a setter its start-up code calls with 0: the game renders 1280x720 docked by its own choice) static uint64_t g_wat, g_wlen, g_wpg, g_wpsz; static uint8_t *g_walias; static _Atomic int g_warmed; +static unsigned g_wcap; // printed watch hits left, 0 = no cap (DM_PROBE_FINDMAT) static void watch_where(const char *tag, uint64_t a) { module_t *m = module_of((void *)a); Dl_info di; if (m) fprintf(stderr, " %s=%s+%#llx", tag, m->name, (unsigned long long)(a - (uint64_t)m->base)); @@ -199,7 +204,16 @@ static int watch_decode(ucontext_t *uc, uint32_t in, uint64_t *ea, unsigned *len unsigned rt = in & 31, rn = (in >> 5) & 31, v = (in >> 26) & 1; *wb = -1; if ((in & 0xffffffe0) == 0xd50b7420) { // DC ZVA: zero the 64-byte block *ea = XT(rt) & ~63ull; *len = 64; memset(data, 0, 64); return 1; } - if ((in & 0x3a000000) == 0x28000000) { // STP / STNP: opc 101 V 0 type L imm7 + if ((in & 0xbfff0000) == 0x0d000000 && !(((in >> 13) & 7) & 1)) { // ST1 (single structure, no offset): one lane of Vt; opcode 000 / 010 / 100 = byte / half / word or double + unsigned op = (in >> 13) & 7, q = (in >> 30) & 1, s = (in >> 12) & 1, size = (in >> 10) & 3, sz, idx; + if (op == 0) { sz = 1; idx = q << 3 | s << 2 | size; } + else if (op == 2) { if (size & 1) return 0; sz = 2; idx = q << 2 | s << 1 | size >> 1; } + else if (size == 0) { sz = 4; idx = q << 1 | s; } + else if (size == 1 && !s) { sz = 8; idx = q; } + else return 0; + *ea = XN(rn); *len = sz; memcpy(data, (uint8_t *)&ns->__v[rt] + idx * sz, sz); return 1; + } + if ((in & 0x3a000000) == 0x28000000) { // STP / STNP: opc 101 V 0 type L imm7 if (in & (1u << 22)) return 0; // LDP unsigned opc = in >> 30, type = (in >> 23) & 3, sz = v ? 4u << opc : (opc & 2 ? 8 : 4); if ((!v && opc == 1) || opc == 3) return 0; // STGP / LDPSW, reserved @@ -247,6 +261,8 @@ static int watch_fault(void *addr, int is_write, void *ucv) { } if (wb >= 0) { if (wb == 31) uc->uc_mcontext->__ss.__sp = wbv; else if (wb == 29) uc->uc_mcontext->__ss.__fp = wbv; else if (wb == 30) uc->uc_mcontext->__ss.__lr = wbv; else uc->uc_mcontext->__ss.__x[wb] = wbv; } uc->uc_mcontext->__ss.__pc = pc + 4; + if (hit && g_wcap == 1) hit = 0; // DM_PROBE_FINDMAT's cap reached + else if (hit && g_wcap) g_wcap--; if (hit) { flockfile(stderr); { extern uint64_t g_t0_ns; uint64_t now_ns(void); uint32_t thr_cur_handle(void); @@ -257,6 +273,36 @@ static int watch_fault(void *addr, int is_write, void *ucv) { } return 1; } + // CAS / CASA / CASL / CASAL (one register, any size): carried out atomically through the alias, so a page busy with them stays protected. Ocarina of Time: lock words beside + // the camera's projection matrix took CAS at every frame, and the 1 ms the page was left unprotected for each one hid the projection's own store + { uint32_t in = *(uint32_t *)pc; + if (g_walias && (in & 0x3fa07c00) == 0x08a07c00) { + _STRUCT_ARM_THREAD_STATE64 *ss = &uc->uc_mcontext->__ss; unsigned rs = (in >> 16) & 31, rn = (in >> 5) & 31, rt = in & 31, sz = 1u << (in >> 30); + uint64_t ea = rn == 31 ? ss->__sp : rn == 29 ? ss->__fp : rn == 30 ? ss->__lr : ss->__x[rn]; + #define RX(r) ((r) == 31 ? 0 : (r) == 29 ? ss->__fp : (r) == 30 ? ss->__lr : ss->__x[r]) + uint64_t exp = RX(rs), nv = RX(rt), was = 0; + #undef RX + if (ea >= g_wpg && ea + sz <= g_wpg + g_wpsz && !(ea & (sz - 1))) { + int hit = ea < g_wat + g_wlen && ea + sz > g_wat; uint64_t old = hit ? watch_val() : 0; void *p = g_walias + (ea - g_wpg); + switch (sz) { + case 1: { uint8_t e = (uint8_t)exp; __atomic_compare_exchange_n((uint8_t *)p, &e, (uint8_t)nv, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); was = e; break; } + case 2: { uint16_t e = (uint16_t)exp; __atomic_compare_exchange_n((uint16_t *)p, &e, (uint16_t)nv, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); was = e; break; } + case 4: { uint32_t e = (uint32_t)exp; __atomic_compare_exchange_n((uint32_t *)p, &e, (uint32_t)nv, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); was = e; break; } + default: { uint64_t e = exp; __atomic_compare_exchange_n((uint64_t *)p, &e, nv, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); was = e; break; } + } + if (rs != 31) { if (rs == 29) ss->__fp = was; else if (rs == 30) ss->__lr = was; else ss->__x[rs] = was; } // Ws is zero-extended: was already is + ss->__pc = pc + 4; + if (hit && watch_val() != old) { + flockfile(stderr); + { extern uint64_t g_t0_ns; uint64_t now_ns(void); uint32_t thr_cur_handle(void); + fprintf(stderr, "[dm] WATCH %#llx [%.4fs] T=%x CAS of %u bytes at %#llx: %#llx → %#llx", (unsigned long long)g_wat, (now_ns() - g_t0_ns) / 1e9, thr_cur_handle(), sz, (unsigned long long)ea, (unsigned long long)old, (unsigned long long)watch_val()); } + watch_where("pc", pc); watch_where("lr", ss->__lr); fputc('\n', stderr); + dm_backtrace(ss->__fp); + funlockfile(stderr); + } + return 1; + } + } } // Exclusive and atomic stores (STXR / STLXR / STLR / STXP, CAS, SWP, LD) address [Xn] with no offset: one that reaches the watched bytes is reported like a store, every time // (its new value lands when it runs on the unprotected page). Tears of the Kingdom's memory-shortage flag is set by such a store, and the page it lies on takes many of them { uint32_t in = *(uint32_t *)pc; int ex = (in & 0x3f000000) == 0x08000000, at = (in & 0x3f200c00) == 0x38200000; // exclusive class (CAS / CASP among them); LD / SWP @@ -281,6 +327,16 @@ static int watch_fault(void *addr, int is_write, void *ucv) { return 1; } static uint64_t g_wrel; static int g_wheap; // heap+: the address is that far past the guest heap's base, resolved once the game opens its heap +// @xN+: the address is that register plus the offset at the first printed probe hit (an object the game allocates where addresses move from run to run, as Ocarina of Time's +// layout resources and panes in the alias region do); the watch arms itself on it as on any other address +static int g_wfrom = -1; static uint64_t g_wfoff; +static void watch_from_hit(ucontext_t *uc) { + if (g_wfrom < 0 || g_wat) return; + uint64_t at = uc->uc_mcontext->__ss.__x[g_wfrom] + g_wfoff; + if ((at & (g_wpsz - 1)) + g_wlen > g_wpsz) { LOG("WATCH: [RED] %#llx + %#llx crosses a host page: not armed", (unsigned long long)at, (unsigned long long)g_wlen); g_wfrom = -1; return; } + g_wpg = at & ~(g_wpsz - 1); g_wat = at; + LOG("write watch from x%d + %#llx = %#llx", g_wfrom, (unsigned long long)g_wfoff, (unsigned long long)at); +} static void *watch_arm(void *p) { (void)p; for (;;) { @@ -352,14 +408,117 @@ static void *poll_run(void *p) { } return NULL; } +// DM_PROBE_FINDMAT=[,]: who builds the camera's projection. That many seconds after start a host thread scans the guest heap for perspective matrices (4x4 floats, +// row or column major, the w row or column 0,0,±1,0, off-diagonal zeros, x and y scales positive) and prints each with its y / x scale ratio (the projection's aspect), then arms the +// write watch above on the n-th (default 0) whose ratio is 16:9 within 0.5 %, its 64 bytes, for 40 printed stores. Heap addresses move between runs, so the watch is armed in the same run. +// Ocarina of Time: the game renders a wider crop but projects at 16:9, and neither sead::PerspectiveProjection nor tanf runs in play +static void *findmat_run(void *p) { + double secs = ((double *)p)[0]; int pick = (int)((double *)p)[1]; extern uint64_t g_t0_ns; uint64_t now_ns(void); + while ((now_ns() - g_t0_ns) / 1e9 < secs) usleep(100000); + uint64_t hb = 0; size_t hl = 0; dm_guest_heap_range(&hb, &hl); + if (!hb || !hl) { LOG("FINDMAT: [RED] no guest heap"); return NULL; } + LOG("FINDMAT: scanning heap %#llx + %#zx", (unsigned long long)hb, hl); + enum { CH = 1 << 20 }; static float buf[CH / 4 + 16]; int found = 0, n16 = 0; uint64_t pickat = 0; + for (uint64_t a = hb; a < hb + hl; a += CH) { + vm_size_t got = 0; size_t want = a + CH + 64 <= hb + hl ? CH + 64 : hb + hl - a; + if (vm_read_overwrite(mach_task_self(), a, want, (vm_address_t)buf, &got) || got < 64) continue; + for (size_t i = 0; i + 16 <= got / 4 && i < CH / 4; i++) { + const float *f = buf + i; + if (!(f[0] > 0.05f && f[0] < 50 && f[5] > 0.05f && f[5] < 50) || f[1] != 0 || f[4] != 0 || f[3] != 0 || f[7] != 0 || f[15] != 0) continue; + int rowm = (f[14] == -1 || f[14] == 1) && f[12] == 0 && f[13] == 0 && f[8] == 0 && f[9] == 0 && f[11] != 0; // sead::Matrix44 rows: w row 0,0,±1,0 + int colm = (f[11] == -1 || f[11] == 1) && f[2] == 0 && f[6] == 0 && f[12] == 0 && f[13] == 0 && f[14] != 0; // column major: w column + if (!rowm && !colm) continue; + float r = f[5] / f[0]; int is169 = fabsf(r / (16.0f / 9) - 1) < 0.005f; + uint64_t at = a + i * 4; + if (found++ < 200) LOG("FINDMAT %#llx (heap+%#llx) %s ratio %.4f%s x %g y %g z %g %g", (unsigned long long)at, (unsigned long long)(at - hb), rowm ? "rows" : "cols", + r, is169 ? " 16:9" : "", f[0], f[5], f[10], rowm ? f[11] : f[14]); + if (is169 && n16++ == pick) pickat = at; + } + } + LOG("FINDMAT: %d matrices, %d at 16:9", found, n16); + if (!pickat) return NULL; + g_wpsz = (uint64_t)getpagesize(); g_wlen = 64; g_wcap = 41; + if ((pickat & (g_wpsz - 1)) + g_wlen > g_wpsz) g_wlen = g_wpsz - (pickat & (g_wpsz - 1)); + g_wpg = pickat & ~(g_wpsz - 1); g_wat = pickat; + LOG("FINDMAT: watching %#llx + %#llx", (unsigned long long)g_wat, (unsigned long long)g_wlen); + return NULL; +} +// DM_PROBE_FINDF=,,[,[,]]: where a value the game computes lives. That many seconds after start a host thread scans the opened guest heap and the alias region +// for the float a with the float b bytes after it (4 by default; 0 = both 4 and 16), prints each place (up to 100), and arms the write watch above on the n-th (default 0), both floats, for 40 +// printed stores. Ocarina of Time: the HUD's corner groups sit at (-1920, 1078) in its 3840x2160 layout space; their world matrices hold that translation +static void *findf_run(void *p) { + double *arg = p; double secs = arg[0]; float fa = (float)arg[1], fb = (float)arg[2]; int pick = (int)arg[4]; extern uint64_t g_t0_ns; uint64_t now_ns(void); + int gaps[2] = { (int)arg[3], (int)arg[3] }; if (!gaps[0]) { gaps[0] = 4; gaps[1] = 16; } // gap 0: both 4 (a vector, a column-major matrix) and 16 (a row-major 3x4 or 4x4) + void svc_alias_range(uint8_t **base, size_t *size); + while ((now_ns() - g_t0_ns) / 1e9 < secs) usleep(100000); + uint64_t hb = 0; size_t hl = 0; dm_guest_heap_range(&hb, &hl); uint8_t *ab = NULL; size_t al = 0; svc_alias_range(&ab, &al); + struct { uint64_t b; size_t n; const char *nm; } reg[2] = { { hb, hl, "heap" }, { (uint64_t)(uintptr_t)ab, al, "alias" } }; + enum { CH = 1 << 20 }; static uint8_t buf[CH + 64]; int found = 0; uint64_t pickat = 0; int pickgap = 4; + for (int r = 0; r < 2; r++) { + if (!reg[r].b || !reg[r].n) continue; + LOG("FINDF: scanning %s %#llx + %#zx for %g, %g %d or %d bytes after", reg[r].nm, (unsigned long long)reg[r].b, reg[r].n, fa, fb, gaps[0], gaps[1]); + uint64_t end = reg[r].b + reg[r].n; + for (mach_vm_address_t ra = reg[r].b; ra < end; ) { // the mapped, readable parts only (the alias region is 64 GB, mostly unmapped) + mach_vm_size_t rs = 0; vm_region_basic_info_data_64_t bi; mach_msg_type_number_t cnt = VM_REGION_BASIC_INFO_COUNT_64; mach_port_t obj; + if (mach_vm_region(mach_task_self(), &ra, &rs, VM_REGION_BASIC_INFO_64, (vm_region_info_t)&bi, &cnt, &obj) || ra >= end) break; + uint64_t re = ra + rs < end ? ra + rs : end; + if (bi.protection & VM_PROT_READ) for (uint64_t a = ra; a < re; a += CH) { + vm_size_t got = 0; size_t want = a + CH + 64 <= re ? CH + 64 : re - a; + if (vm_read_overwrite(mach_task_self(), a, want, (vm_address_t)buf, &got) || got < 24) continue; + for (size_t i = 0; i + 20 <= got && i < CH; i += 4) { + float x, y; memcpy(&x, buf + i, 4); if (x != fa) continue; + for (int g = 0; g < 2; g++) { + if (g && gaps[1] == gaps[0]) break; + memcpy(&y, buf + i + gaps[g], 4); if (y != fb) continue; + uint64_t at = a + i; + if (found < 100) { float c[12] = { 0 }; size_t from = i >= 16 ? i - 16 : 0; memcpy(c, buf + from, from + 48 <= got ? 48 : got - from); + LOG("FINDF %d %#llx (%s+%#llx) gap %d around: %g %g %g %g | %g %g %g %g | %g %g %g %g", found, (unsigned long long)at, reg[r].nm, (unsigned long long)(at - reg[r].b), + gaps[g], c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7], c[8], c[9], c[10], c[11]); } + if (found++ == pick) { pickat = at; pickgap = gaps[g]; } + } + } + } + ra = re; + } + } + LOG("FINDF: %d places", found); + if (!pickat) return NULL; + g_wpsz = (uint64_t)getpagesize(); g_wlen = (uint64_t)pickgap + 4; g_wcap = 41; + if ((pickat & (g_wpsz - 1)) + g_wlen > g_wpsz) g_wlen = g_wpsz - (pickat & (g_wpsz - 1)); + g_wpg = pickat & ~(g_wpsz - 1); g_wat = pickat; + LOG("FINDF: watching %#llx + %#llx", (unsigned long long)g_wat, (unsigned long long)g_wlen); + return NULL; +} static void watch_install(void) { + { const char *e = getenv("DM_PROBE_FINDMAT"); + if (e) { static double arg[2]; char *end; arg[0] = strtod(e, &end); arg[1] = *end == ',' ? strtod(end + 1, 0) : 0; + dm_fault_hook_register(watch_fault); + pthread_t t; pthread_create(&t, NULL, findmat_run, arg); pthread_detach(t); + pthread_create(&t, NULL, watch_arm, NULL); pthread_detach(t); } } + { const char *e = getenv("DM_PROBE_FINDF"); + if (e) { static double arg[5]; arg[3] = 4; char *end = (char *)e; + for (int k = 0; k < 5 && *end; k++) { arg[k] = strtod(end, &end); if (*end == ',') end++; else break; } + dm_fault_hook_register(watch_fault); + pthread_t t; pthread_create(&t, NULL, findf_run, arg); pthread_detach(t); + pthread_create(&t, NULL, watch_arm, NULL); pthread_detach(t); } } { const char *e = getenv("DM_PROBE_POLL"); if (e) { char *end; g_pheap = !strncmp(e, "heap+", 5); if (g_pheap) e += 5; g_palias = !strncmp(e, "alias+", 6); if (g_palias) e += 6; g_poll = strtoull(e, &end, 16); g_plen = *end == '+' ? strtoull(end + 1, &end, 16) : 4; if (*end == '=') { g_pwant = 1; g_pval = strtoull(end + 1, 0, 16); } if ((!g_poll && !g_pheap && !g_palias) || !g_plen || g_plen > 8) die("DM_PROBE_POLL format: [heap+|alias+]
[+][=] (hex)"); pthread_t t; pthread_create(&t, NULL, poll_run, NULL); pthread_detach(t); } } const char *e = getenv("DM_PROBE_WATCH"); if (!e) return; - char *end; g_wheap = !strncmp(e, "heap+", 5); + char *end; + if (e[0] == '@' && e[1] == 'x') { // @xN+[+]: armed at the first printed probe hit + g_wfrom = (int)strtol(e + 2, &end, 10) & 31; g_wfoff = *end == '+' ? strtoull(end + 1, &end, 16) : 0; g_wlen = *end == '+' ? strtoull(end + 1, 0, 16) : 8; + if (!g_wlen) die("DM_PROBE_WATCH format: @xN+[+] (hex)"); + g_wpsz = (uint64_t)getpagesize(); + dm_fault_hook_register(watch_fault); + pthread_t t; pthread_create(&t, NULL, watch_arm, NULL); pthread_detach(t); + g_wcap = 41; // a per-frame writer: 40 printed stores + LOG("write watch on x%d + %#llx + %#llx at the first probe hit", g_wfrom, (unsigned long long)g_wfoff, (unsigned long long)g_wlen); + return; + } + g_wheap = !strncmp(e, "heap+", 5); uint64_t at = strtoull(e + (g_wheap ? 5 : 0), &end, 16); g_wlen = *end == '+' ? strtoull(end + 1, 0, 16) : 8; if ((!at && !g_wheap) || !g_wlen) die("DM_PROBE_WATCH format: [heap+]
[+] (hex)"); g_wpsz = (uint64_t)getpagesize(); diff --git a/dm/host/tests/t_clockwait.c b/dm/host/tests/t_clockwait.c index aa628cb88f..2d11bf6b19 100644 --- a/dm/host/tests/t_clockwait.c +++ b/dm/host/tests/t_clockwait.c @@ -71,5 +71,16 @@ int main(void) { assert(late_frames == 2); assert(late_max < 2000); puts("PASS: a shorter period costs two late waits, then the waits end on time again"); + + // The power line's clause (dm_clock_top) names the thread, its predicted sleeps, the waits a sleep ended too late for (the two above) and the period; a second call, with no clock + // wait since, gives nothing: a game with no clock waits prints no clause + char ck[400]; dm_clock_top(ck, sizeof ck); printf(" clause: %s\n", ck); + unsigned long long y = 0, pr = 0, first = 0; double per = 0; + const char *q = strchr(ck, '\''); q = q ? strchr(q + 1, '\'') : NULL; + assert(q && sscanf(q, "' %llu yields, %llu predicted sleeps (wait over at the first poll after it %llu;", &y, &pr, &first) == 3); + assert(strstr(ck, "period ") && sscanf(strstr(ck, "period ") + 7, "%lf", &per) == 1); + assert(y > 0 && pr >= 40 && first >= 2 && first <= 4 && per > 16.0 && per < 17.0); + dm_clock_top(ck, sizeof ck); assert(!ck[0]); + puts("PASS: the power line names the thread that made clock waits, and says nothing once none did"); return 0; } diff --git a/dm/host/tests/t_codec_video.c b/dm/host/tests/t_codec_video.c index 7c581d90cb..4b3552ee97 100644 --- a/dm/host/tests/t_codec_video.c +++ b/dm/host/tests/t_codec_video.c @@ -13,7 +13,8 @@ #include #include -uint64_t now_ns(void) { return 1; } +static _Atomic uint64_t g_clock = 1; // the host clock the decoder sees (paced(): pictures read at a game's frame rate); the decoder's thread reads it too +uint64_t now_ns(void) { return g_clock; } __thread _Atomic int dm_host_work; // hle_thread.c void dm_host_helper_qos(qos_class_t q) { (void)q; } // hle_thread.c: the decoder's thread keeps the default class in the unit test static struct { void *ev; int bound, set; pthread_t by; } g_ev[16]; // by: the thread that signalled it last @@ -59,7 +60,42 @@ static const uint8_t vp9[] = { 0xff,0xff,0xff,0xf2,0x2a,0xc0,0x00, }; +// A player that reads one picture per game frame (Ocarina of Time's title movie, 60 fps, through the AV1 decoder): with two buffers, packets topped up as the decoder takes them, +// one picture read every read_ns of host clock; times step 16 / 17 ms (the stream's milliseconds, in ns) or, with unit 1000, the same in µs. Returns the movie time the last +// of n reads showed and counts the reads whose picture was not the one after the previous (skips) +static int64_t paced(uint64_t read_ns, int n, int64_t unit, uint64_t pause_at, int *skips) { + _Alignas(16) static uint8_t dec[0x400], pool[2][0x40], mem[2][16 * 16 * 4]; uint64_t size, align, id; uint32_t idx; cv_sync sync; uint16_t w, h, cw, ch; int64_t ts = 0, prev = -1; bool eos; + cv_pref pref = h_cv_pref(16, 16, 3, 0); assert(!h_cv_poolsize(&size, &align, &pref, 1)); + for (int i = 0; i < 2; i++) assert(!h_cv_pool(pool[i], mem[i], size, &pref, 1, 0)); + assert(!h_cv_vp9init2(dec, 0x10000, 16, 16, 1, 1, 3, NULL, 0)); cv_dec *d = cv_of(dec); + for (uint32_t i = 0; i < 2; i++) { assert(!h_cv_vp9reg(dec, i, pool[i], 0)); assert(!h_cv_vp9acq(&idx, &sync, dec)); } + int sent = 0; *skips = 0; g_clock = 1000000000ull; + for (int r = 0; r < n; r++) { + for (;;) { // the decoder full: CV_HOLD pictures waiting, every packet decoded (settle), so the release chooses among them + pthread_mutex_lock(&d->mu); int full = cv_pending(d) >= CV_HOLD; pthread_mutex_unlock(&d->mu); if (full) break; + int64_t t = (sent * 50 + 1) / 3; assert(!h_cv_vp9submit(&id, dec, vp9, sizeof vp9, t * unit * 1000, false)); sent++; // t: 16 or 17 ms + } + settle(dec); + uint32_t b = (uint32_t)(r & 1); h_cv_vp9rel(dec, b, sync); assert(!h_cv_vp9acq(&idx, &sync, dec) && idx == b); + assert(!h_cv_vp9props(&w, &h, &cw, &ch, &ts, &eos, dec, b)); + if (prev >= 0 && ts - prev > 17 * unit * 1000) (*skips)++; + prev = ts; g_clock += read_ns; if (pause_at && r == (int)pause_at) g_clock += 500000000ull; + } + assert(!h_cv_vp9fin(dec)); for (int i = 0; i < 2; i++) h_cv_poolfin(pool[i]); + g_clock = 1; return ts; +} + int main(void) { + { // the movie follows its clock when the player reads slower than the movie's rate, and loses nothing when it keeps up + int skips; int64_t t; + t = paced(16666667, 300, 1000, 0, &skips); assert(skips == 0); assert(t >= 4900000000ll && t <= 5000000000ll); // 60 reads a second: every picture, 5 s of movie in 5 s + t = paced(33333333, 300, 1000, 0, &skips); assert(skips >= 290); assert(t >= 9700000000ll && t <= 10000000000ll); // 30 a second: every other picture, 10 s of movie in 10 s + t = paced(50000000, 300, 1000, 0, &skips); assert(t >= 14500000000ll && t <= 15000000000ll); // 20 a second (hold 3): 15 s in 15 s + t = paced(33333333, 300, 1, 0, &skips); assert(skips == 0); // times in µs: the unit is not known for certain, nothing is dropped + t = paced(33333333, 300, 1000, 150, &skips); assert(t >= 9700000000ll && t <= 10000000000ll); // a 500 ms pause: the clock starts again from the picture after it, no catch-up + printf("t_codec_video: the movie clock passed\n"); + } + _Alignas(16) static uint8_t dec[0x400], pool[3][0x40], spt[0x80], mem[16 * 16 * 4]; uint64_t size, align, id; uint32_t idx; cv_sync sync; uint16_t w, h, cw, ch; int64_t ts; bool eos; diff --git a/dm/host/tests/t_nro.c b/dm/host/tests/t_nro.c index c34d74d37c..1be29a604c 100644 --- a/dm/host/tests/t_nro.c +++ b/dm/host/tests/t_nro.c @@ -7,6 +7,7 @@ void dm_thread_service_connect(void) {} // threads started so far have nothing #include #include void mtl_present_screen(uint32_t w, uint32_t h) { (void)w; (void)h; } // loader.c: a screen taller than 16:9; no renderer here +void dm_display_changed(void) {} // loader.c: a profile with screen_aspect any changed shape (hle_oe.c pushes the display notifications); no game here struct dm_flags g_flag; uint64_t now_ns(void) { return 0; } diff --git a/dm/host/tests/t_symbols.c b/dm/host/tests/t_symbols.c index 7aa8dd1d2f..bd88fee595 100644 --- a/dm/host/tests/t_symbols.c +++ b/dm/host/tests/t_symbols.c @@ -21,6 +21,7 @@ static uint8_t *test_section(const struct mach_header_64 *mh, const char *seg, c #include "../hle.c" #include "../loader.c" void mtl_present_screen(uint32_t w, uint32_t h) { (void)w; (void)h; } // loader.c: a screen taller than 16:9; no renderer here +void dm_display_changed(void) {} // loader.c: a profile with screen_aspect any changed shape (hle_oe.c pushes the display notifications); no game here #undef getsectiondata struct dm_flags g_flag; diff --git a/dm/ios/Sources/DmGamepad.m b/dm/ios/Sources/DmGamepad.m index 1f2040e7a1..f3b1eaabf1 100644 --- a/dm/ios/Sources/DmGamepad.m +++ b/dm/ios/Sources/DmGamepad.m @@ -136,6 +136,7 @@ static void phone_motion_start(UIView *body) { @interface DmGamepad : UIView - (void)arrange:(DmLayout)layout; - (BOOL)menuTakes:(CGPoint)p; +- (BOOL)padOff; @end // The menu button: a UIButton whose menu is the in-game menu (UIKit draws it and takes the touches while it is open). Its hit circle is larger than the drawn one, and a key nearer // to the touch wins (− / + sit beside it), so it asks the pad @@ -643,11 +644,15 @@ static BOOL pads_slotted(GCController *gone) { dispatch_async(dispatch_get_main_queue(), ^{ cp_poll(); }); // a controller came or went while the controller applet's prompt is up return waiting || pad_slot_mask(&g_slots) != 0; // a controller waiting for its first press hides the touch gamepad too } +- (BOOL)padOff { return _padOff; } - (void)padsChanged:(NSNotification *)note { GCController *c = note.object, *gone = [note.name isEqual:GCControllerDidDisconnectNotification] ? c : nil; if (c && (!c.extendedGamepad || g_merge)) LOG("controller %s: %s%s", gone ? "disconnected" : "connected", pad_name(c), c.extendedGamepad ? "" : " (no extended gamepad profile: not used)"); BOOL any = g_merge ? pads_merged(gone) : pads_slotted(gone); - dispatch_async(dispatch_get_main_queue(), ^{ self->_padOff = any; self->_controls.hidden = any; [self reset]; }); // the touch gamepad hides while any controller is in use + dispatch_async(dispatch_get_main_queue(), ^{ // the touch gamepad hides while any controller is in use; upright the picture then takes the whole screen (front_ios.m, DmLayout.h dm_layout_controls_hidden) + BOOL was = self->_padOff; self->_padOff = any; self->_controls.hidden = any; [self reset]; + if (was != any) [self.superview setNeedsLayout]; + }); } @end @@ -745,6 +750,7 @@ int front_ctrl_support(int min, int max) { UIView *dm_gamepad_view(CGRect frame) { DmGamepad *v = [[DmGamepad alloc] initWithFrame:frame]; g_view = v; return v; } void dm_gamepad_arrange(UIView *view, DmLayout layout) { [(DmGamepad *)view arrange:layout]; } void dm_gamepad_opmode_changed(void) { [g_view opmodeChanged]; } +BOOL dm_gamepad_off(UIView *view) { return [view isKindOfClass:DmGamepad.class] && [(DmGamepad *)view padOff]; } void dm_gamepad_touch_feedback(bool on) { [g_view setTouchFeedback:on]; } int dm_pad_layout(void) { return g_view ? [g_view padLayout] : 0; } bool dm_pad_layout_offered(int layout) { return layout == 0 || layout == 1 || (layout == 2 && dm_opmode() == 0); } diff --git a/dm/ios/Sources/DmHostingController.swift b/dm/ios/Sources/DmHostingController.swift index 14eee41774..36e4f969cb 100644 --- a/dm/ios/Sources/DmHostingController.swift +++ b/dm/ios/Sources/DmHostingController.swift @@ -1,7 +1,7 @@ import SwiftUI import UIKit -// Full-screen SwiftUI presentations must preserve the game's four-orientation policy. +// Full-screen SwiftUI presentations (the launcher) follow the game's orientation policy: every orientation, so the app's list decides, unless Rotation locks it (front_ios.m dm_rotation_vc_mask). final class DmHostingController: UIHostingController { - override var supportedInterfaceOrientations: UIInterfaceOrientationMask { .all } + override var supportedInterfaceOrientations: UIInterfaceOrientationMask { dm_rotation_vc_mask() } } diff --git a/dm/ios/Sources/DmIOS-Bridging-Header.h b/dm/ios/Sources/DmIOS-Bridging-Header.h index 2c4aad68d3..db7a7ae894 100644 --- a/dm/ios/Sources/DmIOS-Bridging-Header.h +++ b/dm/ios/Sources/DmIOS-Bridging-Header.h @@ -1,4 +1,5 @@ -// The C and Objective-C functions Launcher.swift and GameMenu.swift call (CloudSaves.h, DmGameMenu.h, save_sync.h's report before Play). project.yml points SWIFT_OBJC_BRIDGING_HEADER here. +// The C and Objective-C functions Launcher.swift, GameMenu.swift and DmHostingController.swift call (CloudSaves.h, DmGameMenu.h, DmRotation.h, save_sync.h's report before Play). project.yml points SWIFT_OBJC_BRIDGING_HEADER here. #import "CloudSaves.h" #import "DmGameMenu.h" +#import "DmRotation.h" #include "save_sync.h" diff --git a/dm/ios/Sources/DmLayout.h b/dm/ios/Sources/DmLayout.h index bb3631f749..62431d4646 100644 --- a/dm/ios/Sources/DmLayout.h +++ b/dm/ios/Sources/DmLayout.h @@ -5,7 +5,18 @@ NS_ASSUME_NONNULL_BEGIN -typedef struct { CGRect game, controls; BOOL separated, topSafeOnly; } DmLayout; +// game: the picture's rectangle; controls: the touch controls'; area: where the picture may go (the view in the overlay layout, the part above the controls in a split), whose shape a +// profile with screen_aspect any renders (front_ios.m view_shape, front.h front_view_aspect) +typedef struct { CGRect game, controls; BOOL separated, topSafeOnly; CGRect area; } DmLayout; + +// Rotation (DM_ROTATION, a launcher and in-game menu setting): auto, landscape or portrait. auto gives `automatic`: every orientation for the view controllers, so the app's own list +// decides, and for the app (front_ios_app_orientations) its Info.plist list for the device: the phone's two landscapes, the iPad's four. landscape locks the two landscapes, portrait +// upright (upside down too where the device has it: an iPad, not a Face ID iPhone) +static inline UIInterfaceOrientationMask dm_rotation_mask(const char *_Nullable value, UIInterfaceOrientationMask automatic) { + if (value && !strcmp(value, "landscape")) return UIInterfaceOrientationMaskLandscape; + if (value && !strcmp(value, "portrait")) return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown; + return automatic; +} static inline UIEdgeInsets dm_game_safe_insets(CGRect bounds, UIEdgeInsets insets, BOOL duo) { return duo && bounds.size.height > bounds.size.width ? UIEdgeInsetsMake(insets.top, 0, 0, 0) : insets; @@ -46,7 +57,7 @@ static inline CGRect dm_horizontal_division(CGRect b, CGRect division) { } static inline DmLayout dm_layout(CGRect b, UIEdgeInsets insets, BOOL partiallyOpen, CGRect division, CGFloat aspect) { - DmLayout l = { dm_aspect_fit(b, aspect), b, NO, NO }; + DmLayout l = { dm_aspect_fit(b, aspect), b, NO, NO, b }; if (CGRectIsEmpty(b)) return l; division = dm_horizontal_division(b, division); BOOL portrait = b.size.height > b.size.width; @@ -58,17 +69,35 @@ static inline DmLayout dm_layout(CGRect b, UIEdgeInsets insets, BOOL partiallyOp CGRect lower = CGRectMake(CGRectGetMinX(b), CGRectGetMaxY(division), b.size.width, CGRectGetMaxY(b) - CGRectGetMaxY(division)); if (upper.size.height <= 0 || CGRectGetMaxY(safe) <= CGRectGetMinY(lower)) return l; - l.game = dm_aspect_fit(upper, aspect); l.controls = lower; l.separated = YES; + l.game = dm_aspect_fit(upper, aspect); l.controls = lower; l.separated = YES; l.area = upper; + return l; +} + +// Portrait layout Full screen (DM_PORTRAIT_LAYOUT=full, the default, for a profile whose picture takes any shape: front_ios.m portrait_full): upright with no fold to split at, +// the picture covers the whole view and the touch controls, still arranged in the lower half as in the split, are drawn over it, as they are over the picture in landscape. +// Touches above the controls go to the game's touch screen as in the split. A half-folded Duo keeps its split at the fold +static inline DmLayout dm_layout_full_picture(DmLayout l, CGRect b, BOOL partiallyOpen, CGRect division, CGFloat aspect) { + if (!l.separated || CGRectIsEmpty(b) || b.size.height <= b.size.width || partiallyOpen || !CGRectIsNull(dm_horizontal_division(b, division))) return l; + l.game = dm_aspect_fit(b, aspect); l.area = b; return l; } +// The touch controls are hidden (a controller is connected, DmGamepad.m dm_gamepad_off): upright with no fold to split at, the picture takes the whole screen inside its safe area +// instead of the half above controls that are not there. Landscape, and a half-folded Duo's split at its fold, stay as dm_layout makes them +static inline DmLayout dm_layout_controls_hidden(DmLayout l, CGRect b, UIEdgeInsets insets, BOOL partiallyOpen, CGRect division, CGFloat aspect) { + if (CGRectIsEmpty(b) || b.size.height <= b.size.width || partiallyOpen || !CGRectIsNull(dm_horizontal_division(b, division))) return l; + CGRect safe = UIEdgeInsetsInsetRect(b, insets); + if (CGRectIsEmpty(safe)) return l; + return (DmLayout){ dm_aspect_fit(safe, aspect), b, NO, NO, safe }; +} + // The picture is on a TV (front_ios.m DmTVSceneDelegate): the controls take the whole view and no touch goes to the game's touch screen (the game is docked there). -static inline DmLayout dm_layout_pad_only(CGRect b) { return (DmLayout){ CGRectZero, b, NO, NO }; } +static inline DmLayout dm_layout_pad_only(CGRect b) { return (DmLayout){ CGRectZero, b, NO, NO, CGRectZero }; } // Fill covers the full view only in the overlay layout (landscape). A portrait or tabletop split keeps the picture fitted in its -// area above the controls, where cropping a small picture would cost more than the bars. +// area above the controls, where cropping a small picture would cost more than the bars, and so does an upright screen with the controls hidden (a 16:9 picture would lose most of its width) static inline DmLayout dm_layout_picture(DmLayout l, CGRect b, BOOL fill, CGFloat aspect) { - if (fill && !l.separated && !CGRectIsEmpty(b)) l.game = dm_aspect_fill(b, aspect); + if (fill && !l.separated && !CGRectIsEmpty(b) && b.size.width >= b.size.height) l.game = dm_aspect_fill(b, aspect); return l; } @@ -84,5 +113,6 @@ UIView *dm_gamepad_view(CGRect frame); void dm_gamepad_arrange(UIView *view, DmLayout layout); void dm_gamepad_reset(void); void dm_gamepad_opmode_changed(void); // the console mode changed (the in-game menu, a TV): the Tap layout exists only in handheld mode +BOOL dm_gamepad_off(UIView *view); // the touch controls are hidden while a controller is in use (the view stays, for game touches) NS_ASSUME_NONNULL_END diff --git a/dm/ios/Sources/DmRotation.h b/dm/ios/Sources/DmRotation.h new file mode 100644 index 0000000000..c61c4330e6 --- /dev/null +++ b/dm/ios/Sources/DmRotation.h @@ -0,0 +1,14 @@ +// Rotation (DM_ROTATION, a launcher and in-game menu setting: auto, landscape, portrait; DmLayout.h dm_rotation_mask): front_ios.m keeps it, the root view controller, the launcher's +// hosting controller (DmHostingController.swift) and the app delegate (main.m) ask it which orientations they allow. +#pragma once +#import + +#ifdef __cplusplus +extern "C" { +#endif +UIInterfaceOrientationMask dm_rotation_vc_mask(void); // a full-screen view controller's: every orientation under auto (the app's list decides) +UIInterfaceOrientationMask front_ios_app_orientations(void); // the app's (application:supportedInterfaceOrientationsForWindow:): under auto its Info.plist list for this device +void dm_rotation_set(const char *_Nullable value); // main thread: DM_ROTATION = value (NULL keeps the environment's), and the windows turn to an orientation it allows +#ifdef __cplusplus +} +#endif diff --git a/dm/ios/Sources/Launcher.swift b/dm/ios/Sources/Launcher.swift index 0f9d8b6639..717a294df9 100644 --- a/dm/ios/Sources/Launcher.swift +++ b/dm/ios/Sources/Launcher.swift @@ -103,48 +103,19 @@ private struct LauncherView: View { var body: some View { GeometryReader { geometry in - HStack(spacing: 0) { - VStack(spacing: 16) { - if let icon = appIcon() { - Image(uiImage: icon).resizable().frame(width: 96, height: 96) - .clipShape(RoundedRectangle(cornerRadius: 22)) - .accessibilityHidden(true) - } - Text((info("CFBundleDisplayName") as? String) ?? "Game") - .font(.title.weight(.bold)).multilineTextAlignment(.center) - Text("Version \((info("CFBundleShortVersionString") as? String) ?? "")") - .font(.callout).foregroundStyle(.secondary) - playButton + // Landscape: the game's name and Play on the left third, the settings beside them; upright (Rotation, an iPad turned), the name and Play above the settings + if geometry.size.width >= geometry.size.height { + HStack(spacing: 0) { + header(icon: 96) + .padding(16) + .frame(width: geometry.size.width / 3, height: geometry.size.height) + settingsList.frame(width: geometry.size.width * 2 / 3) } - .padding(16) - .frame(width: geometry.size.width / 3, height: geometry.size.height) - List { - ForEach(m.sections, id: \.self) { section in - let rows = m.rows(in: section) - if !rows.isEmpty { - Section(section) { - ForEach(rows) { SettingRow(s: $0, m: m) } - } - } - } - Section { - Button("Reset to tested defaults") { m.reset() } - .disabled(!m.changed) - } footer: { - Text("Brings back all settings this game was tested with.") - } - CloudSavesSection() - Section { - HStack { - Text("Memory available") - Spacer() - Text(ByteCountFormatter.string(fromByteCount: Int64(memory), countStyle: .memory)).monospacedDigit().foregroundStyle(.secondary) - } - } + } else { + VStack(spacing: 0) { + header(icon: 64).padding(.horizontal, 16).padding(.vertical, 12) + settingsList } - .listStyle(.insetGrouped) - .contentMargins(.horizontal, 12, for: .scrollContent) - .frame(width: geometry.size.width * 2 / 3) } } .preferredColorScheme(.dark) @@ -164,6 +135,53 @@ private struct LauncherView: View { try? await Task.sleep(for: .seconds(2)) } } + // Rotation turns the screen as soon as it is picked, before Play (front_ios.m dm_rotation_set); the saved pick at once when the screen shows + .onAppear { if let v = m.values["DM_ROTATION"] { dm_rotation_set(v) } } + .onChange(of: m.values["DM_ROTATION"]) { _, v in if let v { dm_rotation_set(v) } } + } + + private func header(icon size: CGFloat) -> some View { + VStack(spacing: size > 64 ? 16 : 8) { + if let icon = appIcon() { + Image(uiImage: icon).resizable().frame(width: size, height: size) + .clipShape(RoundedRectangle(cornerRadius: size * 22 / 96)) + .accessibilityHidden(true) + } + Text((info("CFBundleDisplayName") as? String) ?? "Game") + .font(.title.weight(.bold)).multilineTextAlignment(.center) + Text("Version \((info("CFBundleShortVersionString") as? String) ?? "")") + .font(.callout).foregroundStyle(.secondary) + playButton + } + } + + private var settingsList: some View { + List { + ForEach(m.sections, id: \.self) { section in + let rows = m.rows(in: section) + if !rows.isEmpty { + Section(section) { + ForEach(rows) { SettingRow(s: $0, m: m) } + } + } + } + Section { + Button("Reset to tested defaults") { m.reset() } + .disabled(!m.changed) + } footer: { + Text("Brings back all settings this game was tested with.") + } + CloudSavesSection() + Section { + HStack { + Text("Memory available") + Spacer() + Text(ByteCountFormatter.string(fromByteCount: Int64(memory), countStyle: .memory)).monospacedDigit().foregroundStyle(.secondary) + } + } + } + .listStyle(.insetGrouped) + .contentMargins(.horizontal, 12, for: .scrollContent) } @ViewBuilder var playButton: some View { diff --git a/dm/ios/Sources/front_ios.m b/dm/ios/Sources/front_ios.m index 1495d647e0..2474b959f8 100644 --- a/dm/ios/Sources/front_ios.m +++ b/dm/ios/Sources/front_ios.m @@ -18,6 +18,7 @@ void dm_gamepad_active(void); #import "DmLayout.h" #import "DmGameMenu.h" +#import "DmRotation.h" void front_ios_boot(void); int front_ios_boot_ok(void); @@ -96,6 +97,24 @@ - (void)showFPS:(BOOL)on; @end static DmRootVC *g_root; static CGFloat g_picture_aspect = DM_PICTURE_16_9; // the presented picture's width / height (front_picture_shape); main thread +// The game view's shape for a profile with screen_aspect any (front.h front_view_aspect, dm_screen_view_changed): the shape of the picture's area (DmLayout.h DmLayout.area), so +// the game renders the space it is shown in with no bars: in landscape the app window (an iPad's 1.43, an iPhone's 2.17, a window under Stage Manager), upright the part above the +// touch controls (an iPhone 17's 402x375 points, 1.07) or, with a controller, the whole safe area; on a TV the TV's. A change is handed to the host once the layout has settled for 300 ms +static _Atomic double g_view_aspect; static uint64_t g_view_change; // g_view_change: main thread +double front_view_aspect(void) { return g_view_aspect; } +static void view_shape(CGSize sz, int notify) { + if (sz.width <= 0 || sz.height <= 0) return; + double a = sz.width / sz.height; if (a == g_view_aspect) return; + g_view_aspect = a; if (!notify) return; + uint64_t n = ++g_view_change; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 300 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ if (n == g_view_change) dm_screen_view_changed(a); }); +} +// Portrait layout (DM_PORTRAIT_LAYOUT): full (the default) or split. Full screen needs a picture that takes the screen's shape: a profile with screen_aspect any following the view +// (DM_SCREEN_ASPECT auto); any other picture stays above the controls, where a 16:9 one centred on an upright screen would sit under them +static BOOL portrait_full(void) { + const char *a = getenv("DM_SCREEN_ASPECT"), *p = getenv("DM_PORTRAIT_LAYOUT"); + return DM_GAME_SCREEN_ASPECT == 2 && (!a || !*a || !strcmp(a, "auto")) && !(p && !strcmp(p, "split")); +} static void launcher_done(void) { [g_root startGame]; } @implementation DmRootVC - (void)loadView { self.view = [DmRootView new]; } @@ -154,12 +173,15 @@ - (void)startGame { // takes 1.3 to 1.77), else 16:9. The window's, not the screen's: on an iPad under Stage Manager or Split View the app does not fill the screen. Resolved here, before the // host writes the state page (main.c dm_fps_state_apply) const char *a = getenv("DM_SCREEN_ASPECT"); - if (a && !strcmp(a, "auto")) { + if (DM_GAME_SCREEN_ASPECT == 2) { // a profile whose stubs take any shape (screen_aspect any) follows the picture's area, wider or taller (loader.c, front_view_aspect): + // the layout pass below sets it (viewDidLayoutSubviews), before the host starts + } else if (a && !strcmp(a, "auto")) { CGSize sz = self.view.window ? self.view.window.bounds.size : UIScreen.mainScreen.bounds.size; double r = MAX(sz.width, sz.height) / MAX(MIN(sz.width, sz.height), 1); char v[16]; if (r >= 1.3 && r < 1.77) snprintf(v, sizeof v, "%.3f", r); else strcpy(v, "0"); setenv("DM_SCREEN_ASPECT", v, 1); LOG("front end: picture shape auto: window %.0fx%.0f points (%.3f:1) → DM_SCREEN_ASPECT=%s", sz.width, sz.height, r, v); } } + dm_rotation_set(NULL); // the launcher's pick (Play put it in the environment), a saved one with DM_LAUNCHER=0, or an env file's self.fill = dm_picture_fill(getenv("DM_PICTURE_FIT")); if (self.fill) LOG("front end: picture Fill (DM_PICTURE_FIT=fill), the 16:9 picture covers the screen in landscape and its edges are cropped"); self.view.clipsToBounds = YES; // with Fill the game view is larger than the screen @@ -196,10 +218,14 @@ - (void)viewDidLayoutSubviews { BOOL duoPortrait = b.size.height > b.size.width && (self.hingeStatus != 0 || !CGRectIsNull(division)); UIEdgeInsets gameInsets = dm_game_safe_insets(b, self.view.safeAreaInsets, duoPortrait); BOOL onTV = self.game.superview != self.view; // the TV's view lays the picture out; the phone is all pad - DmLayout layout = onTV ? dm_layout_pad_only(b) : dm_layout_picture(dm_layout(b, gameInsets, self.partiallyOpen, division, g_picture_aspect), b, self.fill, g_picture_aspect); + DmLayout layout = dm_layout(b, gameInsets, self.partiallyOpen, division, g_picture_aspect); + if (portrait_full()) layout = dm_layout_full_picture(layout, b, self.partiallyOpen, division, g_picture_aspect); + else if (dm_gamepad_off(self.pad)) layout = dm_layout_controls_hidden(layout, b, gameInsets, self.partiallyOpen, division, g_picture_aspect); + layout = onTV ? dm_layout_pad_only(b) : dm_layout_picture(layout, b, self.fill, g_picture_aspect); + view_shape(onTV ? self.game.superview.bounds.size : layout.area.size, 1); if (!onTV) self.game.frame = layout.game; layout.topSafeOnly = duoPortrait; - NSString *line = [NSString stringWithFormat:@"%@, hinge %ld%s, divisions %@, picture %@, controls %@", onTV ? @"pad only (picture on the TV)" : layout.separated ? @"split" : self.fill ? @"overlay, Fill" : @"overlay", + NSString *line = [NSString stringWithFormat:@"%@, hinge %ld%s, divisions %@, picture %@, controls %@", onTV ? @"pad only (picture on the TV)" : layout.separated ? (CGRectIntersectsRect(layout.game, layout.controls) ? @"portrait full screen, controls over the picture" : @"split") : self.fill ? @"overlay, Fill" : @"overlay", (long)self.hingeStatus, self.partiallyOpen ? " (half open)" : "", regionLog, NSStringFromCGRect(layout.game), NSStringFromCGRect(layout.controls)]; if (![line isEqualToString:self.layoutLog]) { self.layoutLog = line; LOG("front end: layout %s", line.UTF8String); } self.pad.frame = b; @@ -229,10 +255,43 @@ - (void)viewDidAppear:(BOOL)a { - (BOOL)prefersHomeIndicatorAutoHidden { return YES; } - (UIRectEdge)preferredScreenEdgesDeferringSystemGestures { return UIRectEdgeAll; } // Edge gestures need two swipes, to avoid accidental exits - (BOOL)prefersStatusBarHidden { return YES; } -- (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAll; } +- (UIInterfaceOrientationMask)supportedInterfaceOrientations { return dm_rotation_vc_mask(); } @end UIViewController *front_ios_root(void) { return [DmRootVC new]; } +// Rotation (DM_ROTATION; DmRotation.h, DmLayout.h dm_rotation_mask). The phone's Info.plist lists only the two landscapes (the Duo's inner display follows its bounds) and the iPad's +// all four; the app delegate (main.m) answers with this, which replaces that list, so portrait can be chosen on a phone too while auto keeps each device's list +UIInterfaceOrientationMask dm_rotation_vc_mask(void) { return dm_rotation_mask(getenv("DM_ROTATION"), UIInterfaceOrientationMaskAll); } +static UIInterfaceOrientationMask plist_orientations(void) { + NSArray *list = nil; + if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) list = [NSBundle.mainBundle objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations~ipad"]; + if (![list isKindOfClass:NSArray.class]) list = [NSBundle.mainBundle objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"]; + UIInterfaceOrientationMask m = 0; + if ([list isKindOfClass:NSArray.class]) for (id o in list) { + if ([o isEqual:@"UIInterfaceOrientationPortrait"]) m |= UIInterfaceOrientationMaskPortrait; + else if ([o isEqual:@"UIInterfaceOrientationPortraitUpsideDown"]) m |= UIInterfaceOrientationMaskPortraitUpsideDown; + else if ([o isEqual:@"UIInterfaceOrientationLandscapeLeft"]) m |= UIInterfaceOrientationMaskLandscapeLeft; + else if ([o isEqual:@"UIInterfaceOrientationLandscapeRight"]) m |= UIInterfaceOrientationMaskLandscapeRight; + } + return m ? m : UIInterfaceOrientationMaskAll; +} +UIInterfaceOrientationMask front_ios_app_orientations(void) { return dm_rotation_mask(getenv("DM_ROTATION"), plist_orientations()); } +void dm_rotation_set(const char *value) { + if (value) setenv("DM_ROTATION", value, 1); + const char *now = getenv("DM_ROTATION"); if (!now || !*now) now = "auto"; + static char was[16]; if (strcmp(was, now)) { snprintf(was, sizeof was, "%s", now); LOG("front end: rotation %s (DM_ROTATION)", now); } + UIInterfaceOrientationMask m = front_ios_app_orientations() & dm_rotation_vc_mask(); + for (UIScene *sc in UIApplication.sharedApplication.connectedScenes) { + if (![sc isKindOfClass:UIWindowScene.class] || ![sc.session.role isEqualToString:UIWindowSceneSessionRoleApplication]) continue; // not a TV's + UIWindowScene *ws = (UIWindowScene *)sc; + for (UIWindow *w in ws.windows) for (UIViewController *vc = w.rootViewController; vc; vc = vc.presentedViewController) [vc setNeedsUpdateOfSupportedInterfaceOrientations]; + // UIKit turns a window whose orientation the new mask leaves out only when asked: a lock chosen while upright turns the screen at once + if (m && !(m & (1u << ws.effectiveGeometry.interfaceOrientation))) + [ws requestGeometryUpdateWithPreferences:[[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:m] errorHandler:^(NSError *e) { + LOG("front end: rotation %s: the window did not turn (%s)", now, e.localizedDescription.UTF8String); }]; + } +} + // A TV (cable or AirPlay): iOS gives the app the TV as a scene of its own instead of mirroring the phone. The game's view moves there, 16:9 fills the TV, and the game is // docked as a Switch on its dock (1080p, the operation mode change notification); the phone keeps the pad. Unplugging puts the view back and the mode the game had before @interface DmTVVC : UIViewController @@ -285,6 +344,8 @@ bool dm_setting_live(const char *env, const char *value) { dm_set_opmode(m); dm_gamepad_opmode_changed(); LOG("front end: console mode %s (in-game menu)", m ? "docked" : "handheld"); return true; } + if (!strcmp(env, "DM_ROTATION")) { if (value) dm_rotation_set(value); return true; } + if (!strcmp(env, "DM_PORTRAIT_LAYOUT")) { if (value) { [g_root.view setNeedsLayout]; LOG("front end: portrait layout %s (in-game menu)", value); } return true; } if (!strcmp(env, "DM_SHOW_FPS")) { if (value) [g_root showFPS:atoi(value) != 0]; return true; } if (!strcmp(env, "DM_TOUCH_HAPTICS")) { if (value) dm_gamepad_touch_feedback(atoi(value) != 0); return true; } if (!strcmp(env, "DM_RUMBLE")) { if (value) { dm_haptics_set_enabled(atoi(value) != 0); LOG("front end: game rumble %s (in-game menu)", atoi(value) ? "on" : "off"); } return true; } diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.m index 7cd198ec54..19c983ab9d 100644 --- a/dm/ios/Sources/main.m +++ b/dm/ios/Sources/main.m @@ -21,6 +21,7 @@ int dm_main(int argc, char **argv); // dm/host/main.c compiled in with -Dmain=dm_main UIViewController *front_ios_root(void); +UIInterfaceOrientationMask front_ios_app_orientations(void); // front_ios.m: the orientations Rotation allows (DM_ROTATION) void front_ios_focus_event(int ev); static char *g_argv[4]; static int g_argc; @@ -246,6 +247,8 @@ @implementation App - (UISceneConfiguration *)application:(UIApplication *)a configurationForConnectingSceneSession:(UISceneSession *)s options:(UISceneConnectionOptions *)o { return [[UISceneConfiguration alloc] initWithName:[s.role isEqualToString:UIWindowSceneSessionRoleExternalDisplayNonInteractive] ? @"TV" : @"Default" sessionRole:s.role]; // a TV (front_ios.m DmTVSceneDelegate) } +// Replaces the Info.plist orientation list: Rotation (DM_ROTATION) can turn a phone upright, auto keeps the list (front_ios.m front_ios_app_orientations) +- (UIInterfaceOrientationMask)application:(UIApplication *)a supportedInterfaceOrientationsForWindow:(UIWindow *)w { return front_ios_app_orientations(); } @end // Scene lifecycle: create the window + hand focus events to front_ios.m diff --git a/dm/ios/tests/duo/README.md b/dm/ios/tests/duo/README.md index 782fd74c68..606bdb10e9 100644 --- a/dm/ios/tests/duo/README.md +++ b/dm/ios/tests/duo/README.md @@ -2,7 +2,7 @@ This XCTest app compiles the production iOS gamepad, layout and hosting-controller code with inert host-runtime stubs. Its fixture `game_profile.h` supplies no game data, so the harness does not generate or require a game profile or extracted files. -The Simulator unit tests cover portrait and landscape layout, safe areas, valid and invalid division regions, 16:9 fitting and the Fill picture, touch hit ownership (the menu button against − / +), multitouch and video coordinates, pose-change input release, the in-game menu's layout pick and its live settings (picture, console mode, rumble, frame-rate counter) on the production root view controller, the drawable's pixel cap, controller-to-player slots, stale controller callbacks, and preservation of a seeded controller-motion sample across layout changes. The optional virtual-controller case runs when Simulator exposes one. They use synthetic touches, controller snapshots, hinge statuses and division callbacks; they do not exercise UIKit's own hit-testing of real touches, the menu's presentation or system touch cancellation. +The Simulator unit tests cover portrait and landscape layout, safe areas, valid and invalid division regions, 16:9 fitting and the Fill picture, touch hit ownership (the menu button against − / +), multitouch and video coordinates, pose-change input release, the in-game menu's layout pick and its live settings (picture, console mode, rumble, frame-rate counter) on the production root view controller, the drawable's pixel cap, the Rotation setting's orientation masks with a real turn of the Simulator's window (the harness's app delegate answers as the production one, main.m), the picture area's shape handed to the host, controller-to-player slots, stale controller callbacks, and preservation of a seeded controller-motion sample across layout changes. The optional virtual-controller case runs when Simulator exposes one. They use synthetic touches, controller snapshots, hinge statuses and division callbacks; they do not exercise UIKit's own hit-testing of real touches, the menu's presentation or system touch cancellation. The harness uses synthetic host state and does not validate an installed game, physical hinge sensors or device motion. diff --git a/dm/ios/tests/duo/Sources/DuoHarnessApp.m b/dm/ios/tests/duo/Sources/DuoHarnessApp.m index e9b168d263..bccd185d44 100644 --- a/dm/ios/tests/duo/Sources/DuoHarnessApp.m +++ b/dm/ios/tests/duo/Sources/DuoHarnessApp.m @@ -1,6 +1,7 @@ #import #import "DmLayout.h" #import "DuoHarnessRuntime.h" +#import "DmRotation.h" #include #include #if __has_include() @@ -61,6 +62,10 @@ - (UISceneConfiguration *)application:(UIApplication *)application (void)application; (void)options; return [[UISceneConfiguration alloc] initWithName:@"Default" sessionRole:session.role]; } +// As the production app delegate (main.m): Rotation replaces the Info.plist list, so a phone can turn upright +- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { + (void)application; (void)window; return front_ios_app_orientations(); +} @end @implementation DuoHarnessSceneDelegate diff --git a/dm/ios/tests/duo/Sources/DuoHarnessRuntime.h b/dm/ios/tests/duo/Sources/DuoHarnessRuntime.h index 9d0d779c6f..f3def7278b 100644 --- a/dm/ios/tests/duo/Sources/DuoHarnessRuntime.h +++ b/dm/ios/tests/duo/Sources/DuoHarnessRuntime.h @@ -32,6 +32,7 @@ typedef struct { } DuoHarnessState; DuoHarnessInput duo_harness_input(void); +double duo_harness_view_shape(void); // the last shape front_ios.m handed the host (dm_screen_view_changed), 0 = none yet int duo_harness_rumble(void); // the in-game menu's rumble switch (dm_haptics_set_enabled) void dm_set_opmode(int mode); int dm_opmode(void); diff --git a/dm/ios/tests/duo/Sources/DuoRuntimeStubs.m b/dm/ios/tests/duo/Sources/DuoRuntimeStubs.m index 84efd5dfd9..64476115d6 100644 --- a/dm/ios/tests/duo/Sources/DuoRuntimeStubs.m +++ b/dm/ios/tests/duo/Sources/DuoRuntimeStubs.m @@ -94,6 +94,8 @@ void dm_motion_clear(int player) { } uint32_t dm_player_npad(int player) { return player == 0 ? 0x20 : (uint32_t)player; } +int dm_players_reported(void) { return 1; } // hle_hid.c: the players the game sees (the controller applet's prompt) +int front_web_touch(void) { return 0; } // web_apple.m: no offline page is shown static int g_opmode; // handheld, until a test or the in-game menu docks it int dm_opmode(void) { return g_opmode; } @@ -104,6 +106,9 @@ void dm_motion_clear(int player) { void dm_haptics_apple_init(void) {} void dm_haptics_apple_controller(int player, GCController *controller) { (void)player; (void)controller; } +static double g_view_shape; +void dm_screen_view_changed(double aspect) { g_view_shape = aspect; } // loader.c: the shape a screen_aspect any profile renders +double duo_harness_view_shape(void) { return g_view_shape; } int front_ios_boot_ok(void) { return 1; } void front_ios_boot(void) {} bool dm_show_launcher(void *viewController, void (*done)(void)) { (void)viewController; (void)done; return false; } diff --git a/dm/ios/tests/duo/Sources/Fixtures/game_profile.h b/dm/ios/tests/duo/Sources/Fixtures/game_profile.h index cf8eb6920c..71d9f0810d 100644 --- a/dm/ios/tests/duo/Sources/Fixtures/game_profile.h +++ b/dm/ios/tests/duo/Sources/Fixtures/game_profile.h @@ -2,3 +2,4 @@ // Synthetic defaults for the production virtual gamepad; no extracted game data. #define DM_GAME_PAD_LAYOUT 1 +#define DM_GAME_SCREEN_ASPECT 2 // screen_aspect any: the front end reports its picture area's shape (front_view_aspect, dm_screen_view_changed) diff --git a/dm/ios/tests/duo/Tests/DuoHarnessTests.m b/dm/ios/tests/duo/Tests/DuoHarnessTests.m index 641d8f50f2..2c7a5aa57d 100644 --- a/dm/ios/tests/duo/Tests/DuoHarnessTests.m +++ b/dm/ios/tests/duo/Tests/DuoHarnessTests.m @@ -12,6 +12,7 @@ #import "DmLayout.h" #import "DmGameMenu.h" #import "DuoHarnessRuntime.h" +#import "DmRotation.h" #include "dm_input.h" #include #include @@ -1362,4 +1363,150 @@ - (void)testControllersKeepIndependentPlayersAndLayoutKeepsMotionState { } +// Rotation (DM_ROTATION): the view controllers' mask and the app's, which replaces the Info.plist list (main.m), so a phone can be locked upright +- (void)testRotationSettingSetsTheOrientationMasks { + const UIInterfaceOrientationMask all = UIInterfaceOrientationMaskAll, land = UIInterfaceOrientationMaskLandscape, + upright = UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown; + XCTAssertEqual(dm_rotation_mask(NULL, all), all); + XCTAssertEqual(dm_rotation_mask("auto", land), land, @"auto keeps the device's own list"); + XCTAssertEqual(dm_rotation_mask("landscape", all), land); + XCTAssertEqual(dm_rotation_mask("portrait", land), upright, @"portrait is allowed even where the Info.plist lists only landscape"); + XCTAssertEqual(dm_rotation_mask("sideways", land), land, @"an unknown value is auto"); + + UIViewController *root = [self harnessRootViewController]; + XCTAssertNotNil(root); + [root.view layoutIfNeeded]; + unsetenv("DM_ROTATION"); + BOOL pad = UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad; + XCTAssertEqual(root.supportedInterfaceOrientations, all); + XCTAssertEqual(front_ios_app_orientations(), pad ? all : land, @"auto: the Info.plist list for this device"); + XCTAssertTrue(dm_setting_live("DM_ROTATION", NULL), @"the in-game menu offers Rotation"); + dm_setting_live("DM_ROTATION", "landscape"); + XCTAssertEqual(root.supportedInterfaceOrientations, land); + XCTAssertEqual(front_ios_app_orientations(), land); + dm_setting_live("DM_ROTATION", "auto"); + XCTAssertEqual(root.supportedInterfaceOrientations, all); + XCTAssertEqual(front_ios_app_orientations(), pad ? all : land); + unsetenv("DM_ROTATION"); +} + +- (void)waitForRoot:(UIViewController *)root portrait:(BOOL)portrait { + NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(UIViewController *vc, NSDictionary *bindings) { + (void)bindings; CGSize sz = vc.view.window.bounds.size; return portrait ? sz.height > sz.width : sz.width > sz.height; + }]; + XCTNSPredicateExpectation *e = [[XCTNSPredicateExpectation alloc] initWithPredicate:p object:root]; + XCTAssertEqual([XCTWaiter waitForExpectations:@[e] timeout:8.0], XCTWaiterResultCompleted, @"the window turns %s", portrait ? "upright" : "to landscape"); + [root.view layoutIfNeeded]; +} + +// The pick turns the window at once, a phone included (its Info.plist lists only landscape); upright the picture area is above the controls, and a screen_aspect any profile is +// handed that area's shape, not 16:9 (front_ios.m view_shape) +- (void)testRotationTurnsTheWindowAndTheGameTakesThePictureAreasShape { + UIViewController *root = [self harnessRootViewController]; + XCTAssertNotNil(root); + UIView *game = [root valueForKey:@"game"]; + setenv("DM_PORTRAIT_LAYOUT", "split", 1); // Picture above controls; Full screen below + dm_setting_live("DM_ROTATION", "portrait"); + [self waitForRoot:root portrait:YES]; + XCTAssertEqual(root.supportedInterfaceOrientations, UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown); + CGRect b = root.view.bounds; + DmLayout l = dm_layout(b, root.view.safeAreaInsets, NO, CGRectNull, DM_PICTURE_16_9); + XCTAssertTrue(l.separated); + XCTAssertEqualWithAccuracy(front_view_aspect(), l.area.size.width / l.area.size.height, 1e-3, @"the area above the controls: %@", NSStringFromCGRect(l.area)); + XCTAssertLessThan(front_view_aspect(), 16.0 / 9.0 - 0.1, @"not 16:9"); + // the game presents that shape (its sides rounded to 8 pixels): the picture fills the area + CGFloat a = l.area.size.width / l.area.size.height; + front_picture_shape((int)(a * 10000), 10000); + XCTestExpectation *applied = [self expectationWithDescription:@"shape applied"]; + dispatch_async(dispatch_get_main_queue(), ^{ [applied fulfill]; }); + [self waitForExpectations:@[applied] timeout:2]; + [root.view setNeedsLayout]; [root.view layoutIfNeeded]; + XCTAssertEqualWithAccuracy(game.frame.size.width, l.area.size.width, 1.0, @"%@ in %@", NSStringFromCGRect(game.frame), NSStringFromCGRect(l.area)); + XCTAssertEqualWithAccuracy(game.frame.size.height, l.area.size.height, 1.0); + // Full screen (the default): the picture covers the view, the controls stay in the lower half, over it + setenv("DM_PORTRAIT_LAYOUT", "full", 1); XCTAssertTrue(dm_setting_live("DM_PORTRAIT_LAYOUT", "full")); + [root.view layoutIfNeeded]; + XCTAssertEqualWithAccuracy(front_view_aspect(), b.size.width / b.size.height, 1e-3, @"the whole view's shape"); + front_picture_shape((int)(b.size.width / b.size.height * 10000), 10000); + XCTestExpectation *full = [self expectationWithDescription:@"full shape applied"]; + dispatch_async(dispatch_get_main_queue(), ^{ [full fulfill]; }); + [self waitForExpectations:@[full] timeout:2]; + [root.view setNeedsLayout]; [root.view layoutIfNeeded]; + XCTAssertEqualWithAccuracy(game.frame.size.width, b.size.width, 1.0, @"%@", NSStringFromCGRect(game.frame)); + XCTAssertEqualWithAccuracy(game.frame.size.height, b.size.height, 1.0); + XCTAssertTrue(CGRectGetMaxY(game.frame) > CGRectGetMidY(b) + 100, @"the picture runs under the controls"); + unsetenv("DM_PORTRAIT_LAYOUT"); + front_picture_shape(1920, 1080); + dm_setting_live("DM_ROTATION", "landscape"); + [self waitForRoot:root portrait:NO]; + XCTAssertEqualWithAccuracy(front_view_aspect(), root.view.bounds.size.width / root.view.bounds.size.height, 1e-3, @"landscape: the whole view"); + dm_setting_live("DM_ROTATION", "auto"); + unsetenv("DM_ROTATION"); + XCTestExpectation *restored = [self expectationWithDescription:@"16:9 restored"]; + dispatch_async(dispatch_get_main_queue(), ^{ [restored fulfill]; }); + [self waitForExpectations:@[restored] timeout:2]; +} + +- (void)testPictureAreaIsTheViewOrTheSpaceAboveTheControls { + CGRect land = CGRectMake(0, 0, 874, 402), up = CGRectMake(0, 0, 402, 874); + UIEdgeInsets landInsets = UIEdgeInsetsMake(0, 62, 21, 62), upInsets = UIEdgeInsetsMake(62, 0, 34, 0); + DmLayout l = dm_layout(land, landInsets, NO, CGRectNull, DM_PICTURE_16_9); + XCTAssertTrue(CGRectEqualToRect(l.area, land), @"landscape overlay: the whole view, %@", NSStringFromCGRect(l.area)); + l = dm_layout(up, upInsets, NO, CGRectNull, DM_PICTURE_16_9); + XCTAssertTrue(l.separated); + XCTAssertTrue(CGRectEqualToRect(l.area, CGRectMake(0, 62, 402, 375)), @"upright: above the midpoint, inside the safe area, %@", NSStringFromCGRect(l.area)); + CGFloat a = l.area.size.width / l.area.size.height; + DmLayout own = dm_layout(up, upInsets, NO, CGRectNull, a); + XCTAssertEqualWithAccuracy(own.game.size.width, 402, 1); XCTAssertEqualWithAccuracy(own.game.size.height, 375, 1); + XCTAssertTrue(CGRectEqualToRect(dm_layout_pad_only(up).area, CGRectZero)); +} + +// Portrait layout Full screen: the picture covers the view under the controls, which keep their lower-half rectangle; landscape and a half-folded Duo stay +- (void)testFullScreenPortraitPutsTheControlsOverThePicture { + CGRect land = CGRectMake(0, 0, 874, 402), up = CGRectMake(0, 0, 402, 874); + UIEdgeInsets upInsets = UIEdgeInsetsMake(62, 0, 34, 0); + CGFloat a = up.size.width / up.size.height; + DmLayout split = dm_layout(up, upInsets, NO, CGRectNull, a); + DmLayout l = dm_layout_full_picture(split, up, NO, CGRectNull, a); + XCTAssertTrue(CGRectEqualToRect(l.area, up), @"%@", NSStringFromCGRect(l.area)); + XCTAssertEqualWithAccuracy(l.game.size.width, 402, 1); XCTAssertEqualWithAccuracy(l.game.size.height, 874, 1); + XCTAssertTrue(l.separated && CGRectEqualToRect(l.controls, split.controls), @"the controls keep their portrait arrangement"); + XCTAssertTrue(CGRectContainsRect(l.game, l.controls), @"and are drawn over the picture"); + DmLayout over = dm_layout(land, UIEdgeInsetsZero, NO, CGRectNull, DM_PICTURE_16_9); + DmLayout same = dm_layout_full_picture(over, land, NO, CGRectNull, DM_PICTURE_16_9); + XCTAssertTrue(CGRectEqualToRect(same.game, over.game) && CGRectEqualToRect(same.area, over.area), @"landscape as it was"); + DmLayout half = dm_layout(up, upInsets, YES, CGRectNull, a); + DmLayout halfFull = dm_layout_full_picture(half, up, YES, CGRectNull, a); + XCTAssertTrue(CGRectEqualToRect(halfFull.game, half.game) && CGRectEqualToRect(halfFull.area, half.area), @"a half-folded Duo keeps its split"); +} + +// A controller hides the touch controls: upright the picture takes the whole safe area; landscape and a half-folded Duo's split stay +- (void)testHiddenControlsGiveAnUprightPictureTheWholeScreen { + CGRect land = CGRectMake(0, 0, 874, 402), up = CGRectMake(0, 0, 402, 874); + UIEdgeInsets upInsets = UIEdgeInsetsMake(62, 0, 34, 0); + DmLayout l = dm_layout_controls_hidden(dm_layout(up, upInsets, NO, CGRectNull, DM_PICTURE_16_9), up, upInsets, NO, CGRectNull, DM_PICTURE_16_9); + XCTAssertFalse(l.separated); + XCTAssertTrue(CGRectEqualToRect(l.area, CGRectMake(0, 62, 402, 778)), @"%@", NSStringFromCGRect(l.area)); + XCTAssertTrue(CGRectEqualToRect(l.controls, up)); + XCTAssertEqualWithAccuracy(l.game.size.width, 402, 1, @"16:9 fits the width"); + DmLayout filled = dm_layout_picture(l, up, YES, DM_PICTURE_16_9); + XCTAssertTrue(CGRectEqualToRect(filled.game, l.game), @"Fill stays fitted upright: %@", NSStringFromCGRect(filled.game)); + DmLayout over = dm_layout(land, UIEdgeInsetsZero, NO, CGRectNull, DM_PICTURE_16_9); + DmLayout same = dm_layout_controls_hidden(over, land, UIEdgeInsetsZero, NO, CGRectNull, DM_PICTURE_16_9); + XCTAssertTrue(CGRectEqualToRect(same.game, over.game) && CGRectEqualToRect(same.area, over.area), @"landscape as it was"); + DmLayout half = dm_layout(up, upInsets, YES, CGRectNull, DM_PICTURE_16_9); + DmLayout halfHidden = dm_layout_controls_hidden(half, up, upInsets, YES, CGRectNull, DM_PICTURE_16_9); + XCTAssertTrue(halfHidden.separated && CGRectEqualToRect(halfHidden.area, half.area), @"a half-folded Duo keeps its split"); +} + +// In landscape the game is handed the whole view's shape, as before +- (void)testProductionRootReportsThePictureAreaShape { + UIViewController *root = [self harnessRootViewController]; + XCTAssertNotNil(root); + [root.view setNeedsLayout]; [root.view layoutIfNeeded]; + CGRect b = root.view.bounds; + BOOL duo = [[root valueForKey:@"hingeStatus"] integerValue] != 0; + DmLayout l = dm_layout(b, dm_game_safe_insets(b, root.view.safeAreaInsets, duo), [[root valueForKey:@"partiallyOpen"] boolValue], CGRectNull, DM_PICTURE_16_9); + XCTAssertEqualWithAccuracy(front_view_aspect(), l.area.size.width / l.area.size.height, 1e-3, @"area %@ in %@", NSStringFromCGRect(l.area), NSStringFromCGRect(b)); +} @end diff --git a/dm/tools/docs_patches.py b/dm/tools/docs_patches.py index d164f274b6..dca82546fc 100644 --- a/dm/tools/docs_patches.py +++ b/dm/tools/docs_patches.py @@ -173,18 +173,18 @@ def build_rows(gs): # {build ID: [(game, display version, module)]} return out -OTHER_BASE = 0x8000000 # where the dry run puts a MATCH_FRAME_STEP rule's other functions, 16 MB apart, so their sites read as offsets in them; its patch area starts at 0x6000000, - # within a b's reach (128 MB) of a main's sites below it and of up to six other functions above +OTHER_BASE = 0x8000000 # where the dry run puts a MATCH_FRAME_STEP rule's other functions, OTHER_SPAN apart, so their sites read as offsets in them; its patch area starts at +OTHER_SPAN = 0x400000 # 0x6000000, within a b's reach (128 MB) of a main's sites below it and of up to 24 other functions above (16 MB apart, Ocarina of Time's ninth was out of reach) def frame_step_sites(fn, base=0, others=(), found=None): # (offset, reason) of each site a FRAME_STEP function (or a MATCH_FRAME_STEP stub, its function at base) writes, whether it marks a pos, puts = [0x6000000], [] # render-scale stub, the sites in each of the rule's other functions ({label: [(offset, reason)]}) and the capabilities it declares def emit(w): pos[0] += 4 - at = {label: OTHER_BASE + i * 0x1000000 for i, label in enumerate(others)} + at = {label: OTHER_BASE + i * OTHER_SPAN for i, label in enumerate(others)} ctx = types.SimpleNamespace(here=lambda: pos[0], emit=emit, site=lambda off, orig: None, put=lambda off, words, why: puts.append((off, why)), state=0x9000000, render_scale=0, step_max=0, base=base, others=at, found=found, capabilities=set(), address=lambda off: 0) fn(ctx) - in_others = {label: sorted((off - a, why) for off, why in puts if a <= off < a + 0x1000000) for label, a in at.items()} + in_others = {label: sorted((off - a, why) for off, why in puts if a <= off < a + OTHER_SPAN) for label, a in at.items()} return sorted((off, why) for off, why in puts if off < OTHER_BASE), ctx.render_scale, in_others, sorted(ctx.capabilities) diff --git a/dm/tools/gpuprof.py b/dm/tools/gpuprof.py index b373c4e21b..5398b71eac 100755 --- a/dm/tools/gpuprof.py +++ b/dm/tools/gpuprof.py @@ -11,13 +11,16 @@ gpuprof.py log.txt --timeline 600 every encoder of frame 600 in GPU order, with the idle gaps between them gpuprof.py log.txt --ab the [ab] phases: medians per configuration and the difference from the base +With DM_NVN_GPUPROF_GEOM=1 a render pass line ends in "geom " (from the pass's start to where its vertex and mesh stages finish): the timeline splits each pass into +geometry and the time after it, and the table adds the mean geometry ms per frame of each group. + Times are GPU timestamps taken where each encoder begins and ends (relaxed: encoders may overlap), so the sum over encoders is not the frame's GPU time; the frame line's span (first start to last end) is closer to it. See docs/agents/05-debugging.md, "GPU time on the device". """ import argparse, collections, re, statistics, sys ENC = re.compile(r'\[gpuprof\] F(\d+)\s+(\d+)\s+([\d.]+) us (render pass|compute / copy)(.*)') -RP = re.compile(r'^ (\d+) (\d+)x(\d+) colors (\d+) depth (\d+) loads (\d+) draws (\d+) start ([+-][\d.]+) seg (\d+)(?: load (\d+) KB store (\d+) KB)?(?: fmt (\d+)/(\d+))?') +RP = re.compile(r'^ (\d+) (\d+)x(\d+) colors (\d+) depth (\d+) loads (\d+) draws (\d+) start ([+-][\d.]+) seg (\d+)(?: load (\d+) KB store (\d+) KB)?(?: fmt (\d+)/(\d+))?(?: geom ([\d.]+))?') CP = re.compile(r'^ after pass (\d+) start ([+-][\d.]+) seg (\d+) copies (\d+) \(uniform updates (\d+)\) dispatches (\d+)') FRAME = re.compile(r'\[gpuprof\] frame (\d+): render ([\d.]+) ms, compute / copy ([\d.]+) ms over (\d+) encoders.*?first start to last end ([\d.]+) ms') AB = re.compile(r'\[ab\] phase (\d+) (\S+): (\d+) frames, GPU p50 ([\d.]+) / p90 ([\d.]+) / mean ([\d.]+) ms, frame p50 ([\d.]+) / p90 ([\d.]+) / mean ([\d.]+) ms' @@ -39,7 +42,8 @@ def fmt_name(v): return MTL_FORMATS.get(v, str(v)) if v else '-' -Enc = collections.namedtuple('Enc', 'frame idx us kind pass_ w h colors depth loads draws start seg load_kb store_kb cfmt dfmt copies ubd dispatches') +# geom: us from a render pass's start to where its vertex and mesh stages finish (DM_NVN_GPUPROF_GEOM=1), None without +Enc = collections.namedtuple('Enc', 'frame idx us kind pass_ w h colors depth loads draws start seg load_kb store_kb cfmt dfmt copies ubd dispatches geom', defaults=(None,)) def parse(lines): @@ -55,7 +59,8 @@ def parse(lines): if not r: continue g = [int(x) if x is not None else 0 for x in (r.group(1), r.group(2), r.group(3), r.group(4), r.group(5), r.group(6), r.group(7))] e = Enc(f, idx, us, 'R', g[0], g[1], g[2], g[3], g[4], g[5], g[6], float(r.group(8)), int(r.group(9)), - int(r.group(10) or 0), int(r.group(11) or 0), int(r.group(12) or 0), int(r.group(13) or 0), 0, 0, 0) + int(r.group(10) or 0), int(r.group(11) or 0), int(r.group(12) or 0), int(r.group(13) or 0), 0, 0, 0, + float(r.group(14)) if r.group(14) else None) else: c = CP.match(rest) if not c: continue @@ -119,6 +124,18 @@ def aggregate(frames, by='shape', only=None): return rows, nf +def geom_means(frames, by='shape', only=None): + """Mean geometry us per frame of each group that has DM_NVN_GPUPROF_GEOM stamps ({group: us}; empty without them)""" + tot, nf = collections.defaultdict(float), 0 + for f, es in frames.items(): + if only and f not in only: continue + nf += 1 + ref = max((e.w * e.h for e in es if e.kind == 'R' and e.colors), default=0) + for e in es: + if e.geom is not None: tot[shape_key(e) if by == 'shape' else class_key(e, ref)] += e.geom + return {k: v / nf for k, v in tot.items()} if nf else {} + + def parse_ab(lines): out = [] for line in lines: @@ -188,7 +205,8 @@ def main(argv=None): gap = max(0.0, e.start - end); end = max(end, e.start + e.us) if e.kind == 'R': what = (f'pass {e.pass_} {e.w}x{e.h} {e.colors}c{"+d" if e.depth else ""} draws {e.draws} loads {e.loads} ' - f'load {e.load_kb} KB store {e.store_kb} KB {fmt_name(e.cfmt)}/{fmt_name(e.dfmt)}') + f'load {e.load_kb} KB store {e.store_kb} KB {fmt_name(e.cfmt)}/{fmt_name(e.dfmt)}' + + (f' | geometry {e.geom:.1f} us, after it {e.us - e.geom:.1f} us' if e.geom is not None else '')) else: what = f'compute / copy after pass {e.pass_}: copies {e.copies} (uniform updates {e.ubd}) dispatches {e.dispatches}' print(f' {e.idx:4d} +{e.start:9.1f} {e.us:8.1f}{" gap %.1f" % gap if gap >= 1 else "":>12s} {what}') @@ -203,11 +221,13 @@ def main(argv=None): rows, nf = aggregate(frames, a.by, only) tot = sum(r[2] for r in rows) or 1 print(f'\nmean per frame over {nf} frames, by {a.by}:') - print(f' {"group":52s} {"passes":>7s} {"ms":>7s} {"share":>6s} {"us/pass":>8s} {"draws":>7s} {"load MB":>8s} {"store MB":>8s}') + geo = geom_means(frames, a.by, only) + print(f' {"group":52s} {"passes":>7s} {"ms":>7s} {"share":>6s} {"us/pass":>8s} {"draws":>7s} {"load MB":>8s} {"store MB":>8s}' + (f' {"geom ms":>8s}' if geo else '')) shown, rest = rows[:a.top], rows[a.top:] if rest: shown = shown + [('other (%d groups)' % len(rest), sum(r[1] for r in rest), sum(r[2] for r in rest), sum(r[3] for r in rest), sum(r[4] for r in rest), sum(r[5] for r in rest))] for k, n, us, dr, ld, st in shown: - print(f' {k:52s} {n:7.1f} {us / 1e3:7.2f} {100 * us / tot:5.1f}% {us / n if n else 0:8.1f} {dr:7.0f} {ld / 1024:8.1f} {st / 1024:8.1f}') + g = (f' {geo[k] / 1e3:8.2f}' if k in geo else f' {"-":>8s}') if geo else '' + print(f' {k:52s} {n:7.1f} {us / 1e3:7.2f} {100 * us / tot:5.1f}% {us / n if n else 0:8.1f} {dr:7.0f} {ld / 1024:8.1f} {st / 1024:8.1f}' + g) print(f' {"total":52s} {sum(r[1] for r in rows):7.1f} {tot / 1e3:7.2f}') return 0 diff --git a/dm/tools/lint_python_baseline.tsv b/dm/tools/lint_python_baseline.tsv index ad81da4a0d..96a17204f0 100644 --- a/dm/tools/lint_python_baseline.tsv +++ b/dm/tools/lint_python_baseline.tsv @@ -207,7 +207,6 @@ ruff dm/tools/patch_nso.py B023 1 Function definition does not bind loop variabl ruff dm/tools/patch_nso.py B023 2 Function definition does not bind loop variable `n` ruff dm/tools/patch_nso.py PIE808 1 Unnecessary `start` argument in `range` ruff dm/tools/sdis.py F841 1 Local variable `lo` is assigned to but never used -ruff dm/tools/tests/test_gpuprof.py F401 1 `os` imported but unused ruff dm/tools/tests/test_gpuprof.py F401 1 `sys` imported but unused ruff dm/tools/tests/test_image_atomic_bounds.py B023 1 Function definition does not bind loop variable `dependencies` ruff dm/tools/tests/test_nsp_incremental.py B023 1 Function definition does not bind loop variable `build` diff --git a/dm/tools/tests/test_gpuprof.py b/dm/tools/tests/test_gpuprof.py index 243e64d810..f06d42b95e 100644 --- a/dm/tools/tests/test_gpuprof.py +++ b/dm/tools/tests/test_gpuprof.py @@ -55,6 +55,25 @@ def test_parse(self): self.assertEqual(self.flines[600], {'render_ms': 0.71, 'compute_ms': 0.03, 'encoders': 5, 'span_ms': 0.76}) self.assertEqual(self.flines[1200]['span_ms'], 0.91) + def test_geom(self): + # DM_NVN_GPUPROF_GEOM: a pass line ending in its geometry time parses and is grouped; lines without it give None and no column + self.assertIsNone(self.frames[600][0].geom); self.assertEqual(gpuprof.geom_means(self.frames), {}) + frames, _ = gpuprof.parse([rp(600, 0, 300.0, 24, 1600, 900, 1, 1, 50, 0.0, 5625, 5625, 92, 252) + ' geom 120.5', + rp(600, 1, 100.0, 25, 1600, 900, 1, 0, 1, 300.0, 5625, 5625, 115, 0)]) + e = frames[600][0] + self.assertEqual((e.geom, e.dfmt, e.draws), (120.5, 252, 50)) + self.assertIsNone(frames[600][1].geom) + self.assertEqual(gpuprof.geom_means(frames), {'1600x900 1c+d RG11B10Float/Depth32Float': 120.5}) + out = io.StringIO() + with tempfile.NamedTemporaryFile('w', suffix='.log', delete=False) as f: f.write('\n'.join(LOG[:1] + [rp(600, 0, 300.0, 24, 1600, 900, 1, 1, 50, 0.0, 5625, 5625, 92, 252) + ' geom 120.5']) + '\n') + try: + with contextlib.redirect_stdout(out): self.assertEqual(gpuprof.main([f.name, '--timeline', '600']), 0) + self.assertIn('geometry 120.5 us, after it 179.5 us', out.getvalue()) + out = io.StringIO() + with contextlib.redirect_stdout(out): self.assertEqual(gpuprof.main([f.name]), 0) + self.assertIn('geom ms', out.getvalue()); self.assertIn(' 0.12', out.getvalue()) + finally: os.unlink(f.name) + def test_frame_stats(self): s = gpuprof.frame_stats(self.frames[600]) self.assertEqual((s['encoders'], s['passes'], s['draws']), (5, 4, 802)) diff --git a/dm/tools/tests/test_launcher_settings.py b/dm/tools/tests/test_launcher_settings.py index db5bfb597f..3262642adf 100644 --- a/dm/tools/tests/test_launcher_settings.py +++ b/dm/tools/tests/test_launcher_settings.py @@ -72,10 +72,16 @@ def test_hold_frames_takes_on_and_off(self): # the host reads DM_FPS_HOLD as o s = build(BOTW, 'nvn')['DM_SHOW_FPS'] self.assertEqual((s['on'], s['off']), ('1', '0')) + def test_portrait_layout_only_for_a_picture_of_any_shape_on_the_iphone(self): # a shown condition of two parts (&): screen_aspect any, and iOS + oot = '0400486024DEC000' # Ocarina of Time: screen_aspect any + self.assertEqual(build(oot, 'nvn')['DM_PORTRAIT_LAYOUT']['default'], 'full') + self.assertNotIn('DM_PORTRAIT_LAYOUT', build(oot, 'nvn', 'mac')) + self.assertNotIn('DM_PORTRAIT_LAYOUT', build(BOTW, 'nvn')) # screen_aspect on: a 16:9 or taller picture stays above the controls + def test_iphone_switches_only_on_the_iphone(self): # the frame-rate counter and touch feedback are the iOS front end's (front_ios.m, DmGamepad.m) ios, mac = build(BOTW, 'nvn'), build(BOTW, 'nvn', 'mac') self.assertEqual(build(BOTW, 'nvn', 'ios').keys(), ios.keys()) # ios when unset - self.assertEqual(set(ios) - set(mac), {'DM_SHOW_FPS', 'DM_TOUCH_HAPTICS', 'DM_PICTURE_FIT'}) + self.assertEqual(set(ios) - set(mac), {'DM_SHOW_FPS', 'DM_TOUCH_HAPTICS', 'DM_PICTURE_FIT', 'DM_ROTATION'}) self.assertIn('DM_RUMBLE', mac); self.assertIn('DM_METAL_HUD', mac) self.assertEqual(set(mac) - set(ios), {'DM_FULLSCREEN', 'DM_SW2'}) # the Mac window's Display mode (front_mac.m reads 1 or 0); Switch 2 controllers (pad_switch2_apple.m, wired on the Mac only) s = mac['DM_FULLSCREEN'] diff --git a/dm/tools/tests/test_oot_aspect.py b/dm/tools/tests/test_oot_aspect.py new file mode 100644 index 0000000000..22d3478dce --- /dev/null +++ b/dm/tools/tests/test_oot_aspect.py @@ -0,0 +1,441 @@ +"""Execute Ocarina of Time's emitted screen-shape stubs on ARM64, without game files. + +Optional dependency: unicorn. On macOS its JIT needs execution outside the sandbox. +""" +import importlib +import importlib.util +from pathlib import Path +import struct +import sys +import types +from typing import Any +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +uc: Any = None # unicorn and its ARM64 constants when installed (typed Any: the tests are skipped without it) +arm: Any = None +try: + uc, arm = importlib.import_module('unicorn'), importlib.import_module('unicorn.arm64_const') +except ImportError: + pass + +spec = importlib.util.spec_from_file_location('oot_patches', Path(__file__).resolve().parents[2] / 'games/0400486024DEC000/patches.py') +assert spec is not None and spec.loader is not None +patch = importlib.util.module_from_spec(spec); spec.loader.exec_module(patch) + + +def camera(r, cap: float = 1.0): + """The camera's x / y multipliers the loader writes for a shape (loader.c screen_camera), upright held to the vertical angle of a picture of shape cap (screen_upright_cap, + DM_SCREEN_UPRIGHT_FOV: 1 by default, 0 off)""" + if not r: return (1, 1) + l = r if r >= 1 else 1 / r + xl, yl = (16 / 9 / l, 1) if l >= 16 / 9 else (1, l * 9 / 16) + x, y = (xl, yl) if r >= 1 else (yl * 16 / 9, xl * 9 / 16) + if cap and r < 1 and r < cap: + ky = camera(cap, 0)[1] + if y < ky: x, y = ky * 16 / (9 * r), ky + return x, y + + +@unittest.skipIf(uc is None, 'optional ARM64 execution dependency: unicorn') +class OutputSize(unittest.TestCase): + # The setter's first instruction (ldp w8,w9,[x0,#0x10]) at SITE in a code area; the stub branches back to SITE + 4 + base, area, state, obj, req = 0x4000000, 0x4100000, 0x4200000, 0x6000000, 0x6001000 + SITE = 0x1000 + + def setUp(self): + self.u = uc.Uc(uc.UC_ARCH_ARM64, uc.UC_MODE_ARM) + for a, n in ((self.base, 0x100000), (self.area, 0x10000), (self.state, 0x4000), (self.obj, 0x2000)): + self.u.mem_map(a, n) + self.u.mem_write(self.base + self.SITE, struct.pack('<2I', 0x29422408, 0xd503201f)) # ldp w8,w9,[x0,#0x10]; nop + self.cursor = self.area - self.base + self.ctx = types.SimpleNamespace(here=lambda: self.cursor, emit=self.emit, site=lambda off, orig: None, put=self.put, + state=self.state - self.base, others={'output size': self.SITE}) + patch.screen_shape(self.ctx) + self.u.mem_write(self.obj + 0x10, struct.pack('<2I', 1111, 2222)) # the size the settings hold now + + def emit(self, w): + self.u.mem_write(self.base + self.cursor, struct.pack(' pixels: + s = (pixels / (f[1] * f[2])) ** 0.5; f = (ratio, f[1] * s, f[2] * s) + self.u.mem_write(self.state + 0xa0, struct.pack('<3f', *f)) + self.u.mem_write(self.state + 0xc4, struct.pack('<2f', *camera(ratio))) + + def call(self, w, h): + """Run the setter's entry with x1 -> {w, h}; the size it goes on with (x1's pair) and the registers its first instruction loads""" + self.u.mem_write(self.req, struct.pack('<2I', w, h)) + self.u.reg_write(arm.UC_ARM64_REG_X0, self.obj); self.u.reg_write(arm.UC_ARM64_REG_X1, self.req) + end = self.base + self.SITE + 4 + stop = self.u.hook_add(uc.UC_HOOK_CODE, lambda u, a, n, d: u.emu_stop(), begin=end, end=end) + try: self.u.emu_start(self.base + self.SITE, end, count=100) + finally: self.u.hook_del(stop) + self.assertEqual(self.u.reg_read(arm.UC_ARM64_REG_PC), end) + self.assertEqual((self.u.reg_read(arm.UC_ARM64_REG_W8), self.u.reg_read(arm.UC_ARM64_REG_W9)), (1111, 2222)) # the original first instruction ran + x1 = self.u.reg_read(arm.UC_ARM64_REG_X1) + self.assertEqual(struct.unpack('<2I', self.u.mem_read(self.req, 8)), (w, h)) # the caller's struct (the init's config) is never written + return x1, struct.unpack('<2I', self.u.mem_read(x1, 8)) + + def factors(self): return struct.unpack('<2f', self.u.mem_read(self.state + 0xb8, 8)) + + def test_16_9_is_the_setter_as_it_is(self): + self.u.mem_write(self.state + 0xb8, struct.pack('<2f', 1.2375, 1)) # from an earlier, wider size + self.shape(0) + self.assertEqual(self.call(2048, 1152), (self.req, (2048, 1152))) + self.assertEqual(self.factors(), (0, 0)) # the camera: 16:9 + + def test_the_camera_multipliers_go_with_the_size(self): + for ratio in (2.2, 1.43, 0.46): + self.shape(ratio); self.call(2048, 1152) + self.assertEqual(self.factors(), tuple(struct.unpack('<2f', struct.pack('<2f', *camera(ratio))))) + + def test_wider_keeps_the_height(self): + for ratio, docked, handheld in ((2.2, (2536, 1152), (1904, 864)), (2.4, (2768, 1152), (2072, 864)), (21 / 9, (2688, 1152), (2016, 864))): + self.shape(ratio) + self.assertEqual(self.call(2048, 1152), (self.state + 0xe0, docked), ratio) + self.assertEqual(self.call(1536, 864), (self.state + 0xe0, handheld), ratio) + + def test_taller_keeps_the_width(self): + for ratio, docked, handheld in ((1.43, (2048, 1432), (1920, 1344)), (1.3, (2048, 1576), (1920, 1480)), (4 / 3, (2048, 1536), (1920, 1440))): + self.shape(ratio) + self.assertEqual(self.call(2048, 1152), (self.state + 0xe0, docked), ratio) + self.assertEqual(self.call(1920, 1080), (self.state + 0xe0, handheld), ratio) + + def test_any_shape_keeps_the_pixels_in_bounds(self): + for ratio in (1179 / 2556, 0.75, 1.0, 3.0, 5.0): # an iPhone held upright, a portrait window, a square, ultrawide beyond 21:9 + self.shape(ratio) + _, (w, h) = self.call(2048, 1152) + self.assertLessEqual(w * h, 1.5 * 2048 * 1152 * 1.01, ratio) + self.assertGreater(w * h, 1.5 * 2048 * 1152 * 0.97, ratio) # scaled down only as far as the bound + self.assertLess(abs(w / h / ratio - 1), 0.01, ratio) + self.assertEqual((w % 8, h % 8), (0, 0)) + + def test_a_phone_upright(self): + # The iPhone 17 upright (screen shape 0.460, the game's handheld 1920x1080): 1200x2600 at the stub's 1.5x bound (the device log's "present: picture shape 1200x2600"), + # 976x2120 with DM_SCREEN_PIXELS=1 + self.shape(0.460) + self.assertEqual(self.call(1920, 1080)[1], (1200, 2600)) + self.shape(0.460, 1.0) + self.assertEqual(self.call(1920, 1080)[1], (976, 2120)) + + def test_a_lower_pixel_bound_from_the_loader(self): + for pixels in (0.5, 1.0, 1.25): + for ratio in (1179 / 2556, 0.460, 0.75, 1.3, 2.174, 3.0): + for req in ((1920, 1080), (2048, 1152), (1536, 864)): + self.shape(ratio); full = self.call(*req)[1] + self.shape(ratio, pixels); _, (w, h) = self.call(*req) + if full[0] * full[1] <= pixels * req[0] * req[1] * 1.01: + self.assertLessEqual(abs(w - full[0]) + abs(h - full[1]), 8, (pixels, ratio, req)) # under the bound already: as it is + continue + self.assertLessEqual(w * h, pixels * req[0] * req[1] * 1.02, (pixels, ratio, req)) + self.assertGreater(w * h, pixels * req[0] * req[1] * 0.96, (pixels, ratio, req)) # down to the bound only + self.assertLess(abs(w / h / ratio - 1), 0.012, (pixels, ratio, req)) # the same shape + self.assertEqual((w % 8, h % 8), (0, 0)) + + def test_the_shape_holds_to_a_multiple_of_8(self): + for ratio in (1.3, 1.43, 1.6, 2.0, 2.2, 2.4): + self.shape(ratio) + _, (w, h) = self.call(2048, 1152) + self.assertEqual((w % 8, h % 8), (0, 0)) + self.assertLess(abs(w / h / ratio - 1), 0.004, ratio) + + +@unittest.skipIf(uc is None, 'optional ARM64 execution dependency: unicorn') +class CameraProjection(unittest.TestCase): + # The camera copy's last matrix store (str q18,[x20,#0x30]) at FN + 0x2ec; the stub branches back after it. x19 the render camera, x20 its matrix (+0x148) + base, area, state, cam = 0x4000000, 0x4100000, 0x4200000, 0x6000000 + FN = 0x1000; SITE = FN + 0x2ec + M = (1.20628, 0, 0, 0, 0, 2.14451, 0, 0, 0, 0, -1.00001, -0.200001, 0, 0, -1, 0) # the game's 16:9 projection (fovy 50°, near 0.1) + + def setUp(self): + self.u = uc.Uc(uc.UC_ARCH_ARM64, uc.UC_MODE_ARM) + for a, n in ((self.base, 0x100000), (self.area, 0x10000), (self.state, 0x4000), (self.cam, 0x1000)): + self.u.mem_map(a, n) + self.u.mem_write(self.base + self.SITE, struct.pack('<2I', 0x3d800e92, 0xd503201f)) # str q18,[x20,#0x30]; nop + self.cursor = self.area - self.base + ctx = types.SimpleNamespace(here=lambda: self.cursor, emit=self.emit, site=lambda off, orig: None, put=self.put, state=self.state - self.base, others={'camera copy': self.FN}) + patch.camera_projection(ctx) + + emit, put = OutputSize.emit, OutputSize.put + + def shape(self, ratio, asked=None, cap: float = 1.0): + """The factors the output size was made with (state +0xb8 / +0xbc, 0 = 16:9) and, apart, the shape the host asks for now (+0xa0..: the camera ignores it)""" + f = lambda r: (r, max(r * 9 / 16, 1), max(16 / (9 * r), 1)) if r else (0, 1, 1) + self.u.mem_write(self.state + 0xa0, struct.pack('<3f', *f(ratio if asked is None else asked))) + self.u.mem_write(self.state + 0xb8, struct.pack('<2f', *camera(ratio, cap)) if ratio else bytes(8)) + + def run_copy(self): + """The matrix as the copy leaves it (rows 0..2 stored, row 3 in q18, rows 0 / 1 also in v4 / v5), aspect 16:9 at +0x1d4; the matrix, v4, v5 and the aspect after""" + m = struct.pack('<16f', *self.M) + self.u.mem_write(self.cam + 0x148, m[:48] + bytes(16)); self.u.mem_write(self.cam + 0x1d4, struct.pack(' 16 / 9: self.assertAlmostEqual(m[5], self.M[5], 5) # wider: the vertical angle kept + elif ratio >= 1: self.assertAlmostEqual(m[0], self.M[0], 5) # taller landscape: the horizontal angle kept + else: self.assertAlmostEqual(m[5], self.M[0], 4) # upright: no more height than a square, whose height gets landscape's horizontal angle + for a, b in zip(m[8:], self.M[8:]): self.assertAlmostEqual(a, b, 5) # z and w rows untouched + for a, b in zip(v4 + v5, m[:8]): self.assertAlmostEqual(a, b, 6) # the frustum code after reads the same rows + self.assertAlmostEqual(aspect, ratio, 3, ratio) + + + def test_upright_without_the_cap(self): + # DM_SCREEN_UPRIGHT_FOV=0: upright takes the scale of the same screen turned landscape (a phone sees about 90 degrees vertically) + for ratio in (0.7, 1179 / 2556, 9 / 16): + self.shape(ratio, cap=0) + m = self.run_copy()[0] + self.assertAlmostEqual(m[5] / m[0], ratio, 3, ratio) + if 1 / ratio >= 16 / 9: self.assertAlmostEqual(m[0], self.M[5], 4) # a phone upright: its width gets landscape's vertical angle + else: self.assertAlmostEqual(m[5], self.M[0], 4) # an iPad upright: its height gets landscape's horizontal angle + + def test_the_upright_cap_holds_the_vertical_angle(self): + tan = lambda m: 1 / m[5] # tan of half the vertical angle + for cap in (1, 0.75, 16 / 9): + self.shape(cap, cap=0); held = tan(self.run_copy()[0]) # the cap's own picture + for ratio in (min(cap, 1) - 0.05, 0.6, 1179 / 2556, 0.3): + self.shape(ratio, cap=cap); m = self.run_copy()[0] + self.assertAlmostEqual(tan(m), held, 4, (cap, ratio)) # no more height than the cap's picture + self.assertAlmostEqual(m[5] / m[0], ratio, 3, (cap, ratio)) # the picture keeps its own shape: the width narrows + self.assertAlmostEqual(tan(self.M), 1 / 2.14451, 5) # 16:9: fovy 50 degrees + self.shape(1.0, cap=0); square = tan(self.run_copy()[0]) + self.shape(1179 / 2556, cap=0); phone = tan(self.run_copy()[0]) + self.assertGreater(phone, 1.2 * square) # a phone upright saw about 90 degrees, a square 79 + self.shape(1.3, cap=16 / 9); m = self.run_copy()[0] + self.assertAlmostEqual(m[0], self.M[0], 5) # landscape is never capped + + +@unittest.skipIf(uc is None, 'optional ARM64 execution dependency: unicorn') +class ShapeChange(unittest.TestCase): + # The display update's flag load (ldp w11,w9,[x0,#8]) at FN + 0x18; the stub branches back after it + base, area, state, obj = 0x4000000, 0x4100000, 0x4200000, 0x6000000 + FN = 0x1000; SITE = FN + 0x18 + + def setUp(self): + self.u = uc.Uc(uc.UC_ARCH_ARM64, uc.UC_MODE_ARM) + for a, n in ((self.base, 0x100000), (self.area, 0x10000), (self.state, 0x4000), (self.obj, 0x1000)): + self.u.mem_map(a, n) + self.u.mem_write(self.base + self.SITE, struct.pack('<2I', 0x2941240b, 0xd503201f)) + self.cursor = self.area - self.base + patch.shape_change(types.SimpleNamespace(here=lambda: self.cursor, emit=self.emit, site=lambda off, orig: None, put=self.put, state=self.state - self.base, others={'display update': self.FN})) + self.u.mem_write(self.obj + 8, struct.pack('<2I', 0x1004, 0x2)) # flags, the mode word + + emit, put = OutputSize.emit, OutputSize.put + + def update(self): + self.u.reg_write(arm.UC_ARM64_REG_X0, self.obj) + end = self.base + self.SITE + 4 + stop = self.u.hook_add(uc.UC_HOOK_CODE, lambda u, a, n, d: u.emu_stop(), begin=end, end=end) + try: self.u.emu_start(self.base + self.SITE, end, count=50) + finally: self.u.hook_del(stop) + self.assertEqual(self.u.reg_read(arm.UC_ARM64_REG_W9), 0x2) + return self.u.reg_read(arm.UC_ARM64_REG_W11) + + def test_a_new_shape_recomputes_the_size_once(self): + self.u.mem_write(self.state + 0xac, struct.pack('= 1: self.assertTrue(abs(w - 3840) < 0.5 or abs(h - 2160) < 0.5, r) # landscape: the HUD keeps its size + self.assertAlmostEqual(c[0], 2 / w, 8, r); self.assertAlmostEqual(c[5], 2 / h, 8, r) + self.assertAlmostEqual(c[16], 2 / w, 8, r); self.assertAlmostEqual(c[21], -2 / h, 8, r) # the y-flipped copy too + for i in (2, 3, 10, 11, 14, 15, 18, 19, 26, 27, 30, 31): # z and w untouched + self.assertEqual(c[i], struct.unpack('<36f', self.block()[:0x90])[i], (r, i)) + + +@unittest.skipIf(uc is None, 'optional ARM64 execution dependency: unicorn') +class LayoutSize(unittest.TestCase): + # The getter (ldr x8,[x0]; add x0,x8,#0x200; ret) at FN; the screen's init at INIT calls it at +0x350 and +0x394 + base, area, state, obj, res = 0x4000000, 0x4100000, 0x4200000, 0x6000000, 0x6100000 + FN, INIT, CALLER = 0x1000, 0x8000, 0x9000 + + def setUp(self): + self.u = uc.Uc(uc.UC_ARCH_ARM64, uc.UC_MODE_ARM) + for a, n in ((self.base, 0x100000), (self.area, 0x10000), (self.state, 0x4000), (self.obj, 0x1000), (self.res, 0x1000)): + self.u.mem_map(a, n) + self.u.mem_write(self.base + self.FN, struct.pack('<3I', 0xf9400008, 0x91080100, 0xd65f03c0)) + self.cursor = self.area - self.base + patch.hud(types.SimpleNamespace(here=lambda: self.cursor, emit=self.emit, site=lambda off, orig: None, put=self.put, state=self.state - self.base, + others={'layout size': self.FN, 'screen init': self.INIT})) + self.u.mem_write(self.obj, struct.pack(':