Gamepad pause menu row order; close an ordering race in dirty-page tracking
- Gamepad pause menu: "Options" and "Game Difficulty" swap places. With a gamepad the cursor rests on the centre row when the menu opens, and pressing confirm right away used to change the difficulty setting. Touch layout is unchanged. - Graphics layer (preventive): setting a page read-only now marks it BUSY until mprotect has landed, so an unprotect-before-write from another thread can no longer leave a page read-only with state NONE. Adds the unit test t_dirty_race, which stages the interleaving deterministically.
This commit is contained in:
+45
-13
@@ -13,8 +13,24 @@
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <mach/mach_time.h>
|
||||
#include <sched.h>
|
||||
|
||||
enum { PG_NONE = 0, PG_PROT = 1, PG_BUSY = 2 }; // BUSY:正在解除保护(另一线程同时缺页时自旋等它) | BUSY: being unprotected (another thread faulting at the same time spins waiting for it)
|
||||
// 页状态与 mprotect 的次序(改保护的一方先把状态改成 BUSY,mprotect 落地后才改成终态;别的线程见 BUSY 就等):
|
||||
// 设只读:NONE → BUSY → mprotect(只读) → PROT;解保护:PROT → BUSY → mprotect(可写) → NONE。
|
||||
// 不变式:状态是 NONE 的页一定可写、是 PROT 的页一定只读。原先设只读是「先记 PROT、攒一段再 mprotect」,这段时间里另一线程的写前解保护
|
||||
// 会把状态改回 NONE,随后攒批的 mprotect 落地 ⇒ 页只读而状态 NONE:游戏线程写它时缺页处理只回「重执行」永远空转;
|
||||
// 宿主用系统调用往里读文件时 prep_write 看状态 NONE 跳过,系统调用不走缺页处理,直接 EFAULT、数据读不全。
|
||||
// BUSY 最长持续 = 一次 mprotect 的时间(设只读时再加上给这一段逐页改状态的几次原子写)。等待有上限 BUSY_WAIT_MS,超限报红:
|
||||
// 缺页处理里超限按「不是我们的页」返回,交给崩溃处理如实报崩,不静默空转。等待只读原子量、不拿任何锁。
|
||||
// Order of page state and mprotect (the side changing protection first sets the state to BUSY and sets the final state only after mprotect has landed; other threads wait when they see BUSY):
|
||||
// set read-only: NONE -> BUSY -> mprotect(read-only) -> PROT; unprotect: PROT -> BUSY -> mprotect(writable) -> NONE.
|
||||
// Invariant: a page whose state is NONE is always writable, and one whose state is PROT is always read-only. Setting read-only used to be "record PROT first, batch up a run, then mprotect"; during that time another thread's unprotect-before-write
|
||||
// could set the state back to NONE, and then the batched mprotect landed => the page read-only with state NONE: when the game thread wrote to it the page-fault handler only returned "re-execute" and spun forever;
|
||||
// when the host read a file into it with a system call, prep_write saw state NONE and skipped, the system call did not go through the page-fault handler and failed with EFAULT, leaving the data incomplete.
|
||||
// BUSY lasts at most one mprotect (plus, when setting read-only, the few atomic writes that change the state of the pages in the run). The wait has an upper limit BUSY_WAIT_MS and reports red beyond it:
|
||||
// in the page-fault handler, exceeding it returns "not our page" and lets the crash handler report the crash truthfully instead of spinning silently. The wait only reads atomics and takes no lock.
|
||||
enum { PG_NONE = 0, PG_PROT = 1, PG_BUSY = 2 };
|
||||
enum { BUSY_WAIT_MS = 2000 };
|
||||
// 跟踪区间 = 各内存池(MemoryPoolInitialize 登记)。池销毁后复用 live=0 的槽,信号处理里无锁扫描。
|
||||
// Tracked ranges = the memory pools (registered by MemoryPoolInitialize). After a pool is destroyed its live=0 slot is reused; the signal handler scans without locks.
|
||||
#define MAX_RANGE 4096 // 原为 256:内存池多于它时超出的池不跟踪,里面的贴图每次取用都当成脏的重传(暗黑实测峰值见内存读数行的「内存池」;塞尔达约 300 个,踩过)。扫描只到已用的槽数,容量大不增加开销 | was 256: with more memory pools than that the excess pools are untracked and their textures are treated as dirty and re-uploaded on every use (for Diablo's measured peak see "memory pools" in the memory readout line; Zelda has about 300 and hit this). The scan only covers slots in use, so a larger capacity costs nothing
|
||||
@@ -35,6 +51,22 @@ static void mp(uintptr_t a, size_t len, int prot) {
|
||||
atomic_fetch_add(&g_mp_ticks, mach_absolute_time() - t); atomic_fetch_add(&g_mp_calls, 1); atomic_fetch_add(&g_mp_pages, len >> g_shift);
|
||||
}
|
||||
|
||||
static mach_timebase_info_data_t g_tb; // 首次登记池时取好(缺页路径里只做乘除) | Obtained when a pool is first registered (the fault path only multiplies and divides)
|
||||
static _Atomic int g_busy_red;
|
||||
// 等这一页离开 BUSY。返回 1 = 已离开;0 = 等过了上限(报红一次)。信号处理里可用:只有原子读、mach_absolute_time、sched_yield
|
||||
// Wait for this page to leave BUSY. Returns 1 = it has left; 0 = waited past the limit (reported red once). Usable in a signal handler: only atomic reads, mach_absolute_time and sched_yield
|
||||
static int busy_wait(range_t *r, uintptr_t p) {
|
||||
uint64_t t0 = 0;
|
||||
for (unsigned n = 1; atomic_load(&r->state[p]) == PG_BUSY; n++) {
|
||||
if (n & 0x3ff) continue;
|
||||
uint64_t now = mach_absolute_time(); if (!t0) t0 = now;
|
||||
if ((now - t0) * g_tb.numer / g_tb.denom > (uint64_t)BUSY_WAIT_MS * 1000000ull) {
|
||||
if (!atomic_exchange(&g_busy_red, 1)) LOG("【红】脏页跟踪:页 %p 停在「忙」超过 %d 毫秒(改保护的线程没走完),不再等", (void *)(r->base + (p << g_shift)), BUSY_WAIT_MS);
|
||||
return 0; }
|
||||
sched_yield();
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
static range_t *find(uintptr_t a) {
|
||||
int n = atomic_load(&g_nr);
|
||||
for (int i = 0; i < n; i++) if (atomic_load_explicit(&g_r[i].live, memory_order_acquire) && a >= g_r[i].base && a < g_r[i].end) return &g_r[i];
|
||||
@@ -52,7 +84,7 @@ static int on_fault(void *addr, int is_write, void *uc) {
|
||||
uintptr_t p = ((uintptr_t)addr - r->base) >> g_shift;
|
||||
uint8_t st = PG_PROT;
|
||||
if (atomic_compare_exchange_strong(&r->state[p], &st, PG_BUSY)) { unprotect_page(r, p); atomic_fetch_add(&g_faults, 1); return 1; }
|
||||
if (st == PG_BUSY) { while (atomic_load(&r->state[p]) == PG_BUSY) {} return 1; } // 别的线程正在解:等它解完重执行 | Another thread is unprotecting it: wait for it to finish and re-execute
|
||||
if (st == PG_BUSY) return busy_wait(r, p); // 别的线程正在改这页的保护:等它改完重执行(改成了只读就再缺页一次、走上面那一支) | Another thread is changing this page's protection: wait for it to finish and re-execute (if it became read-only, it faults once more and takes the branch above)
|
||||
return atomic_load(&r->gen[p]) != 0; // 刚被别的线程解掉(本次缺页发生在解之前):重执行;从未保护过的页不是我们的 | Just unprotected by another thread (this fault happened before the unprotect): re-execute; pages that were never protected are not ours
|
||||
}
|
||||
static void prep_write(void *addr, size_t len) {
|
||||
@@ -62,9 +94,9 @@ static void prep_write(void *addr, size_t len) {
|
||||
if (!r) { a = (a + g_pg) & ~(g_pg - 1); continue; }
|
||||
uintptr_t stop = e < r->end ? e : r->end;
|
||||
for (uintptr_t p = (a - r->base) >> g_shift, q = (stop - 1 - r->base) >> g_shift; p <= q; p++) {
|
||||
uint8_t st = PG_PROT;
|
||||
if (atomic_compare_exchange_strong(&r->state[p], &st, PG_BUSY)) { unprotect_page(r, p); atomic_fetch_add(&g_preps, 1); }
|
||||
else while (atomic_load(&r->state[p]) == PG_BUSY) {}
|
||||
for (;;) { uint8_t st = PG_PROT; // 见 BUSY 等完要重看:对方可能是在设只读,等完这页是 PROT,照样得解 | After waiting out BUSY, look again: the other side may have been setting read-only, in which case the page is PROT after the wait and still has to be unprotected
|
||||
if (atomic_compare_exchange_strong(&r->state[p], &st, PG_BUSY)) { unprotect_page(r, p); atomic_fetch_add(&g_preps, 1); break; }
|
||||
if (st != PG_BUSY || !busy_wait(r, p)) break; }
|
||||
}
|
||||
a = stop;
|
||||
}
|
||||
@@ -72,7 +104,7 @@ static void prep_write(void *addr, size_t len) {
|
||||
|
||||
void nvn_dirty_add_range(const void *mem, size_t size) {
|
||||
static int inited;
|
||||
if (!inited) { inited = 1; g_pg = (uintptr_t)getpagesize(); g_shift = __builtin_ctzl(g_pg); dm_fault_hook_register(on_fault); dm_guest_write_prep_register(prep_write); }
|
||||
if (!inited) { inited = 1; g_pg = (uintptr_t)getpagesize(); g_shift = __builtin_ctzl(g_pg); mach_timebase_info(&g_tb); dm_fault_hook_register(on_fault); dm_guest_write_prep_register(prep_write); }
|
||||
atomic_fetch_add(&g_adds_total, 1);
|
||||
pthread_mutex_lock(&g_slot_mu);
|
||||
int n = atomic_load(&g_nr);
|
||||
@@ -117,22 +149,22 @@ void nvn_dirty_remove_range(const void *mem) {
|
||||
int nvn_dirty_tracked(const void *addr, size_t len) {
|
||||
range_t *r = find((uintptr_t)addr); return r && (uintptr_t)addr + len <= r->end;
|
||||
}
|
||||
// 设只读:先置状态再 mprotect(反过来会有「页已只读、状态仍为 0」的窗口,那时的合法写入会被当成崩溃)
|
||||
// Set read-only: set the state first, then mprotect (the reverse leaves a window of "page already read-only, state still 0", during which a legitimate write would be treated as a crash)
|
||||
// 设只读:先把页标成 BUSY,mprotect 落地后才标 PROT(次序与不变式见文件头的状态说明)
|
||||
// Set read-only: mark the page BUSY first, and mark it PROT only after mprotect has landed (for the order and the invariant see the state notes at the top of the file)
|
||||
void nvn_dirty_protect(const void *addr, size_t len) {
|
||||
if (!len || !nvn_dirty_tracked(addr, len)) return;
|
||||
range_t *r = find((uintptr_t)addr);
|
||||
uintptr_t a = (uintptr_t)addr, p = (a - r->base) >> g_shift, q = (a + len - 1 - r->base) >> g_shift;
|
||||
// 连续置成 PROT 的页合成一次 mprotect(逐页调用在首传大贴图时一帧上千次;选角页启动帧 5:4888 次)。
|
||||
// 已是 PROT / BUSY 的页断开连续段:不重复保护,也不碰别的线程正在解的页
|
||||
// Consecutive pages set to PROT are merged into one mprotect (per-page calls reach thousands per frame on the first upload of large textures; character select page startup frame 5: 4888 calls).
|
||||
// Pages already PROT / BUSY break the consecutive run: do not protect again, and do not touch pages another thread is unprotecting
|
||||
// 已是 PROT / BUSY 的页断开连续段:不重复保护,也不碰别的线程正在改的页
|
||||
// Consecutive pages set to PROT are merged into one mprotect (per-page calls ran to over a thousand per frame when large textures were first uploaded; character select, startup frame 5: 4888 calls).
|
||||
// Pages already PROT / BUSY break a run: they are not protected again, and pages another thread is changing are left alone
|
||||
uintptr_t run = 0; int open = 0;
|
||||
for (uintptr_t i = p; i <= q + 1; i++) {
|
||||
uint8_t st = PG_NONE;
|
||||
int took = i <= q && atomic_compare_exchange_strong(&r->state[i], &st, PG_PROT);
|
||||
int took = i <= q && atomic_compare_exchange_strong(&r->state[i], &st, PG_BUSY);
|
||||
if (took && !open) { run = i; open = 1; }
|
||||
if (!took && open) { mp(r->base + (run << g_shift), (i - run) << g_shift, PROT_READ); open = 0; }
|
||||
if (!took && open) { mp(r->base + (run << g_shift), (i - run) << g_shift, PROT_READ); for (uintptr_t k = run; k < i; k++) atomic_store(&r->state[k], PG_PROT); open = 0; }
|
||||
}
|
||||
}
|
||||
uint64_t nvn_dirty_now(void) { return atomic_load(&g_now); }
|
||||
|
||||
@@ -30,6 +30,8 @@ t_rt_depth_ro.dSYM/
|
||||
t_pso_skey
|
||||
t_pso_skey.dSYM/
|
||||
t_dirty_slots
|
||||
t_dirty_race
|
||||
t_dirty_race.dSYM/
|
||||
t_dirty_slots.dSYM/
|
||||
t_pfv
|
||||
t_pfv.dSYM/
|
||||
|
||||
@@ -12,6 +12,8 @@ t_nvn: t_nvn.c ../nvn/hle_nvn.c ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_nvn.c ../../host/crash.c $(GFX) $(FW)
|
||||
t_dirty_slots: t_dirty_slots.c ../nvn/nvn_dirty.c ../../host/crash.c ../nvn/nvn_dirty.h
|
||||
clang $(CFLAGS) -o $@ t_dirty_slots.c ../../host/crash.c ../nvn/nvn_dirty.c
|
||||
t_dirty_race: t_dirty_race.c ../nvn/nvn_dirty.c ../../host/crash.c ../nvn/nvn_dirty.h
|
||||
clang $(CFLAGS) -o $@ t_dirty_race.c ../../host/crash.c
|
||||
t_builtin: t_builtin.m ../nvn/nvn_builtin.h
|
||||
clang -O1 -g -Wall -fobjc-arc -o $@ t_builtin.m -framework Metal -framework Foundation
|
||||
t_deswz_gpu: t_deswz_gpu.m ../tex/nvn_deswizzle.c ../tex/nvn_deswizzle_gpu.m ../tex/nvn_deswizzle.h ../tex/nvn_deswizzle_gpu.h ../nvn/nvn_tex.c ../nvn/nvn_tex.h
|
||||
@@ -52,9 +54,10 @@ t_pso_skey: t_pso_skey.m ../nvn/nvn_pso_skey.h ../nvn/nvn_obj.h
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_pso_skey.m -framework Foundation
|
||||
t_pfv: t_pfv.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_pfv.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
run: t_nvn t_dirty_slots t_builtin t_deswz_gpu t_pace t_refl t_hmap t_cover t_fuse_check t_present_crop t_reorder_chain t_defer_chain t_zskip t_xv t_ub t_mip_extent t_rt_range_shape t_rt_range_ro t_rt_range t_rt_depth_ro t_pso_skey t_pfv
|
||||
run: t_nvn t_dirty_slots t_dirty_race t_builtin t_deswz_gpu t_pace t_refl t_hmap t_cover t_fuse_check t_present_crop t_reorder_chain t_defer_chain t_zskip t_xv t_ub t_mip_extent t_rt_range_shape t_rt_range_ro t_rt_range t_rt_depth_ro t_pso_skey t_pfv
|
||||
./t_nvn
|
||||
./t_dirty_slots
|
||||
./t_dirty_race
|
||||
./t_builtin
|
||||
./t_deswz_gpu
|
||||
./t_pace
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// 脏页跟踪「设只读」与「写前解保护」的次序竞态。
|
||||
// 现场:线程甲 nvn_dirty_protect 已把页的状态记成「受保护」、攒批的 mprotect 还没落地;线程乙这时来 prep_write(宿主往客体内存写之前的解保护,
|
||||
// 例如读盘把文件读进贴图存储)。旧实现:乙把状态改回「无」,随后甲的 mprotect 落地 ⇒ 页只读而状态「无」——
|
||||
// 宿主再往里读文件:prep_write 看状态「无」跳过,系统调用不走缺页处理,直接 EFAULT;游戏线程直接写:缺页处理只回「重执行」,永远空转。
|
||||
// 造法:把 nvn_dirty.c 里的 mprotect 换成这里的 t_mprotect——甲设只读的那一次调用落地之前,先放乙进来并等 100 毫秒,次序是确定的。
|
||||
// 期望值不靠被测实现:乙的 prep_write 返回之后,这一页必须真的可写(往里 read 16 字节得 16;直接写一个字节不卡、读回是写进去的值),
|
||||
// 且这次写要被记成脏(nvn_dirty_since 对设只读之前取的戳返回 1)。
|
||||
// Ordering race between "set read-only" and "unprotect before write" in dirty-page tracking.
|
||||
// Scene: thread A, in nvn_dirty_protect, has already recorded the page state as "protected" while the batched mprotect has not landed yet; thread B now arrives with prep_write (the unprotect done before the host writes into guest memory,
|
||||
// for example a disk read putting a file into texture storage). Old implementation: B sets the state back to "none", then A's mprotect lands => the page is read-only while its state is "none" --
|
||||
// when the host reads a file into it again: prep_write sees state "none" and skips, the system call does not go through the page-fault handler and fails with EFAULT; when the game thread writes directly: the page-fault handler only returns "re-execute" and spins forever.
|
||||
// How it is staged: the mprotect in nvn_dirty.c is replaced by t_mprotect here -- before the call with which A sets read-only lands, B is let in and given 100 ms, so the order is deterministic.
|
||||
// Expected values do not depend on the implementation under test: after B's prep_write returns, this page must really be writable (reading 16 bytes into it gives 16; writing one byte directly does not hang and reads back as written),
|
||||
// and this write must be recorded as dirty (nvn_dirty_since returns 1 for a stamp taken before the page was set read-only).
|
||||
#define mprotect t_mprotect
|
||||
#include "../nvn/nvn_dirty.c"
|
||||
#undef mprotect
|
||||
int mprotect(void *, size_t, int);
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
|
||||
module_t g_mod[MAX_MOD];
|
||||
int g_nmod;
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
void crash_install(void);
|
||||
|
||||
static int g_fail;
|
||||
#define EXPECT(name, want, got) do { \
|
||||
long long want_ = (long long)(want), got_ = (long long)(got); \
|
||||
printf("%-58s 期望 %-4lld → 真结果 %-4lld %s\n", name, want_, got_, want_ == got_ ? "✓" : "✗"); \
|
||||
if (want_ != got_) g_fail++; \
|
||||
} while (0)
|
||||
|
||||
static uint8_t *g_page; static _Atomic int g_armed, g_go, g_b_done;
|
||||
static void *thread_b(void *arg) { (void)arg; while (!atomic_load(&g_go)) usleep(200); prep_write(g_page, 16); atomic_store(&g_b_done, 1); return NULL; }
|
||||
int t_mprotect(void *a, size_t n, int prot) {
|
||||
if (prot == PROT_READ && atomic_exchange(&g_armed, 0)) { atomic_store(&g_go, 1); usleep(100000); } // 甲的 mprotect 落地前:放乙进来,等它跑到头或卡在等待上 | Before A's mprotect lands: let B in and wait until it runs to the end or gets stuck waiting
|
||||
return mprotect(a, n, prot);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
crash_install();
|
||||
size_t pg = (size_t)getpagesize();
|
||||
g_page = mmap(NULL, 2 * pg, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
|
||||
if (g_page == MAP_FAILED) { perror("mmap"); return 2; }
|
||||
nvn_dirty_add_range(g_page, 2 * pg);
|
||||
uint64_t stamp = nvn_dirty_now();
|
||||
pthread_t tb; pthread_create(&tb, NULL, thread_b, NULL);
|
||||
atomic_store(&g_armed, 1);
|
||||
nvn_dirty_protect(g_page, 2 * pg); // 甲:置状态 → (乙插进来)→ mprotect 落地 | A: set the state -> (B cuts in) -> mprotect lands
|
||||
for (int i = 0; i < 2000 && !atomic_load(&g_b_done); i++) usleep(1000);
|
||||
EXPECT("乙的写前解保护在 2 秒内返回", 1, atomic_load(&g_b_done));
|
||||
if (!atomic_load(&g_b_done)) { printf("t_dirty_race:乙没返回,后面的项不测\n"); return 1; }
|
||||
pthread_join(tb, NULL);
|
||||
int fd = open("/dev/zero", O_RDONLY); g_page[pg] = 0; // 第二页没人解过保护,这一写走缺页处理(对照:正常路径是通的) | Nobody has unprotected the second page, so this write goes through the page-fault handler (control: the normal path works)
|
||||
ssize_t r = read(fd, g_page, 16); // 乙接下来要做的那次宿主写:系统调用直接写进页里 | The host write that B is about to make: a system call writing straight into the page
|
||||
EXPECT("乙解完保护后往这页读文件:读到的字节数 = 请求的 16", 16, r);
|
||||
if (r == 16) { ((volatile uint8_t *)g_page)[1] = 0x5a; EXPECT("直接写这页不卡、读回是写进去的值", 0x5a, g_page[1]); }
|
||||
else { printf(" (read 失败 errno=%d;页只读而状态为「无」,直接写会在缺页处理里空转,这一项不执行)\n", errno); g_fail++; }
|
||||
EXPECT("这次写被记成脏(对设只读前的戳)", 1, nvn_dirty_since(g_page, 16, stamp));
|
||||
close(fd);
|
||||
printf("t_dirty_race:%s\n", g_fail ? "不通" : "全通"); return g_fail != 0;
|
||||
}
|
||||
Reference in New Issue
Block a user