diff --git a/docs/LIUWANG97-POWER-COMPARISON-20261024.zh-CN.md b/docs/LIUWANG97-POWER-COMPARISON-20261024.zh-CN.md new file mode 100644 index 00000000..1b0c7c17 --- /dev/null +++ b/docs/LIUWANG97-POWER-COMPARISON-20261024.zh-CN.md @@ -0,0 +1,103 @@ +# liuwang97 fork 分支与省电差异复核(2026-10-24) + +## 核查范围 + +本轮通过 `git ls-remote --heads` 获取分支列表,向现有仓库的 +`refs/remotes/liuwang97/*` 获取对象;没有克隆新仓库、切换分支、合并或改设备。 +不是只浏览较旧的 main。比较的本地 HEAD 为 +`b47485341161088f34f6b4645a89416825c4c6a5`。 + +| 分支 | 本次固定 HEAD | 主要意义 | +| --- | --- | --- | +| main | 0b96af26 | 较旧基线,不代表后续优化集合 | +| cpu-load | b7474ed2 | 常驻服务优化;比上次 ccf89bb6 多一项 AT 锁忙/页面错误合并修复 | +| boot-speed | 1fb42beb | 原始启动优化与 USB os_desc 修复 | +| kernel-7.2-merged | 75295203 | 集成 PR 后补齐 7.2 的 PCIe 初次链路等待跳过 | +| lpintc-wake | 02833daa | LP_AP_INTC;最新增加 F50 验证说明,模块执行逻辑未新增改变 | +| pr/cpu-load | f5528dd8 | 整理后的常驻服务 PR,含测试修正;不能代替 cpu-load 的新增 b7474ed2 | +| pr/boot-speed | af2f37e4 | 整理后的启动 PR | +| pr/gadget-os-desc-double-free | 9f81f427 | USB 生命周期修复,最新增加 F50 验证说明 | +| fix/install-ps1-resume-function-order | ee1c4d50 | 安装器函数顺序修复,与省电无直接关系 | + +完整 SHA、文件 blob、配置摘要和选取的源码快照保存在 +`work/liuwang97-power-audit-20261024/manifest.json` 及同目录文件。 + +## CPU 深度空闲:默认没有禁用 + +八个包含后续 CPU 控制代码的分支均设置 `LOWLATENCY` 默认值为 0: + +- `mu300-cpu lowlatency on` 才向 CPU0 各 `state*/disable` 写 1,保存用户选择。 +- `off` 写 0 并删除该保存项。 +- 启动回放 `lowlat_apply()` 只在保存值为 1 时禁用 CPU0 idle;未开启时保留内核默认。 +- 不对其他 CPU 做同样的无条件禁用。较旧 main 没有这套后续可选功能。 + +证据:[cpu-load 的 CPU 控制实现](https://github.com/liuwang97/mu300-linux/blob/b7474ed2c152ec1fd94b5a0ceaab3a4d8c1339cb/rootfs/overlay/opt/mu300/bin/mu300-cpu)。 + +需要区分默认源码与作者调试设备:FINDINGS 218 记录他曾在设备 `/etc/rc.local` +禁用 CPU0 的 `cluster-pd`,用于绕过深睡唤醒延迟;LP_AP_INTC 修复的目标就是 +允许保留 cluster-pd。不能把这段历史写成他从来没有关闭过深睡,也不能根据源码 +判断作者现在每台实体设备的设置。 +见 [lpintc-wake 的实验记录](https://github.com/liuwang97/mu300-linux/blob/02833daa0cc976698d42aa4a218c0a631f92b3fb/docs/FINDINGS.md)。 + +本地仍由 `mu300-lowlatency` 在 OpenWrt `mu300-hw` 和 systemd fixups 启动时 +禁用 CPU0 各状态。这延续了此前用户指定的低延迟策略;当前 U30 Air 实测 core-sleep/ +cluster-pd 无新增驻留、WFI 有驻留,详见同日省电检查。 +LP_AP_INTC 已移植并实机加载,但没有因此自动改变该策略。 + +## 已覆盖的主要优化 + +- C AT I/O bridge、ucode modem daemon、唯一物理通道所有者和事件等待。 +- 常驻原生 rpcd 系统快照/网速,短信签名变化才读取列表,隐藏页面停止刷新。 +- procd 服务小核 cpuset;没有把“强制下线大核”当作这项优化的一部分。 +- NO_HZ_IDLE、HIGH_RES_TIMERS、UCLAMP_TASK/GROUP、THERMAL_NETLINK 配置。 +- LP_AP_INTC 唤醒模块;本地另增加映射失败的完整资源清理。 +- eMMC 就绪探测、预读模块、无线顺序、随机池和早期串口输出等适用启动优化。 +- 6.18/7.2 PCIe 初次链路等待的各自错误路径适配,保留恢复时正常等待。 +- USB NCM/RNDIS os_desc 生命周期修复;没有反向覆盖本地 NCM TX 修复。 + +本地 LP_AP_INTC 与 fork 最新文件的差异仅为来源注释,以及本地已有的映射失败清理。 +不能将 fork 新的 F50 实测文字当作漏掉了一个新版模块。 + +## 确实存在的行为差异 + +| 项目 | 对方实现 | 本地当前实现 | 评估 | +| --- | --- | --- | --- | +| CPU0 idle | 低延迟可选,默认保留内核 idle | 既有启动策略禁用 CPU0 状态 | 对续航最值得优先做受控验证的差异,不能凭代码估计节省功率 | +| LED 调度 | `.tick-hint` 记录下个到期时间,按到期/uevent 调度;安全核查为充电 30 秒、其他 90 秒 | sysd 每 5 秒启动既有 LED `sleep --if-due` helper | 可进一步减少周期唤醒与 fork;需要适配本地 U30 Air 的 50% 蓝/白规则、硬件呼吸、用户超时及充电事件 | +| 温控间隔 | 距阈值较远时自适应,内核已负责限频时最长 30 秒,独立 guard 最长 10 秒;接近阈值/持有限频/告警仍 5 秒 | 保留 5 秒保护周期 | 已知且有意保留的保护时效差异;进一步采用需保留当前温控所有权、错误处理与电池保护 | +| 定时器 slack | sysd、短信、NDP、温控等待阶段设置 500 ms,启动动作前恢复 | 不增加 slack | 是未采用的唤醒合并策略,会允许部分超时等待更晚返回;实际收益需测,不能宣称定时器已经一定合并 | +| early-recorder | `logread -l 300`;启动 90 秒后每 30 秒采样 | 读完整 logread 后截尾;90 秒后仍每 10 秒 | 小核亲和已移植;剩余两项没有采用。只作用于早期约五分钟记录窗口,不解释设备长时间运行后的待机负载 | +| 短信/NDP 兜底 | 事件驱动下短信同步默认 1800 秒、配置核查 600 秒;NDP 安全核查 300 秒,并退避无地址 solicitation | 短信仍 300 秒归档,NDP 10 秒安全检查,数据看守 30 秒 | 事件机制已移植,安全期限保留本地值;改变这些值会改变漏事件/断线后的最长恢复时延,属于行为取舍 | +| 整机 suspend | CONFIG_SUSPEND/PM_SLEEP/PM_AUTOSLEEP 已编译,autosleep 默认不启动,文档注明实验性 | 当前 U30 Air 内核 CONFIG_SUSPEND 未启用 | 独立于 cpuidle。不能只补配置就宣称 USB/Wi-Fi/基带/电源恢复可靠 | +| mu300-power | 提供空闲关热点/射频及 eco 下线核心等策略 | 沿用本地电源与充电入口,没有引入第二套所有者 | 不列作纯减开销优化;会改变联网功能和用户电源策略,本轮不建议直接搬入 | + +其中 LED/温控/安全期限的大部分差异在上一轮移植报告中已经明确保留,并非本轮 +才发现整批常驻服务漏移植。当前真实待机测量只有约 0.55%~0.63% 的八核总容量忙碌, +sysd 本身约单核 0.2%;不要承诺上述小项有数量级功耗收益。 + +主要来源:[sysd](https://github.com/liuwang97/mu300-linux/blob/b7474ed2c152ec1fd94b5a0ceaab3a4d8c1339cb/rootfs/overlay/opt/mu300/bin/mu300-sysd)、 +[early-recorder](https://github.com/liuwang97/mu300-linux/blob/b7474ed2c152ec1fd94b5a0ceaab3a4d8c1339cb/rootfs/overlay/opt/mu300/bin/early-recorder)、 +[内核配置](https://github.com/liuwang97/mu300-linux/blob/02833daa0cc976698d42aa4a218c0a631f92b3fb/upstream/mu300-mainline.config)。 + +## 新增且尚未覆盖的修复 b7474ed2 + +[提交 b7474ed2](https://github.com/liuwang97/mu300-linux/commit/b7474ed2c152ec1fd94b5a0ceaab3a4d8c1339cb) +在上一轮移植源 ccf89bb6 之后,包含两项相关可靠性修复: + +1. 通道客户端锁被持有时明确返回 busy,采集轮次有界地每 250 ms 重试;若始终未能 + 发出命令,不发布“AT 无应答”覆盖旧缓存。 +2. 时间足够新的正常快档数据覆盖仅含错误的慢档缓存,清除旧 error 字段。 + +本地 `internal_at/round_at` 没有前一项的 held/asked/held_out 状态;页面虽有 +自己的分阶段缓存合并,仍会把正常快档合进旧 error 对象并保留 error。 +使用两边实际网页函数、相同的假输入(慢档错误 ts=100、正常快档 ts=101)离线执行: +本地结果保留 error,fork 结果移除 error。脚本为 +`work/liuwang97-power-audit-20261024/compare-merge.js`。 +这是离线数据合并复现,未在实体基带上制造 AT 锁冲突;不把它宣传为省电收益。 + +## 本轮产出边界 + +本轮仅刷新审查用 Git 引用、读取代码、执行无设备的合并函数对照、归档报告。 +没有 cherry-pick、改生产代码、构建内核/固件、修改或重启 U30 Air。 +后续优先级:CPU0 idle/低延迟选择及真实功率验证;适配 LED 到期调度; +单独处理 b7474ed2 的缓存/锁忙可靠性修复。其余降频率与定时器 slack 保留明确时效取舍。 diff --git a/docs/POWER-ALIGNMENT-20261024.zh-CN.md b/docs/POWER-ALIGNMENT-20261024.zh-CN.md new file mode 100644 index 00000000..2eac25e4 --- /dev/null +++ b/docs/POWER-ALIGNMENT-20261024.zh-CN.md @@ -0,0 +1,38 @@ +# U30 Air 调度省电与 CPU0 深睡开关(2026-10-24) + +已按用户指定的五项内容修改 MU300 `clean-tf-7.2` 分支,并部署到当前连接的 U30 Air。E5 仓库同步了 CPU0 深睡网页开关及其共同打包路径,未部署到 E5 系设备。 + +## 改动范围 + +1. CPU 页面新增「CPU0 深度休眠」开关。通过实际设备树中的 `sprd,ums9620` 与 CPU0 空闲状态名识别 T157/T760 平台,只调整 CPU0 的 `core-sleep-*`、`cluster-pd`;不调整 WFI 和其他核心。T158/UMS9621 隐藏开关,直接调用写接口也会拒绝。修改即时生效并保存,启动时重放;没有保存选择时保留已有启动策略。 +2. 灯效采用截止时间提示与状态变化触发。稳定时不再每五秒启动 LED shell;充电时至多三十秒核对一次,其他情况至多九十秒,睡灯截止时间与按键/电源事件仍可提前触发。保留本分支 U30 Air 的颜色边界、硬件呼吸曲线、充电常亮、拔线后超时熄灯及单一灯效控制者。 +3. 温控检查根据距离阈值自适应。报警中、恢复限频中及读取异常时维持五秒;由脚本负责限频时最长十秒,确认内核散热绑定接管时最长三十秒。保留原阈值、紧急关机和用户频率上限恢复规则。旧 shell 温控守护也同步此节奏。 +4. 调度守护和短信/联网/IPv6 事件接收的空闲等待使用 500 ms timer slack。事件到来仍可立即唤醒;子进程动作恢复原精度,原始单调时钟截止时间不变。设置容差失败不退出功能服务,继续使用原有精度。 +5. 启动日志直接读取最近 300 条,过滤既有 `PR_CAPBSET` 噪声;前九十秒保持两秒采集,此后改三十秒。总采集时长和持久化写入边界不变。 + +调度思路参考本地已固定的 `liuwang97/mu300-linux` 分支快照(`cpu-load`:`b7474ed2c152ec1fd94b5a0ceaab3a4d8c1339cb`),按本分支已有按键、灯效、温控和双卡逻辑适配。分支审计见 `LIUWANG97-POWER-COMPARISON-20261024.zh-CN.md`。本次未额外合入该 fork 的其他基带收集改动。 + +## 离线验证 + +- 实际 ucode CPU0 后端:MU300、E5 各五项通过。覆盖只读查询、无配置启动、保存/重放、仅修改目标状态、T158 拒绝、参数校验,以及保存失败恢复原始混合状态。 +- 新网页组件:两个仓库通过;覆盖支持/不支持、修改成功和写入失败后重新显示实际状态。原 CPU 核心页面两仓库及多语言/移动布局、CPU 全页面 24 种布局检查通过。 +- E5 真实共同 UI staging:六种 profile 连续执行两次通过,检查 init 链接、RPC/ACL、执行权限、网页资源和保留用户显式配置;无关原生编译和屏幕生成使用独立测试替身。 +- 实际 ubus 事件回归 20 项通过,包括短信及时接收、失败导入不确认、同步截止时间、监听器退出、网络地址就地续租及用户主动断网。 +- 按键/温控/灯效/日志相关测试 26 项中 24 项通过,另外两项需要显式启用的运行时测试已单独启用真实 ARM64 按键助手,两项均通过。 +- 新调度检查三项通过:自适应温控边界、子动作不继承宽松容差、稳定灯效不再每五秒启动 shell。真实灯效后端新增充电色阶、拔线和熄灯截止时间检查通过。 +- 两仓库 `git diff --check` 通过。 + +测试使用独立 ARM64 OpenWrt 容器,不代表设备冷启动、长时间待机或实际短信通话的硬件验证。测试初期发现容器缺少 ubus 运行目录、完整 flock/usleep 等环境条件,已补足后重测;另修复 timer slack 写入被内核拒绝时触发 `set -e` 退出的问题,相关回归随后通过。 + +## U30 Air 实机部署及边界 + +- 部署前确认设备身份与启动实例,确认待覆盖现有文件均匹配本分支基线。17 个运行文件保存原件后原子替换,完整 SHA-256 校验通过。 +- 设备原件:`/root/mu300-power-20261024-104312/`;本机原件、哈希、操作结果与测试日志在 `work/liuwang97-power-audit-20261024/`。 +- 定向重新加载 rpcd、sysd、短信、IPv6 学习和联网监视实例。未重启设备,基带桥接与管理进程 PID 保持不变。网络事件监视实例在原 procd 策略下恢复运行。 +- 配置文件哈希、CPU0 各状态开关与部署前一致。CPU0 深睡仍关闭,没有自动创建用户选择。真实 LuCI CPU 页面已验证开关可见、可操作、显示关闭;没有在实机点击开启深睡,尚未验证该设备开启后的长期唤醒稳定性。 +- 基带桥接及所有 broker 正常,短信双实例、联网监视、IPv6 学习、sysd 均运行。实机 sysd timer slack 读回为 `500000000` ns。 +- 实机页面加载存在 LuCI 自身初始化阶段的 `"%s/%s.js%s".format is not a function` 错误;在同设备浏览器分别使用部署前后网页代码重放,均出现相同栈,CPU 页面及新开关仍成功渲染。该既有错误未作为本次修改的回归,也未在本任务中改动 LuCI。 +- 更新后两个短采样区间的八核合计忙碌比例约为 0.61% 和 0.92%。采样并非严格同负载对照,不能据此推算续航收益;当前还连接 USB,未做独立电池放电测量。 +- 启动日志的新采集节奏将在下次开机生效,本次没有触发持久化启动记录器进行人工写入测试。 + +未生成新固件发布包;E5 原有短信、来电、屏幕和网络修复修改均保留。 diff --git a/docs/U30AIR-POWER-AUDIT-20261024.zh-CN.md b/docs/U30AIR-POWER-AUDIT-20261024.zh-CN.md new file mode 100644 index 00000000..52e4836e --- /dev/null +++ b/docs/U30AIR-POWER-AUDIT-20261024.zh-CN.md @@ -0,0 +1,80 @@ +# U30 Air 省电只读检查(2026-10-24) + +## 结论 + +当前没有看到占满核心的后台进程或明显 CPU 空转。主要省电取舍是: + +1. 既有低延迟策略仍禁用 CPU0 的 core-sleep/cluster-pd,CPU0 空闲时主要停在 WFI。 +2. 管理网页实时刷新增加 CPU 和唤醒开销,关闭后明显下降。 +3. 当前内核未启用整机 suspend;CPU idle 与整机 suspend 必须分别看待。 + +本轮只检查,不修改设备设置、服务、内核、无线或充电参数;没有为省电回滚此前修复。 +不能由本次短时 CPU 采样推算续航改善百分比或整机功率。 + +## 设备和方法 + +- 经既有 SSH 公钥固定记录、机型和设备身份核验,确认 U30 Air,OpenWrt,内核 7.2.8。 +- 经 USB 的 `192.168.77.1` 连接,热点和蜂窝维持工作;采样期间流量较小。 +- 第一阶段用户管理网页开着;用户确认关闭管理页后,补测第二阶段。 +- 每阶段三次读取、间隔约 20 秒,覆盖约 40 秒。读取 CPU、进程 ticks、cpuidle、 + cpufreq、IRQ、网络计数和电源 sysfs;采样间隔远端 Python 休眠,未做高频追踪。 +- Python 采样器本身约占单核 0.6%~0.7%,SSH/USB 和采样造成的开销仍包含在结果内。 + 仅有前后各一段,不是反复 A/B/A 或电池独立供电实验。 +- 两阶段均验证配置文件 SHA-256 和 boot ID 不变。没有执行 AT、切卡或触碰 NV。 + +## CPU 和后台进程 + +百分比口径:下表整机值以八核总容量为 100%;进程值以单核容量为 100%。 + +| 条件 | 整机忙碌比例,两个约 20 秒窗口 | rpcd,单核比例 | mu300-modemd,单核比例 | +| --- | --- | --- | --- | +| 管理页打开 | 1.528%、1.812% | 4.322%、4.469% | 1.739%、2.085% | +| 用户关闭管理页后 | 0.626%、0.551% | 两窗口均未增加 CPU tick | 约 0.050%、0.050% | + +页面关闭后的 CPU 忙碌折合单核约 4.4%~5.0%,包含内核、转发、全部服务与采样器, +不能把它写成单个常驻服务占用。闭页后的 ndp-learn shell 约为单核 0.70%~1.09%, +sysd/traffic 约 0.20%~0.25%,AT bridge 约 0~0.05%;没有据此认定 IPv6 路由服务有忙循环。 +进程等待点显示 NDP/bridge 在 poll、主要 ucode 服务在 epoll。 + +管理页关闭后 arch_timer 和广播定时器 IRQ 也减少,未见 USB NCM 每秒数千次重试的迹象。 +Wi-Fi/蜂窝存在少量真实流量,因此这些窗口不是完全无业务的实验室待机。 + +## 空闲和频率 + +- 三个 cpufreq domain 都是 schedutil,未见配置锁定最高频。 +- CPU0 三个状态的 disable 均为 1,但安全回退仍实际使用 WFI:页面打开时 WFI + 驻留约 95.2%~96.6%,关闭后约 98.2%~98.8%;core-sleep 和 cluster-pd + 在两阶段都没有新增进入次数。不能把 disable=1 写成 CPU0 一直忙等。 +- 其他核仍进入深层 idle;首轮 CPU7 cluster-pd 驻留约 99.2%。 +- CPU7 的 scaling_cur_freq/time_in_state 显示 1.703 GHz,但同阶段实际深睡约 99%, + cpuinfo_cur_freq 曾读到 26 MHz;请求频率/驻留记账不能当成持续有功运行频率。 +- 先前为降低延迟引入的 `mu300-lowlatency` 仍执行。这是既有用户选择, + 本次未擅自撤销,也未把它归咎于近期部署的异常。 +- `ums9620_lpintc` 已加载。此前 USB 实验已证明允许 CPU0 cluster-pd 时它能改善 + 唤醒延迟,但本轮没有改变 idle 或完成 Wi-Fi/USB/电池功率的新一轮 A/B。 + +优先可评估的优化是:保留 LP_AP_INTC,复测允许 CPU0 深层 idle 的延迟和功率, +再提供明确的低延迟/省电选择。现有数据不足以承诺无延迟代价或具体节省多少电量。 + +## 整机与外设电源边界 + +- 实机配置为 `CONFIG_NO_HZ_IDLE=y`、`CONFIG_PM=y`、`CONFIG_HZ=250`, + `CONFIG_SUSPEND` 和 `CONFIG_PM_DEBUG` 未启用,`/sys/power/state` 为空。 + 这是当前内核能力边界,不能通过网页开关直接补出可靠的整机 suspend。 +- USB 数据连接和 Wi-Fi 热点开启时,DWC3、PCIe/WCN 等 runtime PM 节点处于 active; + 部分 control=on。该快照不证明外设无流量或拔线后也不会省电,不能直接强制改 auto。 +- 电池约 33%~34%、25.5~25.6°C,系统测得温区约 47~49°C,无须为本轮检查改温控。 +- 当前 USB 在线且充电,BQ 输入电流上限为 500 mA;FGU 净充电电流样本约 +15~+94 mA。 + 此为电池侧净电流及软件输入预算,不是 USB 功率计结果,也不是电池独立供电的负载电流。 + 本次未重新排查或修改既有充电协商策略。 +- 电池灯使用内核 pattern 触发;没有据此认定存在用户态软件呼吸动画空转。 + +## 证据 + +原始计数、两阶段摘要、只读采样器及脱敏附加信息位于忽略目录: + +`work/u30air-power-20261024/` + +主要文件:`samples.json`、`samples-page-closed.json`、`summary.json`、 +`summary-page-closed.json`、`extra.json`。不保存短信正文、号码、密码或 SIM 身份原文。 +本轮没有修改生产源码或部署任何省电补丁。 diff --git a/openwrt/build-rootfs.sh b/openwrt/build-rootfs.sh index a3faf5db..dc595575 100755 --- a/openwrt/build-rootfs.sh +++ b/openwrt/build-rootfs.sh @@ -245,6 +245,7 @@ if [ -d /in/luci-plugin ]; then ucode $R/usr/libexec/unisoc-modem/disable-channel-analysis $R ucode $R/usr/libexec/unisoc-modem/filter-wifi-ciphers $R chmod 0755 $R/etc/init.d/unisoc-cpu $R/etc/init.d/unisoc-cpu-cores $R/usr/libexec/rpcd/unisoc-cpu-cores + chmod 0755 $R/etc/init.d/unisoc-cpu-idle $R/usr/libexec/rpcd/unisoc-cpu-idle chmod 0600 $R/etc/config/unisoc_apn chmod 0755 $R/etc/init.d/unisoc-ttl $R/etc/hotplug.d/iface/92-unisoc-ttl $R/etc/uci-defaults/98-unisoc-ttl chmod 0755 $R/etc/uci-defaults/97-unisoc-upgrade-policy @@ -322,6 +323,7 @@ if [ -d /in/luci-plugin ]; then ln -sf ../init.d/unisoc-traffic $R/etc/rc.d/K01unisoc-traffic ln -sf ../init.d/unisoc-cpu $R/etc/rc.d/S99unisoc-cpu ln -sf ../init.d/unisoc-cpu-cores $R/etc/rc.d/S99unisoc-cpu-cores + ln -sf ../init.d/unisoc-cpu-idle $R/etc/rc.d/S99unisoc-cpu-idle ln -sf ../init.d/unisoc-cpu $R/etc/rc.d/K89unisoc-cpu ln -sf ../init.d/mu300-charge $R/etc/rc.d/S97mu300-charge ln -sf ../init.d/mu300-charge $R/etc/rc.d/K20mu300-charge diff --git a/openwrt/luci-app-mu300/Makefile b/openwrt/luci-app-mu300/Makefile index 0500b7d3..068ae063 100644 --- a/openwrt/luci-app-mu300/Makefile +++ b/openwrt/luci-app-mu300/Makefile @@ -32,6 +32,7 @@ define Package/luci-app-mu300/conffiles /etc/config/mu300-charge /etc/unisoc-modem/cpu.json /etc/unisoc-cpu-cores.json +/etc/unisoc-cpu-idle.json /etc/unisoc-modem/cpu-voltage.json endef @@ -44,6 +45,7 @@ define Package/luci-app-mu300/install $(CP) ./root/. $(1)/ chmod 0644 $(1)/usr/share/rpcd/ucode/*.uc $(1)/usr/share/ucode/mu300/*.uc chmod 0755 $(1)/etc/init.d/unisoc-cpu-cores $(1)/usr/libexec/rpcd/unisoc-cpu-cores $(1)/usr/libexec/unisoc-modem/cpu-cores + chmod 0755 $(1)/etc/init.d/unisoc-cpu-idle $(1)/usr/libexec/rpcd/unisoc-cpu-idle $(1)/usr/libexec/unisoc-modem/cpu-idle chmod 0600 $(1)/etc/config/unisoc_apn chmod 0755 $(1)/etc/uci-defaults/97-unisoc-upgrade-policy chmod 0600 $(1)/etc/config/mu300-charge @@ -87,6 +89,7 @@ define Package/luci-app-mu300/postinst /etc/init.d/unisoc-traffic start 2>/dev/null || true /etc/init.d/unisoc-cpu enable 2>/dev/null || true /etc/init.d/unisoc-cpu-cores enable 2>/dev/null || true + /etc/init.d/unisoc-cpu-idle enable 2>/dev/null || true } exit 0 endef @@ -114,6 +117,7 @@ define Package/luci-app-mu300/postrm /etc/init.d/unisoc-traffic disable 2>/dev/null || true /etc/init.d/unisoc-cpu disable 2>/dev/null || true /etc/init.d/unisoc-cpu-cores disable 2>/dev/null || true + /etc/init.d/unisoc-cpu-idle disable 2>/dev/null || true rm -f /etc/unisoc-modem/usb-boot.conf fi rm -f /tmp/luci-indexcache /tmp/luci-modulecache/* 2>/dev/null diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js index 5dc88e32..afacaf2e 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js @@ -151,6 +151,13 @@ var DASH_I18N = { "保存兼容性设置失败,未执行网络模式应用": ["Could not save compatibility settings; the network mode was not applied", "Uyumluluk ayarları kaydedilemedi; şebeke modu uygulanmadı"], '恢复核心初始状态': ['Restore initial core states', 'İlk çekirdek durumlarını geri yükle'], 'CPU0 保持在线': ['CPU0 stays online', 'CPU0 açık kalır'], + "CPU0 深度休眠": ["CPU0 deep idle", "CPU0 derin boşta bekleme"], + "允许 CPU0 深度休眠": ["Allow CPU0 deep idle", "CPU0 derin boşta beklemesine izin ver"], + "开启有利于空闲省电;关闭优先低延迟。仅改变 CPU0 深层空闲状态,WFI 和其他核心保持原设置。": ["Enable to favor idle power savings; disable to favor low latency. Only CPU0 deep states change; WFI and other cores keep their settings.", "Boştayken enerji tasarrufu için açın; düşük gecikme için kapatın. Yalnızca CPU0 derin durumları değişir; WFI ve diğer çekirdek ayarları korunur."], + "设置即时生效并在开机后保留。": ["Changes apply immediately and persist across reboots.", "Ayarlar hemen uygulanır ve yeniden başlatmalarda korunur."], + "设置已应用并保存,重启后继续生效。": ["Settings applied and saved for future boots.", "Ayarlar uygulandı ve sonraki açılışlar için kaydedildi."], + "无法读取 CPU0 深度休眠状态": ["Cannot read CPU0 deep idle state", "CPU0 derin boşta bekleme durumu okunamıyor"], + "CPU0 深度休眠设置失败": ["CPU0 deep idle change failed", "CPU0 derin boşta bekleme ayarı başarısız"], "CPU 核心开关": ["CPU core controls", "CPU çekirdek denetimleri"], "按内核能力逐核开启或关闭。CPU0 保持在线;关闭核心会降低并行处理能力,是否省电取决于实际负载。": ["Enable or disable individual cores supported by the kernel. CPU0 stays online. Disabling cores reduces parallel capacity; power savings depend on the workload.", "Çekirdek desteğine göre CPU çekirdeklerini açın veya kapatın. CPU0 açık kalır. Çekirdek kapatmak paralel kapasiteyi azaltır; enerji tasarrufu yüke bağlıdır."], "仅保存核心开关;不改变调频、调压和温控配置。": ["Save core states only; frequency, voltage and thermal settings are unchanged.", "Yalnızca çekirdek durumlarını kaydeder; frekans, voltaj ve sıcaklık ayarları değişmez."], diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/cpu-idle.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/cpu-idle.js new file mode 100644 index 00000000..54927091 --- /dev/null +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/cpu-idle.js @@ -0,0 +1,43 @@ +'use strict'; +'require baseclass'; +'require rpc'; +'require mu300.common as M'; +const get=rpc.declare({object:'unisoc-cpu-idle',method:'get',expect:{}}); +const apply=rpc.declare({object:'unisoc-cpu-idle',method:'apply',params:['enabled'],expect:{}}); +function node(tag,text,cls) { + const el=document.createElement(tag); + if(text!=null)el.textContent=M.translate(text); + if(cls)el.className=cls; + return el; +} +return baseclass.extend({render:function() { + const card=node('section',null,'mud-card mud-cpu-section mud-cpu-idle');card.hidden=true; + card.dataset.scope='idle'; + const head=node('div',null,'mud-cpu-heading');head.append(node('h3','CPU0 深度休眠'),node('span','即时生效','mud-cpu-badge')); + const label=node('label',null,'mud-cpu-persist'), input=node('input');input.type='checkbox';input.dataset.cpuIdle=''; + label.append(input,node('span','允许 CPU0 深度休眠')); + const note=node('p','开启有利于空闲省电;关闭优先低延迟。仅改变 CPU0 深层空闲状态,WFI 和其他核心保持原设置。','mud-note'); + const result=node('p','设置即时生效并在开机后保留。','mud-note');result.setAttribute('role','status'); + card.append(head,label,note,result); + let current=null,busy=false; + function paint(state) {current=state;input.checked=state.enabled;input.indeterminate=!!state.mixed;} + get().then(state=>{ + if(!state.ok)throw Error(state.error || M.translate('无法读取 CPU0 深度休眠状态')); + if(!state.supported)return; + paint(state);card.hidden=false; + }).catch(e=>{card.hidden=false;input.disabled=true;result.textContent=e.message;}); + input.onchange=async()=>{ + if(busy || !current)return; + busy=true;input.disabled=true; + try { + const state=await apply(input.checked); + if(!state.ok)throw Error(state.error || M.translate('CPU0 深度休眠设置失败')); + paint(state);result.textContent=M.translate('设置已应用并保存,重启后继续生效。'); + } catch(e) { + result.textContent=e.message; + try {const state=await get();if(state.ok)paint(state);else current=null;} + catch(_) {current=null;} + } finally {busy=false;if(current)input.disabled=false;} + }; + return card; +}}); diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/cpu.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/cpu.js index 5d000f13..20745b86 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/cpu.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/cpu.js @@ -4,6 +4,7 @@ 'require poll'; 'require mu300.common as M'; 'require mu300.cpu-cores as Cores'; +'require mu300.cpu-idle as Idle'; var get = rpc.declare({ object: 'mu300dash', method: 'cpu_get', expect: { '': {} } }); var apply = rpc.declare({ object: 'mu300dash', method: 'cpu_apply', params: ['payload'], expect: { '': {} } }); @@ -104,7 +105,7 @@ return view.extend({ root.appendChild(node('style', CSS)); var title = node('div', null, 'mud-cpu-title'); title.append(node('h2', M.translate('CPU 设置')), node('p', M.translate('频率、电压、温控分别保存。频率和温控即时生效,电压重启后生效。'), 'mud-note')); - root.append(title,Cores.render()); + root.append(title,Cores.render(),Idle.render()); var frequency = node('section', null, 'mud-card mud-cpu-section'); frequency.append(heading('频率与调速策略', '即时生效')); var grid = node('div', null, 'mud-cpu-grid'); frequency.append(grid); root.append(frequency); diff --git a/openwrt/luci-app-mu300/root/etc/init.d/unisoc-cpu-idle b/openwrt/luci-app-mu300/root/etc/init.d/unisoc-cpu-idle new file mode 100644 index 00000000..c7e49116 --- /dev/null +++ b/openwrt/luci-app-mu300/root/etc/init.d/unisoc-cpu-idle @@ -0,0 +1,6 @@ +#!/bin/sh /etc/rc.common +START=99 +start() { + [ -s /etc/unisoc-cpu-idle.json ] || return 0 + /usr/libexec/unisoc-modem/cpu-idle boot | logger -t unisoc-cpu-idle +} diff --git a/openwrt/luci-app-mu300/root/lib/upgrade/keep.d/unisoc-cpu-idle b/openwrt/luci-app-mu300/root/lib/upgrade/keep.d/unisoc-cpu-idle new file mode 100644 index 00000000..337c91f9 --- /dev/null +++ b/openwrt/luci-app-mu300/root/lib/upgrade/keep.d/unisoc-cpu-idle @@ -0,0 +1 @@ +/etc/unisoc-cpu-idle.json diff --git a/openwrt/luci-app-mu300/root/usr/libexec/rpcd/unisoc-cpu-idle b/openwrt/luci-app-mu300/root/usr/libexec/rpcd/unisoc-cpu-idle new file mode 100644 index 00000000..aa492b2b --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/libexec/rpcd/unisoc-cpu-idle @@ -0,0 +1,8 @@ +#!/bin/sh +case "$1:$2" in + list:) echo '{"get":{},"apply":{"enabled":true}}' ;; + call:get) /usr/libexec/unisoc-modem/cpu-idle get ;; + call:apply) /usr/libexec/unisoc-modem/cpu-idle apply ;; + *) echo '{"ok":false,"error":"CPU0 深度休眠操作无效"}' ;; +esac +exit 0 diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cpu-idle b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cpu-idle new file mode 100644 index 00000000..f50e37b9 --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cpu-idle @@ -0,0 +1,8 @@ +#!/bin/sh +action=${1:-get} +case "$action" in get|apply|boot) ;; *) exit 2 ;; esac +if [ "$action" != get ]; then + exec 9>"${UNISOC_IDLE_LOCK:-/run/unisoc-cpu-idle.lock}" || exit 1 + flock -n 9 || { echo '{"ok":false,"error":"CPU0 深度休眠设置正忙"}'; exit 1; } +fi +exec ucode "${UNISOC_IDLE_LIB:-/usr/libexec/unisoc-modem/cpu-idle.uc}" "$action" diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cpu-idle.uc b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cpu-idle.uc new file mode 100644 index 00000000..f64125d0 --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cpu-idle.uc @@ -0,0 +1,79 @@ +// CPU0 deep idle on UMS9620 (T157/T760). WFI and other CPUs are untouched. +import * as fs from 'fs'; +const ROOT=getenv('UNISOC_IDLE_ROOT') || ''; +const CONFIG=getenv('UNISOC_IDLE_CONFIG') || ROOT+'/etc/unisoc-cpu-idle.json'; +function read(p) { return trim(fs.readfile(p) ?? ''); } +function states() { + let compat=split(fs.readfile(ROOT+'/sys/firmware/devicetree/base/compatible') ?? '', '\x00'); + if(index(compat,'sprd,ums9620')<0) return []; + let base=ROOT+'/sys/devices/system/cpu/cpu0/cpuidle', out=[]; + for(let id in sort(fs.lsdir(base) || [])) { + if(!match(id,/^state[0-9]+$/))continue; + let path=base+'/'+id, name=read(path+'/name'), value=read(path+'/disable'); + if(name!='cluster-pd' && !match(name,/^core-sleep-/))continue; + if(value!='0' && value!='1')die('无法读取 CPU0 深度休眠状态'); + push(out,{id,name,disabled:value=='1',path:path+'/disable'}); + } + return out; +} +function profile() { + if(!fs.stat(CONFIG))return null; + let v=json(fs.readfile(CONFIG)); + if(v?.version!=1 || type(v.enabled)!='bool' || length(keys(v))!=2)die('CPU0 深度休眠配置无效'); + return v; +} +function status(nodes) { + if(!length(nodes))return {ok:true,supported:false,enabled:false,mixed:false,states:[]}; + let p=profile(), enabled=length(filter(nodes,n=>!n.disabled)); + return {ok:true,supported:!!length(nodes),enabled:!!length(nodes) && enabled==length(nodes), + mixed:enabled>0 && enabled({id:n.id,name:n.name,disabled:n.disabled}))}; +} +function write_nodes(nodes, enabled) { + let value=enabled?'0':'1'; + for(let n in nodes) { + if(read(n.path)==value)continue; + if(fs.writefile(n.path,value+'\n')==null || read(n.path)!=value)return false; + } + return true; +} +function restore(nodes) { + let ok=true; + for(let n in nodes) { + let value=n.disabled?'1':'0'; + if(read(n.path)!=value && (fs.writefile(n.path,value+'\n')==null || read(n.path)!=value))ok=false; + } + return ok; +} +function save(enabled) { + let tmp=CONFIG+'.new', text=sprintf('%J\n',{version:1,enabled}); + if(fs.writefile(tmp,text)==length(text) && fs.chmod(tmp,384) && fs.rename(tmp,CONFIG))return true; + fs.unlink(tmp);return false; +} +try { + let action=ARGV[0] || 'get', nodes=states(); + if(action=='get')print(sprintf('%J\n',status(nodes))); + else if(action=='boot' || action=='apply') { + let enabled; + if(action=='boot') { + let p=profile(); + if(!p || !length(nodes)) {print('{"ok":true,"skipped":true}\n');exit(0);} + enabled=p.enabled; + } else { + let request=json(fs.readfile('/dev/stdin') || '{}'); + delete request.ubus_rpc_session; + if(type(request.enabled)!='bool' || length(keys(request))!=1)die('CPU0 深度休眠请求无效'); + if(!length(nodes))die('此平台不提供 CPU0 深度休眠开关'); + enabled=request.enabled; + } + // Validate any saved file before changing hardware. + profile(); + if(!write_nodes(nodes,enabled)) { + print(sprintf('%J\n',{ok:false,error:'内核未接受 CPU0 深度休眠设置',rollback:restore(nodes)}));exit(1); + } + if(action=='apply' && !save(enabled)) { + print(sprintf('%J\n',{ok:false,error:'无法保存 CPU0 深度休眠设置',rollback:restore(nodes)}));exit(1); + } + print(sprintf('%J\n',status(states()))); + } else die('CPU0 深度休眠操作无效'); +} catch(e) {print(sprintf('%J\n',{ok:false,error:replace(''+e,/\n.*/, '')}));exit(1);} diff --git a/openwrt/luci-app-mu300/root/usr/share/rpcd/acl.d/unisoc-cpu-idle.json b/openwrt/luci-app-mu300/root/usr/share/rpcd/acl.d/unisoc-cpu-idle.json new file mode 100644 index 00000000..d90ed7eb --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/share/rpcd/acl.d/unisoc-cpu-idle.json @@ -0,0 +1,7 @@ +{ + "unisoc-cpu-idle": { + "description": "CPU0 deep idle on supported UMS9620 devices", + "read": {"ubus": {"unisoc-cpu-idle": ["get"]}}, + "write": {"ubus": {"unisoc-cpu-idle": ["apply"]}} + } +} diff --git a/rootfs/overlay/opt/mu300/bin/early-recorder b/rootfs/overlay/opt/mu300/bin/early-recorder index 492fbe5d..a773090e 100755 --- a/rootfs/overlay/opt/mu300/bin/early-recorder +++ b/rootfs/overlay/opt/mu300/bin/early-recorder @@ -35,7 +35,7 @@ while [ "$(cut -d. -f1 /proc/uptime)" -lt "$end" ]; do ip -br addr 2>/dev/null echo "--- lsmod" systemctl list-units --no-legend --plain --state=activating,failed 2>/dev/null - [ -f /etc/openwrt_release ] && { echo "--- ps"; ps w 2>/dev/null; echo "--- logread"; logread 2>/dev/null | grep -v PR_CAPBSET | tail -300; echo "--- android logcat"; tail -150 /var/log/android-logcat.txt 2>/dev/null; echo "--- mu300 logs"; tail -40 /tmp/mu300-*.log 2>/dev/null; } + [ -f /etc/openwrt_release ] && { echo "--- ps"; ps w 2>/dev/null; echo "--- logread"; logread -l 300 2>/dev/null | grep -v PR_CAPBSET; echo "--- android logcat"; tail -150 /var/log/android-logcat.txt 2>/dev/null; echo "--- mu300 logs"; tail -40 /tmp/mu300-*.log 2>/dev/null; } echo "--- dmesg" dmesg -s 1000000 2>/dev/null || dmesg | tail -c 1000000 echo "MU300-PERSIST-END" @@ -51,5 +51,5 @@ while [ "$(cut -d. -f1 /proc/uptime)" -lt "$end" ]; do sync # every 2 s for the first minute and a half, where the intermittent early hangs have happened; a 10 s gap # left a single snapshot of a boot that died between 11 and 21 s - if [ "$(cut -d. -f1 /proc/uptime)" -lt 90 ]; then sleep 2; else sleep 10; fi + if [ "$(cut -d. -f1 /proc/uptime)" -lt 90 ]; then sleep 2; else sleep 30; fi done diff --git a/rootfs/overlay/opt/mu300/bin/mu300-led b/rootfs/overlay/opt/mu300/bin/mu300-led index 232c954c..8e35dd7c 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-led +++ b/rootfs/overlay/opt/mu300/bin/mu300-led @@ -97,6 +97,33 @@ awake() { until=$(rd "$STATE/.awake-until") || return 1 [ "$(uptime_s)" -lt "${until:-0}" ] } +# A deadline hint for sysd. Keep all board colours and physical writes here. +tick_hint() { + local now due until cap status color mode marker=- + now=$(uptime_s); due=$((now + 600)) + until=$(rd "$STATE/.awake-until") + case $until in ''|*[!0-9]*) ;; *) + [ "$KEEP_LIT" = 1 ] || [ "$TIMEOUT" = 0 ] || [ "$until" -le "$now" ] || due=$until ;; + esac + if [ "$DEVICE" = u30air ]; then + local root=${MU300_POWER_SUPPLY_DIR:-$R/sys/class/power_supply} + cap=$(rd "$root/sc27xx-fgu/capacity"); status=$(rd "$root/sc27xx-fgu/status") + [ "$KEEP_LIT" != 0 ] || status=Discharging + case $cap in ''|*[!0-9]*) marker=unavailable ;; *) + color=white; [ "$cap" -ge 50 ] || color=blue + [ "$status" != Full ] || color=white + mode=steady + if [ "$status" = Charging ]; then mode=breathe; [ "$cap" -ge 10 ] || color=red; fi + marker=$color:$mode:$KEEP_LIT ;; + esac + fi + mkdir -p "$STATE" || return 0 + (umask 077; printf 'due %s\nbattery %s\n' "$due" "$marker" > "$STATE/.tick-hint.new") && + mv "$STATE/.tick-hint.new" "$STATE/.tick-hint" + return 0 +} +# Do not write hints from the long-lived animation workers. +case ${1:-} in siren|boot-worker|test) ;; *) trap tick_hint EXIT ;; esac vendor_ldo() { # vendor_ldo zte-ldoN: the 5.4 kernel's switch for that LDO, if there case $1 in zte-ldo[0-9]) ;; *) return 1 ;; esac for f in "$R"/sys/devices/platform/*zte*ldo*leds*/vddcama${1#zte-ldo}_status; do [ -e "$f" ] && { echo "$f"; return 0; }; done @@ -273,10 +300,11 @@ case "$1 ${2:-}" in echo $(( $(uptime_s) + TIMEOUT )) > "$STATE/.awake-until" battery show_all ;; - "sleep "*) + "tick "*|"sleep "*) + [ "$1" != tick ] || battery [ "$TIMEOUT" = 0 ] && exit 0 - if [ "${2:-}" = --if-due ] && awake; then exit 0; fi - [ -e "$STATE/.awake-until" ] || [ "${2:-}" != --if-due ] || exit 0 # dark already + if { [ "$1" = tick ] || [ "${2:-}" = --if-due ]; } && awake; then exit 0; fi + [ -e "$STATE/.awake-until" ] || { [ "$1" != tick ] && [ "${2:-}" != --if-due ]; } || exit 0 rm -f "$STATE/.awake-until" for f in "$STATE"/*; do [ -f "$f" ] && write "${f##*/}" 0; done ;; "alarm on") diff --git a/rootfs/overlay/opt/mu300/bin/mu300-lowlatency b/rootfs/overlay/opt/mu300/bin/mu300-lowlatency index 4a45596e..e3dfb318 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-lowlatency +++ b/rootfs/overlay/opt/mu300/bin/mu300-lowlatency @@ -3,6 +3,10 @@ # CPU0 idle after boot. Apply the requested policy to every MU300 profile. # CPU0 only; no polling, frequency changes or radio/PCIe power commands. R=${MU300_SYSROOT:-} +# An explicit web choice takes precedence over the previous startup policy. +if [ -s "$R/etc/unisoc-cpu-idle.json" ]; then + UNISOC_IDLE_ROOT="$R" exec /usr/libexec/unisoc-modem/cpu-idle boot +fi status=0 for node in "$R"/sys/devices/system/cpu/cpu0/cpuidle/state*/disable; do [ -f "$node" ] || continue diff --git a/rootfs/overlay/opt/mu300/bin/mu300-sysd b/rootfs/overlay/opt/mu300/bin/mu300-sysd index e0d1a27c..d83101ed 100644 --- a/rootfs/overlay/opt/mu300/bin/mu300-sysd +++ b/rootfs/overlay/opt/mu300/bin/mu300-sysd @@ -1,8 +1,7 @@ #!/usr/bin/ucode // Event-driven service core from liuwang97/cpu-load ccf89bb6, adapted locally. // Preserve this branch's U30 double-click, LED helper, per-policy owned caps, -// vendor-kernel policy and five-second protection/LED deadlines. No mu300-power -// protocol, adaptive thermal delay or upstream frequency backstop is assumed. +// vendor-kernel policy, thermal ownership and board LED semantics. // --round runs one thermal round for offline tests; MU300_SYSROOT is a fake root. 'use strict'; @@ -98,8 +97,15 @@ function which(cmd) { return null; } -// Retain the normal scheduler deadlines; no added timer slack. -function fork_exec(exe, args, envs, cb) { return uloop.process(exe,args,envs,cb); } +// Coalesce idle waits only. Never let child actions inherit this tolerance. +const SLACK_FILE='/proc/self/timerslack_ns'; +let slack=(R=='' && MODE=='')?rd(SLACK_FILE):null; +function slack_wait() {if(slack!=null)writefile(SLACK_FILE,'500000000');} +function fork_exec(exe, args, envs, cb) { + if(slack!=null)writefile(SLACK_FILE,slack); + let p=uloop.process(exe,args,envs,cb); + slack_wait();return p; +} let running = 0; // started and not ended yet (the helper is not counted) let idle_check; // set below @@ -279,20 +285,52 @@ function press(code, kind) { } // The existing LED helper owns policy, custom styles, battery and charger state. -// Keep its safety tick unchanged; power-supply events can request a sooner check. +// Deadlines and power events drive checks; the helper remains the LED owner. const UEVENTS = 'power_supply,extcon'; +const LEDDIR=R+'/run/mu300/led', PSY=env('MU300_POWER_SUPPLY_DIR',R+'/sys/class/power_supply'); +let led_hint=null, led_seen=null; +function led_hint_load() { + led_hint=null; + let lines=split(readfile(LEDDIR+'/.tick-hint') ?? '', '\n'); + if(!match(lines[0] ?? '',/^due [0-9]+$/))return; + led_hint={due:+substr(lines[0],4),battery:substr(lines[1] ?? '',8)}; +} +function led_observe() { + let battery='-'; + if(led_hint?.battery!='-' && led_hint!=null) { + let cap=rd(PSY+'/sc27xx-fgu/capacity'), st=rd(PSY+'/sc27xx-fgu/status'); + let on=rd(PSY+'/bq256xx-charger/online'); + if(on==null)on=(st=='Charging' || st=='Full')?'1':'0'; + if(on!='1')st='Discharging'; + let color=+cap>=50?'white':'blue', mode='steady'; + if(st=='Full')color='white'; + if(st=='Charging') {mode='breathe';if(+cap<10)color='red';} + battery=digits(cap)?color+':'+mode+':'+(on=='1'?'1':'0'):'unavailable'; + } + return [battery,rd(LEDDIR+'/.awake-until'),rd(LEDDIR+'/.boot-chase'), + rd(LEDDIR+'/.battery-breathe'),rd(R+'/run/mu300/led-siren.pid')]; +} let led_timer = null, led_soon_timer = null, led_ticking = false, led_again = false; function led_look() { if (led_ticking) { led_again = true; return; } + led_hint_load(); + let observed=led_observe(); + if(led_hint && now() { + spawn(['mu300-led','tick'], () => { led_ticking = false; + led_hint_load();led_seen=sprintf('%J',led_observe()); if (led_again) { led_again = false; led_look(); } else led_arm(); }); } led_arm = function() { - led_timer = retimer(led_timer,5000, () => { led_timer = null; led_look(); }); + led_hint_load(); + let on=rd(PSY+'/bq256xx-charger/online'), safety=on=='1'?30:90; + let left=led_hint?min(safety,led_hint.due-now()):5; + let due=rd(LEDDIR+'/.awake-until'); + if(on!='1' && digits(due) && +due>now())left=min(left,+due-now()); + led_timer = retimer(led_timer,max(50,int(left*1000)+50), () => { led_timer = null; led_look(); }); }; function led_soon() { led_soon_timer ??= uloop.timer(500, () => { led_soon_timer = null; led_look(); }); @@ -404,6 +442,7 @@ const CRIT = num('MU300_THERMAL_CRIT', 105000); const BATT_HOT = num('MU300_BATTERY_HOT', 500); const BATT_COOL = num('MU300_BATTERY_COOL', 450); const WAIT = 5; +const MAX_WAIT=30, MAX_WAIT_ALONE=10; const TH = R + '/sys/class/thermal'; const LED = BIN + '/mu300-led'; const CAPS = R + '/run/mu300/thermal-caps'; @@ -427,7 +466,8 @@ function hottest(zones) { let t = 0; for (let z in zones) { let v = rd(TH + '/' + z + '/temp'); - if (integer(v) && +v > t) + if (!integer(v))die('无法读取温区 '+z); + if (+v > t) t = +v; } return t; @@ -561,7 +601,10 @@ function thermal_round() { } else if (exists(ALARM) && t<=COOL && bn!=null && bn<=BATT_COOL) { unlink(ALARM); log('thermal-guard','cooled down (SoC '+t+' mC, battery '+bs+' dC): LED alarm off'); chain([LED,'alarm','off']); } - return 5; // Preserve this branch's protection cadence, including without native cooling. + if(!length(zones) || exists(ALARM) || length(names(CAPS,'')) || (b!=null && !integer(b)))return WAIT; + let gap=WAIT+int((HOT-t)/2000); + if(integer(b))gap=min(gap,WAIT+int((BATT_HOT-+b)/10)); + return max(WAIT,min(gap,throttle?MAX_WAIT_ALONE:MAX_WAIT)); } function thermal_next() { let gap = WAIT; @@ -643,6 +686,7 @@ if (parts.thermal) { thermal_init(); thermal_next(); } +slack_wait(); uloop.run(); helper_close(); if (rd(OWN_DIR+'/pid')==''+OWN_PID) { unlink(OWN_DIR+'/pid'); rmdir(OWN_DIR); } diff --git a/rootfs/overlay/opt/mu300/bin/thermal-guard b/rootfs/overlay/opt/mu300/bin/thermal-guard index a02ad676..97ed83ba 100755 --- a/rootfs/overlay/opt/mu300/bin/thermal-guard +++ b/rootfs/overlay/opt/mu300/bin/thermal-guard @@ -59,12 +59,15 @@ native_cpu_cooling() { } hottest() { - local max=0 t + local max=0 t valid=1 found=0 for z in "$R"/sys/class/thermal/thermal_zone*/temp; do - read -r t < "$z" 2>/dev/null || continue + read -r t < "$z" 2>/dev/null || { valid=0; continue; } + case $t in ''|*[!0-9]*) valid=0; continue ;; esac + found=1 [ "$t" -gt "$max" ] 2>/dev/null && max=$t done echo "$max" + [ "$valid" = 1 ] && [ "$found" = 1 ] } DEVICE=$(${MU300_BIN:-/opt/mu300/bin}/mu300-device) battery() { # the battery's temperature in tenths of a degree; the U30 Air only @@ -138,6 +141,7 @@ guard_raise() { } while :; do t=$(hottest) + sensors_ok=$? throttle=$legacy_throttle emergency=$legacy_throttle if [ -d "$R/sys/module/mu300_thermal" ]; then @@ -169,5 +173,20 @@ while :; do "$LED" alarm off fi [ -n "$R" ] && exit 0 - sleep 5 + # Adaptive safety cadence; retain fast checks near thresholds or on errors. + gap=5 + if [ "$sensors_ok" = 0 ] && [ ! -e "$ALARM" ] && ! ls "$CAPS"/policy* >/dev/null 2>&1; then + gap=$((5 + (HOT - t) / 2000)) + case $b in ''|*[!0-9]*) [ -z "$b" ] || gap=5 ;; *) + bgap=$((5 + (BATT_HOT - b) / 10)); [ "$gap" -le "$bgap" ] || gap=$bgap ;; + esac + max_gap=30; [ "$throttle" != 1 ] || max_gap=10 + [ "$gap" -le "$max_gap" ] || gap=$max_gap + [ "$gap" -ge 5 ] || gap=5 + fi + idle_slack= + { IFS= read -r idle_slack < /proc/$$/timerslack_ns; } 2>/dev/null || idle_slack= + [ -z "$idle_slack" ] || { printf '500000000\n' > /proc/$$/timerslack_ns; } 2>/dev/null + sleep "$gap" + [ -z "$idle_slack" ] || { printf '%s\n' "$idle_slack" > /proc/$$/timerslack_ns; } 2>/dev/null done diff --git a/rootfs/overlay/opt/mu300/lib/data-events.sh b/rootfs/overlay/opt/mu300/lib/data-events.sh index c0603872..b637eae7 100644 --- a/rootfs/overlay/opt/mu300/lib/data-events.sh +++ b/rootfs/overlay/opt/mu300/lib/data-events.sh @@ -53,7 +53,8 @@ watch_event_decode() { esac } watch_next() { - local interval=${MU300_WATCH_INTERVAL:-30} due line status + local interval=${MU300_WATCH_INTERVAL:-30} due line status idle_slack= + { IFS= command read -r idle_slack < /proc/$$/timerslack_ns; } 2>/dev/null || idle_slack= watch_event= case "$interval" in ''|*[!0-9]*) echo 'mobile-data: watch interval must be whole seconds' >&2; return 1 ;; esac [ "$watch_events" = 1 ] || return 1 @@ -61,7 +62,10 @@ watch_next() { due=$((WATCH_NOW + interval)) while [ "$WATCH_NOW" -lt "$due" ]; do status=0 + # Only the blocking wait gets slack; AT/route actions keep their defaults. + [ -z "$idle_slack" ] || { printf '500000000\n' > /proc/$$/timerslack_ns; } 2>/dev/null || : IFS= read -r -t "$((due - WATCH_NOW))" line <&8 || status=$? + [ -z "$idle_slack" ] || { printf '%s\n' "$idle_slack" > /proc/$$/timerslack_ns; } 2>/dev/null || : watch_clock || return 1 if [ "$status" != 0 ]; then # Bash read reports its timer as 128 + SIGALRM. /proc/uptime diff --git a/rootfs/overlay/opt/mu300/lib/ndp-events.sh b/rootfs/overlay/opt/mu300/lib/ndp-events.sh index a1e5daa6..b838979c 100644 --- a/rootfs/overlay/opt/mu300/lib/ndp-events.sh +++ b/rootfs/overlay/opt/mu300/lib/ndp-events.sh @@ -55,14 +55,18 @@ ndp_event_relevant() { return 0 } ndp_events_wait() { - local due line status + local due line status idle_slack= + { IFS= command read -r idle_slack < /proc/$$/timerslack_ns; } 2>/dev/null || idle_slack= NDP_DIRTY=0 ndp_clock || return 1 due=$NDP_TICK_AT [ "$NDP_FULL_AT" -ge "$due" ] || due=$NDP_FULL_AT while [ "$NDP_NOW" -lt "$due" ]; do status=0 + # Only the blocking wait gets slack; AT/route actions keep their defaults. + [ -z "$idle_slack" ] || { printf '500000000\n' > /proc/$$/timerslack_ns; } 2>/dev/null || : IFS= read -r -t "$((due - NDP_NOW))" line <&8 || status=$? + [ -z "$idle_slack" ] || { printf '%s\n' "$idle_slack" > /proc/$$/timerslack_ns; } 2>/dev/null || : ndp_clock || return 1 if [ "$status" != 0 ]; then # Bash timeout is not EOF, even if uptime rounds below due. diff --git a/rootfs/overlay/opt/mu300/lib/sms-events.sh b/rootfs/overlay/opt/mu300/lib/sms-events.sh index c7301dae..193e11be 100644 --- a/rootfs/overlay/opt/mu300/lib/sms-events.sh +++ b/rootfs/overlay/opt/mu300/lib/sms-events.sh @@ -50,13 +50,17 @@ sms_event_decode() { # Wait until a relevant event or the real monotonic deadline. Unrelated radio # traffic does not start processes, scan logs or move the safety-sync deadline. sms_events_wait() { - local due=$1 line status + local due=$1 line status idle_slack= + { IFS= command read -r idle_slack < /proc/$$/timerslack_ns; } 2>/dev/null || idle_slack= sms_event= while :; do sms_clock || return 1 [ "$SMS_NOW" -lt "$due" ] || return 0 status=0 + # Only the blocking wait gets slack; AT/route actions keep their defaults. + [ -z "$idle_slack" ] || { printf '500000000\n' > /proc/$$/timerslack_ns; } 2>/dev/null || : IFS= read -r -t "$((due - SMS_NOW))" line <&8 || status=$? + [ -z "$idle_slack" ] || { printf '%s\n' "$idle_slack" > /proc/$$/timerslack_ns; } 2>/dev/null || : if [ "$status" != 0 ]; then sms_clock || return 1 # Bash's timer can fire just before /proc/uptime rounds up. diff --git a/tests/cpu_cores_browser.py b/tests/cpu_cores_browser.py index 5d990270..0866f3c3 100644 --- a/tests/cpu_cores_browser.py +++ b/tests/cpu_cores_browser.py @@ -42,7 +42,7 @@ with sync_playwright() as p: const M=new Function('rpc','baseclass','L',sources[0])(rpc,baseclass,L); M.localizeMenu=()=>{}; const Cores=new Function('baseclass','rpc','poll','M',sources[1])(baseclass,rpc,poll,M); - window.cpuView=new Function('view','rpc','poll','M','Cores',sources[2])(view,rpc,poll,M,Cores); + window.cpuView=new Function('view','rpc','poll','M','Cores','Idle',sources[2])(view,rpc,poll,M,Cores,{render:()=>document.createElement('div')}); const cpu={ok:1,available:true,persistent:false,policies:[],zones:[],voltage:{supported:false}}; document.body.append(cpuView.render(cpu)); }''',[sources,lang]) diff --git a/tests/cpu_idle_browser.py b/tests/cpu_idle_browser.py new file mode 100644 index 00000000..15cdea29 --- /dev/null +++ b/tests/cpu_idle_browser.py @@ -0,0 +1,43 @@ +"""Exercise the actual idle switch from both repositories with fake RPC.""" +from pathlib import Path +from playwright.sync_api import sync_playwright + +TOP=Path(__file__).resolve().parents[1] +with sync_playwright() as pw: + browser=pw.chromium.launch(executable_path='C:/Program Files/Google/Chrome/Application/chrome.exe') + for repo,app in [(TOP,'mu300'),(TOP.parent/'e5-linux','t551m')]: + js=repo/f'openwrt/luci-app-{app}/htdocs/luci-static/resources' + for supported in (True,False): + page=browser.new_page(viewport={'width':360,'height':800});errors=[] + page.on('pageerror',lambda e:errors.append(str(e))) + page.set_content('
') + page.evaluate('''([source,supported])=>{ + window.state={ok:true,supported,enabled:false};window.calls=[];window.fail=false; + const rpc={declare:s=>(enabled)=>{ + if(s.method==='apply'){ + calls.push(enabled); + if(fail)return Promise.resolve({ok:false,error:'fixture failure'}); + state.enabled=enabled; + } + return Promise.resolve({...state}); + }}; + const Idle=new Function('baseclass','rpc','M',source)({extend:x=>x},rpc,{translate:s=>s}); + document.querySelector('main').append(Idle.render()); + }''',[(js/'mu300/cpu-idle.js').read_text(encoding='utf-8'),supported]) + if supported: + control=page.locator('[data-cpu-idle]');control.check() + page.wait_for_function('calls.length===1 && !document.querySelector("input").disabled') + assert page.evaluate('calls')==[True] + assert control.is_checked() + page.evaluate('fail=true');control.click() + page.wait_for_function('calls.length===2 && !document.querySelector("input").disabled') + assert control.is_checked(), 'failed apply must display actual state' + assert 'fixture failure' in page.locator('[role=status]').inner_text() + else: + page.wait_for_timeout(20) + assert page.locator('.mud-cpu-idle').is_hidden() + assert page.evaluate('calls')==[] + assert not errors,errors + page.close() + browser.close() +print('PASS: both repositories, supported/unsupported, apply, failure and actual state') diff --git a/tests/dashboard_cpu_sections_browser.py b/tests/dashboard_cpu_sections_browser.py index 0ac87346..263e3c1e 100644 --- a/tests/dashboard_cpu_sections_browser.py +++ b/tests/dashboard_cpu_sections_browser.py @@ -25,7 +25,7 @@ with sync_playwright() as p: window.data={ok:1,persist:false,policies:[0,4,7].map((id,i)=>({id:'policy'+id,cpus:['0 1 2 3','4 5 6','7'][i],driver:'sprd-cpufreq-v2',governors:['schedutil','performance'],governor:'schedutil',frequencies:[408000,1000000,1800000],min:408000,max:1800000,hardware_min:408000,hardware_max:1800000,current:1000000,writable:true})),zones:[{name:'soc-thmzone',id:'thermal_zone19',temp:42000,minimum:40000,maximum:100000,step:1000,mode:'enabled',policy:'step_wise',trips:[{id:0,type:'passive',temp:70000,hysteresis:1000,writable:true,throttles_cpu:false},{id:1,type:'passive',temp:85000,hysteresis:1000,writable:true,throttles_cpu:true},{id:2,type:'critical',temp:110000,hysteresis:2000,writable:false}],cooling:[{id:'cdev0',type:'cpufreq-cpu0',state:0,max_state:9}]},{name:'lit0-thmzone',id:'thermal_zone7',temp:40000,trips:[],cooling:[]}],voltage:{supported:false}}; const rpc={declare:o=>(payload)=>{if(o.method==='cpu_apply'){requests.push(JSON.parse(payload));}return Promise.resolve(data);}}; const M=new Function('rpc','baseclass','L',common)(rpc,{extend:o=>o},L); - window.view=new Function('view','rpc','poll','M','Cores',cpu)({extend:o=>o},rpc,{add(){},remove(){}},M,{render:()=>document.createElement('div')}); + window.view=new Function('view','rpc','poll','M','Cores','Idle',cpu)({extend:o=>o},rpc,{add(){},remove(){}},M,{render:()=>document.createElement('div')},{render:()=>document.createElement('div')}); document.body.append(view.render(data)); }''',[common,cpu,lang]) assert page.evaluate('document.documentElement.scrollWidth <= innerWidth'),(theme,dark,lang,width,'overflow') diff --git a/tests/test_cpu_idle.py b/tests/test_cpu_idle.py new file mode 100644 index 00000000..827825b5 --- /dev/null +++ b/tests/test_cpu_idle.py @@ -0,0 +1,80 @@ +"""Run the production ucode against private UMS9620/UMS9621 sysfs trees.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +TOP=Path(__file__).resolve().parents[1] +LIB=Path(os.environ.get('CPU_IDLE_TEST_LIB',str(TOP/'openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cpu-idle.uc'))) + + +class CpuIdle(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.root=Path(self.tmp.name) + p=self.root/'sys/firmware/devicetree/base';p.mkdir(parents=True) + (p/'compatible').write_bytes(b'board,test\0sprd,ums9620\0') + (self.root/'etc').mkdir() + for cpu in (0,1): + for index,name in enumerate(('WFI','core-sleep-lit','cluster-pd')): + p=self.root/f'sys/devices/system/cpu/cpu{cpu}/cpuidle/state{index}';p.mkdir(parents=True) + (p/'name').write_text(name);(p/'disable').write_text('1' if cpu==0 else '0') + self.profile=self.root/'etc/unisoc-cpu-idle.json' + self.env=dict(os.environ,UNISOC_IDLE_ROOT=str(self.root)) + + def tearDown(self):self.tmp.cleanup() + + def call(self,action,request=None,**env): + p=subprocess.run(['ucode',str(LIB),action],input=json.dumps(request or {}), + text=True,capture_output=True,env=dict(self.env,**env),timeout=5) + self.assertTrue(p.stdout,p.stderr) + return p.returncode,json.loads(p.stdout) + + def values(self):return [p.read_text().strip() for p in sorted(self.root.glob('sys/devices/system/cpu/cpu*/cpuidle/state*/disable'))] + + def test_get_and_absent_boot_never_change_state(self): + before=self.values() + self.assertTrue(self.call('get')[1]['supported']) + self.assertFalse(self.call('get')[1]['enabled']) + self.assertTrue(self.call('boot')[1]['skipped']) + self.assertEqual(self.values(),before);self.assertFalse(self.profile.exists()) + + def test_apply_persist_replay_and_only_cpu0_deep_states(self): + code,result=self.call('apply',{'enabled':True,'ubus_rpc_session':'fixture'}) + self.assertEqual(code,0);self.assertTrue(result['enabled']) + self.assertEqual(self.values(),['1','0','0','0','0','0']) + self.assertEqual(json.loads(self.profile.read_text()),{'version':1,'enabled':True}) + self.assertEqual(self.profile.stat().st_mode&0o777,0o600) + for p in self.root.glob('sys/devices/system/cpu/cpu0/cpuidle/state[12]/disable'):p.write_text('1') + self.assertEqual(self.call('boot')[0],0) + self.assertEqual(self.values(),['1','0','0','0','0','0']) + self.assertFalse(self.call('apply',{'enabled':False})[1]['enabled']) + self.assertEqual(self.values(),['1','1','1','0','0','0']) + + def test_ums9621_hidden_and_direct_write_rejected(self): + (self.root/'sys/firmware/devicetree/base/compatible').write_bytes(b'sprd,ums9621\0') + before=self.values() + self.assertFalse(self.call('get')[1]['supported']) + self.assertNotEqual(self.call('apply',{'enabled':True})[0],0) + self.assertEqual(self.values(),before);self.assertFalse(self.profile.exists()) + + def test_invalid_requests_and_profile_are_rejected_before_writes(self): + before=self.values() + for request in ({'enabled':1},{'enabled':'true'},{'enabled':True,'path':'arbitrary'},{}): + self.assertNotEqual(self.call('apply',request)[0],0) + self.assertEqual(self.values(),before) + self.profile.write_text('{broken') + self.assertNotEqual(self.call('apply',{'enabled':True})[0],0) + self.assertEqual(self.values(),before) + + def test_save_failure_restores_exact_mixed_state(self): + path=self.root/'sys/devices/system/cpu/cpu0/cpuidle/state1/disable';path.write_text('0') + self.assertTrue(self.call('get')[1]['mixed']) + before=self.values() + code,result=self.call('apply',{'enabled':True},UNISOC_IDLE_CONFIG=str(self.root/'missing/profile.json')) + self.assertNotEqual(code,0);self.assertTrue(result['rollback']) + self.assertEqual(self.values(),before) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_device_scripts.py b/tests/test_device_scripts.py index 0c231251..2fd73c67 100644 --- a/tests/test_device_scripts.py +++ b/tests/test_device_scripts.py @@ -346,7 +346,7 @@ class Buttons(ShellTest): cases = [('116 short', ['mu300-led wake']), ('138 short', ['mu300-led wake', 'mu300-wifi-band toggle']), ('138 long', ['mu300-led wake', 'systemctl is-active --quiet mu300-hotspot', 'systemctl start mu300-hotspot']), - ('0 tick', ['mu300-led sleep --if-due']), + ('0 tick', [getattr(self,'LED_TICK','mu300-led sleep --if-due')]), ('116 long', ['mu300-led wake', 'systemctl poweroff']), ('115 short', [])] for shell in self.each_shell(): diff --git a/tests/test_power_idle_scheduling.py b/tests/test_power_idle_scheduling.py new file mode 100644 index 00000000..b31dc077 --- /dev/null +++ b/tests/test_power_idle_scheduling.py @@ -0,0 +1,100 @@ +"""Production sysd with private sensors/helpers; no real device access.""" +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import tempfile +import time +import unittest + +TOP=Path(__file__).resolve().parents[1] +SYSD=TOP/'rootfs/overlay/opt/mu300/bin/mu300-sysd' + + +class Scheduling(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.base=Path(self.tmp.name) + self.root=self.base/'root';self.bin=self.base/'bin';self.bin.mkdir() + (self.root/'proc').mkdir(parents=True);(self.root/'proc/uptime').symlink_to('/proc/uptime') + (self.root/'run/mu300').mkdir(parents=True) + (self.root/'run/mu300/device').write_text('f50') + self.stub('mu300-device','''#!/bin/sh +echo f50 +''') + self.stub('mu300-led','''#!/bin/sh +exit 0 +''') + self.env=dict(os.environ,MU300_SYSROOT=str(self.root),MU300_RUN=str(self.root/'run'),MU300_BIN=str(self.bin),PATH=str(self.bin)+':'+os.environ['PATH']) + + def tearDown(self):self.tmp.cleanup() + + def stub(self,name,source): + p=self.bin/name;p.write_text(source);p.chmod(0o755);return p + + def zone(self,temp): + p=self.root/'sys/class/thermal/thermal_zone0';p.mkdir(parents=True,exist_ok=True) + (p/'temp').write_text(str(temp));(p/'trip_point_0_temp').write_text('85000') + + def round(self,temp,expected): + self.zone(temp) + p=subprocess.run(['ucode',str(SYSD),'--round'],env=self.env,capture_output=True,text=True,timeout=5) + self.assertEqual(p.returncode,0,p.stderr) + self.assertIn(f'next look in {expected} s',p.stderr) + + def test_adaptive_thermal_limits_alarm_and_read_error(self): + self.round(45000,25);self.round(10000,30);self.round(84000,5) + self.round(86000,5) + (self.root/'run/mu300/thermal-alarm').unlink() + (self.root/'sys/module/mu300_thermal').mkdir(parents=True) + self.round(45000,10) # No native binding: guard remains the policy owner. + p=self.root/'sys/class/thermal/thermal_zone0/temp';p.write_text('unavailable') + bad=subprocess.run(['ucode',str(SYSD),'--round'],env=self.env,capture_output=True,text=True,timeout=5) + self.assertNotEqual(bad.returncode,0) + + def test_led_deadline_does_not_fork_every_five_seconds(self): + helper=self.stub('keys','''#!/usr/bin/python3 +import ctypes,time +ctypes.CDLL(None).prctl(1,15) # Match the real helper's parent-death signal. +time.sleep(60) +''') + self.stub('mu300-led','''#!/usr/bin/python3 +import os,time +from pathlib import Path +root=Path(os.environ['MU300_SYSROOT']) +p=root/'run/mu300/led';p.mkdir(exist_ok=True) +with (root/'calls').open('a') as f:f.write('tick\\n') +now=int(float(Path('/proc/uptime').read_text().split()[0])) +(p/'.tick-hint').write_text('due '+str(now+600)+'\\nbattery -\\n') +''') + env=dict(self.env,MU300_KEYS_BIN=str(helper),MU300_SYSD_PARTS='led') + daemon=subprocess.Popen(['ucode',str(SYSD)],env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + try: + deadline=time.monotonic()+9 + while not (self.root/'calls').exists() and time.monotonic()