diff --git a/dm/games/0100FF500E34A000/README.md b/dm/games/0100FF500E34A000/README.md index aca1a7cb..afb4d367 100644 --- a/dm/games/0100FF500E34A000/README.md +++ b/dm/games/0100FF500E34A000/README.md @@ -12,6 +12,43 @@ the opening battle take about 33 ms. The unsigned 1.1.2 IPA builds successfully (13.2 GiB), with all 15,129 shader libraries and a complete CRC check. Further story progression, saving / reloading and iPhone validation remain open. + +## Android (AYN Thor, Turnip v27.0.0-R1, 2026-11-25) + +New Game → Sword Valley prologue (Mechon M72, the M82 boss) → Colony 9: Shulk and Reyn's +first fights, the road into Colony 9 and the Commercial District, day to evening, save and load. + +- **Resolved: the Colony 9 roads drew black, then in black and grey blocks.** Four shaders + (`48b8ea8fad25398d`, `fe993ca274dfde1c`, `5119ea2c4c0a2211`, `efa9a20a7f820920`) read the + 1280x720 A2B10G10R10 targets (NVN format `0x3d`) as uint shader images: their raw 32-bit + words. The replay had no uint view of that packed format, so the images read as unbound + (`[RED] ... has no view of shape 0x81 (storage)`): black roads. `class_twin` (`vka_tex.c`) now + gives packed 4-byte formats R32_UINT / R32_SINT twins. With the view, the roads came out in + blocks: Turnip on a7xx keeps UBWC for an image whatever its view formats + (`ubwc_all_formats_compatible`), and the R32_UINT view read compressed data. An image whose + format list holds a view of another texel layout (not its sRGB / raw UNORM twin) is now made + with `VK_IMAGE_COMPRESSION_DISABLED_EXT` (`VK_EXT_image_compression_control`, `vka_dev.c`; + `DM_VK_UBWC_RAWVIEW=0` turns it off). `TU_DEBUG=noubwc` drew the roads right; `sysmem`, + `nolrz`, `DM_VK_UBWC=0` and `DM_VK_ZSHARE=0` did not. +- **Frame pacing:** the game times its own 30 fps (33.23 ms a frame) and presents at interval 1, + which beats against the Thor's 117.84 Hz panel (four refreshes are 33.94 ms): in SurfaceFlinger + about one frame in seven stayed five refreshes. `fps_limit 30` makes the host's limiter tick in + whole panel refreshes: 10,809 of 10,809 frames on screen for exactly four refreshes over six + minutes of Colony 9 (SurfaceFlinger `--latency` present times). +- **Resolved: about one boot in four crashed 1–4 s into `nnMain`** on a corrupt heap: `memset` + (`sdk+0xc9e24`) of a size read from a resource block's footer (`main+0x71e7b8` → `main+0x70a620`), + null `+0x68` at `main+0x721d88`, wild pointers at `main+0x6f248c` (the heap's free-list walk, the + same wild value `0x8082848b9197a1` in several boots) and `main+0x721728`. With or without a save + (3 of 12 with an empty save folder). Not changed by `core_preempt on`, a barrier after file reads, + `DM_SPIN=0`, `DM_AUDIO=0`, `DM_VK_WORKER=0`; one CPU (`taskset`): 6 of 12. The game takes two of + a core's threads (core 0: `main`, `resource_creater`, `WorkerThread0`) never to run at the same + moment, as on Horizon. `core_preempt lock` (`DM_CORE_LOCK`, `hle_thread.c`): a core's threads take + turns, a lock held in guest code and given up at SVCs, for the first 20 s (`DM_CORE_LOCK_SECS`). + 0 of 60 boots crashed (24 with the lock for good, 36 with the boot window). Held for good it cost + 2–3 hitches of 70–100 ms in 5 min of Colony 9 (`resource_creater` ran 100 ms in guest code while + the main thread waited for core 0); with the 20 s window, 9,026 of 9,026 frames at four refreshes + over the same 5 min route. +- **Open: save thumbnails are black.** `bfsgame00.tmb` (240x180 RGBA) holds 12 non-zero bytes. ## Memory The NPDM declares no system resource. The 4 GB guest reservation, diff --git a/dm/games/0100FF500E34A000/game.tsv b/dm/games/0100FF500E34A000/game.tsv index d71c565d..284b0bc8 100644 --- a/dm/games/0100FF500E34A000/game.tsv +++ b/dm/games/0100FF500E34A000/game.tsv @@ -10,6 +10,10 @@ name Xenoblade Chronicles: Definitive Edition ipa XenobladeChroniclesDefinitiveEdition.ipa app_category public.app-category.role-playing-games pad_layout full +# Android: the game times its own 30 fps (33.23 ms) while presenting at interval 1, which beats against the panel (AYN Thor 117.84 Hz: 4 refreshes = 33.94 ms): 1 frame in ~7 stayed 5 refreshes (SurfaceFlinger, 2026-11-25). The limiter ticks in whole panel refreshes: 10,809 of 10,809 frames at 4 over six minutes (README) +fps_limit 30 +# Android: about one boot in four corrupted the heap 1-4 s into nnMain (README); the game takes two threads of one core never running at the same moment: 0 of 60 boots crashed with this (the first 20 s) +core_preempt lock # ---- Versions ---- build v196608 1.1.2 main=92c78bb3dcbbc3f7a3caf601d7b85f7a subsdk0=5a7ada8dd7447c10aa244944f64d0aff sdk=ad3fdfbd62a5f4b082d385ffe420d440 diff --git a/dm/games/README.md b/dm/games/README.md index bd5d0ba7..7f5ebd2e 100644 --- a/dm/games/README.md +++ b/dm/games/README.md @@ -287,7 +287,7 @@ One row per profile; the notes are each profile's `README.md`. | `fps_steps
` | One row per main build, for a game whose framework runs a whole number of fixed steps each frame and presents at that many vsyncs, picking the count from a mode field: the framework at `[main + ]`, then `[that + each member]` (`` comma-separated, at most 3, or `-`), and the offsets of the mode and the step count in it. The frame rate cap (and the frame limit, whichever is lower) then holds 60, 30 or 20 fps with 1, 2 or 3 steps a frame, so the game keeps its speed (`hle_fpslock.c` `steps_tick`): 30 writes mode 2, 20 the count 3 and a mode that keeps it, 60 and 0 the game's own mode. No rewrite: the launcher's ordinary cap list. [A framework's fixed steps per frame hold the frame rate cap at full speed](../../docs/reference/frame-rate.md#a-frameworks-fixed-steps-per-frame-hold-the-frame-rate-cap-at-full-speed). Mario Kart World 1.8.0 | | `ue_fps_cvar` | Unreal Engine games: the console variable the host writes `fps_target` into (`hle_fpslock.c`). `t.MaxFPS` (the default) is the engine's frame limit; a game whose settings apply a variable of its own to `t.MaxFPS` names that one, or the next settings change sets the game's 30 again (SHIN MEGAMI TENSEI V: Vengeance: `Project.FrameRateLimit`). The rewriter finds it by its registered name, so a name set here must be in `dm/tools/ue_cvar.py`'s `NAMES` (a red line otherwise): [Unreal's frame limit and present interval, found by name](../../docs/reference/frame-rate.md#unreals-frame-limit-and-present-interval-found-by-name) | | `ue_texture_pool` | Unreal Engine games: megabytes of the texture streaming pool (`r.Streaming.PoolSize`) the host raises the game's own to, on the Mac (`hle_uecvar.c`; the rewriter finds the variable by its name, `dm/tools/ue_cvar.py`): past its pool the streamer drops the top mips of what is in view, and the Switch's pool is small (DRAGON QUEST VII Reimagined: 200 MB, 1000 on Windows). `0` (the default): the game's own pool. A larger value the game sets, or −1, stays. `DM_UE_TEXTURE_POOL` overrides it; on iOS only that switch turns it on (`Documents/env.txt`). An improvement over the Switch, not a fix: [Unreal's texture streaming pool](../../docs/reference/rendering.md#unreals-texture-streaming-pool) | -| `core_preempt` | `on` / `off` (the default): additionally check higher-priority runnable threads pinned to the caller's core after every thread SVC (`hle_thread.c`). `DM_PREEMPT=0` / `1` overrides it. Wake-triggered same-core handoffs apply to every game with either setting and wait until the threads the wake made runnable block, with no wall-clock cap. Metroid Dread no longer needs this key or its movie request-ring gates; see [Same-core wake handoffs](../../docs/reference/threads.md#same-core-wake-handoffs) | +| `core_preempt` | `on` / `off` (the default): additionally check higher-priority runnable threads pinned to the caller's core after every thread SVC (`hle_thread.c`). `DM_PREEMPT=0` / `1` overrides it. Wake-triggered same-core handoffs apply to every game with either setting and wait until the threads the wake made runnable block, with no wall-clock cap. Metroid Dread no longer needs this key or its movie request-ring gates; see [Same-core wake handoffs](../../docs/reference/threads.md#same-core-wake-handoffs). PEANUTS: `lock` instead: the guest threads of one core take turns as on Horizon (a core's lock held in guest code, given up at SVCs; `DM_CORE_LOCK=0` / `1` overrides): Xenoblade Chronicles: Definitive Edition corrupted its heap at boot one time in four without it | | `alloc_big_align` | `on` / `off` (the default): `nn::mem::StandardAllocator::Allocate` aligns blocks of 64 KB or more to 64 KB (`hle_os.c`). Vanillaware's engine (13 Sentinels: Aegis Rim, Unicorn Overlord) takes a memory pool's storage from malloc and cuts ring heaps out of it at 64 KB alignment relative to the pool's GPU address. On the Switch that address is big-page aligned; the host's is the CPU address, only 4 KB aligned, so the last ring heap does not fit and keeps base 0, and the game writes through a null pointer (13 Sentinels entering its first battle, Unicorn Overlord past the title screen) | | `shared_font` | Optional, decided by the game files without it (the SDK version the host reads from the `sdk` module, `loader.c` `dm_sdk_major`, and the imports of `main` and its NROs, `dm_game_imports`): what the shared-font address points at. `bfttf` (SDK 11 and later, when `main` imports `ScalableFontEngineHelper::Decode`) = the 8-byte BFTTF header (with the "already decoded" marker) followed by the TTF, which Mario passes to `Decode`; `ttf` = the TTF itself, which SDK 10 and older games hand straight to `ScalableFontEngine::LoadFont` (Super Mario 3D World + Bowser's Fury: with the header the engine fails with error 403 and the game crashes looking up a glyph; Odyssey, Link's Awakening, Age of Calamity and Three Houses alike) and Unity's player to FreeType (Patrick's Parabox: with the header its Japanese, Korean and Chinese text drew nothing). No profile sets it | | `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) | diff --git a/dm/games/game.py b/dm/games/game.py index ce84a04c..239190d4 100644 --- a/dm/games/game.py +++ b/dm/games/game.py @@ -166,8 +166,8 @@ def header(g): sys.exit(f"{g.id}: pso_gpu takes 1-4 whitespace-separated GPU architectures such as 'g18p applegpu_g19p' (each an optional applegpu_ prefix then an alphanumeric token; there is no none: omit the key for g18p with pso_mtl4 on, or no archive with pso_mtl4 off): {pg}") et = g.get('enc_thread', 'off') # Metal encoding on its own thread on the Mac by default (nvn_rec.h rec_on; on iOS it is on for every game; DM_NVN_ENC_THREAD overrides): on / off if et not in ('on', 'off'): sys.exit(f'{g.id}: enc_thread must be on or off: {et}') - cp = g.get('core_preempt', 'off') # same-core preemption approximation (hle_thread.c): on / off - if cp not in ('on', 'off'): sys.exit(f'{g.id}: core_preempt must be on or off: {cp}') + cp = g.get('core_preempt', 'off') # same-core preemption approximation (hle_thread.c): on / off; PEANUTS: lock, one core's threads take turns (DM_CORE_LOCK) + if cp not in ('on', 'off', 'lock'): sys.exit(f'{g.id}: core_preempt must be on, off or lock: {cp}') aba = g.get('alloc_big_align', 'off') # nn::mem::StandardAllocator::Allocate aligns blocks of 64 KB or more to 64 KB (hle_os.c; Vanillaware's memory pool storage): on / off if aba not in ('on', 'off'): sys.exit(f'{g.id}: alloc_big_align must be on or off: {aba}') sf = g.get('shared_font', 'bfttf') # what the shared-font address points at (hle_sdk16.c): bfttf = 8-byte header + TTF, ttf = the TTF alone @@ -423,7 +423,7 @@ def header(g): 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_DISPLAY_VERSIONS {vers}', f'#define DM_GAME_PRESENT_DISPLAY {int(pi == "display")}', - f'#define DM_GAME_CORE_PREEMPT {int(cp == "on")}', + f'#define DM_GAME_CORE_PREEMPT {2 if cp == "lock" else int(cp == "on")}', # PEANUTS: lock = DM_CORE_LOCK (hle_thread.c) f'#define DM_GAME_ALLOC_BIG_ALIGN {int(aba == "on")}', f'#define DM_GAME_FPS_TARGET {int(ft)}', f'#define DM_GAME_FPS_HOLD {int(fh == "on")}', diff --git a/dm/host/hle_thread.c b/dm/host/hle_thread.c index 8069b1f9..19b98794 100644 --- a/dm/host/hle_thread.c +++ b/dm/host/hle_thread.c @@ -62,6 +62,8 @@ typedef struct thr { struct { struct thr *by; uint64_t epoch; } hand[4]; int nhand; // the handoffs this thread was made runnable for (its waker's, then those the waker belonged to), until it blocks (note_runnable / hand_leave) _Atomic int *host_work; // points at the thread's dm_host_work (registered when the thread starts) int native_wait; // nesting depth of a blocking native HLE wait (G held) + _Atomic int preempt_req; // PEANUTS: DM_CORE_LOCK: a higher-priority thread of its core waits (on_preempt_sig) + int clk; // PEANUTS: DM_CORE_LOCK: the core whose lock this thread holds while it runs guest code (core_lock_take), -1 none int host_owned; // a guest thread the host created itself (dm_guest_thread_spawn): it waits in host code and is not one of the game's threads uint64_t wseq; // Sequence number of wait registration: at equal priority first come, first woken (same order as the Horizon kernel's KThread wait tree) struct thr *next; // Wait chain @@ -103,6 +105,23 @@ static thr_t *g_all; extern __thread _Atomic int dm_host_work; // declared in hle.h too; defined in hle_nvn.c static _Atomic uint64_t g_preempt_n, g_preempt_ns; // same-core handoffs: count and total wait (svc_thread) static int g_core_preempt; // also check already-runnable peers after every thread SVC (profile / DM_PREEMPT) +// PEANUTS: DM_CORE_LOCK=1 (restart; experiment): the threads of one core take turns as on Horizon, where two threads of a core never run at the same moment and a running +// thread gives its core up only where it blocks. A guest thread whose affinity is one core holds that core's lock while it runs guest code: taken when it enters guest code and +// when an SVC returns, given up when an SVC is entered (the gate: where a thread blocks, sleeps or yields). Threads whose mask allows several cores run free. A native HLE wait +// gives it up too; the lock is taken again at the thread's next SVC exit (taking it at the wait's end would order it after the HLE's own mutex) +// A ticket lock (first come, first served): a thread that gives its core up at an SVC and takes it again on the way out queues behind the threads already waiting, as a +// yield hands the core to the others on Horizon. A plain mutex let the giver take it straight back: Xenoblade's resource_creater ran 100 ms on core 0 while the main thread waited +static int g_core_lock = -1; +// A thread of higher priority (a lower number) that waits for its core preempts the holder, as on Horizon: it signals the holder (SIGURG), whose handler, when the holder is +// in guest code, gives the core up and queues for it again. In host code (an HLE function, which may hold host locks) the holder is not stopped; the waiter signals again +static struct { pthread_mutex_t m; pthread_cond_t c; uint64_t next, serving; struct thr *owner; } g_core_lk[4] = { + {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0, 0}, {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0, 0}, + {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0, 0}, {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0, 0}}; +static uint64_t g_core_lock_end; // the lock applies until then (DM_CORE_LOCK_SECS from the main thread's start, default 20; 0 = for good): Xenoblade's heap race is at boot, and the lock's waits cost 2-3 hitches of 70-100 ms in 5 min of play +static uint64_t g_core_slice_ns = 0; // (off by default: a 4 ms slice gave Xenoblade 7 hitches in 5 min instead of 3) +static int core_lock_on(void) { if (g_core_lock < 0) { const char *e = getenv("DM_CORE_LOCK"); g_core_lock = e ? atoi(e) != 0 : DM_GAME_CORE_PREEMPT == 2; } return g_core_lock; } // the profile's core_preempt lock, DM_CORE_LOCK overrides +static void core_lock_take(struct thr *t); +static void core_lock_give(struct thr *t); static pthread_mutex_t G = PTHREAD_MUTEX_INITIALIZER; #define MAX_H 4096 @@ -142,7 +161,7 @@ uint64_t dm_thread_id_self(void) { thr_t *t = pthread_getspecific(g_keythr); ret // the caller's core runs until it blocks before the signalling thread continues. // See docs/reference/threads.md, "Same-core wake handoffs", for the movie lifetime failure this prevents. // svc_thread calls it after waking such a thread. Wait for guest blocking, not a host dispatch snapshot or a wall-clock deadline: neither establishes that the work has finished. -void dm_thread_mark_host(void) { thr_t *t = pthread_getspecific(g_keythr); if (t) t->host_owned = 1; } +void dm_thread_mark_host(void) { thr_t *t = pthread_getspecific(g_keythr); if (t) { t->host_owned = 1; core_lock_give(t); } } // PEANUTS: DM_CORE_LOCK // Holding G. wake() clears wkind before the pthread resumes; it must already count as runnable in that window, even if Mach still reports WAITING / STOPPED. // Explicit host GPU work and contended native codec locks do not occupy a guest core. Ordinary host dispatch delays and HLE calls do, until a guest wait / sleep / exit or a service request (dm_thread_service_request) says otherwise. static int thr_runnable(const thr_t *t) { @@ -211,6 +230,7 @@ void dm_thread_native_wait(int entering) { thr_t *t = pthread_getspecific(g_keythr); if (!t) return; if (entering && dm_core_excl_held && dm_core_excl_release) dm_core_excl_release(); // PEANUTS: it blocks (dm_core_excl_held above); before G, which the release does not take + if (entering) core_lock_give(t); // PEANUTS: DM_CORE_LOCK (taken again at the next SVC exit) pthread_mutex_lock(&G); // PEANUTS: where this thread's stack is while it waits (dm_guest_stopped_in), noted inside the entering branch. As a statement of its own between the two branches it // took the else below for itself: a wait entered inside another counted down instead of up, and the outer wait's end died on "unbalanced native HLE wait" @@ -389,6 +409,32 @@ static void qos_apply(thr_t *t) { // on the thread itself, holding G (prio and // A host helper thread (audio notify / silent sink, vsync, movie decode) created from a guest thread inherits that thread's class; under DM_QOS_MAP it sets its own instead void dm_host_helper_qos(plat_qos_t q) { if (g_qos_map) plat_qos_set_self(q); } static const char *thr_name(thr_t *t, char *buf, size_t n); +static pthread_once_t g_preempt_once = PTHREAD_ONCE_INIT; +static void preempt_install(void); +static void core_lock_take(thr_t *t) { + if (!core_lock_on() || t->clk >= 0 || t->host_owned) return; // (a host-owned guest thread waits in host code: never) + if (g_core_lock_end && now_ns() > g_core_lock_end) return; // past the boot window: the threads run free + uint64_t m = t->mask; if (!m || (m & (m - 1))) return; // several cores: runs free + int c = __builtin_ctzll(m); if (c > 3) return; + pthread_once(&g_preempt_once, preempt_install); + pthread_mutex_lock(&g_core_lk[c].m); uint64_t my = g_core_lk[c].next++; + uint64_t w0 = now_ns(); + while (g_core_lk[c].serving != my) { + thr_t *o = g_core_lk[c].owner; + // a higher priority preempts the holder at once; any waiter after a time slice (DM_CORE_SLICE_US, default 0: never): the core's threads stay exclusive, and a holder + // that runs long in guest code (Xenoblade's resource_creater, 100 ms beside the waiting main thread) no longer holds the others back + if (o && o != t && (t->prio < o->prio || (g_core_slice_ns && now_ns() - w0 > g_core_slice_ns))) { atomic_store(&o->preempt_req, 1); pthread_kill(o->pt, SIGURG); } + struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_nsec += 1000000; if (ts.tv_nsec >= 1000000000) { ts.tv_sec++; ts.tv_nsec -= 1000000000; } + pthread_cond_timedwait(&g_core_lk[c].c, &g_core_lk[c].m, &ts); // (1 ms: the holder may have been in host code at the signal) + } + g_core_lk[c].owner = t; + pthread_mutex_unlock(&g_core_lk[c].m); t->clk = c; +} +static void core_lock_give(thr_t *t) { + if (t->clk < 0) return; + int c = t->clk; t->clk = -1; + pthread_mutex_lock(&g_core_lk[c].m); g_core_lk[c].owner = NULL; g_core_lk[c].serving++; pthread_cond_broadcast(&g_core_lk[c].c); pthread_mutex_unlock(&g_core_lk[c].m); +} static void *thread_main(void *p) { thr_t *t = p; pthread_setspecific(g_keythr, t); @@ -400,9 +446,11 @@ static void *thread_main(void *p) { pthread_mutex_unlock(&G); crash_thread_init(); guest_thread_init(); guest_thread_set_id(t->id); + t->clk = -1; guest_gate_stack(1); // the guest runs on its own stack from dm_thread_enter on: this pthread's stack below this frame is where its SVCs run pthread_mutex_lock(&G); while (!t->started) pthread_cond_wait(&t->cv, &G); t->entered = 1; pthread_mutex_unlock(&G); { char nb[48], hn[64]; snprintf(hn, sizeof hn, "%#x %s", t->handle, thr_name(t, nb, sizeof nb)); plat_thread_set_name(hn); } // the guest's name (set before StartThread) for sample / Instruments + core_lock_take(t); // PEANUTS: DM_CORE_LOCK dm_thread_enter(t->entry, t->arg, t->stack_top); // Does not return: the guest must exit through ExitThread die("guest thread entry returned"); } @@ -465,10 +513,24 @@ static void on_pause_sig(int sig, siginfo_t *si, void *uc_) { } pthread_mutex_unlock(&G); } +// PEANUTS: DM_CORE_LOCK preemption (core_lock_take): in guest code, the holder gives its core up and queues again behind the higher-priority waiter +static void on_preempt_sig(int sig, siginfo_t *si, void *uc_) { + (void)sig; (void)si; + thr_t *t = pthread_getspecific(g_keythr); + if (!t || !atomic_exchange(&t->preempt_req, 0) || t->clk < 0 || atomic_load(&t->svc_regs)) return; + ucontext_t *uc = uc_; + if (!module_of((void *)PLAT_UC_PC(uc)) && !guest_code_extra(PLAT_UC_PC(uc))) return; // in host code: not stopped there (the waiter signals again) + int e = errno; core_lock_give(t); core_lock_take(t); errno = e; +} +static void preempt_install(void) { + struct sigaction sa = {.sa_sigaction = on_preempt_sig, .sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESTART}; + sigemptyset(&sa.sa_mask); sigaction(SIGURG, &sa, NULL); +} // called by the gate on SVC entry / exit (gate_dispatch in hle.c) void thr_svc_enter(uint64_t *regs, uint64_t pc) { thr_t *t = pthread_getspecific(g_keythr); if (!t) return; if (dm_core_excl_held && dm_core_excl_release) dm_core_excl_release(); // PEANUTS: an SVC is where a thread blocks (dm_core_excl_held above) + core_lock_give(t); // PEANUTS: DM_CORE_LOCK t->svc_pc = pc; t->svc_x18 = (uint64_t)(uintptr_t)dm_slot_get(18); atomic_store(&t->svc_regs, regs); atomic_fetch_or(&t->svc_state, 1); if (atomic_load_explicit(&t->qos_pending, memory_order_relaxed) && atomic_exchange(&t->qos_pending, 0)) { pthread_mutex_lock(&G); qos_apply(t); pthread_mutex_unlock(&G); @@ -477,6 +539,7 @@ void thr_svc_enter(uint64_t *regs, uint64_t pc) { } void thr_svc_leave(void) { thr_t *t = pthread_getspecific(g_keythr); if (!t) return; + core_lock_take(t); // PEANUTS: DM_CORE_LOCK int in = 1; if (atomic_compare_exchange_strong(&t->svc_state, &in, 0)) { atomic_store(&t->svc_regs, NULL); return; } // no pause requested: G is not needed (every other thread's SVC takes it) pthread_mutex_lock(&G); while (t->pause_req) { t->paused = 1; pthread_cond_broadcast(&t->pcv); pthread_cond_wait(&t->pcv, &G); } @@ -674,7 +737,7 @@ static void hitch_init(void) { uint32_t svc_thread_main_init(void) { pthread_key_create(&g_keythr, NULL); qos_map_init(); - { const char *e = getenv("DM_PREEMPT"); g_core_preempt = e ? atoi(e) != 0 : DM_GAME_CORE_PREEMPT; } + { const char *e = getenv("DM_PREEMPT"); g_core_preempt = e ? atoi(e) != 0 : DM_GAME_CORE_PREEMPT == 1; } // PEANUTS: 2 (core_preempt lock) is DM_CORE_LOCK, not core_preempt pause_install(); hitch_init(); thr_t *t = calloc(1, sizeof *t); @@ -687,6 +750,10 @@ uint32_t svc_thread_main_init(void) { t->qos = (uint32_t)plat_qos_of(pthread_self()); pthread_mutex_lock(&G); t->handle = h_new(O_THREAD, t); t->id = g_next_id++; t->all = g_all; g_all = t; pthread_mutex_unlock(&G); pthread_setspecific(g_keythr, t); + t->clk = -1; core_lock_take(t); // PEANUTS: DM_CORE_LOCK + if (core_lock_on()) { const char *e = getenv("DM_CORE_SLICE_US"); if (e) g_core_slice_ns = (uint64_t)atoll(e) * 1000; + const char *w = getenv("DM_CORE_LOCK_SECS"); long secs = w ? atol(w) : 20; g_core_lock_end = secs > 0 ? now_ns() + (uint64_t)secs * 1000000000ull : 0; + LOG("DM_CORE_LOCK: the guest threads of one core take turns, as on Horizon (a core's lock held in guest code, given up at SVCs; preempted by a higher priority, or after %llu us)", (unsigned long long)(g_core_slice_ns / 1000)); } guest_thread_set_id(t->id); // main.c ran guest_thread_init before this, and no guest code has run yet plat_thread_set_name("0x1001 main thread"); LOG("main guest thread QoS %#x (priority %d)", t->qos, t->prio); diff --git a/docs/advanced_settings.tsv b/docs/advanced_settings.tsv index 3a0ea809..8523228b 100644 --- a/docs/advanced_settings.tsv +++ b/docs/advanced_settings.tsv @@ -50,6 +50,9 @@ DM_COOP_INTERNET developer Game text both DM_COOP_ROOM developer Game text both DM_COPY_GAME_RESOURCES developer Game text both DM_COPY_ROMFS developer Packing text both +DM_CORE_LOCK developer Performance text both +DM_CORE_LOCK_SECS developer Performance text both +DM_CORE_SLICE_US developer Performance text both DM_CRA_LIB developer Diagnostics text both DM_CTL internal Diagnostics text both Mac or iOS only DM_DAV1D_FRAME_DELAY developer Diagnostics text both diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv index a6b3adbf..71b7d63d 100644 --- a/docs/env_switches.tsv +++ b/docs/env_switches.tsv @@ -48,6 +48,9 @@ DM_COOP_INTERNET switch `1` (at start; unset or `0`: off) lets the optional co-o DM_COOP_ROOM switch The host's 16-symbol room code for `DM_COOP_INTERNET=1`, with optional spaces or hyphens. Required when joining; ignored with internet mode off. The dependency may include it in diagnostics: redact before sharing logs DM_COPY_GAME_RESOURCES switch `NO` skips the Xcode build phase that copies the game's resources into the app (`stage_resources.sh`, on by default); `build_ipa.sh` sets it for its unsigned build, which packs them itself DM_COPY_ROMFS switch `NO` keeps the game files out of the app, in the Xcode build phase (`stage_resources.sh`) and in the unsigned IPA of `build_ipa.sh` (on by default): `main.m` takes the validated `Documents/romfs.img` copied by `scripts/push_romfs.sh`, then a `Documents/romfs` folder; the build writes the image's identity as `romfs.id` into the app, and `main.m` uses only a matching image (`--romfs separate` of the NSP script sets this) +DM_CORE_LOCK switch `0` / `1` (restart) overrides the profile's `core_preempt lock`: the guest threads of one core take turns as on Horizon, where two threads of a core never run at the same moment: a thread whose affinity is one core holds that core's lock (a first-come ticket lock) while it runs guest code and gives it up at each SVC and native HLE wait; a waiter of higher priority preempts the holder in guest code (SIGURG); threads that may run on several cores run free. For the first `DM_CORE_LOCK_SECS` seconds only [PEANUTS] +DM_CORE_LOCK_SECS switch `=` (restart, default 20; 0 = for good) how long from the start `DM_CORE_LOCK` applies: Xenoblade Chronicles: Definitive Edition's race is at boot, and the lock's waits cost 2-3 hitches of 70-100 ms in 5 min of play [PEANUTS] +DM_CORE_SLICE_US switch `=` (restart, default 0 = never) with `DM_CORE_LOCK`, a waiter of the same priority preempts the holder after waiting that long (a time slice); 4000 gave Xenoblade more hitches, not fewer [PEANUTS] DM_CRA_LIB path `=` libcra (`dm/gfx/tools/cra_unscramble.c`), the unscramble of Camelot's archive (Mario Tennis Fever) that `dm/gfx/tools/cra.py` loads through ctypes, in place of `libcra.so` on Android and of the Python loop elsewhere; one that does not load is an Error (the tests set it to a build of their own) DM_CTL diagnostic `=` (Mac): the host polls the file every 100 ms and runs each appended line: button presses, `shot`, `passdump`, `texdump`, `env KEY=VALUE`, `peek`, `memdump`, `drag` and more DM_DAV1D_FRAME_DELAY diagnostic `=` dav1d's maximum frame delay for AV1 movies (`hle_movie_av1.c`; default 0, automatic frame threading). Frame-parallel dav1d (profile `av1_decoder dav1d`, `DM_AV1_DAV1D_FP`): 1-8 frames in flight, default 5 with 8 threads, 3 with 4-6, else 1