diff --git a/docs/G83-Storm-Investigation-20261203.md b/docs/G83-Storm-Investigation-20261203.md index 195d6b5..4d1d835 100644 --- a/docs/G83-Storm-Investigation-20261203.md +++ b/docs/G83-Storm-Investigation-20261203.md @@ -394,3 +394,160 @@ v8 = v7 + CSB 同上下文 detail-4 信号量等待;v10/v10.1/v10.2/v10.3 = v8 结论:`06d3a52` 的校验逻辑本身正确(`E8` 位移按 `RA+rel` 计算,读取越界由前置 `size>0xA02D0` 覆盖, 任何一项不符时规则与观察器都不安装,方向安全)。§12.5 关于 B 类规则不应视为可上线的结论不变。 + +## 13. 第三轮审查(2026-12-03 夜,分支 `review/g83-round3-20261203`) + +任务清单见 `docs/G83-Review-Round3-20261203.md`。 + +### 13.0 验证级别与上一轮闭环 + +本轮所有改动只有 **CPU 测试(arm64,无 Rosetta)与交叉构建**,没有 x86 套件、原版回放或硬件运行。 +G83 套件 199 通过;29 个失败与 main 相同,都是 x86 夹具;RELEASE 与 DEBUG 构建都通过,警告数不变(460)。 + +| 提交 | 内容 | 验证级别 | +|---|---|---| +| `0466e43` | 原样移植研究树里已有测试的只读 BCS 信号量等待见证(第 4 项第一步) | CPU;两棵树都从未部署 | +| `18ad5d0` | 把恢复与孤儿规则两个安装块原样移出 `processTGLAccelerator`,DEBUG 构建首次通过(第 6 项) | 构建级;需实机确认两个 Ready 标志仍为 Yes | +| `d369666` | 孤儿完成分 B/C 计数,记录拆除豁免用的是哪个端口,并对已完成的戳做回退采样(第 2、3 项的裁决数据) | CPU(7 个变异体全部被测出);需实机 | + +上一轮闭环:`TGLOrphanObserveReady=Yes`(`59BFDDAE`)证明安装期的字节校验与本机 16.0.32 一致。 +它只证明**安装**正确,不证明规则的行为正确。 + +### 13.1 WiFi 开机慢(第 1 项,最高优先;与 WEX 无关,未改任何代码) + +**证据包能确定的时间分解(14:00:07 启动)**: + +| 区间 | 时长 | 依据 | 归属 | +|---|---|---|---| +| 内核启动 → en1 出现(`DHCP en1: start` 14:00:14.855) | ≤7.8 s | configd | 含 AirportItlwm 挂载与固件加载,证据包分不开;即便全算固件,也只占小头 | +| airportd 就绪 → AutoJoin ENABLED(14:00:18.005,`prev=DISABLED`) | ~3 s | airportd | 系统策略侧 | +| 自动加入开始(14:00:18.304)→ en1 link ACTIVE(14:01:12.253) | **53.9 s** | **证据包里这一段没有任何日志** | 未知,见下方假设 | +| link ACTIVE → 第 5 次 DISCOVER 后首次收到 OFFER(14:01:29.43) | 17.2 s | configd:DISCOVER 分别在 0/2.0/4.2/9.1/17.2 s 发出 | 见下方假设 | +| BOUND(14:01:30.49)→ 发布地址(14:01:32.11) | 1.6 s | configd | 系统侧 | + +**结论**:所问的"固件、扫描、802.1X 各占多少",用现有证据包**无法回答**。关联耗时的 83%(53.9 s)落在没有日志的区间。下面列出可以检验的假设,并给出区分它们所需的日志。 + +| 假设 | 支持的线索 | 反对或待查 | 区分方法 | +|---|---|---|---| +| H1:每次扫描都走全频段(约 9 s),驱动没有遵守请求里的信道列表 | 单次 SCAN 耗时 8.94 s;"ac" 调度有 9 项扫描,多数是 `BSSChannelsOnly=1, maxBSSChannelCount=3` 的窄扫描(原生硬件应在 0.2 s 内完成);6 次 × 9 s ≈ 54 s | 不知道这段时间实际发了几次扫描 | 统计 18 s–72 s 之间 `END REQ [SCAN] took` 的次数和各自耗时:窄扫描如果也要 8–9 s,H1 成立。**归属驱动侧** | +| H2:头几轮自动加入找不到候选,之后按定时器重试 | 有 `Failed cache-assisted scan`;三次启动都落在 59–65 s,像定时器而不是随机 | 重试间隔被截断,未知 | 查 `Auto-join ENDED/FINISHED`、候选数、retry interval 的行。归属系统策略侧,或驱动首扫结果不完整 | +| H3:802.1X 凭据需要用户登录(钥匙串)后才能用 | 14:00:15 有 `no user logged in`;网络是 WPA2 企业网 | 三次启动耗时一致,除非开了自动登录,否则不像受登录时刻影响 | 比较 loginwindow 登录时刻与 link ACTIVE;`profiles show -type configuration` 查 802.1X 描述文件是用户模式还是 System/LoginWindow 模式 | +| HD1:驱动在**关联时**就报 link ACTIVE,此时 EAP 和四次握手还没完成,端口授权前的 DISCOVER 被丢弃 | 关联后才出现 SecTrust 证书评估;首个 OFFER 晚 17 s,期间没有 NAK | — | 比较 eapolclient 的认证成功或 EAPOL-Key 时刻与 14:01:29.4:两者接近即成立。此时 17 s 实际是 EAP 认证时间加 DHCP 退避对齐的损失(最多约 8 s) | +| HD2:网络侧(DHCP 中继/监听、RADIUS 下发 VLAN) | — | — | 同一 AP 下用另一台设备,或改用有线对照 | + +**IPv6 RA**:证据包里没有任何迹象。DHCPv4 INIT 的退避不依赖 RA,日志里也只有"发出的 DISCOVER 没有回应"。按现有证据,RA 不是原因。 + +**上游情况**: +- OpenIntelWireless/itlwm 没有开机关联慢的已知 issue 或修复。802.1X 相关的 #618、#744、#1021 讨论的是能否支持和稳定性,不是延迟。 +- 官方最新稳定版是 2.3.0(2024-06),**没有 Tahoe 版**。社区在 Tahoe 上的做法(#1062)是 2.3.0 Ventura 版加 OCLP 补丁。 +- 本机的"AirportItlwm 2.4.0 (zxystd)"不是官方发布版本,来源应记入部署文档。 +- 因此**没有可以直接引用的上游参数级缓解**。 + +**缓解建议(都不需要禁用服务)**: +1. **系统策略侧**:如果 H3 成立,把 802.1X 描述文件装成 System 或 LoginWindow 模式,让 EAP 在登录前完成。这是改配置,不是禁用服务。 +2. **系统策略侧**:清理已知网络。现在有 59 个,其中至少 1 个已 72 周未用。可以缩小候选和窄扫描的信道集,但单靠这一项收益有限。 +3. **驱动侧(AirportItlwm,不在本仓库)**:如果 H1 成立,扫描应遵守信道列表和 dwell 时间;如果 HD1 成立,应在 RSN 密钥安装、端口授权之后才报 link up,这样 DHCP 会在认证完成后立即开始,省掉退避对齐的损失。两处都要改 itlwm 源码;确认假设后可以带着证据向上游提 issue。 +4. **网络侧**:RADIUS 时延、TLS 会话复用(PEAP fast reconnect),归 IT 管理。 + +**补采命令**(只读,在 G83 下次启动后运行;把 `B` 换成实际启动时刻): + +```sh +B="2026-12-03 14:00:07"; E="2026-12-03 14:02:10" +log show --start "$B" --end "$E" --info --debug --style compact \ + --predicate 'process IN {"airportd","eapolclient","configd","loginwindow"} OR sender == "AirportItlwm"' > wifi-boot.log +grep -E 'REQ \[SCAN\]|took|Auto-join (ENDED|FINISHED|STARTED)|candidate|JOIN|[Aa]ssoc|EAP|EAPOL|[Aa]uthenticat|link (ACTIVE|INACTIVE)|loginwindow|[Rr]etry' wifi-boot.log +profiles show -type configuration | grep -iE '802|eap|SystemMode|LoginWindow' +``` + +把 `grep` 的输出(按需脱敏)补进证据包,就能对上表逐项下结论。 + +### 13.2 B 类规则的实机裁决标准(第 2 项) + +`d369666` 新增了裁决所需的字段: +- `stormCompletions`、`teardownCompletions`; +- `settled[8]`,每项记录 `kind`、`written`、`doneBefore`、`samples`、`regressed`、`firstRegressionNs`、`lowest`; +- `regressions`,表示出现过回退的记录数。 + +回退的含义:写槽之后,GPU 又写入了比 `written` 更小的戳,说明被当作"已销毁"的工作其实还留着,并且执行了。 + +| 观测(每次风暴单独判定) | 裁决 | +|---|---| +| 任一 `kind=Storm` 的记录 `regressed>0`,且该索引在写入到首次回退之间没有出现在 `TGLRecoveryLive` 的复位记录里 | **立即加 `-wex-no-orphan-storm` 下线 B 类**。规则完成了被保留的工作,正是 §12.5 担心的情形 | +| 同上,但两者之间有该索引的复位 | 不能下结论,可能是复位重写了槽。保留数据,继续观察 | +| `stormCompletions>0`,相关记录 `samples>0` 且 `regressed==0`,风暴在数秒内收敛,没有应用侧异常或 GPU 页错误 | **继续观察**。至少积累 3 次独立风暴才可称"实机有效",即便如此也只是"未观察到被保留的工作"。采样只在有事件完成时进行,所以零回退的证据强度低于一次正回退 | +| `stormCompletions>0`,但同一索引的复位仍在持续,风暴不收敛 | 规则无效,下线,不要加强 | +| 风暴中 `stormCompletions==0`,`lastReason` 多为 Owner、RingBusy、OwnerUnknown | 规则没有触发,B 类问题照旧。是否往 §12.5 方向加守卫,要先看这些拒绝原因合不合理 | +| 本观察期内没有风暴 | 不裁决,保持现状 | + +另外,一条记录的 `samples==0`(写入后 60 s 内没有任何事件完成)不算任何一方的证据。 + +### 13.3 C 类拆除豁免(第 3 项) + +- 现在每次 C 类完成都会记录将死拥有者所在的端口(`KindTeardownActive` 或 `KindTeardownPending`)。 +- **最低成本的加强**:如果实机上 C 类完成全部来自 active 端口,就把豁免收窄到只认 active。只需改一行,测试已有现成用例。这样 `RING_HEAD/TAIL` 读到的一定是将死上下文自己的环,"pending 端口"这块盲区就消除了。 +- pending 端口的正式判据,是读该上下文 LRC 映像里保存的 RING_HEAD/TAIL。需要从二进制取 `IGHardwareContext` 到 LRC 的偏移,交给本机静态分析处理。 +- "后写 PIPE_CONTROL 尚未落地"没有低成本判据。 +- 在这之前维持"接受并观察"。 + +### 13.4 跨引擎 BCS 善后(第 4 项) + +- `0x0e009002` 是 MI_SEMAPHORE_WAIT:PPGTT 地址(bit22=0)、轮询模式(bit15)、比较方式 SAD≥SDD(bits14:12=001)。 + 等待目标是**进程可见的 PPGTT 地址**,可能是 Metal 事件或栅栏,不是内核 GGTT 戳槽。所以孤儿规则写槽不会解除它,这一点是好的,因为没有伪造完成。 +- **#109 gpurec 的"兄弟引擎"指的是 RCS↔CCS**:两者共享 GDRST 渲染域。gpurec 做的是在 RCS 复位后重建 CCS 被清掉的 HWS_PGA 和 RCU_MODE。BCS 属于另一个复位域,gpurec 不会复位它。G83 上 CCS 已被 `-wex-noccs` 禁用,兄弟路径根本没有作用对象。**移植 gpurec 解决不了 BCS 等待,不建议移植。** +- 原生路径对 BCS 自身有挂起检测:历史上 9 份 BCS 报告就是原生复位 BCS 生成的。所以连锁问题在原生层面会收敛,代价是多一次复位。 +- **最小方案**: + 1. `0466e43` 已移植只读见证。下次 BCS 失败时,它记录等待目标、比较值、CPU 侧读到的前后值以及映射,回答"生产者已完成但 BCS 仍在等"还是"值永远不会到"。 + 2. 只有当见证显示等待确实无法满足、而且 BCS 复位循环不收敛时,才考虑在 RCS 复位时同步走**原生** BCS 复位。风险:BCS 上其他进程的无辜工作会被一起销毁,所以必须有"BCS 正在等的就是本次被销毁的生产者"这一身份证据才可以做。 + 3. 任何情况下都**不写信号量值**,那等于伪造完成。 + +### 13.5 恢复戳等待超时(清单 §5) + +- 唯一样本(`target 0xcc54 / observed 0xcc4a`,日期按 D4 应为 12-02 12:01)说明恢复戳排在 10 个尚未完成的戳后面。1 s 超时量的是"复位后重放的工作是否推进",并不说明戳丢了。 +- **锁内重试**会在同一个队列上空等,所以设计上禁止它是对的。 +- **锁外补发也不安全**,原因有两点: + - 写环尾归原生锁所有,锁外提交会和原生提交竞争。 + - 补发会让该索引的 submitted 再加一。如果补发的戳同样到不了,就凭空制造出一个新的未满足戳,正好喂给 B 类风暴。 +- **结论:不做行为改动。** 判断这次超时是"晚到"还是"一直没到",可以看该索引后来有没有出现事件超时: + - 晚到:`done` 追上 `target`,不再超时。 + - 没到:触发新的事件段,由 `7e6bdc2` 的"本通道复位"关联处理,并在 §13.2 的数据里出现。 +- 如果这种超时反复出现,要修的是重放变慢或再次挂起的原因,也就是挂起本身,而不是等待方式。 + +### 13.6 DEBUG 栈预算(清单 §6) + +- `18ad5d0` 已修复,验证级别是构建级。 +- `processTGLAccelerator` 的帧:DEBUG 从 6360 B 降到 5784 B,RELEASE 从 2280 B 降到 2136 B。 +- 拆出的 `installTGLRecovery` 和 `installTGLOrphan` 帧分别为 472/360 B(DEBUG)和 376/232 B(RELEASE)。安装期最深的调用链在 RELEASE 下最多增加 232 B,只发生在 kext 启动时。 +- 新函数放在 `processTGLAccelerator` 之后,因为 `tests/xelp_video_irq.py` 会按函数名切取源码。 +- 需要实机确认 `TGLRecoverySinglePassReady` 和 `TGLOrphanObserveReady` 仍为 Yes,并在 x86 上跑 `--accelerator` 原版回放。 + +### 13.7 禁用的试验补丁(清单 §7) + +背景: +- 这五项是上游维护者在 `964549e`(10-18)把统一构建改为默认关闭的,没有公开失败原因。上游 #239 已经问过"打开时出了什么问题",在我读到的内容里还没有答复。 +- #239(RPL-HX,同属 Gen12 LP)列出的挂起 IPEHR 家族包含 `0x7a000004` 和 `0x7105000d`,**与 G83 B 类的首发指令相同**。 + +| 位 | 试验 | 与本机挂起的关系 | 外部证据 | 预期收益 | 回归风险 | 建议 | +|---|---|---|---|---|---|---| +| 1 | 外层 RCS 完成包的常量缓存替代 | 只改等待者 PIPE_CONTROL 的失效位;#200 结论是 walker 永远不会完成,PIPE_CONTROL 只是在等它 | 无 | 低 | 中:每次 RCS 提交的完成包都会变,影响戳的可见性 | 暂不试 | +| 2 | INDIRECT_CTX(Wa_18022495364) | 同属状态缓存失效这一类 | #239 **单独**试过,现场确认与 Linux 一致:**无效**,还出现了一次新形态挂起(BB 开始后取到了数据页) | 低 | 中:每次 RCS 恢复都会改上下文映像 | 先向上游问清当初为什么禁用 | +| 4 | same-tail 强制恢复 | 与复位后重放同一 tail 的提交有关,风暴里正好有大量重放 | 无(Linux 也避免相同 tail 的轻量恢复) | 中低 | 低到中:只在"见证过的相同 tail 重提交"时触发 | **如果要试,排第一** | +| 8 | GSYNC 禁用(TGL B0 B0A0[2]) | 与计算挂起没有直接关系 | 无 | 低 | 未知 | 不试 | +| 16 | RPCS 全 slice | 功耗与 slice 配置 | #239 的组合包里包含 RPCS 单 slice,结果无效 | 低 | 功耗和性能 | 不试 | + +试验规则: +- 一次只开一项。 +- **不要与 B 类规则的裁决期重叠**,否则互相干扰,无法归因。 +- B 类事件有概率性(曾连续 78 小时零事件),每项至少需要数周窗口加上 IPEHR 家族统计才能下结论。 + +### 13.8 低优先 + +- **SyncFlip**:当初做成独立插件,是因为本机跑的是闭源下游 WEX,无法改它(11-16 的判断)。现在 G83 已经是源码构建的 WEX,这个前提不存在了。 + - 建议把同步翻页的模式逻辑直接放进 WEX:framebuffer 的 kext 处理器本来就由 WEX 持有,可以彻底避开 Lilu 重复注册导致的 `AlreadyDone` 和 AuxKC 回调问题。 + - 如果继续用插件,在全局回调入口加一个"收到过任意 index"的计数,区分"回调从未触发"和"触发了但锚点不符"。 +- **外接屏唤醒约 7 秒**:同意维护者结论,没有 WEX 可修的地方。 + +### 13.9 自检 + +- **有没有把未实机验证的内容写成"已修复"?** 没有。三个提交的验证级别都是 CPU 或构建级;WiFi 部分只有分析。 +- **有没有伪造完成或禁用服务?** 没有。`0466e43` 和 `d369666` 只读,除了诊断表不写任何东西;`18ad5d0` 是纯代码搬移。 +- **有没有改动 GPU 以外的东西?** 没有。WiFi 部分没有改代码。 diff --git a/driver/G83/WhateverXe/kern_tgl_hang_bcs_wait.hpp b/driver/G83/WhateverXe/kern_tgl_hang_bcs_wait.hpp new file mode 100644 index 0000000..64c8545 --- /dev/null +++ b/driver/G83/WhateverXe/kern_tgl_hang_bcs_wait.hpp @@ -0,0 +1,95 @@ +// Failure-only CPU witnesses near a saved BCS head. Candidate instructions and +// software PTEs do not establish the GPU's active packet or cached translation. +#ifndef kern_tgl_hang_bcs_wait_hpp +#define kern_tgl_hang_bcs_wait_hpp +#include "kern_tgl_hang_pending.hpp" +#include "kern_tgl_ppgtt.hpp" +namespace TGLHangBCSWait { +using TGLHangPending::kernelRange; +using TGLHangPending::u32; +enum Field {Context,Owner,Task,Table,TableClass,LRCBuffer,LRCCPU,LRCSize, + RingBuffer,RingCPU,RingSize,RingLength,ContextID,Root,Fields}; +struct Candidate { + // ring offset, header, comparison data, target GPU address, guard, + // CPU value before/after, unsigned GTE satisfied before/after. + uint64_t q[9]; + TGLPPGTT::Mapping before,after; +}; +struct Capture { + // schema, guard, begin/end ns, ring, saved head/tail/start, window offset, + // number of candidate headers, reserved. Guard 0 means CPU witnesses stable. + uint64_t q[16],before[Fields],after[Fields]; + uint32_t words[16],recheck[16]; + Candidate candidates[4]; +}; +static_assert(sizeof(Capture)<4096,"bounded BCS wait evidence"); +template +bool ownership(uint64_t *q,uint64_t ring,uint64_t expectedClass,Read &read) { + auto get=[&](uint64_t p,unsigned offset,uint64_t &v,unsigned n=8) { + v=0;return kernelRange(p,offset+n) && read(p+offset,&v,n)==n; + }; + uint64_t engine=0,contextEngine=0,owner=0,back=0,lrc=0,hi=0,lo=0; + if(!get(ring,0x40,engine,1) || engine!=2 || !get(ring,0x20,q[Context]) || + !get(q[Context],0x6c,contextEngine,1) || contextEngine!=2 || + !get(ring,0x10,q[Owner]) || !q[Owner] || !get(q[Context],0x50,owner) || owner!=q[Owner] || + !get(q[Context],0xb0,back) || back!=ring || + !get(q[Context],0x58,q[Task]) || !get(q[Task],0x260,q[Table]) || + !get(q[Table],0,q[TableClass]) || !expectedClass || q[TableClass]!=expectedClass || + !get(q[Context],0x98,q[LRCBuffer]) || !get(q[LRCBuffer],0x38,q[LRCCPU]) || + !get(q[LRCBuffer],0x20,q[LRCSize]) || !get(ring,0x18,lrc) || lrc!=q[LRCCPU] || + !get(ring,0x80,q[RingBuffer]) || !get(q[RingBuffer],0x38,q[RingCPU]) || + !get(q[RingBuffer],0x20,q[RingSize]) || !get(ring,0x8c,q[RingLength],4) || + !get(q[Context],0x7c,q[ContextID],4))return false; + if(q[LRCSize]<8192 || q[LRCSize]>81920 || (q[LRCSize]&4095) || + !kernelRange(q[LRCCPU],q[LRCSize]) || (q[LRCCPU]&4095) || + q[RingLength]<4096 || q[RingLength]>32768 || (q[RingLength]&(q[RingLength]-1)) || + q[RingSize] +void collect(Capture &c,uint64_t ring,const uint8_t *regs,uint64_t expectedClass, + uint64_t directBase,uint64_t directEnd,Read read) { + c.q[0]=1;c.q[1]=1;c.q[4]=ring; + c.q[5]=u32(regs)&0x1ffffc;c.q[6]=u32(regs+4);c.q[7]=u32(regs+12); + if(regs[0x94]!=2 || !ownership(c.before,ring,expectedClass,read))return; + const auto b=c.before; + c.q[1]=2; + if(b[ContextID]!=((u32(regs+0xac)>>5)&2047) || c.q[5]>=b[RingLength])return; + c.q[8]=(c.q[5]+b[RingLength]-16)&(b[RingLength]-1); + auto window=[&](uint32_t *out) { + for(unsigned i=0;i<16;++i) + if(read(b[RingCPU]+((c.q[8]+i*4)&(b[RingLength]-1)),out+i,4)!=4)return false; + return true; + }; + c.q[1]=3;if(!window(c.words))return; + auto read64=[&](uint64_t p,uint64_t &v) { + return kernelRange(p,8) && read(p,&v,8)==8; + }; + // Exact observed Gen8+ PPGTT polling/GTE packet. Do not reinterpret GGTT, + // token waits, unknown compare modes, or partial headers as this packet. + // Bit definitions: Linux i915 gt/intel_gpu_commands.h, MI_SEMAPHORE_WAIT. + for(unsigned i=0;i+4<=16 && c.q[9]<4;++i)if(c.words[i]==0x0e009002) { + auto &d=c.candidates[c.q[9]++];auto q=d.q; + q[0]=(c.q[8]+i*4)&(b[RingLength]-1);q[1]=c.words[i];q[2]=c.words[i+1]; + q[3]=uint64_t(c.words[i+2])|(uint64_t(c.words[i+3])<<32);q[4]=1; + if(!q[3] || q[3]>>47 || (q[3]&3))continue; + d.before=TGLPPGTT::inspect(b[Table],q[3],read64);const auto &m=d.before; + q[4]=2; + if(m.status || m.rootPhysical!=b[Root] || m.physical>UINT64_MAX-directBase)continue; + const uint64_t cpu=directBase+m.physical; + q[4]=3; + if(!kernelRange(cpu,4) || cpu=directEnd || directEnd-cpu<4)continue; + uint32_t first=0,last=0; + if(read(cpu,&first,4)!=4 || read(cpu,&last,4)!=4)continue; + q[5]=first;q[6]=last;q[7]=first>=q[2];q[8]=last>=q[2]; + d.after=TGLPPGTT::inspect(b[Table],q[3],read64);q[4]=4; + if(!memcmp(&d.before,&d.after,sizeof(d.before)))q[4]=0; + } + c.q[1]=4; + if(!window(c.recheck) || memcmp(c.words,c.recheck,sizeof(c.words)) || + !ownership(c.after,ring,expectedClass,read) || memcmp(c.before,c.after,sizeof(c.before)))return; + c.q[1]=0; +} +} +#endif diff --git a/driver/G83/WhateverXe/kern_tgl_hang_pending.hpp b/driver/G83/WhateverXe/kern_tgl_hang_pending.hpp index 9205c3b..7e2f47f 100644 --- a/driver/G83/WhateverXe/kern_tgl_hang_pending.hpp +++ b/driver/G83/WhateverXe/kern_tgl_hang_pending.hpp @@ -29,9 +29,18 @@ void collect(Capture &c,uint64_t address,const uint8_t *regs,const uint8_t *ring return kernelRange(p,n) && read(p,out,n)==n; }; c.q[2]=1; - if(regs[0x94] || ring[0x40] || c.q[7]>=64 || c.q[10]>=64 || + // The same native submit-bank layout is used by the BCS ring. Admit only + // matching RCS/BCS engine snapshots; never decode a different engine's cache. + const uint8_t engine=regs[0x94]; + if((engine!=0 && engine!=2) || ring[0x40]!=engine || c.q[7]>=64 || c.q[10]>=64 || !kernelRange(address,0x8a8) || !kernelRange(c.q[4],0x80)) return; uint32_t owner=0,retired=0;const uint64_t stamps=u64(ring+0x30); + // RCS retains its existing contract. Before adding BCS capture require the + // context's engine, owner and ring backlink to agree with the saved ring. + uint8_t contextEngine=0;uint64_t contextOwner=0,contextRing=0; + if(engine==2 && (!copy(c.q[4]+0x6c,&contextEngine,1) || contextEngine!=engine || + !copy(c.q[4]+0x50,&contextOwner,8) || !contextOwner || contextOwner!=u64(ring+0x10) || + !copy(c.q[4]+0xb0,&contextRing,8) || contextRing!=address)) return; c.q[2]=2; if(!copy(c.q[4]+0x7c,&owner,4) || !kernelRange(stamps,4096) || !copy(stamps+c.q[7]*64,&retired,4)) return; @@ -63,6 +72,14 @@ void collect(Capture &c,uint64_t address,const uint8_t *regs,const uint8_t *ring c.q[9]=finalRetired;c.q[2]=5; if(context!=c.q[4] || stampBase!=stamps || index!=c.q[7] || write!=c.q[10] || finalOwner!=owner || finalRetired!=retired) return; + if(engine==2) { + uint8_t finalEngine=0,finalContextEngine=0;uint64_t finalContextOwner=0,finalContextRing=0,finalRingOwner=0; + if(!copy(address+0x40,&finalEngine,1) || finalEngine!=engine || + !copy(address+0x10,&finalRingOwner,8) || finalRingOwner!=contextOwner || + !copy(context+0x6c,&finalContextEngine,1) || finalContextEngine!=engine || + !copy(context+0x50,&finalContextOwner,8) || finalContextOwner!=contextOwner || + !copy(context+0xb0,&finalContextRing,8) || finalContextRing!=address) return; + } c.q[2]=0; } } diff --git a/driver/G83/WhateverXe/kern_tgl_orphan.hpp b/driver/G83/WhateverXe/kern_tgl_orphan.hpp index 3051bd4..04c1267 100644 --- a/driver/G83/WhateverXe/kern_tgl_orphan.hpp +++ b/driver/G83/WhateverXe/kern_tgl_orphan.hpp @@ -14,11 +14,22 @@ #define kern_tgl_orphan_hpp #include namespace TGLOrphan { -constexpr unsigned Indices=64,LogSlots=8; +constexpr unsigned Indices=64,LogSlots=8,SettledSlots=8; struct Episode { uint64_t first,last; uint32_t idx,sent,done,timeouts; }; +// One settled stamp (round 3, for the hardware verdict). kind: KindStorm, +// or the port(s) whose dying owner admitted the teardown exemption. After the +// write, sampleSettled() re-reads the slot: a value below `written` means the +// GPU later wrote an older stamp, i.e. work the rule treated as destroyed was +// retained and executed. `slot` 0 = sampling ended (window over, or the +// index's stamp table, slot or submitted count changed). +enum Kind : uint32_t { KindStorm=1, KindTeardownActive=2, KindTeardownPending=4 }; +struct Settled { + uint64_t ns,slot,stamps,firstRegressionNs; + uint32_t idx,written,doneBefore,kind,lowest,regressed,samples,pad; +}; struct Table { uint64_t calls,invalidIdx,loops,logNext; // Raw hop values of the latest observation; self-validates the offsets at @@ -30,6 +41,10 @@ struct Table { uint32_t typeSeen,lutSeen; Episode current[Indices]; Episode log[LogSlots]; + // Appended in round 3; the fields above keep their offsets for existing + // decoders. completions = stormCompletions + teardownCompletions. + uint64_t stormCompletions,teardownCompletions,regressions,samples,settledNext; + Settled settled[SettledSlots]; }; // Reason bits for the last decision (0 = completed). UnusableIdx: an // event-machine hop (accel, stamps, submitted, slot) was unreadable. Before @@ -297,6 +312,7 @@ template Decision evaluate(Env &env,Table &t,const Marks &marks,const g.streamer=streamerOK; // Not read is reported as unreadable, never as a busy ring. g.ringUnreadable=true; + bool exemptActive=false,exemptPending=false; if (g.streamer) { // Active/pending contexts exactly as the native timeout obtains them, // through the scheduler vtable, but only when that slot is the solved @@ -318,8 +334,9 @@ template Decision evaluate(Env &env,Table &t,const Marks &marks,const g.owner=ownerBlocks(ownsActive==Owns::Yes,dyingContext(td,active))|| ownerBlocks(ownsPending==Owns::Yes,dyingContext(td,pending)); // The exemption was used: an owner exists and every owner is dying. - g.teardownExempt=!g.owner && ((ownsActive==Owns::Yes && dyingContext(td,active))|| - (ownsPending==Owns::Yes && dyingContext(td,pending))); + exemptActive=!g.owner && ownsActive==Owns::Yes && dyingContext(td,active); + exemptPending=!g.owner && ownsPending==Owns::Yes && dyingContext(td,pending); + g.teardownExempt=exemptActive || exemptPending; if (g.teardownExempt && gap>MaxTeardownGap) g.gapOK=false; uint64_t bar {}; if (env.u64(streamer+Off::StreamerBar,bar) && bar) { @@ -350,8 +367,37 @@ template Decision evaluate(Env &env,Table &t,const Marks &marks,const env.store32(slot,sent); env.signal(accel,1ULL<(idx)); ++t.completions; + if (g.teardownExempt) ++t.teardownCompletions; else ++t.stormCompletions; + Settled &r=t.settled[t.settledNext%SettledSlots]; + r={}; + r.slot=slot;r.stamps=stamps;r.idx=static_cast(idx); + r.written=sent;r.doneBefore=done;r.lowest=sent; + r.kind=g.teardownExempt ? ((exemptActive ? KindTeardownActive : 0U)|(exemptPending ? KindTeardownPending : 0U)) : KindStorm; + __atomic_store_n(&r.ns,now,__ATOMIC_RELEASE); + ++t.settledNext; return {true,0}; } +// Re-read settled slots for SampleWindowNs after the write. Writes only the +// table, under the caller's gate. Called from both wrappers with the event +// machine they received; a record of another machine is left alone. +constexpr uint64_t SampleWindowNs=60000000000ULL; +template void sampleSettled(Env &env,Table &t,uint64_t machine,uint64_t now) { + for (auto &r:t.settled) { + if (!r.slot) continue; + if (nowSampleWindowNs) {r.slot=0;continue;} + uint64_t stamps {},slot {};uint32_t sent {},value {}; + if (!env.u64(machine+Off::MachineStamps,stamps) || stamps!=r.stamps) continue; + if (!env.u64(stamps+static_cast(r.idx)*8,slot) || slot!=r.slot || + !env.u32(machine+Off::MachineSent+static_cast(r.idx)*Off::SentStride,sent) || + static_cast(sent-r.written)<0) {r.slot=0;continue;} // index reused or reset + if (!env.u32(slot,value)) continue; + ++r.samples;++t.samples; + if (static_cast(value-r.written)<0) { + if (!r.regressed++) {r.firstRegressionNs=now;++t.regressions;} + if (static_cast(value-r.lowest)<0) r.lowest=value; + } + } +} // Serialises evaluations: the episode table and audit fields are shared by // every thread that reaches eventTimeout. A busy gate is never waited on. @@ -362,9 +408,24 @@ template Decision evaluateExclusive(Env &env,Gate &gate,Table &t,cons if (!__atomic_compare_exchange_n(&gate.busy,&expected,1U,false,__ATOMIC_ACQUIRE,__ATOMIC_RELAXED)) return {false,Contended}; const Decision d=evaluate(env,t,marks,c,machine,idx); + if (machine && t.completions) sampleSettled(env,t,machine,env.now()); __atomic_store_n(&gate.busy,0U,__ATOMIC_RELEASE); return d; } +// finishEvent path: no gate traffic unless the newest settled record is +// inside the window. A busy gate skips this sample (never waits). +template void sampleExclusive(Env &env,Gate &gate,Table &t,uint64_t machine) { + if (!machine || !__atomic_load_n(&t.completions,__ATOMIC_RELAXED)) return; + const uint64_t next=__atomic_load_n(&t.settledNext,__ATOMIC_RELAXED); + const uint64_t newest=__atomic_load_n(&t.settled[(next+SettledSlots-1)%SettledSlots].ns,__ATOMIC_ACQUIRE); + const uint64_t now=env.now(); + if (!newest || nowSampleWindowNs) return; + uint32_t expected=0; + if (!__atomic_compare_exchange_n(&gate.busy,&expected,1U,false,__ATOMIC_ACQUIRE,__ATOMIC_RELAXED)) + return; + sampleSettled(env,t,machine,now); + __atomic_store_n(&gate.busy,0U,__ATOMIC_RELEASE); +} // finishEvent entry: mark the current thread when the caller is one of the // teardown sites, recording the hardware contexts the event's owner holds. diff --git a/driver/G83/WhateverXe/kern_xe.cpp b/driver/G83/WhateverXe/kern_xe.cpp index 6ea16dd..ef21149 100644 --- a/driver/G83/WhateverXe/kern_xe.cpp +++ b/driver/G83/WhateverXe/kern_xe.cpp @@ -114,6 +114,7 @@ void endTGLBootMode(void *path) { #include "kern_xelp_queue_memory.hpp" #include "kern_tgl_hang_refs.hpp" #include "kern_tgl_hang_pending.hpp" +#include "kern_tgl_hang_bcs_wait.hpp" #include "kern_tgl_hang_detail.hpp" #include "kern_tgl_hang_ggtt.hpp" #include "kern_tgl_hang_prestop.hpp" @@ -489,6 +490,8 @@ uint64_t XE::wrapTGLOrphanFinish(void *machine,void *event,uint32_t reason) { const uint64_t r=(callbackXE && callbackXE->orgTGLOrphanFinish) ? FunctionCast(wrapTGLOrphanFinish,callbackXE->orgTGLOrphanFinish)(machine,event,reason) : 0; TGLOrphan::leave(mine); + // Read-only witness for settled stamps (no-op until the first completion). + TGLOrphan::sampleExclusive(env,tglOrphanGate,tglOrphanTable,reinterpret_cast(machine)); return r; } @@ -13107,114 +13110,10 @@ bool XE::processTGLAccelerator(KernelPatcher &patcher, size_t index, mach_vm_add // resets keep the single-pass reset/account/resume contract. // Select by firmware mode and exact donor ABI, not host OS or machine. const bool recoveryRequested=checkKernelArgument("-disablegfxfirmware"); - bool recoveryOK=!recoveryRequested; - if (recoveryRequested) { - const char *recovery="__ZN18IGAccelFIFOChannel22resetHardwareAndReplayEv"; - const uint8_t head[] {0x55,0x48,0x89,0xE5,0x41,0x57,0x41,0x56,0x41,0x54,0x53,0x48,0x83,0xEC,0x10, - 0x49,0x89,0xFF,0x4C,0x8B,0xB7,0x30,0x01,0,0,0x4C,0x8D,0x65,0xDC,0x49,0x8B,0x06, - 0x49,0x8B,0x76,0x20,0x48,0x8B,0x9E,0xB8,0,0,0}; - const uint8_t failedAndResume[] {0xFF,0x83,0x7C,0x01,0,0,0x49,0x8B,0x47,0x18,0x48,0x8B,0xB8,0x50,0x12,0,0, - 0x48,0x8B,0x07,0xFF,0x90,0x80,0x01,0,0}; - const uint8_t successDispatch[] {0xFF,0x90,0x68,0x01,0,0,0x84,0xC0,0x74,0x09,0x41,0x80,0x7E,0x40,0,0x74,0x08,0xEB,0x72}; - const uint8_t successPath[] {0x49,0x8B,0x47,0x18,0x48,0x8B,0xB8,0x50,0x12,0,0,0x48,0x8B,0x07,0xFF,0x90,0x80,0x01,0,0, - 0x48,0x85,0xDB,0x74,0xDA,0x49,0x8B,0x47,0x18,0x48,0x8B,0xB8,0x80,0x03,0,0,0x8B,0x73,0x20,0x48,0x8B,0x07,0xFF,0x90,0xD8,0x01,0,0, - 0x48,0x89,0xDF,0xE8,0xFD,0xF9,0xFF,0xFF,0x8B,0x93,0x78,0x01,0,0,0x48,0x8D,0x75,0xD8,0x4C,0x89,0xF7,0xB9,0x40,0x42,0x0F,0, - 0xE8,0xC4,0x54,0xFF,0xFF,0x84,0xC0,0x74,0xA0,0xFF,0x83,0x7C,0x01,0,0,0xEB,0x98}; - const uint8_t submitHead[] {0x55,0x48,0x89,0xE5,0x41,0x56,0x53,0x48,0x83,0xEC,0x10,0x48,0x8B,0x47,0x18,0xF6,0x80,0x78,0x0C,0,0,0x02}; - const auto submit=patcher.solveSymbol(index,"__ZN18IGAccelFIFOChannel18submitStampCommandEv",address,size); - // hostOK already qualifies and routes this exact sleep entry. Call - // the routed entry, as the native E8 does, not the saved trampoline. - recoveryOK=hostOK && orgTGLHostWait && size>0xDF668 && submit==address+0x4C506 && - patcher.solveSymbol(index,recovery,address,size)==address+0x4CA1E && - patcher.solveSymbol(index,"__ZN20IGHardwareRingBuffer19resetGraphicsEngineEP17IGHardwareContext",address,size)==address+0x43576 && - patcher.solveSymbol(index,"__ZN12IGScheduler56resumeEv",address,size)==address+0x3906C && - !memcmp(reinterpret_cast(address+0x4CA1E),head,sizeof(head)) && - !memcmp(reinterpret_cast(address+0x4CA5F),failedAndResume,sizeof(failedAndResume)) && - !memcmp(reinterpret_cast(address+0x4CA4C),successDispatch,sizeof(successDispatch)) && - !memcmp(reinterpret_cast(address+0x4CAD1),successPath,sizeof(successPath)) && - !memcmp(reinterpret_cast(submit),submitHead,sizeof(submitHead)); - patcher.clearError(); - if (recoveryOK) { - // The native poll loses GDRST bits above bit 7 and can wait - // indefinitely. Preserve its exact entry/continuations, including - // scratch handling, and use its false exit on an unacknowledged reset. - static const uint8_t poll[] {0x4c,0x8d,0x3d,0xff,0x84,0x10,0x00,0x8b,0x88,0x1c,0x94,0x00,0x00,0x0f,0xb6,0xd9,0x8b,0x88,0xc4,0xce,0x00,0x00,0xf6,0xc1,0x01,0x74,0x1d,0xc7,0x80,0x00,0x41,0x00,0x00,0xb1,0xb1,0xf0,0xf0,0xc7,0x80,0x04,0x41,0x00,0x00,0xb2,0xb2,0xf0,0xf0,0x83,0xe1,0xfe,0x89,0x88,0xc4,0xce,0x00,0x00,0x4c,0x89,0xff,0x31,0xf6,0xba,0x0a,0x00,0x00,0x00,0xb9,0xe8,0x03,0x00,0x00,0xe8,0x00,0x00,0x00,0x00,0x31,0xff,0xe8,0x00,0x00,0x00,0x00,0x41,0x85,0x5c,0x24,0x70}; - const int64_t delta=reinterpret_cast(tglResetPollBridge)-static_cast(address+0x43783); - static const uint8_t done[]{0x49,0x8b,0x44,0x24,0x50,0x75,0xa8,0xc7,0x80,0x08,0x4a,0,0,0,0,4,0}; - // The two imported call displacements are relocated by the kernel. - recoveryOK=!memcmp(reinterpret_cast(address+0x4377e),poll,72) && - !memcmp(reinterpret_cast(address+0x437ca),poll+76,3) && - !memcmp(reinterpret_cast(address+0x437d1),poll+83,5) && - !memcmp(reinterpret_cast(address+0x437d6),done,sizeof(done)) && delta>=INT32_MIN && delta<=INT32_MAX; - if(recoveryOK) { - tglResetPollSuccess=address+0x437dd;tglResetPollFailure=address+0x4374c; - uint8_t branch[5]{0xe9};const auto relative=static_cast(delta);memcpy(branch+1,&relative,4); - patcher.routeBlock(address+0x4377e,branch,sizeof(branch)); - recoveryOK=patcher.getError()==KernelPatcher::Error::NoError && !memcmp(reinterpret_cast(address+0x4377e),branch,sizeof(branch)); - } - patcher.clearError(); - } - IORegistryEntry::getRegistryRoot()->setProperty("TGLResetDomainPollReady",recoveryOK); - if (recoveryOK) { - tglRecoveryStamp={reinterpret_cast(submit),reinterpret_cast(address+0x41FE4)}; - KernelPatcher::RouteRequest hook[] {{recovery,wrapTGLRecovery,orgTGLRecovery}}; - recoveryOK=patcher.routeMultiple(index,hook,arrsize(hook),address,size); - } - if (recoveryOK) if (auto live=OSSerializer::forTarget(nullptr,tglRecoverySerialize)) { - IORegistryEntry::getRegistryRoot()->setProperty("TGLRecoveryLive",live);live->release(); - } - } - bool orphanOK=false; - if (recoveryRequested) { - const char *orphanTimeout="__ZN19IGAccelEventMachine12eventTimeoutEi"; - const uint8_t orphanHead[] {0x55,0x48,0x89,0xE5,0x41,0x57,0x41,0x56,0x41,0x55,0x41,0x54,0x53,0x48,0x83,0xEC,0x18, - 0x41,0x89,0xF5,0x49,0x89,0xFE,0x48,0x8B,0x47,0x10}; - const auto stampUpdate=patcher.solveSymbol(index, - "__ZN16IntelAccelerator17signalStampUpdateERK8IGBitSetILm64EE",address,size); - const char *finish="__ZN19IGAccelEventMachine11finishEventEP12IOAccelEventj"; - const uint8_t finishHead[] {0x55,0x48,0x89,0xE5,0x41,0x57,0x41,0x56,0x41,0x54,0x53, - 0x41,0x89,0xD7,0x48,0x89,0xFB}; - orphanOK=size>0xA02D0 && stampUpdate==address+0x2AB4E && - patcher.solveSymbol(index,orphanTimeout,address,size)==address+0x15F22 && - !memcmp(reinterpret_cast(address+0x15F22),orphanHead,sizeof(orphanHead)) && - // The LUT and scheduler offsets the decision reads are the ones - // this eventTimeout body uses; a drifted body means no install. - TGLOrphan::anchorsMatch([address](uint32_t offset,uint8_t &b) { - b=*reinterpret_cast(address+offset);return true;}) && - patcher.solveSymbol(index,finish,address,size)==address+0x15E90 && - !memcmp(reinterpret_cast(address+0x15E90),finishHead,sizeof(finishHead)); - // The teardown sites must match byte-for-byte before the rule - // installs: the call to finishEvent, its displacement and the - // reason immediate at each verified return address. - if (orphanOK) { - auto readImg=[](void *ctx,uint64_t off,uint8_t &v)->bool { - v=*reinterpret_cast(reinterpret_cast(ctx)+off); - return true; - }; - for (const auto &c:TGLOrphan::SiteCalls) - orphanOK=orphanOK && TGLOrphan::verifySite(c,0x15E90,readImg, - reinterpret_cast(address)); - } - patcher.clearError(); - if (orphanOK) { - tglOrphanAccelBase=address; - tglOrphanSignalUpdate=stampUpdate; - // The owner guard calls scheduler vtable+0x198 only when it is - // this routine (anchor audit 2026-11-13: 0x380EC); otherwise the - // observer runs but the rule reports OwnerUnknown and never writes. - const auto active=patcher.solveSymbol(index, - "__ZN12IGScheduler517getActiveContextsE10IGHwCsTypePP17IGHardwareContextPyS3_",address,size); - tglOrphanActiveContexts=active==address+0x380EC ? active : 0; - patcher.clearError(); - tglOrphanKillSwitch=checkKernelArgument("-wex-no-orphan-complete"); - tglOrphanStormOff=checkKernelArgument("-wex-no-orphan-storm"); - KernelPatcher::RouteRequest hook[] { - {orphanTimeout,wrapTGLOrphanTimeout,orgTGLOrphanTimeout}, - {finish,wrapTGLOrphanFinish,orgTGLOrphanFinish}}; - orphanOK=patcher.routeMultiple(index,hook,arrsize(hook),address,size); - } - patcher.clearError(); - } + // Separate frames (recovery, orphan): keep processTGLAccelerator inside + // the DEBUG stack budget. Both are moved unchanged. + const bool recoveryOK=!recoveryRequested || installTGLRecovery(patcher,index,address,size,hostOK); + const bool orphanOK=recoveryRequested && installTGLOrphan(patcher,index,address,size); IORegistryEntry::getRegistryRoot()->setProperty("TGLOrphanObserveReady",orphanOK); if (orphanOK) if (auto live=OSSerializer::forTarget(nullptr,tglOrphanSerialize)) { IORegistryEntry::getRegistryRoot()->setProperty("TGLOrphanLive",live);live->release(); @@ -13241,6 +13140,124 @@ bool XE::processTGLAccelerator(KernelPatcher &patcher, size_t index, mach_vm_add return true; } +// Single-pass recovery installation for the exact 16.0.32 accelerator (moved +// out of processTGLAccelerator unchanged; called only when recovery is +// requested). hostOK is the caller's qualification of the routed sleep entry. +bool XE::installTGLRecovery(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size, bool hostOK) { + bool recoveryOK=false; + const char *recovery="__ZN18IGAccelFIFOChannel22resetHardwareAndReplayEv"; + const uint8_t head[] {0x55,0x48,0x89,0xE5,0x41,0x57,0x41,0x56,0x41,0x54,0x53,0x48,0x83,0xEC,0x10, + 0x49,0x89,0xFF,0x4C,0x8B,0xB7,0x30,0x01,0,0,0x4C,0x8D,0x65,0xDC,0x49,0x8B,0x06, + 0x49,0x8B,0x76,0x20,0x48,0x8B,0x9E,0xB8,0,0,0}; + const uint8_t failedAndResume[] {0xFF,0x83,0x7C,0x01,0,0,0x49,0x8B,0x47,0x18,0x48,0x8B,0xB8,0x50,0x12,0,0, + 0x48,0x8B,0x07,0xFF,0x90,0x80,0x01,0,0}; + const uint8_t successDispatch[] {0xFF,0x90,0x68,0x01,0,0,0x84,0xC0,0x74,0x09,0x41,0x80,0x7E,0x40,0,0x74,0x08,0xEB,0x72}; + const uint8_t successPath[] {0x49,0x8B,0x47,0x18,0x48,0x8B,0xB8,0x50,0x12,0,0,0x48,0x8B,0x07,0xFF,0x90,0x80,0x01,0,0, + 0x48,0x85,0xDB,0x74,0xDA,0x49,0x8B,0x47,0x18,0x48,0x8B,0xB8,0x80,0x03,0,0,0x8B,0x73,0x20,0x48,0x8B,0x07,0xFF,0x90,0xD8,0x01,0,0, + 0x48,0x89,0xDF,0xE8,0xFD,0xF9,0xFF,0xFF,0x8B,0x93,0x78,0x01,0,0,0x48,0x8D,0x75,0xD8,0x4C,0x89,0xF7,0xB9,0x40,0x42,0x0F,0, + 0xE8,0xC4,0x54,0xFF,0xFF,0x84,0xC0,0x74,0xA0,0xFF,0x83,0x7C,0x01,0,0,0xEB,0x98}; + const uint8_t submitHead[] {0x55,0x48,0x89,0xE5,0x41,0x56,0x53,0x48,0x83,0xEC,0x10,0x48,0x8B,0x47,0x18,0xF6,0x80,0x78,0x0C,0,0,0x02}; + const auto submit=patcher.solveSymbol(index,"__ZN18IGAccelFIFOChannel18submitStampCommandEv",address,size); + // hostOK already qualifies and routes this exact sleep entry. Call + // the routed entry, as the native E8 does, not the saved trampoline. + recoveryOK=hostOK && orgTGLHostWait && size>0xDF668 && submit==address+0x4C506 && + patcher.solveSymbol(index,recovery,address,size)==address+0x4CA1E && + patcher.solveSymbol(index,"__ZN20IGHardwareRingBuffer19resetGraphicsEngineEP17IGHardwareContext",address,size)==address+0x43576 && + patcher.solveSymbol(index,"__ZN12IGScheduler56resumeEv",address,size)==address+0x3906C && + !memcmp(reinterpret_cast(address+0x4CA1E),head,sizeof(head)) && + !memcmp(reinterpret_cast(address+0x4CA5F),failedAndResume,sizeof(failedAndResume)) && + !memcmp(reinterpret_cast(address+0x4CA4C),successDispatch,sizeof(successDispatch)) && + !memcmp(reinterpret_cast(address+0x4CAD1),successPath,sizeof(successPath)) && + !memcmp(reinterpret_cast(submit),submitHead,sizeof(submitHead)); + patcher.clearError(); + if (recoveryOK) { + // The native poll loses GDRST bits above bit 7 and can wait + // indefinitely. Preserve its exact entry/continuations, including + // scratch handling, and use its false exit on an unacknowledged reset. + static const uint8_t poll[] {0x4c,0x8d,0x3d,0xff,0x84,0x10,0x00,0x8b,0x88,0x1c,0x94,0x00,0x00,0x0f,0xb6,0xd9,0x8b,0x88,0xc4,0xce,0x00,0x00,0xf6,0xc1,0x01,0x74,0x1d,0xc7,0x80,0x00,0x41,0x00,0x00,0xb1,0xb1,0xf0,0xf0,0xc7,0x80,0x04,0x41,0x00,0x00,0xb2,0xb2,0xf0,0xf0,0x83,0xe1,0xfe,0x89,0x88,0xc4,0xce,0x00,0x00,0x4c,0x89,0xff,0x31,0xf6,0xba,0x0a,0x00,0x00,0x00,0xb9,0xe8,0x03,0x00,0x00,0xe8,0x00,0x00,0x00,0x00,0x31,0xff,0xe8,0x00,0x00,0x00,0x00,0x41,0x85,0x5c,0x24,0x70}; + const int64_t delta=reinterpret_cast(tglResetPollBridge)-static_cast(address+0x43783); + static const uint8_t done[]{0x49,0x8b,0x44,0x24,0x50,0x75,0xa8,0xc7,0x80,0x08,0x4a,0,0,0,0,4,0}; + // The two imported call displacements are relocated by the kernel. + recoveryOK=!memcmp(reinterpret_cast(address+0x4377e),poll,72) && + !memcmp(reinterpret_cast(address+0x437ca),poll+76,3) && + !memcmp(reinterpret_cast(address+0x437d1),poll+83,5) && + !memcmp(reinterpret_cast(address+0x437d6),done,sizeof(done)) && delta>=INT32_MIN && delta<=INT32_MAX; + if(recoveryOK) { + tglResetPollSuccess=address+0x437dd;tglResetPollFailure=address+0x4374c; + uint8_t branch[5]{0xe9};const auto relative=static_cast(delta);memcpy(branch+1,&relative,4); + patcher.routeBlock(address+0x4377e,branch,sizeof(branch)); + recoveryOK=patcher.getError()==KernelPatcher::Error::NoError && !memcmp(reinterpret_cast(address+0x4377e),branch,sizeof(branch)); + } + patcher.clearError(); + } + IORegistryEntry::getRegistryRoot()->setProperty("TGLResetDomainPollReady",recoveryOK); + if (recoveryOK) { + tglRecoveryStamp={reinterpret_cast(submit),reinterpret_cast(address+0x41FE4)}; + KernelPatcher::RouteRequest hook[] {{recovery,wrapTGLRecovery,orgTGLRecovery}}; + recoveryOK=patcher.routeMultiple(index,hook,arrsize(hook),address,size); + } + if (recoveryOK) if (auto live=OSSerializer::forTarget(nullptr,tglRecoverySerialize)) { + IORegistryEntry::getRegistryRoot()->setProperty("TGLRecoveryLive",live);live->release(); + } + return recoveryOK; +} + +// Orphan-rule installation for the exact 16.0.32 accelerator (moved out of +// processTGLAccelerator unchanged; called only when recovery is requested). +// Any anchor, site or route mismatch returns false and nothing is routed. +bool XE::installTGLOrphan(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size) { + bool orphanOK=false; + const char *orphanTimeout="__ZN19IGAccelEventMachine12eventTimeoutEi"; + const uint8_t orphanHead[] {0x55,0x48,0x89,0xE5,0x41,0x57,0x41,0x56,0x41,0x55,0x41,0x54,0x53,0x48,0x83,0xEC,0x18, + 0x41,0x89,0xF5,0x49,0x89,0xFE,0x48,0x8B,0x47,0x10}; + const auto stampUpdate=patcher.solveSymbol(index, + "__ZN16IntelAccelerator17signalStampUpdateERK8IGBitSetILm64EE",address,size); + const char *finish="__ZN19IGAccelEventMachine11finishEventEP12IOAccelEventj"; + const uint8_t finishHead[] {0x55,0x48,0x89,0xE5,0x41,0x57,0x41,0x56,0x41,0x54,0x53, + 0x41,0x89,0xD7,0x48,0x89,0xFB}; + orphanOK=size>0xA02D0 && stampUpdate==address+0x2AB4E && + patcher.solveSymbol(index,orphanTimeout,address,size)==address+0x15F22 && + !memcmp(reinterpret_cast(address+0x15F22),orphanHead,sizeof(orphanHead)) && + // The LUT and scheduler offsets the decision reads are the ones + // this eventTimeout body uses; a drifted body means no install. + TGLOrphan::anchorsMatch([address](uint32_t offset,uint8_t &b) { + b=*reinterpret_cast(address+offset);return true;}) && + patcher.solveSymbol(index,finish,address,size)==address+0x15E90 && + !memcmp(reinterpret_cast(address+0x15E90),finishHead,sizeof(finishHead)); + // The teardown sites must match byte-for-byte before the rule + // installs: the call to finishEvent, its displacement and the + // reason immediate at each verified return address. + if (orphanOK) { + auto readImg=[](void *ctx,uint64_t off,uint8_t &v)->bool { + v=*reinterpret_cast(reinterpret_cast(ctx)+off); + return true; + }; + for (const auto &c:TGLOrphan::SiteCalls) + orphanOK=orphanOK && TGLOrphan::verifySite(c,0x15E90,readImg, + reinterpret_cast(address)); + } + patcher.clearError(); + if (orphanOK) { + tglOrphanAccelBase=address; + tglOrphanSignalUpdate=stampUpdate; + // The owner guard calls scheduler vtable+0x198 only when it is + // this routine (anchor audit 2026-11-13: 0x380EC); otherwise the + // observer runs but the rule reports OwnerUnknown and never writes. + const auto active=patcher.solveSymbol(index, + "__ZN12IGScheduler517getActiveContextsE10IGHwCsTypePP17IGHardwareContextPyS3_",address,size); + tglOrphanActiveContexts=active==address+0x380EC ? active : 0; + patcher.clearError(); + tglOrphanKillSwitch=checkKernelArgument("-wex-no-orphan-complete"); + tglOrphanStormOff=checkKernelArgument("-wex-no-orphan-storm"); + KernelPatcher::RouteRequest hook[] { + {orphanTimeout,wrapTGLOrphanTimeout,orgTGLOrphanTimeout}, + {finish,wrapTGLOrphanFinish,orgTGLOrphanFinish}}; + orphanOK=patcher.routeMultiple(index,hook,arrsize(hook),address,size); + } + patcher.clearError(); + return orphanOK; +} + bool XE::processDisplay13Shutdown(KernelPatcher &p,size_t index,mach_vm_address_t address,size_t size) { const char *symbol="__ZN31AppleIntelFramebufferController10hwShutdownEP21AppleIntelFramebuffer"; const uint8_t entry[]={0x55,0x48,0x89,0xe5,0x41,0x57,0x41,0x56,0x41,0x55,0x41,0x54,0x53,0x48,0x83,0xec,0x18}; @@ -16976,14 +16993,18 @@ void XE::wrapTGLHangRingDump(void *ring,void *registers) { } char key[32];snprintf(key,sizeof(key),"TGLHangBatch%u",slot); IORegistryEntry::getRegistryRoot()->setProperty(key,c,sizeof(*c)); - if (slot==0 && c->q[3]==sizeof(c->regs) && c->q[4]==sizeof(c->ring)) { + // Keep the existing first RCS detail report, and retain bounded BCS pending + // evidence on its own native dump. Do not run the RCS command/PPGTT decoder + // against copy-engine packets. The global four-slot failure budget remains. + const bool bcs=c->regs[0x94]==2 && c->ring[0x40]==2; + if ((slot==0 || bcs) && c->q[3]==sizeof(c->regs) && c->q[4]==sizeof(c->ring)) { struct PendingWork {TGLHangPending::Capture pending;TGLHangSelect::Selection selection;uint8_t ring[0x8a8];}; auto work=static_cast(IOMalloc(sizeof(PendingWork))); if(work) { bzero(work,sizeof(*work));auto &pending=work->pending;auto &selection=work->selection; tglHostClock(pending.q+1); auto boundedRead=[&](uint64_t address,void *out,unsigned count)->uint64_t {return read(address,out,count);}; - if(tglHangDetailKernel())TGLHangSelect::select(selection,c->q[2],reinterpret_cast(tglCSBEngines[0].streamer),c->regs,boundedRead); + if(!bcs && tglHangDetailKernel())TGLHangSelect::select(selection,c->q[2],reinterpret_cast(tglCSBEngines[0].streamer),c->regs,boundedRead); uint64_t selected=c->q[2];const uint8_t *ringBytes=c->ring; if(selection.q[0] && !selection.q[1] && selection.q[4]!=selected) { if(read(selection.q[4],work->ring,sizeof(work->ring))==sizeof(work->ring)) { @@ -16991,8 +17012,26 @@ void XE::wrapTGLHangRingDump(void *ring,void *registers) { } else selection.q[1]=7; } TGLHangPending::collect(pending,selected,c->regs,ringBytes,boundedRead); - IORegistryEntry::getRegistryRoot()->setProperty("TGLHangPending0",&pending,sizeof(pending)); - tglCaptureHangDetail(pending,c->regs,selection); + if(bcs) { + snprintf(key,sizeof(key),"TGLHangPendingBCS%u",slot); + IORegistryEntry::getRegistryRoot()->setProperty(key,&pending,sizeof(pending)); + // Small, no-fault CPU witnesses for the semaphore waits seen in BCS + // reset reports. This observes failure only, never completes a wait. + auto wait=static_cast(IOMalloc(sizeof(TGLHangBCSWait::Capture))); + if(wait) { + bzero(wait,sizeof(*wait));tglHostClock(wait->q+2); + if(tglVM.enabled && tglVM.nofault) + TGLHangBCSWait::collect(*wait,selected,c->regs,tglPPGTTClass,tglVM.directBase,tglVM.directEnd,boundedRead); + else {wait->q[0]=1;wait->q[1]=5;wait->q[4]=selected;} + tglHostClock(wait->q+3); + snprintf(key,sizeof(key),"TGLHangBCSWait%u",slot); + IORegistryEntry::getRegistryRoot()->setProperty(key,wait,sizeof(*wait)); + IOFree(wait,sizeof(*wait)); + } + } else { + IORegistryEntry::getRegistryRoot()->setProperty("TGLHangPending0",&pending,sizeof(pending)); + tglCaptureHangDetail(pending,c->regs,selection); + } IOFree(work,sizeof(*work)); } } diff --git a/driver/G83/WhateverXe/kern_xe.hpp b/driver/G83/WhateverXe/kern_xe.hpp index bc8d7ee..249a371 100644 --- a/driver/G83/WhateverXe/kern_xe.hpp +++ b/driver/G83/WhateverXe/kern_xe.hpp @@ -110,6 +110,8 @@ class XE { __attribute__((noinline)) bool processAlderLakeNTaskBoundary(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size); __attribute__((noinline)) bool processDisplay13Framebuffer(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size); __attribute__((noinline)) bool processTGLAccelerator(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size); + bool installTGLOrphan(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size); + bool installTGLRecovery(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size, bool hostOK); __attribute__((noinline)) bool processKextFull(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size); // Separate from generation-selected SKL/ICL patch modules. bool tglRequested {false}; diff --git a/driver/G83/tests/README.md b/driver/G83/tests/README.md index 8516992..04c3c62 100644 --- a/driver/G83/tests/README.md +++ b/driver/G83/tests/README.md @@ -70,9 +70,17 @@ producer, unreadable and foreign owner hops, the slot or submission changing between the reads and the write, a concurrent evaluation, audit reasons, installer anchor drift, the mark table and `-wex-no-orphan-storm`. The native callees, IOAccel locks, return-address capture and all hardware are modelled. +Every completion is attributed (`stormCompletions` / `teardownCompletions`, +and the dying owner's port) and recorded in `settled[8]`; for 60 s the slot +is re-read from both wrappers, and a value below the written stamp (modulo +2^32) counts as a regression. Counterexamples cover attribution, the window, +index reuse (submitted count below the written stamp), a replaced slot, a +foreign event machine, a busy gate and wrap-around. Passing does not establish that a settled stamp's work was destroyed rather than retained in a native queue; that requires live `TGLOrphanLive` and -`TGLRecoveryLive` evidence from a storm. +`TGLRecoveryLive` evidence from a storm. Sampling is periodic only while +events finish, so a zero regression count is weaker evidence than a +non-zero one. `tgl_reset_poll_native` executes the production installer, naked bridge and bounded full-width GDRST helper inside the fixed TGL reset body. It preserves diff --git a/driver/G83/tests/tgl_hang_bcs_wait.cpp b/driver/G83/tests/tgl_hang_bcs_wait.cpp new file mode 100644 index 0000000..fa0841c --- /dev/null +++ b/driver/G83/tests/tgl_hang_bcs_wait.cpp @@ -0,0 +1,91 @@ +#include "kern_tgl_hang_bcs_wait.hpp" +#include +#include +#include +#include +using namespace TGLHangBCSWait; +namespace { +constexpr uint64_t K=0xffff800000000000ULL,Ring=K+0x200000,Ctx=Ring+0x1000,Task=Ring+0x2000, + LRCBuf=Ring+0x3000,RingBuf=Ring+0x4000,LRC=Ring+0x5000,Storage=Ring+0x8000, + TableObject=K+0x20000,Class=K+0xabcdef,Target=0x40000040,Value=K+0x30040; +struct Fixture { + std::map> blocks; + uint8_t regs[0xb0]{}; + bool mutateOwner{},mutateWords{},mutatePTE{},changeValue{},partial{}; + unsigned valueReads{}; + void alloc(uint64_t p,unsigned n){blocks[p].resize(n);} + templatevoid put(uint64_t p,T v) { + auto it=blocks.upper_bound(p);assert(it!=blocks.begin());--it; + assert(p-it->first+sizeof(v)<=it->second.size());memcpy(it->second.data()+p-it->first,&v,sizeof(v)); + } + void reg(unsigned n,uint32_t v){memcpy(regs+n,&v,4);} + void packet(unsigned offset=16,uint32_t header=0x0e009002) { + const uint32_t words[]={header,11,uint32_t(Target),0}; + for(unsigned i=0;i<4;++i)put(Storage+((offset+4*i)&4095),words[i]); + } + Fixture() { + for(auto p:{Ring,Ctx,Task,LRCBuf,RingBuf,Storage,TableObject,K+0x1000,K+0x2000, + K+0x7000,K+0xc000,K+0x11000,K+0x12000,K+0x30000})alloc(p,4096); + alloc(LRC,8192);for(auto p:{K+0x3000,K+0x8000,K+0xd000})alloc(p,16384); + put(TableObject,Class);put(TableObject+0x40,K+0x1000);put(TableObject+0x48,K+0x3000); + put(K+0x1000+0x18,uint64_t(0x2000));put(K+0x3000,K+0x7000);put(K+0x3008,K+0x8000); + put(K+0x8000+32,K+0xc000);put(K+0x8000+40,K+0xd000);put(K+0xd000,K+0x11000); + put(K+0x11000+0x20,K+0x12000);put(K+0x12000,uint64_t(0x30003)); + put(Ring+0x40,uint8_t(2));put(Ctx+0x6c,uint8_t(2));put(Ring+0x20,Ctx); + put(Ring+0x10,K+0x99000);put(Ctx+0x50,K+0x99000);put(Ctx+0xb0,Ring); + put(Ctx+0x58,Task);put(Task+0x260,TableObject);put(Ctx+0x98,LRCBuf); + put(LRCBuf+0x38,LRC);put(LRCBuf+0x20,uint64_t(8192));put(Ring+0x18,LRC); + put(Ring+0x80,RingBuf);put(RingBuf+0x38,Storage);put(RingBuf+0x20,uint64_t(4096)); + put(Ring+0x8c,uint32_t(4096));put(Ctx+0x7c,uint32_t(8));put(LRC+0x10cc,uint32_t(0x2000)); + regs[0x94]=2;reg(0,20);reg(0xac,8<<5);packet();put(Value,uint32_t(10)); + } + uint64_t read(uint64_t p,void *out,unsigned n) { + if(p==Value && n==4) { + ++valueReads; + if(mutateOwner)put(Ctx+0x50,K+0x99008); + if(mutateWords)put(Storage+16,uint32_t(0)); + if(mutatePTE)put(K+0x12000,uint64_t(0x31003)); + if(changeValue && valueReads==2)put(Value,uint32_t(11)); + } + auto it=blocks.upper_bound(p);if(it==blocks.begin())return 0;--it; + if(p-it->first+n>it->second.size())return 0; + if(partial && p==Value)return 0; + memcpy(out,it->second.data()+p-it->first,n);return n; + } + Capture run(uint64_t directEnd=K+0x1000000) { + Capture c{};collect(c,Ring,regs,Class,K,directEnd, + [&](uint64_t p,void *out,unsigned n){return read(p,out,n);});return c; + } +}; +} +int main() { + {Fixture f;auto c=f.run();assert(!c.q[1] && c.q[9]==1 && !c.candidates[0].q[4]); + assert(c.candidates[0].q[3]==Target && c.candidates[0].q[5]==10 && !c.candidates[0].q[7]);} + {Fixture f;f.changeValue=true;auto c=f.run();assert(!c.q[1] && !c.candidates[0].q[4]); + assert(c.candidates[0].q[5]==10 && c.candidates[0].q[6]==11 && c.candidates[0].q[8]);} + {Fixture f;f.put(Storage+16,uint32_t(0));f.packet(4092);f.reg(0,0);auto c=f.run(); + assert(!c.q[1] && c.q[9]==1 && c.candidates[0].q[0]==4092 && !c.candidates[0].q[4]);} + for(unsigned mode=0;mode<7;++mode) { + Fixture f; + if(mode==0)f.regs[0x94]=0; + if(mode==1)f.put(Ring+0x40,uint8_t(0)); + if(mode==2)f.put(Ctx+0xb0,Ring+8); + if(mode==3)f.put(TableObject,Class+8); + if(mode==4)f.put(LRCBuf+0x38,LRC+4); + if(mode==5)f.put(Ring+0x8c,uint32_t(32769)); + if(mode==6)f.reg(0xac,9<<5); + assert(f.run().q[1] && !f.valueReads); + } + for(uint32_t header:{0x0e409002U,0x0e00c002U,0x0e009003U}) { + Fixture f;f.packet(16,header);auto c=f.run();assert(!c.q[1] && !c.q[9] && !f.valueReads); + } + {Fixture f;f.put(Storage+24,uint32_t(Target|1));auto c=f.run();assert(c.candidates[0].q[4]==1 && !f.valueReads);} + {Fixture f;f.put(LRC+0x10cc,uint32_t(0x4000));auto c=f.run();assert(c.candidates[0].q[4]==2 && !f.valueReads);} + {Fixture f;f.put(K+0x12000,uint64_t(0));auto c=f.run();assert(c.candidates[0].q[4]==2 && !f.valueReads);} + {Fixture f;auto c=f.run(Value);assert(c.candidates[0].q[4]==3 && !f.valueReads);} + {Fixture f;f.partial=true;assert(f.run().candidates[0].q[4]==3);} + {Fixture f;f.mutatePTE=true;assert(f.run().candidates[0].q[4]==4);} + {Fixture f;f.mutateOwner=true;assert(f.run().q[1]==4);} + {Fixture f;f.mutateWords=true;assert(f.run().q[1]==4);} + printf("PASS: BCS wait CPU witnesses, wrapping, changing values and rejected identities/mappings/races; no GPU work\n"); +} diff --git a/driver/G83/tests/tgl_hang_pending.cpp b/driver/G83/tests/tgl_hang_pending.cpp index 1f7317e..93765d2 100644 --- a/driver/G83/tests/tgl_hang_pending.cpp +++ b/driver/G83/tests/tgl_hang_pending.cpp @@ -8,10 +8,10 @@ constexpr uint64_t Ring=0xffff800000010000ULL,Context=Ring+0x10000,Stamps=Ring+0 struct Fixture { std::array ring{}; std::array regs{}; - std::array context{}; + std::array context{}; std::array stamps{}; std::array bytes{}; - bool partial{},mutateCache{},mutateOwner{},mutateRetired{},mutateWrite{},deny{}; + bool partial{},mutateCache{},mutateOwner{},mutateRetired{},mutateWrite{},deny{},mutateEngine{},mutateBacklink{},mutateContextOwner{}; unsigned dataReads{}; template static void put(uint8_t *p,unsigned offset,T value) {memcpy(p+offset,&value,sizeof(value));} Fixture() { @@ -34,6 +34,9 @@ struct Fixture { if(mutateOwner)context[0x7c]^=1; if(mutateRetired)stamps[64]^=1; if(mutateWrite)ring[0x8a0]^=1; + if(mutateEngine)context[0x6c]^=1; + if(mutateBacklink)context[0xb0]^=8; + if(mutateContextOwner)context[0x50]^=8; const unsigned count=partial?n-1:n;memcpy(out,bytes.data(),count);return count; } auto copy=[&](uint64_t base,const auto &v)->bool { @@ -49,6 +52,25 @@ struct Fixture { }; } int main() { + // BCS captures use the common cache but must qualify engine/ownership both + // before copying and after it. They remain pending candidates, not active BBs. + for(unsigned failure=0;failure<8;++failure) { + Fixture f;f.regs[0x94]=2;f.ring[0x40]=2;f.context[0x6c]=2; + Fixture::put(f.context.data(),0x50,uint64_t(Ring+0x50000)); + Fixture::put(f.ring.data(),0x10,uint64_t(Ring+0x50000)); + Fixture::put(f.context.data(),0xb0,Ring); + if(failure==1)f.ring[0x40]=0; + if(failure==2)f.context[0x6c]=0; + if(failure==3)Fixture::put(f.context.data(),0xb0,Ring+8); + if(failure==4)Fixture::put(f.context.data(),0x50,uint64_t(Ring+0x50008)); + if(failure==5)f.mutateEngine=true; + if(failure==6)f.mutateBacklink=true; + if(failure==7)f.mutateContextOwner=true; + auto c=f.run(); + if(!failure)assert(!c->q[2] && c->q[11]==1 && c->entries[0].stable); + else if(failure<=4)assert(c->q[2] && !f.dataReads); + else assert(c->q[2]==5); + } {Fixture f;auto c=f.run();assert(c->q[2]==0 && c->q[11]==1 && f.dataReads==1); assert(c->entries[0].stable && c->entries[0].copied==128); assert(!memcmp(c->entries[0].bytes,f.bytes.data(),128));} diff --git a/driver/G83/tests/tgl_orphan.cpp b/driver/G83/tests/tgl_orphan.cpp index eb38a03..74dbe1d 100644 --- a/driver/G83/tests/tgl_orphan.cpp +++ b/driver/G83/tests/tgl_orphan.cpp @@ -539,6 +539,137 @@ static void teardown() { } } + +// Round 3: every completion is attributed (storm vs teardown, and the port of +// the dying owner), and the slot is re-read for 60 s afterwards. A later +// value below the written one is the hardware signal that settled work was +// retained and executed (the B-class verdict's "re-executed" criterion). +static void settled() { + { // Storm completion: attributed to B, no regression while the slot holds. + World w; + assert(w.storm().complete); + assert(w.t.completions == 1 && w.t.stormCompletions == 1 && w.t.teardownCompletions == 0); + const Settled &r = w.t.settled[0]; + assert(w.t.settledNext == 1 && r.ns == 12 * S && r.idx == 16 && r.written == 100 && r.doneBefore == 97); + assert(r.kind == KindStorm && r.slot == w.slot && r.stamps == w.stamps && r.lowest == 100); + w.m.clock = 20 * S; + sampleExclusive(w.m, w.gate, w.t, w.machine); + assert(r.samples >= 1 && !r.regressed && !w.t.regressions && w.t.samples >= 1); + // The GPU later writes older stamps: retained work executed. + w.m.put(w.slot, 98); + w.m.clock = 25 * S; + sampleExclusive(w.m, w.gate, w.t, w.machine); + assert(r.regressed == 1 && r.firstRegressionNs == 25 * S && r.lowest == 98 && w.t.regressions == 1); + w.m.put(w.slot, 99); + w.m.clock = 26 * S; + sampleExclusive(w.m, w.gate, w.t, w.machine); + assert(r.regressed == 2 && r.firstRegressionNs == 25 * S && r.lowest == 98 && w.t.regressions == 1); + // The timeout path samples too (under its own gate acquisition). + w.m.put(w.slot, 97); + w.m.clock = 27 * S; + evaluateExclusive(w.m, w.gate, w.t, w.marks, w.c, w.machine, 5); + assert(r.regressed == 3 && r.lowest == 97 && w.t.regressions == 1); + // A busy gate skips the sample, never waits. + const uint64_t before = w.t.samples; + w.gate.busy = 1; + w.m.clock = 28 * S; + sampleExclusive(w.m, w.gate, w.t, w.machine); + assert(w.t.samples == before && w.gate.busy == 1); + w.gate.busy = 0; + // Window over: the record stops sampling and later values are ignored. + w.m.put(w.slot, 90); + w.m.clock = (12 + 61) * S; + evaluateExclusive(w.m, w.gate, w.t, w.marks, w.c, w.machine, 5); + assert(r.slot == 0 && r.regressed == 3 && r.lowest == 97); + } + { // Nothing settled: the finishEvent path does not touch the gate. + World w; + w.gate.busy = 1; + w.m.clock = 5 * S; + sampleExclusive(w.m, w.gate, w.t, w.machine); + assert(w.gate.busy == 1 && !w.t.samples); + } + { // The index was reused or reset (submitted count fell below the written + // stamp): the record ends without counting the new owner's low values. + World w; + assert(w.storm().complete); + w.m.put(w.machine + 0x104 + 16 * 24, 3); + w.m.put(w.slot, 1); + w.m.clock = 20 * S; + sampleExclusive(w.m, w.gate, w.t, w.machine); + assert(w.t.settled[0].slot == 0 && !w.t.settled[0].regressed && !w.t.regressions); + } + { // A different slot pointer for the index also ends the record. + World w; + assert(w.storm().complete); + uint64_t other = w.m.add(0xffffff8000e00000ULL, 8); + w.m.put(w.stamps + 16 * 8, other); + w.m.clock = 20 * S; + sampleExclusive(w.m, w.gate, w.t, w.machine); + assert(w.t.settled[0].slot == 0 && !w.t.regressions); + } + { // Another event machine (different stamp table) leaves the record alone. + World w; + assert(w.storm().complete); + uint64_t m2 = w.m.add(0xffffff8000f00000ULL, 0x104 + 64 * 24); + uint64_t s2 = w.m.add(0xffffff8001000000ULL, 64 * 8); + w.m.put(m2 + 0x28, s2); + w.m.put(w.slot, 50); + const uint32_t seen = w.t.settled[0].samples; // the completing call sampled once + w.m.clock = 20 * S; + sampleExclusive(w.m, w.gate, w.t, m2); + assert(w.t.settled[0].slot == w.slot && w.t.settled[0].samples == seen && !w.t.regressions); + } + { // Stamps compare modulo 2^32: a forward wrap is not a regression. + World w; + w.m.put(w.machine + 0x104 + 16 * 24, 0xFFFFFFFEU); + w.m.put(w.slot, 0xFFFFFFFBU); + assert(w.storm().complete && w.t.settled[0].written == 0xFFFFFFFEU); + const uint32_t seen = w.t.settled[0].samples; + w.m.put(w.machine + 0x104 + 16 * 24, 2); + w.m.put(w.slot, 1); + w.m.clock = 20 * S; + sampleExclusive(w.m, w.gate, w.t, w.machine); + assert(w.t.settled[0].samples == seen + 1 && !w.t.settled[0].regressed && !w.t.regressions); + } + { // Teardown completions are attributed to C with the dying owner's port. + World w; + w.m.put(w.slot, 99); + w.m.put(w.chA + 0x20, 16); // the active (dying) context owns idx 16 + uint64_t object = w.m.add(0xffffff8000d00000ULL, 0x1300); + w.m.put(object + 0x1298, w.ctxA); + Mark *mine = enter(w.m, w.marks, w.base, w.base + 0x6956F, reinterpret_cast(object + 0x5D0)); + assert(w.storm().complete); + leave(mine); + assert(w.t.teardownCompletions == 1 && !w.t.stormCompletions && w.t.settled[0].kind == KindTeardownActive); + World v; // the dying owner sits in the pending port + v.m.put(v.slot, 99); + v.m.put(v.chA + 0x20, 16); + v.m.active = nullptr; + v.m.pending = reinterpret_cast(v.ctxA); + uint64_t o2 = v.m.add(0xffffff8000d00000ULL, 0x1300); + v.m.put(o2 + 0x1298, v.ctxA); + mine = enter(v.m, v.marks, v.base, v.base + 0x6956F, reinterpret_cast(o2 + 0x5D0)); + assert(v.storm().complete); + leave(mine); + assert(v.t.teardownCompletions == 1 && v.t.settled[0].kind == KindTeardownPending); + } + { // The ring of records keeps the newest eight. + World w; + for (unsigned i = 0; i < SettledSlots + 2; ++i) { + w.t.current[16] = {}; + w.m.put(w.machine + 0x104 + 16 * 24, 100 + i); + w.m.put(w.slot, 97 + i); + const uint64_t t0 = 100 * i; + w.c.lastResetNs = (t0 + 3) * S; + w.at(t0); w.at(t0 + 6); + assert(w.at(t0 + 12).complete); + } + assert(w.t.settledNext == SettledSlots + 2 && w.t.settled[0].written == 100 + SettledSlots); + assert(w.t.settled[1].written == 101 + SettledSlots && w.t.settled[2].written == 102); + } +} + int main() { episodes(); guardTable(); @@ -546,6 +677,7 @@ int main() { production(); races(); teardown(); + settled(); // Teardown-site verification: a synthetic image with a correct call at // RL-5 and movl $reason,%edx at RL-10 passes; every drift refuses. static std::array img {};