mirror of
https://github.com/dikeckaan/mu300-linux.git
synced 2026-12-05 08:02:40 +00:00
Fix shared storage ordering and backport modem reliability improvements
This commit is contained in:
1 parent
f6b0668d2e
commit
0438ab01c7
35 files changed
+1278
-28
No files matched your search
@@ -68,6 +68,13 @@ jobs:
|
||||
docker run --rm -e KV="$KV" -v mu300-mainline:/src -v "$PWD/upstream":/work \
|
||||
mu300-mainline-build bash /work/build-modules.sh > /dev/null
|
||||
ls upstream/out/modules/*.ko | wc -l
|
||||
- name: Check shared SDHCI DMA ordering
|
||||
env:
|
||||
KV: ${{ matrix.kv }}
|
||||
run: |
|
||||
docker run --rm -e KV="$KV" -v mu300-mainline:/src:ro \
|
||||
-v "$PWD/upstream":/work:ro -v "$PWD/tests":/tests:ro \
|
||||
mu300-mainline-build bash -c 'python3 /tests/test_emmc_dma.py "/src/linux-$KV" --adapter /work/port/emmc.py'
|
||||
- name: Build logs
|
||||
if: failure()
|
||||
run: tail -n 60 upstream/out/modules/*.log 2>/dev/null || true
|
||||
@@ -0,0 +1,59 @@
|
||||
# MU300 / F50 / U30Air / V50 更新日志
|
||||
|
||||
日期:2026-10-14
|
||||
|
||||
对应提交:`f6b0668`
|
||||
|
||||
适用范围:MU300 仓库的公共安装功能及 F50、U30Air、V50 机型适配。
|
||||
|
||||
本日志介绍这次提交带来的变化。新版安装包尚未统一编译发布,旧预览包不等于包含全部改动的新版固件。
|
||||
|
||||
## 一个包,两种安装入口
|
||||
|
||||
- 保留原有 Magisk TF 卡部署流程,同时增加解压后在电脑运行的安装器。
|
||||
- 电脑安装器提供 TF 卡、userdata 镜像、独立内置分区、重装、重置后续装、更新和启动切换入口。
|
||||
- 电脑与 Magisk 共用一份系统包,去掉重复的 rootfs,减少安装包体积。
|
||||
- 顶层集中主安装器和 Magisk 必需文件;快捷脚本、说明和辅助文件归入文件夹,文件名使用英文。
|
||||
|
||||
## 内置安装更灵活
|
||||
|
||||
- 优先检查闪存里有没有尚未分配给任何分区的空间;足够时直接利用,不必缩小 userdata,也不必重置 Android。
|
||||
- 必须缩容时,未加密 userdata 走保留数据流程;加密 userdata 走重置 Android 后续装流程。
|
||||
- 安装后的文件系统扩展到所选分区容量,避免选了 8 GB、10 GB,系统却仍只有约 2 GB。
|
||||
- 离线安装持续输出阶段、耗时和复制进度,减少长时间没有反馈的情况。
|
||||
- 保留分区、启动相关备份和续装记录,并在继续安装前核对设备与分区状态。
|
||||
|
||||
## 修复电脑安装时遇到的问题
|
||||
|
||||
- 修复部分 Android 环境找不到镜像挂载设备,导致续装失败的问题。
|
||||
- 兼容部分 root 环境会改变二进制输出的问题,避免备份和设备信息读取失真。
|
||||
- 修复设备正常重启、连接断开后被误报为失败的问题。
|
||||
- 修复兼容修正版安装器因包名称变化而拒绝续装的问题;仍严格检查实际系统文件、目标设备和分区。
|
||||
- 热点密码改为明文输入,方便检查是否输错。
|
||||
- 结束时明确显示完成、失败、取消或需要下一步操作,并在交互运行时等待用户关闭。
|
||||
- 更新改由电脑主动上传文件,减少设备无法回连电脑下载、被防火墙拦住的问题。
|
||||
|
||||
## V50 适配与 F50 区分
|
||||
|
||||
- 增加 V50 / MU3351 的准确识别,避免与其他名称相似的机型混淆。
|
||||
- 系统按实际硬件区分 F50 与 V50,避免旧配置或其他机型的备份带来错误功能。
|
||||
- V50 开放双卡配置,并改进只插第二张卡时的初始化处理。
|
||||
- 适配 V50 的 NET1、NET2、Wi-Fi 三组灯,网页可分别调整开关和亮度。
|
||||
- NET1、NET2 分别反映两张 SIM 的注册状态;Wi-Fi 灯反映热点频段。
|
||||
- 补齐 V50 CPU 电压支持、NFC 引脚和 USB 角色设置入口。
|
||||
- 更新时检查固件是否明确支持 V50,避免误用缺少 V50 灯驱动的旧 F50 包。
|
||||
- V50 新支持面向 6.18 / 7.2 内核,不包含旧 5.4 安装路径。
|
||||
|
||||
## 默认启动提示与存储兼容
|
||||
|
||||
- 网页首页在临时启动 OpenWrt 时给出提示,可确认设为默认启动,无需立即重启。
|
||||
- 启动设置写入失败时恢复原状态,避免设置显示与实际启动行为不一致。
|
||||
- 改进内置闪存的系统休眠及写入兼容处理,保留运行时自动省电,不再强制闪存一直唤醒。
|
||||
- 灯光状态复用现有通知和系统事件,不额外增加常驻 AT 轮询。
|
||||
|
||||
## 当前验证范围
|
||||
|
||||
- 安装器、型号区分及相关功能已通过离线回归;V50 部分灯光、硬件识别和网页功能已有实机验证。
|
||||
- 双卡实际联网、V50 OTG 外设及完整安装流程仍有待验证项,不能视为所有组合均已验收。
|
||||
- 最新存储兼容策略尚未部署实机;历史 EXT4 元数据损坏的唯一根因仍未确认,不能宣称已彻底解决。
|
||||
- 两个仓库继续各自保留机型对应的驱动、固件和存储布局,不能跨仓库、跨型号混刷。
|
||||
@@ -0,0 +1,85 @@
|
||||
# eMMC 文件损坏与 DMA 排序调查(2026-10-14)
|
||||
|
||||
## 当前结论
|
||||
|
||||
E5 已有直接证据表明本次并非单纯“重启少等几秒”:目录或 inode 表中出现了另一物理块的完整旧内容。同时,普通文件读写在 E5 和 V50 均触发 `mmc0: ADMA error: 0x02000002`,当时命令/数据 CRC 错误计数仍为 0。
|
||||
|
||||
修复展锐 SDHCI 的 DMA/MMIO 排序缺口后,E5 保持 HS400 enhanced strobe、200 MHz、8 bit,已通过 896 MiB 多缓冲写入及等量 O_DIRECT 读回、3584 次原子目录更新、重启后的 224 MiB 最新代数据校验,以及两遍离线只读 fsck。存储错误计数均为 0,运行时休眠仍启用。
|
||||
|
||||
V50 已按用户要求重新部署完整 OpenWrt:沿用现有 8 GiB 独立分区,没有再次缩容 userdata;重新从该 V50 的 Android 提取固件和运行库,一次性安装新内核及 52 个匹配的核心模块。完整普通镜像启动、网页登录页、热点、基带 AT、双卡配置和 V50 灯控进程检查通过;原热点设置、账号密码和 SSH 密钥保留。
|
||||
|
||||
在完整系统中,两轮合计 256 MiB 写入及等量 O_DIRECT 读回、1024 次元数据更新通过;正常重启后,64 MiB 最新代内容仍完全一致。当前 HS400 enhanced strobe、200 MHz、8 bit,运行时休眠为 auto/suspended,ADMA、超时、CRC、EXT4 计数均为 0。诊断启动镜像已替换为普通镜像,有界测试文件已清除。
|
||||
|
||||
这表示上述现场验证通过,不是任何硬件条件下永久不再损坏的保证。
|
||||
|
||||
## 原始损坏证据
|
||||
|
||||
E5 的第一次离线修复使用 e2fsck undo 文件保存了修复前的块内容。ADB 的终端路径插入了 CR,去掉每个 LF 前的传输 CR 后,undo header 和每个数据记录的 CRC32C 均通过,排除了把传输损坏误当磁盘损坏。
|
||||
|
||||
- `/opt/e5` 的 inode 为 1544,原 extent 指向文件系统块 14169。
|
||||
- 块 14169 的 4096 字节,与 inode 表块 398 **逐字节相同**。
|
||||
- SHA256:`36a7f5d0ffabfc5f1c8ddc669a2830cef818deaa1b4386dc7cbd6b1cc8b22992`。
|
||||
- 后续旧驱动写入期间,另有三个 inode 出现了旧备份目录、备份文件的 inode 内容,导致目录/普通文件类型改变、校验和失效、多个 inode 引用相同的数据块。
|
||||
|
||||
因此,单纯延长 reboot 前 sleep 或反复 fsck 不能解释、更不能根治这种“位置正确、内容属于别处”的问题。文件系统或内存/DMA 路径、卡内地址映射都需要考虑;不能只凭块形态排除卡内故障。
|
||||
|
||||
## 本次修正
|
||||
|
||||
两仓库公共适配器:
|
||||
|
||||
- E5:`devices/common/emmc.py`,由 E5、T551M、M8 的内核准备流程共用。
|
||||
- MU300:`upstream/port/emmc.py`。
|
||||
|
||||
展锐驱动覆盖了 SDHCI 的 MMIO 访问器,却全部使用 relaxed 访问。SDHCI 核心会先写 coherent ADMA 描述符,再写 COMMAND 启动 DMA;coherent 分配不保证这两个操作的先后关系。完成状态的读取也需要约束后续 DMA 数据读取。
|
||||
|
||||
本次改为与通用 SDHCI 访问器相同的 `readl/writel/writew/writeb`,保留展锐对保留寄存器、中断掩码和硬件复位位的特殊处理。没有加入轮询服务或逐次刷盘任务,没有降低总线模式、关闭写缓存或全局禁用运行时休眠。
|
||||
|
||||
这是一个独立可确认的驱动 API 排序缺口,E5 对照结果支持其有效;暂不宣称它是两种芯片所有历史损坏的唯一根因。
|
||||
|
||||
参考:[Linux MMIO 访问约定](https://docs.kernel.org/driver-api/device-io.html)、[DMA coherent 内存与内存屏障](https://docs.kernel.org/core-api/dma-api-howto.html)。原厂参考驱动也有 relaxed 访问,但其请求调度等路径不同,不能据此认为当前组合一定安全,也不能声称本次是照抄原厂已经存在的修复。
|
||||
|
||||
## 验证方法和边界
|
||||
|
||||
使用独立临时普通文件,不对原始分区做压力写,不操作 NV 或 Android 数据分区布局。每个 4 KiB 块携带文件编号、代数、块编号和逐字内容特征;fsync 后通过 O_DIRECT 读回,避免只读到页缓存而误报通过。
|
||||
|
||||
每轮四个并行写入者:总计 128 MiB 写入、128 MiB 读回,并发 512 次 fsync/rename 元数据更新。E5 修复前同组测试触发 1 次 ADMA 错误;修复后 7 轮没有新增错误。之后正常重启,并在未挂载根分区时执行两遍 `e2fsck -fn`,均通过;再恢复普通启动镜像、重启,校验全部 7 轮文件的最新代内容,共 224 MiB。
|
||||
|
||||
实际验证还包括内核/模块哈希、运行内核配置、蜂窝 IP/DNS、热点、屏幕服务、短信转发接口以及用户配置哈希。受旧驱动影响的程序、模块链接和流量状态已从校验过的载荷/保存数据恢复。
|
||||
|
||||
这些是有界测试,不是寿命或任何供电环境下永不出错的证明。已有损坏必须离线修复,排序修正不会自动恢复被覆盖的数据。
|
||||
|
||||
## V50 启动失败的另外两个问题
|
||||
|
||||
本次部署先遗漏了与新内核匹配的根分区模块,造成 BTF 类型校验失败,这是部署失误;配套模块补齐后仍未完整启动,因此不能把启动问题全部归咎于 BTF 或 eMMC 休眠。
|
||||
|
||||
随后在 Android 下只读核对根分区,发现 `sbin/procd` 等 7 个基础程序缺失,整个 `/opt/mu300` 目录也已脱离。71 个原程序及本机 Android 运行库的大部分内容可以在 `lost+found` 对应,说明“fsck 已通过”不等于系统文件齐全。`/sbin/init` 仍存在,旧启动检查却只检查这个小入口,因而继续 `switch_root` 后无法进入正常 procd;这解释了仅补齐模块依然无网页、无 SSH 的现象。
|
||||
|
||||
完整 `lost+found` 和原配置已留本地备份。遵照用户后续指示,没有执行逐文件恢复方案,而是重新制作干净系统、重新提取本机固件、写入已有 OpenWrt 分区,完成镜像回读、扩容至 8 GiB 和文件校验后才启动。没有修改 Android A 槽、GPT 或工厂 NV。原文件为何全部脱落尚不能从 fsck 结果精确定位到某一次写入;不能把“重新部署成功”当作 DMA 排序是唯一根因的证明。
|
||||
|
||||
## HS400 与 HS200
|
||||
|
||||
HS200 是合理的对照手段,但“降速后正常”不能独自区分 PHY 裕量、休眠恢复、命令调度和 DMA 排序。较慢模式也改变了时序关系,可能只是降低竞态出现概率。
|
||||
|
||||
本次优先保持 HS400。E5 已在 HS400 下通过上述验证;V50 也已独立通过完整系统启动、运行时休眠恢复和跨重启持久化验证。没有据社区描述将所有机型强制降到 HS200。
|
||||
|
||||
## 所有受支持机型的构建覆盖
|
||||
|
||||
排序修正没有机型判断,所有受支持机型共用:
|
||||
|
||||
| 仓库 / 构建 | 覆盖机型 | 修复接入 |
|
||||
| --- | --- | --- |
|
||||
| E5 机型内核构建 | E5、T551M、VIPME M8 | 三个 prepare-kernel 入口均调用 devices/common/emmc.py |
|
||||
| E5 公共主线构建 | E5 公共内核 | Docker build.sh、本机交叉编译 build-native.sh 均调用公共适配器 |
|
||||
| E5 旧 5.4 构建 | 该入口支持的 E5 | build-linux.sh 补丁序列新增 0029-sdhci-sprd-dma-ordering.patch |
|
||||
| MU300 主线 6.18 / 7.2 | F50 / MU300、V50 / MU3351、U30 Air | port/install.py 无条件调用公共 emmc.py |
|
||||
| MU300 旧 5.4 构建 | 该入口支持的 F50 / MU300、U30 Air | build-all.sh 的 KPATCHES 新增排序补丁,U30 Air 复用已打补丁源码 |
|
||||
|
||||
新适配机型沿用公共构建链即可继承修正。5.4 只回补 MMIO 排序,不移植主线专属的 FUA/PM 结构,不更改总线模式、频率或睡眠策略。MU300 5.4 的补丁摘要改变后会自动从固定提交重新应用补丁集,防止缓存漏修;E5 5.4 保留原有严格补丁序列验证。
|
||||
|
||||
实际 6.18、7.2 驱动和本地原厂 5.4 参考驱动的访问器 C 编译执行、保留寄存器、复位位、中断掩码、缓存升级、重复应用和部分补丁失败阻断测试通过。旧补丁也通过 E5 构建使用的 git apply / reverse-check 检查。两仓库主线发布 CI 已加入同组排序检查。
|
||||
|
||||
尚未逐个重编全部机型发行镜像;已安装旧内核、已发布旧包不会因源码修改自动更新。5.4 完整构建与实机验证未进行。
|
||||
|
||||
## 本地证据
|
||||
|
||||
详细设备日志、undo 文件、启动镜像备份和测试记录保存在忽略目录 `out/emmc-investigation-20261014/`。其中包含设备标识和用户配置,不作为公开附件提交。
|
||||
@@ -1935,3 +1935,17 @@ initramfs 又优先相信该标记。现与桌面安装器对齐 V50/MU3351/ums9
|
||||
V50 更新要求包明确支持,主线包和共用 TF 包检查内置 AW9523B 支持。
|
||||
详见 [V50 记录](V50-MU3351-20261014.zh-CN.md#f50--v50-共用固件的机型隔离)。
|
||||
本轮仅修改代码与回归验证,未重新编译、打包或刷机。
|
||||
|
||||
## 2026-10-14:六项上游修复的公共适配
|
||||
|
||||
按 #199 / #184 / #217 / #190 / #211 / #228 移植权限、TF 检测、升级锁、温控保护、转发结果及内核/打包检查。保留机型边界和现有双卡后端;E5 无相同升级保活链路,因此不引入 MU300 更新器。E5/T551M 原厂虚拟温区同类提前返回问题也纳入公共修正,M8 同步。正常导入树不重复改权限;不预装 Docker,不增加常驻 AT/温控轮询。详见 [范围与验证](UPSTREAM-BACKPORT-20261014.zh-CN.md)。尚未统一构建安装包或部署实机。
|
||||
|
||||
|
||||
## 2026-10-14:eMMC DMA/MMIO 排序与 E5、V50 实机验证
|
||||
|
||||
公共 SDHCI 适配器改用有序 MMIO 访问器,修补 ADMA 描述符提交与完成读取之间的排序缺口;保留寄存器特殊处理、HS400 和运行时省电。E5 的修复前块记录存在另一 inode 表的完整内容,E5/V50 旧驱动普通文件测试均曾触发 ADMA 错误,不能仅按断电未刷盘解释。
|
||||
|
||||
E5 完成 896 MiB 写入及等量直接读回、3584 次元数据更新、重启后 224 MiB 校验和两遍离线只读 fsck。V50 按用户要求重装现有 8 GiB OpenWrt 分区、重新提取本机固件,完整系统两轮 256 MiB 写读、1024 次元数据更新、重启后 64 MiB 校验通过。两机保持 HS400/200 MHz,错误计数为 0、运行时休眠启用;不把有界测试宣布为所有硬件永久可靠。V50 曾有本次部署漏同步模块导致的 BTF 不匹配,以及旧根目录脱落导致基础程序缺失,已在报告中分别记录。详见 [证据、范围及限制](EMMC-DMA-ORDERING-20261014.zh-CN.md)。未统一构建发行包,T551M/M8 未实机部署本次内核。
|
||||
|
||||
|
||||
2026-10-14 补齐排序修复覆盖:E5/T551M/M8 的三个机型内核入口及公共 Docker/本机交叉编译、MU300/F50/V50/U30 Air 两条主线版本均接入公共适配器;另补入两仓库旧 5.4 补丁链,不带入主线专属 PM/FUA 改动。发布 CI 增加实际访问器 C 编译执行检查。实际 6.18、7.2、原厂 5.4 参考驱动测试通过;尚未逐个重编和升级全部机型,详见同一调查报告的构建覆盖表。
|
||||
@@ -0,0 +1,42 @@
|
||||
# 上游六项修复移植记录(2026-10-14)
|
||||
|
||||
本次按用户选定的六项 PR 做针对性移植,保留现有机型识别、双卡配置、安装与更新布局。
|
||||
此记录描述源码和验证结果;尚未统一编译发布安装包,也没有部署实机。
|
||||
|
||||
## 移植范围
|
||||
|
||||
| 上游修复 | MU300 / F50 / U30Air / V50 | E5 / T551M / M8 公共仓库 |
|
||||
| --- | --- | --- |
|
||||
| [#199 导入固件权限](https://github.com/dikeckaan/mu300-linux/pull/199),`209c2bfa` | 归档权限按用途生成,不依赖电脑文件系统;启动前纠正导入树权限;提前创建日志目录 | Android 本机收集时统一权限,公共启动脚本纠正旧安装;三个机型及普通构建入口均带上辅助脚本 |
|
||||
| [#184 TF 检测](https://github.com/dikeckaan/mu300-linux/pull/184),`18401274` | 应用八组 EIC 补丁;修正旧缓存树中仅掩盖 GPIO 延迟、跳过后续 MMC 参数解析的回退 | 原生驱动已有八组支持,公共适配增加幂等检查及兼容修正,不套用 MU300 的板级存储参数 |
|
||||
| [#217 升级锁](https://github.com/dikeckaan/mu300-linux/pull/217),`2d340d78` | 保活进程关闭锁描述符,保留本仓库已有的 exec 锁继承保护 | 现有更新器使用自身互斥机制,没有这条下载后自替换与保活链路,不移植无关服务 |
|
||||
| [#190 温控](https://github.com/dikeckaan/mu300-linux/pull/190),`53234365` 等 | 虚拟温区继续使用其余有效传感器;全部失败返回错误;检查温区读数及被动阈值后再交给内核降频;只恢复保护程序自己降低的频率上限 | E5/T551M 原厂虚拟温区也有相同提前返回问题,公共内核适配已修正;M8 独立虚拟温区同步修正;不新增用户态温控轮询 |
|
||||
| [#211 转发结果](https://github.com/dikeckaan/mu300-linux/pull/211),`9bf4e7b5`、`70f96734` | 沿用现有双卡转发后端,补成功条件、清空记录、测试间隔 | 同步到三机型共用的网页、后端与 RPC,保留原生完整短信事件接入 |
|
||||
| [#228 内核与打包](https://github.com/dikeckaan/mu300-linux/pull/228),`0cf5106e`、`b91e8043` | 扩充可选模块;校验 Image 内嵌配置和完整模块清单;包内携带构建证据 | 公共配置及三机型构建入口对齐;在原有哈希、vermagic、模块归档检查上增加内嵌配置和扩展能力检查 |
|
||||
|
||||
## 用户可见行为
|
||||
|
||||
- 短信转发增加可选成功条件,如 `errcode=0`、`ok=true`。只检查响应 JSON 的顶层简单字段,不把响应内容显示或写入投递日志。未填写时保持原来的 HTTP 2xx 判定;钉钉保留固定成功码检查。
|
||||
- 预设可填入对应成功条件;旧配置仍可读取,旧客户端未携带新字段时保留已有条件,用户主动清空才撤销。
|
||||
- 最近投递记录可以确认后清空;不删除短信,不改变转发配置、处理进度或去重状态;清理不会跟随同名符号链接。
|
||||
- 手动测试至少间隔 5 秒,正常短信转发不受该节流限制。保留本仓库原有的失败不自动重发策略,避免重复投递。
|
||||
- 中、英、土耳其语及主题继续共用;不引入上游整套页面替换。
|
||||
- 新增虚拟机 virtio/9p、检查点、MPTCP/组播/MPLS、NFS/CIFS、磁盘映射、USB/IP、UVC 等支持。外设和大部分扩展以模块提供,不增加启动加载列表,不预装 Docker、虚拟机管理器或相关常驻服务。
|
||||
- 正常启动的权限检查只读;需要纠正时才修改导入文件的权限,不遍历 dev/proc/sys 绑定挂载,不跟随导入树中的符号链接。
|
||||
- 不修改 NV、运行时 eMMC 省电策略、现有网络/AT 轮询率或温控临界关机阈值。
|
||||
|
||||
## 验证
|
||||
|
||||
- 实际 Kconfig 合并:E5 6.18、MU300 6.18.54 / 7.2.8,新增配置全部被接受;兼容 NFSv4.1 仅在部分内核单独提供的依赖。
|
||||
- MU300 两版内核:修改后的虚拟温区模块及应用 EIC 补丁后的驱动对象编译通过。
|
||||
- E5 原厂虚拟温区适配:在实际 T551M 内核头文件下编译通过,适配可重复执行。
|
||||
- C 故障测试执行实际温度回调:部分传感器失败仍报告最高有效温度;全部失败返回错误,不制造低温读数;原厂回调最后一个传感器失败也不再丢弃此前有效值。
|
||||
- 真实 OpenWrt JSON/ucode 集成:两仓库测试 HTTP 200 服务拒收、布尔/字符串成功值、嵌套/无效/超长响应、旧配置、旧编辑器、钉钉、清空隔离与测试节流通过;不访问真实推送服务。
|
||||
- Chromium:两仓库页面在中英土语言、手机/桌面宽度下测试,成功条件保存和清空二次确认通过。
|
||||
- 权限、旧归档模式、锁描述符、完整模块与内嵌配置故障测试,以及相邻温控/短信/安装器回归通过。
|
||||
|
||||
## 尚待
|
||||
|
||||
完整新内核及匹配模块需要重新构建,再统一打包;旧构建产物会被新增检查明确拒绝。
|
||||
实机启动、TF 插拔、温控异常恢复和真实推送服务验收尚未进行,编译与离线测试不能代替这些验证。
|
||||
本次不宣称修复了未确定根因的存储损坏或所有“无模组”故障。
|
||||
+1
-1
@@ -45,7 +45,7 @@ echo "==> sources"
|
||||
fetch /src/zte-u30air "$KERNEL_REPO" "$KERNEL_REV"
|
||||
cd /src/zte-u30air
|
||||
# the tree is the pinned commit plus exactly these patches: reapply from a clean checkout whenever they change
|
||||
KPATCHES="bluetooth-marlin3-link-policy of-reserved-mem-skip of-reserved-mem-add regdb-wens-certificate sipa-delegate-einprogress wcn-pcie-scan-timeout sipc-base-addr-attr sprdwcn-mbuf-pool-deinit-null sprdwcn-edma-pressure-stats"
|
||||
KPATCHES="bluetooth-marlin3-link-policy of-reserved-mem-skip of-reserved-mem-add regdb-wens-certificate sipa-delegate-einprogress wcn-pcie-scan-timeout sipc-base-addr-attr sprdwcn-mbuf-pool-deinit-null sprdwcn-edma-pressure-stats sdhci-sprd-dma-ordering"
|
||||
sum=$(cd /work/patches && cat $(for p in $KPATCHES; do echo $p.patch; done) | sha256sum | cut -d" " -f1)
|
||||
if [ "$(cat .mu300-patches 2>/dev/null)" != "$sum" ]; then
|
||||
git checkout -q -f "$KERNEL_REV" && git clean -q -fdx -e .mu300-patches
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
Subject: [PATCH] mmc: sdhci-sprd: order ADMA submission and completion
|
||||
|
||||
Match generic SDHCI MMIO ordering while preserving the vendor reset, reserved
|
||||
register and interrupt-mask handling. Coherent descriptors still require ordering
|
||||
before the command doorbell. Keep timing, clocks and runtime PM unchanged.
|
||||
|
||||
--- a/drivers/mmc/host/sdhci-sprd.c
|
||||
+++ b/drivers/mmc/host/sdhci-sprd.c
|
||||
@@ -195,7 +195,8 @@
|
||||
if (unlikely(reg == SDHCI_MAX_CURRENT))
|
||||
return SDHCI_SPRD_MAX_CUR;
|
||||
|
||||
- return readl_relaxed(host->ioaddr + reg);
|
||||
+ /* Shared SDHCI policy: order ADMA descriptors and DMA completion. */
|
||||
+ return readl(host->ioaddr + reg);
|
||||
}
|
||||
|
||||
static inline void sdhci_sprd_writel(struct sdhci_host *host, u32 val, int reg)
|
||||
@@ -207,7 +208,7 @@
|
||||
if (unlikely(reg == SDHCI_SIGNAL_ENABLE || reg == SDHCI_INT_ENABLE))
|
||||
val = val & SDHCI_SPRD_INT_SIGNAL_MASK;
|
||||
|
||||
- writel_relaxed(val, host->ioaddr + reg);
|
||||
+ writel(val, host->ioaddr + reg);
|
||||
}
|
||||
|
||||
static inline void sdhci_sprd_writew(struct sdhci_host *host, u16 val, int reg)
|
||||
@@ -216,7 +217,7 @@
|
||||
if (unlikely(reg == SDHCI_BLOCK_COUNT))
|
||||
return;
|
||||
|
||||
- writew_relaxed(val, host->ioaddr + reg);
|
||||
+ writew(val, host->ioaddr + reg);
|
||||
}
|
||||
|
||||
static inline void sdhci_sprd_writeb(struct sdhci_host *host, u8 val, int reg)
|
||||
@@ -264,7 +265,7 @@
|
||||
val |= SDHCI_HW_RESET_CARD;
|
||||
}
|
||||
|
||||
- writeb_relaxed(val, host->ioaddr + reg);
|
||||
+ writeb(val, host->ioaddr + reg);
|
||||
}
|
||||
|
||||
static inline void sdhci_sprd_sd_clk_off(struct sdhci_host *host)
|
||||
@@ -99,6 +99,7 @@ var callSmsSync = scopedRpc({ object: 'mu300dash', method: 'sms_sync', expect: {
|
||||
var callForwardGet = rpc.declare({ object: 'mu300dash', method: 'forward_get', params: [ 'profile' ], expect: { '': {} } });
|
||||
var callForwardStatus = rpc.declare({ object: 'mu300dash', method: 'forward_status', params: [ 'profile' ], expect: { '': {} } });
|
||||
var callForwardSet = rpc.declare({ object: 'mu300dash', method: 'forward_set', params: [ 'payload' ], expect: { '': {} } });
|
||||
var callForwardClear = rpc.declare({ object: 'mu300dash', method: 'forward_log_clear', expect: { '': {} } });
|
||||
var callForwardTest = rpc.declare({ object: 'mu300dash', method: 'forward_test', params: [ 'profile' ], expect: { '': {} } });
|
||||
var callTrafficGet = scopedRpc({ object: 'mu300dash', method: 'traffic_get', expect: { '': {} } });
|
||||
var callTrafficSet = scopedRpc({ object: 'mu300dash', method: 'traffic_set', params: [ 'payload' ], expect: { '': {} } });
|
||||
@@ -496,6 +497,15 @@ var DASH_I18N = {
|
||||
'测试消息': ['Test message', 'Test mesajı'],
|
||||
'仅保留本次开机最近 30 次投递结果,不记录号码、地址或短信内容。': ['Keeps the last 30 delivery results since boot; no numbers, addresses or message content are recorded.', 'Açılıştan bu yana son 30 teslimat sonucu tutulur; numara, adres veya mesaj içeriği kaydedilmez.'],
|
||||
'最近电源通知:': ['Last power notice: ', 'Son güç bildirimi: '],
|
||||
"成功响应条件(可选)": ["Success response condition (optional)", "Başarılı yanıt koşulu (isteğe bağlı)"],
|
||||
"留空时任意 HTTP 2xx 为成功;填写 errcode=0 或 ok=true 时,还需响应 JSON 顶层字段匹配。": ["Empty accepts any HTTP 2xx; errcode=0 or ok=true also checks a top-level JSON field.", "Boşken tüm HTTP 2xx yanıtları başarılıdır; errcode=0 veya ok=true üst düzey JSON alanını da denetler."],
|
||||
"成功响应条件格式无效": ["Invalid success response condition", "Başarılı yanıt koşulu geçersiz"],
|
||||
"服务返回失败结果": ["The service rejected the delivery", "Hizmet gönderimi reddetti"],
|
||||
"服务响应无法确认成功": ["The service response does not confirm success", "Hizmet yanıtı başarıyı doğrulamıyor"],
|
||||
"请等待 5 秒后再测试": ["Please wait 5 seconds before testing again", "Tekrar denemeden önce 5 saniye bekleyin"],
|
||||
"清空投递记录": ["Clear delivery history", "Teslimat geçmişini temizle"],
|
||||
"清空投递记录?": ["Clear delivery history?", "Teslimat geçmişi temizlensin mi?"],
|
||||
"只清除最近投递记录,不影响短信、转发配置或已处理状态。": ["Only clears delivery history; messages, settings and processed state stay unchanged.", "Yalnızca teslimat geçmişini temizler; mesajlar, ayarlar ve işlenen kayıtlar korunur."],
|
||||
'暂无投递': ['No delivery yet', 'Henüz teslimat yok'],
|
||||
'发送成功': ['Sent successfully', 'Başarıyla gönderildi'],
|
||||
'已拦截向原发件人转发': ['Forwarding to original sender blocked', 'Asıl gönderene yönlendirme engellendi'],
|
||||
@@ -1584,7 +1594,7 @@ return baseclass.extend({
|
||||
callSmsDel: callSmsDel, callSmsSync: callSmsSync,
|
||||
callForwardGet: callForwardGet, callForwardStatus: callForwardStatus,
|
||||
callSimGet: callSimGet, simSelector: simSelector, selectedSlot: selectedSlot, selectViewedSlot: selectViewedSlot,
|
||||
callForwardSet: callForwardSet, callForwardTest: callForwardTest,
|
||||
callForwardSet: callForwardSet, callForwardTest: callForwardTest, callForwardClear: callForwardClear,
|
||||
callTrafficGet: callTrafficGet, callTrafficSet: callTrafficSet,
|
||||
callTrafficClear: callTrafficClear,
|
||||
callUsbGet: callUsbGet, callUsbSet: callUsbSet,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* status poll never includes a URL, phone number, password or SMS body. */
|
||||
var METHODS = { webhook: 'Webhook', dingtalk: '钉钉机器人', smtp: '邮件 SMTP', sms: '本机短信' };
|
||||
var RESULTS = {
|
||||
service_rejected: '服务返回失败结果', service_answer_missing: '服务响应无法确认成功',
|
||||
idle: '暂无投递', sent: '发送成功', disabled: '转发未开启',
|
||||
self_forward_blocked: '已拦截向原发件人转发',
|
||||
message_too_long: '短信过长,未发送', storage_failed: '设备保存失败',
|
||||
@@ -16,6 +17,7 @@ var RESULTS = {
|
||||
smtp_auth_failed: '邮箱服务器拒绝登录,请检查授权码'
|
||||
};
|
||||
var ERRORS = {
|
||||
forward_test_wait: '请等待 5 秒后再测试',
|
||||
forward_busy: '转发正在执行,请稍后再试', disabled: '转发未开启',
|
||||
invalid_config: '配置无效', invalid_forward_config: '配置无效',
|
||||
invalid_destination: '目标地址无效', forward_storage_failed: '设备保存失败',
|
||||
@@ -107,6 +109,8 @@ return view.extend({
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-webhook_body">正文模板</label><textarea rows="6" id="mud-fwd-webhook_body" spellcheck="false"></textarea></div>
|
||||
<div class="mud-note">占位符:{from}、{text}、{time}、{sim}、{device}、{kind}。JSON 占位符放在字符串内;按格式自动转义,绝不执行命令。</div>
|
||||
<div class="mud-note">GET 只发送 URL 参数;JSON 模板留空时沿用旧版 from/text/date 格式。仅支持公网 HTTPS,验证证书且不跟随重定向。</div>
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-webhook_expect">成功响应条件(可选)</label><input id="mud-fwd-webhook_expect" maxlength="128" placeholder="errcode=0"></div>
|
||||
<div class="mud-note">留空时任意 HTTP 2xx 为成功;填写 errcode=0 或 ok=true 时,还需响应 JSON 顶层字段匹配。</div>
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-webhook_headers">附加请求头(每行 Name: value)</label><textarea rows="3" id="mud-fwd-webhook_headers" autocomplete="off" spellcheck="false"></textarea></div>
|
||||
</div>
|
||||
<div class="mud-fwd-channel" data-method="dingtalk">
|
||||
@@ -157,6 +161,7 @@ return view.extend({
|
||||
<button class="mud-btn on" id="mud-fwd-save">保存设置</button>
|
||||
<button class="mud-btn" id="mud-fwd-test">发送测试消息</button>
|
||||
<button class="mud-btn" id="mud-fwd-refresh">刷新状态</button>
|
||||
<button class="mud-btn" id="mud-fwd-clear">清空投递记录</button>
|
||||
</div>
|
||||
</section>`;
|
||||
M.localize(root);
|
||||
@@ -199,6 +204,7 @@ return view.extend({
|
||||
this.q('webhook_method').value = c.webhook_method || 'POST';
|
||||
this.q('webhook_content_type').value = c.webhook_content_type || 'application/json';
|
||||
this.q('webhook_timeout').value = c.webhook_timeout || 12;
|
||||
this.q('webhook_expect').value = c.webhook_expect || '';
|
||||
this.q('webhook_body').value = c.webhook_body || '';
|
||||
this.q('webhook_headers').value = c.webhook_headers || '';
|
||||
this.q('preset').value = '';
|
||||
@@ -218,7 +224,7 @@ return view.extend({
|
||||
'smtp_host', 'smtp_port', 'smtp_username', 'smtp_to', 'smtp_password',
|
||||
'blacklist_phone', 'blacklist_keywords', 'nickname' ].forEach(function(k) { p[k] = self.q(k).value.trim(); });
|
||||
[ 'sms_to_phone', 'blacklist_phone', 'blacklist_keywords' ].forEach(function(k) { p[k] = lines(p[k]).join('\n'); });
|
||||
[ 'webhook_method', 'webhook_content_type', 'webhook_timeout', 'webhook_headers', 'webhook_body' ].forEach(function(k) { p[k] = self.q(k).value; });
|
||||
[ 'webhook_method', 'webhook_content_type', 'webhook_timeout', 'webhook_headers', 'webhook_body', 'webhook_expect' ].forEach(function(k) { p[k] = self.q(k).value; });
|
||||
if (p.clear_smtp_password) {
|
||||
p.smtp_host = ''; p.smtp_username = ''; p.smtp_to = ''; p.smtp_password = ''; p.smtp_port = '465';
|
||||
}
|
||||
@@ -230,6 +236,7 @@ return view.extend({
|
||||
if (words.length > 32 || words.some(function(w) { return unescape(encodeURIComponent(w)).length > 128; }) ||
|
||||
new Set(words).size !== words.length) return '关键词无效、重复或超过数量上限';
|
||||
if (p.power_forward_enabled && !this.status.power_supported) return '设备暂未提供有效电池状态';
|
||||
if (p.webhook_expect && !/^[A-Za-z_][A-Za-z0-9_]{0,63}=(-?[0-9]{1,16}|[a-z]{1,16})$/.test(p.webhook_expect)) return '成功响应条件格式无效';
|
||||
if (!/^\d+$/.test(p.webhook_timeout) || +p.webhook_timeout < 1 || +p.webhook_timeout > 120) return '请求超时必须为 1–120 秒';
|
||||
if (p.webhook_body && p.webhook_content_type === 'application/json') {
|
||||
try { JSON.parse(p.webhook_body); } catch (e) { return '正文模板必须是有效 JSON'; }
|
||||
@@ -280,16 +287,27 @@ return view.extend({
|
||||
unload: function() { poll.remove(this._refresh); },
|
||||
wire: function() {
|
||||
var self = this;
|
||||
this.q('clear').onclick = function() {
|
||||
M.confirmBox('清空投递记录?', '只清除最近投递记录,不影响短信、转发配置或已处理状态。', { okText: '确定' }).then(function(yes) {
|
||||
if (!yes) return;
|
||||
self.q('clear').disabled = true;
|
||||
M.callForwardClear().then(function(r) {
|
||||
if (!r.ok) { self.error(r.error || '设备保存失败'); return; }
|
||||
self.error(''); return self.refreshStatus();
|
||||
}).catch(function() { self.error('读取失败,请刷新页面'); }).finally(function() { self.q('clear').disabled = false; });
|
||||
});
|
||||
};
|
||||
this.q('mode').onchange = function() { self.paintMethod(); };
|
||||
this.q('webhook_method').onchange = function() { self.paintMethod(); };
|
||||
this.q('preset').onchange = function() {
|
||||
var p = preset(this.value); if (!p) return;
|
||||
var name = this.value, p = preset(name); if (!p) return;
|
||||
M.confirmBox('填入推送预设?', '将替换当前 Webhook 地址、正文及请求头,保存后才会生效。', { okText: '确定' }).then(function(yes) {
|
||||
if (!yes) return;
|
||||
self.q('webhook_url').value = p[0];
|
||||
self.q('webhook_method').value = 'POST';
|
||||
self.q('webhook_content_type').value = typeof p[1] === 'string' ? 'application/x-www-form-urlencoded' : 'application/json';
|
||||
self.q('webhook_body').value = typeof p[1] === 'string' ? p[1] : JSON.stringify(p[1], null, 2);
|
||||
self.q('webhook_expect').value = ({bark:'code=200',pushplus:'code=200',serverchan:'code=0',telegram:'ok=true',wecom:'errcode=0',dingtalk:'errcode=0'})[name] || '';
|
||||
self.q('webhook_headers').value = ''; self.paintMethod();
|
||||
});
|
||||
};
|
||||
|
||||
@@ -455,6 +455,7 @@ do_list() {
|
||||
"forward_status": { "profile": "String" },
|
||||
"forward_set": { "payload": "String" },
|
||||
"forward_test": { "profile": "String" },
|
||||
"forward_log_clear": { },
|
||||
"traffic_get": { "slot": "String" },
|
||||
"traffic_set": { "payload": "String", "slot": "String" },
|
||||
"traffic_clear": { "confirm": false, "slot": "String" },
|
||||
@@ -536,6 +537,7 @@ call)
|
||||
cpu_apply) inp '@.payload' | "$DASH/cpu" apply ;;
|
||||
cpu_voltage_get) "$DASH/cpu-voltage" get ;;
|
||||
cpu_voltage_save) inp '@.payload' | "$DASH/cpu-voltage" save ;;
|
||||
forward_log_clear) "$DASH/sms-forward" log-clear ;;
|
||||
forward_status) "$DASH/sms-forward" status "$(inp '@.profile' shared)" ;;
|
||||
forward_set)
|
||||
payload=$(inp '@.payload')
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/* PR #211: emit only a finite verdict, never any service response content. */
|
||||
'use strict';
|
||||
import * as fs from 'fs';
|
||||
let rule = getenv('MU300_FORWARD_EXPECT') || '';
|
||||
let valid = match(rule, /^[A-Za-z_][A-Za-z0-9_]{0,63}=(-?[0-9]{1,16}|[a-z]{1,16})$/);
|
||||
let verdict = 'none';
|
||||
try {
|
||||
let raw = fs.readfile(ARGV[0]);
|
||||
if (valid && raw != null && length(raw) <= 4096) {
|
||||
let data = json(raw);
|
||||
let sep = index(rule, '=');
|
||||
let key = substr(rule, 0, sep), wanted = substr(rule, sep + 1);
|
||||
if (type(data) == 'object' && key in data) {
|
||||
let value = data[key];
|
||||
if (type(value) in ['string', 'int', 'double', 'bool'] || value == null)
|
||||
verdict = (type(value) == 'string' ? value : sprintf('%J', value)) == wanted ? 'ok' : 'differs';
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
print(verdict, '\n');
|
||||
@@ -56,6 +56,7 @@ webhook_fields() {
|
||||
json_add_string webhook_body "$webhook_body"
|
||||
json_add_string webhook_headers "$webhook_headers"
|
||||
json_add_int webhook_timeout "$webhook_timeout"
|
||||
json_add_string webhook_expect "$webhook_expect"
|
||||
}
|
||||
render_webhook() { # JSON input, no eval or shell expansion of templates
|
||||
json_init; json_add_object config
|
||||
@@ -158,12 +159,59 @@ list_valid() { # newline-delimited list, max count, kind
|
||||
$1
|
||||
EOF_LIST
|
||||
}
|
||||
# PR #211: optional top-level JSON success rule; no eval or response in logs.
|
||||
answer_rule_valid() {
|
||||
[ -z "$1" ] && return 0
|
||||
[ ${#1} -le 128 ] && one_line "$1" || return 1
|
||||
_answer_key=${1%%=*}; _answer_value=${1#*=}
|
||||
case "$_answer_key" in ''|[0-9]*|*[!A-Za-z0-9_]*) return 1 ;; esac
|
||||
[ ${#_answer_key} -le 64 ] || return 1
|
||||
case "$_answer_value" in
|
||||
''|*=*) return 1 ;;
|
||||
*[!0-9-]*)
|
||||
[ ${#_answer_value} -le 16 ] || return 1
|
||||
case "$_answer_value" in *[!a-z]*) return 1 ;; esac ;;
|
||||
*) _answer_digits=${_answer_value#-}
|
||||
number "$_answer_digits" && [ ${#_answer_digits} -le 16 ] || return 1 ;;
|
||||
esac
|
||||
}
|
||||
answer_check() {
|
||||
_expect=${webhook_expect:-}
|
||||
[ "$method" != dingtalk ] || _expect=errcode=0
|
||||
[ -n "$_expect" ] || return 0
|
||||
answer_rule_valid "$_expect" || { DELIVER_RESULT=invalid_forward_config; return 1; }
|
||||
_verdict=$(MU300_FORWARD_EXPECT="$_expect" ucode "${MU300_FORWARD_ANSWER:-/usr/libexec/unisoc-modem/forward-answer.uc}" "$1" 2>/dev/null) || _verdict=none
|
||||
case "$_verdict" in
|
||||
ok) return 0 ;;
|
||||
differs) DELIVER_RESULT=service_rejected ;;
|
||||
*) DELIVER_RESULT=service_answer_missing ;;
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
clear_history() {
|
||||
ensure_base || { reply_error forward_storage_failed; return; }
|
||||
exec 8> "$BASE/state.lock"
|
||||
flock -n 8 || { reply_error forward_busy; return; }
|
||||
# Only remove the log name: never truncate a symlink's target or touch cursors.
|
||||
rm -f -- "$HISTORY" || { reply_error forward_storage_failed; return; }
|
||||
reply_ok
|
||||
}
|
||||
test_gate() {
|
||||
local uptime idle last=0
|
||||
read -r uptime idle < /proc/uptime || return 1
|
||||
uptime=${uptime%%.*}
|
||||
[ ! -r "$ROOT_RESULT.test-at" ] || read -r last < "$ROOT_RESULT.test-at"
|
||||
number "$last" && number "$uptime" || return 1
|
||||
[ "$uptime" -lt "$last" ] || [ "$last" = 0 ] || [ "$((uptime - last))" -ge 5 ] || return 1
|
||||
printf '%s\n' "$uptime" > "$ROOT_RESULT.test-at"
|
||||
}
|
||||
|
||||
load_config() {
|
||||
enabled=0 method=webhook webhook_url= dingtalk_webhook= dingtalk_secret=
|
||||
sms_to_phone= smtp_host= smtp_port=465 smtp_username= smtp_to= smtp_password=
|
||||
power_forward_enabled=0 blacklist_phone= blacklist_keywords= nickname= template_language=
|
||||
smtp_forward_device_info=0 dingtalk_forward_device_info=0 sms_forward_device_info=0
|
||||
webhook_method=POST webhook_content_type=application/json webhook_body= webhook_headers= webhook_timeout=12
|
||||
webhook_method=POST webhook_content_type=application/json webhook_body= webhook_headers= webhook_timeout=12 webhook_expect=
|
||||
[ -s "$CONFIG" ] || return 0
|
||||
json_load_file "$CONFIG" 2>/dev/null || return 1
|
||||
json_get_vars enabled method webhook_url dingtalk_webhook dingtalk_secret sms_to_phone
|
||||
@@ -176,6 +224,7 @@ load_config() {
|
||||
json_get_var webhook_body webhook_body ''
|
||||
json_get_var webhook_headers webhook_headers ''
|
||||
json_get_var webhook_timeout webhook_timeout 12
|
||||
json_get_var webhook_expect webhook_expect ''
|
||||
}
|
||||
load_state() {
|
||||
last_id=0 since=0 power_percent=-1 power_status=none
|
||||
@@ -221,7 +270,7 @@ write_result() { printf '%s|%s\n' "$1" "$2" > "$RESULT.tmp.$$" && mv -f "$RESULT
|
||||
record_delivery() { # kind only; never store destination, source or message content
|
||||
case "$1" in sms|power|test) ;; *) return 1 ;; esac
|
||||
case "$method" in webhook|dingtalk|smtp|sms) ;; *) return 1 ;; esac
|
||||
case "$DELIVER_RESULT" in sent|disabled|self_forward_blocked|message_too_long|storage_failed|source_unavailable|power_unavailable|invalid_config|invalid_forward_config|invalid_destination|delivery_failed|smtp_auth_failed) ;; *) return 1 ;; esac
|
||||
case "$DELIVER_RESULT" in sent|disabled|self_forward_blocked|message_too_long|storage_failed|source_unavailable|power_unavailable|invalid_config|invalid_forward_config|invalid_destination|delivery_failed|smtp_auth_failed|service_rejected|service_answer_missing) ;; *) return 1 ;; esac
|
||||
# Writers already hold state.lock. Keep 30 small records in RAM, newest first.
|
||||
{
|
||||
printf '%s|%s|%s|%s' "$(date +%s)" "$1" "$method" "$DELIVER_RESULT"
|
||||
@@ -242,7 +291,7 @@ add_history() {
|
||||
number "$_when" && [ ${#_when} -le 11 ] || continue
|
||||
case "$_kind" in sms|power|test) ;; *) continue ;; esac
|
||||
case "$_method" in webhook|dingtalk|smtp|sms) ;; *) continue ;; esac
|
||||
case "$_result" in sent|disabled|self_forward_blocked|message_too_long|storage_failed|source_unavailable|power_unavailable|invalid_config|invalid_forward_config|invalid_destination|delivery_failed|smtp_auth_failed) ;; *) continue ;; esac
|
||||
case "$_result" in sent|disabled|self_forward_blocked|message_too_long|storage_failed|source_unavailable|power_unavailable|invalid_config|invalid_forward_config|invalid_destination|delivery_failed|smtp_auth_failed|service_rejected|service_answer_missing) ;; *) continue ;; esac
|
||||
[ -z "$_extra" ] || continue
|
||||
case "$_slot" in ''|0|1) ;; *) continue ;; esac
|
||||
case "$_http" in ''|0|[1-5][0-9][0-9]) ;; *) continue ;; esac
|
||||
@@ -346,6 +395,7 @@ set_config() {
|
||||
json_get_var new_webhook_body webhook_body ''
|
||||
json_get_var new_webhook_headers webhook_headers ''
|
||||
json_get_var new_webhook_timeout webhook_timeout 12
|
||||
json_get_var new_webhook_expect webhook_expect '__keep__'
|
||||
json_get_var new_enabled enabled
|
||||
json_get_var new_method method
|
||||
json_get_var new_template_language template_language
|
||||
@@ -374,6 +424,7 @@ set_config() {
|
||||
webhook_url=${new_webhook_url:-}; dingtalk_webhook=${new_dingtalk_webhook:-}
|
||||
webhook_method=$new_webhook_method webhook_content_type=$new_webhook_content_type
|
||||
webhook_body=$new_webhook_body webhook_headers=$new_webhook_headers webhook_timeout=$new_webhook_timeout
|
||||
[ "$new_webhook_expect" = __keep__ ] || webhook_expect=$new_webhook_expect
|
||||
sms_to_phone=${new_sms_to_phone:-}; smtp_host=${new_smtp_host:-}
|
||||
smtp_port=${new_smtp_port:-465}; smtp_username=${new_smtp_username:-}; smtp_to=${new_smtp_to:-}
|
||||
power_forward_enabled=${new_power_forward_enabled:-0}
|
||||
@@ -396,6 +447,7 @@ set_config() {
|
||||
case "$method" in webhook|dingtalk|smtp|sms) ;; *) reply_error invalid_config; return ;; esac
|
||||
case "$template_language" in zh|en|tr) ;; *) reply_error invalid_config; return ;; esac
|
||||
[ -z "$webhook_url" ] || https_url "$webhook_url" || { reply_error invalid_destination; return; }
|
||||
answer_rule_valid "$webhook_expect" || { reply_error invalid_forward_config; return; }
|
||||
number "$webhook_timeout" && [ "$webhook_timeout" -ge 1 ] && [ "$webhook_timeout" -le 120 ] &&
|
||||
render_webhook >/dev/null || { reply_error invalid_forward_config; return; }
|
||||
[ -z "$dingtalk_webhook" ] || {
|
||||
@@ -693,8 +745,8 @@ EOF_TARGET
|
||||
HTTP_CODE=$(curl "$@" "$_url" 2>/dev/null)
|
||||
_rc=$?
|
||||
case "$HTTP_CODE" in 2[0-9][0-9]) ;; *) _rc=1 ;; esac
|
||||
if [ "$_rc" -eq 0 ] && [ "$method" = dingtalk ]; then
|
||||
[ "$(jsonfilter -i "$_tmp.reply" -e '@.errcode' 2>/dev/null)" = 0 ] || _rc=1
|
||||
if [ "$_rc" -eq 0 ]; then
|
||||
answer_check "$_tmp.reply" || _rc=1
|
||||
fi
|
||||
rm -f "$_tmp.body" "$_tmp.reply" "$_tmp.headers"
|
||||
fi
|
||||
@@ -885,6 +937,7 @@ start_test() {
|
||||
[ "$enabled" = 1 ] || { reply_error disabled; return; }
|
||||
exec 8> "$BASE/state.lock"
|
||||
flock -n 8 || { reply_error forward_busy; return; }
|
||||
test_gate || { reply_error forward_test_wait; return; }
|
||||
# The child inherits the admission lock; repeated clicks cannot enqueue
|
||||
# an unbounded group of workers or occupy an RPC for a slow HTTP timeout.
|
||||
setsid "$0" test-run "$profile" locked </dev/null >/dev/null 2>&1 &
|
||||
@@ -915,6 +968,7 @@ case "${1:-}" in
|
||||
set) set_config ;;
|
||||
test-run) test_send "${2:-shared}" "${3:-}" ;;
|
||||
test-start) start_test "${2:-shared}" ;;
|
||||
log-clear) clear_history ;;
|
||||
run) run_daemon ;;
|
||||
*) echo 'usage: sms-forward {get|status|set|test-run|run}' >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -5,6 +5,8 @@ set -e
|
||||
A=/opt/mu300/android
|
||||
mark() { [ -x /opt/mu300/bin/bootmark ] && /opt/mu300/bin/bootmark "$@" || true; }
|
||||
mark vendor-start
|
||||
. /opt/mu300/lib/android-import-perms.sh
|
||||
android_import_perms "$A" dev-properties || { echo 'Cannot repair imported Android permissions' >&2; exit 1; }
|
||||
# wait for the modem stack: on the mainline kernel the modules are loaded by userspace (see extra-modules), so
|
||||
# this service can start before /dev/modem exists
|
||||
for n in $(seq 1 90); do
|
||||
@@ -12,7 +14,7 @@ for n in $(seq 1 90); do
|
||||
break
|
||||
done
|
||||
mark vendor-stack-present
|
||||
mkdir -p /dev/socket /dev/block/by-name
|
||||
mkdir -p /dev/socket /dev/block/by-name /var/log
|
||||
# No need to wait for logdw's socket. modem_control is still more than a second away (the chroot mounts, the
|
||||
# node ownership and the cmdline bind all come first), and /dev is rbind-mounted into the chroot, so a socket
|
||||
# that appears late shows up in $A/dev just the same. The old flat "sleep 1" was a second of the boot waiting
|
||||
|
||||
@@ -804,7 +804,8 @@ rollback_boot() {
|
||||
# keeps it from going idle while the update runs (two targets, one of them reachable from mainland China).
|
||||
keepalive_start() {
|
||||
have ping || return 0
|
||||
( while :; do ping -c1 -W2 1.1.1.1 >/dev/null 2>&1 & ping -c1 -W2 223.5.5.5 >/dev/null 2>&1; sleep 3; done ) &
|
||||
# PR #217: children must not keep the upgrade lock after self-update/exit.
|
||||
( while :; do ping -c1 -W2 1.1.1.1 >/dev/null 2>&1 & ping -c1 -W2 223.5.5.5 >/dev/null 2>&1; sleep 3; done ) 9>&- &
|
||||
KEEPALIVE=$!
|
||||
}
|
||||
keepalive_stop() { [ -n "${KEEPALIVE:-}" ] && kill "$KEEPALIVE" 2>/dev/null; KEEPALIVE=; }
|
||||
|
||||
@@ -25,13 +25,25 @@ legacy_throttle=$throttle
|
||||
# frequency control over when every existing CPU cooling device is bound to
|
||||
# the enabled stock zone. Keep our more conservative 105 C shutdown protection.
|
||||
native_cpu_cooling() {
|
||||
local zone mode kind dev link found count=0
|
||||
local zone mode kind dev link found trip value passive=0 count=0
|
||||
[ -d "$R/sys/module/mu300_thermal" ] || return 1
|
||||
for zone in "$R"/sys/class/thermal/thermal_zone*; do
|
||||
read -r kind < "$zone/type" 2>/dev/null || continue
|
||||
[ "$kind" = soc-thmzone ] || continue
|
||||
read -r mode < "$zone/mode" 2>/dev/null || continue
|
||||
[ "$mode" = enabled ] || return 1
|
||||
# PR #190: bindings alone cannot prove that the sensor can throttle.
|
||||
read -r value < "$zone/temp" 2>/dev/null || return 1
|
||||
case $value in ''|*[!0-9]*) return 1 ;; esac
|
||||
[ "$value" -ge "$(( ${1:-0} - 15000 ))" ] || return 1
|
||||
for trip in "$zone"/trip_point_*_type; do
|
||||
read -r kind < "$trip" 2>/dev/null || continue
|
||||
[ "$kind" = passive ] || continue
|
||||
read -r value < "${trip%_type}_temp" 2>/dev/null || continue
|
||||
case $value in ''|*[!0-9]*) continue ;; esac
|
||||
[ "$value" -le "$HOT" ] && passive=1
|
||||
done
|
||||
[ "$passive" = 1 ] || return 1
|
||||
for dev in "$R"/sys/class/thermal/cooling_device*; do
|
||||
read -r kind < "$dev/type" 2>/dev/null || continue
|
||||
case "$kind" in cpufreq-*) ;; *) continue ;; esac
|
||||
@@ -82,24 +94,69 @@ step() {
|
||||
|
||||
# the alarm's state outlives a restart of this service, so a cooled device is never left flashing
|
||||
ALARM=$R/run/mu300/thermal-alarm
|
||||
CAPS=$R/run/mu300/thermal-caps
|
||||
# Remember only limits this guard set, preserving a user's lower ceiling.
|
||||
guard_lower() {
|
||||
local p=$1 current ceiling applied file=$CAPS/${1##*/}
|
||||
read -r current < "$p/scaling_max_freq" || return 1
|
||||
ceiling=$current
|
||||
if [ -r "$file" ]; then
|
||||
IFS='|' read -r ceiling applied < "$file" || ceiling=$current
|
||||
[ "$current" = "$applied" ] || ceiling=$current
|
||||
fi
|
||||
step "$p" -1 || return 0
|
||||
read -r applied < "$p/scaling_max_freq" || return 1
|
||||
mkdir -p "$CAPS" && printf '%s|%s\n' "$ceiling" "$applied" > "$file"
|
||||
}
|
||||
guard_release() {
|
||||
local p=$1 current ceiling applied file=$CAPS/${1##*/}
|
||||
[ -r "$file" ] || return 0
|
||||
IFS='|' read -r ceiling applied < "$file" || return 1
|
||||
read -r current < "$p/scaling_max_freq" || return 1
|
||||
case $ceiling:$applied in *[!0-9:]*|:*|*:) return 1 ;; esac
|
||||
# If another controller/user changed it, that newer choice wins.
|
||||
[ "$current" != "$applied" ] || printf '%s\n' "$ceiling" > "$p/scaling_max_freq" || return 1
|
||||
rm -f "$file"
|
||||
}
|
||||
guard_raise() {
|
||||
local p=$1 current ceiling applied next f file=$CAPS/${1##*/}
|
||||
[ -r "$file" ] || return 0
|
||||
IFS='|' read -r ceiling applied < "$file" || return 1
|
||||
read -r current < "$p/scaling_max_freq" || return 1
|
||||
case $ceiling:$applied in *[!0-9:]*|:*|*:) return 1 ;; esac
|
||||
if [ "$current" != "$applied" ] || [ "$current" -ge "$ceiling" ]; then
|
||||
rm -f "$file"; return 0
|
||||
fi
|
||||
# Keep the previous gradual cool-down recovery, bounded by the user's cap.
|
||||
next=$ceiling
|
||||
for f in $(tr ' ' '\n' < "$p/scaling_available_frequencies" | sort -n); do
|
||||
if [ "$f" -gt "$current" ] && [ "$f" -lt "$next" ]; then next=$f; fi
|
||||
done
|
||||
printf '%s\n' "$next" > "$p/scaling_max_freq" || return 1
|
||||
if [ "$next" = "$ceiling" ]; then rm -f "$file"
|
||||
else printf '%s|%s\n' "$ceiling" "$next" > "$file"; fi
|
||||
}
|
||||
while :; do
|
||||
t=$(hottest)
|
||||
throttle=$legacy_throttle
|
||||
emergency=$legacy_throttle
|
||||
if [ -d "$R/sys/module/mu300_thermal" ]; then
|
||||
throttle=1; emergency=1
|
||||
native_cpu_cooling && throttle=0
|
||||
if native_cpu_cooling "$t"; then
|
||||
throttle=0
|
||||
for p in "$R"/sys/devices/system/cpu/cpufreq/policy*; do guard_release "$p"; done
|
||||
fi
|
||||
fi
|
||||
t=$(hottest)
|
||||
b=$(battery)
|
||||
if [ "$t" -ge "$CRIT" ] && [ "$emergency" = 1 ]; then
|
||||
logger -t thermal-guard "critical temperature ${t} mC, powering off"
|
||||
poweroff
|
||||
elif [ "$t" -ge "$HOT" ] && [ "$throttle" = 1 ]; then
|
||||
for p in "$R"/sys/devices/system/cpu/cpufreq/policy*; do step "$p" -1; done
|
||||
for p in "$R"/sys/devices/system/cpu/cpufreq/policy*; do guard_lower "$p"; done
|
||||
logger -t thermal-guard "hot (${t} mC): lowered cpufreq limits"
|
||||
elif [ "$t" -le "$COOL" ] && [ "$throttle" = 1 ]; then
|
||||
for p in "$R"/sys/devices/system/cpu/cpufreq/policy*; do
|
||||
[ "$(cat $p/scaling_max_freq)" -lt "$(cat $p/cpuinfo_max_freq)" ] && step "$p" 1
|
||||
guard_raise "$p"
|
||||
done
|
||||
fi
|
||||
if [ ! -e "$ALARM" ] && { [ "$t" -ge "$HOT" ] || [ "${b:-0}" -ge "$BATT_HOT" ]; }; then
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
# Adapted from dikeckaan/mu300-linux PR #199 (MIT). Source before vendor startup.
|
||||
# Only imported trees, never dev/proc/sys bind mounts or symlink targets.
|
||||
android_import_perms() {
|
||||
local root=$1 props=$2 owner=${3:-0:0} tree wrong= changed=0
|
||||
[ -d "$root" ] && [ ! -L "$root" ] || return 1
|
||||
for tree in apex system vendor linkerconfig "$props"; do
|
||||
tree="$root/$tree"
|
||||
[ -d "$tree" ] && [ ! -L "$tree" ] || continue
|
||||
wrong=$(find "$tree" -xdev ! -type l \( ! -user "${owner%:*}" -o ! -group "${owner#*:}" \
|
||||
-o -type d ! -perm 755 ! -perm 711 \
|
||||
-o -type f -path '*/bin/*' ! -perm 755 \
|
||||
-o -type f -path "$root/$props/*" ! -perm 444 \
|
||||
-o -type f ! -path '*/bin/*' ! -path "$root/$props/*" ! -perm 644 \) -print) || return 1
|
||||
[ -n "$wrong" ] || continue
|
||||
find "$tree" -xdev ! -type l \( ! -user "${owner%:*}" -o ! -group "${owner#*:}" \) -exec chown "$owner" {} + || return 1
|
||||
find "$tree" -xdev -type d ! -perm 755 ! -perm 711 -exec chmod 755 {} + || return 1
|
||||
find "$tree" -xdev -type f -path '*/bin/*' ! -perm 755 -exec chmod 755 {} + || return 1
|
||||
find "$tree" -xdev -type f -path "$root/$props/*" ! -perm 444 -exec chmod 444 {} + || return 1
|
||||
find "$tree" -xdev -type f ! -path '*/bin/*' ! -path "$root/$props/*" ! -perm 644 -exec chmod 644 {} + || return 1
|
||||
changed=1
|
||||
done
|
||||
[ "$changed" = 0 ] || echo 'Imported Android file permissions repaired' >&2
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Forwarding UI: SIM profiles, drafts, localization, bounded history; mocked RPC."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
WEB=Path(os.environ.get('FORWARD_WEB_ROOT', ROOT/'openwrt/luci-app-mu300/htdocs/luci-static/resources'))
|
||||
|
||||
|
||||
def main():
|
||||
with sync_playwright() as p:
|
||||
browser=p.chromium.launch(executable_path='C:/Program Files/Google/Chrome/Application/chrome.exe')
|
||||
page=browser.new_page(viewport={'width':390,'height':844})
|
||||
errors=[];page.on('pageerror',lambda e:errors.append(str(e)))
|
||||
page.set_content('<html lang="zh"><style>*{box-sizing:border-box}body{margin:12px}</style></html>')
|
||||
page.evaluate('''([common,source])=>{
|
||||
window.L={env:{lang:'zh'},resolveDefault:(p,d)=>Promise.resolve(p).catch(()=>d)};
|
||||
window.calls=[];window.configs={};window.mode='shared';window.historyCleared=false;
|
||||
for(const profile of ['shared','sim0','sim1']) configs[profile]={enabled:1,method:'webhook',template_language:'en',webhook_url:'https://example.com/'+profile,webhook_method:'POST',webhook_content_type:'application/json',webhook_timeout:12,smtp:{port:465,password_configured:true}};
|
||||
window.state=(profile='shared')=>({profile,mode,sim_slots:2,config:configs[profile],status:{enabled:true,method:'webhook',power_supported:true,history:historyCleared?[]:Array.from({length:30},(_,i)=>({time:1700000000+i,kind:'sms',slot:i%2,method:'webhook',result:'sent',http_code:200}))}});
|
||||
const rpc={declare:s=>(...args)=>{
|
||||
calls.push({method:s.method,args});
|
||||
if(s.method==='forward_log_clear')historyCleared=true;
|
||||
if(s.method==='forward_get'||s.method==='forward_status')return Promise.resolve(state(args[0]));
|
||||
if(s.method==='forward_set'){const value=JSON.parse(args[0]);configs[value.profile]={...configs[value.profile],...value};mode=value.mode;}
|
||||
return Promise.resolve({ok:1});
|
||||
}};
|
||||
const M=new Function('rpc','baseclass',common)(rpc,{extend:x=>x});M.localizeMenu=()=>{};
|
||||
window.fwd=new Function('view','poll','M',source)({extend:x=>x},{add:f=>window.tick=f},M);
|
||||
document.body.append(fwd.render(state()));
|
||||
}''',[(WEB/'mu300/common.js').read_text(encoding='utf-8'),(WEB/'view/mu300/forward.js').read_text(encoding='utf-8')])
|
||||
assert page.locator('#mud-fwd-history').evaluate('(el)=>el.scrollHeight>el.clientHeight')
|
||||
assert page.locator('#mud-fwd-history .mud-fwd-event').count()==30
|
||||
page.locator('#mud-fwd-clear').click()
|
||||
page.get_by_role('dialog').get_by_role('button',name='取消',exact=True).click()
|
||||
assert not page.evaluate('calls.some(c=>c.method==="forward_log_clear")')
|
||||
page.locator('#mud-fwd-clear').click()
|
||||
page.get_by_role('dialog').get_by_role('button',name='确定',exact=True).click()
|
||||
page.wait_for_function('historyCleared')
|
||||
page.wait_for_function("!document.querySelector('#mud-fwd-history .mud-fwd-event')")
|
||||
assert not page.evaluate('calls.some(c=>c.method==="forward_set")')
|
||||
page.locator('#mud-fwd-webhook_url').fill('https://example.com/draft')
|
||||
page.evaluate('()=>tick()')
|
||||
assert page.locator('#mud-fwd-webhook_url').input_value().endswith('/draft')
|
||||
page.locator('#mud-fwd-test').click()
|
||||
assert not page.evaluate('calls.some(c=>c.method==="forward_test")')
|
||||
page.locator('#mud-fwd-profile').select_option('sim1')
|
||||
page.get_by_role('dialog').get_by_role('button',name='确定',exact=True).click()
|
||||
page.wait_for_function("fwd.profile==='sim1'")
|
||||
assert page.locator('#mud-fwd-webhook_url').input_value().endswith('/sim1')
|
||||
page.locator('#mud-fwd-mode').select_option('per_sim')
|
||||
page.locator('#mud-fwd-webhook_expect').fill('ok=true')
|
||||
page.locator('#mud-fwd-save').click()
|
||||
page.get_by_role('dialog').get_by_role('button',name='保存',exact=True).click()
|
||||
page.wait_for_function("calls.some(c=>c.method==='forward_set')&&!fwd.q('save').disabled")
|
||||
saved=page.evaluate("JSON.parse(calls.find(c=>c.method==='forward_set').args[0])")
|
||||
assert saved['profile']=='sim1' and saved['mode']=='per_sim'
|
||||
assert saved['webhook_expect']=='ok=true'
|
||||
for language in ['en','tr']:
|
||||
page.evaluate("lang=>{L.env.lang=lang;document.documentElement.lang=lang;fwd.root.remove();document.body.append(fwd.render(state('sim1')))}",language)
|
||||
untranslated=page.evaluate(r"fwd.root.innerText.split('\n').filter(s=>/[\u3400-\u9fff]/.test(s))")
|
||||
assert not untranslated,(language,untranslated)
|
||||
for width in [390,1280]:
|
||||
page.set_viewport_size({'width':width,'height':900})
|
||||
assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
|
||||
assert not errors,errors
|
||||
browser.close()
|
||||
print('PASS: profile switching and saves, unsaved test guard, polling preserves drafts, history scroll, en/tr, mobile and desktop')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/bin/sh
|
||||
# Real OpenWrt JSON/ucode backend; private fixtures and fake HTTPS only.
|
||||
set -e
|
||||
source=$1
|
||||
base=$(mktemp -d /tmp/forward-answer.XXXXXX)
|
||||
trap 'rm -rf "$base"' EXIT
|
||||
export MU300_FORWARD_DIR=$base/config MU300_FORWARD_RESULT=$base/result MU300_FORWARD_RUNTIME=$base
|
||||
export MU300_SMS_POOL=$base/pool
|
||||
export MU300_FORWARD_RENDERER=${source%/*}/forward-template.uc MU300_FORWARD_ANSWER=${source%/*}/forward-answer.uc
|
||||
mkdir -p "$base/config"
|
||||
mkdir -p "$base/pool/msg" "$base/pool/sim1/msg"
|
||||
printf '0\n' > "$base/pool/next_id"
|
||||
printf '0\n' > "$base/pool/sim1/next_id"
|
||||
sed '/^case "${1:-}" in/,$d' "$source" > "$base/lib.sh"
|
||||
set +e
|
||||
. "$base/lib.sh"
|
||||
set -e
|
||||
fail() { echo "FAIL: $*" >&2; exit 1; }
|
||||
uci() { echo 2; }
|
||||
resolve_public() { RESOLVE=example.com:443:8.8.8.8; PICKED_IP=8.8.8.8; }
|
||||
curl() {
|
||||
while [ "$#" -gt 0 ]; do
|
||||
if [ "$1" = -o ]; then shift; printf '%s' "$ANSWER" > "$1"; fi
|
||||
shift
|
||||
done
|
||||
printf 200
|
||||
}
|
||||
set_profile() {
|
||||
_r=$(printf '%s' "$1" | set_config)
|
||||
[ "$(printf '%s' "$_r" | jsonfilter -e '@.ok')" = 1 ] || fail "config $_r"
|
||||
load_config
|
||||
}
|
||||
# Legacy saved profiles have no success rule and must remain readable.
|
||||
printf '%s' '{"enabled":1,"method":"webhook","webhook_url":"https://example.com/hook"}' > "$CONFIG"
|
||||
load_config || fail 'legacy profile unreadable'
|
||||
[ -z "$webhook_expect" ] || fail 'legacy rule not empty'
|
||||
set_profile '{"enabled":1,"method":"webhook","webhook_url":"https://example.com/hook","template_language":"en","webhook_expect":"errcode=0"}'
|
||||
get_view > "$base/view"
|
||||
[ "$(jsonfilter -i "$base/view" -e '@.config.webhook_expect')" = errcode=0 ] || fail 'get rule'
|
||||
set_profile '{"enabled":1,"method":"webhook","webhook_url":"https://example.com/hook","template_language":"en"}'
|
||||
[ "$webhook_expect" = errcode=0 ] || fail 'older editor erased rule'
|
||||
ANSWER='{"errcode":0}'; deliver test NMS '' || fail 'success rejected'
|
||||
ANSWER='{"errcode":400,"message":"PRIVATE_RESPONSE"}'
|
||||
if deliver test NMS ''; then fail 'HTTP 200 service refusal accepted'; fi
|
||||
[ "$DELIVER_RESULT" = service_rejected ] || fail 'rejection result'
|
||||
ANSWER='{"nested":{"errcode":0}}'
|
||||
if deliver test NMS ''; then fail 'nested key accepted'; fi
|
||||
[ "$DELIVER_RESULT" = service_answer_missing ] || fail 'missing result'
|
||||
for ANSWER in '[]' 'not JSON' '{"errcode":[]}' '{"errcode":{"value":0}}' ''; do
|
||||
if deliver test NMS ''; then fail 'invalid reply accepted'; fi
|
||||
done
|
||||
webhook_expect=ok=true
|
||||
ANSWER='{"ok":true}'; deliver test NMS '' || fail 'boolean success'
|
||||
ANSWER='{"ok":false}'; if deliver test NMS ''; then fail 'boolean refusal'; fi
|
||||
webhook_expect=errcode=0
|
||||
ANSWER='{"errcode":"0"}'; deliver test NMS '' || fail 'string success'
|
||||
ANSWER=$(printf '%4100s' ' ')
|
||||
if deliver test NMS ''; then fail 'oversize body accepted'; fi
|
||||
webhook_expect=
|
||||
ANSWER='not JSON'; deliver test NMS '' || fail 'legacy HTTP-only behavior changed'
|
||||
method=dingtalk; dingtalk_webhook='https://oapi.dingtalk.com/robot/send?access_token=TEST'; dingtalk_secret=
|
||||
ANSWER='{"errcode":1}'; if deliver test NMS ''; then fail 'DingTalk regression'; fi
|
||||
ANSWER='{"errcode":0}'; deliver test NMS '' || fail 'DingTalk success'
|
||||
for rule in 'bad key=0' 'errcode=$(reboot)' 'errcode=0;reboot' 'x=' '=0' 'x=12345678901234567' 'x=-' 'x=--1'; do
|
||||
if answer_rule_valid "$rule"; then fail 'unsafe rule accepted'; fi
|
||||
done
|
||||
# Clear only the history name, never a link target, config or processing cursor.
|
||||
printf 'original\n' > "$base/untouched"
|
||||
ln -s "$base/untouched" "$HISTORY"
|
||||
printf 'cursor\n' > "$STATE"
|
||||
before=$(sha256sum "$CONFIG" "$STATE")
|
||||
clear_history > "$base/clear"
|
||||
[ "$(jsonfilter -i "$base/clear" -e '@.ok')" = 1 ] || fail 'clear result'
|
||||
[ ! -L "$HISTORY" ] && [ "$(cat "$base/untouched")" = original ] || fail 'clear followed link'
|
||||
[ "$before" = "$(sha256sum "$CONFIG" "$STATE")" ] || fail 'clear changed state'
|
||||
test_gate || fail 'first test gate'
|
||||
if test_gate; then fail 'rapid duplicate test allowed'; fi
|
||||
printf 'PASS: rule persistence, real JSON scalar checks, private finite results, HTTP-only compatibility, DingTalk, unsafe input, clear isolation and test throttle\n'
|
||||
@@ -7,6 +7,7 @@ export MU300_FORWARD_DIR=$base/config MU300_SMS_POOL=$base/pool MU300_FORWARD_RE
|
||||
export MU300_FORWARD_BATTERY=$base/battery MU300_SMS_BIN=/bin/false
|
||||
export MU300_FORWARD_RUNTIME=$base
|
||||
export MU300_FORWARD_RENDERER=${source%/*}/forward-template.uc
|
||||
export MU300_FORWARD_ANSWER=${source%/*}/forward-answer.uc
|
||||
mkdir -p "$base/config" "$base/pool/msg" "$base/pool/sim1/msg"
|
||||
printf '0\n' > "$base/pool/next_id"
|
||||
printf '0\n' > "$base/pool/sim1/next_id"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Fail closed when KVM is only requested, or optional modules never get shipped."""
|
||||
import hashlib
|
||||
import gzip
|
||||
import importlib.util
|
||||
import io
|
||||
import tarfile
|
||||
@@ -24,6 +25,9 @@ class ContainerSupport(unittest.TestCase):
|
||||
(self.out / name).write_bytes(b'builtin metadata')
|
||||
self.config = {key: 'y' for key in support.BUILTIN}
|
||||
self.config.update({key: 'm' for key in support.MODULES})
|
||||
import re
|
||||
fragment = (TOP/'upstream/mu300-mainline.config').read_text()
|
||||
self.config.update({k.removeprefix('CONFIG_'):v for k,v in re.findall(r'^(CONFIG_\w+)=(.*)$', fragment[fragment.index('# Adapted from MU300 PR #228'):], re.M)})
|
||||
(self.out / 'Image').write_bytes(b'Linux version 6.18.54 test Image')
|
||||
for name in support.MODULES.values():
|
||||
(self.out / 'modules' / f'{name}.ko').write_bytes(name.encode() + b'\0vermagic=6.18.54 SMP\0')
|
||||
@@ -33,7 +37,9 @@ class ContainerSupport(unittest.TestCase):
|
||||
self.manifests()
|
||||
|
||||
def write_config(self):
|
||||
(self.out / 'kernel.config').write_text(''.join(f'CONFIG_{k}={v}\n' for k, v in self.config.items()))
|
||||
config = ''.join(f'CONFIG_{k}={v}\n' for k, v in self.config.items())
|
||||
(self.out / 'kernel.config').write_text(config)
|
||||
(self.out / 'Image').write_bytes(b'Linux version 6.18.54 test Image' + b'IKCFG_ST' + gzip.compress(config.encode()) + b'IKCFG_ED')
|
||||
|
||||
def manifests(self):
|
||||
for manifest, names in [('kernel.sha256', ['Image', 'kernel.config']),
|
||||
|
||||
@@ -379,7 +379,7 @@ class ThermalGuard(ShellTest):
|
||||
z.mkdir(parents=True, exist_ok=True)
|
||||
(z / 'temp').write_text(f'{soc}\n')
|
||||
if trips:
|
||||
(z / 'trip_point_0_temp').write_text('95000\n')
|
||||
(z / 'trip_point_0_temp').write_text('85000\n')
|
||||
if battery is not None:
|
||||
b = self.root / 'sys/class/power_supply/battery'
|
||||
b.mkdir(parents=True, exist_ok=True)
|
||||
@@ -423,6 +423,24 @@ class ThermalGuard(ShellTest):
|
||||
self.device('u30air')
|
||||
self.assertEqual(self.round(shell, 110000), ['poweroff', 'mu300-led alarm on']) # mainline: critical
|
||||
|
||||
def test_guard_recovery_keeps_user_ceiling_and_external_changes(self):
|
||||
for shell in self.each_shell():
|
||||
shutil.rmtree(self.root, ignore_errors=True)
|
||||
self.device('f50')
|
||||
p=self.root/'sys/devices/system/cpu/cpufreq/policy0'
|
||||
p.mkdir(parents=True)
|
||||
(p/'scaling_available_frequencies').write_text('400000 800000 1200000\n')
|
||||
(p/'scaling_max_freq').write_text('800000\n')
|
||||
(p/'cpuinfo_max_freq').write_text('1200000\n')
|
||||
self.round(shell,86000)
|
||||
self.assertEqual((p/'scaling_max_freq').read_text().strip(),'400000')
|
||||
self.round(shell,40000)
|
||||
self.assertEqual((p/'scaling_max_freq').read_text().strip(),'800000')
|
||||
self.round(shell,86000)
|
||||
(p/'scaling_max_freq').write_text('1200000\n')
|
||||
self.round(shell,40000)
|
||||
self.assertEqual((p/'scaling_max_freq').read_text().strip(),'1200000')
|
||||
|
||||
def test_mainline_native_cooling_keeps_emergency_and_user_caps(self):
|
||||
for shell in self.each_shell():
|
||||
shutil.rmtree(self.root, ignore_errors=True)
|
||||
@@ -432,6 +450,7 @@ class ThermalGuard(ShellTest):
|
||||
z.mkdir(parents=True)
|
||||
(z / 'type').write_text('soc-thmzone\n')
|
||||
(z / 'mode').write_text('enabled\n')
|
||||
(z / 'trip_point_0_type').write_text('passive\n')
|
||||
c = z.parent / 'cooling_device0'
|
||||
c.mkdir()
|
||||
(c / 'type').write_text('cpufreq-cpu0\n')
|
||||
@@ -607,6 +626,7 @@ elif op.startswith('w'):
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_v50_uses_its_stock_reset_pin_and_read_only_discovery(self):
|
||||
(self.root/'proc/device-tree/soc/ap-ahb/i2c@2270000/aw9523b_led@5b').mkdir(parents=True)
|
||||
node=self.root/'proc/device-tree/ntag_fm11_gpio';node.mkdir(parents=True)
|
||||
(node/'ntag-reset-gpio').write_bytes(bytes.fromhex('00000018000000bd00000000'))
|
||||
for shell in self.each_shell():
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the actual SDHCI MMIO callbacks and check their DMA/API contract.
|
||||
|
||||
Run on Linux with a prepared kernel tree; temporary copies are patched, never the
|
||||
supplied tree. Also exercises upgrade from cached relaxed accessors and idempotence.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import argparse, re, runpy, shutil, subprocess, tempfile
|
||||
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('kernel',type=Path)
|
||||
parser.add_argument('--adapter',type=Path,default=Path(__file__).resolve().parents[1]/'upstream/port/emmc.py')
|
||||
parser.add_argument('--legacy-patch',type=Path,help='exercise the vendor 5.4 patch instead of the mainline adapter')
|
||||
args=parser.parse_args()
|
||||
if args.legacy_patch:
|
||||
def apply(root):
|
||||
patch=str(args.legacy_patch.resolve())
|
||||
cmd=['patch','--batch','--force','--fuzz=0','-p1','-d',str(root),'-i',patch]
|
||||
if subprocess.run(cmd+['--reverse','--dry-run'],capture_output=True).returncode==0:return
|
||||
subprocess.run(cmd+['--forward','--dry-run'],check=True,capture_output=True)
|
||||
subprocess.run(cmd+['--forward'],check=True,capture_output=True)
|
||||
else:
|
||||
apply=runpy.run_path(str(args.adapter))['apply']
|
||||
paths=['include/linux/mmc/host.h','drivers/mmc/core/block.c',
|
||||
'drivers/mmc/core/mmc.c','drivers/mmc/host/sdhci-sprd.c']
|
||||
with tempfile.TemporaryDirectory(prefix='mmc-dma-contract-') as tmp:
|
||||
root=Path(tmp)
|
||||
for name in paths:
|
||||
dest=root/name;dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(args.kernel/name,dest)
|
||||
apply(root)
|
||||
before={name:(root/name).read_bytes() for name in paths};apply(root)
|
||||
assert before=={name:(root/name).read_bytes() for name in paths},'adapter is not idempotent'
|
||||
source=(root/paths[-1]).read_text()
|
||||
a=source.index('static inline u32 sdhci_sprd_readl(');b=source.index('static inline void sdhci_sprd_sd_clk_off(',a)
|
||||
callbacks=source[a:b]
|
||||
# A reused build tree must receive the fix too, not just fresh checkouts.
|
||||
old=callbacks.replace('\t/* Shared SDHCI policy: order ADMA descriptors and DMA completion. */\n','')
|
||||
old=old.replace('return readl(', 'return readl_relaxed(')
|
||||
for width in ('b','w','l'):old=re.sub(r'\bwrite'+width+r'\(', 'write'+width+'_relaxed(',old)
|
||||
(root/paths[-1]).write_text(source[:a]+old+source[b:]);apply(root)
|
||||
repaired=(root/paths[-1]).read_text()
|
||||
assert 'return readl(host->ioaddr + reg);' in repaired
|
||||
a=repaired.index('static inline u32 sdhci_sprd_readl(');b=repaired.index('static inline void sdhci_sprd_sd_clk_off(',a)
|
||||
callbacks=repaired[a:b]
|
||||
prelude=r'''
|
||||
#include <stdint.h>
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
typedef uint32_t u32; typedef uint16_t u16; typedef uint8_t u8; typedef uint64_t u64;
|
||||
#define unlikely(x) (x)
|
||||
#define SDHCI_MAX_CURRENT 0x48
|
||||
#define SDHCI_SPRD_MAX_CUR 0xffffff
|
||||
#define SDHCI_SIGNAL_ENABLE 0x38
|
||||
#define SDHCI_INT_ENABLE 0x34
|
||||
#define SDHCI_SPRD_INT_SIGNAL_MASK 0x027f000b
|
||||
#define SDHCI_BLOCK_COUNT 0x06
|
||||
#define SDHCI_SOFTWARE_RESET 0x2f
|
||||
#define SDHCI_HW_RESET_CARD 0x08
|
||||
#define SDHCI_COMMAND 0x0e
|
||||
#define SDHCI_INT_STATUS 0x30
|
||||
#define SDHCI_INT_TIMEOUT 0x10000
|
||||
#define SDHCI_INT_DATA_TIMEOUT 0x100000
|
||||
#define SDHCI_INT_DATA_END_BIT 0x400000
|
||||
#define SDHCI_INT_DATA_END 0x02
|
||||
#define SDHCI_INT_CMD_MASK 0x10001
|
||||
#define SDHCI_RESET_DATA 0x04
|
||||
#define cpu_relax() ((void)0)
|
||||
static int writes, ordered_write, ordered_read;
|
||||
struct mmc_data { int error; };
|
||||
struct sdhci_sprd_host { u32 int_status; struct mmc_data *data; };
|
||||
struct sdhci_host { unsigned char *ioaddr; void *cmd; struct sdhci_sprd_host *sprd; };
|
||||
#define TO_SPRD_HOST(host) ((host)->sprd)
|
||||
static u32 load(void *p,int n,int ordered){u32 v=0;memcpy(&v,p,n);ordered_read+=ordered;return v;}
|
||||
static void store(u32 v,void *p,int n,int ordered){memcpy(p,&v,n);writes++;ordered_write+=ordered;}
|
||||
#define readl(p) load(p,4,1)
|
||||
#define readl_relaxed(p) load(p,4,0)
|
||||
#define readb_relaxed(p) load(p,1,0)
|
||||
#define writel(v,p) store(v,p,4,1)
|
||||
#define writew(v,p) store(v,p,2,1)
|
||||
#define writeb(v,p) store(v,p,1,1)
|
||||
#define writel_relaxed(v,p) store(v,p,4,0)
|
||||
#define writew_relaxed(v,p) store(v,p,2,0)
|
||||
#define writeb_relaxed(v,p) store(v,p,1,0)
|
||||
'''
|
||||
cases=r'''
|
||||
int main(void){
|
||||
unsigned char regs[256]={0};struct sdhci_sprd_host sprd={0};
|
||||
struct sdhci_host h={.ioaddr=regs,.sprd=&sprd};
|
||||
assert(sdhci_sprd_readl(&h,SDHCI_MAX_CURRENT)==SDHCI_SPRD_MAX_CUR);
|
||||
assert(!ordered_read);
|
||||
sdhci_sprd_writel(&h,123,SDHCI_MAX_CURRENT);assert(!writes);
|
||||
sdhci_sprd_writew(&h,123,SDHCI_BLOCK_COUNT);assert(!writes);
|
||||
sdhci_sprd_writel(&h,0xffffffff,SDHCI_INT_ENABLE);
|
||||
assert(load(regs+SDHCI_INT_ENABLE,4,0)==SDHCI_SPRD_INT_SIGNAL_MASK);
|
||||
assert(ordered_write==1);
|
||||
sdhci_sprd_writew(&h,0x193a,SDHCI_COMMAND);
|
||||
assert(load(regs+SDHCI_COMMAND,2,0)==0x193a && ordered_write==2);
|
||||
sdhci_sprd_readl(&h,SDHCI_INT_STATUS);assert(ordered_read==1);
|
||||
regs[SDHCI_SOFTWARE_RESET]=SDHCI_HW_RESET_CARD;
|
||||
sdhci_sprd_writeb(&h,1,SDHCI_SOFTWARE_RESET);
|
||||
assert(regs[SDHCI_SOFTWARE_RESET]==9 && ordered_write==3);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
c=root/'contract.c';c.write_text(prelude+callbacks+cases)
|
||||
exe=root/'contract';subprocess.run(['cc','-Wall','-Werror','-O2',str(c),'-o',str(exe)],check=True)
|
||||
subprocess.run([str(exe)],check=True)
|
||||
# Missing anchors must fail closed rather than publish a partially fixed tree.
|
||||
broken=(root/paths[-1]).read_text().replace('return readl(host->ioaddr + reg);','return readl_relaxed(host->ioaddr + reg);')
|
||||
(root/paths[-1]).write_text(broken)
|
||||
try:apply(root)
|
||||
except (ValueError,subprocess.CalledProcessError):pass
|
||||
else:raise AssertionError('partially modified callbacks accepted')
|
||||
print('PASS: ordered DMA submission/completion, reserved registers, IRQ mask, reset bit, cached upgrade, idempotence and fail-closed checks')
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Behavior regressions for the six reviewed upstream fixes; no real device I/O."""
|
||||
import gzip
|
||||
import io
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import tarfile
|
||||
import unittest
|
||||
|
||||
TOP = Path(__file__).resolve().parents[1]
|
||||
E5 = (TOP / 'devices/common/eic.py').exists()
|
||||
|
||||
|
||||
def module(path):
|
||||
spec = importlib.util.spec_from_file_location(path.stem.replace('-', '_'), path)
|
||||
result = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(result)
|
||||
return result
|
||||
|
||||
|
||||
class UpstreamRegressions(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
|
||||
@unittest.skipUnless(shutil.which('bash'), 'needs POSIX shell')
|
||||
def test_import_permissions_and_symlink_targets(self):
|
||||
helper = TOP / ('rootfs/overlay/opt/e5/android-import-perms.sh' if E5 else
|
||||
'rootfs/overlay/opt/mu300/lib/android-import-perms.sh')
|
||||
props = 'dev/__properties__' if E5 else 'dev-properties'
|
||||
root = self.root / 'android'
|
||||
for name in ['vendor/bin/modem_control', 'vendor/etc/modem.xml', props+'/property_info', 'linkerconfig/ld.config.txt']:
|
||||
p=root/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_text('fixture');p.chmod(0o700)
|
||||
for p in root.rglob('*'):
|
||||
if p.is_dir():p.chmod(0o700)
|
||||
outside=self.root/'outside';outside.write_text('keep');outside.chmod(0o600)
|
||||
(root/'vendor/alias').symlink_to(outside)
|
||||
owner=f'{os.getuid()}:{os.getgid()}'
|
||||
for shell in ['dash','bash','busybox']:
|
||||
if not shutil.which(shell):continue
|
||||
argv=[shell]+(['sh'] if shell=='busybox' else [])
|
||||
code='. "$1"; android_import_perms "$2" "$3" "$4"'
|
||||
r=subprocess.run(argv+['-c',code,'test',str(helper),str(root),props,owner],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
self.assertEqual((root/'vendor/bin/modem_control').stat().st_mode & 0o777,0o755)
|
||||
self.assertEqual((root/'vendor/etc/modem.xml').stat().st_mode & 0o777,0o644)
|
||||
self.assertEqual((root/props/'property_info').stat().st_mode & 0o777,0o444)
|
||||
self.assertEqual(outside.stat().st_mode & 0o777,0o600)
|
||||
# Healthy boots do no ownership/mode writes.
|
||||
r=subprocess.run(argv+['-c',code.replace('; android_import', '; chmod() { exit 91; }; chown() { exit 92; }; android_import'),
|
||||
'test',str(helper),str(root),props,owner],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
|
||||
def test_embedded_config_and_full_inventory(self):
|
||||
audit=module(TOP/'upstream/audit-bundle.py')
|
||||
(self.root/'modules').mkdir()
|
||||
cfg='CONFIG_KVM=y\nCONFIG_VIRTIO_NET=m\n'
|
||||
(self.root/'config').write_text(cfg)
|
||||
(self.root/'Image').write_bytes(b'ImageIKCFG_ST'+gzip.compress(cfg.encode())+b'IKCFG_ED')
|
||||
(self.root/'modules.in-tree').write_text('virtio_net.ko\n')
|
||||
(self.root/'modules/virtio_net.ko').write_bytes(b'module')
|
||||
audit.audit(self.root,'config')
|
||||
(self.root/'config').write_text(cfg.replace('KVM=y','KVM=n'))
|
||||
with self.assertRaisesRegex(ValueError,'embedded configuration'):audit.audit(self.root,'config')
|
||||
(self.root/'config').write_text(cfg)
|
||||
(self.root/'modules/virtio_net.ko').unlink()
|
||||
with self.assertRaisesRegex(ValueError,'Missing in-tree'):audit.audit(self.root,'config')
|
||||
(self.root/'modules.in-tree').write_text('../outside.ko\n')
|
||||
with self.assertRaisesRegex(ValueError,'Invalid module'):audit.audit(self.root,'config')
|
||||
(self.root/'Image').write_bytes(b'no config')
|
||||
with self.assertRaisesRegex(ValueError,'no embedded'):audit.audit(self.root,'config')
|
||||
|
||||
def test_vendor_archive_modes_ignore_host_filesystem(self):
|
||||
if E5:self.skipTest('E5 packages imported files on Android itself')
|
||||
overlay=module(TOP/'tools/vendor-overlay.py')
|
||||
src=self.root/'subset';src.mkdir()
|
||||
for name in ['vendor/bin/modem_control','vendor/etc/modem.xml','dev-properties/property_info']:
|
||||
p=src/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(b'data');p.chmod(0o700)
|
||||
data=io.BytesIO()
|
||||
with tarfile.open(fileobj=data,mode='w') as tar:overlay.add_tree(tar,src,'opt/mu300/android',set())
|
||||
data.seek(0)
|
||||
with tarfile.open(fileobj=data) as tar:
|
||||
modes={m.name:m.mode for m in tar}
|
||||
self.assertEqual(modes['opt/mu300/android/vendor/bin/modem_control'],0o755)
|
||||
self.assertEqual(modes['opt/mu300/android/vendor/etc/modem.xml'],0o644)
|
||||
self.assertEqual(modes['opt/mu300/android/dev-properties/property_info'],0o444)
|
||||
|
||||
@unittest.skipUnless(shutil.which('cc'), 'needs host C compiler')
|
||||
def test_e5_factory_virtual_sensor_adapter(self):
|
||||
if not E5:self.skipTest('MU300 has a separate virtual sensor module')
|
||||
adapter=module(TOP/'devices/common/thermal.py')
|
||||
# Pinned E5 factory callback shape, including its last-returned error.
|
||||
original='''static int virtual_thm_get_temp(struct thermal_zone_device *tzd, int *temp)
|
||||
{
|
||||
void *devdata = thermal_zone_device_priv(tzd);
|
||||
int i, ret = 0, max_temp = INT_MIN;
|
||||
struct thermal_zone_device *tz;
|
||||
struct real_tz_list *tz_list;
|
||||
struct virtual_thm_data *thm_data = devdata;
|
||||
struct device *dev = thm_data->vir_thm->dev;
|
||||
for (i = 0; i < thm_data->nr_thm; i++) {
|
||||
tz_list = &thm_data->tz_list[i]; tz = tz_list->tz_dev;
|
||||
\t\tif (!tz || IS_ERR(tz))
|
||||
\t\t\treturn -EINVAL;
|
||||
ret = thermal_zone_get_temp(tz, &tz_list->temp);
|
||||
if (ret) {
|
||||
\t\t\tdev_err(dev, "fail to get temp\\n");
|
||||
\t\t\treturn ret;
|
||||
}
|
||||
max_temp = max(max_temp, tz_list->temp);
|
||||
}
|
||||
\t*temp = max_temp;
|
||||
\treturn ret;
|
||||
}
|
||||
static void virtual_thm_unregister(void) {}
|
||||
'''
|
||||
adapted=adapter.adapt(original)
|
||||
self.assertEqual(adapter.adapt(adapted),adapted)
|
||||
callback=adapted[:adapted.index('\nstatic void')]
|
||||
prelude='''#include <limits.h>
|
||||
#include <errno.h>
|
||||
struct device {int dummy;};
|
||||
struct thermal_zone_device {void *priv; int value,err;};
|
||||
struct real_tz_list {struct thermal_zone_device *tz_dev;int temp;};
|
||||
struct virtual_thm {struct device *dev;};
|
||||
struct virtual_thm_data {int nr_thm;struct real_tz_list *tz_list;struct virtual_thm *vir_thm;};
|
||||
#define thermal_zone_device_priv(tz) ((tz)->priv)
|
||||
#define IS_ERR(tz) ((tz)==(void*)-1)
|
||||
#define max(a,b) ((a)>(b)?(a):(b))
|
||||
#define dev_err_ratelimited(dev,fmt) ((void)(dev))
|
||||
int thermal_zone_get_temp(struct thermal_zone_device *s,int *v){*v=s->value;return s->err;}
|
||||
'''
|
||||
test='''int main(void){
|
||||
struct thermal_zone_device a={0,94000,0},b={0,0,-5};
|
||||
struct real_tz_list list[2]={{&a,0},{&b,0}};struct virtual_thm v={0};
|
||||
struct virtual_thm_data d={2,list,&v};struct thermal_zone_device z={&d,0,0};int t=0;
|
||||
if(virtual_thm_get_temp(&z,&t)||t!=94000)return 1;
|
||||
a.err=-5;t=123;if(virtual_thm_get_temp(&z,&t)!=-EIO||t!=123)return 2;
|
||||
return 0;}
|
||||
'''
|
||||
c=self.root/'factory.c';c.write_text(prelude+callback+test)
|
||||
binary=self.root/'factory'
|
||||
subprocess.run(['cc','-Wall','-Werror',str(c),'-o',str(binary)],check=True,capture_output=True)
|
||||
subprocess.run([str(binary)],check=True)
|
||||
|
||||
@unittest.skipUnless(shutil.which('bash') and shutil.which('flock'), 'needs Linux process locks')
|
||||
def test_keepalive_children_do_not_retain_upgrade_lock(self):
|
||||
if E5:self.skipTest('E5 updater has no self-update keepalive path')
|
||||
src=(TOP/'rootfs/overlay/opt/mu300/bin/mu300-update').read_text()
|
||||
code=src[src.index('keepalive_start() {'):src.index('\napply() {')]
|
||||
stubs=self.root/'bin';stubs.mkdir();mark=self.root/'ping-calls'
|
||||
ping=stubs/'ping'
|
||||
ping.write_text('#!/bin/sh\nif [ -e /proc/$$/fd/9 ]; then echo leaked >> "$MARK"; fi\necho probe >> "$MARK"\n')
|
||||
ping.chmod(0o755)
|
||||
env=dict(os.environ,PATH=str(stubs)+os.pathsep+os.environ['PATH'],MARK=str(mark),LOCKFILE=str(self.root/'lock'))
|
||||
for shell in ['dash','bash']:
|
||||
if not shutil.which(shell):continue
|
||||
mark.unlink(missing_ok=True)
|
||||
commands=code+'\nhave() { command -v "$1" >/dev/null; }; exec 9>>"$LOCKFILE"; flock 9; keepalive_start; sleep .2; keepalive_stop; exec 9>&-; exec 8>>"$LOCKFILE"; flock -n 8 || exit 93'
|
||||
r=subprocess.run([shell,'-c',commands],env=env,capture_output=True,text=True,timeout=10)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
self.assertIn('probe',mark.read_text())
|
||||
self.assertNotIn('leaked',mark.read_text())
|
||||
|
||||
@unittest.skipUnless(shutil.which('cc'), 'needs host C compiler')
|
||||
def test_virtual_sensor_partial_failure_and_all_failed(self):
|
||||
path=TOP/('devices/m8/sprd_virtual_thermal.c' if E5 else 'upstream/modules/mu300_thermal/mu300_thermal.c')
|
||||
source=path.read_text();name='sprd' if E5 else 'mu300'
|
||||
start=source.index(f'static int {name}_virtual_temp(')
|
||||
body=source[start:source.index('\nstatic const',start)]
|
||||
# Execute the production callback against deterministic sensor replies.
|
||||
harness='''#include <limits.h>
|
||||
#include <errno.h>
|
||||
struct thermal_zone_device {void *priv; int value,err;};
|
||||
#define thermal_zone_device_priv(tz) ((tz)->priv)
|
||||
#define max(a,b) ((a)>(b)?(a):(b))
|
||||
int thermal_zone_get_temp(struct thermal_zone_device *s,int *v){*v=s->value;return s->err;}
|
||||
'''+f'struct {name}_virtual {{unsigned count;struct thermal_zone_device *sensor[3];}};\n'+body+f'''
|
||||
int main(void){{
|
||||
struct thermal_zone_device a={{0,94000,0}},b={{0,0,-5}},c={{0,89000,0}};
|
||||
struct {name}_virtual v={{3,{{&a,&b,&c}}}};
|
||||
struct thermal_zone_device zone={{&v,0,0}};int value=123;
|
||||
if({name}_virtual_temp(&zone,&value)||value!=94000)return 1;
|
||||
a.err=c.err=-5;value=123;
|
||||
if({name}_virtual_temp(&zone,&value)!=-EIO||value!=123)return 2;
|
||||
return 0;
|
||||
}}
|
||||
'''
|
||||
p=self.root/'sensor.c';p.write_text(harness);binary=self.root/'sensor'
|
||||
subprocess.run(['cc','-Wall','-Werror',str(p),'-o',str(binary)],check=True,capture_output=True)
|
||||
subprocess.run([str(binary)],check=True)
|
||||
|
||||
@unittest.skipUnless(shutil.which('bash'), 'needs POSIX shell')
|
||||
def test_thermal_fallback_on_unreadable_or_stale_zone(self):
|
||||
if E5:self.skipTest('E5 uses its kernel thermal governors, no thermal-guard')
|
||||
source=(TOP/'rootfs/overlay/opt/mu300/bin/thermal-guard').read_text()
|
||||
code=source[source.index('native_cpu_cooling() {'):source.index('\nhottest() {')]
|
||||
root=self.root;zone=root/'sys/class/thermal/thermal_zone0'
|
||||
zone.mkdir(parents=True);(root/'sys/module/mu300_thermal').mkdir(parents=True)
|
||||
for name,value in [('type','soc-thmzone'),('mode','enabled'),('temp','94000'),('trip_point_0_type','passive'),('trip_point_0_temp','85000')]:
|
||||
(zone/name).write_text(value+'\n')
|
||||
dev=zone.parent/'cooling_device0';dev.mkdir();(dev/'type').write_text('cpufreq-cpu0\n');(zone/'cdev0').symlink_to(dev)
|
||||
def run():return subprocess.run(['bash','-c',code+'\nnative_cpu_cooling 95000'],env=dict(os.environ,R=str(root),HOT='85000'),capture_output=True).returncode
|
||||
self.assertEqual(run(),0)
|
||||
for bad in ['', '0','broken','70000']:
|
||||
(zone/'temp').write_text(bad+'\n');self.assertNotEqual(run(),0)
|
||||
(zone/'temp').write_text('94000\n');(zone/'trip_point_0_temp').write_text('100000\n');self.assertNotEqual(run(),0)
|
||||
|
||||
def test_eic_adapter_idempotence_and_supported_limit(self):
|
||||
if not E5:self.skipTest('MU300 uses the tested upstream GPIO patch')
|
||||
adapter=module(TOP/'devices/common/eic.py')
|
||||
path=self.root/'drivers/gpio/gpio-eic-sprd.c';path.parent.mkdir(parents=True)
|
||||
path.write_text('#define SPRD_EIC_MAX_BANK\t3\n')
|
||||
adapter.apply(self.root);adapter.apply(self.root)
|
||||
self.assertIn('\t8',path.read_text())
|
||||
path.write_text('#define SPRD_EIC_MAX_BANK\t4\n')
|
||||
with self.assertRaises(ValueError):adapter.apply(self.root)
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -16,6 +16,7 @@
|
||||
# IMPORT_HOTSPOT=0|1 copy Android's hotspot SSID/passphrase into each system
|
||||
# KERNEL=5.4|6.18|7.2 the kernel in the new boot image; mu300-update keeps installing that one (boot/kernel)
|
||||
set -e
|
||||
umask 022
|
||||
T=${MU300_INSTALL_TMP:-/data/local/tmp}
|
||||
P=${MU300_PAYLOAD_DIR:-$T}
|
||||
. "$P/mu300-install.env"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# Build a Magisk-installable OpenWrt-on-TF package with Linux 6.18 or 7.2.
|
||||
# Usage: MU300_KERNEL=6.18|7.2 MU300_INPUTS=work tools/build-openwrt-tf-magisk.sh [OUT.zip]
|
||||
# The TF image includes the standalone LuCI package from openwrt/luci-app-mu300.
|
||||
umask 022
|
||||
set -eu
|
||||
TOP=$(cd "$(dirname "$0")/.." && pwd)
|
||||
IN=${MU300_INPUTS:-$TOP/work}
|
||||
@@ -164,6 +165,8 @@ sed -i "s/7\.2/$KERNEL/g" "$STAGE/module.prop"
|
||||
cp "$IN/busybox" "$STAGE/busybox"
|
||||
cp "$ROOTFS" "$STAGE/mu300-openwrt.tar.gz"
|
||||
cp "$BOOT" "$STAGE/boot-linux.img"
|
||||
mkdir -p "$STAGE/kernel-evidence"
|
||||
cp "$UO/kernel.config" "$UO/modules.in-tree" "$UO/kernel.sha256" "$UO/modules.sha256" "$STAGE/kernel-evidence/"
|
||||
(cd "$STAGE" && sha256sum boot-linux.img | cut -d' ' -f1 > boot-linux.sha256)
|
||||
python3 "$TOP/tools/tf-payload-manifest.py" "$STAGE"
|
||||
chmod 755 "$STAGE"/*.sh "$STAGE/busybox"
|
||||
|
||||
+12
-5
@@ -68,6 +68,16 @@ def add_kernel_bundle(tar, bundle: Path, os_name, seen):
|
||||
return krel, len(kos)
|
||||
|
||||
|
||||
def host_free_mode(arc, is_dir):
|
||||
"""PR #199: derive imported modes from purpose, not FAT/exFAT host modes."""
|
||||
if is_dir:
|
||||
return 0o755
|
||||
parts = arc.split('/')
|
||||
if 'dev-properties' in parts[:-1]:
|
||||
return 0o444
|
||||
return 0o755 if parts[-2:-1] == ['bin'] else 0o644
|
||||
|
||||
|
||||
def add_tree(tar, src: Path, dest: str, seen: set, rename=None):
|
||||
for root, dirs, files in os.walk(src, followlinks=False):
|
||||
dirs.sort()
|
||||
@@ -88,11 +98,7 @@ def add_tree(tar, src: Path, dest: str, seen: set, rename=None):
|
||||
continue
|
||||
seen.add(arc)
|
||||
info = tar.gettarinfo(str(path), arcname=arc)
|
||||
if os.name == 'nt':
|
||||
# Windows knows no mode bits, only a read-only attribute, and gettarinfo therefore reports
|
||||
# 0666/0444 for every file and 0777 for every directory there: write what a Linux host would
|
||||
# have stored (mkdir 0755, adb pull 0644), so the installed system gets the same modes
|
||||
info.mode = 0o755 if info.isdir() else (0o444 if not (info.mode & 0o200) else 0o644)
|
||||
info.mode = 0o777 if info.issym() else host_free_mode(arc, info.isdir())
|
||||
info.uid = info.gid = 0
|
||||
info.uname = info.gname = 'root'
|
||||
if info.isfile():
|
||||
@@ -123,6 +129,7 @@ def add_members(tar, src: Path, dest: str, seen: set, rename=None):
|
||||
seen.add(arc)
|
||||
info = copy.copy(m)
|
||||
info.name = arc
|
||||
info.mode = 0o777 if info.issym() else host_free_mode(arc, info.isdir())
|
||||
info.uid = info.gid = 0
|
||||
info.uname = info.gname = 'root'
|
||||
tar.addfile(info, stored.extractfile(m) if m.isreg() else None)
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""PR #228: verify the shipped Image's own config and full module inventory."""
|
||||
import argparse
|
||||
import gzip
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
def embedded_config(image):
|
||||
data = Path(image).read_bytes()
|
||||
start = data.find(b'IKCFG_ST')
|
||||
end = data.find(b'IKCFG_ED', start + 8) if start >= 0 else -1
|
||||
if end < 0:
|
||||
raise ValueError('Image has no embedded kernel config')
|
||||
try:
|
||||
return gzip.decompress(data[start + 8:end]).decode('utf-8')
|
||||
except (OSError, EOFError, UnicodeError) as exc:
|
||||
raise ValueError('Image has invalid embedded kernel config') from exc
|
||||
|
||||
|
||||
def settings(text):
|
||||
return dict(re.findall(r'^(CONFIG_\w+)=(.*)$', text, re.M))
|
||||
|
||||
|
||||
def expanded_check(config, fragment):
|
||||
text = Path(fragment).read_text()
|
||||
marker = '# Adapted from MU300 PR #228;'
|
||||
if marker not in text:
|
||||
raise ValueError('Missing expanded kernel feature contract')
|
||||
for key, wanted in settings(text[text.index(marker):]).items():
|
||||
actual = config.get(key, 'n')
|
||||
if actual != wanted and not (wanted == 'm' and actual == 'y'):
|
||||
raise ValueError(f'Expanded kernel feature {key}: want {wanted}, got {actual}')
|
||||
|
||||
|
||||
def audit(out, config_name='kernel.config'):
|
||||
out = Path(out)
|
||||
config = embedded_config(out / 'Image')
|
||||
if settings(config) != settings((out / config_name).read_text()):
|
||||
raise ValueError('Image embedded configuration differs from ' + config_name)
|
||||
expected = (out / 'modules.in-tree').read_text().splitlines()
|
||||
if not expected or len({name.replace('-', '_') for name in expected}) != len(expected):
|
||||
raise ValueError('Empty or duplicate in-tree module inventory')
|
||||
for name in expected:
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]+\.ko', name):
|
||||
raise ValueError('Invalid module inventory name: ' + name)
|
||||
if not (out / 'modules' / name).is_file():
|
||||
raise ValueError('Missing in-tree module: ' + name)
|
||||
return config
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('output', type=Path)
|
||||
parser.add_argument('--config-name', default='kernel.config')
|
||||
args = parser.parse_args()
|
||||
audit(args.output, args.config_name)
|
||||
print('Image embedded config and complete in-tree module inventory verified')
|
||||
@@ -34,6 +34,10 @@ O=/src/out-$KV
|
||||
mkdir -p $O
|
||||
make O=$O ARCH=arm64 allnoconfig >/dev/null
|
||||
./scripts/kconfig/merge_config.sh -m -O $O $O/.config /work/mu300-mainline.config >/dev/null
|
||||
# PR #228: NFSv4.1 is a separate prerequisite only on kernels exposing it.
|
||||
if grep -q '^config NFS_V4_1$' fs/nfs/Kconfig; then
|
||||
scripts/config --file "$O/.config" --enable NFS_V4_1
|
||||
fi
|
||||
make O=$O ARCH=arm64 olddefconfig >/dev/null
|
||||
# options Kconfig did not take; ones known not to exist in this kernel are listed in config-ignored.txt, any
|
||||
# other one stops the build (a silently dropped option has cost a working feature before)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import re
|
||||
import runpy
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
@@ -37,6 +38,38 @@ MODULES = {
|
||||
'IPVTAP': 'ipvtap', 'GENEVE': 'geneve',
|
||||
}
|
||||
|
||||
# PR #228: optional features must ship their dependency modules too.
|
||||
MODULES.update({
|
||||
'VIRTIO_PCI': 'virtio_pci',
|
||||
'VIRTIO_NET': 'virtio_net',
|
||||
'VIRTIO_BLK': 'virtio_blk',
|
||||
'VIRTIO_CONSOLE': 'virtio_console',
|
||||
'HW_RANDOM_VIRTIO': 'virtio_rng',
|
||||
'VIRTIO_BALLOON': 'virtio_balloon',
|
||||
'VIRTIO_INPUT': 'virtio_input',
|
||||
'VIRTIO_FS': 'virtiofs',
|
||||
'VIRTIO_VSOCKETS': 'vmw_vsock_virtio_transport',
|
||||
'NET_9P': '9pnet',
|
||||
'NET_9P_VIRTIO': '9pnet_virtio',
|
||||
'9P_FS': '9p',
|
||||
'VHOST_SCSI': 'vhost_scsi',
|
||||
'USBIP_CORE': 'usbip_core',
|
||||
'USBIP_HOST': 'usbip_host',
|
||||
'USBIP_VHCI_HCD': 'vhci_hcd',
|
||||
'USB_VIDEO_CLASS': 'uvcvideo',
|
||||
'USB_NET_AX8817X': 'asix',
|
||||
'NFS_FS': 'nfs',
|
||||
'NFSD': 'nfsd',
|
||||
'CIFS': 'cifs',
|
||||
'XFS_FS': 'xfs',
|
||||
'DM_CACHE': 'dm_cache',
|
||||
'DM_WRITECACHE': 'dm_writecache',
|
||||
'DM_MULTIPATH': 'dm_multipath',
|
||||
'DM_INTEGRITY': 'dm_integrity',
|
||||
'DM_MIRROR': 'dm_mirror',
|
||||
'MD_RAID456': 'raid456',
|
||||
})
|
||||
|
||||
|
||||
def config_check(path):
|
||||
config = dict(line.split('=', 1) for line in path.read_text().splitlines()
|
||||
@@ -49,6 +82,7 @@ def config_check(path):
|
||||
raise ValueError(f'CONFIG_{key} missing in built kernel.config; rebuild kernel')
|
||||
if config.get('CONFIG_ARM_SPRD_CPUFREQ_V2') != 'm':
|
||||
raise ValueError('CONFIG_ARM_SPRD_CPUFREQ_V2=m required for boot voltage profiles; rebuild kernel')
|
||||
runpy.run_path(str(Path(__file__).with_name('audit-bundle.py')))['expanded_check'](config, Path(__file__).with_name('mu300-mainline.config'))
|
||||
return config
|
||||
|
||||
|
||||
@@ -82,6 +116,7 @@ def check(out):
|
||||
vermagic = re.search(rb'vermagic=([^\s\x00]+)', (out / name).read_bytes())
|
||||
if not vermagic or vermagic[1] != version[1]:
|
||||
raise ValueError(f'{name} vermagic does not match Image')
|
||||
runpy.run_path(str(Path(__file__).with_name('audit-bundle.py')))['audit'](out)
|
||||
normalized = {name.replace('-', '_') for name in files}
|
||||
if len(normalized) != len(files):
|
||||
raise ValueError('module names collide after hyphen/underscore normalization')
|
||||
|
||||
@@ -52,6 +52,7 @@ python3 "$TOP/boot/build-boot-image.py" --generic-ramdisk --modules "$UO/modules
|
||||
--ueventd-perms "$TOP/android-vendor/ueventd-perms.sh" --out "$W/b/ramdisk-generic.lz4" >/dev/null
|
||||
cp "$UO"/modules/*.ko "$W/b/modules/"
|
||||
for f in modules.builtin modules.builtin.modinfo; do [ ! -f "$UO/$f" ] || cp "$UO/$f" "$W/b/"; done
|
||||
cp "$UO/kernel.config" "$UO/modules.in-tree" "$UO/modules.sha256" "$UO/kernel.sha256" "$W/b/"
|
||||
echo "$krel" > "$W/b/kernel.release"
|
||||
# the devices this kernel runs on; mu300-update and the installers check it (FINDINGS 33c: mainline kernels from
|
||||
# before this file do not bring up the U30 Air's USB)
|
||||
|
||||
@@ -23,9 +23,11 @@ static int mu300_virtual_temp(struct thermal_zone_device *tz, int *temp)
|
||||
for (i = 0; i < v->count; i++) {
|
||||
ret = thermal_zone_get_temp(v->sensor[i], &value);
|
||||
if (ret)
|
||||
return ret; /* Never turn an unreadable sensor into a cold reading. */
|
||||
continue; /* A broken sensor must not hide the other hot readings. */
|
||||
hottest = max(hottest, value);
|
||||
}
|
||||
if (hottest == INT_MIN)
|
||||
return -EIO; /* No valid sensor: never report a fabricated cold reading. */
|
||||
*temp = hottest;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -475,3 +475,106 @@ CONFIG_UNIX_DIAG=m
|
||||
CONFIG_PACKET_DIAG=m
|
||||
CONFIG_IPVTAP=m
|
||||
CONFIG_GENEVE=m
|
||||
|
||||
# Adapted from MU300 PR #228; optional modules are not loaded at boot.
|
||||
# --- extended VM/container support: guest transports, shared directories and checkpoint/restore
|
||||
CONFIG_VIRTIO_PCI=m
|
||||
CONFIG_VIRTIO_NET=m
|
||||
CONFIG_VIRTIO_BLK=m
|
||||
CONFIG_VIRTIO_CONSOLE=m
|
||||
CONFIG_HW_RANDOM=y
|
||||
CONFIG_HW_RANDOM_VIRTIO=m
|
||||
CONFIG_VIRTIO_BALLOON=m
|
||||
CONFIG_VIRTIO_INPUT=m
|
||||
CONFIG_VIRTIO_FS=m
|
||||
CONFIG_VIRTIO_VSOCKETS=m
|
||||
CONFIG_NET_9P=m
|
||||
CONFIG_NET_9P_VIRTIO=m
|
||||
CONFIG_9P_FS=m
|
||||
CONFIG_9P_FS_POSIX_ACL=y
|
||||
CONFIG_CHECKPOINT_RESTORE=y
|
||||
CONFIG_USERFAULTFD=y
|
||||
CONFIG_HUGETLBFS=y
|
||||
CONFIG_CGROUP_HUGETLB=y
|
||||
CONFIG_TARGET_CORE=m
|
||||
CONFIG_VHOST_SCSI=m
|
||||
|
||||
# --- routing and traffic control: multicast, MPLS, multipath TCP and additional tc actions
|
||||
CONFIG_IP_MULTICAST=y
|
||||
CONFIG_IP_MROUTE=y
|
||||
CONFIG_IP_MROUTE_MULTIPLE_TABLES=y
|
||||
CONFIG_IP_PIMSM_V2=y
|
||||
CONFIG_IPV6_MROUTE=y
|
||||
CONFIG_IPV6_MROUTE_MULTIPLE_TABLES=y
|
||||
CONFIG_IPV6_PIMSM_V2=y
|
||||
CONFIG_IPV6_SIT=m
|
||||
CONFIG_NET_IPGRE_BROADCAST=y
|
||||
CONFIG_NET_IPGRE_DEMUX=m
|
||||
CONFIG_NET_IPGRE=m
|
||||
CONFIG_MPLS=y
|
||||
CONFIG_NET_MPLS_GSO=m
|
||||
CONFIG_MPLS_ROUTING=m
|
||||
CONFIG_LWTUNNEL=y
|
||||
CONFIG_MPLS_IPTUNNEL=m
|
||||
CONFIG_MPTCP=y
|
||||
CONFIG_MPTCP_IPV6=y
|
||||
CONFIG_TCP_CONG_HYBLA=m
|
||||
CONFIG_TCP_CONG_HTCP=m
|
||||
CONFIG_TCP_CONG_VEGAS=m
|
||||
CONFIG_TCP_CONG_WESTWOOD=m
|
||||
CONFIG_NET_SCH_SFB=m
|
||||
CONFIG_NET_SCH_CHOKE=m
|
||||
CONFIG_NET_SCH_QFQ=m
|
||||
CONFIG_NET_SCH_TEQL=m
|
||||
CONFIG_NET_ACT_SAMPLE=m
|
||||
CONFIG_NET_ACT_SKBMOD=m
|
||||
CONFIG_NET_ACT_GATE=m
|
||||
CONFIG_NET_ACT_MPLS=m
|
||||
CONFIG_NFT_REJECT_NETDEV=m
|
||||
CONFIG_NETFILTER_XT_TARGET_HMARK=m
|
||||
CONFIG_NETFILTER_XT_TARGET_RATEEST=m
|
||||
CONFIG_NETFILTER_XT_MATCH_RATEEST=m
|
||||
CONFIG_NETFILTER_XT_TARGET_TCPOPTSTRIP=m
|
||||
|
||||
# --- storage: complete NFSv4, filesystem ACLs/encryption and LVM/RAID targets
|
||||
CONFIG_NFSD_V4=y
|
||||
CONFIG_NFS_V4_2=y
|
||||
CONFIG_CIFS_XATTR=y
|
||||
CONFIG_F2FS_FS_XATTR=y
|
||||
CONFIG_F2FS_FS_POSIX_ACL=y
|
||||
CONFIG_XFS_POSIX_ACL=y
|
||||
CONFIG_FS_ENCRYPTION=y
|
||||
CONFIG_FS_VERITY=y
|
||||
CONFIG_DM_CACHE=m
|
||||
CONFIG_DM_WRITECACHE=m
|
||||
CONFIG_DM_MULTIPATH=m
|
||||
CONFIG_DM_INTEGRITY=m
|
||||
CONFIG_DM_MIRROR=m
|
||||
CONFIG_MD_RAID456=m
|
||||
CONFIG_NLS_CODEPAGE_857=m
|
||||
CONFIG_NLS_ISO8859_9=m
|
||||
|
||||
# --- USB peripherals: older ASIX adapters, generic serial, USB/IP and UVC webcams
|
||||
CONFIG_USB_NET_AX8817X=m
|
||||
CONFIG_USB_SERIAL_GENERIC=y
|
||||
CONFIG_USBIP_CORE=m
|
||||
CONFIG_USBIP_HOST=m
|
||||
CONFIG_USBIP_VHCI_HCD=m
|
||||
CONFIG_MEDIA_SUPPORT=m
|
||||
CONFIG_MEDIA_SUPPORT_FILTER=y
|
||||
CONFIG_MEDIA_CAMERA_SUPPORT=y
|
||||
CONFIG_MEDIA_USB_SUPPORT=y
|
||||
CONFIG_VIDEO_DEV=m
|
||||
CONFIG_USB_VIDEO_CLASS=m
|
||||
CONFIG_NFS_FS=m
|
||||
CONFIG_NFSD=m
|
||||
CONFIG_NFS_V4=m
|
||||
CONFIG_NETWORK_FILESYSTEMS=y
|
||||
CONFIG_BLK_DEV_DM=m
|
||||
CONFIG_MD=y
|
||||
CONFIG_BLK_DEV_MD=m
|
||||
CONFIG_CIFS=m
|
||||
CONFIG_XFS_FS=m
|
||||
CONFIG_F2FS_FS=m
|
||||
CONFIG_CRYPTO_XTS=y
|
||||
CONFIG_CRYPTO_CBC=y
|
||||
@@ -0,0 +1,39 @@
|
||||
gpio: eic-sprd: map up to eight EIC banks (the UMS9620's sync controller has six)
|
||||
|
||||
Mainline's sprd-eic maps at most three banks of eight lines per controller (SPRD_EIC_MAX_BANK 3, the SC9860's
|
||||
layout); a controller whose "reg" lists more banks gets a gpiochip of 24 lines and the rest is unreachable. The
|
||||
UMS9620's sync controller (/soc/aon/gpio@2000c0, "sprd,qogirn6pro-eic-sync", "sprd,sc9860-eic-sync") lists six
|
||||
banks (0x2000c0 ... 0x2500c0, Unisoc's qogirn6pro.dtsi), and the F50's SD card slot has its card detect on line
|
||||
35 of it (cd-gpios = <&eic_sync 35 GPIO_ACTIVE_HIGH>): in the fifth bank, so of_gpio_simple_xlate() rejected
|
||||
the line, the lookup never found the chip and mmc_of_parse() returned -EPROBE_DEFER for ever (FINDINGS 31j).
|
||||
The port then dropped cd-gpios and polled the slot (MMC_CAP_NEEDS_POLL); with SDHCI_QUIRK_BROKEN_CARD_DETECTION
|
||||
sdhci_get_cd() reports a card present on every poll, so an empty slot was initialised once a second, and the
|
||||
host's late command interrupts for commands nothing answered came as "mmc1: Got command interrupt 0x00000001
|
||||
even though no command operation was in progress" with a register dump each (issue #181).
|
||||
|
||||
Unisoc's 5.4 driver (gpio-eic-sprd.c, GPL-2.0) maps eight banks; this takes the same limit. Nothing else in the
|
||||
driver depends on it: the bank count comes from the "reg" entries, the gpiochip gets num_banks * 8 lines and the
|
||||
interrupt handler walks the banks the chip has. With the card detect found, mmc_of_parse() succeeds at the first
|
||||
try, the core takes the line's interrupt (EIC sync, both edges) instead of polling, and an empty slot is left
|
||||
alone.
|
||||
|
||||
diff -Naur a/drivers/gpio/gpio-eic-sprd.c b/drivers/gpio/gpio-eic-sprd.c
|
||||
--- a/drivers/gpio/gpio-eic-sprd.c 2026-10-12 11:52:04
|
||||
+++ b/drivers/gpio/gpio-eic-sprd.c 2026-10-12 11:52:13
|
||||
@@ -51,10 +51,13 @@
|
||||
#define SPRD_EIC_SYNC_DATA 0x1c
|
||||
|
||||
/*
|
||||
- * The digital-chip EIC controller can support maximum 3 banks, and each bank
|
||||
- * contains 8 EICs.
|
||||
+ * The digital-chip EIC controller can support maximum 8 banks, and each bank
|
||||
+ * contains 8 EICs: the SC9860's controllers have up to 3 banks, the UMS9620's
|
||||
+ * (qogirn6pro) up to 6 - its sync controller lists six "reg" entries, and the
|
||||
+ * SD card slot's card detect is line 35, in the fifth. Unisoc's own driver
|
||||
+ * maps 8 as well.
|
||||
*/
|
||||
-#define SPRD_EIC_MAX_BANK 3
|
||||
+#define SPRD_EIC_MAX_BANK 8
|
||||
#define SPRD_EIC_PER_BANK_NR 8
|
||||
#define SPRD_EIC_DATA_MASK GENMASK(7, 0)
|
||||
#define SPRD_EIC_BIT(x) ((x) & (SPRD_EIC_PER_BANK_NR - 1))
|
||||
@@ -6,6 +6,32 @@ import re
|
||||
|
||||
def apply(kernel):
|
||||
kernel = Path(kernel)
|
||||
# SDHCI core builds coherent ADMA descriptors immediately before ringing
|
||||
# SDHCI_COMMAND. Coherent allocation does not order these stores against
|
||||
# relaxed MMIO; likewise completion status must order subsequent DMA reads.
|
||||
# Match the ordered accessors provided by the generic SDHCI helpers.
|
||||
io = kernel / 'drivers/mmc/host/sdhci-sprd.c'
|
||||
text = io.read_text()
|
||||
start = text.index('static inline u32 sdhci_sprd_readl(')
|
||||
end = text.index('static inline void sdhci_sprd_sd_clk_off(', start)
|
||||
accessors = text[start:end]
|
||||
marker = 'Shared SDHCI policy: order ADMA descriptors and DMA completion'
|
||||
if marker not in accessors:
|
||||
accessors = accessors.replace(
|
||||
'return readl_relaxed(host->ioaddr + reg);',
|
||||
'/* ' + marker + '. */\n\treturn readl(host->ioaddr + reg);',
|
||||
)
|
||||
for width in ('b', 'w', 'l'):
|
||||
accessors = accessors.replace('write' + width + '_relaxed(', 'write' + width + '(')
|
||||
required = ('return readl(host->ioaddr + reg);',
|
||||
'writel(val, host->ioaddr + reg);',
|
||||
'writew(val, host->ioaddr + reg);',
|
||||
'writeb(val, host->ioaddr + reg);')
|
||||
if (marker not in accessors or any(item not in accessors for item in required)
|
||||
or re.search(r'write[bwl]_relaxed\(', accessors)):
|
||||
raise ValueError('SDHCI MMIO accessor anchors changed')
|
||||
io.write_text(text[:start] + accessors + text[end:])
|
||||
|
||||
header = kernel / 'include/linux/mmc/host.h'
|
||||
text = header.read_text()
|
||||
if '#define MMC_CAP2_NO_REL_WR' not in text:
|
||||
|
||||
@@ -114,12 +114,26 @@ t = open(sp).read()
|
||||
marker = 'MU300: only the non-removable eMMC'
|
||||
old = '\t/* ' + marker + ' is used */\n\tif (!of_property_read_bool(pdev->dev.of_node, "non-removable"))\n\t\treturn -ENODEV;\n'
|
||||
t = t.replace(old, '')
|
||||
# The stock F50 DT describes the removable slot's vendor EIC card-detect GPIO,
|
||||
# but that GPIO supplier can remain deferred under mainline. Do not let that
|
||||
# keep the entire SD host deferred forever: only sdio_sd falls back to polling.
|
||||
# PR #184 maps all EIC banks so the stock card-detect GPIO uses interrupts.
|
||||
# A genuine GPIO deferral still has a TF-only fallback: re-run the full parse
|
||||
# without cd-gpios, rather than skipping bus modes/power sequence after it.
|
||||
parse_old = '\tret = mmc_of_parse(host->mmc);\n\tif (ret)\n\t\treturn ret;\n'
|
||||
parse_new = '''\tret = mmc_of_parse(host->mmc);
|
||||
\tif (ret == -EPROBE_DEFER &&
|
||||
\t of_property_match_string(pdev->dev.of_node, "sprd,name", "sdio_sd") >= 0) {
|
||||
\t\tstruct property *cd = of_find_property(pdev->dev.of_node, "cd-gpios", NULL);
|
||||
\t\tif (cd && !of_remove_property(pdev->dev.of_node, cd)) {
|
||||
\t\t\tdev_warn(&pdev->dev, "MU300: CD GPIO deferred, polling removable TF slot\\n");
|
||||
\t\t\tret = mmc_of_parse(host->mmc);
|
||||
\t\t\thost->mmc->caps |= MMC_CAP_NEEDS_POLL;
|
||||
\t\t}
|
||||
\t}
|
||||
\tif (ret)
|
||||
\t\treturn dev_err_probe(&pdev->dev, ret, "MU300: mmc_of_parse failed\\n");
|
||||
'''
|
||||
# Migrate the earlier cached adaptation, which only masked the deferral.
|
||||
masked = '''\tret = mmc_of_parse(host->mmc);
|
||||
\tif (ret == -EPROBE_DEFER &&
|
||||
\t of_property_read_bool(pdev->dev.of_node, "cd-gpios") &&
|
||||
\t of_property_match_string(pdev->dev.of_node, "sprd,name", "sdio_sd") >= 0) {
|
||||
\t\tdev_warn(&pdev->dev, "MU300: CD GPIO deferred, polling removable TF slot\\n");
|
||||
@@ -129,7 +143,8 @@ parse_new = '''\tret = mmc_of_parse(host->mmc);
|
||||
\tif (ret)
|
||||
\t\treturn dev_err_probe(&pdev->dev, ret, "MU300: mmc_of_parse failed\\n");
|
||||
'''
|
||||
if 'MU300: CD GPIO deferred' not in t:
|
||||
t = t.replace(masked, parse_old)
|
||||
if 'of_remove_property(pdev->dev.of_node, cd)' not in t:
|
||||
if parse_old not in t:
|
||||
sys.exit('port: sdhci-sprd mmc_of_parse anchor changed')
|
||||
t = t.replace(parse_old, parse_new, 1)
|
||||
|
||||
Reference in new issue
Block a user