fix: fill upstream gaps and handle SIM state events

This commit is contained in:
kanoqwq committed 2026-10-16 19:53:44 +08:00
1 parent f59a2968f3
commit ab26e79e88
43 files changed
+3093 -59

No files matched your search

+7 -2
View File
@@ -74,9 +74,11 @@ def update_mu300(api, args, root):
root = Path(root)
gui = api.get('GUI')
execute, read_exact = api['ssh_exec'], api['ssh_read_exact']
if gui and not args.host:
raise ValueError('Enter the management address in the GUI / 请在图形界面填写管理地址')
host = args.host or input('Device IP / 设备 IP [192.168.77.1]: ').strip() or '192.168.77.1'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = args.host or input('Device IP / 设备 IP [192.168.77.1]: ').strip() or '192.168.77.1'
try:
client.connect(host, username='root', password=gui.password if gui else os.environ.get('MU300_SSH_PASSWORD') or getpass.getpass('SSH root password: '),
timeout=15, look_for_keys=False, allow_agent=False)
@@ -114,7 +116,10 @@ fi''').strip().splitlines()
module = api['module'](root)
newboot = api['boot'](root, module, mode, live, slot)
control = module.boot_control(live, slot)
api['confirm']('Update OpenWrt while preserving settings and disk size; then reboot / 保留配置及容量更新,完成后重启。')
if gui:
gui.ctx.boundary()
else:
api['confirm']('Update OpenWrt while preserving settings and disk size; then reboot / 保留配置及容量更新,完成后重启。')
# Stage on disk, never upload a complete rootfs to the device's tmpfs.
destination = '/mnt/mu300-disk/.mu300-desktop-'+secrets.token_hex(6)
execute(client, 'mkdir -m 700 '+destination)
+82
View File
@@ -0,0 +1,82 @@
# 2026-10-16 更新日志:MU300 / F50 / V50 / U30 Air
本页汇总北京时间 2026 年 10 月 16 日的仓库更改,包含当天已有提交和本次提交。
U30 Air 的电池、灯和 PD 功能按机型隔离,不套用到无电池的 F50/V50。
## U30 Air 电量、充电与省电
- 修复合法电量保存值被误判并按电压重算的问题,减少重启后百分比跳变;保存寄存器恢复原厂读改写方式。
- 满电判断使用真实充电器状态及本机原厂电压/电流阈值,移除推测性的强制满电条件,不强制重设电池数据。
- 补齐充电器、电量计和 PD 控制器的电池板识别:F50/V50 不进入 U30 Air 的电池管理路径,覆盖主、备用芯片地址。
- 按原厂配置启用空闲停表、高精度定时器和 menu 空闲调度,保留 HZ=250 与业务轮询频率。不移植无屏机器不存在的相机、显示电源域。
- 修复 SIPC 调试节点重复注册及失败清理,避免多 IPC 子设备重复创建同名节点。
- 补齐看门狗在系统挂起时停表、恢复时按原运行状态重装计数的处理,不开启额外的整机睡眠策略。
## U30 Air 灯、网页及 USB 扩展坞
- 修复 SIM 卡管理页面说明与默认上网卡之间的间距。
- 默认管理地址统一为 `192.168.77.1`,配套脚本默认地址一并调整。
- 网络灯按 4G 蓝、5G 白、无服务红显示;Wi-Fi 灯按 2.4 GHz 蓝、5 GHz 白显示。
- 电池充电改用蓝色硬件呼吸,充满白色;低电量未充电时红色闪烁。加快呼吸节奏并延长峰值保持。
- 外部供电期间保留用户启用的灯;拔电后恢复自动熄灯,修复电量计状态滞后导致电池灯继续亮的问题。
- 灯控操作串行处理,避免电源事件与自动熄灯互相覆盖;网页 LED 设置匹配实际硬件能力。
- 接入 UMP9620 PD/Type-C 控制器,分离 USB 数据角色和供电角色,支持带 PD 供电的扩展坞边充电边使用 USB 外设。
- 修复插线初始状态、PD 接收帧清理及卸载顺序;支持 5 V,未加入高压 PPS。
- 用户已确认手动切主机模式后扩展坞可用且能充电;自动切主机未确认成功,仍保留手动操作。
## 蜂窝恢复、双卡与无卡等待
- 无覆盖后恢复注册时,通过既有 AT 通道的注册事件通知原拨号流程继续,不新增周期 AT 查询或第二套拨号服务。
- 保留手动断网及 autostart=false;U30 原生双卡初始化、预拨号回放和射频切换顺序保持原有逻辑。
- 接入原厂 ECIND SIM 状态事件,经对应卡槽的现有 AT 通道确认状态;无卡后停止无效的注册等待及短信存储查询,插卡后恢复原初始化。
- 区分 SIM 未上电和真正无卡,避免 U30 关卡电源时返回的 CME 10 被错误缓存,阻止下次启动。
- 首次打开 AT 节点遇到 ENODEV 时进行有界重试;首次成功不额外等待,成功的描述符保留使用。
- U30 在数据已手动关闭时重复选择同一张卡,不再等待 IP;切卡失败及回退保留断网状态。
- F50/V50 切上网卡同样尊重手动断网;迁移明确选择卡 2 的旧配置,避免配置与串口布局不一致。不会将所有 F50 强制识别为双卡。
## Wi-Fi 与驱动可靠性
- 不可用 DFS 信道回退到 36 信道时保持 80 MHz,不自动缩小带宽。
- 热点客户端列表增加按已关联 MAC 的 hostapd 回退;未知速率不伪造,不用整接口指标冒充单个客户端。
- 补齐 Wi-Fi 命令被阻止时的回复长度清零和客户端信息结构初始化,避免读取旧数据;保留现有 WPA3 与发送队列修复。
- SIPA 接收线程启动前先启用 runtime PM,线程启动失败则撤销,修复初始化竞态;不增加基带握手等待。
## 安装、更新与日常工具
- 新安装默认 root 密码设为 `root`;更新沿用原有账号保留流程,不覆盖用户已设置的密码。
- 默认内置 ttyd、luci-app-ttyd 及翻译,可在网页进入终端并使用登录认证。
- 普通更新及 Android 安装/更新路径保留用户计划任务 `/etc/crontabs`。
- 构建时移除预置 HTTPS 私钥,打包检查拒绝私钥;仅针对已知上游共享密钥执行一次性清理,用户自建密钥不动。
- 修复 F2FS 缩容检查可能等待不可见输入的问题,补充真实进程状态、读写量和检查输出,失败不继续修改分区表。
- 安装器二进制读取、备份及校验不再经过有损文本处理,增加进度、诊断与设备身份检查。
- 临时启动识别兼容不同版本已安装内核;仅备份、校验并修改 misc,不挂载根分区,不依赖安装包内核哈希完全相同。
- 修复旧隐藏额外空间安装方式被桌面更新拒绝的问题,校验实际布局和容量后调用原更新流程,保留设置及容量。
- 图形界面统一由最终计划确认,不再在日志内索要 yes;缺少参数时明确停止,避免后台读控制协议输入而卡住。
- 增加无线 ADB 操作入口、重启等待及离线帮助;补齐 Apple Silicon macOS 原生构建、工具与打包流程。
- 提供 Windows 安装器独立修补包,可替换宿主程序而不重下固件;保留原固件校验并支持重复应用。
- Docker 保留内核运行支持,不预装 Docker、Xray、sing-box 或其他 VPN 引擎。
## 上游核对与维护
- 扫描上游 main、issue 和 PR,已有等价或更新实现的修复不重复导入;直接修正原入口,避免旧方案与新方案长期叠加。
- 已有的广电名称映射、企业微信转发校验、eMMC 有序寄存器访问等通过回归核对,不重新覆盖。
- 未采用上游较早的电量强制写寄存器方案,也未引入另一套实验性 WPA3、完整安装器或数千个无关内核模块。
- 新增原厂对照及新机型适配清单,记录电池板隔离、AT 顺序、内核模块配套部署和验证边界。
## 验证与交付状态
- 今天较早的 U30 Air 灯、PD、电量及省电修复已部署,用户确认过灯与手动主机扩展坞功能;后续空闲管理、网络、热点、USB 和模块匹配检查通过。
- 最后一轮上游补漏及 SIM 事件处理完成源码、回归与相关模块编译,没有自动部署到实机,也没有重新生成包含这些最后改动的完整 MU 安装包。
- Wi-Fi、SIPA 模块及看门狗对象分别在 6.18.54、7.2.8 编译通过;注册/SIM 事件完成实际 OpenWrt ucode 和 ubus 夹具验证。
- 本次提交前,Windows 安装器测试运行 123 项,通过 119 项,跳过 4 项;另有 AT 打开、双卡、配置迁移、短信、密钥清理和真实 C 函数回归。
- 安装器旧包更新及补丁测试使用模拟传输,没有把夹具成功写成设备更新成功。
- TR3000 弱供电启动、特定 F50 内置卡无信号、欠压冷启动、完整充放电及真实移动失去覆盖后的恢复,仍需对应硬件实测;不宣称所有相关报告已彻底解决。
## 详细说明
- [U30 Air 灯控](U30AIR-LEDS-20261016.zh-CN.md)
- [U30 Air PD 扩展坞](U30AIR-PD-DOCK-20261016.zh-CN.md)
- [原厂电量、省电与恢复](U30AIR-STOCK-CHARGE-20261016.zh-CN.md)
- [上游核对、采用项与未采用项](UPSTREAM-AUDIT-20261016.zh-CN.md)
- [新机型适配清单](NEW-DEVICE-STOCK-ADAPTATION.zh-CN.md)
- [安装器验证记录](../installer/VERIFICATION.md)
+11
View File
@@ -72,8 +72,18 @@ MU 公共恢复逻辑适用于现有 mu300cell 框架;没有把 ModemManager
状态按 2026-10-16 本次工作记录,不覆盖此前用户已经完成的其他机型测试。
## 正常启动与联网时序约束
普通启动不增加固定等待、额外 AT 查询或重复射频初始化。恢复只在明确失败时进入,
一次成功打开的 SIPC 描述符继续持有,不能为探测可用性先开关一次。
锁回放仍在既有 pre-dial 窗口;新机型不能以降低存储速率、轮询频率来替代定位。
## 构建与部署规则
先按行为核对已合入的修复;已经覆盖的上游改动只记录来源,不重复叠补丁。
确认有缺口时直接修现有执行路径,不并行保留新旧两套策略作兜底。
必要的旧配置迁移只在迁移入口执行,完成后以当前配置为唯一来源。
1. 公共修复放共享构建入口,板级能力放 profile/DT 判断,避免只热改实机。
2. 同时检查干净构建和缓存源码的补丁应用。对串口、短信、双卡和拨号顺序运行已有回归。
3. 内核、BTF、initramfs 模块、根文件系统模块必须来自同一构建。
@@ -113,6 +123,7 @@ python3 openwrt/tests/wifi-hostapd-clients.py
## 详细记录
- [上游逐项核对、补缺及 SIM 事件要求](UPSTREAM-AUDIT-20261016.zh-CN.md)
- [U30 原厂电量、空闲省电与注册恢复](U30AIR-STOCK-CHARGE-20261016.zh-CN.md)
- [U30 上游适配与验证记录](U30AIR-UPSTREAM-20261015.zh-CN.md)
- [V50 板级适配记录](V50-MU3351-20261014.zh-CN.md)
File diff suppressed because it is too large. Load diff
+93
View File
@@ -0,0 +1,93 @@
# MU300 上游扫描与适配(2026-10-16)
上游基线:[main 2c13e7bb](https://github.com/dikeckaan/mu300-linux/commit/2c13e7bb5227055561363c5a8150350e9a518058)。
扫描获取了 main 的 1162 条提交元数据、60 个 issue 和 205 个 PR;
另保存当前 main 相对本分支的提交标题,并按当前架构核对相关实现。
原始快照在被忽略的 `work/upstream-audit-20261016/`;本页与旁边的 JSON 索引保留可提交记录。
这是功能/缺陷适用性扫描,不等于对 205 个 PR 的每一行代码做了安全审计。
上游审查部分只改 MU300 仓库;后续追加的 SIM 事件要求在两仓库分别实现。
E5 仓库另行后台编译 E5/M8/T551M。
已有等价或更新实现的内容不重复导入。下面列出的缺口均修改现有处理入口,
不另外启动一套拨号、AT owner 或硬件恢复服务;旧配置仅做首次迁移,当前配置随后为唯一来源。
普通启动、RIL 握手、已有 AT 归属、预拨号锁回放与 CGACT/CGCONTRDP/CGDATA 顺序不增加固定等待,
不新增正常启动 AT 查询;不以关闭 HS400、全局禁止 eMMC 休眠、预装 Docker/VPN 来掩盖问题。
## 用户指定的问题
| 来源 | 结论及本轮处理 |
| --- | --- |
| [#225 / PR #232](https://github.com/dikeckaan/mu300-linux/issues/225) F50 路由器 USB 口重启 | 已有 0016 与新增于上一轮的 0019 覆盖。后者在 vendor BQ、FGU、PD 首次硬件操作前检查本板启用的 charger_policy_service,覆盖主地址与备用地址;不重复导入同一补丁。不能采用已被上游放弃的“part=0 就拒绝”,真实 SGM41513 的 part 可为 0。没有在本轮假装复测 TR3000。 |
| [#231](https://github.com/dikeckaan/mu300-linux/issues/231) 广电大小写翻译 | 当前 common.js 已将国内运营商名去空格/横线/下划线并转大写映射;新增 CHINA BROADNET、China Broadnet、china_broadnet、CHN-BG 及国外运营商原样保留回归。不覆盖已有三语言实现。 |
| [#259](https://github.com/dikeckaan/mu300-linux/issues/259) 企业微信 Webhook | 当前编辑器已有企业微信独立预设(msgtype/text/content)、errcode=0,后端按 JSON 标量校验;与上游旧页面不同。实际 OpenWrt 隔离测试验证,无真实短信或外部发送。修正旧测试夹具与公共电池发现库的接口,不改变业务配置。 |
| [#253](https://github.com/dikeckaan/mu300-linux/issues/253) U30 缺电后的冷启动无模组 | 没有可直接证明本报告根因的日志或上游确定修复。保留已有 SIPC sbuf-ready 入口;补“节点存在但首次 open 返回 ENODEV”有界重试。成功描述符始终保留,不在线重启 AT owner,不自动循环 SFUN。不能把这写成所有欠压冷启动已实测解决。 |
| [#226](https://github.com/dikeckaan/mu300-linux/issues/226) AT 服务冷启动失败 | 既有节点等待之外,补首次 open 失败重试和有效 stderr;正常第一次 open 成功不运行 date/sleep。URC 首次 open 同样处理,成功后 EOF 仍不重开。issue 后续已明确报告 eMMC HS400ES -84、无 mmcblk0;此时固件不存在,AT 等待不能修复存储。既有 ordered MMIO / DLL phase 修复保留,不凭报告统一禁用高速模式。 |
| [#194](https://github.com/dikeckaan/mu300-linux/issues/194) 内置卡可识别却不能用 | U30 native 双卡已接入,不再使用上游旧的“仅 F50 支持 slot1”限制。F50 本分支已按卡槽寻址并在 PDP 前选择/回读 SPSWDATA、使用 sipa_eth8。本轮补当前 data_sim 未设置时,旧 network.wan.sim_slot=1 的首次迁移,以及明确选择 data_sim=1 却仍 sim_slots=1 的能力迁移;在 AT owner 布局建立前执行。不会把所有 F50 强制变成双卡。具体额外预制命令、混刷基带/锁频段及特定内置卡的注册问题,仍需要该硬件证据,不能伪称已全部修好。 |
## 从其他 PR / main 补入的缺口
- [PR #260](https://github.com/dikeckaan/mu300-linux/pull/260):
U30 同槽选择在数据手动关闭时不等待 IP;各失败/回退路径保留断网标记。
F50/V50 普通数据卡切换同样尊重 netifd autostart=false,避免主动关网后被切卡打开。
已选择但无套餐/信号的卡仍允许保留,不能把“选卡”变成强制外网连通性测试。
- [PR #263](https://github.com/dikeckaan/mu300-linux/pull/263):
本分支已经修过命令锁返回值与 EBUSY,本轮补两个 blocked 窗口回复长度清零,
get_station 回复结构初始化,防止未发送/短回复带出旧栈字节。
保留已有 WPA3 和发送队列修复,不导入另一套实验性 SAE 配置或强制退回 WPA2。
- [PR #230](https://github.com/dikeckaan/mu300-linux/pull/230):
mu300-update 与 Android 安装/更新路径均保留 /etc/crontabs。
桌面更新继续调用同一库;真实 apply_one 的隔离夹具确认用户计划任务保留。
- [PR #264](https://github.com/dikeckaan/mu300-linux/pull/264):
镜像构建移除 uhttpd key/crt,发布审计拒绝私钥;
导入上游已发布私钥的 SHA-256 名单及一次性迁移,仅删除匹配的已知共享密钥,
自建密钥不动。检查到本地六份历史/基础归档均没有该 key,
不能把上游已发布包的影响范围直接宣称成我方全部旧包受影响。
- 上游 main 的 SIPA 初始化顺序:
runtime PM 在启动可能立即收到 ENABLE 的 delegate 线程前启用,
启动失败撤销 enable;不增加等待,也不改变基带 AT 握手。
- 上游 UMP9620 watchdog 系统挂起修复:
仅 system suspend_noirq 保存运行状态并停表,resume_noirq 重装计数并恢复;
不开启新的整机睡眠策略、不改变运行时喂狗、正常启动超时或 radio 时序。
本地增加寄存器读取失败返回,未知状态不能被当作已停表。
## 没有照搬的内容
| 来源 | 原因 |
| --- | --- |
| PR #261 电量保存 | 已有 shutdown 保存及后续原厂 masked RMW 修正。上游此 PR 仍沿用早期 force-write 版本,不能覆盖本分支的实机依据。 |
| PR #256 / #258 全量模块、Docker | 现有 KVM/Docker 内核依赖已通过本分支检查,xt_nat 等已包含。不为同步而升全部内核/加入三千余模块,更不预装 Docker/VPN 引擎。 |
| PR #237 / #257 实验 SAE 路线 | 本分支有经用户验证的 WPA3 实现,保留其流程。上游关于 PMK 关联 IE 来源的疑问需要单独验证,既不宣称已排除,也不因未证实疑问砍掉功能。 |
| PR #248 漫游开关 | 是新用户策略/API,不是修复已有回归;本分支 APN 字段与其 roaming 含义不同,且其退出码 4 与本地双卡异常码冲突。本轮不直接 cherry-pick 整套拨号脚本或新增轮询,避免改变已测试握手。 |
| PR #224 / #266 完整 lossless-update/增量硬链接更新 | 更新布局、清单、回滚与桌面后端与本分支不同;先补确认缺失的 crontabs,不用上游旧安装器替换现有 Tauri、独立分区和安全检查。 |
| PR #265 镜像源回退、#244 网页设备管理 | 新功能和不同宿主安装器,不覆盖现有实现;不混入本轮硬件修复。 |
| issue #229、5.4 专用补丁 | 按此前用户范围,不继续维护/编译 5.4。 |
| issue #220/#170 无 CP / 早期硬挂、#54 USB3、#188 T780、#202 VPN | 不把 DMA 警告、mbox 日志当作已证实原因;保留已有权限/驱动排序修复。其他 SoC、接口硬件能力及 VPN 模块并非本轮可凭报告直接修好的项目。 |
## 验证与限制
另按本轮追加要求补入 SIM 状态事件:现有 URC owner 筛选原厂 ECIND type 3,
已有恢复服务经对应卡槽 AT owner 确认 CPIN。只缓存明确的无卡/ready/locked,
不把 timeout、busy、另一槽或无作用域 CPIN 当成无卡。
U30 的 SIM 未上电也会返回 CME 10,故还核对现有上电事务;明确关电后撤销空卡结论,
避免缓存阻止下次正常上电。事件确认也不早于 SMMSWAP、预拨号回放与 native 切卡序列。
确认无卡后 netifd 等待可用性事件,短信服务停止空卡查询和 SIM 存储操作;
插卡后仍走原拨号/短信初始化,不增加正常启动 AT 查询或另外一套守护服务。
没有关闭整颗 CP 或强制改变 U30 native 双卡的 RF 管理顺序。
硬件不提供插拔通知时不能假装支持热插拔;尤其 native RF 混合状态的已知安全限制仍保留。
E5 仓库的原厂二进制证据和边界记录于 `docs/SIM-EVENTS-20261016.zh-CN.md`。
- 首次 open 的真实 shell 行为分别在 dash、bash、BusyBox ash 验证:
立即成功不读时钟、不 sleep;首次失败后保留成功 FD;永久失败按预算退出。
- F50/V50 选卡、U30 native 切卡、同槽手动断网、平台配置迁移及正常默认值分别回归。
- 上游 TLS 指纹迁移测试验证仅删除匹配项,个人密钥与空文件保留。
- 实际 OpenWrt jshn/ucode 夹具验证短信转发与服务成功响应,传输均为本地 stub。
- SIPA 初始化及 watchdog 挂起函数使用真实 C 函数抽取编译、假硬件测试,
不是只匹配源码关键字。
- Wi-Fi(WCN 依赖与 sprd_wlan_combo)、SIPA sprd_modem 模块、watchdog 对象
分别在 6.18.54、7.2.8 编译通过。没有把对象/模块验证说成已完成新的 MU 全量发布包。
- 本轮相关回归通过:AT 首次 open 3、选卡 7、双卡上电 5、平台迁移 8、
U30 热切换 34、TLS 密钥迁移 9、真实 C 电源回调 2;注册 7、移动性 15、
静态 11、SIM 事件 5、作用域 5、短信容量 11。
OpenWrt ucode 的注册/SIM 策略 37 项及实际 ubus 订阅测试通过。
- 本轮没有向连接设备自动刷入这些 MU 修复,没有切卡、发短信或改写 NV;
软件及构建验证不替代特定 F50 内置卡、TR3000、欠压后冷启动的实物复测。
+14
View File
@@ -79,6 +79,10 @@ class Adapter:
self.ctx = context
self.legacy = load(self.root / 'OpenWrt-Installer.py', '_installer_' + secrets.token_hex(4))
self.legacy.GUI = self
# Older package helpers may still implement a terminal confirmation.
# Bind confirmation to the coordinator; never read its NDJSON stdin.
self.legacy.confirm = self.confirm_legacy
self.legacy.input = self.console_input_unavailable
if self.kind == 'e5':
self.legacy.B, self.legacy.F, self.legacy.SCRIPTS = str(self.root), str(self.root/'files'), str(self.root/'scripts')
# Old compatible package scripts must not retain their exact-hash
@@ -107,6 +111,15 @@ class Adapter:
lambda:original(android, *args, **kwargs), output=False)
self.legacy.Android.call = observed
def confirm_legacy(self, *_args, **_kwargs):
if not self.ctx or self.legacy.GUI is not self:
raise RecoveryRequired('GUI confirmation context is unavailable / 图形界面确认上下文不可用,已停止')
self.ctx.boundary()
return True
def console_input_unavailable(self, *_args, **_kwargs):
raise RecoveryRequired('A required GUI option is missing; console input is unavailable / 缺少必要的图形界面参数,已停止;请返回安装计划检查选项')
def stage(self, stage, status='running', **details):
if self.ctx:
self.ctx.stage(stage, status, **details)
@@ -484,6 +497,7 @@ class Adapter:
def update_e5(self, args):
helper = load(self.root/'scripts/tools/e5-update.py', '_update')
helper.GUI = self
helper.input = self.console_input_unavailable
raw_size, raw_hash = self.legacy.gz_metadata(str(self.root/'files/openwrt.ext4.gz'))
previous = sys.argv
try:
+7 -2
View File
@@ -74,9 +74,11 @@ def update_mu300(api, args, root):
root = Path(root)
gui = api.get('GUI')
execute, read_exact = api['ssh_exec'], api['ssh_read_exact']
if gui and not args.host:
raise ValueError('Enter the management address in the GUI / 请在图形界面填写管理地址')
host = args.host or input('Device IP / 设备 IP [192.168.77.1]: ').strip() or '192.168.77.1'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = args.host or input('Device IP / 设备 IP [192.168.77.1]: ').strip() or '192.168.77.1'
try:
client.connect(host, username='root', password=gui.password if gui else os.environ.get('MU300_SSH_PASSWORD') or getpass.getpass('SSH root password: '),
timeout=15, look_for_keys=False, allow_agent=False)
@@ -114,7 +116,10 @@ fi''').strip().splitlines()
module = api['module'](root)
newboot = api['boot'](root, module, mode, live, slot)
control = module.boot_control(live, slot)
api['confirm']('Update OpenWrt while preserving settings and disk size; then reboot / 保留配置及容量更新,完成后重启。')
if gui:
gui.ctx.boundary()
else:
api['confirm']('Update OpenWrt while preserving settings and disk size; then reboot / 保留配置及容量更新,完成后重启。')
# Stage on disk, never upload a complete rootfs to the device's tmpfs.
destination = '/mnt/mu300-disk/.mu300-desktop-'+secrets.token_hex(6)
execute(client, 'mkdir -m 700 '+destination)
+2
View File
@@ -51,6 +51,8 @@ def build_patch(destination, artifact=None):
它修复旧版隐藏额外空间安装被 legacy 检查拒绝的问题。
无需重新分区、重装或清空 Android。请保留原包全部载荷、子目录和备份。
Mac 版本未更新。补丁不会连接或操作设备。
图形界面无需在日志输入 yes,只需确认页面上的最终安装计划。
更新 OpenWrt 不会格式化 Android userdata;首次安装需要重置时,以确认页面的数据影响为准。
若提示校验失败,停止并保留完整提示;不要跳过校验或改选首次分区安装。
Close the installer. Extract every ZIP member over the original package, run
+18 -2
View File
@@ -8,6 +8,8 @@ import sys
def child(package):
from contextlib import nullcontext, redirect_stdout
import hashlib
import builtins
import getpass
import io
import struct
import tempfile
@@ -30,6 +32,11 @@ def child(package):
struct.pack_into('<I',live,28,zlib.crc32(live[:28]))
key=hashlib.sha256(b'frozen-only-test-key').hexdigest()
original_client=paramiko.SSHClient
original_input=builtins.input
original_getpass=getpass.getpass
def no_console(*args,**kwargs):raise AssertionError('GUI attempted console input')
builtins.input=no_console
getpass.getpass=no_console
results=[]
try:
for mode in ('legacy','sd','part','data-image'):
@@ -39,6 +46,10 @@ def child(package):
record=store.create(meta,{'serial':'ssh:'+key,'cid':'a'*32,'ssh_key':key},
{'method':'update','host':'192.168.78.1'}, {'method':'update','openwrt_bytes':capacity})
adapter=Adapter(meta,Context(store,record,lambda *_:None));adapter.password='fixture-only'
prompt_output=io.StringIO()
with redirect_stdout(prompt_output):
assert adapter.legacy.confirm('Userdata will be formatted and Android reset') is True
assert prompt_output.getvalue()==''
events=[];uploads={};probes=[]
channel=SimpleNamespace(recv_exit_status=lambda:0)
public_key=SimpleNamespace(asbytes=lambda:b'frozen-only-test-key')
@@ -62,6 +73,7 @@ def child(package):
adapter.legacy.payload_rootfs=lambda _:nullcontext(archive)
def obsolete(*args,**kwargs):raise AssertionError('Old package update gate executed')
adapter.legacy.update=obsolete
adapter.legacy.confirm=no_console
# The real package boot repacker executes; only transport and
# the uploaded rootfs fixture are replaced. No device opens.
with redirect_stdout(io.StringIO()):adapter.execute()
@@ -73,10 +85,14 @@ def child(package):
assert record['update_layout']['offset']==offset
else:assert not probes
results.append(mode)
finally:paramiko.SSHClient=original_client
finally:
paramiko.SSHClient=original_client
builtins.input=original_input
getpass.getpass=original_getpass
print(json.dumps({'package':package.name,'kernel':meta['kernel'],'frozen_backend':True,
'modes':results,'real_package_boot_repacker':True,'old_gate_bypassed':True,
'original_capacity':capacity,'hardware_access':False}))
'original_capacity':capacity,'gui_console_input_blocked':True,
'gui_confirmation_no_output':True,'hardware_access':False}))
if __name__=='__main__':
+87
View File
@@ -0,0 +1,87 @@
"""GUI compatibility helpers cannot consume the NDJSON pipe as terminal input."""
import io
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import Mock, patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from backend.adapter import Adapter, debug_output
from backend.state import Cancelled, Context, RecoveryRequired, Store
from backend.service import Service
LEGACY = '''GUI = None
class Android:
def call(self, *args, **kwargs): pass
def adb(*args, **kwargs): pass
def confirm(message, word='yes'):
print(message)
return input('Type yes to continue / 输入 yes 继续: ').strip() == word
def missing_option():
return input('A missing required option: ')
'''
class GuiConfirmation(unittest.TestCase):
def setUp(self):
self.temp=tempfile.TemporaryDirectory();self.addCleanup(self.temp.cleanup)
self.root=Path(self.temp.name)
(self.root/'OpenWrt-Installer.py').write_text(LEGACY,encoding='utf-8')
self.store=Store(self.root/'state')
self.record=self.store.create({}, {}, {'method':'part'}, {'method':'part','wipe':True})
self.record['status']='running'
self.events=[]
self.ctx=Context(self.store,self.record,lambda k,d:self.events.append((k,d)))
def adapter(self,kind,context=True):
return Adapter({'path':str(self.root),'adapter':kind}, self.ctx if context else None)
def test_old_gui_confirm_never_prints_or_reads_yes_for_both_adapters(self):
for kind in ('e5','mu300'):
with self.subTest(adapter=kind):
adapter=self.adapter(kind)
with patch('builtins.input',side_effect=AssertionError('Unexpected terminal input')),debug_output(self.ctx):
self.assertTrue(adapter.legacy.confirm('Userdata will be formatted and Android reset'))
self.assertEqual(self.events,[])
self.assertFalse((self.ctx.directory/'debug.ndjson').exists())
self.assertTrue(self.record['plan']['wipe'])
self.assertFalse(self.record['effects'])
def test_unstructured_option_stops_without_printing_a_console_prompt(self):
adapter=self.adapter('mu300')
with patch('builtins.input',side_effect=AssertionError('Unexpected terminal input')),debug_output(self.ctx):
with self.assertRaisesRegex(RecoveryRequired,'required GUI option'):
adapter.legacy.missing_option()
self.assertEqual(self.events,[])
def test_confirmation_cannot_bypass_cancel_or_a_missing_gui_context(self):
adapter=self.adapter('mu300')
self.ctx.cancel=True
with self.assertRaises(Cancelled):adapter.legacy.confirm('message')
self.ctx.cancel=False
adapter.legacy.GUI=None
with self.assertRaises(RecoveryRequired):adapter.legacy.confirm('message')
with self.assertRaises(RecoveryRequired):self.adapter('e5',context=False).legacy.confirm('message')
def test_plain_cli_retains_its_own_typed_confirmation(self):
from backend.adapter import load
cli=load(self.root/'OpenWrt-Installer.py','plain_cli_confirmation_fixture')
with patch('builtins.input',return_value='yes') as read,patch('sys.stdout',io.StringIO()):
self.assertTrue(cli.confirm('CLI destructive warning'))
read.assert_called_once()
with patch('builtins.input',return_value='no'),patch('sys.stdout',io.StringIO()):
self.assertFalse(cli.confirm('CLI destructive warning'))
def test_gui_final_confirmation_is_still_required_before_starting_worker(self):
service=Service(self.root,self.store,io.StringIO())
service.adapters=Mock(side_effect=AssertionError('Unconfirmed plan reached installation'))
with patch('backend.service.inspect_package',return_value={}):
with self.assertRaisesRegex(ValueError,'Confirm the displayed plan'):
service.dispatch({'protocol':1,'command':'start','params':{'transaction':self.record['id'],'confirmed':False}})
service.adapters.assert_not_called()
self.assertIsNone(service.worker)
self.assertFalse(self.store.load(self.record['id'])['effects'])
if __name__=='__main__':unittest.main()
@@ -0,0 +1,36 @@
[
{
"package": "mu300-openwrt-6.18.54-20261016-pd-win-macos",
"kernel": "6.18",
"frozen_backend": true,
"modes": [
"legacy",
"sd",
"part",
"data-image"
],
"real_package_boot_repacker": true,
"old_gate_bypassed": true,
"original_capacity": 34779168768,
"gui_console_input_blocked": true,
"gui_confirmation_no_output": true,
"hardware_access": false
},
{
"package": "mu300-openwrt-7.2.8-20261016-pd-win-macos",
"kernel": "7.2",
"frozen_backend": true,
"modes": [
"legacy",
"sd",
"part",
"data-image"
],
"real_package_boot_repacker": true,
"old_gate_bypassed": true,
"original_capacity": 34779168768,
"gui_console_input_blocked": true,
"gui_confirmation_no_output": true,
"hardware_access": false
}
]
@@ -0,0 +1,22 @@
[
{
"package": "mu300-openwrt-6.18.54-20261016-pd-win-macos",
"kernel": "6.18",
"real_frozen_patcher": true,
"repeat_apply": true,
"cli_package_check": true,
"ndjson_package_check": true,
"firmware_payloads_unchanged": true,
"hardware_access": false
},
{
"package": "mu300-openwrt-7.2.8-20261016-pd-win-macos",
"kernel": "7.2",
"real_frozen_patcher": true,
"repeat_apply": true,
"cli_package_check": true,
"ndjson_package_check": true,
"firmware_payloads_unchanged": true,
"hardware_access": false
}
]
@@ -0,0 +1,22 @@
[
{
"package": "mu300-openwrt-6.18.54-20261016-pd-win-macos",
"kernel": "6.18",
"real_frozen_patcher": true,
"repeat_apply": true,
"cli_package_check": true,
"ndjson_package_check": true,
"firmware_payloads_unchanged": true,
"hardware_access": false
},
{
"package": "mu300-openwrt-7.2.8-20261016-pd-win-macos",
"kernel": "7.2",
"real_frozen_patcher": true,
"repeat_apply": true,
"cli_package_check": true,
"ndjson_package_check": true,
"firmware_payloads_unchanged": true,
"hardware_access": false
}
]
+4
View File
@@ -191,6 +191,7 @@ chroot "$R" /bin/sh -c "command -v flock >/dev/null" || { echo "missing native S
chmod 0755 $R/etc/hotplug.d/power_supply/70-mu300-led
chmod 0755 $R/opt/mu300/bin/mu300-platform-config
chmod 0755 $R/opt/mu300/bin/mu300-network-recovery $R/etc/init.d/mu300-network-recovery
chmod 0755 $R/etc/uci-defaults/92-mu300-uhttpd-key
chmod 0755 $R/opt/mu300/bin/v50-led-status
chmod 0755 $R/opt/mu300/bin/openwrt-board-check
chmod 0755 $R/opt/mu300/bin/ra-deprecate $R/opt/mu300/bin/wcn-reopen
@@ -259,6 +260,9 @@ printf "%s\n" "${MU300_VERSION:-dev}" > $R/etc/mu300/image-version
(MU300_LIB=1; . $R/opt/mu300/bin/mu300-update; upk_manual $R openwrt) > $R/etc/mu300/image-packages
[ -s $R/etc/mu300/image-packages ] || { echo "missing image-packages" >&2; exit 1; }
# --- default-root-password begin ---
# PR #264: uhttpd creates a pair on the device, never in a shared image.
rm -f $R/etc/uhttpd.key $R/etc/uhttpd.crt
[ ! -e $R/etc/uhttpd.key ] || { echo "the image holds a TLS key" >&2; exit 1; }
# Fresh installs use root/root; account merging preserves passwords on updates.
root_hash="\$6\$mu300root\$O/wH3K.NhG6ZZOMSOTLlNNHv08B1RRcRsec0Xc54SuqhFhgPwmQUnxo782srY03f5mYk.Gv0qJ8JGfcrJvYKs."
grep -q "^root:" "$R/etc/shadow" || { echo "missing root account" >&2; exit 1; }
@@ -0,0 +1,73 @@
#!/bin/sh
# The web server's TLS key that the releases shipped (FINDINGS 132). Every OpenWrt and OpenWrt-LuCI image from
# v2026.10.13 to v2026.10.16.1 carried /etc/uhttpd.key, one key per image and the same on every device that installed
# it; anyone who downloads the release has that key, so LuCI over HTTPS could be impersonated. The image build no
# longer puts one in (build-rootfs.sh). This takes a shipped key away on the devices: a key file that is byte for byte
# one of them goes, with its certificate, and uhttpd makes the device its own pair when it starts (it does whenever
# the pair is missing; px5g, an EC P-256 key). A key that is not on the list - one the device made, one the user put
# there - is never touched.
#
# uci-defaults run at boot before uhttpd starts, and the image brings this file again with every update (mu300-update,
# the Magisk zip, the computer's installer: each carries /etc over, and a shipped key with it where the old image is
# not known), so the check runs on the first boot of each image; it removes itself when it ran, as uci-defaults do.
# By hand on a running system (the file is gone after the first boot: take it from the repository):
# "sh 92-mu300-uhttpd-key; /etc/init.d/uhttpd restart". The browser warns once about the new self-signed certificate;
# LuCI over plain HTTP is not affected.
#
# The list: sha256 of etc/uhttpd.key in each published mu300-openwrt-rootfs.tar.gz and mu300-openwrt-luci-rootfs.tar.gz
# (the releases before v2026.10.13 had none), "sha256 release image". Fingerprints only, never a key.
shipped='
0523f54e5501011c84224ee7167cae5032d45962f960a37332bb5b2fdf95a0ba v2026.10.16.1 openwrt-luci
ad78a3f7bd4ac1407e5b5c70075f028c85398853df07e40597d05ceb36cb5a84 v2026.10.16.1 openwrt
1c30ffe55dd7f8fe0f97a509f63fe6a6855066e9acd16357a5c0aa09bff74b20 v2026.10.27 openwrt-luci
83232d512bc55a76b146958a96480cc9602d30a6afa2af050ef855bb7b76d738 v2026.10.27 openwrt
0d4c888a25bc9b7b6d69bd0d7eb0a89a830f1f47da598eb9ab04ff4dd5d968f7 v2026.10.26 openwrt-luci
965ff7db1242cd613bb0b152860ab706164f5a5e5f51edeaf7a04a0b23bea84a v2026.10.26 openwrt
b5ff6d08b976ac6ef0998fd1a469c6e6e72b03cbcb859b7361ebc43251e94e13 v2026.10.25 openwrt-luci
bde402c813981f769183d35163af944f6222c3ccd5f763ce2b3f8010c5d017a4 v2026.10.25 openwrt
3a9d4c39f65f95ccfc39972eae50eeeabdd644f1cb90a22384bf9cf5b0b184a7 v2026.10.24 openwrt-luci
ec44aabecb80cda658813e7a59890cbc1de84cd810a759ca20d2b8b6edadaeaf v2026.10.24 openwrt
7ff399f8757b30d4f41dcb5990379b92c8a864bbae88f43775eefd3fe2eb8992 v2026.10.23 openwrt-luci
7ce9056850a2af01a9ac826d081efb46081212b4733c0c72107b990099c8992b v2026.10.23 openwrt
a7491095077fb7c88fe4b0c50fc6c20f9d0a9b880c8803a63522e2ba41da209c v2026.10.22 openwrt-luci
b34c7bcbcff383e57e875b12f841ba2ddfb6907f38e755139add69ceb7b75d20 v2026.10.22 openwrt
3214f5ff679de9d42dad8102d8049ca13c3a6ca7760cbdbcccd19dbfafa6d97f v2026.10.21 openwrt-luci
0911613bc77475b8d18640001d0cdeb5b8f4841cd5d532c43761ee55ea7cadf9 v2026.10.21 openwrt
388add2e4a19a05ac24f14a7fe4ab08c18e4ab06f7c86ef4cf2ade61a9d4fd8d v2026.10.20 openwrt-luci
250988bd1e20d997145d9a183a5a70f1bdb5fd1bc943657f43a719caaf6ecf96 v2026.10.20 openwrt
609e9da2e694ba030dcfa4fa024c89a755e24580a324a734996b79c4013bd13c v2026.10.19 openwrt-luci
826829aea5733d6bdd8abd89b79b09e43a80151004a5239210b70c68f9415f92 v2026.10.19 openwrt
f71bb0342692ae86ed4878d245bb829f35f933241f6fd254d3e9aeeff3c77deb v2026.10.18 openwrt-luci
e676bbf12ff9044cea6d6d002cc0721dd39272d6c661fc5c76ee45caed58b1c2 v2026.10.18 openwrt
dcf46bf77a3b137f6cd70760452f78903af3ba10aec6bc945c57ab0bb1462e78 v2026.10.17 openwrt-luci
37f6b4d30cd104366105520aee14ad7b8ff07351fb30062eeededfc854570b29 v2026.10.17 openwrt
1d750c8ab73247951e8a4130290db2c32b24a3585cb10609337e10a274ea57d6 v2026.10.16 openwrt-luci
4c712ea908419f8f31ebc82172aba97c4051bd0dd3eb5e475cb602439134478d v2026.10.16 openwrt
5ba3f0ab0a48e887e62a06595d4140f9bfd936fc312306923ce080ceb9a0f491 v2026.10.15 openwrt-luci
33ebd4993c3c5d5e5c9b58c4fbb5a66cef5c8cf9212a89b9df80d56882ae8052 v2026.10.15 openwrt
c570687f4698d712cd30e6dfe98358c99b11336a033f842775bb5f920a4643d4 v2026.10.14 openwrt-luci
591c4569f59ac3832f9606ad155371d9cdb1d6ccc9aa7fa0a502ac37ca2d8c09 v2026.10.14 openwrt
e400ea9c4efc4a0947a294e0d76890f8cfe40b795df7567c8d0abaf916ffd197 v2026.10.13 openwrt-luci
ac8f6431ef5f178a482ecd6bd69bbda2a95f65b5f1e80a88be1b414c55066a51 v2026.10.13 openwrt
'
# KEY CERT: KEY goes, with CERT, when it is one of the shipped keys
drop_shipped() {
[ -f "$1" ] || return 0
sum=$(sha256sum "$1" 2>/dev/null) || return 0
sum=${sum%% *}
case $sum in ''|*[!0-9a-f]*) return 0 ;; esac
printf '%s\n' "$shipped" | grep -q "^$sum " || return 0
rm -f "$1" "$2"
logger -t mu300 "removed the TLS key a release shipped ($1) and its certificate: uhttpd makes the device its own" 2>/dev/null
return 0
}
drop_shipped /etc/uhttpd.key /etc/uhttpd.crt
# and wherever an instance of uhttpd takes its key from
for sec in $(uci -q show uhttpd 2>/dev/null | sed -n "s/^uhttpd\.\([A-Za-z0-9_]*\)\.key=.*/\1/p"); do
key=$(uci -q get "uhttpd.$sec.key")
crt=$(uci -q get "uhttpd.$sec.cert")
[ -z "$key" ] || drop_shipped "$key" "${crt:-/etc/uhttpd.crt}"
done
exit 0
@@ -62,11 +62,12 @@ proto_mu300cell_setup() {
proto_block_restart "$config"
return 1
fi
if [ "$rc" = 5 ]; then
if [ "$rc" = 5 ] || [ "$rc" = 6 ]; then
# Out of PS coverage is transient. Keep autostart and wait for the
# existing owner's registration event, rather than blocking restart.
printf '%s\n' "$slot" > "/run/mu300cell-$config.registration-wait"
proto_notify_error "$config" REGISTRATION_WAIT
if [ "$rc" = 6 ]; then proto_notify_error "$config" SIM_MISSING
else proto_notify_error "$config" REGISTRATION_WAIT; fi
proto_set_available "$config" 0
return 1
fi
@@ -13,6 +13,7 @@ const root = getenv('MU300_REGISTRATION_DIR') || '/run/mu300-registration';
const cfg = uci.cursor();
const runtime = '/run/mu300';
const previous = { key: null, attempted: false };
const sim_changes = {};
function read_json(path) {
try { return json(fs.readfile(path)); } catch (e) { return null; }
}
@@ -22,28 +23,52 @@ function selected_slot() {
let value = native || cfg.get('unisoc_modem', 'main', 'data_sim') || '0';
return value == '0' ? 0 : value == '1' ? 1 : null;
}
function blocked() {
function radio_busy() {
for (let path in [
runtime + '/sim-switching', runtime + '/sim-active-unknown',
'/run/unisoc-data-sim-switch',
'/run/mu300-mobile-data-manual-down'
'/run/unisoc-modem-early-hook-pending'
])
if (fs.stat(path)) return true;
return policy.radio_blocked(!!fs.stat('/run/mu300-radio-freeze'),
!!fs.stat(runtime + '/sim-radio-ready'));
}
function blocked() {
return radio_busy() || !!fs.stat('/run/mu300-mobile-data-manual-down');
}
uloop.init();
const bus = ubus.connect(null, 2);
if (!bus) die('Cellular recovery: ubus unavailable\n');
function evaluate() {
// Only an actual stock SIM-change event queues CPIN. The persistent AT
// broker records its confirmed result before exposing the reply.
// Never queue CPIN ahead of the original SMMSWAP/radio/lock sequence.
// Retain hints while that sequence or a native SIM switch owns the CP.
let initialized = !!fs.stat('/run/mu300-ril-handshake') || !!fs.stat(runtime + '/sim-radio-ready');
for (let changed in initialized && !radio_busy() ? keys(sim_changes) : []) {
delete sim_changes[changed];
let directory = changed == '1' ? '/run/mu300-at4' : '/run/mu300-at';
let command = sprintf("MU300_AT_DIR=%s MU300_AT_DAEMON_ONLY=1 MU300_AT_BUDGET=6 /opt/mu300/bin/mu300-at -t 3 'AT+SPACTCARD=%s;+CPIN?' 2>/dev/null", directory, changed);
let pipe = fs.popen(command, 'r');
if (pipe) { pipe.read('all'); pipe.close(); }
}
cfg.unload('unisoc_modem');
let slot = selected_slot();
if (slot == null) return;
let wait = trim(fs.readfile('/run/mu300cell-' + wan + '.registration-wait') || '');
let wait_slot = wait == '0' ? 0 : wait == '1' ? 1 : null;
let sim = read_json(root + '/sim' + slot + '.json');
// A late CPIN completion must not turn a deliberately powered-off SIM
// into a physical-removal verdict and block its next power-on.
if (sim?.state == 'absent' && !fs.stat(root + '/sim-power' + slot)) sim = null;
policy.recovery(
(method, data) => bus.call('network.interface.' + wan, method, data),
read_json(root + '/slot' + slot + '.json'), wait_slot, slot, blocked(), previous
(method, data) => {
if (method == 'notify_proto' && data.available === false)
fs.writefile('/run/mu300cell-' + wan + '.registration-wait', '' + slot + '\n');
return bus.call('network.interface.' + wan, method, data);
},
read_json(root + '/slot' + slot + '.json'), wait_slot, slot, blocked(), previous,
sim
);
}
// The short one-shot only coalesces event bursts. No timer runs while idle.
@@ -56,10 +81,17 @@ function schedule() {
if (!pending) { pending = true; deferred.set(50); }
}
const registration = bus.listener('mu300.registration', (name, data) => schedule());
const sim_state = bus.listener('mu300.sim-state', (name, data) => schedule());
const sim_change = bus.listener('mu300.sim-change', (name, data) => {
if (data?.slot === 0 || data?.slot === 1) {
sim_changes['' + data.slot] = true;
schedule();
}
});
const network = bus.listener('network.interface', (name, data) => {
if (data?.interface == wan) schedule();
});
if (!registration || !network) die('Cellular recovery: event subscription failed\n');
if (!registration || !network || !sim_state || !sim_change) die('Cellular recovery: event subscription failed\n');
const term = uloop.signal(15, () => uloop.end());
const intr = uloop.signal(2, () => uloop.end());
evaluate();
@@ -21,18 +21,30 @@ export function can_resume(status, wait_slot, selected, blocked) {
status.available !== false || wait_slot !== selected)
return false;
for (let error in status.errors ?? [])
if (error.code != 'REGISTRATION_WAIT')
if (error.code != 'REGISTRATION_WAIT' && error.code != 'SIM_MISSING')
return false;
return true;
};
export function recovery(call, state, wait_slot, selected, blocked, previous) {
export function recovery(call, state, wait_slot, selected, blocked, previous, sim) {
let status = call('status', {});
let same_sim = type(sim) == 'object' && sim.slot === selected;
if (same_sim && sim.state == 'absent') {
previous.key = null; previous.attempted = false;
// Stop setup/renew attempts without overriding a user's ifdown or
// cycling RF. The modem remains able to receive insertion events.
if (!blocked && status?.proto == 'mu300cell' && status.autostart === true && status.available !== false)
return call('notify_proto', { action: 5, available: false }) != null;
return false;
}
let key = registration_key(state, selected);
for (let error in status?.errors ?? [])
if (error.code == 'SIM_MISSING' && same_sim && sim.state == 'ready')
key = sprintf('sim:%d:ready', selected);
if (key != previous.key) {
previous.key = key;
previous.attempted = false;
}
let status = call('status', {});
if (status?.up === true)
previous.attempted = false;
if (key == null || previous.attempted ||
+10 -1
View File
@@ -517,6 +517,7 @@ wait_registered() {
start=$((size + 1))
while [ "$SECONDS" -lt "$deadline" ]; do
[ ! -e /run/mu300-mobile-data-down ] || return 1
if command -v mu300_sim_absent >/dev/null 2>&1 && mu300_sim_absent "$MU300_SIM_SLOT"; then return 6; fi
size=$(wc -c < "$urclog" 2>/dev/null || echo 0)
# start points ONE byte beyond the previous end, so size == start-1
# is an unchanged log, not truncation (which would replay old URCs).
@@ -669,6 +670,9 @@ up_locked() {
modem_stack || { echo "no modem stack in this kernel ($(uname -r))" >&2; exit 3; }
rm -f /run/mu300-mobile-data-down /run/mu300-mobile-data-manual-down
tty_setup
if command -v mu300_sim_absent >/dev/null 2>&1 && mu300_sim_absent "$MU300_SIM_SLOT"; then
echo 'SIM absent; waiting for card state event' >&2; return 6
fi
radio_on || return $?
if [ "$DEVICE" = u30air ] && [ "$MU300_SIM_SLOT" = 0 ] && [ ! -e /run/mu300-radio-freeze ] && [ -e /etc/mu300/sim-data-route-2 ]; then
current=$(at 'AT+SPSWDATA?' 4 | tr -d '\r' | sed -n 's/^+SPSWDATA: *\([01]\) *$/\1/p' | head -n1) || current=
@@ -698,7 +702,12 @@ up_locked() {
# Android's RIL enables the IMS bearer used by SMS. This is idempotent;
# keep it on the normal radio bring-up path and do not wait for IMS here.
at 'AT+CAVIMS=1' 5 >/dev/null || true
wait_registered || { echo "not registered on the network" >&2; exit 5; }
local registration_rc=0
wait_registered || registration_rc=$?
if [ "$registration_rc" != 0 ]; then
[ "$registration_rc" != 6 ] || { echo 'SIM absent; waiting for card state event' >&2; return 6; }
echo "not registered on the network" >&2; exit 5
fi
mark dial-registered
radio_say "注册完成"
+33 -5
View File
@@ -77,12 +77,24 @@ mkfifo -m 600 "$CMD"
# the one open that everything else borrows
open_tty() {
exec 3<&- 2>/dev/null || true
exec 3<>"$DEV" || return 1
exec 3<&- || true
# command suppresses exec redirection's fatal-special-builtin behavior in
# ash/dash. A failed FIRST open is retryable; a successful open is retained.
command exec 3<>"$DEV" || return 1
# on fd 3, not "stty -F $DEV": the -F form opens and closes the tty a second time
stty raw -echo <&3 2>/dev/null || true
}
open_tty || { echo "mu300-atd: cannot open $DEV" >&2; exit 1; }
if ! open_tty; then
echo "mu300-atd: $DEV exists but is not usable; waiting for first open" >&2
first_open_end=$(( $(date +%s) + ${MU300_AT_INITIAL_WAIT:-30} ))
until open_tty; do
[ "$(date +%s)" -lt "$first_open_end" ] || {
echo "mu300-atd: $DEV never became usable; check CP firmware and eMMC availability" >&2
exit 1
}
sleep 1
done
fi
# Keep the other AT channels drained, the way Android's RIL does - it holds nr0-nr5 open and reads all six.
# /dev/stty_nr0 carries the modem's unsolicited output (+SIND, +ECIND, +SPERRLOG, ...), and each stty_nr<n> is
@@ -138,9 +150,19 @@ for n in ${MU300_AT_URC_CHANNELS-0}; do
: > "$log"
# A new owner must not inherit a registered cache from a dead CP.
case "$n" in
0|3) rm -f "${MU300_REGISTRATION_DIR:-/run/mu300-registration}/slot$((n / 3)).json" ;;
0|3) rm -f "${MU300_REGISTRATION_DIR:-/run/mu300-registration}/slot$((n / 3)).json" \
"${MU300_REGISTRATION_DIR:-/run/mu300-registration}/sim$((n / 3)).json" \
"${MU300_REGISTRATION_DIR:-/run/mu300-registration}/sim-power$((n / 3))" ;;
esac
exec 4< "$other" || exit 1
# A late URC channel must also survive ENODEV on its first open. Never
# probe with a separate open/close or reopen a successful descriptor.
if ! command exec 4< "$other"; then
urc_open_end=$(( $(date +%s) + ${MU300_AT_INITIAL_WAIT:-30} ))
until command exec 4< "$other"; do
[ "$(date +%s)" -lt "$urc_open_end" ] || exit 1
sleep 1
done
fi
# $$ remains the parent's PID in ash subshells. Read our actual PID
# without forking so a dead drainer cannot pass the readiness check.
read -r reader_pid reader_stat < /proc/self/stat
@@ -156,6 +178,9 @@ for n in ${MU300_AT_URC_CHANNELS-0}; do
/opt/mu300/bin/led-status sim-status "$((n / 3))" "$urc" >/dev/null 2>&1 ;;
esac
case "$n:$urc" in
0:+ECIND:*|3:+ECIND:*)
! command -v mu300_sim_changed >/dev/null 2>&1 ||
mu300_sim_changed "$((n / 3))" "$urc" ;;
0:+CEREG:*|3:+CEREG:*)
! command -v mu300_registration_save >/dev/null 2>&1 ||
mu300_registration_save "$((n / 3))" "$urc" ;;
@@ -283,6 +308,9 @@ while :; do
else
silent=0
fi
# A bare CPIN has no reliable card identity: SPACTCARD can stick on this
# channel. Only explicitly addressed transactions enter the SIM cache.
! command -v mu300_sim_reply >/dev/null 2>&1 || mu300_sim_reply "$cmd" "$reply"
if [ -n "$answer" ]; then
# write it complete, then move it into place, so the client never reads half an answer
printf '%s\n' "$reply" > "$answer.part" 2>/dev/null && mv "$answer.part" "$answer" 2>/dev/null
+6 -2
View File
@@ -82,7 +82,7 @@ apply)
exit 0
fi
at_slot "$target" 'AT+CPIN?' | grep -q '^+CPIN: READY' || { echo sim_not_ready >&2; exit 1; }
status=$(net_status); was_up=$(field up); was_pending=$(field pending)
status=$(net_status); was_up=$(field up); was_pending=$(field pending); was_autostart=$(field autostart)
restore_original() {
ifdown "$wan"; wait_down || return 1
select_card "$current" || return 1
@@ -102,7 +102,11 @@ apply)
# An unpaid/no-signal SIM can be selected. netifd may attach later; its
# asynchronous registration result must never undo the user's choice.
if select_card "$target" && save_card "$target"; then
ifup "$wan" || logger -t mu300-data-sim 'Data SIM selected; netifd start failed'
# An explicit ifdown/data-cap action remains off after selection.
# Existing autostart intent includes a WAN waiting for registration.
if [ "$was_autostart" != false ]; then
ifup "$wan" || logger -t mu300-data-sim 'Data SIM selected; netifd start failed'
fi
exit 0
fi
# Only selection/readback/storage failures restore the previous choice.
@@ -6,6 +6,21 @@ device=$(mu300-device 2>/dev/null)
case $device in v50|u30air) slots=2 ;; f50) slots=1 ;; *) exit 1 ;; esac
[ "$(uci -q get unisoc_modem.main)" = core ] || exit 0
previous=$(uci -q get unisoc_modem.main.platform_defaults)
# Restore a positively selected internal F50 SIM before the AT owner layout
# is fixed. Ordinary single-SIM F50 boots get no additional modem commands.
if [ "$device" = f50 ] && { [ -z "$previous" ] || [ "$previous" = f50 ]; }; then
selected=$(uci -q get unisoc_modem.main.data_sim)
if [ -z "$previous" ] && [ "$selected" != 0 ] && [ "$selected" != 1 ]; then
legacy=$(uci -q get network.wan.sim_slot)
if [ "$legacy" = 1 ]; then
uci -q set unisoc_modem.main.data_sim=1 || exit 1
selected=1
fi
fi
if [ "$selected" = 1 ] && [ "$(uci -q get unisoc_modem.main.sim_slots)" != 2 ]; then
uci -q set unisoc_modem.main.sim_slots=2 && uci -q commit unisoc_modem || exit 1
fi
fi
if [ "$previous" = "$device" ]; then
# Upgrade existing U30 profiles once; never reset APNs or the selected card.
[ "$device" = u30air ] && [ "$(uci -q get unisoc_modem.main.u30_native_version)" != 1 ] || exit 0
+7 -6
View File
@@ -304,10 +304,12 @@ live_switch() {
available || { fail 'Persistent dual-SIM brokers unavailable; reboot first'; return 1; }
[ ! -e /run/mu300-mobile-data.suspend ] || { fail 'Resume the modem before switching'; return 1; }
[ ! -d /run/unisoc-modem-lock-apply ] || { fail 'Network locks are being applied'; return 1; }
# Decide before the same-slot path too: data deliberately off needs no IP.
if sim_wan_held_down; then held_down=1; fi
if [ "$old" = "$target" ]; then
wan_wait || { atomic "$R/sim-result" no_data; fail 'Active SIM has no data; use default for next-boot selection'; return 1; }
[ "$held_down" = 1 ] || wan_wait || { atomic "$R/sim-result" no_data; fail 'Active SIM has no data; use default for next-boot selection'; return 1; }
sim_cfg_save_default "$target" || return 1
sim_seen_add "$target" || true
[ "$held_down" = 1 ] || sim_seen_add "$target" || true
atomic "$R/sim-result" switched
rm -f "$FALLBACK"; status; return 0
fi
@@ -318,7 +320,6 @@ live_switch() {
refusal=$(preflight "$target") || { fail "$refusal"; return 1; }
# Did the card in use have data? It decides what a target without data means, below.
if wan_up; then had_data=1; fi
if sim_wan_held_down; then held_down=1; fi
# Prevent new dial/watch rounds before netifd cancels the old protocol task.
: > "$R/sim-switching"
atomic "$R/sim-result" switching
@@ -339,14 +340,14 @@ live_switch() {
if [ "$rc" = 75 ]; then
# nothing was sent: the radio lock or the AT channel stayed busy. The previous card is as it was.
atomic "$R/sim-result" failed
rm -f "$R/sim-switching" /run/mu300-mobile-data-down
rm -f "$R/sim-switching"
[ "$held_down" = 1 ] || ifup "$sim_wan" || true
fail 'The modem is busy; nothing was changed, try again'; return 1
fi
if [ "$rc" != 0 ]; then
if roll_back "$old"; then
atomic "$R/sim-result" rolled_back
rm -f "$R/sim-switching" /run/mu300-mobile-data-down
rm -f "$R/sim-switching"
if [ "$held_down" != 1 ]; then
ifup "$sim_wan" || { fail 'Previous SIM restored but WAN could not be started'; return 1; }
fi
@@ -357,7 +358,7 @@ live_switch() {
# The target card is up: let netifd dial it, and keep the boot default where it was until the bearer is
# there. The published slot is this boot's; the saved one is tomorrow's.
publish "$target"
rm -f "$R/sim-switching" /run/mu300-mobile-data-down
rm -f "$R/sim-switching"
atomic "$R/sim-phase" waiting_for_data
if [ "$held_down" = 1 ]; then
sim_cfg_save_default "$target" || { atomic "$R/sim-result" failed; fail storage_failed; return 1; }
+38 -18
View File
@@ -25,6 +25,10 @@ SYNC_INTERVAL=${MU300_SMS_SYNC_INTERVAL:-300}
SMS=${MU300_SMS_BIN:-$(command -v mu300-sms 2>/dev/null || echo /opt/mu300/bin/mu300-sms)}
DIRECT_FLAG=${MU300_SMS_DIRECT_FLAG:-/run/mu300-sms-direct}
SPOOL=$POOL/incoming
REGISTRATION_LIB=${MU300_REGISTRATION_LIB:-/opt/mu300/lib/registration.sh}
[ ! -r "$REGISTRATION_LIB" ] || . "$REGISTRATION_LIB"
sim_absent() { command -v mu300_sim_absent >/dev/null 2>&1 && mu300_sim_absent "${MU300_SIM_SLOT:-0}"; }
sim_ready() { command -v mu300_sim_is >/dev/null 2>&1 && mu300_sim_is "${MU300_SIM_SLOT:-0}" ready; }
# A channel is not a permanent SIM address. Select and execute atomically,
# including CNMI setup and CNMA acknowledgements (not only archive/send).
@@ -60,31 +64,37 @@ until [ -p "$ATDIR/cmd" ]; do
sleep 5
done
# the SIM needs its time after a boot (mobile-data waits 15 s for it); poll for READY, but a
# modem that never answers still gets its periodic sync attempts in the main loop below
# A starting/busy SIM can need time, but a positively absent card is not busy.
# Stop the existing readiness retries on absence; ECIND/CPIN cache updates
# enable setup later through the same receiver, without another polling AT task.
n=0
until sms_at 4 'AT+CPIN?' 2>/dev/null | grep -q READY; do
until sim_absent || sms_at 4 'AT+CPIN?' 2>/dev/null | grep -q READY; do
sim_absent && break
n=$((n + 1))
[ "$n" -gt 60 ] && { echo "mu300-smsd: SIM never became ready, syncing anyway" >&2; break; }
sleep 10
done
at_ok() { sms_at 5 "$1" 2>/dev/null | grep -qx OK; }
rm -f "$DIRECT_FLAG"
# Import anything already on SIM before enabling direct delivery. If direct
# routing is rejected, the old +CMTI/periodic-sync path remains functional.
at_ok 'AT+CNMI=2,1,0,0,0' || true
"$SMS" archive-sim || {
echo "mu300-smsd: PDU archive incomplete; attempting read-only legacy import" >&2
"$SMS" sync || true
}
if at_ok 'AT+CMGF=0' && at_ok 'AT+CSMS=1' &&
at_ok 'AT+CNMI=3,2,2,1,1'; then
: > "$DIRECT_FLAG"
echo "mu300-smsd: direct +CMT delivery enabled" >&2
else
setup_sms() {
rm -f "$DIRECT_FLAG"
# Import anything already on SIM before enabling direct delivery. If direct
# routing is rejected, the old +CMTI/periodic-sync path remains functional.
at_ok 'AT+CNMI=2,1,0,0,0' || true
echo "mu300-smsd: direct delivery rejected; using SIM indications" >&2
fi
"$SMS" archive-sim || {
echo "mu300-smsd: PDU archive incomplete; attempting read-only legacy import" >&2
"$SMS" sync || true
}
if at_ok 'AT+CMGF=0' && at_ok 'AT+CSMS=1' &&
at_ok 'AT+CNMI=3,2,2,1,1'; then
: > "$DIRECT_FLAG"
echo "mu300-smsd: direct +CMT delivery enabled" >&2
else
at_ok 'AT+CNMI=2,1,0,0,0' || true
echo "mu300-smsd: direct delivery rejected; using SIM indications" >&2
fi
}
sim_configured=0
if ! sim_absent; then setup_sms; sim_configured=1; fi
process_spool() {
local f reply
@@ -120,6 +130,16 @@ elapsed=0
echo "mu300-smsd: pooling into $POOL (poll ${POLL}s, full sync every ${SYNC_INTERVAL}s)" >&2
while :; do
sleep "$POLL"
if sim_absent; then
sim_configured=0
rm -f "$DIRECT_FLAG"
continue # no CPIN, CNMI, CMGL or CNMA against a known empty slot
fi
if [ "$sim_configured" = 0 ]; then
sim_ready || continue
setup_sms
sim_configured=1
fi
if process_spool; then
spool_failures=0
else
+1 -1
View File
@@ -157,7 +157,7 @@ check() {
keep_list() {
case $1 in
ubuntu) echo "etc/mu300 etc/ssh etc/hostname etc/localtime etc/timezone etc/fstab home root srv usr/local var/lib/bluetooth" ;;
openwrt) echo "etc/config etc/mu300 etc/unisoc-modem etc/dropbear etc/rc.local root" ;;
openwrt) echo "etc/config etc/mu300 etc/unisoc-modem etc/dropbear etc/rc.local etc/crontabs root" ;;
esac
}
# vendor files that the published images deliberately do not contain
@@ -2,6 +2,95 @@
# Passive cache of PS registration already received by the existing AT owner.
# No tty opens, AT commands, SIM identity, cell location or persistent writes.
# Stock onSimStatusChanged() treats these ECIND values as a request to read
# CPIN. They do NOT prove removal: SIM errors and PIN changes also use them.
mu300_sim_changed() {
local slot=$1 line=$2 type value cause extra
case "$slot:$line" in 0:+ECIND:*|1:+ECIND:*) ;; *) return 0 ;; esac
case "$line" in '+ECIND: 3,'*|'+ECIND:3,'*) ;; *) return 0 ;; esac
line=${line#*:}
line=$(printf '%s' "$line" | tr -d ' \r\t')
IFS=, read -r type value cause extra <<EOF
$line
EOF
[ "$type" = 3 ] && [ -z "$extra" ] || return 0
case "$value:$cause" in
0:|2:|100:|4:|0:[0-9]*|2:[0-9]*|100:[0-9]*|4:[0-9]*|1:2|1:34|1:25|1:1|1:7) ;;
*) return 0 ;;
esac
case "$cause" in *[!0-9]*) return 0 ;; esac
( ubus -t 1 send mu300.sim-change "{\"slot\":$slot}" ) \
3<&- 4<&- </dev/null >/dev/null 2>&1 &
}
mu300_sim_save() {
local slot=$1 state=$2 old= value tmp
local root=${MU300_REGISTRATION_DIR:-/run/mu300-registration}
case "$slot:$state" in 0:absent|1:absent|0:ready|1:ready|0:locked|1:locked) ;; *) return 0 ;; esac
value="{\"slot\":$slot,\"state\":\"$state\"}"
[ ! -f "$root/sim$slot.json" ] || IFS= read -r old < "$root/sim$slot.json" || true
[ "$value" != "$old" ] || return 0
mkdir -p "$root" || return 0
tmp="$root/.sim$slot.$$"
(umask 077; printf '%s\n' "$value" > "$tmp") &&
mv -f "$tmp" "$root/sim$slot.json" || { rm -f "$tmp"; return 0; }
( ubus -t 1 send mu300.sim-state "{\"slot\":$slot}" ) \
3<&- 4<&- </dev/null >/dev/null 2>&1 &
return 0
}
# Observe existing scoped SIM power/CPIN transactions, including the cold
# plan and dashboard reads. No additional normal-boot queries are introduced.
mu300_sim_reply() {
local command=$1 reply=$2 slot line state= root=${MU300_REGISTRATION_DIR:-/run/mu300-registration}
case "$command" in
'AT+SPACTCARD=0;'*) slot=0; command=${command#*;} ;;
'AT+SPACTCARD=1;'*) slot=1; command=${command#*;} ;;
*) return 0 ;;
esac
case "$command" in +CPIN\?|+SFUN=2|+SFUN=3|+SFUN=4|+CFUN=0|+CFUN\?) ;; *) return 0 ;; esac
while IFS= read -r line; do
line=${line%"$(printf '\r')"}
case "$line" in
'+CFUN: 1') state=powered ;;
'+CPIN: READY') state=ready ;;
'+CPIN: SIM PIN'|'+CPIN: SIM PUK'|'+CPIN: SIM PIN2'|'+CPIN: SIM PUK2'|'+CPIN: PH-'*) state=locked ;;
'+CPIN: NOT INSERTED'|'+CPIN: SIM NOT INSERTED') state=absent ;;
'+CME ERROR: 10'|'+CME ERROR: SIM not inserted')
# U30 returns CME 10 for a physically inserted but powered-off
# SIM too. Never use that to prevent its normal RF startup.
[ "$command" != '+CPIN?' ] || [ ! -f "$root/sim-power$slot" ] || mu300_sim_save "$slot" absent
return 0 ;;
OK)
case "$command:$state" in
+SFUN=2:*|+SFUN=4:*|+CFUN\?:powered)
mkdir -p "$root" && : > "$root/sim-power$slot" ;;
+SFUN=3:*|+CFUN=0:*)
rm -f "$root/sim-power$slot" "$root/sim$slot.json" ;;
+CPIN\?:ready|+CPIN\?:locked|+CPIN\?:absent)
[ "$state" != absent ] || [ -f "$root/sim-power$slot" ] || return 0
mkdir -p "$root" && : > "$root/sim-power$slot"
mu300_sim_save "$slot" "$state" ;;
esac
return 0 ;;
esac
done <<EOF
$reply
EOF
# Busy, timeout, ERROR and an incomplete response retain the known state.
return 0
}
mu300_sim_is() {
local state= root=${MU300_REGISTRATION_DIR:-/run/mu300-registration}
case "$1" in 0|1) ;; *) return 1 ;; esac
[ -f "$root/sim$1.json" ] && IFS= read -r state < "$root/sim$1.json" || return 1
[ "$state" = "{\"slot\":$1,\"state\":\"$2\"}" ]
}
mu300_sim_absent() {
[ -f "${MU300_REGISTRATION_DIR:-/run/mu300-registration}/sim-power$1" ] && mu300_sim_is "$1" absent
}
mu300_registration_save() {
local slot=$1 line=$2 kind=${3:-urc} body stat rat a b c d e rest
local root=${MU300_REGISTRATION_DIR:-/run/mu300-registration} old= value tmp
+1
View File
@@ -92,6 +92,7 @@ expect_error '{"webhook_body":"{broken}"}'
expect_error '{"webhook_url":"https://{text}.example.com/hook"}'
expect_error '{"profile":"../../etc"}'
# A future battery device uses the shared profile even in independent mode.
BATTERY=$MU300_FORWARD_BATTERY
mkdir -p "$BATTERY"
printf '1\n' > "$BATTERY/present"; printf '50\n' > "$BATTERY/capacity"; printf 'Discharging\n' > "$BATTERY/status"
check_set '{"profile":"shared","mode":"per_sim","enabled":1,"method":"webhook","webhook_url":"https://power.example.com/hook","power_forward_enabled":1}'
+16
View File
@@ -1,6 +1,13 @@
#!/bin/sh
set -eu
mkdir -p /var/run /etc/config /run/mu300-registration
mkdir -p /opt/mu300/bin
cat > /opt/mu300/bin/mu300-at <<'EOF'
#!/bin/sh
printf '%s\n' "$MU300_AT_DIR:$*" >> /tmp/sim-event-at
printf '+CPIN: READY\nOK\n'
EOF
chmod +x /opt/mu300/bin/mu300-at
printf "config settings 'main'\n option data_sim '1'\n" > /etc/config/unisoc_modem
/sbin/ubusd &
bus_pid=$!
@@ -12,8 +19,17 @@ sleep 1
kill -0 "$pid" || { cat /tmp/recovery.log; exit 1; }
ubus send mu300.registration '{"slot":1}'
ubus send network.interface '{"interface":"wan","action":"ifdown"}'
ubus send mu300.sim-change '{"slot":1}'
ubus send mu300.sim-change '{"slot":"0;bad"}'
ubus send mu300.sim-state '{"slot":1}'
sleep 1
test ! -e /tmp/sim-event-at # initialization has not completed
touch /run/mu300-ril-handshake
ubus send mu300.sim-state '{"slot":1}'
sleep 1
kill -0 "$pid" || { cat /tmp/recovery.log; exit 1; }
grep -q '/run/mu300-at4:.*SPACTCARD=1;+CPIN?' /tmp/sim-event-at
test "$(wc -l < /tmp/sim-event-at)" = 1
kill -TERM "$pid"
wait "$pid"
test ! -s /tmp/recovery.log || { cat /tmp/recovery.log; exit 1; }
+21
View File
@@ -42,3 +42,24 @@ policy.recovery(call, {slot:1,stat:2,rat:7}, 1, 1, false, previous);
s = status();
check(policy.recovery(call, registered, 1, 1, false, previous), 'next registration resumes');
printf('PASS: %d recovery policy checks\n', count);
let absent = { slot: 1, state: 'absent' }, ready = { slot: 1, state: 'ready' };
let action = null;
function sim_call(method, payload) {
if (method == 'status') return s;
action = payload;
return {};
}
s = status(); s.available = true; s.pending = true;
check(policy.recovery(sim_call, registered, 1, 1, false, previous, absent), 'no SIM cancels registration');
check(action.action == 5 && action.available === false, 'availability only; no RF reset');
s.available = false; s.pending = false; s.errors = [{code:'SIM_MISSING'}];
action = null;
check(!policy.recovery(sim_call, registered, 1, 1, false, previous, absent) && action == null, 'absence does not loop');
check(policy.recovery(sim_call, null, 1, 1, false, previous, ready), 'inserted SIM resumes before registration');
check(!policy.recovery(sim_call, null, 1, 1, false, previous, ready), 'one resume per insertion');
s.autostart = false;
previous = {key:null,attempted:false};
check(!policy.recovery(sim_call, null, 1, 1, false, previous, ready), 'manual down remains off after insertion');
check(!policy.recovery(sim_call, null, 1, 1, false, previous, {slot:0,state:'ready'}), 'other slot does not resume');
printf('PASS: %d recovery and SIM policy checks\n', count);
+46
View File
@@ -0,0 +1,46 @@
"""Initial ENODEV is retryable; a working owner is never reopened to probe it."""
from helpers import ShellTest, BIN
class InitialOpen(ShellTest):
def initialization(self):
source=(BIN/'mu300-atd').read_text()
return source[source.index('open_tty() {'):source.index('\n# Keep the other AT channels')]
def test_ready_fast_path_never_waits_or_reads_clock(self):
for shell in self.each_shell():
code=self.initialization()+'''
printf ready >&3
'''
self.stub('stty', ':')
self.stub('sleep', 'exit 90')
self.stub('date', 'exit 91')
sink=self.tmp/'sink'
r=self.sh(shell, code, DEV=sink)
self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(sink.read_text(),'ready')
def test_failed_initial_open_survives_and_retains_the_first_success(self):
for shell in self.each_shell():
sink=self.tmp/'late/sink'
if sink.exists(): sink.unlink()
if sink.parent.exists(): sink.parent.rmdir()
code='''retries=0
sleep() { retries=$((retries+1)); mkdir -p "$STUBLOG/late"; }
stty() { :; }
'''+self.initialization()+'''
printf ready >&3
echo "retries=$retries"
'''
r=self.sh(shell,code,DEV=sink)
self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(sink.read_text(),'ready')
self.assertIn('retries=1',r.stdout)
self.assertIn('waiting for first open',r.stderr)
def test_permanent_failure_is_bounded_and_describes_storage_dependency(self):
for shell in self.each_shell():
self.stub('date', 'echo 100')
r=self.sh(shell,self.initialization(),DEV='/proc/mu300-invalid-tty',MU300_AT_INITIAL_WAIT=0)
self.assertNotEqual(r.returncode,0)
self.assertIn('check CP firmware and eMMC availability',r.stderr)
+19 -2
View File
@@ -34,7 +34,7 @@ if name=='uci':
elif a[:2]==['-q','commit'] and s.get('fail_commit'):
s['fail_commit']=False; save(); sys.exit(1)
elif name=='ubus':
print(json.dumps({'up':s['up'],'pending':False,'l3_device':'card'+str(s['actual'])}))
print(json.dumps({'up':s['up'],'pending':False,'autostart':s.get('autostart',True),'l3_device':'card'+str(s['actual'])}))
elif name=='ifdown':
if not s.get('stuck'): s['up']=False; save()
elif name=='ifup':
@@ -57,6 +57,12 @@ elif name=='jsonfilter':
self.stub(name,f'exec "{driver}" {name} "$@"')
self.stub('sleep', ':')
(self.tmp/'ready').touch()
# BusyBox ash can run ifdown/ifup as applets before consulting PATH.
# Keep all test network operations inside these explicit fixtures.
self.controller=self.tmp/'data-sim'
source=SCRIPT.read_text()
shims='\n'.join(name+'() { "$STUBLOG/stubs/'+name+'" "$@"; }' for name in ('ifdown','ifup','sleep'))
self.controller.write_text(source.replace('#!/bin/sh\n','#!/bin/sh\n'+shims+'\n',1))
self.extra=dict(MU300_SIM_ENV_LIB=self.envlib,MU300_SIM_MUTEX=self.tmp/'mutex',MU300_DUAL_READY=self.tmp/'ready',MU300_DATA_SIM_ACTUAL=self.tmp/'actual')
def reset(self, **values):
@@ -64,7 +70,7 @@ elif name=='jsonfilter':
(self.tmp/'commands').write_text('')
def run_switch(self,shell,target):
return self.script(shell,SCRIPT,'apply',target,**self.extra)
return self.script(shell,self.controller,'apply',target,**self.extra)
def test_same_card_never_disconnects(self):
for shell in self.each_shell():
@@ -84,6 +90,17 @@ elif name=='jsonfilter':
self.assertEqual((s['saved'],s['actual'],s['up']),(int(target),int(target),True))
self.assertFalse((self.tmp/'mutex').exists())
def test_manually_disabled_data_stays_off_on_other_card(self):
for shell in self.each_shell():
self.reset(autostart=False)
state=json.loads(self.db.read_text());state['up']=False
self.db.write_text(json.dumps(state))
r=self.run_switch(shell,'1')
self.assertEqual(r.returncode,0,r.stderr)
state=json.loads(self.db.read_text())
self.assertEqual((state['saved'],state['actual'],state['up']),(1,1,False))
self.assertNotIn('ifup',(self.tmp/'commands').read_text())
def test_failed_selection_restores_original(self):
for shell in self.each_shell():
self.reset(fail_switch=True)
+3
View File
@@ -112,6 +112,9 @@ lang = 'tr';
if (M.carrierName({name: '中国联通'}) !== 'China Unicom') throw Error('Turkish carrier name');
lang = 'zh';
if (M.carrierName({name: '中国联通'}) !== '中国联通') throw Error('Chinese carrier name');
for (const name of ['CHINA BROADNET','China Broadnet','china_broadnet','CHN-BG'])
if (M.carrierName({name}) !== '中国广电') throw Error('Broadnet case alias: '+name);
if (M.carrierName({name:'Unknown Foreign Carrier',plmn:'23410'}) !== 'Unknown Foreign Carrier') throw Error('Foreign carrier changed');
""")
def test_official_theme_bridge_keeps_aurora_intact(self):
+30
View File
@@ -13,6 +13,9 @@ if [ "$2" = get ]; then
unisoc_modem.main) echo core ;;
*.u30_native_version) echo "${TEST_NATIVE_VERSION:-1}" ;;
*.platform_defaults) echo "${TEST_DEFAULTS:-}" ;;
*.data_sim) echo "${TEST_DATA_SIM-0}" ;;
*.sim_slots) echo "${TEST_SLOTS:-1}" ;;
network.wan.sim_slot) echo "${TEST_LEGACY_SLOT:-}" ;;
esac
elif [ "$2" = batch ]; then cat > "$STUBLOG/batch"
elif [ "$2" = set ] || [ "$2" = commit ]; then echo "$*" >> "$STUBLOG/direct"; fi
@@ -33,6 +36,33 @@ elif [ "$2" = set ] || [ "$2" = commit ]; then echo "$*" >> "$STUBLOG/direct"; f
else:self.assertNotIn('sim_slots=',commands)
self.assertNotIn('data_sim=',commands)
def test_selected_f50_internal_card_enables_owners_before_boot(self):
for shell in self.each_shell():
direct=self.tmp/'direct';direct.unlink(missing_ok=True)
r=self.script(shell,SCRIPT,TEST_DEVICE='f50',TEST_DEFAULTS='f50',TEST_DATA_SIM='1')
self.assertEqual(r.returncode,0,r.stderr)
self.assertIn('sim_slots=2',direct.read_text())
self.assertNotIn('data_sim=',direct.read_text())
def test_legacy_f50_selection_migrates_only_before_current_board_defaults(self):
for shell in self.each_shell():
direct=self.tmp/'direct';direct.unlink(missing_ok=True)
r=self.script(shell,SCRIPT,TEST_DEVICE='f50',TEST_LEGACY_SLOT='1',TEST_DATA_SIM='')
self.assertEqual(r.returncode,0,r.stderr)
self.assertIn('data_sim=1',direct.read_text())
self.assertIn('sim_slots=2',direct.read_text())
direct.unlink()
r=self.script(shell,SCRIPT,TEST_DEVICE='f50',TEST_DEFAULTS='f50',TEST_LEGACY_SLOT='1')
self.assertEqual(r.returncode,0,r.stderr)
self.assertFalse(direct.exists())
def test_current_selection_wins_over_stale_legacy_setting(self):
for shell in self.each_shell():
direct=self.tmp/'direct';direct.unlink(missing_ok=True)
r=self.script(shell,SCRIPT,TEST_DEVICE='f50',TEST_LEGACY_SLOT='1',TEST_DATA_SIM='0')
self.assertEqual(r.returncode,0,r.stderr)
self.assertFalse(direct.exists())
def test_cross_board_restore_resets_only_adapter_configuration(self):
for shell in self.each_shell():
for device,marker,slots in [('f50','v50',1),('u30air','v50',2),('v50','f50',2),('f50','u30air',1)]:
+115
View File
@@ -0,0 +1,115 @@
"""Run SIM event/cache logic without serial devices or a running system ubus."""
import json
import shlex
from helpers import ShellTest, TOP
class SimEvents(ShellTest):
def setUp(self):
super().setUp()
self.library = TOP / 'rootfs/overlay/opt/mu300/lib/registration.sh'
self.stub('ubus', 'printf "%s\\n" "$*" >> "$STUBLOG/events"')
def test_stock_events_only_are_hints_not_absence(self):
for shell in self.each_shell():
events = self.tmp / 'events'
events.unlink(missing_ok=True)
source = '. ' + shlex.quote(str(self.library)) + '''
mu300_sim_changed 0 '+ECIND: 3,1,2'
mu300_sim_changed 1 '+ECIND: 3,2'
mu300_sim_changed 1 '+ECIND: 3,4'
mu300_sim_changed 0 '+ECIND: 3,100'
mu300_sim_changed 0 '+ECIND: 2,1,2'
mu300_sim_changed 0 '+ECIND: 3,1,99'
mu300_sim_changed 0 '+ECIND: 3,2junk'
mu300_sim_changed 0 '+ECIND: 3,1,2,7'
mu300_sim_changed 2 '+ECIND: 3,2'
wait
'''
cache = self.tmp / 'sim'
r = self.sh(shell, source, MU300_REGISTRATION_DIR=cache)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(len(events.read_text().splitlines()), 4)
self.assertFalse(cache.exists())
def test_confirmed_cpin_scopes_and_unknown_reply(self):
for shell in self.each_shell():
cache = self.tmp / 'sim'
source = '. ' + shlex.quote(str(self.library)) + '''
mu300_sim_reply 'AT+SPACTCARD=1;+CFUN?' '+CFUN: 1
OK'
mu300_sim_reply 'AT+SPACTCARD=1;+CPIN?' '+CME ERROR: 10'
mu300_sim_absent 1 || exit 91
mu300_sim_absent 0 && exit 92
mu300_sim_reply 'AT+SPACTCARD=1;+CPIN?' '+CME ERROR: 14'
mu300_sim_absent 1 || exit 93
mu300_sim_reply 'AT+SPACTCARD=1;+CPIN?' '+CPIN: READY'
mu300_sim_absent 1 || exit 94
mu300_sim_reply 'AT+SPACTCARD=0;+CPIN?' '+CPIN: SIM PIN
OK'
mu300_sim_reply 'AT+SPACTCARD=1;+CPIN?' '+CPIN: READY
OK'
mu300_sim_absent 1 && exit 95
mu300_sim_reply 'AT+CEREG?' '+CME ERROR: 10'
mu300_sim_reply 'AT+CPIN?' '+CME ERROR: 10'
wait
'''
r = self.sh(shell, source, MU300_REGISTRATION_DIR=cache)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(json.loads((cache/'sim0.json').read_text()), dict(slot=0, state='locked'))
self.assertEqual(json.loads((cache/'sim1.json').read_text()), dict(slot=1, state='ready'))
for file in cache.iterdir(): file.unlink()
def test_sim_power_off_is_not_physical_removal(self):
for shell in self.each_shell():
cache = self.tmp / 'power'
source = '. ' + shlex.quote(str(self.library)) + '''
mu300_sim_reply 'AT+SPACTCARD=0;+CPIN?' '+CME ERROR: 10'
mu300_sim_absent 0 && exit 90
mu300_sim_reply 'AT+SPACTCARD=0;+SFUN=2' 'OK'
mu300_sim_reply 'AT+SPACTCARD=0;+CPIN?' '+CME ERROR: 10'
mu300_sim_absent 0 || exit 91
mu300_sim_reply 'AT+SPACTCARD=0;+SFUN=3' 'OK'
mu300_sim_absent 0 && exit 92
mu300_sim_reply 'AT+SPACTCARD=0;+CPIN?' '+CME ERROR: 10'
mu300_sim_absent 0 && exit 93
mu300_sim_reply 'AT+SPACTCARD=0;+CPIN?' '+CPIN: READY
OK'
mu300_sim_is 0 ready || exit 94
wait
'''
r = self.sh(shell, source, MU300_REGISTRATION_DIR=cache)
self.assertEqual(r.returncode, 0, r.stderr)
for file in cache.iterdir(): file.unlink()
def test_known_absence_ends_registration_without_queries_or_sleep(self):
text = (TOP/'rootfs/overlay/opt/mu300/bin/mobile-data').read_text()
function = text[text.index('wait_registered() {'):text.index('\n# The modem needs')]
for shell in self.each_shell():
# mobile-data is bash; use bash for its SECONDS contract.
if 'bash' not in shell: continue
source = '''at() { exit 90; }
sleep() { exit 91; }
mu300_sim_absent() { return 0; }
''' + function + '\nwait_registered\n'
r = self.sh(shell, source, MU300_SIM_SLOT=0, MU300_SIM_URC=self.tmp/'unused')
self.assertEqual(r.returncode, 6, r.stderr)
def test_sms_known_absence_does_not_probe_or_initialize(self):
text = (TOP/'rootfs/overlay/opt/mu300/bin/mu300-smsd').read_text()
readiness = text[text.index('# A starting/busy SIM'):text.index('at_ok() {')]
gating = text[text.index(' if sim_absent; then', text.index('while :; do\n sleep')):
text.index(' if process_spool; then')]
for shell in self.each_shell():
code = '''sim_absent() { return 0; }
sms_at() { echo unexpected-query; exit 90; }
sleep() { echo unexpected-sleep; exit 91; }
''' + readiness + '''
setup_sms() { echo unexpected-setup; }
sim_ready() { return 1; }
sim_configured=1
for turn in 1 2 3; do
''' + gating + '\necho unexpected-poll\ndone\n[ "$sim_configured" = 0 ]\n'
result = self.sh(shell, code, DIRECT_FLAG=self.tmp/'flag')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, '')
+9
View File
@@ -493,11 +493,20 @@ esac""")
def test_deliberately_down_wan_stays_down_after_native_switch(self):
flag=self.run/'mu300-mobile-data-down';flag.touch()
r=self.ctl('switch','1',T_HELD_DOWN='1')
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
self.assertEqual((self.etc/'uci-slot').read_text(),'0\n')
self.assertNotIn('up',(self.tmp/'net').read_text().splitlines())
self.assertEqual(self.status()['active'],1)
self.assertTrue(flag.exists())
def test_same_card_manual_off_needs_no_address_or_at_command(self):
flag=self.run/'mu300-mobile-data-down';flag.touch()
r=self.ctl('switch','2',T_HELD_DOWN='1',T_WAN='0')
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
self.assertEqual(self.calls(),[])
self.assertTrue(flag.exists())
def test_teardown_must_acknowledge_before_radio_off(self):
self.stub('sleep', ':')
+150
View File
@@ -0,0 +1,150 @@
"""uci-defaults 92-mu300-uhttpd-key (FINDINGS 132): the TLS key pair the OpenWrt releases shipped goes, a key of the
user's stays. No real key is in the repository: the tests add the fingerprint of a scratch file to the list."""
import hashlib
import os
import re
import unittest
from helpers import TOP, ShellTest
OPENWRT = TOP / 'openwrt' / 'overlay'
SCRIPT = OPENWRT / 'etc' / 'uci-defaults' / '92-mu300-uhttpd-key'
def shipped_list():
body = SCRIPT.read_text()
block = body[body.index("shipped='\n") + len("shipped='\n"):]
return block[:block.index("'\n")].splitlines()
class ShippedList(unittest.TestCase):
def test_list_is_fingerprints_of_every_shipping_release(self):
lines = shipped_list()
rows = [line.split(' ') for line in lines]
self.assertTrue(all(len(r) == 3 for r in rows), lines)
sums = [r[0] for r in rows]
self.assertTrue(all(re.fullmatch(r'[0-9a-f]{64}', s) for s in sums))
self.assertEqual(len(sums), len(set(sums)), 'one key per image')
# never the sha256 of an empty file (a key that came out empty would match every empty file)
self.assertNotIn(hashlib.sha256(b'').hexdigest(), sums)
# both images of each release from v2026.10.13 (the first with a key) to v2026.10.16.1
tags = ['v2026.10.%d' % n for n in range(13, 28)] + ['v2026.10.16.1']
self.assertEqual({(t, f) for t in tags for f in ('openwrt', 'openwrt-luci')}, {(r[1], r[2]) for r in rows})
# v2026.10.16.1's plain OpenWrt key, as FINDINGS 132 quotes it (seen on F50-C and in the release tarball)
self.assertTrue(any(s.startswith('ad78a3f7') and t == 'v2026.10.16.1' and f == 'openwrt' for s, t, f in rows))
def test_runs_at_every_boot_of_a_new_image_and_removes_itself(self):
self.assertTrue(os.access(SCRIPT, os.X_OK))
body = SCRIPT.read_text()
self.assertTrue(body.startswith('#!/bin/sh\n'))
# uci-defaults delete a script that ends with 0: that is the marker that it ran on this image
self.assertTrue(body.rstrip().endswith('exit 0'))
self.assertNotIn('BEGIN', body) # fingerprints only, never a key in the repository
self.assertNotIn('PRIVATE KEY', body)
class ImageHasNoKey(unittest.TestCase):
def test_build_removes_the_pair_and_the_audit_refuses_a_key(self):
owrt = (TOP / 'openwrt' / 'build-rootfs.sh').read_text()
self.assertIn('rm -f $R/etc/uhttpd.key $R/etc/uhttpd.crt\n'
'[ ! -e $R/etc/uhttpd.key ] || { echo "the image holds a TLS key" >&2; exit 1; }', owrt)
# the build script is one single-quoted sh -c argument: no apostrophe may be in it
start = "mu300-$FLAVOUR-base:$VER /bin/sh -eu -c '"
body = owrt[owrt.index(start) + len(start):owrt.rindex("ls -la /out/$OUT'")]
self.assertNotIn("'", body)
self.assertIn('rm -f $R/etc/uhttpd.key', body)
rel = (TOP / 'tools' / 'make-release.sh').read_text()
self.assertIn(r"-e '^etc/uhttpd\.key$'", rel)
self.assertTrue(re.search(r'^etc/uhttpd\.key$', 'etc/uhttpd.key'))
class DropShipped(ShellTest):
def setUp(self):
super().setUp()
self.etc = self.tmp / 'etc'
(self.etc / 'ssl').mkdir(parents=True)
self.uci_conf = self.tmp / 'uci-uhttpd'
self.uci_conf.write_text("uhttpd.main=uhttpd\nuhttpd.main.cert='/etc/uhttpd.crt'\n"
"uhttpd.main.key='/etc/uhttpd.key'\n")
# uci: show prints the file, get one value from it
self.stub('uci', '[ "$1" = -q ] && shift\n'
'case $1 in\n'
' show) cat "$STUBLOG/uci-uhttpd" ;;\n'
' get) v=$(grep "^$2=" "$STUBLOG/uci-uhttpd") || exit 1; v=${v#*=}; v=${v#\\\'}; '
'echo "${v%\\\'}" ;;\n'
' *) exit 1 ;;\n'
'esac')
self.stub('logger', 'echo "$*" >> "$STUBLOG/logger.log"')
def pair(self, name, key, crt=b'certificate\n'):
(self.etc / f'{name}.key').write_bytes(key)
(self.etc / f'{name}.crt').write_bytes(crt)
def run_defaults(self, shell, shipped=()):
"""The script with /etc in the scratch directory and SHIPPED (contents) added to its list."""
body = SCRIPT.read_text()
extra = ''.join(f'{hashlib.sha256(k).hexdigest()} vTEST openwrt\n' for k in shipped)
body = body.replace("shipped='\n", "shipped='\n" + extra, 1).replace('/etc/', f'{self.etc}/')
self.uci_conf.write_text(self.uci_conf.read_text().replace("'/etc/", f"'{self.etc}/"))
r = self.sh(shell, body)
self.assertEqual(0, r.returncode, r.stderr)
return r
def test_a_shipped_key_goes_with_its_certificate(self):
for shell in self.each_shell():
self.pair('uhttpd', b'the shipped key\n')
self.run_defaults(shell, shipped=[b'the shipped key\n'])
self.assertFalse((self.etc / 'uhttpd.key').exists())
self.assertFalse((self.etc / 'uhttpd.crt').exists())
self.assertIn('removed the TLS key', (self.tmp / 'logger.log').read_text())
# again (the next image's first boot): nothing there, nothing to do
self.run_defaults(shell, shipped=[b'the shipped key\n'])
self.assertFalse((self.etc / 'uhttpd.key').exists())
def test_a_key_of_the_users_is_never_touched(self):
for shell in self.each_shell():
self.pair('uhttpd', b'made on the device\n', b'its certificate\n')
self.run_defaults(shell, shipped=[b'the shipped key\n', b'made on the device'])
self.assertEqual(b'made on the device\n', (self.etc / 'uhttpd.key').read_bytes())
self.assertEqual(b'its certificate\n', (self.etc / 'uhttpd.crt').read_bytes())
self.assertFalse((self.tmp / 'logger.log').exists())
def test_the_real_list_spares_any_other_key(self):
for shell in self.each_shell():
self.pair('uhttpd', b'made on the device\n')
self.run_defaults(shell)
self.assertTrue((self.etc / 'uhttpd.key').exists())
self.assertTrue((self.etc / 'uhttpd.crt').exists())
def test_an_empty_key_file_is_not_a_shipped_one(self):
for shell in self.each_shell():
self.pair('uhttpd', b'')
self.run_defaults(shell)
self.assertTrue((self.etc / 'uhttpd.key').exists())
def test_the_key_uci_points_to(self):
for shell in self.each_shell():
self.uci_conf.write_text("uhttpd.main=uhttpd\nuhttpd.main.cert='/etc/ssl/lan.crt'\n"
"uhttpd.main.key='/etc/ssl/lan.key'\nuhttpd.other=uhttpd\n"
"uhttpd.other.key='/etc/ssl/other.key'\n")
(self.etc / 'ssl' / 'lan.key').write_bytes(b'the shipped key\n')
(self.etc / 'ssl' / 'lan.crt').write_bytes(b'the shipped certificate\n')
(self.etc / 'ssl' / 'other.key').write_bytes(b'the user key\n')
self.pair('uhttpd', b'made on the device\n')
self.run_defaults(shell, shipped=[b'the shipped key\n'])
self.assertFalse((self.etc / 'ssl' / 'lan.key').exists())
self.assertFalse((self.etc / 'ssl' / 'lan.crt').exists())
self.assertTrue((self.etc / 'ssl' / 'other.key').exists())
# the default pair is the user's: kept, also as the certificate of a section without one
self.assertTrue((self.etc / 'uhttpd.key').exists())
self.assertTrue((self.etc / 'uhttpd.crt').exists())
def test_no_uhttpd_no_key(self):
for shell in self.each_shell():
self.stub('uci', 'exit 1')
self.run_defaults(shell, shipped=[b'the shipped key\n'])
self.assertFalse((self.tmp / 'logger.log').exists())
if __name__ == '__main__':
unittest.main()
+2 -1
View File
@@ -90,7 +90,8 @@ class Update(ShellTest):
'lib/firmware/regulatory.db': b'old',
'lib/modules/7.2.8/wcn_bsp.ko': b'module',
'etc/unisoc-modem/cpu-voltage.json': b'{"offsets":[0,0,0]}',
'etc/config/wireless': b'my-settings'}
'etc/config/wireless': b'my-settings',
'etc/crontabs/root': b'*/5 * * * * /root/check-link\n'}
for name, data in files.items():
path = old / name
path.parent.mkdir(parents=True, exist_ok=True)
+91
View File
@@ -0,0 +1,91 @@
"""Compile the real callbacks: runtime PM precedes thread startup, WDT stops only for system sleep."""
from pathlib import Path
import shutil, subprocess, tempfile, unittest
from helpers import TOP
def function(source, name):
start=source.index(name+'(')
start=source.rfind('\n',0,start)+1
pos=source.index('{',start);end=pos+1;depth=1
while depth:
depth+=(source[end]=='{')-(source[end]=='}');end+=1
return source[start:end]
@unittest.skipUnless(shutil.which('cc'),'C compiler required')
class PowerOrder(unittest.TestCase):
def compile_run(self, source):
with tempfile.TemporaryDirectory() as path:
p=Path(path);(p/'test.c').write_text(source)
subprocess.run(['cc','-Wall','-Werror','-Wno-unused-function',str(p/'test.c'),'-o',str(p/'test')],check=True,capture_output=True)
subprocess.run([str(p/'test')],check=True)
def test_watchdog_suspend_resume_and_read_error(self):
source=(TOP/'upstream/port/drivers/watchdog/ump9620-pmic-wdt.c').read_text()
stub=r'''
#include <assert.h>
#include <stdbool.h>
typedef unsigned int u32;
#define WDT_CTRL 8
#define WDT_CNT_EN 2
struct ump9620_wdt { void *map; u32 base; bool suspended; struct { unsigned timeout; } wdd; };
struct device { struct ump9620_wdt *data; };
static unsigned ctrl, starts, stops, loads, read_error;
static void *dev_get_drvdata(struct device *d) { return d->data; }
static int regmap_read(void *m,unsigned r,u32 *v) { *v=ctrl; return read_error; }
static int ump9620_wdt_ctrl(struct ump9620_wdt *w,bool on) { if(on) starts++; else stops++; return 0; }
static int ump9620_wdt_load(struct ump9620_wdt *w,unsigned t) { assert(t==60); loads++; return 0; }
#define dev_warn(...) ((void)0)
'''
self.compile_run(stub+function(source,'ump9620_wdt_suspend_noirq')+
function(source,'ump9620_wdt_resume_noirq')+r'''
int main(void) {
struct ump9620_wdt w={.wdd={.timeout=60}};struct device d={&w};
ctrl=0;assert(!ump9620_wdt_suspend_noirq(&d));assert(!ump9620_wdt_resume_noirq(&d));
assert(!starts&&!stops&&!loads);
ctrl=WDT_CNT_EN;assert(!ump9620_wdt_suspend_noirq(&d));assert(stops==1&&w.suspended);
assert(!ump9620_wdt_resume_noirq(&d));assert(starts==1&&loads==1&&!w.suspended);
assert(!ump9620_wdt_resume_noirq(&d));assert(starts==1);
read_error=5;assert(ump9620_wdt_suspend_noirq(&d)==5);assert(stops==1);
return 0;
}
''')
def test_sipa_runtime_pm_is_ready_for_immediate_enable_and_failure_rolls_back(self):
source=(TOP/'upstream/modules/sprd_modem/sipa_delegate/sipa_dele_cp_in_ap.c').read_text()
stub=r'''
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#define GFP_KERNEL 0
#define ENOMEM 12
#define EINPROGRESS 115
#define SIPA_RM_RES_CONS_WIFI_UL 1
#define SIPA_RM_RES_CONS_WIFI_DL 2
#define kzalloc(n,f) calloc(1,n)
struct sipa_delegator_create_params { void *pdev; };
struct delegate { void *pdev; void (*on_cmd)(void); void (*local_request_prod)(void);
bool pd_eb_flag,pd_get_flag; int smsg_cnt,prod_id; };
struct wrapper { struct delegate delegator; };
static struct wrapper *s_cp_delegator;
static int enabled, starts, failure, init_failure;
static void cp_dele_on_commad(void) {}
static void cp_dele_local_req_r_prod(void) {}
static int sipa_delegator_init(struct delegate *d,struct sipa_delegator_create_params *p) { d->pdev=p->pdev;return init_failure; }
static void pm_runtime_enable(void *p) { assert(!enabled);enabled=1; }
static void pm_runtime_disable(void *p) { assert(enabled);enabled=0; }
static int sipa_delegator_start(struct delegate *d) { assert(enabled);starts++;return failure; }
static int sipa_rm_add_dependency(int a,int b) { return 0; }
static void sipa_dele_init_sysfs(struct wrapper *w) {}
#define dev_warn(...) ((void)0)
'''
self.compile_run(stub+function(source,'cp_delegator_init')+r'''
int main(void) {
struct sipa_delegator_create_params p={0};
assert(!cp_delegator_init(&p));assert(enabled&&starts==1);free(s_cp_delegator);
enabled=0;failure=-5;assert(cp_delegator_init(&p)==-5);assert(!enabled&&starts==2);free(s_cp_delegator);
init_failure=-6;assert(cp_delegator_init(&p)==-6);assert(!enabled&&starts==2);free(s_cp_delegator);
return 0;
}
''')
+1 -1
View File
@@ -474,7 +474,7 @@ for os in $OSES; do
image_own_save "$M/$os.new"
case $os in
ubuntu) keep="etc/mu300 etc/ssh etc/hostname etc/localtime etc/timezone etc/fstab home root srv usr/local var/lib/bluetooth" ;;
openwrt) keep="etc/config etc/mu300 etc/unisoc-modem etc/dropbear etc/rc.local root" ;;
openwrt) keep="etc/config etc/mu300 etc/unisoc-modem etc/dropbear etc/rc.local etc/crontabs root" ;;
esac
kept=
for k in $keep; do
+1 -1
View File
@@ -122,7 +122,7 @@ for a in mu300-kernel mu300-kernel-6.18 mu300-kernel-7.2 mu300-ubuntu-rootfs mu3
-e '(^|/)lib/firmware/(wcnmodem|gnssmodem|wifi_board_config|bt_configure)' \
-e '^opt/mu300/android/.+' -e '__properties__|dev-properties' \
-e '(^|/)(libmali|libOpenCL|libGLES|libEGL|libvulkan)[^/]*\.so' \
-e '^etc/ssh/ssh_host_' -e '^etc/mu300/(hotspot|vpn|toolkit)\.conf$' -e '^etc/dropbear/dropbear_.*_host_key' \
-e '^etc/uhttpd\.key$' -e '^etc/ssh/ssh_host_' -e '^etc/mu300/(hotspot|vpn|toolkit)\.conf$' -e '^etc/dropbear/dropbear_.*_host_key' \
| grep -vE '^opt/mu300/android/system/?$|^opt/mu300/android/system/bin/?$|^opt/mu300/android/system/bin/cltest$' || true)
if [ -n "$bad" ]; then echo "$a contains files that must not be published:"; echo "$bad" | head -20; fail=1; fi
mid=$(tar -xzOf "$D/$a.tar.gz" ./etc/machine-id 2>/dev/null || true)
@@ -186,10 +186,14 @@ int cp_delegator_init(struct sipa_delegator_create_params *params)
s_cp_delegator->delegator.pd_get_flag = false;
s_cp_delegator->delegator.smsg_cnt = 0;
/* MU300: its result used to be ignored, so a PROD_CP it had deleted again went unnoticed */
ret = sipa_delegator_start(&s_cp_delegator->delegator);
if (ret)
return ret;
/* The thread can receive ENABLE as soon as start runs. Its runtime-PM
* device must already be enabled; no extra wait or handshake is needed. */
pm_runtime_enable(s_cp_delegator->delegator.pdev);
ret = sipa_delegator_start(&s_cp_delegator->delegator);
if (ret) {
pm_runtime_disable(s_cp_delegator->delegator.pdev);
return ret;
}
/*
* MU300: the Wi-Fi offload path, which this device does not use (the CONS_WIFI resources stay released): a
@@ -700,6 +700,8 @@ int sc2355_send_cmd_recv_rsp(struct sprd_priv *priv, struct sprd_msg *msg, u8 *r
if (atomic_read(&priv->hif.block_cmd_after_close) == 1) {
if (cmd_id != CMD_CLOSE) {
ret = -EBUSY;
if (rlen)
*rlen = 0;
pr_info("%s need block cmd after close : %s\n",
__func__, cmdevt_cmd2str(cmd_id));
sprd_chip_free_msg(&priv->chip, msg);
@@ -712,6 +714,8 @@ int sc2355_send_cmd_recv_rsp(struct sprd_priv *priv, struct sprd_msg *msg, u8 *r
if (atomic_read(&priv->hif.change_iface_block_cmd) == 1) {
if (cmd_id != CMD_CLOSE && cmd_id != CMD_OPEN) {
ret = -EBUSY;
if (rlen)
*rlen = 0;
pr_info("%s need block cmd while change iface : %s\n",
__func__, cmdevt_cmd2str(cmd_id));
sprd_chip_free_msg(&priv->chip, msg);
@@ -1947,7 +1951,7 @@ int sc2355_get_station(struct sprd_priv *priv, struct sprd_vif *vif,
struct sprd_sta_info *sta)
{
struct sprd_msg *msg;
struct cmd_get_station get_sta;
struct cmd_get_station get_sta = {};
u8 *r_buf = (u8 *)&get_sta;
u16 r_len = sizeof(get_sta);
int ret;
@@ -4,6 +4,11 @@
* Android, the PM co-processor firmware takes it over. Mainline has no PM firmware, so this driver takes it over
* instead: it shortens the timeout and lets the watchdog core ping it until userspace opens /dev/watchdog. A hard
* hang then resets the board, and LK falls back to Android. MU300 bring-up driver.
*
* The watchdog runs on the PMIC's 32 kHz clock and keeps counting while the AP sleeps, where nothing pings it
* (Android has the PM co-processor feed it): a system sleep longer than the timeout reset the board (FINDINGS 37).
* It is stopped as the last thing before the sleep and armed again, with a fresh count, as the first thing after
* it - the vendor's sprd_wdt does the same for the AP watchdog.
*/
#include <linux/bits.h>
#include <linux/delay.h>
@@ -30,6 +35,7 @@ struct ump9620_wdt {
struct watchdog_device wdd;
struct regmap *map;
u32 base;
bool suspended; /* stopped for a system sleep, to be armed again on resume */
};
static int ump9620_wdt_load(struct ump9620_wdt *w, unsigned int timeout)
@@ -88,6 +94,39 @@ static int ump9620_wdt_set_timeout(struct watchdog_device *wdd, unsigned int t)
return ump9620_wdt_ping(wdd);
}
static int ump9620_wdt_suspend_noirq(struct device *dev)
{
struct ump9620_wdt *w = dev_get_drvdata(dev);
u32 ctrl = 0;
int ret;
ret = regmap_read(w->map, w->base + WDT_CTRL, &ctrl);
if (ret)
return ret;
w->suspended = ctrl & WDT_CNT_EN;
if (w->suspended)
ump9620_wdt_ctrl(w, false);
return 0;
}
static int ump9620_wdt_resume_noirq(struct device *dev)
{
struct ump9620_wdt *w = dev_get_drvdata(dev);
int ret;
if (!w->suspended)
return 0;
w->suspended = false;
ret = ump9620_wdt_load(w, w->wdd.timeout);
if (ret)
dev_warn(dev, "reload after the sleep: %d\n", ret);
return ump9620_wdt_ctrl(w, true);
}
static const struct dev_pm_ops ump9620_wdt_pm_ops = {
NOIRQ_SYSTEM_SLEEP_PM_OPS(ump9620_wdt_suspend_noirq, ump9620_wdt_resume_noirq)
};
static const struct watchdog_info ump9620_wdt_info = {
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE,
.identity = "UMP9620 PMIC watchdog",
@@ -133,6 +172,7 @@ static int ump9620_wdt_probe(struct platform_device *pdev)
return ret;
}
platform_set_drvdata(pdev, w);
ret = devm_watchdog_register_device(&pdev->dev, &w->wdd);
if (ret)
return ret;
@@ -148,7 +188,7 @@ static const struct of_device_id ump9620_wdt_match[] = {
static struct platform_driver ump9620_wdt_driver = {
.probe = ump9620_wdt_probe,
.driver = { .name = "ump9620-wdt", .of_match_table = ump9620_wdt_match },
.driver = { .name = "ump9620-wdt", .of_match_table = ump9620_wdt_match, .pm = pm_sleep_ptr(&ump9620_wdt_pm_ops) },
};
module_platform_driver(ump9620_wdt_driver);
MODULE_DESCRIPTION("UMP9620 PMIC watchdog");