From 4f4d6d57f6e762a06f3be196b5353311324fd7b8 Mon Sep 17 00:00:00 2001 From: Callan Barrett Date: Sat, 10 Oct 2026 19:56:22 +0800 Subject: [PATCH 1/2] feat(zaparoo): grant the native CRT scanout lease, and resync stuck axes ZAPAROO-SCANOUT-2 now has a NATIVE grant beside PROXY: on native CRT output the frontend may map Menu's video window through the scanout module, with no HDMI proxy. Only the v2 module profile is accepted. With Direct Video on and CRT mode off, the framebuffer mux is held away from the Linux console until the launcher's VT switch, so boot text is not shown before the frontend paints. After a launcher key check, a direction still held from an axis is compared with the kernel's current axis value. A direction the kernel no longer reports is released; one it still reports is logged, which points at the pad or its driver. The log heartbeat only stamps a tick when the log grew since the last one. --- ZAPAROO_FORK.md | 6 +- input.cpp | 3 + support/zaparoo/SCANOUT.md | 28 +++- support/zaparoo/alt_launcher.cpp | 57 +++++++- support/zaparoo/alt_launcher.h | 3 + support/zaparoo/launcher_axis_resync.inc | 131 ++++++++++++++++++ support/zaparoo/main_log.cpp | 10 +- support/zaparoo/scanout.cpp | 46 ++++-- support/zaparoo/scanout.h | 5 +- support/zaparoo/scanout_conflict.h | 8 ++ support/zaparoo/scanout_profile.cpp | 2 +- .../zaparoo/tests/scanout_profile_test.cpp | 19 ++- video.cpp | 2 +- 13 files changed, 290 insertions(+), 30 deletions(-) create mode 100644 support/zaparoo/launcher_axis_resync.inc diff --git a/ZAPAROO_FORK.md b/ZAPAROO_FORK.md index 832655e0b..46b121cab 100644 --- a/ZAPAROO_FORK.md +++ b/ZAPAROO_FORK.md @@ -65,14 +65,16 @@ non-blocking spawn) are intentionally omitted. | 37 | **Framebuffer geometry is always computed** | `video_fb_config()` records `fb_width`/`fb_height`/`brd_*` **before** deferring to `alt_launcher_handle_video_fb_config()`; the hook only replaces the enable and the kernel-module write. When the hook sat at the top of the function (`1d9c1e6`, beta 2/3), the menu process never assigned the geometry at all: `video_menu_bg()` built 0x0 wallpaper images (`Warning: bg1 is 0`), and the launch-time `video_fb_enable(0)` took `video_fb_set()`'s menu-background fallback and programmed a 0x0 framebuffer into the FPGA on the way into `fpga_load_rbf` → HDMI output died on every game launch from the frontend. A matching `video_fb_enable(0)` in `alt_launcher_shutdown()`'s no-child branch was tried and reverted: `app_restart()` calls that function a **second** time, after `fpga_load_rbf` has already loaded the game core, and `is_menu()` is a per-process cache of `orig_name` (`user_io.cpp:222`) so it is still true there. `video_fb_set()`'s menu-background fallback then flips the disable into `FB_EN` at menu geometry and writes it into the **new** core, killing every launch. Teardown video belongs on the live-child branch only, which runs before the reconfiguration | `video.cpp` (`video_fb_config`) | | 38 | **gcdb probes the gamepad node, never a touchpad** | gcdb resolves a mapping's `bN` entries by enumerating the probed evdev node's key bits (`get_ctrl_index_maps`); `hN.x` hat entries are arithmetic. A DualSense contributes a gamepad node and a Touchpad node with the same Phys/Uniq, merged by `mergedevs()`, and `input_cb` loads the shared map from whichever node reaches it first, caching the result by vid/pid. Probed through the touchpad, every face button maps to a touchpad code while the d-pad keeps working (a beta report: "d-pad moves, Open/Options/View do nothing", only with keyboard dongles present, which reorder `/dev/input`). `zaparoo_gcdb_probe_dev()` swaps a `QUIRK_DS4TOUCH` probe for the group's `QUIRK_DS4` sibling, and the pre-warm (row 22) only feeds merge-base, non-touchpad nodes. The merge base is only the first of a group's nodes in scan order, so a pad whose receiver also exposes keyboard or mouse interfaces could still be probed through the wrong one (zaparoo-frontend#455): any probe node without `BTN_GAMEPAD`/`BTN_JOYSTICK` bits is swapped for the group's node that has them, and left alone when there is none. Two adjacent upstream hardenings: `get_ctrl_index_maps` bounds its loops to `btn_map`'s size, and `gcdb_controller_idx` skips zeroed cache slots (an all-zero id used to match slot 0 and return an all-zero map as a hit) | `support/zaparoo/launcher_input_detect.inc` (`zaparoo_gcdb_probe_dev`, `zaparoo_prewarm_device_maps`), `input.cpp` (`input_cb` map load, 2-line hook), `gamecontroller_db.cpp` | | 39 | **`app_restart()` copies `exe` before the launcher teardown** | `user_io_init` honours a per-core `main=` (`[RA_*] main=MiSTer_RA`) with `app_restart(path, xml, getFullPath(cfg.main))`, and that pointer aliases file_io's single static `full_path`. `app_restart()` calls `alt_launcher_shutdown()` first, and `kill_stale_frontends()` (`getFullPath(s_launcher_path)`) plus a cold `alt_launcher_installed()` (`FileExists`) rewrite the buffer to `/media/fat/zaparoo/frontend`, so the `execl` re-launched Main **as the frontend binary**: no Main, black screen, `/tmp/CORENAME` stuck at `MENU`. `exe` is now copied to a private buffer before the teardown. Any pointer handed across `alt_launcher_shutdown()` must not alias `full_path` | `fpga_io.cpp` (`app_restart`, 3 lines beside the existing hook) | -| 40 | **Persistent Main log (`main.log`)** | Main's stdout goes to the console after a reboot, so the first-exit-after-boot slowness could not be captured with the `/tmp/mz.log` recipe (row 23). If `/media/fat/zaparoo/main.log` exists, a constructor dup2's it over stdout and stderr before `main()`, writes a start marker (pid, uptime, wall clock) per exec, rotates to `.old` above 8 MB, and starts a detached heartbeat thread that writes `[zt ]` every 250 ms so upstream's untimed lines can be placed against zlog's `t=`. Marker and heartbeat use `dprintf`, not `printf`: the `setvbuf` in `service_boot.cpp` may not have run yet and is only valid before the stream's first use. Touch the file to enable, delete it to disable; absent file, nothing runs | `support/zaparoo/main_log.cpp` (zero upstream hooks) | +| 40 | **Persistent Main log (`main.log`)** | Main's stdout goes to the console after a reboot, so the first-exit-after-boot slowness could not be captured with the `/tmp/mz.log` recipe (row 23). If `/media/fat/zaparoo/main.log` exists, a constructor dup2's it over stdout and stderr before `main()`, writes a start marker (pid, uptime, wall clock) per exec, rotates to `.old` above 8 MB, and starts a detached heartbeat thread that writes `[zt ]` at most every 250 ms, and only when the log has grown since the last stamp, so upstream's untimed lines can be placed against zlog's `t=` and an idle Main writes nothing to the SD card. Marker and heartbeat use `dprintf`, not `printf`: the `setvbuf` in `service_boot.cpp` may not have run yet and is only valid before the stream's first use. Touch the file to enable, delete it to disable; absent file, nothing runs | `support/zaparoo/main_log.cpp` (zero upstream hooks) | | 41 | **Late-appearing display keeps the frontend on the fallback video mode** | `read_edid()` bails silently when the ADV7513 does not sense HPD + monitor sense, so a TV powering up alongside the DE10 leaves `video_init()` on the built-in default (1280x720) and the frontend probes its render size against that: full-res instead of half. The MENU core exposes no HDMI interrupt pin, so upstream's `video_poll()` hot-plug re-init never runs and the wrong mode sticks until the next core load (observed: 34 minutes). The single 500 ms pre-spawn retry now polls out a 3 s hold window, and if the spawn still happens on the fallback mode the launcher watches the transmitter's sense bits for 30 s behind the running child and restarts it once the display answers. `video_reinit()` is spent only on a link down->up edge and at most 3 times per init, so a display that genuinely has no EDID is not flickered. Sense bits are read through a private `i2c_open(0x39)` handle, as `hdmi_cec.cpp` already does for the same chip. If upstream subsequently obtains EDID after that watch expires, a child spawned without EDID is restarted once to reprobe its geometry | `support/zaparoo/alt_launcher.cpp` (zero upstream hooks) | | 42 | **Physical-disc autorun** | Opt-in OSD setting (settings byte 3, off by default). While the menu core is active, a detached worker probes `/dev/sr0` through `/dev/sr7`. CDs use TOC and signature reads; any media accepted by `DVD_READ_STRUCT` is treated as DVD without mounting it. CD launch resolution has no extra config file: it probes known physical-CD provider binaries and uses each provider's MGL in its original directory (`MiSTer_Physical-CD` + `_Physical Disc Cores`, or `MiSTer-disc` + `_Disc_Cores`), preserving `same_dir="1"` behavior. DVDs launch the latest installed `DVD_YYYYMMDD.rbf`, falling back to `DVD_Player.rbf`. Audio and unknown discs are ignored. Detection stops outside the menu core, and the handled fingerprint prevents the same inserted disc relaunching after a return to menu until removal is observed. No physical-disc playback, mounting, or per-core support is included | `support/zaparoo/physical_cd_autorun.cpp/.h`, `support/zaparoo/settings.cpp/.h`, `support/zaparoo/launcher_pages.cpp/.h`, `scheduler.cpp` | | 43 | **Core liveness watchdog** | While frontend is active, polls the existing Core PID file every 2 s. A retained PID that no longer exists or does not identify Core's cached service executable/script triggers a memory diagnostic and the idempotent service ensure through a detached helper. Core owns stale-PID cleanup under its start gate; PID-reuse recovery requires matching Core support. Missing PID files are ignored and attempts are throttled to 30 s; this is a liveness heuristic, not proof of OOM or another specific exit cause | `support/zaparoo/core_watchdog.cpp/.h`; called from `support/zaparoo/save.cpp`'s existing `zaparoo_poll()` fork hook | -| 44 | **Frontend scanout and black handoff** | Exact-qualified HDMI scanout uses a v2 inherited socket slot lease; Main proxies complete UIO packets and remains the sole bus writer, so OSD/video queries stay live. Mismatched handshakes fall back to fb0. Startup stays black through video probing, with bounded fb0 fallback and no live-owner timeout. Failed child stops abort core loads, re-exec and script handoffs. Native CRT and Direct Video retain their existing paths | `support/zaparoo/scanout.cpp/.h`, `bootstrap.h`, `alt_launcher.cpp/.h`, `SCANOUT.md`; surgical hooks in `fpga_io.cpp`, `menu.cpp`, `user_io.cpp`, `video.cpp` | +| 44 | **Frontend scanout and black handoff** | Exact-qualified HDMI scanout uses a v2 inherited socket slot lease; Main proxies complete UIO packets and remains the sole bus writer, so OSD/video queries stay live. Mismatched handshakes fall back to fb0. Startup stays black through video probing, with bounded fb0 fallback and no live-owner timeout. Failed child stops abort core loads, re-exec and script handoffs. Native CRT is offered the same socket in native mode: after the same gating Main answers `ZAPAROO-SCANOUT-2 NATIVE`, meaning the verified module is loaded and the frontend may map the native video window through it; nothing is proxied and `owned()` / `bus_owned()` stay false. HDMI under Direct Video gets no offer and no black bootstrap. Module profiles must carry `zaparoo-scanout-v2-native` | `support/zaparoo/scanout.cpp/.h`, `bootstrap.h`, `alt_launcher.cpp/.h`, `SCANOUT.md`; surgical hooks in `fpga_io.cpp`, `menu.cpp`, `user_io.cpp`, `video.cpp` | | 45 | **Frontend input/FIFO liveness** | Noisy controllers cannot drain forever while the launcher is active; proxy mode uses nonblocking input polls. Stock Menu rumble diagnostics exclude the live frontend. Command FIFO parsing preserves fragmented lines and dispatches coalesced lines independently, discarding overlong/NUL-containing lines rather than executing truncations | `support/zaparoo/command_stream.h`, `tests/integration_test.cpp`; surgical `input.cpp` hooks | | 46 | **Menu snow without a frontend** | The Zaparoo menu core holds its idle video black so a frontend start has no snow flash, and on its own only shows snow behind the OSD. Kiosk mode, the idle screensaver's first stage and a quit frontend all have the OSD closed, so the background went black (zaparoo-frontend#503). Main now sets menu `status[10]` whenever no frontend owns or is about to take the screen: `zaparoo_menu_bg_init()` writes it right after the saved menu status is loaded (F1 saves the whole status word, so a stale bit must not survive into a frontend start), and `zaparoo_menu_bg_poll()` follows `alt_launcher_menu_snow_allowed()`, which is `!alt_launcher_owns_screen()` and not waiting to resume after a script. **Set = snow, clear = black**: the core resets with status 0 before Main has spoken, so clear has to be the black state. Mismatched pairs behave as before the bit existed (black except behind the OSD). Bit 9 is avoided because the retired v1 native CRT contract used it | `support/zaparoo/menu_bg.cpp/.h`, `alt_launcher.cpp` (`alt_launcher_menu_snow_allowed`), `user_io.cpp` (menu init), `zaparoo_poll()`; core side `rtl/zaparoo_snow_enable.sv` in `Menu_MiSTer` | | 47 | **Launcher VT reset on teardown** | The frontend is killed by signal on every core load and so never restores its VT: tty7 stays foreground in `KD_GRAPHICS`, and the kernel refuses to switch away from that, so a later `video_chvt()` blocks in `VT_WAITACTIVE` for good. Opening a manual from a game core's OSD froze Main (zaparoo-frontend#445). `alt_launcher_shutdown()` now calls `reset_launcher_tty()` in both branches, like every other teardown, and the doc viewer takes the same `alt_launcher_prepare_for_script()` / `alt_launcher_resume_after_script()` hand-off as `MENU_SCRIPTS_FB` | `alt_launcher.cpp` (`alt_launcher_shutdown`), `menu.cpp` `MENU_DOC_FILE_SELECTED` / `MENU_DOC_FILE_SELECTED_2` hooks | +| 48 | **No console text on Direct Video startup** | Under Direct Video `video_fb_set()` puts an enabled fb0 on the DAC through the VGA framebuffer mux, and the launcher re-asserts fb0 from queued startup onwards while another VT (boot text, a script) is still active. When the launcher VT is not active at `alt_launcher_init()` or `spawn()`, the launcher's own re-asserts keep fb0 enabled, so the child's `fb_cmd` is still accepted, but leave the mux off until `finalize_spawn()` has switched to tty7. Other callers of `video_fb_enable()` (OSD terminal, scripts, doc viewer, wallpaper) are untouched, as are HDMI and native CRT | `support/zaparoo/alt_launcher.cpp` (`arm_direct_video_hold`, `launcher_fb_reassert`, `finalize_spawn`), `video.cpp` (`video_fb_set` mux line) | +| 49 | **Held directions are checked against the axis** | `input_test` turns each axis into direction presses and keeps one edge per axis; only an event from that axis clears it, so a missed return to center leaves the direction held and the launcher repeating it (a beta device log: Down held 6.8 s after a tap, ended by the next d-pad press). While the launcher is active, an edge held past 200 ms is compared with the kernel's current value for that axis (`EVIOCGABS`), then every second. At rest: the direction is released and logged. Still deflected: one log line per hold, so a stuck device can be told from a held one. `SYN_DROPPED`, which upstream ignores, triggers the same check at once. A press is never synthesized; quirk devices and lightguns are skipped because `input_test` rewrites their ranges | `support/zaparoo/launcher_axis_resync.inc`, `input.cpp` (include plus 2 one-line hooks) | | 28 | **Early service start** | A `__attribute__((constructor))` runs `/media/fat/Scripts/zaparoo.sh -service start` before `main()`, so ahead of the core-1 affinity pin (a child would inherit it) and ahead of `FindStorage()`'s 30s USB wait. Double fork + `setsid()` and **no** `PR_SET_PDEATHSIG`, the inverse of `exec_launcher_child`: the service must survive the `app_restart()` re-exec every core load performs. The detached ensure helper is also reused by the Core liveness watchdog, restoring the saved startup CPU-affinity mask and closing inherited Main descriptors before exec. No marker file, the script is an ensure | `support/zaparoo/service_boot.cpp/.h` (zero upstream hooks) | --- diff --git a/input.cpp b/input.cpp index 2b93dd3d0..6173b156c 100644 --- a/input.cpp +++ b/input.cpp @@ -2954,6 +2954,7 @@ static void assign_player(int dev, int num, int force = 0) // separate support/zaparoo/ file but #included here because it needs this TU's // file-static device tables (input[]/pool[]/devInput/NUMDEV). #include "support/zaparoo/launcher_input_detect.inc" +#include "support/zaparoo/launcher_axis_resync.inc" static void input_cb(struct input_event *ev, struct input_absinfo *absinfo, int dev, bool menu_event) { @@ -5683,6 +5684,7 @@ int input_test(int getchar) memset(&ev, 0, sizeof(ev)); if (read(pool[i].fd, &ev, sizeof(ev)) == sizeof(ev)) { + zaparoo_axis_note_event(i, &ev); if (getchar) { if (ev.type == EV_KEY && ev.value >= 1) @@ -6382,6 +6384,7 @@ int input_poll(int getchar) if (getchar) return ret; uinp_check_key(); + zaparoo_axis_resync(); static int prev_dx = 0; static int prev_dy = 0; diff --git a/support/zaparoo/SCANOUT.md b/support/zaparoo/SCANOUT.md index a353213b7..adbd60cd1 100644 --- a/support/zaparoo/SCANOUT.md +++ b/support/zaparoo/SCANOUT.md @@ -7,14 +7,27 @@ without yielding inside a transaction. Its OSD, input and video queries can run between packets. Do not remove `fpga_io.cpp`'s direct-owner guards or grant access merely because an offer was exported or the child passed `--latch`. -Initial eligibility is HDMI (not Direct Video), with a profile matching both +Slot eligibility is HDMI (not Direct Video), with a profile matching both the running kernel release and its GNU build ID. Frontend finishes vmode/output probes before requesting access. Main waits for `finalize_spawn`, checks active mapping conflicts, optionally loads `/media/fat/zaparoo/modules///zaparoo_scanout.ko`, then acknowledges `ZAPAROO-SCANOUT-2` with `ZAPAROO-SCANOUT-2 PROXY` over the inherited -`SOCK_SEQPACKET` channel. Unknown kernels/native CRT receive no offer. Both old +`SOCK_SEQPACKET` channel. Unknown kernels receive no offer. Both old Main/new frontend and new Main/old direct-MMIO frontend reject the mismatched -handshake and fall back to fb0. Kernel ABI and FPGA scanout commands are unchanged. +handshake and fall back to fb0. FPGA scanout commands are unchanged. + +Native CRT (with or without Direct Video) gets the same socket in a distinct +native mode (`Offer::native`). The request, `finalize_spawn` wait, conflict scan +and module verification are identical; the acknowledgment is +`ZAPAROO-SCANOUT-2 NATIVE`. It tells the frontend the verified module is loaded, +so it may map the Menu core's native video window (`0x3A000000`, 3 MB) and use +the vblank wait through it instead of `/dev/mem`. It grants nothing else: no +slots, no proxy (packets are ignored, `ZAPAROO_SCANOUT_RASTER` is not exported), +and `owned()` / `bus_owned()` stay false, so no HDMI lease behavior switches on. +A denied or absent native offer leaves the frontend on its `/dev/mem` mapping. +Main keeps writing that window's control words through its own `/dev/mem` +mappings; its 3 MB blank after spawn completes before `finalize_spawn`, so +before any native grant. HDMI under Direct Video still receives no offer. Each subsequent packet contains little-endian u16 magic `0x5A52`, sequence, command, count and words. Only SET (`0x57`, 12 words), CAPS (`0x59`, 6 words), and @@ -42,7 +55,8 @@ asynchronous insmod child; it never unloads a module. Parent-death signaling and post-fork parent checks prevent frontend survival after Main. Active `mem_wc`, MagiK, Zaparoo and overlapping `/dev/mem` checks are conservative -cooperative checks, not a security boundary. Raw mappers can race them; +cooperative checks, not a security boundary. The `/dev/mem` check covers the +slots and the native video window for either grant. Raw mappers can race them; independent concurrent renderers remain unsupported. Build with the existing ARM GNU toolchain and `make` or `./docker-build.sh`. @@ -58,8 +72,9 @@ Local builds do not authorize deployment, force-loading or release-channel chang `scanout_profile.cpp` reads the bounded ELF note stream from `/sys/kernel/notes` and the seven-line `profile` file beside the selected module. The format is: magic `ZAPAROO-SCANOUT-PROFILE-1`, release, kernel build ID, module build ID, -module SHA-256, kernel source revision, and `zaparoo-scanout-v1-1080p`, each +module SHA-256, kernel source revision, and `zaparoo-scanout-v2-native`, each followed by a newline. Hex values are lowercase; no extra fields are accepted. +A v1 profile (`zaparoo-scanout-v1-1080p`) selects no module and gets no offer. Module hashing runs in the asynchronous loader child using `sha256sum`; hashing and insmod share an open file descriptor so renaming a package during update @@ -71,5 +86,4 @@ also fails closed. These checks detect incompatible or damaged installations; they do not authenticate packages against a privileged attacker. MagiK's Main-window mapping device participates in the existing conflict check. -The Zaparoo module ABI, slot addresses, UIO protocol and ownership lifecycle -remain unchanged. Unknown builds and old flat module layouts receive no offer. +Slot addresses, UIO protocol and ownership lifecycle remain unchanged. Unknown builds and old flat module layouts receive no offer. diff --git a/support/zaparoo/alt_launcher.cpp b/support/zaparoo/alt_launcher.cpp index 7124b1a58..6ac11d4fe 100644 --- a/support/zaparoo/alt_launcher.cpp +++ b/support/zaparoo/alt_launcher.cpp @@ -160,6 +160,8 @@ static bool s_gave_up = false; static bool s_init_pending = false; static bool s_native_crt = false; static uint8_t s_native_crt_mode = 0; +static bool s_dv_fb_hold = false; +static bool s_dv_fb_hidden = false; static bool s_resume_after_script = false; static bool s_script_resume_crt = false; static bool s_console_lease = false; @@ -723,6 +725,39 @@ static bool switch_to_vt(int vt) return active; } +static bool launcher_vt_active(void) +{ + int fd = open("/dev/tty0", O_RDONLY | O_CLOEXEC); + if (fd < 0) return false; + struct vt_stat st; + bool active = !ioctl(fd, VT_GETSTATE, &st) && st.v_active == s_vt; + close(fd); + return active; +} + +// Under Direct Video an enabled fb0 goes straight to the DAC, and until the +// launcher VT is active that is another VT's console text. Hold the launcher's +// own re-asserts off the output from queued startup until finalize_spawn has +// switched VT. fb0 itself stays enabled so the child's vmode is still accepted. +static void arm_direct_video_hold(void) +{ + bool hold = !s_native_crt && cfg.direct_video && !launcher_vt_active(); + if (hold && !s_dv_fb_hold) zlog("direct video: fb0 kept off the output until the VT switch"); + s_dv_fb_hold = hold; +} + +static void launcher_fb_reassert(void) +{ + s_dv_fb_hidden = s_dv_fb_hold; + video_fb_reassert(); + s_dv_fb_hidden = false; +} + +bool alt_launcher_hide_direct_video_fb(void) +{ + return s_dv_fb_hidden; +} + static void begin_bootstrap() { // Direct Video needs its separate VGA framebuffer mux; keep its old path. @@ -764,6 +799,11 @@ static void finalize_spawn(bool tty_ready) s_tty_deadline = 0; bool vt_ok = switch_to_vt(s_vt); zlog("finalize: tty_ready=%d vt_active=%d fb_state=%d", tty_ready, vt_ok, video_fb_state()); + if (s_dv_fb_hold) + { + s_dv_fb_hold = false; + zlog("direct video: fb0 on the output after the VT switch (vt_active=%d)", vt_ok); + } zaparoo_launcher::handoff(s_native_crt, [] { // The frontend configures /dev/fb0 before Qt starts. Only publish its // existing buffer here; rewriting the mode after Qt has painted clears @@ -793,6 +833,7 @@ static void spawn(void) path[sizeof(path) - 1] = '\0'; begin_bootstrap(); + arm_direct_video_hold(); user_io_osd_key_enable(0); clear_launcher_tty(); @@ -810,13 +851,16 @@ static void spawn(void) // HPS framebuffer is disabled. Re-assert without scheduling the launcher's // current geometry back into the kernel; that delayed write can otherwise // overwrite the child's smaller framebuffer after Qt has mapped it. - video_fb_reassert(); + launcher_fb_reassert(); printf("alt_launcher: %s\n", s_bootstrap.hidden() ? - "bootstrap black (mode probing enabled)" : "HPS framebuffer path enabled"); + "bootstrap black (mode probing enabled)" : s_dv_fb_hold ? + "HPS framebuffer path enabled, off the output until the VT switch" : "HPS framebuffer path enabled"); } s_scanout_ready = false; - zaparoo_scanout::prepare(!s_native_crt && !cfg.direct_video); + // Native CRT gets the native offer whether or not Direct Video is set. + zaparoo_scanout::prepare(s_native_crt ? zaparoo_scanout::Offer::native : + cfg.direct_video ? zaparoo_scanout::Offer::none : zaparoo_scanout::Offer::proxy); s_pid = fork(); if (s_pid < 0) { @@ -885,7 +929,7 @@ bool alt_launcher_handle_video_fb_config(void) // Own HDMI fb configuration from queued initialization through the live // child. This prevents pre-spawn module writes from landing after the // frontend's vmode, and publishes its geometry against later output changes. - video_fb_reassert(); + launcher_fb_reassert(); return true; } @@ -917,6 +961,7 @@ void alt_launcher_init(bool native_crt) s_init_pending = true; s_pending_logged = false; begin_bootstrap(); + arm_direct_video_hold(); zlog("init queued: native_crt=%d edid=%d fb_state=%d", native_crt, video_get_edid(NULL, NULL), video_fb_state()); } @@ -1104,7 +1149,7 @@ void alt_launcher_poll(void) { // Re-send scanout state without reconfiguring /dev/fb0 under Qt; // resetting the live kernel framebuffer clears it until dirty repaint. - video_fb_reassert(); + launcher_fb_reassert(); if (--s_hdmi_fb_reasserts_remaining > 0) { s_hdmi_fb_reassert_timer = GetTimer(2000); @@ -1225,7 +1270,7 @@ void alt_launcher_poll(void) { s_fb_watchdog_timer = GetTimer(250); if (!s_fb_watchdog_timer) s_fb_watchdog_timer = 1; - video_fb_reassert(); + launcher_fb_reassert(); zlog("watchdog: framebuffer was off, re-asserted (fb_state=%d)", video_fb_state()); } diff --git a/support/zaparoo/alt_launcher.h b/support/zaparoo/alt_launcher.h index 3795d6b4b..218773f37 100644 --- a/support/zaparoo/alt_launcher.h +++ b/support/zaparoo/alt_launcher.h @@ -57,6 +57,9 @@ void alt_launcher_respawn(void); bool alt_launcher_scheduler_sleep_enabled(void); // Preserves HDMI launcher fb0 across queued startup and live mode changes. bool alt_launcher_handle_video_fb_config(void); +// True only inside a launcher re-assert made before its VT is active: the +// Direct Video mux must stay off so fb0 shows no other VT's console text. +bool alt_launcher_hide_direct_video_fb(void); void alt_launcher_cfg_apply(void); uint16_t alt_launcher_fb_terminal_key(uint32_t mask, bool osd_button); diff --git a/support/zaparoo/launcher_axis_resync.inc b/support/zaparoo/launcher_axis_resync.inc new file mode 100644 index 000000000..d83d43d2c --- /dev/null +++ b/support/zaparoo/launcher_axis_resync.inc @@ -0,0 +1,131 @@ +// Zaparoo launcher: releases a direction whose axis has gone back to rest +// without Main seeing it. +// +// input_test() turns every axis into direction presses and remembers one edge +// per axis in input[dev].axis_edge. Only an event from that axis clears it, so +// a missed return to center leaves the direction held: the launcher sees a key +// that never comes up and keeps repeating it. An event can go missing when the +// kernel's queue for the device overflows (SYN_DROPPED, which input_test() +// does not act on), and the launcher path leaves the read loop early, which +// makes a backlog likelier than upstream's. +// +// So a held edge is checked against the axis value the kernel holds now. If +// the kernel says the axis is at rest, the direction is released. If it says +// the axis is still deflected, the hold came from the device or its driver and +// only the log records it. A press is never made up. +// +// #included into input.cpp like launcher_input_detect.inc, for the same +// reason: it needs that file's static device tables. + +// Hats and sticks all sit below ABS_MISC; nothing above it is a direction. +#define ZAP_AXIS_CODES 0x28 +#define ZAP_AXIS_FIRST_CHECK_MS 200 +#define ZAP_AXIS_RECHECK_MS 1000 +#define ZAP_AXIS_SCAN_MS 50 + +struct zaparoo_axis_hold +{ + uint8_t state; + uint8_t checks; + unsigned long check; +}; + +static zaparoo_axis_hold s_zaparoo_axis_hold[NUMDEV][ZAP_AXIS_CODES]; +static bool s_zaparoo_axis_dropped[NUMDEV]; +static unsigned long s_zaparoo_axis_scan = 0; + +static bool zaparoo_axis_is_hat(const struct input_absinfo *abs) +{ + return (abs->maximum == 1 && abs->minimum == -1) || (abs->maximum == 2 && abs->minimum == 0); +} + +// At rest by a wide margin: a hat off both ends, a stick inside half of the +// threshold input_test() presses a direction at. Anything nearer an edge is +// left to the device's own events. +static bool zaparoo_axis_at_rest(const struct input_absinfo *abs) +{ + if (zaparoo_axis_is_hat(abs)) return abs->value != abs->minimum && abs->value != abs->maximum; + int range = abs->maximum - abs->minimum + 1; + int center = abs->minimum + (range / 2); + int margin = (range * cfg.dpad_threshold) / 400; + return abs->value >= center - margin && abs->value <= center + margin; +} + +// Every event read from a device passes through here, EV_SYN included. +static void zaparoo_axis_note_event(int i, const struct input_event *ev) +{ + if (ev->type != EV_SYN || ev->code != SYN_DROPPED || !alt_launcher_active()) return; + if (!s_zaparoo_axis_dropped[i]) printf("zaparoo_input: %s dropped events; rechecking held directions\n", input[i].devname); + s_zaparoo_axis_dropped[i] = true; +} + +static void zaparoo_axis_resync() +{ + if (!alt_launcher_active()) return; + + bool dropped = false; + for (int i = 0; i < NUMDEV; i++) dropped |= s_zaparoo_axis_dropped[i]; + if (!dropped && s_zaparoo_axis_scan && !CheckTimer(s_zaparoo_axis_scan)) return; + s_zaparoo_axis_scan = GetTimer(ZAP_AXIS_SCAN_MS); + + for (int i = 0; i < NUMDEV; i++) + { + bool recheck = s_zaparoo_axis_dropped[i]; + s_zaparoo_axis_dropped[i] = false; + + // input_test() rewrites the ranges of quirk devices before it derives + // an edge; the raw kernel value says nothing about those. + if (pool[i].fd < 0 || input[i].mouse || input[i].quirk) continue; + int dev = i; + if (input[dev].bind >= 0) dev = input[dev].bind; + if (input[dev].lightgun) continue; + + for (int code = 0; code < ZAP_AXIS_CODES; code++) + { + zaparoo_axis_hold *hold = &s_zaparoo_axis_hold[i][code]; + uint8_t state = input[dev].axis_edge[code]; + if (!state) + { + hold->state = 0; + continue; + } + if (hold->state != state) + { + hold->state = state; + hold->checks = 0; + hold->check = GetTimer(ZAP_AXIS_FIRST_CHECK_MS); + } + if (!recheck && !CheckTimer(hold->check)) continue; + hold->check = GetTimer(ZAP_AXIS_RECHECK_MS); + + // Bound nodes share one edge table; only the node that has + // this axis can answer for it. + struct input_absinfo abs; + if (ioctl(pool[i].fd, EVIOCGABS(code), &abs) < 0 || abs.maximum == abs.minimum) continue; + + if (!zaparoo_axis_at_rest(&abs)) + { + // Past the first recheck this is a hold of over a second. + // One line per hold tells a stuck device from a held one. + if (hold->checks == 1) + { + printf("zaparoo_input: %s axis %d held at edge %d; kernel value %d [%d..%d]\n", + input[i].devname, code, state, abs.value, abs.minimum, abs.maximum); + } + if (hold->checks < 2) hold->checks++; + continue; + } + + printf("zaparoo_input: %s axis %d released: Main held edge %d, kernel value %d [%d..%d]\n", + input[i].devname, code, state, abs.value, abs.minimum, abs.maximum); + input[dev].axis_edge[code] = 0; + hold->state = 0; + + struct input_event ev = {}; + ev.type = EV_KEY; + ev.value = 0; + ev.code = KEY_EMU + (code << 1) - 1 + state; + input_cb(&ev, zaparoo_axis_is_hat(&abs) ? 0 : &abs, i); + } + } +} diff --git a/support/zaparoo/main_log.cpp b/support/zaparoo/main_log.cpp index 6945a409f..54f585cc2 100644 --- a/support/zaparoo/main_log.cpp +++ b/support/zaparoo/main_log.cpp @@ -1,8 +1,8 @@ // Persistent Main log for beta diagnostics, enabled by the presence of // /media/fat/zaparoo/main.log (touch to enable, delete to disable). stdout and // stderr are appended to it from before main(), so the fd survives every -// app_restart() re-exec and a reboot, and a heartbeat thread stamps the stream -// with uptime so upstream's untimed output can be placed against zlog's t=. +// app_restart() re-exec and a reboot, and a heartbeat thread stamps new output +// with uptime so upstream's untimed lines can be placed against zlog's t=. #include #include #include @@ -24,10 +24,16 @@ static unsigned long uptime_ms(void) static void *heartbeat(void *) { + off_t stamped = -1; for (;;) { usleep(s_heartbeat_ms * 1000); + // Only output that arrived since the last stamp needs one: an idle + // Main must not write to the SD card four times a second. + struct stat st; + if (fstat(STDOUT_FILENO, &st) || st.st_size == stamped) continue; dprintf(STDOUT_FILENO, "[zt %lu]\n", uptime_ms()); + if (!fstat(STDOUT_FILENO, &st)) stamped = st.st_size; } return NULL; } diff --git a/support/zaparoo/scanout.cpp b/support/zaparoo/scanout.cpp index 11a23c4bc..711271756 100644 --- a/support/zaparoo/scanout.cpp +++ b/support/zaparoo/scanout.cpp @@ -25,6 +25,7 @@ namespace zaparoo_scanout { namespace { const char request[] = "ZAPAROO-SCANOUT-2"; const char granted[] = "ZAPAROO-SCANOUT-2 PROXY"; +const char granted_native[] = "ZAPAROO-SCANOUT-2 NATIVE"; const char rejected[] = "ZAPAROO-SCANOUT-2 NO"; const char device[] = "/dev/zaparoo-scanout"; Profile selected_profile; @@ -36,6 +37,8 @@ pid_t loader_pid = 0; bool requested = false; bool granted_lease = false; bool proxied_lease = false; +Offer offer_mode = Offer::none; +bool native_lease = false; bool loader_tried = false; unsigned long long loader_started = 0; @@ -99,8 +102,7 @@ bool conflicting_mappings() conflict = true; break; } - unsigned long long limit = offset + end_addr - start; - if (offset < 0x23800000ULL && limit > 0x23000000ULL) + if (conflicting_physical_range(offset, offset + end_addr - start)) { conflict = true; break; @@ -114,9 +116,16 @@ bool conflicting_mappings() return conflict; } +// A native offer has no fb0 route: its child falls back to its own /dev/mem +// mapping of the native video window. +const char *fallback() +{ + return offer_mode == Offer::native ? "/dev/mem fallback" : "fb0 fallback"; +} + void deny(const char *reason) { - printf("zaparoo_scanout: fb0 fallback: %s\n", reason); + printf("zaparoo_scanout: %s: %s\n", fallback(), reason); if (parent_fd >= 0) send(parent_fd, rejected, sizeof(rejected) - 1, MSG_NOSIGNAL); close_fd(parent_fd); requested = false; @@ -190,6 +199,7 @@ void stop() requested = false; granted_lease = false; proxied_lease = false; + native_lease = false; if (loader_pid) { kill(loader_pid, SIGKILL); @@ -199,15 +209,16 @@ void stop() } } -void prepare(bool eligible) +void prepare(Offer offer) { stop(); owner_pid = getpid(); loader_tried = false; - if (!eligible || loader_pid) return; + offer_mode = offer; + if (offer == Offer::none || loader_pid) return; if (!select_profile(selected_profile)) { - printf("zaparoo_scanout: fb0 fallback: no exact kernel build profile\n"); + printf("zaparoo_scanout: %s: no exact kernel build profile\n", fallback()); return; } int sockets[2]; @@ -232,7 +243,8 @@ void child_environment() char value[24]; snprintf(value, sizeof(value), "%d", child_fd); setenv("ZAPAROO_SCANOUT_FD", value, 1); - setenv("ZAPAROO_SCANOUT_RASTER", "1", 1); + // Nothing is proxied after a native grant, RASTER included. + if (offer_mode == Offer::proxy) setenv("ZAPAROO_SCANOUT_RASTER", "1", 1); } void parent_started(pid_t pid) @@ -266,7 +278,7 @@ bool blank_framebuffer() bool poll(bool video_ready) { // Reap our own loader even when a denied/disconnected request is gone. - if (loader_pid && (parent_fd < 0 || granted_lease)) + if (loader_pid && (parent_fd < 0 || granted_lease || native_lease)) { int status; pid_t result = waitpid(loader_pid, &status, WNOHANG); @@ -280,6 +292,8 @@ bool poll(bool video_ready) stop(); return false; } + // A native lease carries no proxy: packets never execute or end it. + if (count > 0 && native_lease) return false; if (count > 0 && granted_lease) { // Main is the only bus writer. Never yield inside this transaction: @@ -315,13 +329,27 @@ bool poll(bool video_ready) } requested = true; } - if (!requested || granted_lease || !video_ready) return false; + if (!requested || granted_lease || native_lease || !video_ready) return false; if (conflicting_mappings()) { deny("another physical-memory client is active"); return false; } if (!ensure_module()) return false; + if (offer_mode == Offer::native) + { + // The verified module is loaded: the child may map the native video + // window through it. No slot or bus state changes, so this is not a + // grant to the caller and owned() stays false. + native_lease = true; + if (send(parent_fd, granted_native, sizeof(granted_native) - 1, MSG_NOSIGNAL) != (ssize_t)sizeof(granted_native) - 1) + { + stop(); + return false; + } + printf("zaparoo_scanout: frontend pid=%d may map the native video window\n", frontend_pid); + return false; + } // v2 grants slot ownership, never direct FPGA access. Legacy direct-bus // requests are rejected above, so mixed stacks safely fall back to fb0. proxied_lease = true; diff --git a/support/zaparoo/scanout.h b/support/zaparoo/scanout.h index c2db5c41c..f3e8df41c 100644 --- a/support/zaparoo/scanout.h +++ b/support/zaparoo/scanout.h @@ -6,7 +6,10 @@ // Private parent/child handshake. v2 grants scanout slots after video setup; // Main proxies complete UIO packets and remains the sole FPGA-bus writer. namespace zaparoo_scanout { -void prepare(bool eligible); +// What the child may be granted. A native grant covers the module's mapping of +// the Menu core's native video window: no slots, no proxy, no owned() state. +enum class Offer { none, proxy, native }; +void prepare(Offer offer); void child_environment(); void parent_started(pid_t pid); void stop(); diff --git a/support/zaparoo/scanout_conflict.h b/support/zaparoo/scanout_conflict.h index 00b22be56..1a01a2404 100644 --- a/support/zaparoo/scanout_conflict.h +++ b/support/zaparoo/scanout_conflict.h @@ -12,5 +12,13 @@ inline bool internal_mapping_process(long pid, pid_t main_pid, pid_t frontend_pi return pid > 0 && (pid == main_pid || pid == frontend_pid || pid == loader_pid); } +// Physical ranges the module maps: the HDMI scanout slots and the Menu core's +// native video window. limit is one past the last mapped byte. +inline bool conflicting_physical_range(unsigned long long offset, unsigned long long limit) +{ + return (offset < 0x23800000ULL && limit > 0x23000000ULL) || + (offset < 0x3A300000ULL && limit > 0x3A000000ULL); +} + } #endif diff --git a/support/zaparoo/scanout_profile.cpp b/support/zaparoo/scanout_profile.cpp index 4e50bc0a4..c02fc2822 100644 --- a/support/zaparoo/scanout_profile.cpp +++ b/support/zaparoo/scanout_profile.cpp @@ -88,7 +88,7 @@ bool parse_profile(const std::string &text, Profile &profile) lines[1].find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-") != std::string::npos || !hex(lines[2], 32, 128) || !hex(lines[3], 32, 128) || !hex(lines[4], 64, 64) || !hex(lines[5], 40, 40) || - lines[6] != "zaparoo-scanout-v1-1080p") return false; + lines[6] != "zaparoo-scanout-v2-native") return false; profile.release = lines[1]; profile.kernel_id = lines[2]; profile.module_id = lines[3]; profile.sha256 = lines[4]; profile.revision = lines[5]; profile.contract = lines[6]; return true; diff --git a/support/zaparoo/tests/scanout_profile_test.cpp b/support/zaparoo/tests/scanout_profile_test.cpp index d4949d03c..a942b8bbb 100644 --- a/support/zaparoo/tests/scanout_profile_test.cpp +++ b/support/zaparoo/tests/scanout_profile_test.cpp @@ -14,13 +14,30 @@ int main() assert(!internal_mapping_process(0, 10, 0, 0)); assert(!internal_mapping_process(-1, 10, 20, -1)); assert(!internal_mapping_process(30, 10, 20, 0)); + // HDMI slots and the native video window, one byte either side of each. + assert(conflicting_physical_range(0x23000000ULL, 0x23800000ULL)); + assert(conflicting_physical_range(0x237ff000ULL, 0x23801000ULL)); + assert(!conflicting_physical_range(0x22000000ULL, 0x23000000ULL)); + assert(!conflicting_physical_range(0x23800000ULL, 0x23801000ULL)); + assert(conflicting_physical_range(0x3A000000ULL, 0x3A300000ULL)); + assert(conflicting_physical_range(0x3A000000ULL, 0x3A001000ULL)); + assert(conflicting_physical_range(0x3A2ff000ULL, 0x3A301000ULL)); + assert(conflicting_physical_range(0x39fff000ULL, 0x3A000001ULL)); + assert(conflicting_physical_range(0x20000000ULL, 0x40000000ULL)); + assert(!conflicting_physical_range(0x39fff000ULL, 0x3A000000ULL)); + assert(!conflicting_physical_range(0x3A300000ULL, 0x3A301000ULL)); Profile profile; const std::string release = "6.18.38-MiSTer"; const std::string input = "ZAPAROO-SCANOUT-PROFILE-1\n" + release + "\n" + std::string(40, 'a') + "\n" + std::string(40, 'b') + "\n" + - std::string(64, 'c') + "\n" + std::string(40, 'd') + "\nzaparoo-scanout-v1-1080p\n"; + std::string(64, 'c') + "\n" + std::string(40, 'd') + "\nzaparoo-scanout-v2-native\n"; assert(parse_profile(input, profile)); assert(profile.release == release && profile.kernel_id == std::string(40, 'a')); + assert(profile.contract == "zaparoo-scanout-v2-native"); + // A v1 module has no native window mapping: its profile selects nothing. + std::string v1 = input; + v1.replace(v1.find("v2-native"), 9, "v1-1080p"); + assert(!parse_profile(v1, profile)); assert(!parse_profile(input + "extra\n", profile)); assert(!parse_profile(input.substr(0, input.size() - 1), profile)); std::string invalid = input; diff --git a/video.cpp b/video.cpp index 1d3f45aee..900bd791a 100644 --- a/video.cpp +++ b/video.cpp @@ -3649,7 +3649,7 @@ static void video_fb_set(int enable, int n, int update_module) } DisableIO(); - if (cfg.direct_video) set_vga_fb(enable); + if (cfg.direct_video) set_vga_fb(enable && !alt_launcher_hide_direct_video_fb()); if (is_menu()) user_io_status_set("[8:5]", (fb_enabled && !fb_num) ? 0xB : 0); } } From 606bcf24c7d9dfb7fa6cb94c47f4befa29b11b4d Mon Sep 17 00:00:00 2001 From: Callan Barrett Date: Sat, 10 Oct 2026 20:06:28 +0800 Subject: [PATCH 2/2] fix(zaparoo): hold Direct Video fb0 until the VT switch lands, retry failed log stamps Releasing the Direct Video hold after a failed VT switch put another VT's console on the DAC with no retry. Keep the hold and retry the switch, bounded so a VT that never activates cannot leave the output black. A failed heartbeat write no longer records the unstamped size, so the stamp is retried on the next pass. --- support/zaparoo/alt_launcher.cpp | 13 +++++++++++++ support/zaparoo/main_log.cpp | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/support/zaparoo/alt_launcher.cpp b/support/zaparoo/alt_launcher.cpp index 6ac11d4fe..cc8989e55 100644 --- a/support/zaparoo/alt_launcher.cpp +++ b/support/zaparoo/alt_launcher.cpp @@ -161,6 +161,7 @@ static bool s_init_pending = false; static bool s_native_crt = false; static uint8_t s_native_crt_mode = 0; static bool s_dv_fb_hold = false; +static int s_dv_vt_retries = 0; static bool s_dv_fb_hidden = false; static bool s_resume_after_script = false; static bool s_script_resume_crt = false; @@ -744,6 +745,7 @@ static void arm_direct_video_hold(void) bool hold = !s_native_crt && cfg.direct_video && !launcher_vt_active(); if (hold && !s_dv_fb_hold) zlog("direct video: fb0 kept off the output until the VT switch"); s_dv_fb_hold = hold; + s_dv_vt_retries = 0; } static void launcher_fb_reassert(void) @@ -801,6 +803,17 @@ static void finalize_spawn(bool tty_ready) zlog("finalize: tty_ready=%d vt_active=%d fb_state=%d", tty_ready, vt_ok, video_fb_state()); if (s_dv_fb_hold) { + // Releasing the hold on another VT puts its console text on the DAC, + // so retry the switch first. The retries are bounded: a VT that never + // activates must not leave the output black for good. + if (!vt_ok && s_dv_vt_retries < 6) + { + s_dv_vt_retries++; + s_tty_deadline = GetTimer(500); + if (!s_tty_deadline) s_tty_deadline = 1; + zlog("direct video: VT switch failed, fb0 held for retry %d", s_dv_vt_retries); + return; + } s_dv_fb_hold = false; zlog("direct video: fb0 on the output after the VT switch (vt_active=%d)", vt_ok); } diff --git a/support/zaparoo/main_log.cpp b/support/zaparoo/main_log.cpp index 54f585cc2..65b7221f9 100644 --- a/support/zaparoo/main_log.cpp +++ b/support/zaparoo/main_log.cpp @@ -32,7 +32,7 @@ static void *heartbeat(void *) // Main must not write to the SD card four times a second. struct stat st; if (fstat(STDOUT_FILENO, &st) || st.st_size == stamped) continue; - dprintf(STDOUT_FILENO, "[zt %lu]\n", uptime_ms()); + if (dprintf(STDOUT_FILENO, "[zt %lu]\n", uptime_ms()) < 0) continue; if (!fstat(STDOUT_FILENO, &st)) stamped = st.st_size; } return NULL;