mirror of
https://github.com/dikeckaan/mu300-linux.git
synced 2026-12-05 08:02:40 +00:00
feat(mu300): add voltage and forwarding controls; fix Wi-Fi log flood
Add guarded CPU voltage profiles, per-SIM forwarding settings and localized UI. Preserve vendor assets during online updates (upstream f7df326).
Bound WLAN/WCN TX pressure diagnostics with read-only counters, retain queue semantics, and guard both module packaging paths against stale sources.
Validation: 274 regression tests, 272 passed and 2 skipped; 6.18.54 and 7.2.8 modules built. Live 7.2.8 reverse throughput sample approximately 689 Mbps with no flow-control log flood; DMA queue pressure remains observable.
This commit is contained in:
44 files changed
+2063
-105
No files matched your search
@@ -531,6 +531,17 @@ if [ "$root_mounted" = 1 ] && rootdir=$(pick_root) && [ -n "$rootdir" ]; then
|
||||
echo "$DEVICE" > /run/mu300/device
|
||||
init=/sbin/init
|
||||
[ -x /newroot/lib/systemd/systemd ] && init=/lib/systemd/systemd
|
||||
# Mainline cpufreq is now modular so an updated rootfs can read a saved
|
||||
# voltage profile before loading it. Old roots still boot at factory voltage.
|
||||
# Do not load it here when the rootfs adapter exists (one-shot firmware ABI).
|
||||
if [ ! -x /newroot/opt/mu300/bin/cpu-voltage-platform ]; then
|
||||
for cpu_ko in /newroot/lib/modules/$(uname -r)/sprd-cpufreq-v2-driver.ko \
|
||||
/newroot/lib/modules/$(uname -r)/extra/sprd-cpufreq-v2-driver.ko; do
|
||||
[ -f "$cpu_ko" ] || continue
|
||||
insmod "$cpu_ko" voltage_offset_uv=0,0,0 2>/run/cpufreq.err || log 'stage=cpufreq-default-failed'
|
||||
break
|
||||
done
|
||||
fi
|
||||
log "stage=switch-root root=$rootdir init=$init os=$(sed -n 's/^PRETTY_NAME=//p' /newroot/etc/os-release)"
|
||||
persist
|
||||
kill $(jobs -p) 2>/dev/null
|
||||
|
||||
@@ -13,6 +13,7 @@ The mainline builds use the same `upstream/modules/` vendor module source. `upst
|
||||
| `sprdbt-tty-one-port` | Present in `upstream/modules/sprdbt_tty/tty-pcie/tty.c`. |
|
||||
| `wcn-pcie-scan-timeout` | Present in `upstream/modules/wcn_bsp/pcie/pcie.c`. |
|
||||
| `sprdwcn-mbuf-pool-deinit-null` | Added 2026-10-10 to the 5.4 kernel patch list and shared mainline `wcn_bsp/pcie/mchn.c`; a failed PCIe channel init can be unwound without zeroing a NULL pool. |
|
||||
| `wlan_combo-tx-pressure-logging`, `sprdwcn-edma-pressure-stats` | Added 2026-10-10 to 5.4 patches and shared 6.18/7.2 source: bounded TX pressure diagnostics and read-only counters; credit limits, queue capacity, ownership and error returns unchanged. Both mainline module pairs compiled; 5.4 patch dry-run only, not a full build. |
|
||||
| `wlan_combo-wcn-power-serialise` | Added 2026-10-10 for 5.4 and both mainline builds: serialize power transitions, release/acquire the RX context, reject contextless RX and power off before freeing the containing structure. |
|
||||
| `wlan_combo-5ghz-ap-ds-params`, `allow-bridging-ap`, `ap-stations-channel`, `default-board-config`, `pcie-post-init-retry`, `tx-complock-irqsave` | Present in `upstream/modules/sprd_wlan_combo/`. |
|
||||
| `wlan_combo-rx-software-checksum` | Present in the shared source after the 7.2.8 Wi-Fi repair. The running 7.2.8 module was verified to return `CHECKSUM_NONE` without calling `rx_ipv6_csum`. The local `upstream/out` (6.18) and `upstream/out-7.2` WLAN modules were subsequently rebuilt from this source; old TF ZIPs and kernel bundles remain unchanged and must not be reused. |
|
||||
|
||||
@@ -57,3 +57,13 @@ startup. No kernel version/configuration change is included.
|
||||
repository/build checks; runtime boot-cycle acceptance remains outstanding.
|
||||
- No rootfs/ZIP rebuild or remote push. Old r4 packages do not contain these
|
||||
changes; rebuilt module directories do.
|
||||
|
||||
## Follow-up: vendor preservation during online updates
|
||||
|
||||
Reviewed main again at `5582413`. Backported `f7df326` into `mu300-update`:
|
||||
merge missing vendor files instead of BusyBox `cp -an`, preserve image entries
|
||||
and target symlinks, and abort before the directory swap on copy failure.
|
||||
This narrowly updates the earlier decision to leave the updater untouched;
|
||||
it does not import unrelated VPN, suspend or boot-policy changes.
|
||||
See `WIFI-R4-AUDIT-20261010.zh-CN.md` for the inspected r4 payload, validation
|
||||
and the limits of attributing the reported Wi-Fi failure without device logs.
|
||||
@@ -0,0 +1,135 @@
|
||||
# MU300 r4 Wi-Fi 故障排查与上游核对
|
||||
|
||||
## 核对范围
|
||||
|
||||
2026-10-10 拉取 `dikeckaan/mu300-linux` 的 main,最新为 `5582413`。
|
||||
用户报告的包为 `mu300-linux-openwrt-tf-7.2-20261008-r4.zip`,并非当前工作树。
|
||||
本地同名 ZIP 的 SHA256:
|
||||
`d3fab024e7cb19b93593c899472010241a789b30f3683967f94ded8fa7ec0d9c`。
|
||||
用户此前同名 r4 曾重新打包;只有哈希相同才能认定是同一个文件。
|
||||
|
||||
## 已确认的内容
|
||||
|
||||
- 实际检查 ZIP 内的 rootfs,存在 `lib/firmware/wcnmodem.bin`(986032 字节)、
|
||||
`wifi_board_config.ini`(7557 字节)、`wifi_board_config_ab.ini`(6831 字节)。
|
||||
- ZIP 内安装脚本还会从本机 Android 的 `/odm/firmware`、`/vendor/firmware`、
|
||||
`/vendor/etc` 依次查找并复制这些文件;未找到非空文件会中止,不是静默略过。
|
||||
这只能证明包和安装逻辑,不代表故障设备磁盘上的文件一定完整或固件适配成功。
|
||||
- 当前主线驱动的未知项目分支已选择 MU300 的 `wifi_board_config.ini`,
|
||||
5.4 对应 `wlan_combo-default-board-config.patch`;不能仅看模块里含有
|
||||
`wifi_board_config_hulk.ini` 字符串就认定选错,因为其他项目分支仍合法引用它。
|
||||
- 本地 r4 中 7.2.8 模块:
|
||||
`wcn_bsp.ko` SHA256 `ebfc075de429070f280bfdc9385afab7698dded69787633f7b4b611fc39e4a89`;
|
||||
`sprd_wlan_combo.ko` SHA256 `2db2f25642b4a073c1737a30070e644f9f74158813a895d0c67dd27bd373cc1c`。
|
||||
它们与 10 月 10 日重建的模块不同,不能把当前源码/重建结果算作 r4 已携带的修复。
|
||||
- 上游 WCN 上下电串行化/RX 上下文保护 `1f6e825`、PCIe 通道失败清理 `1196cf2`、
|
||||
固件日志策略 `f0323bf` 已在本分支 `f092671` 移植;见 `UPSTREAM-SYNC-20261010.md`。
|
||||
不重新引入已撤掉的无线速率实验代码,不改已验证的 IPv6 软件校验和路径。
|
||||
|
||||
## 本轮补入的上游修复
|
||||
|
||||
来源:<https://github.com/dikeckaan/mu300-linux/commit/f7df326eb044bd204c0eb2ab075c2187b94037a6>。
|
||||
|
||||
`mu300-update` 仍使用 `cp -an old/vendor/. new/vendor/` 并忽略错误。
|
||||
OpenWrt BusyBox 会跳过已存在的目标目录,在线升级可能漏掉 WCN 固件、INI、
|
||||
Android 运行库和旧内核模块。老 BusyBox 不支持 `-n` 时也会被 `|| true` 吞掉。
|
||||
|
||||
移植 `copy_missing`:合并缺失项、保留新版已有文件,不进入目标符号链接;
|
||||
复制或建目录失败则中止,尚未交换旧系统。另加目标根目录检查。
|
||||
保留本分支已有的 `etc/unisoc-modem` 用户配置和 CPU 模块索引处理。
|
||||
|
||||
此问题属于在线升级路径。TF Magisk 全新安装使用另一套复制流程,
|
||||
不能用它解释所有全新安装失败,更不能据此确定朋友机器的故障原因。
|
||||
|
||||
## PCIe 与其他报错的边界
|
||||
|
||||
当前 PCIe host 已读取 DT 的 `num-vectors`;WCN 驱动使用 MSI,legacy INTx 默认关闭。
|
||||
`of_irq_parse_pci`/传统中断映射告警与 MSI 分配失败不是同一件事。
|
||||
需结合 `pci_enable_msi_range` 返回值、`request_irq`、`/proc/interrupts` 的实际增长,
|
||||
以及最早一条固件/INI 错误判断;不应为了消除日志盲目添加 interrupt-map。
|
||||
|
||||
没有故障设备完整日志,不能证明 TX/重排序错误是固件缺失导致,
|
||||
也不能把 SIPA、MMC2、hostapd 的全部报错归为同一连锁反应。
|
||||
特别是 MMC I/O 错误可能反过来导致 TF 中的固件/模块读取失败。
|
||||
|
||||
## 验证与部署状态
|
||||
|
||||
- `tests/test_update.py` 的隔离测试覆盖已有目录合并、保留新版文件、设备配置、
|
||||
隐藏文件、源符号链接、目标符号链接与断链、失败前不交换旧系统。
|
||||
- `tests/update_vendor_busybox_fixture.sh` 在 `mu300-openwrt-base:25.12.5`
|
||||
只读/无网络容器中复现旧 BusyBox 漏拷贝,验证新复制逻辑,不访问实机。
|
||||
- 本轮实机 SSH 超时,没有加载/卸载 Wi-Fi 驱动,没有重启,也没有更改网络。
|
||||
- 未生成新 ZIP,已有 r4 文件未改动。故障机的修复确认仍需开机完整日志及实测。
|
||||
|
||||
## 后续实机只读核对(用户正在 iperf3 打流)
|
||||
|
||||
用户重新接通管理连接后,实机可访问,内核运行 7.2.8。以下只针对这台设备、
|
||||
这次开机及采样窗口,不替代朋友故障机的日志:
|
||||
|
||||
- 热点为 5 GHz、36 信道、80 MHz,hostapd 状态 `ENABLED`。
|
||||
- 启动日志两次显示读取 `wifi_board_config.ini`,长度 `0x1d85`,解析返回 0;
|
||||
同时存在 `CMD_DOWNLOAD_INI / SPRD_CMD_STATUS_UNKNOWN_ERROR`,不能将“文件解析成功”
|
||||
写成“固件明确接受了全部配置”。源码对此未知状态仅打印,CRC/索引/长度错误才触发该处理分支的 assert。
|
||||
- `of_irq_parse_pci rc=-22` 之后有 `pci_enable_msi_range 32 ok`,
|
||||
`legacy 0 msi_en 1`、IRQ 50–81 全部申请成功、使能掩码 `0xffffffff`。
|
||||
sysfs 确有 32 路 MSI。15.54 秒采样中 IRQ 71 从 84344 增至 93475,
|
||||
IRQ 72 从 84758 增至 100808;不存在这次采样中“MSI 没有映射/没有工作”的证据。
|
||||
- 同窗口 wlan0 TX 从 6699553930 增至 8015505836 字节,约 677 Mbit/s
|
||||
(接口计数推算,非 iperf 应用层成绩),RX/TX error/drop 均未增长。
|
||||
- 磁盘上的两份 7.2 模块哈希匹配 10 月 10 日重建产物,不是原 r4 的模块;
|
||||
`image-version` 仍写 r4,因此不能用这个版本标签判断是否带过热更新。
|
||||
内核没有暴露模块 srcversion/build-id 文件,未以文件哈希冒充加载态证明。
|
||||
- 确实出现 `CMD_TX_DATA ... ERROR`,以及 `edma_pending_q_buffer(10) full`。
|
||||
后一个 51.27 秒日志窗口中队列满 72 行,未见 TX 命令错误/重排序错误/assert,
|
||||
但环形日志会覆盖历史,不能把计数下降解释为错误恢复。
|
||||
- 同窗口共 46585 行,其中 46155 行是 `sc2355_pcie_fc_test_send_num`:
|
||||
源码在发送配额限制分支逐次 `pr_err`,约 900 行/秒,挤掉了启动证据。
|
||||
这是可以单独处理的日志噪声/开销问题,不等于固件崩溃;队列满仍需区分流控和实际丢包。
|
||||
- MMC2 原文为无命令时收到 command interrupt,`Timeout: 0x00000000`
|
||||
是随后的 SDHCI 寄存器转储字段,不能据此认定 I/O 超时。
|
||||
MMC2 对应 `22220000.sdio`,当前 TF 根挂载在 `mmcblk1p1`。
|
||||
|
||||
全程没有改热点/驱动/日志参数,没有重启,iperf3 服务保持运行。
|
||||
|
||||
## TX 流控刷屏修复与受控部署
|
||||
|
||||
以上只读核对后,用户要求修复并批准安装、重启。此次只替换 WLAN/WCN 模块:
|
||||
|
||||
- 配额限制/无 credit 分支不再逐次打印错误,改为限频 debug;新增只读累计计数,
|
||||
不新增定时器或轮询,不改 credit 算法、等待时间、队列容量或返回值。
|
||||
- DMA pending 队列满按通道计数,警告限为每 5 秒最多 1 条(所有通道共享),
|
||||
实际 push 失败仍保留限频错误日志。计数是拒绝提交/检查次数,不是丢包数。
|
||||
- 满队列不接管调用者链表,原有重排队/释放逻辑保留。不能将减少日志等同于消除队列压力。
|
||||
- 6.18.54、7.2.8 两套模块编译通过,位于 `upstream/out-voltage-*`;
|
||||
5.4 对应补丁完成 dry-run,未执行 5.4 全量编译。
|
||||
- TF 与 kernel bundle 打包入口同时检查 WLAN/WCN 源码是否比模块新,避免误用旧二进制。
|
||||
这只是原有时间戳防漏检查的扩展,不替代模块清单/哈希校验。
|
||||
- 三项回归测试验证生产 credit 函数返回值、5 万次满队列拒绝后的所有权及恢复,
|
||||
以及只读诊断/构建接入。限频器在隔离测试中使用替身,并非内核计时实测。
|
||||
|
||||
实机 7.2.8 部署备份:`/etc/mu300/backup/wifi-pressure-PjNJMd`。
|
||||
新模块 SHA256:
|
||||
|
||||
- WCN:`16fe4bdd694ba2af1866e679af14a0552c68495142e949f3a14f0ffe05536031`
|
||||
- WLAN:`f1013a06f725d70702f0bd2dfe79b38ad092bf9d9ed4f942d0c92bd6675c255a`
|
||||
|
||||
重启后两个新 sysfs 参数存在,证明已加载新代码;hostapd 状态 ENABLED,
|
||||
5 GHz/36 信道,32 路 MSI 分配成功。网络、无线、防火墙、DHCP、CPU 电压配置及
|
||||
USB 重枚举脚本均通过部署前后的哈希一致性检查,CPU 偏移仍为 `0,0,0`。
|
||||
iperf3 已恢复监听 `192.168.77.1:5201`。高负载效果仍待相同条件打流复测;
|
||||
未重新打包 rootfs/TF ZIP,也未宣称 INI 未知状态或队列压力根因已解决。
|
||||
|
||||
部署后本地完整回归:274 项,272 通过、2 项因缺少指定 OpenWrt 集成环境跳过;
|
||||
6.18/7.2 构建清单校验均通过。
|
||||
|
||||
用户重新从手机启动反向打流,开机 138.13–158.14 秒采样:
|
||||
|
||||
- wlan0 TX 1466850219 → 3191337865 字节,约 689 Mbit/s(接口计数推算),
|
||||
TX errors/dropped 维持 0;不是应用层吞吐或端到端无丢包的证明。
|
||||
- credit_limited_checks 13954 → 38182,zero_credit_checks 2498 → 6643;
|
||||
流控仍在实际触发,日志不再逐次输出。
|
||||
- push_failures 与 EDMA ch10 同增 36(510 → 546),说明队列压力仍存在;
|
||||
不能写成“DMA 队列满已彻底修复”。
|
||||
- 20.01 秒内总日志 174 行、原流控刷屏 0 行、队列满警告 4 行、
|
||||
push 失败 33 行、限频摘要 5 行。窗口内未匹配到 BUG/Oops/panic/ASSERT/
|
||||
CMD_TX_DATA ERROR。修复前约 900 行/秒的特定刷屏在真实负载下消除。
|
||||
@@ -0,0 +1,63 @@
|
||||
# F50 CPU 电压偏移
|
||||
|
||||
CPU 页面按固件的三个 domain 显示对应 CPU 核心、当前偏移、下次启动偏移和频率/电压表。
|
||||
频率设置即时生效;电压设置独立持久化,仅在重启初始化调频驱动时应用。
|
||||
范围 -50 至 +25 mV,步进 3.125 mV。默认全部为零,不添加超频档位、不关闭温控。
|
||||
任何非零偏移都可能造成不稳定或数据损坏,范围限制不代表对每颗芯片都安全。
|
||||
|
||||
可手动输入偏移,也可点击每簇的默认(0)、-3.125 或 -6.25 mV 小幅预设。
|
||||
预设只填写输入框,不直接保存,也不代表经过该芯片的稳定性认证。
|
||||
保存前的二次确认逐簇列出当前偏移与下次启动偏移,非零配置默认聚焦取消。
|
||||
取消(含取消按钮上按 Enter)不保存;只有确认保存才写入下次启动配置。
|
||||
|
||||
## 平台边界
|
||||
|
||||
插件只通过只读 cpufreq 属性发现 domain,不把 policy 编号或 E5 的电源轨映射照搬给 F50。
|
||||
平台适配器 `/opt/mu300/bin/cpu-voltage-platform` 验证 SoC 以及两个 SML 分区;
|
||||
没有匹配驱动或未知固件时禁用非零调压,仍可恢复默认。
|
||||
插件不依赖 AT、基带、网络或其他看板进程,没有后台轮询调压任务。
|
||||
现有内核内置驱动不能热替换;需要配套的新 Image 和模块。6.18/7.2 使用同一份驱动。
|
||||
|
||||
## 固件依据(只读分析)
|
||||
|
||||
UMS9620 F50,sml_a/sml_b 均为 1 MiB,SHA256:
|
||||
`ff4782690fd805ff54fe34853ef8ee5c7e51c3259e20077c55373b50a4b259c2`。
|
||||
|
||||
SMC `0x8200060b` 经 `0xb000c784` 调用 `0xb0005ab8`:
|
||||
bits 8..31 分别是三个 domain 的偏移字节,bit7 为负号,其余为 mV 幅度。
|
||||
`0xb0005004` 保存每 domain 的偏移;`0xb0003354` 按
|
||||
`ceil(mV * 1000 / 3125)` 调整 selector。`0xb00038b0` 分别对 CPU/SRAM
|
||||
两张表调用该函数。PAIR_GET 路径 `0xb0004bae` 附近将 selector 乘 3125 返回 µV。
|
||||
Linux 参数以 µV 表示,仅接受完整步进,编码用 `floor(abs(uV)/1000)` 反解上述舍入。
|
||||
未写入 SML、NV、DTBO 或 PMIC 寄存器。不能将 `margin_set` 当作调压接口。
|
||||
|
||||
驱动模块参数只读;禁止 sysfs unbind,模块没有卸载入口,DVFS_INIT 有一次性保护。
|
||||
OpenWrt 在 S08(根文件系统挂载之后)读取配置并加载模块;无插件使用零偏移。
|
||||
其他系统由 extra-modules 加载;旧 rootfs 无平台适配器时,initramfs 从该 rootfs
|
||||
加载零偏移模块以维持普通调频。绝不在早期初始化基带。
|
||||
|
||||
## 回退
|
||||
|
||||
配置在 `/etc/unisoc-modem/cpu-voltage.json`。应用非零值前写入
|
||||
`cpu-voltage-armed.json` 并同步磁盘。正常系统 shutdown 清除标记,服务 stop 不清除。
|
||||
下次启动若发现上一次留下的标记,将配置改名为 `.json.rejected`,加载零偏移。
|
||||
直接拔电也视为异常关机;请重新保存后再正常重启,不会自动重试被拒绝的配置。
|
||||
“恢复默认电压”保存全零,当前已生效的偏移仍需重启才撤销。
|
||||
如果无法进入 OpenWrt,可在 Android 挂载 TF 后移除这两个 JSON 文件再启动。
|
||||
此回退依赖文件系统可读写,不替代原有 Android 启动失败保护。
|
||||
|
||||
## 验证
|
||||
|
||||
`tests/cpu_voltage_fixture.sh` 用假 sysfs/固件适配器验证范围、步进、未知固件、
|
||||
缺失 domain、保存/回读、正常重启、异常重启和恢复默认;不访问实际电源寄存器。
|
||||
`tests/test_cpu_voltage.py` 覆盖编码往返、模块一次性约束、RPC 权限和打包清单。
|
||||
实机电压与启动验证结果必须另行记录,不能以隔离测试代替。
|
||||
|
||||
2026-10-10:6.18.54 和 7.2.8 的 Image/内核模块编译通过;F50 实机运行 7.2.8。
|
||||
全零配置启动后读取三个 domain(CPU 0–3、4–6、7),共 31 个频率/电压对。
|
||||
保存 `[3125,3125,3125]` 后重启,31 个频率均不变,电压逐项增加恰好 3125 µV,
|
||||
模块只读参数和页面状态一致;vddcpu1、vddcpu2 亦读到 753125 µV。
|
||||
S08 实测发现 by-name 软链尚未创建,已修正为用内核 PARTNAME 直接定位,无新增等待。
|
||||
再保存全零并正常重启,31 个档位逐项回到原始电压,模块参数为 `0,0,0`,
|
||||
armed 标记被正常清除;AT 返回 OK,USB 管理网、5 GHz/80 MHz AP 和蜂窝连接恢复。
|
||||
这不是极限降压或长时间稳定性认证,未在实机进行故意断电/死机试验。
|
||||
@@ -0,0 +1,61 @@
|
||||
短信转发融合适配(2026-10-10)
|
||||
|
||||
参考 D:/Git/e5-linux 的 luci-app-t551m 短信转发页面与 e5-sms,
|
||||
在独立 luci-app-mu300 中实现功能融合,不引入 E5 AT、ModemManager 或 Python 服务依赖。
|
||||
|
||||
使用方法
|
||||
1. 蜂窝 → 短信转发。选择“所有 SIM 共用”或“按 SIM 独立配置”。
|
||||
2. “正在编辑”选择共用配置、SIM 1、SIM 2,分别设置并保存。
|
||||
各配置独立保存启用状态、渠道、凭据和黑名单。切换编辑对象前会提示未保存修改。
|
||||
独立模式按短信实际来源卡路由,与当前上网卡及看板查看卡无关。
|
||||
未激活配置不会自动处理短信,但允许单独发送测试消息。
|
||||
3. Webhook 可选 JSON、Bark、PushPlus、ServerChan、Telegram、企业微信、钉钉预设。
|
||||
预设填表后请替换 YOUR_KEY / YOUR_TOKEN 等凭据再保存。
|
||||
钉钉需要加签时仍使用原来的“钉钉机器人”渠道。
|
||||
4. 支持 GET / POST、JSON / 表单编码 / 纯文本、附加请求头、1–120 秒超时。
|
||||
默认 12 秒。JSON 模板为空保留原来的 from/text/date 数据格式。
|
||||
占位符为 {from}、{text}、{time}、{sim}、{device}、{kind}。
|
||||
JSON 占位符放在字符串值中;嵌套对象/数组也支持。
|
||||
URL、表单值自动百分号编码;替换仅执行一遍,不解释短信里的占位符或命令。
|
||||
GET 只发送 URL 参数,不发送正文。附加头为静态 Name: value,每行一个。
|
||||
5. SMTP、钉钉加签、本机短信、号码/关键词黑名单、三种模板语言全部保留。
|
||||
电源通知始终走共用配置,请启用共用配置并填写渠道。
|
||||
F50 无有效电池数据时不可启用电源通知,不影响短信渠道;有电池的设备继续支持。
|
||||
充电状态变化和电量跨过 5/20/40/60/80/100% 时通知。
|
||||
6. 页面继续复用插件弹窗、toast、loading;兼容 Aurora 与官方主题的样式变量。
|
||||
|
||||
兼容与安全
|
||||
- 旧 config.json 和旧密码原位保留,默认 shared;无自动开启或复制凭据。
|
||||
新增 config.sim0.json、config.sim1.json、mode,位于 /etc/unisoc-modem/forward/。
|
||||
配置目录 0700,文件通过 umask 077 创建。编辑返回“已配置”状态,不返回密码/加签密钥。
|
||||
- SIM 1 与 SIM 2 独立收件游标;启用、换渠道、切换配置模式先建立历史屏障。
|
||||
不把历史同步当新短信,不自动补发失败投递。每个合格新事件只尝试一次。
|
||||
- 电源游标单独存放于 state.power,不能覆盖尚未初始化的短信收件游标。
|
||||
- 仍只支持公网 HTTPS,校验 TLS、拒绝私网 DNS 结果、固定解析地址、不跟随重定向。
|
||||
未照搬 E5 的明文 HTTP、命令式 curl、失败自动重试和含发件号码的日志行为。
|
||||
Host、Content-Length 等影响请求边界的附加头禁止覆盖。凭据/正文不写投递记录。
|
||||
- 单服务处理两个短信池,不增加 AT 轮询。测试任务非阻塞准入,不累计排队进程;
|
||||
有投递正在执行时,保存/测试明确返回忙,避免 RPC 超时后误认为未保存。
|
||||
- 最近 30 条 RAM 记录只含时间、事件类型、渠道、来源 SIM、HTTP 状态和有限结果码。
|
||||
HTTP 成功表示服务端接受请求,不等于最终邮箱/手机已经收到推送。
|
||||
|
||||
验证
|
||||
- 本轮完整回归运行 261 项,260 通过,1 项 Docker 集成因默认未配置镜像而跳过;
|
||||
被跳过的同一套集成脚本已另行在 ARM64 容器和实机运行通过。
|
||||
- tests/forward_profiles_fixture.sh:真实 jshn/ucode,隔离短信池、配置和虚拟发送端。
|
||||
覆盖分卡路由、密码隔离、模式切换/重启不重发历史、屏蔽名单、JSON/URL/表单转义、
|
||||
请求头/方法/超时验证、POST/GET 出站参数、HTTP 错误、旧 JSON、钉钉加签、SMTP。
|
||||
用虚拟电池目录验证独立模式下的共用电源通知;尚未在 U30 电池硬件实测。
|
||||
- tests/forward_events_fixture.sh:原新短信/历史/黑名单/重启/记录上限回归仍通过。
|
||||
- 可在依赖齐全的 OpenWrt 环境执行:
|
||||
sh tests/forward_profiles_fixture.sh openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward
|
||||
测试替换了发送端,不会发送真实邮件、HTTP 或短信,也不会写真实收件库。
|
||||
- 实机热更新仅 5 个插件文件,并重启转发服务、重载 rpcd;网络配置、USB 角色、
|
||||
AT 所有者 PID 未改变。实际设备运行过同一套隔离测试。
|
||||
- 浏览器检查三语言、390/1280 宽度、浅/深色主题变量、预设确认、GET 正文禁用、
|
||||
切换编辑配置、保存后 loading 结束。没有修改实机转发配置或触发外部发送。
|
||||
- 本轮没有实际接收运营商短信或发送外部通知;不能据隔离测试宣称真实邮件已送达。
|
||||
|
||||
构建
|
||||
两个发布路径增加 sms-forward、forward-template.uc、forward.js 和服务脚本的清单检查。
|
||||
插件仍可独立安装;本轮未重新构建 rootfs、未制作 Magisk 包。
|
||||
+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"
|
||||
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"
|
||||
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,62 @@
|
||||
MU300: bounded TX-pressure diagnostics; counters do not change queue ownership or credit limits.
|
||||
|
||||
--- a/drivers/unisoc_platform/sprdwcn/pcie/edma_engine.c
|
||||
+++ b/drivers/unisoc_platform/sprdwcn/pcie/edma_engine.c
|
||||
@@ -12,6 +12,9 @@
|
||||
|
||||
#include <linux/delay.h>
|
||||
#include <linux/timer.h>
|
||||
+#include <linux/atomic.h>
|
||||
+#include <linux/moduleparam.h>
|
||||
+#include <linux/ratelimit.h>
|
||||
#include <misc/marlin_platform.h>
|
||||
#include <misc/wcn_bus.h>
|
||||
#include <linux/pci.h>
|
||||
@@ -39,6 +42,29 @@ static int hisrfunc_line;
|
||||
static int hisrfunc_last_msg;
|
||||
static struct edma_info g_edma = { 0 };
|
||||
|
||||
+/* A full pending queue refuses ownership; the caller must retry/free it.
|
||||
+ * Keep exact rejection counts even when diagnostic messages are throttled.
|
||||
+ * No timer, workqueue, hardware access or periodic logging is added.
|
||||
+ */
|
||||
+static atomic64_t edma_pending_full[ARRAY_SIZE(g_edma.chn_sw)];
|
||||
+
|
||||
+static int mu300_edma_stats_get(char *buffer, const struct kernel_param *kp)
|
||||
+{
|
||||
+ int i, len = 0;
|
||||
+
|
||||
+ for (i = 0; i < ARRAY_SIZE(edma_pending_full); i++)
|
||||
+ len += scnprintf(buffer + len, PAGE_SIZE - len, "ch%d=%lld%s", i,
|
||||
+ (long long)atomic64_read(&edma_pending_full[i]),
|
||||
+ i == ARRAY_SIZE(edma_pending_full) - 1 ? "\n" : " ");
|
||||
+ return len;
|
||||
+}
|
||||
+
|
||||
+static const struct kernel_param_ops mu300_edma_stats_ops = {
|
||||
+ .get = mu300_edma_stats_get,
|
||||
+};
|
||||
+module_param_cb(mu300_edma_stats, &mu300_edma_stats_ops, NULL, 0444);
|
||||
+MODULE_PARM_DESC(mu300_edma_stats, "Per-channel pending-queue rejections (not packet drops)");
|
||||
+
|
||||
static unsigned char *mpool_buffer;
|
||||
static struct dma_buf mpool_dm = {0};
|
||||
|
||||
@@ -1001,11 +1027,16 @@ static int edma_pending_q_buffer(int chn, void *head, void *tail, int num)
|
||||
{
|
||||
struct edma_pending_q *q;
|
||||
struct edma_info *edma = edma_info();
|
||||
+ static DEFINE_RATELIMIT_STATE(full_rs, DEFAULT_RATELIMIT_INTERVAL, 1);
|
||||
|
||||
q = &(edma->chn_sw[chn].pending_q);
|
||||
|
||||
if ((q->wt + 1) % (q->max) == q->rd) {
|
||||
- pr_warn_ratelimited("WARN %s(%d) full\n", __func__, chn);
|
||||
+ atomic64_inc(&edma_pending_full[chn]);
|
||||
+ if (__ratelimit(&full_rs))
|
||||
+ pr_warn("WARN %s(%d) full (rejected submissions=%lld)\n",
|
||||
+ __func__, chn,
|
||||
+ (long long)atomic64_read(&edma_pending_full[chn]));
|
||||
return ERROR;
|
||||
}
|
||||
q->ring[q->wt].head = head;
|
||||
@@ -0,0 +1,90 @@
|
||||
MU300: bounded TX-pressure diagnostics; counters do not change queue ownership or credit limits.
|
||||
|
||||
--- a/sc2355/pcie.c
|
||||
+++ b/sc2355/pcie.c
|
||||
@@ -12,6 +12,8 @@
|
||||
#include <linux/io.h>
|
||||
#include <linux/regmap.h>
|
||||
#include <linux/of_device.h>
|
||||
+#include <linux/atomic.h>
|
||||
+#include <linux/moduleparam.h>
|
||||
|
||||
#include <misc/marlin_platform.h>
|
||||
|
||||
@@ -28,6 +30,36 @@
|
||||
#define SPRD_NORMAL_MEM 0
|
||||
#define SPRD_DEFRAG_MEM 1
|
||||
|
||||
+/* Count pressure without printk on every TX scheduling pass. These are
|
||||
+ * checks/failed submissions, not unique packets or packet-drop counters.
|
||||
+ * Static storage survives a WCN power cycle; reads never touch the device.
|
||||
+ */
|
||||
+static atomic64_t tx_credit_limited = ATOMIC64_INIT(0);
|
||||
+static atomic64_t tx_zero_credit = ATOMIC64_INIT(0);
|
||||
+static atomic64_t tx_push_failures = ATOMIC64_INIT(0);
|
||||
+
|
||||
+static int mu300_tx_fc_stats_get(char *buffer, const struct kernel_param *kp)
|
||||
+{
|
||||
+ return scnprintf(buffer, PAGE_SIZE,
|
||||
+ "credit_limited_checks=%lld zero_credit_checks=%lld push_failures=%lld\n",
|
||||
+ (long long)atomic64_read(&tx_credit_limited),
|
||||
+ (long long)atomic64_read(&tx_zero_credit),
|
||||
+ (long long)atomic64_read(&tx_push_failures));
|
||||
+}
|
||||
+
|
||||
+static const struct kernel_param_ops mu300_tx_fc_stats_ops = {
|
||||
+ .get = mu300_tx_fc_stats_get,
|
||||
+};
|
||||
+module_param_cb(mu300_tx_fc_stats, &mu300_tx_fc_stats_ops, NULL, 0444);
|
||||
+MODULE_PARM_DESC(mu300_tx_fc_stats, "TX credit checks and failed submissions (not packet drops)");
|
||||
+
|
||||
+static void sc2355_pcie_note_credit_limit(int remaining)
|
||||
+{
|
||||
+ atomic64_inc(&tx_credit_limited);
|
||||
+ if (remaining <= 0)
|
||||
+ atomic64_inc(&tx_zero_credit);
|
||||
+}
|
||||
+
|
||||
#define INIT_INTF_SC2355(num, type, out, interval, bsize, psize, max, \
|
||||
threshold, time, in_irq, pending, pop, push, complete, suspend) \
|
||||
{ .channel = num, .hif_type = type, .inout = out, .intr_interval = interval, \
|
||||
@@ -1572,7 +1604,8 @@ int sc2355_pcie_push_link(struct sprd_hif *hif, int chn,
|
||||
time = jiffies - time;
|
||||
|
||||
if (ret) {
|
||||
- pr_err("%s: push link fail: %d, chn: %d!\n", __func__, ret,
|
||||
+ atomic64_inc(&tx_push_failures);
|
||||
+ pr_err_ratelimited("%s: push link fail: %d, chn: %d!\n", __func__, ret,
|
||||
chn);
|
||||
}
|
||||
return ret;
|
||||
@@ -1938,6 +1971,7 @@ int sc2355_pcie_fc_get_send_num(struct sprd_hif *hif,
|
||||
|
||||
if ((free_num + data_num) >= tx_buf_max) {
|
||||
- pr_info("%s, free_num=%d, data_num=%d\n", __func__,
|
||||
+ sc2355_pcie_note_credit_limit(tx_buf_max - free_num);
|
||||
+ pr_debug_ratelimited("%s, free_num=%d, data_num=%d\n", __func__,
|
||||
free_num, data_num);
|
||||
return (tx_buf_max - free_num);
|
||||
} else {
|
||||
@@ -1963,7 +1997,9 @@ int sc2355_pcie_fc_test_send_num(struct sprd_hif *hif,
|
||||
free_num = atomic_read(&tx_mgmt->xmit_msg_list.free_num);
|
||||
|
||||
if ((free_num + data_num) >= tx_buf_max) {
|
||||
- pr_err("%s,%d free_num=%d, data_num=%d\n",
|
||||
+ /* Credit exhaustion is normal backpressure, not a firmware error. */
|
||||
+ sc2355_pcie_note_credit_limit(tx_buf_max - free_num);
|
||||
+ pr_debug_ratelimited("%s,%d free_num=%d, data_num=%d\n",
|
||||
__func__, __LINE__, free_num, data_num);
|
||||
return (tx_buf_max - free_num);
|
||||
} else {
|
||||
--- a/sc2355/tx.c
|
||||
+++ b/sc2355/tx.c
|
||||
@@ -398,7 +398,7 @@ static int tx_eachmode_data(struct sprd_hif *hif, enum sprd_mode mode)
|
||||
else
|
||||
send_num = sc2355_fc_test_send_num(hif, mode, total);
|
||||
if (total != 0 && send_num <= 0) {
|
||||
- pr_err("%s, %d: _fc_ no credit!\n", __func__, __LINE__);
|
||||
+ pr_debug_ratelimited("%s, %d: _fc_ no credit!\n", __func__, __LINE__);
|
||||
return -ENOMEM;
|
||||
}
|
||||
@@ -153,6 +153,7 @@ printf "127.0.0.1\tlocalhost\n\n::1\tlocalhost ip6-localhost ip6-loopback\nff02:
|
||||
printf "mu300\n" > $R/etc/hostname # the real one comes from uci (etc/uci-defaults/90-mu300)
|
||||
cp -a /in/opt-mu300 $R/opt/mu300
|
||||
cp -a /in/overlay/. $R/
|
||||
chmod 0755 $R/opt/mu300/bin/cpu-voltage-platform $R/etc/init.d/mu300-cpu-driver
|
||||
[ -s $R/www/luci-static/aurora/main.css ] || { echo "Aurora theme assets missing" >&2; exit 1; }
|
||||
for f in www/luci-static/resources/view/aurora/studio.js \
|
||||
www/luci-static/resources/view/aurora/marketplace.js \
|
||||
@@ -216,7 +217,7 @@ printf "%s\n" "${MU300_VERSION:-dev}" > $R/etc/mu300/image-version
|
||||
# enable the services (rc.common "enable" needs ubus, which is not running in the build container)
|
||||
# accounts still those of the image until an installer or mu300-update puts the device ones in place
|
||||
: > $R/etc/.mu300-accounts-from-image
|
||||
for s in mu300-accounts mu300-vendor mu300-hw mu300-post mu300-toolkit mu300-atd mu300-modem-log mu300-wifi-client mu300-buttons mu300-ndp mu300-smsd; do
|
||||
for s in mu300-accounts mu300-cpu-driver mu300-vendor mu300-hw mu300-post mu300-toolkit mu300-atd mu300-modem-log mu300-wifi-client mu300-buttons mu300-ndp mu300-smsd; do
|
||||
n=$(sed -n "s/^START=//p" $R/etc/init.d/$s)
|
||||
ln -sf ../init.d/$s $R/etc/rc.d/S$n$s
|
||||
done
|
||||
@@ -229,6 +230,7 @@ if [ -d /in/luci-plugin ]; then
|
||||
ln -sf ../init.d/unisoc-traffic $R/etc/rc.d/S$n"unisoc-traffic"
|
||||
ln -sf ../init.d/unisoc-traffic $R/etc/rc.d/K01unisoc-traffic
|
||||
ln -sf ../init.d/unisoc-cpu $R/etc/rc.d/S99unisoc-cpu
|
||||
ln -sf ../init.d/unisoc-cpu $R/etc/rc.d/K89unisoc-cpu
|
||||
fi
|
||||
# busybox PATH is /usr/sbin:/usr/bin:/sbin:/bin, so the commands go into /usr/bin
|
||||
for c in mu300-toolkit mu300-next-boot mu300-os mu300-update mobile-data mu300-at mu300-sms led-status mu300-vpn wifi-client mu300-ttl mu300-wifi-band mu300-led mu300-usb mu300-nfc; do ln -sf /opt/mu300/bin/$c $R/usr/bin/$c; done
|
||||
|
||||
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=luci-app-mu300
|
||||
PKG_VERSION:=1.2.0
|
||||
PKG_RELEASE:=9
|
||||
PKG_RELEASE:=10
|
||||
PKG_LICENSE:=MIT
|
||||
PKG_MAINTAINER:=MU300 Linux contributors
|
||||
PKGARCH:=all
|
||||
@@ -26,6 +26,7 @@ endef
|
||||
define Package/luci-app-mu300/conffiles
|
||||
/etc/config/unisoc_modem
|
||||
/etc/unisoc-modem/cpu.json
|
||||
/etc/unisoc-modem/cpu-voltage.json
|
||||
endef
|
||||
|
||||
define Build/Compile
|
||||
|
||||
@@ -40,6 +40,7 @@ function simSelector(root) {
|
||||
var panel = document.createElement('details'); panel.className = 'mud-card mud-sim-selector';
|
||||
panel.style.marginBottom = '14px';
|
||||
var summary = document.createElement('summary');
|
||||
summary.className = 'mud-sim-toggle';
|
||||
summary.textContent = translate('正在查看') + ' SIM ' + (Number(selectedSlot()) + 1);
|
||||
var label = document.createElement('label'), select = document.createElement('select');
|
||||
label.textContent = translate('查看卡槽') + ' ';
|
||||
@@ -93,10 +94,10 @@ var callSmsShow = scopedRpc({ object: 'mu300dash', method: 'sms_show', params: [
|
||||
var callSmsSend = scopedRpc({ object: 'mu300dash', method: 'sms_send', params: [ 'num', 'text' ], expect: { '': {} } });
|
||||
var callSmsDel = scopedRpc({ object: 'mu300dash', method: 'sms_delete', params: [ 'id', 'sim' ], expect: { '': {} } });
|
||||
var callSmsSync = scopedRpc({ object: 'mu300dash', method: 'sms_sync', expect: { '': {} } });
|
||||
var callForwardGet = rpc.declare({ object: 'mu300dash', method: 'forward_get', expect: { '': {} } });
|
||||
var callForwardStatus = rpc.declare({ object: 'mu300dash', method: 'forward_status', 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 callForwardTest = rpc.declare({ object: 'mu300dash', method: 'forward_test', 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: { '': {} } });
|
||||
var callTrafficClear = scopedRpc({ object: 'mu300dash', method: 'traffic_clear', nobatch: true, params: [ 'confirm' ], expect: { '': {} } });
|
||||
@@ -224,6 +225,38 @@ var DASH_I18N = {
|
||||
'短信转发': ['SMS forwarding', 'SMS yönlendirme'],
|
||||
'开启短信转发': ['Enable SMS forwarding', 'SMS yönlendirmeyi aç'],
|
||||
'转发已开启': ['Forwarding enabled', 'Yönlendirme açık'],
|
||||
'转发配置': ['Forwarding profiles', 'Yönlendirme profilleri'],
|
||||
'启用当前配置': ['Enable this profile', 'Bu profili etkinleştir'],
|
||||
'电源通知使用共用配置;请同时开启该配置并设置渠道。': ['Power notifications use the shared profile; enable that profile and configure its channel.', 'Güç bildirimleri ortak profili kullanır; bu profili etkinleştirip kanalını yapılandırın.'],
|
||||
'转发正在执行,请稍后再试': ['A delivery is running; please try again shortly', 'Bir gönderim sürüyor; lütfen biraz sonra tekrar deneyin'],
|
||||
'配置模式': ['Configuration mode', 'Yapılandırma modu'],
|
||||
'所有 SIM 共用': ['Shared by all SIMs', 'Tüm SIM kartları için ortak'],
|
||||
'按 SIM 独立配置': ['Separate profile per SIM', 'SIM başına ayrı profil'],
|
||||
'正在编辑': ['Editing profile', 'Düzenlenen profil'],
|
||||
'共用配置 / 电源通知': ['Shared profile / power notifications', 'Ortak profil / güç bildirimleri'],
|
||||
'独立模式按收到短信的卡选择渠道和黑名单,不受上网卡切换影响。电源通知始终使用共用配置。': ['Separate mode selects the channel and blacklist by the receiving SIM, not the data SIM. Power notifications always use the shared profile.', 'Ayrı modda kanal ve kara liste veri SIM kartına değil, SMS alan karta göre seçilir. Güç bildirimleri her zaman ortak profili kullanır.'],
|
||||
'当前配置用于新短信转发。': ['This profile handles new incoming SMS.', 'Bu profil yeni gelen SMS mesajlarını yönlendirir.'],
|
||||
'当前配置不用于短信;保存后仍保留,可单独测试。': ['This profile is inactive for SMS; its settings are retained and can be tested separately.', 'Bu profil SMS için etkin değil; ayarları korunur ve ayrı olarak test edilebilir.'],
|
||||
'电源通知请在共用配置中设置,独立模式下仍生效。': ['Configure power notifications in the shared profile; they remain active in separate mode.', 'Güç bildirimlerini ortak profilde ayarlayın; ayrı modda da etkin kalır.'],
|
||||
'填入推送预设': ['Fill from a push preset', 'Bildirim ön ayarını doldur'],
|
||||
'自定义 / 兼容旧版': ['Custom / legacy compatible', 'Özel / eski sürümle uyumlu'],
|
||||
'企业微信': ['WeCom', 'WeCom'],
|
||||
'钉钉 Webhook': ['DingTalk Webhook', 'DingTalk Webhook'],
|
||||
'预设只填入表单,请替换密钥后保存;需要钉钉加签时请选择“钉钉机器人”。': ['Presets only fill the form. Replace the keys and save; use DingTalk bot for signed requests.', 'Ön ayarlar yalnızca formu doldurur. Anahtarları değiştirip kaydedin; imzalı istekler için DingTalk botunu seçin.'],
|
||||
'请求方法': ['Request method', 'İstek yöntemi'],
|
||||
'请求超时(秒,1–120)': ['Request timeout (seconds, 1–120)', 'İstek zaman aşımı (saniye, 1–120)'],
|
||||
'正文格式': ['Body format', 'Gövde biçimi'],
|
||||
'正文模板': ['Body template', 'Gövde şablonu'],
|
||||
'纯文本': ['Plain text', 'Düz metin'],
|
||||
'占位符:{from}、{text}、{time}、{sim}、{device}、{kind}。JSON 占位符放在字符串内;按格式自动转义,绝不执行命令。': ['Placeholders: {from}, {text}, {time}, {sim}, {device}, {kind}. Put JSON placeholders inside strings; values are escaped for the format, never executed.', 'Yer tutucular: {from}, {text}, {time}, {sim}, {device}, {kind}. JSON yer tutucularını dizgelerin içine koyun; değerler biçime göre kaçışlanır, komut olarak çalıştırılmaz.'],
|
||||
'GET 只发送 URL 参数;JSON 模板留空时沿用旧版 from/text/date 格式。仅支持公网 HTTPS,验证证书且不跟随重定向。': ['GET sends URL parameters only. An empty JSON template preserves the legacy from/text/date format. Public HTTPS only, with certificate verification and no redirects.', 'GET yalnızca URL parametrelerini gönderir. Boş JSON şablonu eski from/text/date biçimini korur. Yalnızca genel HTTPS; sertifika doğrulanır, yönlendirmeler izlenmez.'],
|
||||
'附加请求头(每行 Name: value)': ['Extra headers (Name: value, one per line)', 'Ek başlıklar (satır başına Name: value)'],
|
||||
'请求超时必须为 1–120 秒': ['Request timeout must be 1–120 seconds', 'İstek zaman aşımı 1–120 saniye olmalıdır'],
|
||||
'正文模板必须是有效 JSON': ['Body template must be valid JSON', 'Gövde şablonu geçerli JSON olmalıdır'],
|
||||
'填入推送预设?': ['Fill from this push preset?', 'Bu bildirim ön ayarı doldurulsun mu?'],
|
||||
'将替换当前 Webhook 地址、正文及请求头,保存后才会生效。': ['This replaces the Webhook URL, body and headers in the form. Changes take effect only after saving.', 'Formdaki Webhook adresi, gövde ve başlıklar değiştirilir. Değişiklikler yalnızca kaydettikten sonra geçerli olur.'],
|
||||
'切换编辑配置?': ['Switch the profile being edited?', 'Düzenlenen profil değiştirilsin mi?'],
|
||||
'未保存的修改将被丢弃。': ['Unsaved changes will be discarded.', 'Kaydedilmemiş değişiklikler silinecek.'],
|
||||
'转发未开启': ['Forwarding disabled', 'Yönlendirme kapalı'],
|
||||
'转发方式': ['Forwarding method', 'Yönlendirme yöntemi'],
|
||||
'模板语言': ['Template language', 'Şablon dili'],
|
||||
@@ -317,6 +350,35 @@ var DASH_I18N = {
|
||||
'CPU 设置已应用': ['CPU settings applied', 'CPU ayarları uygulandı'],
|
||||
'CPU 设置失败且回滚不完整,请检查实际状态': ['CPU settings failed and rollback was incomplete; check actual state', 'CPU ayarları başarısız ve geri alma eksik; gerçek durumu kontrol edin'],
|
||||
'CPU 配置无效': ['Invalid CPU settings', 'Geçersiz CPU ayarları'],
|
||||
'调速器与频率即时应用;电压偏移独立保存,重启后生效,不修改温控。': ['Governors and frequency limits apply immediately. Voltage offsets are saved separately and apply after reboot; thermal controls are unchanged.', 'Yönetici ve frekans sınırları hemen uygulanır. Voltaj ofsetleri ayrı kaydedilir ve yeniden başlatmada uygulanır; sıcaklık denetimi değişmez.'],
|
||||
'CPU 电压偏移': ['CPU voltage offsets', 'CPU voltaj ofsetleri'],
|
||||
'频率与调速策略': ['Frequency & governor', 'Frekans ve yönetici'],
|
||||
'即时生效': ['Applies immediately', 'Hemen uygulanır'],
|
||||
'重启生效': ['Applies after reboot', 'Yeniden başlatmada uygulanır'],
|
||||
'当前频率': ['Current frequency', 'Geçerli frekans'],
|
||||
'按 CPU 簇设置,步进 3.125 mV。偏移会同时作用于固件对应的 CPU/SRAM 电压表;不增加超频档位。': ['Set each CPU cluster in 3.125 mV steps. Firmware adjusts the corresponding CPU/SRAM voltage tables together; no overclock states are added.', 'Her CPU kümesini 3.125 mV adımlarla ayarlayın. Donanım yazılımı ilgili CPU/SRAM voltaj tablolarını birlikte ayarlar; hız aşırtma kademesi eklenmez.'],
|
||||
'已保存,将在下次重启时应用': ['Saved; applies on next reboot', 'Kaydedildi; sonraki yeniden başlatmada uygulanır'],
|
||||
'当前电压偏移与保存值一致': ['Active voltage offsets match the saved values', 'Etkin voltaj ofsetleri kayıtlı değerlerle aynı'],
|
||||
'当前内核或固件不支持电压调整': ['This kernel or firmware does not support voltage adjustment', 'Bu çekirdek veya donanım yazılımı voltaj ayarını desteklemiyor'],
|
||||
'检测到异常关机,已停用上次的电压设置并恢复默认。': ['An unclean shutdown was detected. The previous voltage profile was disabled and defaults restored.', 'Düzgün kapanmama algılandı. Önceki voltaj profili devre dışı bırakılıp varsayılanlar geri yüklendi.'],
|
||||
'当前偏移': ['Active offset', 'Etkin ofset'],
|
||||
'偏移预设': ['Offset presets', 'Ofset ön ayarları'],
|
||||
'默认电压': ['Default voltage', 'Varsayılan voltaj'],
|
||||
'预设仅填入小幅偏移,不会直接保存;非零偏移仍需验证稳定性,不保证每颗芯片都安全。': ['Presets only fill in small offsets; they do not save. Non-zero offsets still require stability testing and are not guaranteed safe for every chip.', 'Ön ayarlar yalnızca küçük ofsetleri doldurur; kaydetmez. Sıfır dışı ofsetler kararlılık testi gerektirir ve her çip için güvenli olduğu garanti edilmez.'],
|
||||
'当前偏移 → 下次启动偏移': ['Active offset → Next boot offset', 'Etkin ofset → Sonraki açılış ofseti'],
|
||||
'请核对各簇偏移。非零偏移可能导致死机或数据损坏,预设也不保证稳定。确认仅保存配置,下次重启生效,不会立即调压。': ['Check the offsets for each cluster. Non-zero offsets may cause crashes or data corruption; presets do not guarantee stability. Confirming only saves the configuration for the next reboot; voltage will not change now.', 'Her kümenin ofsetini kontrol edin. Sıfır dışı ofsetler çökmeye veya veri bozulmasına yol açabilir; ön ayarlar kararlılığı garanti etmez. Onaylama yalnızca sonraki yeniden başlatma için yapılandırmayı kaydeder; voltaj şimdi değişmez.'],
|
||||
'确认保存': ['Confirm save', 'Kaydetmeyi onayla'],
|
||||
'下次启动偏移(mV)': ['Next boot offset (mV)', 'Sonraki açılış ofseti (mV)'],
|
||||
'当前固件电压表': ['Current firmware voltage table', 'Geçerli donanım yazılımı voltaj tablosu'],
|
||||
'保存电压设置': ['Save voltage settings', 'Voltaj ayarlarını kaydet'],
|
||||
'恢复默认电压': ['Restore default voltage', 'Varsayılan voltajı geri yükle'],
|
||||
'调压可能导致死机或数据丢失,请从小幅调整开始。异常断电或重启后会停用电压配置;正常关机保留。保存不会立即调压或自动重启。': ['Voltage changes may cause crashes or data loss; start with small adjustments. An unclean shutdown disables the profile; clean shutdown preserves it. Saving does not change live voltage or reboot.', 'Voltaj değişiklikleri çökmeye veya veri kaybına yol açabilir; küçük ayarlarla başlayın. Düzgün olmayan kapanma profili devre dışı bırakır; normal kapanma korur. Kaydetmek anlık voltajı değiştirmez veya yeniden başlatmaz.'],
|
||||
'CPU 电压配置无效': ['Invalid CPU voltage settings', 'Geçersiz CPU voltaj ayarları'],
|
||||
'恢复默认电压?': ['Restore default voltage?', 'Varsayılan voltaj geri yüklensin mi?'],
|
||||
'保存电压设置?': ['Save voltage settings?', 'Voltaj ayarları kaydedilsin mi?'],
|
||||
'电压设置仅在下次重启时应用;请确认已了解调压风险。': ['Voltage settings apply only after reboot. Please confirm that you understand the risks.', 'Voltaj ayarları yalnızca yeniden başlatmada uygulanır. Riskleri anladığınızı onaylayın.'],
|
||||
'正在保存电压设置…': ['Saving voltage settings…', 'Voltaj ayarları kaydediliyor…'],
|
||||
'电压设置已保存,重启后生效': ['Voltage settings saved; reboot to apply', 'Voltaj ayarları kaydedildi; uygulamak için yeniden başlatın'],
|
||||
'CPU 设置正忙,请稍后重试': ['CPU settings are busy; try again later', 'CPU ayarları meşgul; daha sonra tekrar deneyin'],
|
||||
'CPU 配置回读不一致': ['CPU settings did not match readback', 'CPU ayarları geri okumayla eşleşmedi'],
|
||||
'无法保存 CPU 设置': ['Could not save CPU settings', 'CPU ayarları kaydedilemedi'],
|
||||
@@ -913,6 +975,7 @@ html.mud-bootstrap-theme{--surface:var(--background-color-high);--surface-sunken
|
||||
.mud-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(330px,1fr));gap:10px;margin-top:6px}
|
||||
.mud-card{background:var(--surface,var(--background-alt,var(--background,#fff)));border:1px solid var(--hairline,var(--border,#e3e6ea));border-radius:calc(var(--radius-base,.5rem) + .375rem);padding:14px 16px;box-shadow:var(--app-shadow-sm,0 1px 3px rgba(0,0,0,.04));transition:border-color .15s}
|
||||
.mud-card:hover{border-color:color-mix(in oklab,var(--brand,var(--primary,#2f7bf6)) 30%,var(--hairline,var(--border,#e3e6ea)))}
|
||||
.mud .mud-sim-toggle,.mud .mud-sim-toggle:hover{background:transparent}
|
||||
.mud-card>h3{margin:0 0 8px;font-size:.7rem;font-weight:600;color:var(--text-muted,var(--text-light,#787d85));letter-spacing:.08em}
|
||||
.mud-card>h3::before{content:'';display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--brand,var(--primary,#2f7bf6));margin-right:7px;vertical-align:1px}
|
||||
.mud-hero{display:flex;flex-wrap:wrap;gap:12px 28px;align-items:center;background:var(--brand-subtle,var(--surface,#fff));margin-bottom:12px;padding:16px 20px}
|
||||
@@ -1229,9 +1292,9 @@ function busy(btn, on) {
|
||||
|
||||
/* ------------------------------------------------------------------ 对话框
|
||||
* M.confirmBox(title, message, opts) -> Promise<boolean>:主题化确认框,
|
||||
* 取消/遮罩/Escape 都 resolve(false),确定/Enter resolve(true)。
|
||||
* 取消/遮罩/Escape 都 resolve(false),确定 resolve(true),Enter 遵循当前按钮焦点。
|
||||
* M.alertBox(title, message, opts) -> Promise<true>:单按钮提示框。
|
||||
* opts: { danger:true 红色确认键, okText, cancelText };danger 时默认焦点在取消上。 */
|
||||
* opts: { danger:true 红色确认键, okText, cancelText, content: DOM Node };danger 时默认焦点在取消上。 */
|
||||
function dialog(opts) {
|
||||
opts = opts || {};
|
||||
return new Promise(function(resolve) {
|
||||
@@ -1245,6 +1308,7 @@ function dialog(opts) {
|
||||
'</div></div>';
|
||||
wrap.querySelector('h4').textContent = translate(opts.title || '确认');
|
||||
wrap.querySelector('.mud-dlg-msg').textContent = translate(opts.message || '');
|
||||
if (opts.content instanceof Node) wrap.querySelector('.mud-dlg-msg').appendChild(opts.content);
|
||||
var btns = wrap.querySelectorAll('.mud-dlg-btns .mud-btn');
|
||||
btns[btns.length - 1].textContent = translate(opts.okText || '确定');
|
||||
if (withCancel) btns[0].textContent = translate(opts.cancelText || '取消');
|
||||
@@ -1255,10 +1319,10 @@ function dialog(opts) {
|
||||
};
|
||||
var onKey = function(ev) {
|
||||
if (ev.key == 'Escape') { ev.preventDefault(); done(withCancel ? false : true); }
|
||||
else if (ev.key == 'Enter') { ev.preventDefault(); done(true); }
|
||||
else if (ev.key == 'Enter') { ev.preventDefault(); done(!(withCancel && document.activeElement === btns[0])); }
|
||||
};
|
||||
wrap.addEventListener('click', function(ev) {
|
||||
var b = ev.target.closest('button');
|
||||
var b = ev.target.closest('.mud-dlg-btns button[data-r]');
|
||||
if (b) done(b.getAttribute('data-r') == '1');
|
||||
else if (ev.target === wrap && withCancel) done(false);
|
||||
});
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
var get = rpc.declare({ object: 'mu300dash', method: 'cpu_get', expect: { '': {} } });
|
||||
var apply = rpc.declare({ object: 'mu300dash', method: 'cpu_apply', params: ['payload'], expect: { '': {} } });
|
||||
var getVoltage = rpc.declare({ object: 'mu300dash', method: 'cpu_voltage_get', expect: { '': {} } });
|
||||
var saveVoltage = rpc.declare({ object: 'mu300dash', method: 'cpu_voltage_save', params: ['payload'], expect: { '': {} } });
|
||||
function node(tag, text, cls) {
|
||||
var e = document.createElement(tag); if (text != null) e.textContent = text;
|
||||
if (cls) e.className = cls; return e;
|
||||
@@ -17,32 +19,108 @@ function select(values, value, label) {
|
||||
e.value = value; return e;
|
||||
}
|
||||
function field(name, input) { var e = node('label', null, 'mud-cpu-field'); e.append(node('span', M.translate(name)), input); return e; }
|
||||
function heading(title, badge, description) {
|
||||
var head = node('div', null, 'mud-cpu-heading'), copy = node('div');
|
||||
copy.append(node('h3', M.translate(title)));
|
||||
if (description) copy.append(node('p', M.translate(description), 'mud-note'));
|
||||
head.append(copy, node('span', M.translate(badge), 'mud-cpu-badge'));
|
||||
return head;
|
||||
}
|
||||
function clusterTitle(cpus) {
|
||||
var head = node('div', null, 'mud-cpu-cluster-head');
|
||||
head.append(node('h4', 'CPU ' + cpus.trim().replace(/\s+/g, ', ')));
|
||||
return head;
|
||||
}
|
||||
|
||||
var CSS = `
|
||||
.mud-cpu{max-width:1200px;margin:0 auto;padding:4px 0 12px}
|
||||
.mud-cpu .mud-cpu-title{margin:0 0 20px;padding:0 2px}
|
||||
.mud-cpu .mud-cpu-title h2{margin:0 0 8px;padding:0;border:0;font-size:1.5rem;font-weight:650;letter-spacing:-.03em;color:var(--text,#222)}
|
||||
.mud-cpu .mud-note{margin:0;color:var(--text-muted,#777);font-size:.77rem;line-height:1.65}
|
||||
.mud-cpu .mud-cpu-section{padding:22px;margin:0 0 20px;overflow-wrap:anywhere}
|
||||
.mud-cpu .mud-cpu-section:hover{border-color:var(--hairline,var(--border,#e3e6ea))}
|
||||
.mud-cpu-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;margin-bottom:20px}
|
||||
.mud-cpu-heading>div{min-width:0;flex:1}
|
||||
.mud-cpu .mud-cpu-heading h3{margin:0 0 6px;padding:0;border:0;font-size:1rem;font-weight:650;letter-spacing:0;color:var(--text,#222)}
|
||||
.mud-cpu-badge{flex-shrink:0;border:1px solid var(--hairline,#ddd);border-radius:99px;padding:4px 10px;color:var(--text-muted,#777);background:var(--surface-sunken,rgba(127,127,127,.05));font-size:.7rem;line-height:1.5}
|
||||
.mud-cpu-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,260px),1fr));gap:14px;align-items:start}
|
||||
.mud-cpu-cluster{min-width:0;padding:18px;border:1px solid var(--hairline,#ddd);border-radius:12px;background:color-mix(in srgb,var(--surface-sunken,#f4f5f7) 55%,var(--surface,#fff))}
|
||||
.mud-cpu-cluster-head{display:flex;align-items:center;gap:10px;margin-bottom:18px}
|
||||
.mud-cpu-cluster-head::before{content:'';width:8px;height:8px;border-radius:3px;background:var(--brand,#2f7bf6);opacity:.8;flex-shrink:0}
|
||||
.mud-cpu .mud-cpu-cluster-head h4{font-size:.85rem;font-weight:650;letter-spacing:.015em;margin:0;padding:0;border:0;color:var(--text,#222)}
|
||||
.mud-cpu-metric{display:flex;flex-direction:column;gap:4px;margin:0 0 20px}
|
||||
.mud-cpu-metric>span{font-size:.72rem;color:var(--text-muted,#777)}
|
||||
.mud-cpu-metric>div{display:flex;align-items:baseline;gap:7px;font-variant-numeric:tabular-nums;line-height:1.2}
|
||||
.mud-cpu-metric strong{font-size:1.8rem;font-weight:650;letter-spacing:-.04em;color:var(--text,#222)}
|
||||
.mud-cpu-metric small{font-size:.78rem;color:var(--text-muted,#777)}
|
||||
.mud-cpu-field{display:flex;flex-direction:column;gap:7px;margin:0 0 14px;min-width:0;font-size:.75rem;color:var(--text-muted,#777)}
|
||||
.mud-cpu .mud-cpu-field select,.mud-cpu .mud-cpu-field input{width:100%;max-width:none;min-width:0;box-sizing:border-box;margin:0;min-height:40px;padding:8px 10px;border:1px solid var(--hairline,#ddd);border-radius:8px;background:var(--surface,#fff);color:var(--text,#222);box-shadow:none;font-size:.84rem;font-variant-numeric:tabular-nums}
|
||||
.mud-cpu .mud-cpu-field :is(input,select):focus-visible,.mud-cpu-table>button:focus-visible{outline:2px solid var(--brand,#2f7bf6);outline-offset:2px}
|
||||
.mud-cpu .mud-cpu-field :disabled{opacity:.5;cursor:not-allowed}
|
||||
.mud-cpu-presets{display:flex;flex-wrap:wrap;gap:6px;margin:-3px 0 14px}
|
||||
.mud-cpu .mud-cpu-presets .mud-btn{flex:1;padding:5px 8px;min-height:32px;font-size:.7rem;white-space:nowrap;font-variant-numeric:tabular-nums}
|
||||
.mud-cpu .mud-cpu-preset-note{margin:0 0 16px;font-size:.7rem}
|
||||
.mud-dlg .mud-cpu-confirm-values{margin:12px 0 0;white-space:normal;font-variant-numeric:tabular-nums}
|
||||
.mud-cpu-confirm-values>div{display:flex;flex-wrap:wrap;justify-content:space-between;gap:4px 16px;padding:7px 0;border-top:1px solid var(--hairline,#ddd)}
|
||||
.mud-cpu-confirm-values strong{color:var(--text,#222);white-space:nowrap}
|
||||
.mud-cpu-range{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
|
||||
.mud-cpu .mud-cpu-meta{font-size:.65rem;line-height:1.6;color:var(--text-subtle,var(--text-muted,#888));padding-top:10px;border-top:1px solid var(--hairline,#ddd);overflow-wrap:anywhere}
|
||||
.mud-cpu-actions{display:flex;flex-wrap:wrap;gap:12px;align-items:center;justify-content:flex-end;padding-top:18px;margin-top:18px;border-top:1px solid var(--hairline,#ddd)}
|
||||
.mud-cpu .mud-cpu-actions .mud-btn{min-height:38px;padding:8px 16px;line-height:1.5;white-space:normal;text-align:center}
|
||||
.mud-cpu-persist{display:flex;gap:10px;align-items:flex-start;flex:1;min-width:min(100%,240px);margin:0;color:var(--text,#222);cursor:pointer}
|
||||
.mud-cpu-persist input{margin:3px 0 0;flex-shrink:0;accent-color:var(--brand,#2f7bf6)}
|
||||
.mud-cpu-persist>span{display:flex;flex-direction:column;gap:3px;max-width:620px;font-size:.8rem}
|
||||
.mud-cpu-persist .mud-note{font-size:.7rem}
|
||||
.mud-cpu-table{border-top:1px solid var(--hairline,#ddd);margin-top:6px;padding-top:12px}
|
||||
.mud-cpu-table>button{display:flex;align-items:center;justify-content:space-between;gap:12px;width:100%;cursor:pointer;font-size:.72rem;color:var(--text-muted,#777);line-height:1.6;padding:2px 0;border:0;border-radius:0;background:transparent;box-shadow:none;text-align:left;white-space:normal}
|
||||
.mud-cpu-table>button::after{content:'↗';color:var(--brand,#2f7bf6);flex-shrink:0}
|
||||
.mud-dlg .mud-cpu-voltage-scroll{max-height:min(55vh,420px);overflow:auto;overscroll-behavior:contain;white-space:normal;margin-top:12px}
|
||||
.mud-dlg .mud-cpu-voltage-table{width:100%;margin:0;border-collapse:collapse;font-size:.78rem;font-variant-numeric:tabular-nums;table-layout:fixed}
|
||||
.mud-dlg .mud-cpu-voltage-table :is(td,th){padding:8px 10px;border:0;border-bottom:1px solid var(--hairline,#ddd);background:transparent;color:var(--text,#222);overflow-wrap:anywhere;text-align:left}
|
||||
.mud-dlg .mud-cpu-voltage-table th{position:sticky;top:0;background:var(--surface,#fff);font-weight:600}
|
||||
.mud-dlg .mud-cpu-voltage-table :is(td,th):last-child{text-align:right}
|
||||
.mud-cpu .mud-cpu-status{flex:1;margin:0;min-width:min(100%,220px);font-size:.73rem;line-height:1.6;color:var(--success,#368364)}
|
||||
.mud-cpu .mud-cpu-status[data-pending="true"]{color:var(--warning,#ad7420)}
|
||||
.mud-cpu-status::before{content:'';display:inline-block;width:6px;height:6px;border-radius:50%;background:currentColor;margin-right:7px;vertical-align:1px}
|
||||
.mud-cpu .mud-cpu-warning{margin-top:16px;padding:12px 14px;border-left:2px solid var(--warning,#ad7420);border-radius:0 6px 6px 0;background:color-mix(in srgb,var(--warning,#ad7420) 5%,var(--surface,#fff));font-size:.7rem}
|
||||
@media(max-width:600px){.mud-cpu .mud-cpu-section{padding:16px}.mud-cpu-heading{flex-wrap:wrap;gap:8px;margin-bottom:16px}.mud-cpu-heading>div{flex-basis:100%}.mud-cpu-cluster{padding:16px}.mud-cpu-grid{grid-template-columns:minmax(0,1fr)}.mud-cpu-actions{gap:12px}.mud-cpu-actions>.mud-cpu-persist,.mud-cpu-actions>.mud-cpu-status{flex-basis:100%}.mud-cpu .mud-cpu-actions .mud-btn{flex:1}.mud-cpu .mud-cpu-title h2{font-size:1.3rem}}
|
||||
`;
|
||||
|
||||
return view.extend({
|
||||
load: function() { return get(); },
|
||||
load: function() { return Promise.all([get(), getVoltage().catch(function() { return {}; })]).then(function(r) { r[0].voltage = r[1]; return r[0]; }); },
|
||||
render: function(data) {
|
||||
M.injectCss(); M.localizeMenu();
|
||||
var self = this, root = this.root = node('div', null, 'mud');
|
||||
root.appendChild(node('style', '.mud-cpu-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,250px),1fr));gap:14px}.mud-cpu-field{display:flex;flex-direction:column;gap:8px;margin:14px 0}.mud-cpu-field select,.mud-cpu-field input{width:100%;min-width:0;box-sizing:border-box;padding:8px;border:1px solid var(--hairline,#8885);border-radius:8px;background:var(--surface,#fff);color:var(--text,#222)}.mud-cpu-actions{display:flex;flex-wrap:wrap;gap:14px;align-items:center;margin-top:14px}.mud-cpu-grid .mud-card{min-width:0;overflow-wrap:anywhere}'));
|
||||
root.append(node('h2', M.translate('CPU 设置')), node('p', M.translate('仅调整驱动支持的调速器与频率范围,不修改电压或温控。'), 'mud-note'));
|
||||
var grid = node('div', null, 'mud-cpu-grid'); root.append(grid);
|
||||
var self = this, root = this.root = node('div', null, 'mud mud-cpu');
|
||||
root.appendChild(node('style', CSS));
|
||||
var title = node('div', null, 'mud-cpu-title');
|
||||
title.append(node('h2', M.translate('CPU 设置')), node('p', M.translate('调速器与频率即时应用;电压偏移独立保存,重启后生效,不修改温控。'), 'mud-note'));
|
||||
root.append(title);
|
||||
var frequency = node('section', null, 'mud-card mud-cpu-section');
|
||||
frequency.append(heading('频率与调速策略', '即时生效'));
|
||||
var grid = node('div', null, 'mud-cpu-grid'); frequency.append(grid); root.append(frequency);
|
||||
this.inputs = [];
|
||||
(data.policies || []).forEach(function(p) {
|
||||
var card = node('section', null, 'mud-card'), current = node('div', mhz(p.current), 'mud-cpu-current'); current.dataset.policy = p.id;
|
||||
card.append(node('h3', 'CPU ' + p.cpus.replace(/ /g, ', ')), current);
|
||||
var card = node('div', null, 'mud-cpu-cluster'), current = node('strong', p.current == null ? '--' : p.current / 1000, 'mud-cpu-current'); current.dataset.policy = p.id;
|
||||
var metric = node('div', null, 'mud-cpu-metric'), value = node('div'); value.append(current, node('small', 'MHz'));
|
||||
metric.append(node('span', M.translate('当前频率')), value);
|
||||
card.append(clusterTitle(p.cpus), metric);
|
||||
var gov = select(p.governors, p.governor), lo, hi;
|
||||
if (p.frequencies.length) { lo = select(p.frequencies, p.min, mhz); hi = select(p.frequencies, p.max, mhz); }
|
||||
else { lo = node('input'); hi = node('input'); [lo, hi].forEach(function(e) { e.type = 'number'; e.min = p.hardware_min; e.max = p.hardware_max; e.step = 1; }); lo.value = p.min; hi.value = p.max; }
|
||||
[gov, lo, hi].forEach(function(e) { e.disabled = !p.writable; });
|
||||
card.append(field('调速器', gov), field(p.frequencies.length ? '最低频率' : '最低频率(kHz)', lo), field(p.frequencies.length ? '最高频率' : '最高频率(kHz)', hi));
|
||||
card.append(node('p', p.driver + ' · ' + mhz(p.hardware_min) + ' – ' + mhz(p.hardware_max), 'mud-note'));
|
||||
var range = node('div', null, 'mud-cpu-range');
|
||||
range.append(field(p.frequencies.length ? '最低频率' : '最低频率(kHz)', lo), field(p.frequencies.length ? '最高频率' : '最高频率(kHz)', hi));
|
||||
card.append(field('调速器', gov), range);
|
||||
card.append(node('div', p.driver + ' · ' + mhz(p.hardware_min) + ' – ' + mhz(p.hardware_max), 'mud-cpu-meta'));
|
||||
grid.append(card); if (p.writable) self.inputs.push({ p: p, gov: gov, lo: lo, hi: hi });
|
||||
});
|
||||
if (!(data.policies || []).length) root.append(node('div', M.translate('CPU 调频驱动尚未就绪'), 'mud-card'));
|
||||
if (!(data.policies || []).length) frequency.append(node('div', M.translate('CPU 调频驱动尚未就绪'), 'mud-note'));
|
||||
var controls = node('div', null, 'mud-cpu-actions'), persist = this.persist = node('input'); persist.type = 'checkbox'; persist.checked = !!data.persist;
|
||||
var label = node('label'); label.append(persist, document.createTextNode(' ' + M.translate('开机自动应用')));
|
||||
var label = node('label', null, 'mud-cpu-persist'), persistCopy = node('span');
|
||||
persistCopy.append(node('span', M.translate('开机自动应用')), node('span', M.translate('未勾选时仅本次运行生效,并取消之前保存的开机应用设置。'), 'mud-note'));
|
||||
label.append(persist, persistCopy);
|
||||
var button = node('button', M.translate('应用设置'), 'mud-btn on'); button.disabled = !this.inputs.length;
|
||||
controls.append(label, button); root.append(controls, node('p', M.translate('未勾选时仅本次运行生效,并取消之前保存的开机应用设置。'), 'mud-note'));
|
||||
controls.append(label, button); frequency.append(controls);
|
||||
button.onclick = function() {
|
||||
if (self.busy) return;
|
||||
var changes = self.inputs.map(function(x) { return { id: x.p.id, cpus: x.p.cpus, governor: x.gov.value, min: Number(x.lo.value), max: Number(x.hi.value) }; });
|
||||
@@ -58,12 +136,94 @@ return view.extend({
|
||||
}).catch(function(e) { M.toast(M.translate(e.message), { type: 'error' }); }).finally(function() { toast.close(); M.busy(button, false); });
|
||||
}).finally(function() { self.busy = false; });
|
||||
};
|
||||
var voltage = data.voltage || {}, section = node('section', null, 'mud-card mud-cpu-section');
|
||||
section.append(heading('CPU 电压偏移', '重启生效', '按 CPU 簇设置,步进 3.125 mV。偏移会同时作用于固件对应的 CPU/SRAM 电压表;不增加超频档位。'));
|
||||
section.append(node('p', M.translate('预设仅填入小幅偏移,不会直接保存;非零偏移仍需验证稳定性,不保证每颗芯片都安全。'), 'mud-note mud-cpu-preset-note'));
|
||||
root.append(section);
|
||||
var voltageGrid = node('div', null, 'mud-cpu-grid'), offsets = [], pending = node('p', null, 'mud-cpu-status'); pending.setAttribute('role', 'status');
|
||||
function updatePending(r) { pending.dataset.pending = String(!!r.pending); pending.textContent = M.translate(r.pending ? '已保存,将在下次重启时应用' : '当前电压偏移与保存值一致'); }
|
||||
updatePending(voltage);
|
||||
pending.hidden = !(voltage.domains || []).length;
|
||||
if (!voltage.supported) section.append(node('p', M.translate('当前内核或固件不支持电压调整'), 'mud-note'));
|
||||
if (voltage.recovery) section.append(node('p', M.translate('检测到异常关机,已停用上次的电压设置并恢复默认。'), 'mud-note'));
|
||||
(voltage.domains || []).forEach(function(d) {
|
||||
var card = node('div', null, 'mud-cpu-cluster'), input = node('input');
|
||||
input.type = 'number'; input.min = -50; input.max = 25; input.step = 3.125;
|
||||
input.value = ((voltage.offsets || [0, 0, 0])[d.id] || 0) / 1000;
|
||||
input.disabled = !voltage.supported;
|
||||
var metric = node('div', null, 'mud-cpu-metric'), value = node('div');
|
||||
value.append(node('strong', d.offset / 1000), node('small', 'mV'));
|
||||
metric.append(node('span', M.translate('当前偏移')), value);
|
||||
card.append(clusterTitle(d.cpus), metric, field('下次启动偏移(mV)', input));
|
||||
var presets = node('div', null, 'mud-cpu-presets');
|
||||
presets.setAttribute('role', 'group'); presets.setAttribute('aria-label', M.translate('偏移预设'));
|
||||
var presetButtons = [0, -3.125, -6.25].map(function(offset) {
|
||||
var button = node('button', offset === 0 ? M.translate('默认电压') : offset + ' mV', 'mud-btn');
|
||||
button.type = 'button'; button.disabled = !voltage.supported;
|
||||
button.onclick = function() { input.value = offset; updatePresets(); };
|
||||
presets.append(button); return { button: button, offset: offset };
|
||||
});
|
||||
function updatePresets() {
|
||||
presetButtons.forEach(function(p) {
|
||||
var selected = input.value.trim() !== '' && Number(input.value) === p.offset;
|
||||
p.button.classList.toggle('on', selected); p.button.setAttribute('aria-pressed', String(selected));
|
||||
});
|
||||
}
|
||||
input.addEventListener('input', updatePresets); updatePresets(); card.append(presets);
|
||||
var tableAction = node('div', null, 'mud-cpu-table'), tableButton = node('button', M.translate('当前固件电压表'));
|
||||
tableButton.type = 'button'; tableButton.setAttribute('aria-haspopup', 'dialog');
|
||||
tableButton.onclick = function() {
|
||||
if (self.tableOpen) return;
|
||||
self.tableOpen = true;
|
||||
var scroll = node('div', null, 'mud-cpu-voltage-scroll'), table = node('table', null, 'mud-cpu-voltage-table');
|
||||
var head = node('thead'), headers = node('tr'), body = node('tbody');
|
||||
['MHz', 'mV'].forEach(function(unit) { var cell = node('th', unit); cell.scope = 'col'; headers.append(cell); });
|
||||
head.append(headers);
|
||||
(d.table || []).forEach(function(pair) { var row = node('tr'); row.append(node('td', pair.khz / 1000), node('td', pair.uv / 1000)); body.append(row); });
|
||||
table.append(head, body); scroll.append(table);
|
||||
M.alertBox(M.translate('当前固件电压表') + ' · CPU ' + d.cpus.trim().replace(/\s+/g, ', '), '', { content: scroll }).finally(function() {
|
||||
self.tableOpen = false;
|
||||
if (tableButton.isConnected) tableButton.focus({ preventScroll: true });
|
||||
});
|
||||
};
|
||||
tableAction.append(tableButton); card.append(tableAction); voltageGrid.append(card); offsets.push({ id: d.id, cpus: d.cpus, active: d.offset, input: input, updatePresets: updatePresets });
|
||||
});
|
||||
var save = node('button', M.translate('保存电压设置'), 'mud-btn on'), reset = node('button', M.translate('恢复默认电压'), 'mud-btn');
|
||||
save.disabled = !voltage.supported;
|
||||
var actions = node('div', null, 'mud-cpu-actions'); actions.append(pending, save, reset);
|
||||
section.append(voltageGrid, actions, node('p', M.translate('调压可能导致死机或数据丢失,请从小幅调整开始。异常断电或重启后会停用电压配置;正常关机保留。保存不会立即调压或自动重启。'), 'mud-note mud-cpu-warning'));
|
||||
function submitVoltage(defaults) {
|
||||
if (self.busy) return;
|
||||
var values = [0, 0, 0];
|
||||
if (!defaults) offsets.forEach(function(x) { values[x.id] = x.input.value.trim() === '' ? NaN : Number(x.input.value) * 1000; });
|
||||
if (values.some(function(v) { return !Number.isInteger(v) || v < -50000 || v > 25000 || v % 3125; })) { M.toast(M.translate('CPU 电压配置无效'), { type: 'error' }); return; }
|
||||
var confirmation = node('div', null, 'mud-cpu-confirm-values');
|
||||
confirmation.append(node('p', M.translate('当前偏移 → 下次启动偏移')));
|
||||
offsets.forEach(function(x) {
|
||||
var row = node('div');
|
||||
row.append(node('span', 'CPU ' + x.cpus.trim().replace(/\s+/g, ', ')), node('strong', (x.active / 1000) + ' → ' + (values[x.id] / 1000) + ' mV'));
|
||||
confirmation.append(row);
|
||||
});
|
||||
self.busy = true;
|
||||
M.confirmBox(defaults ? '恢复默认电压?' : '保存电压设置?', '请核对各簇偏移。非零偏移可能导致死机或数据损坏,预设也不保证稳定。确认仅保存配置,下次重启生效,不会立即调压。', { content: confirmation, danger: values.some(function(v) { return v !== 0; }), okText: '确认保存' }).then(function(yes) {
|
||||
if (!yes) return;
|
||||
var target = defaults ? reset : save; M.busy(target, true);
|
||||
var toast = M.toast('正在保存电压设置…', { type: 'busy', timeout: 0 });
|
||||
return saveVoltage(JSON.stringify({ offsets: values })).then(function(r) {
|
||||
if (!r.ok) throw new Error(r.error || 'CPU 电压配置无效');
|
||||
offsets.forEach(function(x) { x.input.value = r.offsets[x.id] / 1000; x.updatePresets(); });
|
||||
updatePending(r); M.toast(M.translate('电压设置已保存,重启后生效'), { type: 'success' });
|
||||
}).catch(function(e) { M.toast(M.translate(e.message), { type: 'error' }); }).finally(function() { toast.close(); M.busy(target, false); });
|
||||
}).finally(function() { self.busy = false; });
|
||||
}
|
||||
save.onclick = function() { submitVoltage(false); };
|
||||
reset.onclick = function() { submitVoltage(true); };
|
||||
this.refresh = function() {
|
||||
if (document.hidden || !root.isConnected || self.busy || self.inflight) return Promise.resolve();
|
||||
self.inflight = true;
|
||||
return get().then(function(r) {
|
||||
if (!root.isConnected) return;
|
||||
(r.policies || []).forEach(function(p) { var e = root.querySelector('[data-policy="' + p.id + '"]'); if (e) e.textContent = mhz(p.current); });
|
||||
(r.policies || []).forEach(function(p) { var e = root.querySelector('[data-policy="' + p.id + '"]'); if (e) e.textContent = p.current == null ? '--' : p.current / 1000; });
|
||||
}).catch(function() {}).finally(function() { self.inflight = false; });
|
||||
};
|
||||
poll.add(this.refresh, 2);
|
||||
|
||||
@@ -16,6 +16,7 @@ var RESULTS = {
|
||||
smtp_auth_failed: '邮箱服务器拒绝登录,请检查授权码'
|
||||
};
|
||||
var ERRORS = {
|
||||
forward_busy: '转发正在执行,请稍后再试', disabled: '转发未开启',
|
||||
invalid_config: '配置无效', invalid_forward_config: '配置无效',
|
||||
invalid_destination: '目标地址无效', forward_storage_failed: '设备保存失败',
|
||||
sms_list_unavailable: '短信服务暂不可用', power_unavailable: '设备暂未提供有效电池状态'
|
||||
@@ -23,6 +24,19 @@ var ERRORS = {
|
||||
function result(code) { return M.translate(RESULTS[code] || '暂无投递'); }
|
||||
function lines(value) { return String(value || '').split(/\r?\n/).map(function(s) { return s.trim(); }).filter(Boolean); }
|
||||
function count(value) { return lines(value).length; }
|
||||
function preset(name) {
|
||||
var title = M.translate('短信') + ' {from}', content = '{text}\n{time} · {sim} · {device}';
|
||||
var presets = {
|
||||
json: ['https://example.com/sms', { from: '{from}', text: '{text}', time: '{time}', sim: '{sim}', device: '{device}' }],
|
||||
bark: ['https://api.day.app/push', { device_key: 'YOUR_KEY', title: title, body: content, group: 'MU300' }],
|
||||
pushplus: ['https://www.pushplus.plus/send', { token: 'YOUR_TOKEN', title: title, content: content, template: 'txt' }],
|
||||
serverchan: ['https://sctapi.ftqq.com/YOUR_SENDKEY.send', 'title={from}&desp={text}%0A{time}%20{sim}'],
|
||||
telegram: ['https://api.telegram.org/botYOUR_TOKEN/sendMessage', { chat_id: 'YOUR_CHAT_ID', text: title + '\n' + content }],
|
||||
wecom: ['https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY', { msgtype: 'text', text: { content: title + '\n' + content } }],
|
||||
dingtalk: ['https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN', { msgtype: 'text', text: { content: title + '\n' + content } }]
|
||||
};
|
||||
return presets[name];
|
||||
}
|
||||
function validPhones(value, max) {
|
||||
var a = lines(value), seen = {};
|
||||
return a.length <= max && a.every(function(p) {
|
||||
@@ -33,7 +47,7 @@ function validPhones(value, max) {
|
||||
}
|
||||
|
||||
return view.extend({
|
||||
load: function() { return L.resolveDefault(M.callForwardGet(), {}); },
|
||||
load: function() { return L.resolveDefault(M.callForwardGet('shared'), {}); },
|
||||
render: function(data) {
|
||||
M.injectCss();
|
||||
M.localizeMenu();
|
||||
@@ -62,11 +76,20 @@ return view.extend({
|
||||
@media(max-width:480px){.mud-fwd-event{grid-template-columns:1fr 1fr}.mud-fwd-event>:last-child{grid-column:1/-1}}
|
||||
@media(max-width:760px){.mud-fwd-grid{grid-template-columns:minmax(0,1fr)}.mud-fwd-pair{display:grid;grid-template-columns:minmax(0,1fr)}.mud-fwd-actions .mud-btn{flex:1}}
|
||||
</style>
|
||||
<section class="mud-card" style="margin-bottom:14px">
|
||||
<h3>转发配置</h3>
|
||||
<div class="mud-fwd-pair">
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-mode">配置模式</label><select id="mud-fwd-mode"><option value="shared">所有 SIM 共用</option><option value="per_sim">按 SIM 独立配置</option></select></div>
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-profile">正在编辑</label><select id="mud-fwd-profile"><option value="shared">共用配置 / 电源通知</option><option value="sim0">SIM 1</option><option value="sim1">SIM 2</option></select></div>
|
||||
</div>
|
||||
<div class="mud-note">独立模式按收到短信的卡选择渠道和黑名单,不受上网卡切换影响。电源通知始终使用共用配置。</div>
|
||||
<div class="mud-note" id="mud-fwd-profile-note"></div>
|
||||
</section>
|
||||
<div class="mud-fwd-grid">
|
||||
<section class="mud-card">
|
||||
<div class="mud-fwd-row"><h3>短信转发</h3><span class="mud-fwd-state" id="mud-fwd-state">--</span></div>
|
||||
<div class="mud-note" id="mud-fwd-last">暂无投递</div>
|
||||
<label class="mud-fwd-toggle"><input type="checkbox" id="mud-fwd-enabled">开启短信转发</label>
|
||||
<label class="mud-fwd-toggle"><input type="checkbox" id="mud-fwd-enabled">启用当前配置</label>
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-method">转发方式</label>
|
||||
<select id="mud-fwd-method"><option value="webhook">Webhook</option><option value="dingtalk">钉钉机器人</option><option value="smtp">邮件 SMTP</option><option value="sms">本机短信</option></select></div>
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-template_language">模板语言</label>
|
||||
@@ -74,7 +97,17 @@ return view.extend({
|
||||
<div class="mud-note">保存后用于转发标题、提示文字和电源通知;短信原文及设备备注保持不变。</div>
|
||||
<div class="mud-fwd-channel" data-method="webhook">
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-webhook_url">HTTPS 地址</label><input id="mud-fwd-webhook_url" type="url" autocomplete="off" placeholder="https://example.com/hook"></div>
|
||||
<div class="mud-note">以固定 JSON 格式发送,不执行自定义命令。</div>
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-preset">填入推送预设</label><select id="mud-fwd-preset"><option value="">自定义 / 兼容旧版</option><option value="json">JSON Webhook</option><option value="bark">Bark</option><option value="pushplus">PushPlus</option><option value="serverchan">ServerChan</option><option value="telegram">Telegram</option><option value="wecom">企业微信</option><option value="dingtalk">钉钉 Webhook</option></select></div>
|
||||
<div class="mud-note">预设只填入表单,请替换密钥后保存;需要钉钉加签时请选择“钉钉机器人”。</div>
|
||||
<div class="mud-fwd-pair">
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-webhook_method">请求方法</label><select id="mud-fwd-webhook_method"><option>POST</option><option>GET</option></select></div>
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-webhook_timeout">请求超时(秒,1–120)</label><input type="number" min="1" max="120" step="1" id="mud-fwd-webhook_timeout"></div>
|
||||
</div>
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-webhook_content_type">正文格式</label><select id="mud-fwd-webhook_content_type"><option value="application/json">JSON</option><option value="application/x-www-form-urlencoded">Form URL-encoded</option><option value="text/plain">纯文本</option></select></div>
|
||||
<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_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">
|
||||
<div class="mud-fwd-field"><label for="mud-fwd-dingtalk_webhook">机器人 Webhook 地址</label><input id="mud-fwd-dingtalk_webhook" type="url" autocomplete="off" placeholder="https://oapi.dingtalk.com/robot/send?..."></div>
|
||||
@@ -102,6 +135,7 @@ return view.extend({
|
||||
</section>
|
||||
<section class="mud-card">
|
||||
<h3>电源通知</h3>
|
||||
<div class="mud-note">电源通知使用共用配置;请同时开启该配置并设置渠道。</div>
|
||||
<label class="mud-fwd-toggle"><input id="mud-fwd-power_forward_enabled" type="checkbox">电源状态通知</label>
|
||||
<div class="mud-note" id="mud-fwd-power-note">充电状态变化,或电量跨过 5%、20%、40%、60%、80%、100% 时通知。</div>
|
||||
<div class="mud-note" id="mud-fwd-power-last"></div>
|
||||
@@ -128,7 +162,11 @@ return view.extend({
|
||||
M.localize(root);
|
||||
this.root = root;
|
||||
this.data = data || {};
|
||||
this.profile = this.data.profile || 'shared';
|
||||
this.saved = this.data.config || null;
|
||||
this.q('mode').value = this.data.mode || 'shared';
|
||||
this.q('profile').value = this.profile;
|
||||
this.q('profile').querySelector('[value="sim1"]').disabled = this.data.sim_slots !== 2;
|
||||
this.status = this.data.status || {};
|
||||
this.wire();
|
||||
if (this.saved) this.fill(this.saved);
|
||||
@@ -157,6 +195,13 @@ return view.extend({
|
||||
'dingtalk_forward_device_info', 'sms_forward_device_info' ].forEach(function(k) { self.q(k).checked = !!c[k]; });
|
||||
[ 'method', 'webhook_url', 'dingtalk_webhook', 'sms_to_phone', 'blacklist_phone',
|
||||
'blacklist_keywords', 'nickname' ].forEach(function(k) { self.q(k).value = c[k] || ''; });
|
||||
this.q('method').value = c.method || 'webhook';
|
||||
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_body').value = c.webhook_body || '';
|
||||
this.q('webhook_headers').value = c.webhook_headers || '';
|
||||
this.q('preset').value = '';
|
||||
this.q('template_language').value = c.template_language || M.uiLanguage();
|
||||
[ 'host', 'port', 'username', 'to' ].forEach(function(k) { self.q('smtp_' + k).value = c.smtp && c.smtp[k] || (k === 'port' ? '465' : ''); });
|
||||
[ 'smtp_password', 'dingtalk_secret' ].forEach(function(k) { self.q(k).value = ''; self.q('clear_' + k).checked = false; });
|
||||
@@ -165,7 +210,7 @@ return view.extend({
|
||||
this.paintMethod();
|
||||
},
|
||||
payload: function() {
|
||||
var self = this, p = {};
|
||||
var self = this, p = { profile: this.profile, mode: this.q('mode').value };
|
||||
[ 'enabled', 'power_forward_enabled', 'smtp_forward_device_info',
|
||||
'dingtalk_forward_device_info', 'sms_forward_device_info',
|
||||
'clear_smtp_password', 'clear_dingtalk_secret' ].forEach(function(k) { p[k] = self.q(k).checked ? 1 : 0; });
|
||||
@@ -173,6 +218,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; });
|
||||
if (p.clear_smtp_password) {
|
||||
p.smtp_host = ''; p.smtp_username = ''; p.smtp_to = ''; p.smtp_password = ''; p.smtp_port = '465';
|
||||
}
|
||||
@@ -184,6 +230,10 @@ 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 (!/^\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'; }
|
||||
}
|
||||
if (p.enabled && ((p.method === 'webhook' && !p.webhook_url) ||
|
||||
(p.method === 'dingtalk' && !p.dingtalk_webhook) ||
|
||||
(p.method === 'sms' && !p.sms_to_phone) ||
|
||||
@@ -193,6 +243,9 @@ return view.extend({
|
||||
paintMethod: function() {
|
||||
var method = this.q('method').value;
|
||||
this.root.querySelectorAll('.mud-fwd-channel').forEach(function(el) { el.hidden = el.getAttribute('data-method') !== method; });
|
||||
this.q('webhook_body').disabled = this.q('webhook_method').value === 'GET';
|
||||
var active = this.q('mode').value === 'shared' ? this.profile === 'shared' : this.profile !== 'shared';
|
||||
this.q('profile-note').textContent = M.translate(active ? '当前配置用于新短信转发。' : '当前配置不用于短信;保存后仍保留,可单独测试。');
|
||||
},
|
||||
paintStatus: function() {
|
||||
var s = this.status || {};
|
||||
@@ -205,27 +258,55 @@ return view.extend({
|
||||
(s.history || []).slice(0, 30).forEach(function(item) {
|
||||
var row = document.createElement('div'); row.className = 'mud-fwd-event';
|
||||
var kind = { sms: '短信', power: '电源通知', test: '测试消息' }[item.kind] || '短信';
|
||||
[new Date(Number(item.time) * 1000).toLocaleString(), M.translate(kind) + ' · ' + M.translate(METHODS[item.method] || '未知'), result(item.result)].forEach(function(value) {
|
||||
[new Date(Number(item.time) * 1000).toLocaleString(), M.translate(kind) + (item.slot == null ? '' : ' · SIM ' + (Number(item.slot) + 1)) + ' · ' + M.translate(METHODS[item.method] || '未知'), result(item.result) + (item.http_code ? ' · HTTP ' + item.http_code : '')].forEach(function(value) {
|
||||
var el = document.createElement('span'); el.textContent = value; row.appendChild(el);
|
||||
});
|
||||
history.appendChild(row);
|
||||
});
|
||||
if (!history.childNodes.length) history.textContent = M.translate('暂无投递');
|
||||
this.q('power_forward_enabled').disabled = !s.power_supported && !this.q('power_forward_enabled').checked;
|
||||
this.q('power-note').textContent = M.translate(s.power_supported ?
|
||||
this.q('power_forward_enabled').disabled = this.profile !== 'shared' || (!s.power_supported && !this.q('power_forward_enabled').checked);
|
||||
this.q('power-note').textContent = M.translate(this.profile !== 'shared' ? '电源通知请在共用配置中设置,独立模式下仍生效。' : s.power_supported ?
|
||||
'充电状态变化,或电量跨过 5%、20%、40%、60%、80%、100% 时通知。' : '设备暂未提供有效电池状态');
|
||||
},
|
||||
refreshStatus: function() {
|
||||
var self = this;
|
||||
if (this._inflight) return this._inflight;
|
||||
this._inflight = L.resolveDefault(M.callForwardStatus(), {}).then(function(r) {
|
||||
if (self.root.isConnected && r.status) { self.status = r.status; self.paintStatus(); }
|
||||
var profile = this.profile;
|
||||
this._inflight = L.resolveDefault(M.callForwardStatus(profile), {}).then(function(r) {
|
||||
if (self.root.isConnected && self.profile === profile && r.status) { self.status = r.status; self.paintStatus(); }
|
||||
}).finally(function() { self._inflight = null; });
|
||||
return this._inflight;
|
||||
},
|
||||
unload: function() { poll.remove(this._refresh); },
|
||||
wire: function() {
|
||||
var self = this;
|
||||
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;
|
||||
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_headers').value = ''; self.paintMethod();
|
||||
});
|
||||
};
|
||||
this.q('profile').onchange = function() {
|
||||
var next = this.value; this.value = self.profile;
|
||||
var dirty = JSON.stringify(self.payload()) !== self.savedPayload;
|
||||
(dirty ? M.confirmBox('切换编辑配置?', '未保存的修改将被丢弃。', { okText: '确定' }) : Promise.resolve(true)).then(function(yes) {
|
||||
if (!yes) return;
|
||||
self.q('profile').disabled = true; self.q('save').disabled = true; self.q('test').disabled = true;
|
||||
L.resolveDefault(M.callForwardGet(next), {}).then(function(v) {
|
||||
if (!v.config) { self.error('读取失败,请刷新页面'); return; }
|
||||
self.profile = next; self.q('profile').value = next; self.q('mode').value = v.mode || 'shared';
|
||||
self.saved = v.config; self.status = v.status || {}; self.fill(v.config);
|
||||
self.savedPayload = JSON.stringify(self.payload()); self.paintStatus(); self.error('');
|
||||
}).finally(function() { self.q('profile').disabled = false; self.q('save').disabled = false; self.q('test').disabled = false; });
|
||||
});
|
||||
};
|
||||
this.q('method').onchange = function() { self.paintMethod(); };
|
||||
this.q('save').onclick = function() {
|
||||
var p = self.payload(), error = self.validate(p);
|
||||
@@ -233,13 +314,12 @@ return view.extend({
|
||||
M.confirmBox('保存短信转发设置?', '开启后只处理新收到的短信;历史短信不会补发。', { okText: '保存' }).then(function(yes) {
|
||||
if (!yes) return;
|
||||
var btn = self.q('save'), toast = M.toast('正在保存短信转发设置…', { type: 'busy', timeout: 0 });
|
||||
M.busy(btn, true); self.error('');
|
||||
M.busy(btn, true); self.q('profile').disabled = true; self.q('test').disabled = true; self.error('');
|
||||
L.resolveDefault(M.callForwardSet(JSON.stringify(p)), {}).then(function(r) {
|
||||
M.busy(btn, false);
|
||||
if (!r.ok) { self.error(r.error || '保存失败'); toast.update('保存失败', 'error'); }
|
||||
else {
|
||||
self.savedPayload = null;
|
||||
L.resolveDefault(M.callForwardGet(), {}).then(function(v) {
|
||||
return L.resolveDefault(M.callForwardGet(self.profile), {}).then(function(v) {
|
||||
if (v.config) {
|
||||
self.saved = v.config;
|
||||
self.status = v.status || {};
|
||||
@@ -247,9 +327,11 @@ return view.extend({
|
||||
self.savedPayload = JSON.stringify(self.payload());
|
||||
self.paintStatus();
|
||||
}
|
||||
toast.update('已保存', 'success');
|
||||
});
|
||||
toast.update('已保存', 'success');
|
||||
}
|
||||
}).finally(function() {
|
||||
M.busy(btn, false); self.q('profile').disabled = false; self.q('test').disabled = false;
|
||||
setTimeout(function() { toast.close(); }, 3000);
|
||||
});
|
||||
});
|
||||
@@ -265,9 +347,9 @@ return view.extend({
|
||||
M.confirmBox('发送测试消息?', msg, { okText: '发送' }).then(function(yes) {
|
||||
if (!yes) return;
|
||||
var btn = self.q('test'); M.busy(btn, true);
|
||||
L.resolveDefault(M.callForwardTest(), {}).then(function(r) {
|
||||
L.resolveDefault(M.callForwardTest(self.profile), {}).then(function(r) {
|
||||
M.busy(btn, false);
|
||||
M.toast(r.ok ? '测试已开始,请稍后刷新状态' : '测试失败:' + (r.error || '未知错误'),
|
||||
M.toast(r.ok ? '测试已开始,请稍后刷新状态' : M.translate('测试失败:') + M.translate(ERRORS[r.error] || '未知错误'),
|
||||
{ type: r.ok ? 'success' : 'error' });
|
||||
setTimeout(function() { self.refreshStatus(); }, 1500);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
#!/bin/sh /etc/rc.common
|
||||
# No daemon/polling; restoring is opt-in and independent of modem startup.
|
||||
START=99
|
||||
STOP=89
|
||||
start() {
|
||||
[ -f /etc/unisoc-modem/cpu.json ] || return 0
|
||||
/usr/libexec/unisoc-modem/cpu boot | logger -t unisoc-cpu
|
||||
}
|
||||
shutdown() {
|
||||
# Only a real clean system shutdown disarms recovery, not service stop.
|
||||
/usr/libexec/unisoc-modem/cpu-voltage shutdown >/dev/null
|
||||
sync
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/etc/unisoc-modem/cpu.json
|
||||
/etc/unisoc-modem/cpu-voltage.json
|
||||
# Preserve an armed profile's guard: an unclean upgrade must not bypass recovery.
|
||||
/etc/unisoc-modem/cpu-voltage-armed.json
|
||||
@@ -376,12 +376,14 @@ do_list() {
|
||||
"sms_send": { "num": "String", "text": "String", "slot": "String" },
|
||||
"sms_delete": { "id": "String", "sim": "String", "slot": "String" },
|
||||
"sms_sync": { "slot": "String" },
|
||||
"forward_get": { },
|
||||
"forward_get": { "profile": "String" },
|
||||
"cpu_get": { },
|
||||
"cpu_apply": { "payload": "String" },
|
||||
"forward_status": { },
|
||||
"cpu_voltage_get": { },
|
||||
"cpu_voltage_save": { "payload": "String" },
|
||||
"forward_status": { "profile": "String" },
|
||||
"forward_set": { "payload": "String" },
|
||||
"forward_test": { },
|
||||
"forward_test": { "profile": "String" },
|
||||
"traffic_get": { "slot": "String" },
|
||||
"traffic_set": { "payload": "String", "slot": "String" },
|
||||
"traffic_clear": { "confirm": false, "slot": "String" },
|
||||
@@ -446,18 +448,23 @@ call)
|
||||
sms_send) run_m sms_send 'm_sms_send' ;;
|
||||
sms_delete) run_m sms_delete 'm_sms_delete' ;;
|
||||
sms_sync) run_m sms_sync 'm_sms_sync' ;;
|
||||
forward_get) "$DASH/sms-forward" get ;;
|
||||
forward_get) "$DASH/sms-forward" get "$(inp '@.profile' shared)" ;;
|
||||
cpu_get) "$DASH/cpu" get ;;
|
||||
cpu_apply) inp '@.payload' | "$DASH/cpu" apply ;;
|
||||
forward_status) "$DASH/sms-forward" status ;;
|
||||
cpu_voltage_get) "$DASH/cpu-voltage" get ;;
|
||||
cpu_voltage_save) inp '@.payload' | "$DASH/cpu-voltage" save ;;
|
||||
forward_status) "$DASH/sms-forward" status "$(inp '@.profile' shared)" ;;
|
||||
forward_set)
|
||||
payload=$(inp '@.payload')
|
||||
printf '%s' "$payload" | "$DASH/sms-forward" set
|
||||
;;
|
||||
forward_test)
|
||||
# Delivery can take 25 s and must not tie up the LuCI RPC request.
|
||||
setsid "$DASH/sms-forward" test-run >/dev/null 2>&1 &
|
||||
printf '{"ok":1,"started":1}\n'
|
||||
profile=$(inp '@.profile' shared)
|
||||
case "$profile" in shared|sim0) ;; sim1)
|
||||
[ "$(uci -q get unisoc_modem.main.sim_slots 2>/dev/null)" = 2 ] || { printf '{"ok":0,"error":"invalid_config"}\n'; exit 0; } ;;
|
||||
*) printf '{"ok":0,"error":"invalid_config"}\n'; exit 0 ;; esac
|
||||
# The backend admits one worker, then returns without holding RPC.
|
||||
"$DASH/sms-forward" test-start "$profile"
|
||||
;;
|
||||
traffic_get)
|
||||
ubus -t 3 call unisoc.traffic get "{\"slot\":${MU300_SIM_SLOT:-0}}" 2>/dev/null || printf '{"error":"traffic_unavailable"}\n'
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
if [ "${1:-get}" != get ]; then
|
||||
mkdir -p /run
|
||||
exec 9>/run/unisoc-cpu-voltage.lock
|
||||
flock -x 9
|
||||
fi
|
||||
exec ucode "${MU300_CPU_VOLTAGE_UC:-/usr/libexec/unisoc-modem/cpu-voltage.uc}" "${1:-get}"
|
||||
@@ -0,0 +1,99 @@
|
||||
// Boot-only voltage profiles. No arbitrary shell arguments, live voltage
|
||||
// writes, AT access, polling worker, or firmware/boot partition modifications.
|
||||
import * as fs from 'fs';
|
||||
const DIR=getenv('MU300_CPU_VOLTAGE_DIR') || '/etc/unisoc-modem';
|
||||
const RUN=getenv('MU300_CPU_VOLTAGE_RUN') || '/run';
|
||||
const ROOT=getenv('MU300_CPU_SYS') || '/sys/devices/system/cpu/cpufreq';
|
||||
const CONFIG=DIR+'/cpu-voltage.json', ARMED=DIR+'/cpu-voltage-armed.json';
|
||||
const BOOT=trim(fs.readfile(getenv('MU300_CPU_BOOT_ID') || '/proc/sys/kernel/random/boot_id') || '');
|
||||
const PLATFORM=getenv('MU300_CPU_PLATFORM') || '/opt/mu300/bin/cpu-voltage-platform';
|
||||
function readjson(path) { try { return json(fs.readfile(path) || 'null'); } catch(e) { return null; } }
|
||||
function valid(v) {
|
||||
if(type(v)!='array' || length(v)!=3) return false;
|
||||
for(let n in v) if(type(n)!='int' || n < -50000 || n > 25000 || n%3125) return false;
|
||||
return true;
|
||||
}
|
||||
function store(path,value) {
|
||||
let s=sprintf('%J\n',value), tmp=path+'.new';
|
||||
fs.mkdir(DIR,448);
|
||||
if(fs.writefile(tmp,s)!=length(s) || !fs.chmod(tmp,384) || !fs.rename(tmp,path)) {
|
||||
fs.unlink(tmp); return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function supported(force) {
|
||||
let cache=RUN+'/unisoc-cpu-firmware.json', c=readjson(cache);
|
||||
if(!force && BOOT && c?.boot==BOOT) return c.supported===true;
|
||||
// Only the installed platform adapter knows its verified SML hashes.
|
||||
// Environment overrides are test-only, never RPC/user configuration.
|
||||
if(!fs.access(PLATFORM,'x') || !match(PLATFORM,/^[\/a-zA-Z0-9_.-]+$/)) return false;
|
||||
let p=fs.popen(PLATFORM+' check >/dev/null 2>&1','r');
|
||||
let ok=p && p.close()==0;
|
||||
// Do not pin a transient early-boot discovery failure for the whole boot.
|
||||
if(BOOT && ok) store(cache,{boot:BOOT,supported:true});
|
||||
return !!ok;
|
||||
}
|
||||
function current() {
|
||||
let domains=[], seen={};
|
||||
for(let id in sort(fs.lsdir(ROOT)||[])) {
|
||||
if(!match(id,/^policy[0-9]+$/)) continue;
|
||||
let path=ROOT+'/'+id+'/', d=trim(fs.readfile(path+'scaling_voltage_domain')||''),
|
||||
offset=trim(fs.readfile(path+'scaling_voltage_offset')||'');
|
||||
if(!match(d,/^[012]$/) || !match(offset,/^-?[0-9]+$/) || seen[d]) continue;
|
||||
seen[d]=true;
|
||||
let table=[];
|
||||
for(let line in split(trim(fs.readfile(path+'scaling_voltage_table')||''),'\n')) {
|
||||
let pair=match(line,/^([0-9]+) ([0-9]+)$/);
|
||||
if(pair) push(table,{khz:int(pair[1]),uv:int(pair[2])});
|
||||
}
|
||||
push(domains,{id:int(d),policy:id,cpus:trim(fs.readfile(path+'affected_cpus')||''),offset:int(offset),table});
|
||||
}
|
||||
return domains;
|
||||
}
|
||||
function status() {
|
||||
let domains=current(), config=readjson(CONFIG), firmware=supported(false);
|
||||
let next=config?.version==1 && valid(config.offsets)?config.offsets:[0,0,0];
|
||||
return {ok:1,supported:firmware && length(domains)==3,firmware,domains,
|
||||
offsets:next,min:-50000,max:25000,step:3125,
|
||||
pending:length(filter(domains,d=>d.offset!=next[d.id]))>0,
|
||||
recovery:readjson(RUN+'/unisoc-cpu-voltage-recovery.json')?.reason || null};
|
||||
}
|
||||
function save(input) {
|
||||
if(!valid(input?.offsets)) return {ok:0,error:'CPU 电压配置无效'};
|
||||
let nonzero=length(filter(input.offsets,n=>n!=0))>0;
|
||||
if(nonzero && (!supported(true) || length(current())!=3)) return {ok:0,error:'当前内核或固件不支持电压调整'};
|
||||
if(!store(CONFIG,{version:1,offsets:input.offsets})) return {ok:0,error:'无法保存 CPU 设置'};
|
||||
// Do not clear ARMED while running at nonzero voltage, even on reset.
|
||||
return status();
|
||||
}
|
||||
function bootargs() {
|
||||
let config=readjson(CONFIG), armed=readjson(ARMED), reason=null;
|
||||
if(fs.stat(ARMED)) {
|
||||
if(BOOT && armed?.boot==BOOT) return '0,0,0'; // never apply twice
|
||||
reason='unclean_shutdown';
|
||||
if(fs.stat(CONFIG) && !fs.rename(CONFIG,CONFIG+'.rejected')) return '0,0,0';
|
||||
fs.unlink(ARMED); config=null;
|
||||
}
|
||||
if(reason) store(RUN+'/unisoc-cpu-voltage-recovery.json',{reason});
|
||||
if(config?.version!=1 || !valid(config.offsets) || !length(filter(config.offsets,n=>n!=0))) return '0,0,0';
|
||||
if(!BOOT || !supported(true)) return '0,0,0';
|
||||
if(!store(ARMED,{boot:BOOT,offsets:config.offsets})) return '0,0,0';
|
||||
return join(',',config.offsets);
|
||||
}
|
||||
let action=ARGV[0]||'get', result;
|
||||
try {
|
||||
if(action=='boot-args') { print(bootargs()+'\n'); exit(0); }
|
||||
if(action=='get') result=status();
|
||||
else if(action=='save') {
|
||||
let text=fs.stdin.read(4097);
|
||||
result=length(text)>4096?{ok:0,error:'CPU 电压配置无效'}:save(json(text));
|
||||
} else if(action=='shutdown') {
|
||||
let armed=readjson(ARMED);
|
||||
result={ok:!fs.stat(ARMED) || (BOOT && armed?.boot==BOOT && fs.unlink(ARMED))?1:0};
|
||||
} else result={ok:0,error:'CPU 电压配置无效'};
|
||||
} catch(e) {
|
||||
if(action=='boot-args') { print('0,0,0\n'); exit(0); }
|
||||
result={ok:0,error:'CPU 电压配置无效'};
|
||||
}
|
||||
print(sprintf('%J\n',result));
|
||||
exit(result.ok?0:1);
|
||||
@@ -0,0 +1,57 @@
|
||||
// E5-compatible placeholders, adapted to MU300's pinned HTTPS transport.
|
||||
// This helper only validates/renders data. It never runs commands or sends mail.
|
||||
import { readfile } from 'fs';
|
||||
function fail() { print('{"ok":0}\n'); exit(1); }
|
||||
function urlenc(s) {
|
||||
let out = '';
|
||||
for (let i = 0; i < length(s); i++) {
|
||||
let c = substr(s, i, 1);
|
||||
out += match(c, /[A-Za-z0-9_.~-]/) ? c : sprintf('%%%02X', ord(s, i));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function fill(s, values, encode) {
|
||||
return replace(s, /\{(from|text|time|sim|device|kind)\}/g,
|
||||
(all, key) => encode(`${values[key] ?? ''}`));
|
||||
}
|
||||
function walk(value, values) {
|
||||
if (type(value) == 'string') return fill(value, values, (s) => s);
|
||||
if (type(value) == 'array') return map(value, (v) => walk(v, values));
|
||||
if (type(value) == 'object') {
|
||||
let out = {};
|
||||
for (let k, v in value) out[k] = walk(v, values);
|
||||
return out;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
try {
|
||||
let input = json(readfile('/dev/stdin')), c = input.config, v = input.values ?? {};
|
||||
if (type(c) != 'object') fail();
|
||||
let method = c.webhook_method ?? 'POST';
|
||||
let ct = c.webhook_content_type ?? 'application/json';
|
||||
let body = c.webhook_body ?? '', headers = c.webhook_headers ?? '';
|
||||
let timeout = c.webhook_timeout ?? 12, url = c.webhook_url ?? '';
|
||||
if (type(body) != 'string' || length(body) > 8192 ||
|
||||
type(headers) != 'string' || length(headers) > 4096 ||
|
||||
(method != 'GET' && method != 'POST') ||
|
||||
index(['application/json', 'application/x-www-form-urlencoded', 'text/plain'], ct) < 0 ||
|
||||
!match(`${timeout}`, /^[0-9]+$/) || +timeout < 1 || +timeout > 120) fail();
|
||||
// Placeholders may appear in path/query, never the TLS/DNS authority.
|
||||
let authority = match(url, /^https:\/\/([^\/?#]+)/);
|
||||
if (url && (!authority || match(authority[1], /[{}@]/) || match(url, /[[:space:][:cntrl:]#]/))) fail();
|
||||
let hs = [];
|
||||
for (let h in split(headers, '\n')) {
|
||||
if (!length(h)) continue;
|
||||
if (length(hs) >= 16 || !match(h, /^[A-Za-z0-9!#$%&'*+.^_`|~-]+:[^[:cntrl:]]+$/)) fail();
|
||||
let name = lc(split(h, ':')[0]);
|
||||
if (index(['host', 'content-length', 'content-type', 'transfer-encoding', 'connection', 'expect'], name) >= 0) fail();
|
||||
push(hs, h);
|
||||
}
|
||||
let rendered = body;
|
||||
if (length(body)) {
|
||||
if (ct == 'application/json') rendered = sprintf('%J', walk(json(body), v));
|
||||
else rendered = fill(body, v, ct == 'application/x-www-form-urlencoded' ? urlenc : (s) => s);
|
||||
}
|
||||
print(sprintf('%J\n', { ok: 1, url: fill(url, v, urlenc), body: rendered,
|
||||
method, content_type: ct, headers: join('\n', hs), timeout: +timeout }));
|
||||
} catch (e) { fail(); }
|
||||
@@ -9,10 +9,13 @@ BASE=${MU300_FORWARD_DIR:-/etc/unisoc-modem/forward}
|
||||
POOL=${MU300_SMS_POOL:-$(uci -q get unisoc_modem.main.sms_pool 2>/dev/null)}
|
||||
[ -d "${POOL:-/etc/unisoc-modem/sms}/msg" ] || [ ! -d /etc/mu300/sms/msg ] || POOL=/etc/mu300/sms
|
||||
POOL=${POOL:-/etc/unisoc-modem/sms}
|
||||
ROOT_POOL=$POOL
|
||||
CONFIG=$BASE/config.json
|
||||
STATE=$BASE/state
|
||||
RESULT=${MU300_FORWARD_RESULT:-/run/unisoc-modem-forward-result}
|
||||
HISTORY=${MU300_FORWARD_HISTORY:-$RESULT.history}
|
||||
ROOT_RESULT=$RESULT
|
||||
RENDERER=${MU300_FORWARD_RENDERER:-/usr/libexec/unisoc-modem/forward-template.uc}
|
||||
SMS=${MU300_SMS_BIN:-$(uci -q get unisoc_modem.main.sms_command 2>/dev/null)}
|
||||
[ -n "$SMS" ] || SMS=$(command -v mu300-sms 2>/dev/null || true)
|
||||
case "$SMS" in */*) ;; *) SMS=$(command -v "$SMS" 2>/dev/null || true) ;; esac
|
||||
@@ -30,6 +33,41 @@ reply_error() {
|
||||
reply_ok() { printf '{"ok":1}\n'; }
|
||||
number() { case "$1" in ''|*[!0-9]*) return 1 ;; *) return 0 ;; esac; }
|
||||
bool() { [ "$1" = 0 ] || [ "$1" = 1 ]; }
|
||||
read_mode() {
|
||||
forward_mode=shared
|
||||
[ ! -r "$BASE/mode" ] || read -r forward_mode < "$BASE/mode"
|
||||
case "$forward_mode" in shared|per_sim) ;; *) return 1 ;; esac
|
||||
}
|
||||
select_profile() {
|
||||
profile=${1:-shared}
|
||||
CONFIG=$BASE/config.json STATE=$BASE/state POOL=$ROOT_POOL RESULT=$ROOT_RESULT
|
||||
case "$profile" in
|
||||
shared) ;;
|
||||
sim0) CONFIG=$BASE/config.sim0.json; RESULT=$ROOT_RESULT.sim0 ;;
|
||||
sim1)
|
||||
[ "$(uci -q get unisoc_modem.main.sim_slots 2>/dev/null)" = 2 ] || return 1
|
||||
CONFIG=$BASE/config.sim1.json STATE=$BASE/state.sim1 POOL=$ROOT_POOL/sim1 RESULT=$ROOT_RESULT.sim1 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
webhook_fields() {
|
||||
json_add_string webhook_method "$webhook_method"
|
||||
json_add_string webhook_content_type "$webhook_content_type"
|
||||
json_add_string webhook_body "$webhook_body"
|
||||
json_add_string webhook_headers "$webhook_headers"
|
||||
json_add_int webhook_timeout "$webhook_timeout"
|
||||
}
|
||||
render_webhook() { # JSON input, no eval or shell expansion of templates
|
||||
json_init; json_add_object config
|
||||
json_add_string webhook_url "$webhook_url"; webhook_fields; json_close_object
|
||||
json_add_object values
|
||||
json_add_string from "${_from:-}"; json_add_string text "${_text:-}"
|
||||
json_add_string time "${_date:-}"
|
||||
json_add_string sim "SIM$((${MU300_SIM_SLOT:-0} + 1))"
|
||||
json_add_string device "${nickname:-$(cat /proc/sys/kernel/hostname 2>/dev/null)}"
|
||||
json_add_string kind "${_kind:-sms}"; json_close_object
|
||||
json_dump | ucode "$RENDERER" 2>/dev/null
|
||||
}
|
||||
one_line() {
|
||||
case "$1" in *"$NL"*|*"$CR"*) return 1 ;; esac
|
||||
[ -z "$(printf '%s' "$1" | LC_ALL=C tr -d '\040-\176\200-\377')" ]
|
||||
@@ -125,6 +163,7 @@ load_config() {
|
||||
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
|
||||
[ -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
|
||||
@@ -132,6 +171,11 @@ load_config() {
|
||||
json_get_vars power_forward_enabled blacklist_phone blacklist_keywords nickname
|
||||
json_get_vars smtp_forward_device_info dingtalk_forward_device_info sms_forward_device_info
|
||||
json_get_var template_language template_language ''
|
||||
json_get_var webhook_method webhook_method POST
|
||||
json_get_var webhook_content_type webhook_content_type application/json
|
||||
json_get_var webhook_body webhook_body ''
|
||||
json_get_var webhook_headers webhook_headers ''
|
||||
json_get_var webhook_timeout webhook_timeout 12
|
||||
}
|
||||
load_state() {
|
||||
last_id=0 since=0 power_percent=-1 power_status=none
|
||||
@@ -154,6 +198,7 @@ save_config() {
|
||||
json_add_string method "$method"
|
||||
json_add_string template_language "$template_language"
|
||||
json_add_string webhook_url "$webhook_url"
|
||||
webhook_fields
|
||||
json_add_string dingtalk_webhook "$dingtalk_webhook"
|
||||
json_add_string dingtalk_secret "$dingtalk_secret"
|
||||
json_add_string sms_to_phone "$sms_to_phone"
|
||||
@@ -179,7 +224,12 @@ record_delivery() { # kind only; never store destination, source or message cont
|
||||
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
|
||||
# Writers already hold state.lock. Keep 30 small records in RAM, newest first.
|
||||
{
|
||||
printf '%s|%s|%s|%s\n' "$(date +%s)" "$1" "$method" "$DELIVER_RESULT"
|
||||
printf '%s|%s|%s|%s' "$(date +%s)" "$1" "$method" "$DELIVER_RESULT"
|
||||
case "${MU300_SIM_SLOT:-}" in 0|1)
|
||||
case "${HTTP_CODE:-0}" in [1-5][0-9][0-9]) _http=$HTTP_CODE ;; *) _http=0 ;; esac
|
||||
printf '|%s|%s' "$MU300_SIM_SLOT" "$_http" ;;
|
||||
esac
|
||||
printf '\n'
|
||||
[ ! -r "$HISTORY" ] || head -n 29 "$HISTORY"
|
||||
} > "$HISTORY.tmp.$$" && mv -f "$HISTORY.tmp.$$" "$HISTORY"
|
||||
}
|
||||
@@ -187,18 +237,22 @@ add_history() {
|
||||
json_add_array history
|
||||
if [ -r "$HISTORY" ]; then
|
||||
_history_n=0
|
||||
while IFS='|' read -r _when _kind _method _result _extra; do
|
||||
while IFS='|' read -r _when _kind _method _result _slot _http _extra; do
|
||||
_history_n=$((_history_n + 1)); [ "$_history_n" -le 30 ] || break
|
||||
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
|
||||
[ -z "$_extra" ] || continue
|
||||
case "$_slot" in ''|0|1) ;; *) continue ;; esac
|
||||
case "$_http" in ''|0|[1-5][0-9][0-9]) ;; *) continue ;; esac
|
||||
json_add_object ''
|
||||
json_add_int time "$_when"
|
||||
json_add_string kind "$_kind"
|
||||
json_add_string method "$_method"
|
||||
json_add_string result "$_result"
|
||||
[ -z "$_slot" ] || json_add_int slot "$_slot"
|
||||
[ -z "$_http" ] || json_add_int http_code "$_http"
|
||||
json_close_object
|
||||
done < "$HISTORY"
|
||||
fi
|
||||
@@ -230,14 +284,19 @@ add_status() {
|
||||
json_close_object
|
||||
}
|
||||
get_view() {
|
||||
read_mode && select_profile "${1:-shared}" || { reply_error invalid_config; return; }
|
||||
load_config || { reply_error invalid_config; return; }
|
||||
load_state
|
||||
json_init
|
||||
json_add_string mode "$forward_mode"
|
||||
json_add_string profile "$profile"
|
||||
json_add_int sim_slots "$([ "$(uci -q get unisoc_modem.main.sim_slots 2>/dev/null)" = 2 ] && echo 2 || echo 1)"
|
||||
json_add_object config
|
||||
json_add_boolean enabled "$enabled"
|
||||
json_add_string method "$method"
|
||||
json_add_string template_language "$template_language"
|
||||
json_add_string webhook_url "$webhook_url"
|
||||
webhook_fields
|
||||
json_add_string dingtalk_webhook "$dingtalk_webhook"
|
||||
json_add_boolean dingtalk_secret_configured "$([ -n "$dingtalk_secret" ] && echo 1 || echo 0)"
|
||||
json_add_string sms_to_phone "$sms_to_phone"
|
||||
@@ -260,19 +319,33 @@ get_view() {
|
||||
json_dump
|
||||
}
|
||||
status_only() {
|
||||
read_mode && select_profile "${1:-shared}" || { reply_error invalid_config; return; }
|
||||
load_config || { reply_error invalid_config; return; }
|
||||
load_state
|
||||
json_init
|
||||
json_add_string mode "$forward_mode"
|
||||
json_add_string profile "$profile"
|
||||
add_status
|
||||
json_dump
|
||||
}
|
||||
set_config() {
|
||||
ensure_base || { reply_error forward_storage_failed; return; }
|
||||
exec 8> "$BASE/state.lock"
|
||||
flock -x 8 || { reply_error forward_storage_failed; return; }
|
||||
flock -n 8 || { reply_error forward_busy; return; }
|
||||
_payload=$(cat)
|
||||
[ ${#_payload} -le 12288 ] && json_load "$_payload" 2>/dev/null ||
|
||||
[ ${#_payload} -le 32768 ] && json_load "$_payload" 2>/dev/null ||
|
||||
{ reply_error invalid_config; return; }
|
||||
json_get_var new_profile profile shared
|
||||
json_get_var new_mode mode ''
|
||||
read_mode && select_profile "$new_profile" || { reply_error invalid_config; return; }
|
||||
old_mode=$forward_mode
|
||||
new_mode=${new_mode:-$old_mode}
|
||||
case "$new_mode" in shared|per_sim) ;; *) reply_error invalid_config; return ;; esac
|
||||
json_get_var new_webhook_method webhook_method POST
|
||||
json_get_var new_webhook_content_type webhook_content_type application/json
|
||||
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_enabled enabled
|
||||
json_get_var new_method method
|
||||
json_get_var new_template_language template_language
|
||||
@@ -299,6 +372,8 @@ set_config() {
|
||||
# Older clients omit this field; retain the saved language in that case.
|
||||
template_language=${new_template_language:-${template_language:-zh}}
|
||||
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
|
||||
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}
|
||||
@@ -321,6 +396,8 @@ 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; }
|
||||
number "$webhook_timeout" && [ "$webhook_timeout" -ge 1 ] && [ "$webhook_timeout" -le 120 ] &&
|
||||
render_webhook >/dev/null || { reply_error invalid_forward_config; return; }
|
||||
[ -z "$dingtalk_webhook" ] || {
|
||||
https_url "$dingtalk_webhook" &&
|
||||
case "$dingtalk_webhook" in https://oapi.dingtalk.com/robot/send*) true ;; *) false ;; esac
|
||||
@@ -349,6 +426,7 @@ set_config() {
|
||||
[ -r "$POOL/next_id" ] || { reply_error sms_list_unavailable; return; }
|
||||
fi
|
||||
power_read
|
||||
[ "$profile" = shared ] || power_forward_enabled=0
|
||||
[ "$power_forward_enabled" = 0 ] || [ "$power_ok" = 1 ] ||
|
||||
{ reply_error power_unavailable; return; }
|
||||
load_state
|
||||
@@ -359,13 +437,32 @@ set_config() {
|
||||
since=$(date +%s)
|
||||
# A channel/enable change establishes a separate barrier for SIM 2,
|
||||
# before the new configuration becomes visible to the single worker.
|
||||
reset_second_barrier || { reply_error forward_storage_failed; return; }
|
||||
if [ "$profile" = shared ]; then
|
||||
reset_second_barrier || { reply_error forward_storage_failed; return; }
|
||||
fi
|
||||
fi
|
||||
# Switching routing never replays the backlog from either inbox. Publish
|
||||
# routing last, under the same lock as the worker and all profile writes.
|
||||
if [ "$new_mode" != "$old_mode" ]; then
|
||||
( POOL=$ROOT_POOL; reset_second_barrier ) || { reply_error forward_storage_failed; return; }
|
||||
( STATE=$BASE/state; last_id=$(cat "$ROOT_POOL/next_id" 2>/dev/null)
|
||||
if number "$last_id"; then since=$(date +%s); save_state; else rm -f "$STATE"; fi
|
||||
) || { reply_error forward_storage_failed; return; }
|
||||
load_state
|
||||
fi
|
||||
if [ "$power_forward_enabled" = 1 ] && [ "$power_ok" = 1 ]; then
|
||||
power_percent=$current_percent; power_status=$current_status
|
||||
( STATE=$BASE/state.power; save_state ) || { reply_error forward_storage_failed; return; }
|
||||
fi
|
||||
# Save the replay barrier before making the new enabled configuration visible.
|
||||
save_state && save_config || { reply_error forward_storage_failed; return; }
|
||||
# A not-yet-initialized inbox must stay without a cursor: the first ready
|
||||
# worker pass will baseline it. Saving 0|0 here would legitimize imports.
|
||||
if [ -r "$POOL/next_id" ] || [ -s "$STATE" ]; then
|
||||
save_state || { reply_error forward_storage_failed; return; }
|
||||
fi
|
||||
save_config || { reply_error forward_storage_failed; return; }
|
||||
printf '%s\n' "$new_mode" > "$BASE/mode.tmp.$$" && mv -f "$BASE/mode.tmp.$$" "$BASE/mode" ||
|
||||
{ reply_error forward_storage_failed; return; }
|
||||
write_result idle idle || :
|
||||
reply_ok
|
||||
}
|
||||
@@ -473,6 +570,7 @@ sms_units() {
|
||||
}
|
||||
deliver() { # kind, sender, body, date. Returns a finite result code in DELIVER_RESULT.
|
||||
_kind=$1 _from=$2 _text=$3 _date=${4:-}; DELIVER_RESULT=delivery_failed
|
||||
HTTP_CODE=0
|
||||
[ "$enabled" = 1 ] || { DELIVER_RESULT=disabled; return 1; }
|
||||
format_message "$_kind" "$_from" "$_text"
|
||||
# Webhooks keep raw SMS bodies and stable JSON keys; only generated test
|
||||
@@ -509,7 +607,7 @@ EOF_TARGET
|
||||
[ "$_delivered" = 1 ] || { DELIVER_RESULT=self_forward_blocked; return 1; }
|
||||
DELIVER_RESULT=sent; return 0
|
||||
fi
|
||||
_tmp=/run/unisoc-modem-forward.$$
|
||||
_tmp=${MU300_FORWARD_RUNTIME:-/run}/unisoc-modem-forward.$$
|
||||
if [ "$method" = smtp ]; then
|
||||
command -v msmtp >/dev/null 2>&1 || { DELIVER_RESULT=delivery_failed; return 1; }
|
||||
resolve_public "$smtp_host" "$smtp_port" ||
|
||||
@@ -571,14 +669,34 @@ EOF_TARGET
|
||||
_url=$webhook_url
|
||||
fi
|
||||
json_dump > "$_tmp.body"
|
||||
curl -q --noproxy '*' --proto '=https' --resolve "$RESOLVE" --max-redirs 0 --connect-timeout 4 \
|
||||
--max-time 12 --max-filesize 4096 --fail -sS -H 'Content-Type: application/json; charset=utf-8' \
|
||||
--data-binary "@$_tmp.body" -o "$_tmp.reply" "$_url" >/dev/null 2>&1
|
||||
_request_method=POST _request_type=application/json _request_timeout=12 _request_headers=
|
||||
if [ "$method" = webhook ]; then
|
||||
_request=$(render_webhook) && json_load "$_request" || {
|
||||
rm -f "$_tmp.body"; DELIVER_RESULT=invalid_forward_config; return 1;
|
||||
}
|
||||
json_get_var _url url
|
||||
json_get_var _request_method method
|
||||
json_get_var _request_type content_type
|
||||
json_get_var _request_timeout timeout
|
||||
json_get_var _request_headers headers
|
||||
if [ -n "$webhook_body" ] || [ "$_request_type" != application/json ]; then
|
||||
json_get_var _request_body body
|
||||
printf '%s' "$_request_body" > "$_tmp.body"
|
||||
fi
|
||||
fi
|
||||
printf '%s\n' "$_request_headers" > "$_tmp.headers"
|
||||
set -- -q --noproxy '*' --proto '=https' --resolve "$RESOLVE" --max-redirs 0 --connect-timeout 4 \
|
||||
--max-time "$_request_timeout" --max-filesize 4096 --fail -sS \
|
||||
-H "Content-Type: $_request_type; charset=utf-8" -H "@$_tmp.headers" \
|
||||
-X "$_request_method" -o "$_tmp.reply" -w '%{http_code}'
|
||||
[ "$_request_method" = GET ] || set -- "$@" --data-binary "@$_tmp.body"
|
||||
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
|
||||
fi
|
||||
rm -f "$_tmp.body" "$_tmp.reply"
|
||||
rm -f "$_tmp.body" "$_tmp.reply" "$_tmp.headers"
|
||||
fi
|
||||
[ "$_rc" -eq 0 ] && { DELIVER_RESULT=sent; return 0; }
|
||||
return 1
|
||||
@@ -672,8 +790,12 @@ reset_second_barrier() (
|
||||
save_state
|
||||
)
|
||||
process_second_sim() (
|
||||
[ "$enabled" = 1 ] || exit 0
|
||||
[ "$(uci -q get unisoc_modem.main.sim_slots 2>/dev/null)" = 2 ] || exit 0
|
||||
if [ "${forward_mode:-shared}" = per_sim ]; then
|
||||
CONFIG=$BASE/config.sim1.json RESULT=$ROOT_RESULT.sim1
|
||||
load_config || exit 1
|
||||
fi
|
||||
[ "$enabled" = 1 ] || exit 0
|
||||
STATE=$BASE/state.sim1
|
||||
POOL=$POOL/sim1
|
||||
export MU300_SMS_POOL=$POOL MU300_SIM_SLOT=1 MU300_AT_DIR=/run/mu300-at4
|
||||
@@ -688,6 +810,24 @@ process_second_sim() (
|
||||
load_state; read_result
|
||||
process_sms
|
||||
)
|
||||
process_first_sim() (
|
||||
export MU300_SIM_SLOT=0 MU300_SMS_POOL=$ROOT_POOL MU300_AT_DIR=/run/mu300-at
|
||||
export MU300_SMS_OP_LOCK=/tmp/mu300-sms-op.lock MU300_SMS_DIRECT_FLAG=/run/mu300-sms-direct
|
||||
if [ "$forward_mode" = per_sim ]; then
|
||||
CONFIG=$BASE/config.sim0.json RESULT=$ROOT_RESULT.sim0
|
||||
load_config || exit 1
|
||||
fi
|
||||
[ "$enabled" = 1 ] || exit 0
|
||||
if [ ! -s "$STATE" ]; then
|
||||
last_id=$(cat "$POOL/next_id" 2>/dev/null)
|
||||
number "$last_id" || exit 0
|
||||
since=$(date +%s)
|
||||
save_state || exit 1
|
||||
exit 0
|
||||
fi
|
||||
load_state; read_result
|
||||
process_sms
|
||||
)
|
||||
process_power() {
|
||||
power_read
|
||||
[ "$power_ok" = 1 ] || return 0
|
||||
@@ -695,6 +835,8 @@ process_power() {
|
||||
_old_percent=$power_percent; _old_status=$power_status
|
||||
power_percent=$current_percent; power_status=$current_status
|
||||
save_state || return 1
|
||||
# Establish a power baseline on first observation, not a synthetic alert.
|
||||
[ "$_old_status" != none ] || return 0
|
||||
[ "$enabled" = 1 ] && [ "$power_forward_enabled" = 1 ] || return 0
|
||||
# Match the ZWRT power policy: a status transition, or one notification
|
||||
# when crossing any threshold (including a jump over several points).
|
||||
@@ -720,14 +862,34 @@ process_power() {
|
||||
}
|
||||
test_send() {
|
||||
ensure_base || exit 1
|
||||
exec 8> "$BASE/state.lock"
|
||||
flock -x 8 || exit 1
|
||||
if [ "${2:-}" != locked ]; then
|
||||
exec 8> "$BASE/state.lock"
|
||||
flock -n 8 || exit 1
|
||||
fi
|
||||
select_profile "${1:-shared}" || exit 1
|
||||
if [ "$profile" = sim1 ]; then
|
||||
export MU300_SIM_SLOT=1 MU300_SMS_POOL=$POOL MU300_AT_DIR=/run/mu300-at4
|
||||
export MU300_SMS_OP_LOCK=/tmp/mu300-sms-op-sim1.lock MU300_SMS_DIRECT_FLAG=/run/mu300-sms-direct-sim1
|
||||
else
|
||||
export MU300_SIM_SLOT=0 MU300_SMS_POOL=$ROOT_POOL MU300_AT_DIR=/run/mu300-at
|
||||
export MU300_SMS_OP_LOCK=/tmp/mu300-sms-op.lock MU300_SMS_DIRECT_FLAG=/run/mu300-sms-direct
|
||||
fi
|
||||
load_config || exit 1
|
||||
load_state; read_result
|
||||
deliver test NMS '' || :
|
||||
record_delivery test || :
|
||||
write_result "$DELIVER_RESULT" "$power_last_result" || :
|
||||
}
|
||||
start_test() {
|
||||
ensure_base && select_profile "${1:-shared}" && load_config || { reply_error invalid_config; return; }
|
||||
[ "$enabled" = 1 ] || { reply_error disabled; return; }
|
||||
exec 8> "$BASE/state.lock"
|
||||
flock -n 8 || { reply_error forward_busy; 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 &
|
||||
printf '{"ok":1,"started":1}\n'
|
||||
}
|
||||
run_daemon() {
|
||||
ensure_base || exit 1
|
||||
# procd owns the process. A second manual start exits without stealing work.
|
||||
@@ -736,35 +898,23 @@ run_daemon() {
|
||||
while :; do
|
||||
exec 8> "$BASE/state.lock"
|
||||
flock -x 8 || exit 1
|
||||
if load_config; then
|
||||
if [ "$enabled" = 1 ] && [ ! -s "$STATE" ]; then
|
||||
# A manually restored config without replay state is not a
|
||||
# license to forward the whole historical local pool.
|
||||
last_id=$(cat "$POOL/next_id" 2>/dev/null)
|
||||
if ! number "$last_id"; then
|
||||
flock -u 8
|
||||
sleep "${MU300_FORWARD_POLL:-5}"
|
||||
continue
|
||||
fi
|
||||
since=$(date +%s)
|
||||
power_read
|
||||
power_percent=$current_percent; power_status=$current_status
|
||||
save_state || exit 1
|
||||
fi
|
||||
if read_mode && select_profile shared && load_config; then
|
||||
process_first_sim || :
|
||||
load_state; read_result
|
||||
process_sms || :
|
||||
process_power || :
|
||||
( STATE=$BASE/state.power; load_state; process_power ) || :
|
||||
process_second_sim || :
|
||||
fi
|
||||
flock -u 8
|
||||
sleep "${MU300_FORWARD_POLL:-5}"
|
||||
# Idle sleep must not retain the singleton lock after procd stops us.
|
||||
sleep "${MU300_FORWARD_POLL:-5}" 8>&- 9>&-
|
||||
done
|
||||
}
|
||||
case "${1:-}" in
|
||||
get) get_view ;;
|
||||
status) status_only ;;
|
||||
get) get_view "${2:-shared}" ;;
|
||||
status) status_only "${2:-shared}" ;;
|
||||
set) set_config ;;
|
||||
test-run) test_send ;;
|
||||
test-run) test_send "${2:-shared}" "${3:-}" ;;
|
||||
test-start) start_test "${2:-shared}" ;;
|
||||
run) run_daemon ;;
|
||||
*) echo 'usage: sms-forward {get|status|set|test-run|run}' >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -6,7 +6,7 @@
|
||||
"mu300dash": [
|
||||
"sysinfo", "status", "rates", "cells", "signal", "at_history",
|
||||
"lock_get", "lock_status", "sms_list", "sms_show", "forward_get",
|
||||
"forward_status", "traffic_get", "usb_get", "usb_net_list", "cpu_get", "sim_get", "data_sim_get", "data_sim_status"
|
||||
"forward_status", "traffic_get", "usb_get", "usb_net_list", "cpu_get", "cpu_voltage_get", "sim_get", "data_sim_get", "data_sim_status"
|
||||
]
|
||||
},
|
||||
"uci": {
|
||||
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh /etc/rc.common
|
||||
# Rootfs is mounted; load cpufreq before modem/network bring-up, with or without
|
||||
# the optional dashboard. Factory offsets if the plugin is not installed.
|
||||
START=08
|
||||
start() {
|
||||
/opt/mu300/bin/cpu-voltage-platform load
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#!/bin/sh
|
||||
# Platform adapter only. The standalone LuCI package owns UI/profile policy.
|
||||
# Never write firmware partitions or voltage regulators from userspace.
|
||||
set -eu
|
||||
module=sprd_cpufreq_v2_driver
|
||||
ko=/lib/modules/$(uname -r)/sprd-cpufreq-v2-driver.ko
|
||||
[ -f "$ko" ] || ko=/lib/modules/$(uname -r)/extra/sprd-cpufreq-v2-driver.ko
|
||||
helper=/usr/libexec/unisoc-modem/cpu-voltage
|
||||
supported() {
|
||||
tr '\000' '\n' </sys/firmware/devicetree/base/compatible | grep -qx 'sprd,ums9620' || return 1
|
||||
expected=ff4782690fd805ff54fe34853ef8ee5c7e51c3259e20077c55373b50a4b259c2
|
||||
for slot in a b; do
|
||||
part=/dev/disk/by-partlabel/sml_$slot
|
||||
[ -b "$part" ] || part=/dev/block/by-name/sml_$slot
|
||||
if [ ! -b "$part" ]; then
|
||||
# Android-style by-name links are created by vendor startup, later
|
||||
# than S08. Resolve already-present kernel partition labels now;
|
||||
# never delay CPU/network boot waiting for those optional symlinks.
|
||||
set -- $(grep -l "^PARTNAME=sml_$slot\$" /sys/class/block/*/uevent)
|
||||
[ "$#" = 1 ] || return 1
|
||||
part=${1%/uevent}
|
||||
part=/dev/${part##*/}
|
||||
fi
|
||||
[ -b "$part" ] || return 1
|
||||
real=$(readlink -f "$part") || return 1
|
||||
[ "$(cat "/sys/class/block/${real##*/}/size")" = 2048 ] || return 1
|
||||
hash=$(sha256sum "$part") || return 1
|
||||
[ "${hash%% *}" = "$expected" ] || return 1
|
||||
done
|
||||
}
|
||||
case ${1:-load} in
|
||||
check) supported ;;
|
||||
load)
|
||||
[ -f "$ko" ] || exit 0 # Old/built-in driver; do not reinitialize it.
|
||||
mkdir -p /run
|
||||
exec 9>/run/mu300-cpu-driver.lock
|
||||
flock -x 9
|
||||
[ ! -d /sys/module/$module ] || exit 0
|
||||
offsets=0,0,0
|
||||
if [ -x "$helper" ]; then
|
||||
offsets=$("$helper" boot-args) || offsets=0,0,0
|
||||
fi
|
||||
# Defense in depth before passing any non-factory value to firmware.
|
||||
if [ "$offsets" != 0,0,0 ]; then
|
||||
supported || offsets=0,0,0
|
||||
sync # Persist the crash guard BEFORE the one-shot DVFS_INIT.
|
||||
fi
|
||||
insmod "$ko" "voltage_offset_uv=$offsets"
|
||||
;;
|
||||
*) exit 2 ;;
|
||||
esac
|
||||
@@ -6,6 +6,8 @@
|
||||
# nothing the host ever sees. So they are loaded here, once userspace is up and the gadget is long since bound.
|
||||
# sipa-dele is deliberately not in that list: it has to come after the modem, not with it (see below).
|
||||
M=/lib/modules/$(uname -r)
|
||||
# Also covers non-OpenWrt roots; the loader is serialized and idempotent.
|
||||
/opt/mu300/bin/cpu-voltage-platform load || echo 'CPU driver load failed'
|
||||
if [ -f "$M/sipc-core.ko" ] && ! [ -e /dev/modem ]; then
|
||||
for m in sprd_systimer sprd_time_sync sprd_time_sync_cp trusty trusty-pm trusty-log trusty-irq trusty-ipc \
|
||||
trusty-virtio sprd_shm unisoc-mailbox sprd-sipc-virt-bus sprd_power_manager sipc-core spipe spool \
|
||||
|
||||
@@ -151,7 +151,7 @@ check() {
|
||||
keep_list() {
|
||||
case $1 in
|
||||
ubuntu) echo "etc/mu300 etc/ssh etc/hostname etc/localtime etc/timezone etc/fstab home root srv usr/local var/lib/bluetooth" ;;
|
||||
openwrt) echo "etc/config etc/mu300 etc/dropbear etc/rc.local root" ;;
|
||||
openwrt) echo "etc/config etc/mu300 etc/unisoc-modem etc/dropbear etc/rc.local root" ;;
|
||||
esac
|
||||
}
|
||||
# vendor files that the published images deliberately do not contain
|
||||
@@ -164,6 +164,27 @@ vendor_list() {
|
||||
esac
|
||||
}
|
||||
|
||||
# Backport upstream f7df326: BusyBox cp -an skips existing directories instead
|
||||
# of merging their contents. The image already has firmware/ and android/,
|
||||
# so that used to silently lose the device's firmware/runtime on update.
|
||||
# Preserve all image entries, including symlinks; never copy through a target
|
||||
# link. find visits each directory before its contents, allowing subtree skips.
|
||||
copy_missing() {
|
||||
[ -d "$1" ] && [ -d "$2" ] && [ ! -L "$2" ] || return 1
|
||||
( cd "$1" && find . ! -name . ) | {
|
||||
skip=
|
||||
while IFS= read -r p; do
|
||||
case $p in "$skip"/*) continue ;; esac
|
||||
if [ -e "$2/$p" ] || [ -L "$2/$p" ]; then
|
||||
{ [ -d "$2/$p" ] && [ ! -L "$2/$p" ]; } || skip=$p
|
||||
continue
|
||||
fi
|
||||
cp -a "$1/$p" "$2/$p" || exit 1
|
||||
skip=$p
|
||||
done
|
||||
}
|
||||
}
|
||||
|
||||
# Accounts are settings too, and /etc/shadow is not in keep_list: an update used to leave the image's own password
|
||||
# (the well-known ubuntu/ubuntu, or OpenWrt's empty root) and drop the users added on the device. Take the old
|
||||
# entry of every account both systems have (password hashes, group memberships merged), and bring over the users
|
||||
@@ -253,8 +274,10 @@ apply_one() { # apply_one OS TAG
|
||||
# firmware and the Android userspace come from this device, never from the release
|
||||
for v in $(vendor_list "$os"); do
|
||||
[ -d "$old/$v" ] || continue
|
||||
mkdir -p "$new/$v"
|
||||
cp -an "$old/$v/." "$new/$v/" 2>/dev/null || true
|
||||
mkdir -p "$new/$v" && copy_missing "$old/$v" "$new/$v" || {
|
||||
rm -rf "$new"
|
||||
die "$os: copying the vendor files failed, nothing was changed"
|
||||
}
|
||||
done
|
||||
# services enabled by hand (the links point into the system, so test with -L)
|
||||
if [ "$os" = ubuntu ]; then
|
||||
@@ -391,6 +414,11 @@ boot_update() { # boot_update TAG (MU300_KERNEL_BUNDLE=FILE uses a local mu30
|
||||
for os in $(installed_systems); do
|
||||
case $os in ubuntu) d=$DISK/$os/lib/modules/$krel/extra ;; *) d=$DISK/$os/lib/modules/$krel ;; esac
|
||||
mkdir -p "$d" && cp "$tmp"/modules/*.ko "$d/" || { echo "boot: installing the modules into $os failed" >&2; return 1; }
|
||||
# Built-in -> module transitions (cpufreq voltage profiles) need
|
||||
# fresh indexes on OpenWrt too, not only on Ubuntu.
|
||||
for f in modules.builtin modules.builtin.modinfo; do
|
||||
[ ! -f "$tmp/$f" ] || cp "$tmp/$f" "$DISK/$os/lib/modules/$krel/" || return 1
|
||||
done
|
||||
if [ "$os" = ubuntu ]; then
|
||||
# what the kernel has built in (bundles from v2026.09.29 on): modprobe of a built-in driver then
|
||||
# succeeds, and depmod stops warning
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/bin/sh
|
||||
# Isolated fake sysfs and firmware gate. Never loads a module or adjusts voltage.
|
||||
set -eu
|
||||
lib=$1
|
||||
base=$(mktemp -d /tmp/mu300-voltage-test.XXXXXX)
|
||||
export MU300_CPU_VOLTAGE_DIR=$base/etc MU300_CPU_VOLTAGE_RUN=$base/run
|
||||
export MU300_CPU_SYS=$base/sys MU300_CPU_BOOT_ID=$base/boot
|
||||
export MU300_CPU_PLATFORM=$base/platform
|
||||
mkdir -p "$base/etc" "$base/run" "$base/sys"
|
||||
printf 'boot-one\n' > "$base/boot"
|
||||
printf '#!/bin/sh\ntest ! -f "%s/unsupported"\n' "$base" > "$base/platform"
|
||||
chmod 755 "$base/platform"
|
||||
for d in 0 1 2; do
|
||||
dir=$base/sys/policy$d; mkdir -p "$dir"
|
||||
printf '%s\n' "$d" > "$dir/scaling_voltage_domain"
|
||||
printf '0\n' > "$dir/scaling_voltage_offset"
|
||||
printf '%s\n' "$d" > "$dir/affected_cpus"
|
||||
printf '1000000 750000\n1500000 850000\n' > "$dir/scaling_voltage_table"
|
||||
done
|
||||
call() { ucode "$lib" "$@"; }
|
||||
check() { jsonfilter -s "$1" -e "$2"; }
|
||||
out=$(call get)
|
||||
test "$(check "$out" '@.supported')" = true
|
||||
test "$(check "$out" '@.domains[0].table[0].uv')" = 750000
|
||||
for bad in '[]' '[1,0,0]' '[-53125,0,0]' '[28125,0,0]' '[0,0]' '["0",0,0]' '[0,0,0,0]' '[true,0,0]' '[0.5,0,0]'; do
|
||||
if printf '{"offsets":%s}' "$bad" | call save > "$base/out"; then echo 'accepted invalid offsets'; exit 1; fi
|
||||
done
|
||||
test ! -e "$base/etc/cpu-voltage.json"
|
||||
out=$(printf '{"offsets":[-3125,0,6250]}' | call save)
|
||||
test "$(check "$out" '@.pending')" = true
|
||||
test "$(call boot-args)" = '-3125,0,6250'
|
||||
test -f "$base/etc/cpu-voltage-armed.json"
|
||||
# Repeating startup cannot apply an offset twice.
|
||||
test "$(call boot-args)" = '0,0,0'
|
||||
# Reset while running must not erase the crash guard.
|
||||
printf '{"offsets":[0,0,0]}' | call save > "$base/out"
|
||||
test -f "$base/etc/cpu-voltage-armed.json"
|
||||
call shutdown > "$base/out"
|
||||
test ! -e "$base/etc/cpu-voltage-armed.json"
|
||||
printf '{"offsets":[-3125,0,0]}' | call save > "$base/out"
|
||||
test "$(call boot-args)" = '-3125,0,0'
|
||||
# Simulate an unclean boot, reject persisted voltage and never retry it.
|
||||
printf 'boot-two\n' > "$base/boot"
|
||||
test "$(call boot-args)" = '0,0,0'
|
||||
test -f "$base/etc/cpu-voltage.json.rejected"
|
||||
test ! -e "$base/etc/cpu-voltage.json"
|
||||
out=$(call get)
|
||||
test "$(check "$out" '@.recovery')" = unclean_shutdown
|
||||
# A clean shutdown preserves a saved profile across boots.
|
||||
printf '{"offsets":[0,3125,0]}' | call save > "$base/out"
|
||||
test "$(call boot-args)" = '0,3125,0'
|
||||
call shutdown > "$base/out"
|
||||
printf 'boot-three\n' > "$base/boot"
|
||||
test "$(call boot-args)" = '0,3125,0'
|
||||
call shutdown > "$base/out"
|
||||
# Unknown firmware may reset to defaults, but may not save/apply an offset.
|
||||
touch "$base/unsupported"
|
||||
if printf '{"offsets":[-3125,0,0]}' | call save > "$base/out"; then exit 1; fi
|
||||
test "$(call boot-args)" = '0,0,0'
|
||||
printf '{"offsets":[0,0,0]}' | call save > "$base/out"
|
||||
# Missing/duplicate domain interfaces are unsupported, never fabricate controls.
|
||||
rm "$base/unsupported" "$base/sys/policy2/scaling_voltage_domain"
|
||||
if printf '{"offsets":[0,0,3125]}' | call save > "$base/out"; then exit 1; fi
|
||||
test ! -e "$base/etc/cpu-voltage-armed.json"
|
||||
echo "PASS voltage validation/gate/persistence/reset/clean+unclean recovery: $base"
|
||||
@@ -0,0 +1,169 @@
|
||||
#!/bin/sh
|
||||
# Real jshn/ucode integration; all destinations, inboxes and transports isolated.
|
||||
set -e
|
||||
source=$1
|
||||
base=$(mktemp -d /tmp/mu300-forward-profiles.XXXXXX)
|
||||
export MU300_FORWARD_DIR=$base/config MU300_SMS_POOL=$base/pool MU300_FORWARD_RESULT=$base/result
|
||||
export MU300_FORWARD_BATTERY=$base/battery MU300_SMS_BIN=/bin/false
|
||||
export MU300_FORWARD_RUNTIME=$base
|
||||
export MU300_FORWARD_RENDERER=${source%/*}/forward-template.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"
|
||||
sed '/^case "${1:-}" in/,$d' "$source" > "$base/lib.sh"
|
||||
. "$base/lib.sh"
|
||||
uci() { case "$*" in *unisoc_modem.main.sim_slots*) echo 2 ;; *) return 1 ;; esac; }
|
||||
fail() { echo "FAIL: $*" >&2; exit 1; }
|
||||
check_set() {
|
||||
reply=$(printf '%s' "$1" | set_config)
|
||||
[ "$(printf '%s' "$reply" | jsonfilter -e '@.ok')" = 1 ] || fail "set $reply"
|
||||
}
|
||||
expect_error() {
|
||||
reply=$(printf '%s' "$1" | set_config)
|
||||
[ "$(printf '%s' "$reply" | jsonfilter -e '@.ok')" = 0 ] || fail 'invalid config accepted'
|
||||
}
|
||||
check_set '{"enabled":1,"method":"webhook","webhook_url":"https://shared.example.com/hook","template_language":"en"}'
|
||||
get_view shared > "$base/view"
|
||||
[ "$(jsonfilter -i "$base/view" -e '@.mode')" = shared ]
|
||||
[ "$(jsonfilter -i "$base/view" -e '@.config.webhook_timeout')" = 12 ]
|
||||
# Shared settings survive adding independent profiles; secrets never cross profiles.
|
||||
check_set '{"profile":"sim0","enabled":1,"method":"smtp","smtp_host":"smtp.example.com","smtp_username":"a@example.com","smtp_to":"b@example.com","smtp_password":"SECRET_A"}'
|
||||
check_set '{"profile":"sim1","enabled":1,"method":"smtp","smtp_host":"smtp.example.com","smtp_username":"c@example.com","smtp_to":"d@example.com","smtp_password":"SECRET_B"}'
|
||||
check_set '{"profile":"sim0","enabled":1,"method":"smtp","smtp_host":"smtp.example.com","smtp_username":"a@example.com","smtp_to":"b@example.com","smtp_password":""}'
|
||||
[ "$(jsonfilter -i "$BASE/config.sim0.json" -e '@.smtp_password')" = SECRET_A ]
|
||||
[ "$(jsonfilter -i "$BASE/config.sim1.json" -e '@.smtp_password')" = SECRET_B ]
|
||||
get_view sim0 > "$base/view"
|
||||
! grep -q SECRET "$base/view"
|
||||
check_set '{"profile":"sim0","enabled":1,"method":"webhook","webhook_url":"https://sim0.example.com/hook","clear_smtp_password":1}'
|
||||
check_set '{"profile":"sim1","enabled":1,"method":"webhook","webhook_url":"https://sim1.example.com/hook","clear_smtp_password":1}'
|
||||
old_sms() {
|
||||
printf '%s\n' "$2" > "$1/next_id"
|
||||
printf 'dir: mt\nfrom: 10010\nreceived: %s\nscts: old\nsource: direct\ncoding: pdu\n\n{from} "quoted"\n' "$(date +%s)" > "$1/msg/$(printf '%06d' "$2")"
|
||||
}
|
||||
old_sms "$ROOT_POOL" 1; old_sms "$ROOT_POOL/sim1" 1
|
||||
# Mode change baselines both inboxes, without changing any other profile.
|
||||
check_set '{"profile":"shared","mode":"per_sim","enabled":1,"method":"webhook","webhook_url":"https://shared.example.com/hook"}'
|
||||
[ "$(cut -d'|' -f1 "$BASE/state")" = 1 ]
|
||||
[ "$(cut -d'|' -f1 "$BASE/state.sim1")" = 1 ]
|
||||
read_mode; select_profile shared; load_config
|
||||
deliver() { printf '%s|%s|%s\n' "${MU300_SIM_SLOT:-0}" "$webhook_url" "$3" >> "$base/deliveries"; DELIVER_RESULT=sent; }
|
||||
process_first_sim; process_second_sim
|
||||
[ ! -e "$base/deliveries" ]
|
||||
old_sms "$ROOT_POOL" 2; old_sms "$ROOT_POOL/sim1" 2
|
||||
process_first_sim; process_second_sim; process_first_sim; process_second_sim
|
||||
[ "$(wc -l < "$base/deliveries")" = 2 ]
|
||||
grep -q '^0|https://sim0.example.com/' "$base/deliveries"
|
||||
grep -q '^1|https://sim1.example.com/' "$base/deliveries"
|
||||
# SIM2 still processes when shared is disabled (SIM1 is not a global switch).
|
||||
check_set '{"profile":"shared","mode":"per_sim","enabled":0,"method":"webhook"}'
|
||||
old_sms "$ROOT_POOL/sim1" 3
|
||||
select_profile shared; load_config; read_mode; process_second_sim
|
||||
[ "$(wc -l < "$base/deliveries")" = 3 ]
|
||||
# Per-card disable/re-enable must not deliver messages received while disabled.
|
||||
check_set '{"profile":"sim1","mode":"per_sim","enabled":0,"method":"webhook","webhook_url":"https://sim1.example.com/hook"}'
|
||||
old_sms "$ROOT_POOL/sim1" 4
|
||||
check_set '{"profile":"sim1","mode":"per_sim","enabled":1,"method":"webhook","webhook_url":"https://sim1.example.com/hook"}'
|
||||
select_profile shared; load_config; read_mode; process_second_sim
|
||||
[ "$(wc -l < "$base/deliveries")" = 3 ]
|
||||
# JSON/form/URL escaping is one pass: placeholders inside SMS stay literal.
|
||||
load_config
|
||||
webhook_url='https://example.com/hook?text={text}&sim={sim}'
|
||||
webhook_body='{"text":"{text}","nested":{"sim":"{sim}"}}'
|
||||
webhook_method=POST webhook_content_type=application/json webhook_timeout=10 webhook_headers='Authorization: Bearer TEST_ONLY'
|
||||
_text='hello "世界" & = + {sim} $(reboot)
|
||||
second line'
|
||||
_from=10010 _date=now _kind=sms MU300_SIM_SLOT=1
|
||||
render_webhook > "$base/render"
|
||||
body=$(jsonfilter -i "$base/render" -e '@.body')
|
||||
[ "$(printf '%s' "$body" | jsonfilter -e '@.text')" = "$_text" ]
|
||||
[ "$(printf '%s' "$body" | jsonfilter -e '@.nested.sim')" = SIM2 ]
|
||||
url=$(jsonfilter -i "$base/render" -e '@.url')
|
||||
case "$url" in *'%26%20%3D%20%2B%20%7Bsim%7D'*'sim=SIM2') ;; *) fail 'URL escaping' ;; esac
|
||||
webhook_content_type=application/x-www-form-urlencoded webhook_body='text={text}&from={from}'
|
||||
render_webhook > "$base/render"
|
||||
body=$(jsonfilter -i "$base/render" -e '@.body')
|
||||
case "$body" in *'%26%20%3D%20%2B%20%7Bsim%7D'*'&from=10010') ;; *) fail 'form escaping' ;; esac
|
||||
expect_error '{"webhook_timeout":121}'
|
||||
expect_error '{"webhook_headers":"Host: internal.example.com"}'
|
||||
expect_error '{"webhook_headers":"X-Test: a\r\nInjected: yes"}'
|
||||
expect_error '{"webhook_method":"DELETE"}'
|
||||
expect_error '{"webhook_body":"{broken}"}'
|
||||
expect_error '{"webhook_url":"https://{text}.example.com/hook"}'
|
||||
expect_error '{"profile":"../../etc"}'
|
||||
# A future battery device uses the shared profile even in independent mode.
|
||||
mkdir -p "$BATTERY"
|
||||
printf '1\n' > "$BATTERY/present"; printf '50\n' > "$BATTERY/capacity"; printf 'Discharging\n' > "$BATTERY/status"
|
||||
check_set '{"profile":"shared","mode":"per_sim","enabled":1,"method":"webhook","webhook_url":"https://power.example.com/hook","power_forward_enabled":1}'
|
||||
select_profile shared; load_config; load_state; read_result; process_power
|
||||
[ "$(wc -l < "$base/deliveries")" = 3 ]
|
||||
printf 'Charging\n' > "$BATTERY/status"
|
||||
process_power
|
||||
grep -q 'https://power.example.com/hook' "$base/deliveries"
|
||||
# status/history never expose templates, headers, destinations or message text.
|
||||
status_only sim1 > "$base/status"
|
||||
! grep -qE 'SECRET|quoted|example.com|TEST_ONLY' "$base/status"
|
||||
echo 'PASS profiles/secrets/barriers/source-SIM/escaping/validation/power/privacy'
|
||||
# Restore production delivery, replace ONLY network transports. No sockets open.
|
||||
. "$base/lib.sh"
|
||||
resolve_public() { RESOLVE="$1:$2:93.184.216.34"; PICKED_IP=93.184.216.34; }
|
||||
curl() {
|
||||
printf '%s\n' "$@" > "$base/curl.args"
|
||||
replyfile=
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--data-binary) shift; cp "${1#@}" "$base/curl.body" ;;
|
||||
-H) shift; case "$1" in @*) cp "${1#@}" "$base/curl.headers" ;; esac ;;
|
||||
-o) shift; replyfile=$1 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
printf '%s' '{"errcode":0}' > "$replyfile"
|
||||
printf '%s' "${TEST_HTTP_CODE:-200}"
|
||||
}
|
||||
msmtp() { cat > "$base/smtp.body"; }
|
||||
# Minimal base images may omit openssl; exercise argument/encoding plumbing
|
||||
# there. On the device the installed openssl performs the actual HMAC/MIME.
|
||||
if ! command -v openssl >/dev/null 2>&1; then
|
||||
openssl() { case "$1" in dgst) cat ;; base64) cat >/dev/null; printf 'VEVTVCs/=' ;; *) return 1 ;; esac; }
|
||||
fi
|
||||
load_config
|
||||
enabled=1 method=webhook webhook_url='https://example.com/hook?from={from}'
|
||||
webhook_headers='Authorization: Bearer TEST_ONLY'
|
||||
webhook_body='{"text":"{text}","sim":"{sim}"}'
|
||||
webhook_timeout=25 webhook_method=POST webhook_content_type=application/json
|
||||
MU300_SIM_SLOT=1
|
||||
deliver sms 10010 '"body" & {sim}' now
|
||||
[ "$DELIVER_RESULT" = sent ] && [ "$HTTP_CODE" = 200 ]
|
||||
[ "$(jsonfilter -i "$base/curl.body" -e '@.text')" = '"body" & {sim}' ]
|
||||
[ "$(jsonfilter -i "$base/curl.body" -e '@.sim')" = SIM2 ]
|
||||
grep -q '^Authorization: Bearer TEST_ONLY$' "$base/curl.headers"
|
||||
grep -q '^25$' "$base/curl.args"
|
||||
webhook_method=GET
|
||||
deliver sms 10010 'body' now
|
||||
! grep -q '^--data-binary$' "$base/curl.args"
|
||||
grep -q '^GET$' "$base/curl.args"
|
||||
TEST_HTTP_CODE=302
|
||||
if deliver sms 10010 body now; then fail 'redirect accepted'; fi
|
||||
[ "$DELIVER_RESULT" = delivery_failed ]
|
||||
TEST_HTTP_CODE=503
|
||||
if deliver sms 10010 body now; then fail 'server failure accepted'; fi
|
||||
TEST_HTTP_CODE=200 webhook_method=POST webhook_body=
|
||||
deliver sms 10010 legacy now
|
||||
[ "$(jsonfilter -i "$base/curl.body" -e '@.text')" = legacy ]
|
||||
[ "$(jsonfilter -i "$base/curl.body" -e '@.date')" = now ]
|
||||
method=dingtalk dingtalk_webhook='https://oapi.dingtalk.com/robot/send?access_token=TEST_ONLY' dingtalk_secret=TEST_SIGN_KEY
|
||||
deliver sms 10010 body now
|
||||
grep -q 'timestamp=.*sign=' "$base/curl.args"
|
||||
[ "$(jsonfilter -i "$base/curl.body" -e '@.msgtype')" = text ]
|
||||
method=smtp smtp_host=smtp.example.com smtp_port=465 smtp_username=from@example.com smtp_to=to@example.com smtp_password=TEST_ONLY
|
||||
deliver sms 10010 body now
|
||||
grep -q 'Subject: =?UTF-8?B?' "$base/smtp.body"
|
||||
echo 'PASS isolated real delivery: POST/GET/headers/timeout/HTTP errors/legacy JSON/DingTalk signing/SMTP'
|
||||
# Saving a disabled profile before its inbox exists cannot create a zero/zero
|
||||
# cursor that would subsequently turn a SIM history import into live mail.
|
||||
mv "$ROOT_POOL/next_id" "$ROOT_POOL/next_id.fixture-hold"
|
||||
rm -f "$BASE/state"
|
||||
check_set '{"profile":"shared","mode":"shared","enabled":0,"method":"webhook"}'
|
||||
[ ! -e "$BASE/state" ]
|
||||
mv "$ROOT_POOL/next_id.fixture-hold" "$ROOT_POOL/next_id"
|
||||
echo 'PASS uninitialized inbox retains first-ready replay barrier'
|
||||
@@ -52,6 +52,13 @@ class ContainerSupport(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'KVM'):
|
||||
support.check(self.out)
|
||||
|
||||
def test_old_builtin_cpufreq_cannot_silently_omit_voltage(self):
|
||||
self.config['ARM_SPRD_CPUFREQ_V2'] = 'y'
|
||||
self.write_config()
|
||||
self.manifests()
|
||||
with self.assertRaisesRegex(ValueError, 'boot voltage profiles'):
|
||||
support.check(self.out)
|
||||
|
||||
def test_missing_builtin_index_rejected_before_any_packaging(self):
|
||||
(self.out / 'modules.builtin').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'modules.builtin missing'):
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Boot-only voltage ABI, packaging and standalone capability boundaries."""
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import unittest
|
||||
from helpers import TOP, ShellTest
|
||||
|
||||
APP = TOP / 'openwrt/luci-app-mu300'
|
||||
|
||||
class CpuVoltage(unittest.TestCase):
|
||||
def test_firmware_quantization_roundtrip(self):
|
||||
for uv in range(-50000, 25001, 3125):
|
||||
magnitude = abs(uv) // 1000
|
||||
decoded = ((magnitude * 1000 + 3124) // 3125) * 3125
|
||||
self.assertEqual(-decoded if uv < 0 else decoded, uv)
|
||||
self.assertLessEqual(magnitude, 100)
|
||||
|
||||
def test_boot_only_kernel_and_loader(self):
|
||||
driver = (TOP/'upstream/port/drivers/cpufreq/sprd-cpufreq-v2-driver.c').read_text()
|
||||
self.assertIn('voltage_offset_count, 0444', driver)
|
||||
self.assertIn('.suppress_bind_attrs = true', driver)
|
||||
self.assertNotIn('module_exit(', driver)
|
||||
self.assertIn('if (firmware_initialized)', driver)
|
||||
self.assertIn('CONFIG_ARM_SPRD_CPUFREQ_V2=m', (TOP/'upstream/mu300-mainline.config').read_text())
|
||||
self.assertNotIn('sprd-cpufreq-v2', (TOP/'upstream/module-order.txt').read_text())
|
||||
loader = (TOP/'rootfs/overlay/opt/mu300/bin/cpu-voltage-platform').read_text()
|
||||
self.assertLess(loader.index('sync #'), loader.index('insmod "$ko"'))
|
||||
self.assertIn('for slot in a b', loader)
|
||||
self.assertIn('flock -x 9', loader)
|
||||
|
||||
def test_permissions_and_build_contract(self):
|
||||
acl=json.loads((APP/'root/usr/share/rpcd/acl.d/luci-app-mu300.json').read_text())['luci-app-mu300']
|
||||
self.assertIn('cpu_voltage_get', acl['read']['ubus']['mu300dash'])
|
||||
self.assertNotIn('cpu_voltage_save', acl['read']['ubus']['mu300dash'])
|
||||
for script in ('build-openwrt-tf-magisk.sh','make-release.sh'):
|
||||
text=(TOP/'tools'/script).read_text()
|
||||
for entry in ('cpu-voltage.uc', 'cpu-voltage-platform', 'S08mu300-cpu-driver', 'K89unisoc-cpu'):
|
||||
self.assertIn(entry,text)
|
||||
init=(APP/'root/etc/init.d/unisoc-cpu').read_text()
|
||||
self.assertIn('shutdown()',init)
|
||||
self.assertNotIn('stop()',init)
|
||||
|
||||
@unittest.skipUnless(shutil.which('ucode') and shutil.which('jsonfilter'), 'requires OpenWrt ucode/jsonfilter; also run cpu_voltage_fixture.sh in the OpenWrt container')
|
||||
def test_isolated_profiles(self):
|
||||
subprocess.run(['sh',str(TOP/'tests/cpu_voltage_fixture.sh'),str(APP/'root/usr/libexec/unisoc-modem/cpu-voltage.uc')],check=True,timeout=30)
|
||||
|
||||
class EarlyVoltageDiscovery(ShellTest):
|
||||
def test_partition_labels_work_before_vendor_symlinks(self):
|
||||
source=(TOP/'rootfs/overlay/opt/mu300/bin/cpu-voltage-platform').read_text()
|
||||
check=source[source.index('supported() {'):source.index('case ${1:-load}')]
|
||||
# Redirect every filesystem read to regular fake devices; no actual
|
||||
# partitions, module loading, or hash bypass in production code.
|
||||
check=check.replace('/sys/',str(self.tmp)+'/sys/').replace('/dev/',str(self.tmp)+'/dev/').replace('[ -b ', '[ -f ')
|
||||
compatible=self.tmp/'sys/firmware/devicetree/base/compatible'
|
||||
compatible.parent.mkdir(parents=True)
|
||||
compatible.write_bytes(b'zte,f50\0sprd,ums9620\0')
|
||||
(self.tmp/'dev').mkdir()
|
||||
for i,slot in enumerate(('a','b'),6):
|
||||
block=self.tmp/f'sys/class/block/mmcblk0p{i}'
|
||||
block.mkdir(parents=True)
|
||||
(block/'uevent').write_text(f'PARTNAME=sml_{slot}\n')
|
||||
(block/'size').write_text('2048\n')
|
||||
(self.tmp/f'dev/mmcblk0p{i}').write_bytes(b'fake firmware')
|
||||
self.stub('sha256sum','printf "%s %s\\n" ff4782690fd805ff54fe34853ef8ee5c7e51c3259e20077c55373b50a4b259c2 "$1"')
|
||||
for shell in self.each_shell():
|
||||
r=self.sh(shell,check+'\nsupported')
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
(self.tmp/'sys/class/block/mmcblk0p7/size').write_text('4096\n')
|
||||
for shell in self.each_shell():
|
||||
self.assertNotEqual(self.sh(shell,check+'\nsupported').returncode,0)
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Forwarding superset: shell portability, packaging, and opt-in real OpenWrt fixtures.
|
||||
|
||||
Run the real jshn/ucode suite with MU300_TEST_OPENWRT_IMAGE set to an image
|
||||
containing the plugin dependencies. It never contacts any external recipient.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import unittest
|
||||
from helpers import ShellTest, TOP
|
||||
|
||||
LIB = TOP / 'openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem'
|
||||
|
||||
|
||||
class ForwardProfiles(ShellTest):
|
||||
def test_template_helper_is_required_by_both_release_paths(self):
|
||||
for name in ('build-openwrt-tf-magisk.sh', 'make-release.sh'):
|
||||
text = (TOP / 'tools' / name).read_text()
|
||||
for path in ('sms-forward', 'forward-template.uc'):
|
||||
self.assertIn('./usr/libexec/unisoc-modem/' + path + ' ', text)
|
||||
|
||||
def test_mode_defaults_and_invalid_mode_fail_closed(self):
|
||||
source = (LIB / 'sms-forward').read_text()
|
||||
code = source[source.index('read_mode() {'):source.index('select_profile() {')]
|
||||
for shell in self.each_shell():
|
||||
base = self.tmp / '_'.join(shell).replace('/', '_')
|
||||
base.mkdir(exist_ok=True)
|
||||
r = self.sh(shell, code + '\nread_mode && echo "$forward_mode"', BASE=base)
|
||||
self.assertEqual(r.stdout.strip(), 'shared')
|
||||
for mode in ('shared', 'per_sim', 'bad'):
|
||||
(base / 'mode').write_text(mode + '\n')
|
||||
r = self.sh(shell, code + '\nread_mode && echo "$forward_mode"', BASE=base)
|
||||
self.assertEqual(r.returncode == 0, mode != 'bad')
|
||||
|
||||
@unittest.skipUnless(os.environ.get('MU300_TEST_OPENWRT_IMAGE') and shutil.which('docker'),
|
||||
'Set MU300_TEST_OPENWRT_IMAGE for real OpenWrt integration')
|
||||
def test_real_openwrt_isolated_integration(self):
|
||||
run = subprocess.run([
|
||||
'docker', 'run', '--rm', '--platform', 'linux/arm64', '-v', f'{TOP}:/src:ro',
|
||||
os.environ['MU300_TEST_OPENWRT_IMAGE'], 'sh', '/src/tests/forward_profiles_fixture.sh',
|
||||
'/src/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward',
|
||||
], capture_output=True, text=True, timeout=180)
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
self.assertIn('PASS isolated real delivery', run.stdout)
|
||||
@@ -2,6 +2,8 @@
|
||||
release it takes, the kernel choice, the byte helpers it edits boot image headers with, and whether a kernel bundle
|
||||
may go onto this device."""
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import tarfile
|
||||
import unittest
|
||||
@@ -30,6 +32,109 @@ class Update(ShellTest):
|
||||
r = self.up(shell, 'echo loaded')
|
||||
self.assertEqual((r.returncode, r.stdout), (0, 'loaded\n'), r.stderr)
|
||||
|
||||
@unittest.skipUnless(shutil.which('busybox'), 'requires the real BusyBox cp applet')
|
||||
def test_busybox_existing_directory_regression(self):
|
||||
source, target = self.tmp / 'source', self.tmp / 'target'
|
||||
source.mkdir(); target.mkdir()
|
||||
(source / 'wcnmodem.bin').write_bytes(b'firmware')
|
||||
(target / 'regulatory.db').write_bytes(b'image')
|
||||
for shell in self.each_shell():
|
||||
# Reproduce the old implementation, then test the replacement
|
||||
# against the same applet (not GNU cp behind a mocked shell).
|
||||
(target / 'wcnmodem.bin').unlink(missing_ok=True)
|
||||
r = self.up(shell, f'busybox cp -an "{source}/." "{target}/"')
|
||||
# Older BusyBox builds reject -n outright; the old updater hid
|
||||
# that error with `|| true`, causing the same missing firmware.
|
||||
if r.returncode:
|
||||
self.assertIn('invalid option', r.stderr)
|
||||
self.assertFalse((target / 'wcnmodem.bin').exists())
|
||||
r = self.up(shell, f'cp() {{ busybox cp "$@"; }}; copy_missing "{source}" "{target}"')
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual((target / 'wcnmodem.bin').read_bytes(), b'firmware')
|
||||
self.assertEqual((target / 'regulatory.db').read_bytes(), b'image')
|
||||
|
||||
def test_copy_missing_preserves_image_entries_and_links(self):
|
||||
source, target, outside = self.tmp / 'source', self.tmp / 'target', self.tmp / 'outside'
|
||||
(source / 'blocked/subdir').mkdir(parents=True)
|
||||
(source / 'blocked/subdir/no-write').write_text('vendor')
|
||||
(source / 'dangling').mkdir()
|
||||
(source / 'dangling/no-write').write_text('vendor')
|
||||
(source / 'name with space').write_text('vendor')
|
||||
(source / '.hidden').write_text('hidden')
|
||||
(source / 'kept').write_text('old')
|
||||
(source / 'link').symlink_to('name with space')
|
||||
target.mkdir(); outside.mkdir()
|
||||
(target / 'blocked').symlink_to(outside)
|
||||
(target / 'dangling').symlink_to(outside / 'absent')
|
||||
(target / 'kept').write_text('image')
|
||||
for shell in self.each_shell():
|
||||
r = self.up(shell, f'copy_missing "{source}" "{target}"')
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(list(outside.iterdir()), [])
|
||||
self.assertEqual((target / 'kept').read_text(), 'image')
|
||||
self.assertEqual((target / 'name with space').read_text(), 'vendor')
|
||||
self.assertEqual((target / '.hidden').read_text(), 'hidden')
|
||||
self.assertEqual(os.readlink(target / 'link'), 'name with space')
|
||||
for name in ('name with space', '.hidden', 'link'):
|
||||
(target / name).unlink()
|
||||
r = self.up(shell, f'copy_missing "{source}" "{target}/blocked"')
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
|
||||
def vendor_update_fixture(self):
|
||||
old = self.disk / 'openwrt'
|
||||
files = {'opt/mu300/android/system/bin/cltest': b'old',
|
||||
'opt/mu300/android/vendor/bin/modem_control': b'vendor',
|
||||
'opt/mu300/android/dev-properties/property_info': b'properties',
|
||||
'lib/firmware/wcnmodem.bin': b'firmware',
|
||||
'lib/firmware/wifi_board_config.ini': b'board',
|
||||
'lib/firmware/regulatory.db': b'old',
|
||||
'lib/modules/7.2.8/wcn_bsp.ko': b'module',
|
||||
'etc/unisoc-modem/cpu-voltage.json': b'{"offsets":[0,0,0]}',
|
||||
'etc/config/wireless': b'my-settings'}
|
||||
for name, data in files.items():
|
||||
path = old / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
stage = self.disk / '.mu300-update'
|
||||
stage.mkdir(exist_ok=True)
|
||||
with tarfile.open(stage / 'mu300-openwrt-rootfs.tar.gz', 'w:gz') as archive:
|
||||
for name, data in [('sbin/init', b'#!/bin/sh\n'),
|
||||
('etc/mu300/image-version', b'test-new\n'),
|
||||
('lib/firmware/regulatory.db', b'image'),
|
||||
('opt/mu300/android/system/bin/cltest', b'image')]:
|
||||
member = tarfile.TarInfo(name)
|
||||
member.size = len(data)
|
||||
member.mode = 0o755 if name == 'sbin/init' else 0o644
|
||||
archive.addfile(member, io.BytesIO(data))
|
||||
return old, files
|
||||
|
||||
def test_update_carries_vendor_files_before_switch(self):
|
||||
for shell in self.each_shell():
|
||||
old, files = self.vendor_update_fixture()
|
||||
r = self.up(shell, 'sync() { :; }; is_root() { false; }; apply_one openwrt test-new')
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
for name, data in files.items():
|
||||
expected = b'image' if name.endswith(('cltest', 'regulatory.db')) else data
|
||||
self.assertEqual((old / name).read_bytes(), expected, name)
|
||||
self.assertEqual((self.disk / 'openwrt.old' / name).read_bytes(), data)
|
||||
self.assertEqual((old / 'etc/mu300/image-version').read_text(), 'test-new\n')
|
||||
shutil.rmtree(old)
|
||||
shutil.rmtree(self.disk / 'openwrt.old')
|
||||
|
||||
def test_vendor_copy_failure_keeps_old_system(self):
|
||||
for shell in self.each_shell():
|
||||
old, files = self.vendor_update_fixture()
|
||||
r = self.up(shell, '''sync() { :; }; is_root() { false; };
|
||||
cp() { case "$*" in *wcnmodem.bin*) return 1;; esac; command cp "$@"; }
|
||||
apply_one openwrt test-new''')
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertIn('copying the vendor files failed', r.stderr)
|
||||
self.assertFalse((self.disk / 'openwrt.old').exists())
|
||||
self.assertFalse((self.disk / 'openwrt.new').exists())
|
||||
for name, data in files.items():
|
||||
self.assertEqual((old / name).read_bytes(), data)
|
||||
shutil.rmtree(old)
|
||||
|
||||
def test_rootfs_asset(self):
|
||||
osr = self.disk / 'ubuntu' / 'etc' / 'os-release'
|
||||
cases = [('24.04', {}, 'mu300-ubuntu-rootfs.tar.gz'),
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""TX-pressure logging must not change credits, ownership, or error returns."""
|
||||
import shutil
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from helpers import TOP
|
||||
|
||||
WLAN = TOP / 'upstream/modules/sprd_wlan_combo/sc2355'
|
||||
WCN = TOP / 'upstream/modules/wcn_bsp/pcie/edma_engine.c'
|
||||
|
||||
|
||||
def function(text, name):
|
||||
start = re.search(r'(?m)^(?:static )?(?:inline )?(?:int|void) ' + re.escape(name) + r'\(', text).start()
|
||||
return text[start:text.index('\n}', start) + 2]
|
||||
|
||||
|
||||
class TxPressureLogging(unittest.TestCase):
|
||||
def run_c(self, code):
|
||||
cc = shutil.which('cc')
|
||||
if not cc:
|
||||
self.skipTest('requires a host C compiler')
|
||||
with tempfile.TemporaryDirectory(prefix='mu300-tx-pressure-') as tmp:
|
||||
source, binary = Path(tmp) / 'check.c', Path(tmp) / 'check'
|
||||
source.write_text(code)
|
||||
subprocess.run([cc, '-std=gnu11', '-Wall', '-Werror', str(source), '-o', str(binary)], check=True, capture_output=True)
|
||||
subprocess.run([str(binary)], check=True, timeout=5)
|
||||
|
||||
def test_production_credit_functions_keep_limits_and_count_pressure(self):
|
||||
text = (WLAN / 'pcie.c').read_text()
|
||||
funcs = '\n'.join(function(text, name) for name in (
|
||||
'sc2355_pcie_note_credit_limit', 'sc2355_pcie_fc_get_send_num', 'sc2355_pcie_fc_test_send_num'))
|
||||
self.assertNotIn('pr_err(', funcs)
|
||||
self.run_c(r'''
|
||||
#include <assert.h>
|
||||
typedef long long atomic64_t;
|
||||
static atomic64_t tx_credit_limited, tx_zero_credit;
|
||||
#define atomic64_inc(p) (++*(p))
|
||||
#define atomic_read(p) (*(p))
|
||||
#define pr_debug_ratelimited(...) ((void)0)
|
||||
enum sprd_mode { SPRD_MODE_NONE, SPRD_MODE_AP };
|
||||
struct tx_mgmt { struct { int free_num; } xmit_msg_list; };
|
||||
struct sprd_hif { struct tx_mgmt *tx_mgmt; };
|
||||
static unsigned int get_max_fw_tx_dscr(void) { return 1024; }
|
||||
static unsigned int pcie_get_tx_buf_num(void) { return 1024; }
|
||||
''' + funcs + r'''
|
||||
int main(void) {
|
||||
struct tx_mgmt tx = {0}; struct sprd_hif hif = {&tx};
|
||||
long long limited = 0, zero = 0;
|
||||
for (int queued = 0; queued <= 1024; queued += 16) {
|
||||
tx.xmit_msg_list.free_num = queued;
|
||||
for (int wanted = -1; wanted <= 1200; wanted++) {
|
||||
int expected = wanted <= 0 ? 0 : (wanted < 1024-queued ? wanted : 1024-queued);
|
||||
if (wanted > 0 && queued+wanted >= 1024) {
|
||||
limited += 2;
|
||||
if (queued == 1024) zero += 2;
|
||||
}
|
||||
assert(sc2355_pcie_fc_get_send_num(&hif, SPRD_MODE_AP, wanted) == expected);
|
||||
assert(sc2355_pcie_fc_test_send_num(&hif, SPRD_MODE_AP, wanted) == expected);
|
||||
assert(tx.xmit_msg_list.free_num == queued);
|
||||
assert(sc2355_pcie_fc_get_send_num(&hif, SPRD_MODE_NONE, wanted) == 0);
|
||||
assert(sc2355_pcie_fc_test_send_num(&hif, SPRD_MODE_NONE, wanted) == 0);
|
||||
}
|
||||
}
|
||||
assert(tx_credit_limited == limited && tx_zero_credit == zero);
|
||||
return 0;
|
||||
}
|
||||
''')
|
||||
|
||||
def test_full_queue_refuses_ownership_and_recovers_without_wait(self):
|
||||
text = WCN.read_text()
|
||||
body = function(text, 'edma_pending_q_buffer')
|
||||
self.assertNotIn('sleep', body)
|
||||
self.run_c(r'''
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
typedef long long atomic64_t;
|
||||
static atomic64_t edma_pending_full[32];
|
||||
#define atomic64_inc(p) (++*(p))
|
||||
#define atomic64_read(p) (*(p))
|
||||
#define DEFAULT_RATELIMIT_INTERVAL 5
|
||||
#define DEFINE_RATELIMIT_STATE(name, interval, burst) int name = 0
|
||||
static int warnings;
|
||||
#define pr_warn(...) (warnings++)
|
||||
static int __ratelimit(int *state) { return !(*state)++; }
|
||||
#define ERROR (-1)
|
||||
#define OK 0
|
||||
#define INCR_RING_BUFF_INDX(i,n) (((i)+1)%(n))
|
||||
struct entry { void *head, *tail; int num; };
|
||||
struct edma_pending_q { int wt, rd, max; struct entry ring[4]; };
|
||||
struct edma_info { struct { struct edma_pending_q pending_q; } chn_sw[32]; };
|
||||
static struct edma_info edma;
|
||||
static struct edma_info *edma_info(void) { return &edma; }
|
||||
''' + body + r'''
|
||||
int main(void) {
|
||||
struct edma_pending_q *q = &edma.chn_sw[10].pending_q;
|
||||
q->max = 4; q->wt = 3; q->rd = 0;
|
||||
struct edma_pending_q before = *q;
|
||||
int head = 1, tail = 2;
|
||||
for (int i = 0; i < 50000; i++)
|
||||
assert(edma_pending_q_buffer(10, &head, &tail, 2) == ERROR);
|
||||
assert(!memcmp(&before, q, sizeof(before)));
|
||||
assert(edma_pending_full[10] == 50000 && warnings == 1);
|
||||
for (int i = 0; i < 32; i++) if (i != 10) assert(edma_pending_full[i] == 0);
|
||||
q->rd = 1; /* completion frees capacity; same caller-owned list retries */
|
||||
assert(edma_pending_q_buffer(10, &head, &tail, 2) == OK);
|
||||
assert(q->wt == 0 && q->rd == 1);
|
||||
assert(q->ring[3].head == &head && q->ring[3].tail == &tail && q->ring[3].num == 2);
|
||||
assert(edma_pending_full[10] == 50000);
|
||||
return 0;
|
||||
}
|
||||
''')
|
||||
|
||||
def test_diagnostics_read_only_and_legacy_build_wired(self):
|
||||
wlan, wcn = (WLAN / 'pcie.c').read_text(), WCN.read_text()
|
||||
self.assertIn('module_param_cb(mu300_tx_fc_stats, &mu300_tx_fc_stats_ops, NULL, 0444)', wlan)
|
||||
self.assertIn('module_param_cb(mu300_edma_stats, &mu300_edma_stats_ops, NULL, 0444)', wcn)
|
||||
push = function(wlan, 'sc2355_pcie_push_link')
|
||||
self.assertIn('pr_err_ratelimited', push)
|
||||
self.assertIn('return ret;', push)
|
||||
self.assertIn('sprdwl_list_cut_to_send_list(tx_head,', wlan)
|
||||
self.assertIn('if (!ret) {\n\t\t\trx_mgmt->addr_trans_head = NULL;', wlan)
|
||||
self.assertNotIn('pr_err("%s, %d: _fc_ no credit!', (WLAN / 'tx.c').read_text())
|
||||
self.assertIn('sprdwcn-edma-pressure-stats', (TOP / 'kernel/build-all.sh').read_text())
|
||||
for name in ('sprdwcn-edma-pressure-stats', 'wlan_combo-tx-pressure-logging'):
|
||||
self.assertTrue((TOP / f'kernel/patches/{name}.patch').is_file())
|
||||
for path in ('tools/build-openwrt-tf-magisk.sh', 'upstream/make-bundle.sh'):
|
||||
packaging = (TOP / path).read_text()
|
||||
self.assertIn('for wireless_driver in sprd_wlan_combo wcn_bsp; do', packaging)
|
||||
self.assertIn('-newer "$wireless_module"', packaging)
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/bin/sh
|
||||
# Run in a disposable OpenWrt container with the repository mounted read-only.
|
||||
# No devices, network, services or boot metadata are accessed.
|
||||
set -eu
|
||||
task_tmp=$(mktemp -d /tmp/mu300-vendor-copy.XXXXXX)
|
||||
trap 'rm -rf "$task_tmp"' EXIT
|
||||
export MU300_LIB=1 MU300_DISK="$task_tmp/disk"
|
||||
. "${1:?path to mu300-update}"
|
||||
mkdir -p "$task_tmp/old/firmware" "$task_tmp/new/firmware" "$task_tmp/outside"
|
||||
printf vendor > "$task_tmp/old/firmware/wcnmodem.bin"
|
||||
printf board > "$task_tmp/old/firmware/wifi_board_config.ini"
|
||||
printf image > "$task_tmp/new/firmware/regulatory.db"
|
||||
busybox cp -an "$task_tmp/old/firmware/." "$task_tmp/new/firmware/" || true
|
||||
[ ! -e "$task_tmp/new/firmware/wcnmodem.bin" ]
|
||||
copy_missing "$task_tmp/old" "$task_tmp/new"
|
||||
[ "$(cat "$task_tmp/new/firmware/wcnmodem.bin")" = vendor ]
|
||||
[ "$(cat "$task_tmp/new/firmware/wifi_board_config.ini")" = board ]
|
||||
[ "$(cat "$task_tmp/new/firmware/regulatory.db")" = image ]
|
||||
mkdir -p "$task_tmp/old/link/subdir"
|
||||
printf unsafe > "$task_tmp/old/link/subdir/file"
|
||||
ln -s "$task_tmp/outside" "$task_tmp/new/link"
|
||||
copy_missing "$task_tmp/old" "$task_tmp/new"
|
||||
[ ! -e "$task_tmp/outside/subdir" ]
|
||||
mkdir "$task_tmp/failure"
|
||||
cp() { return 1; }
|
||||
if copy_missing "$task_tmp/old/firmware" "$task_tmp/failure"; then
|
||||
echo 'copy error was hidden' >&2
|
||||
exit 1
|
||||
fi
|
||||
echo 'PASS: real OpenWrt BusyBox reproduces old loss; firmware merge, image retention, symlink guard and copy failure pass'
|
||||
@@ -49,13 +49,15 @@ for m in "$UO"/modules/*.ko; do
|
||||
[ "$v" = "$rel" ] || { echo "$m is built for '$v', Image is '$rel'" >&2; exit 1; }
|
||||
done
|
||||
# The TF path packages modules directly rather than going through make-bundle.sh.
|
||||
# Check the shared WLAN source here too, or an old module can silently undo the
|
||||
# IPv6 RX checksum fix even when its vermagic matches the newly built Image.
|
||||
wlan_module=$UO/modules/sprd_wlan_combo.ko
|
||||
if [ -n "$(find "$TOP/upstream/modules/sprd_wlan_combo" -type f -newer "$wlan_module" -print -quit)" ]; then
|
||||
echo "WLAN source is newer than $wlan_module; rebuild sprd_wlan_combo for $rel" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Check both shared wireless modules: matching vermagic does not prove that
|
||||
# the IPv6 checksum or TX-pressure logging fixes reached the built binaries.
|
||||
for wireless_driver in sprd_wlan_combo wcn_bsp; do
|
||||
wireless_module=$UO/modules/$wireless_driver.ko
|
||||
if [ -n "$(find "$TOP/upstream/modules/$wireless_driver" -type f -newer "$wireless_module" -print -quit)" ]; then
|
||||
echo "$wireless_driver source is newer than $wireless_module; rebuild it for $rel" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo "==> OpenWrt rootfs ($rel modules included)"
|
||||
MU300_GPU=0 MU300_INPUTS="$IN" MU300_MAINLINE_OUT="$UO" MU300_LUCI_PLUGIN_SRC="$PLUGIN" \
|
||||
@@ -77,6 +79,11 @@ for f in ./lib/netifd/proto/mu300cell.sh ./lib/netifd/proto/mu300cell-v6.sh \
|
||||
./www/luci-static/resources/view/mu300/traffic.js ./etc/init.d/unisoc-traffic \
|
||||
./www/luci-static/resources/view/mu300/cpu.js ./etc/init.d/unisoc-cpu \
|
||||
./usr/libexec/unisoc-modem/cpu ./usr/libexec/unisoc-modem/cpu.uc \
|
||||
./usr/libexec/unisoc-modem/cpu-voltage ./usr/libexec/unisoc-modem/cpu-voltage.uc \
|
||||
./opt/mu300/bin/cpu-voltage-platform ./etc/init.d/mu300-cpu-driver \
|
||||
./etc/rc.d/S08mu300-cpu-driver ./etc/rc.d/K89unisoc-cpu \
|
||||
./usr/libexec/unisoc-modem/sms-forward ./usr/libexec/unisoc-modem/forward-template.uc \
|
||||
./www/luci-static/resources/view/mu300/forward.js ./etc/init.d/unisoc-sms-forward \
|
||||
./usr/libexec/unisoc-modem/data-sim ./www/luci-static/resources/view/mu300/sim.js \
|
||||
./usr/libexec/unisoc-modem/operator.uc ./usr/libexec/unisoc-modem/refresh-config \
|
||||
./www/luci-static/resources/view/mu300/device.js \
|
||||
|
||||
@@ -92,6 +92,11 @@ for f in ./opt/mu300/bin/mu300-at ./opt/mu300/bin/mu300-sim-env ./opt/mu300/bin/
|
||||
./www/luci-static/resources/view/mu300/traffic.js ./etc/init.d/unisoc-traffic \
|
||||
./www/luci-static/resources/view/mu300/cpu.js ./etc/init.d/unisoc-cpu \
|
||||
./usr/libexec/unisoc-modem/cpu ./usr/libexec/unisoc-modem/cpu.uc \
|
||||
./usr/libexec/unisoc-modem/cpu-voltage ./usr/libexec/unisoc-modem/cpu-voltage.uc \
|
||||
./opt/mu300/bin/cpu-voltage-platform ./etc/init.d/mu300-cpu-driver \
|
||||
./etc/rc.d/S08mu300-cpu-driver ./etc/rc.d/K89unisoc-cpu \
|
||||
./usr/libexec/unisoc-modem/sms-forward ./usr/libexec/unisoc-modem/forward-template.uc \
|
||||
./www/luci-static/resources/view/mu300/forward.js ./etc/init.d/unisoc-sms-forward \
|
||||
./usr/libexec/unisoc-modem/data-sim ./www/luci-static/resources/view/mu300/sim.js \
|
||||
./www/luci-static/resources/view/mu300/device.js ./usr/libexec/unisoc-modem/device-usb \
|
||||
./etc/hotplug.d/net/90-unisoc-usb-host ./etc/hotplug.d/iface/90-unisoc-usb-host \
|
||||
|
||||
@@ -19,6 +19,7 @@ MODULES = {
|
||||
'IP_VS': 'ip_vs', 'IP_VS_RR': 'ip_vs_rr', 'IP_VS_WRR': 'ip_vs_wrr',
|
||||
'IP_VS_SH': 'ip_vs_sh', 'VXLAN': 'vxlan', 'IPVLAN': 'ipvlan',
|
||||
'MACVTAP': 'macvtap', 'BINFMT_MISC': 'binfmt_misc', 'FUSE_FS': 'fuse',
|
||||
'ARM_SPRD_CPUFREQ_V2': 'sprd_cpufreq_v2_driver',
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +32,8 @@ def config_check(path):
|
||||
for key in MODULES:
|
||||
if config.get('CONFIG_' + key) not in ('y', 'm'):
|
||||
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')
|
||||
return config
|
||||
|
||||
|
||||
|
||||
@@ -27,14 +27,17 @@ for m in "$UO"/modules/*.ko; do
|
||||
v=$(strings "$m" | sed -n 's/^vermagic=\([^ ]*\) .*/\1/p' | head -1)
|
||||
[ "$v" = "$krel" ] || { echo "$m is built for '$v', the kernel is '$krel'" >&2; exit 1; }
|
||||
done
|
||||
# A matching vermagic is not enough: the shared WLAN source may have changed
|
||||
# A matching vermagic is not enough: the shared WLAN/WCN source may have changed
|
||||
# after this output was built (the IPv6 RX checksum fix exposed exactly that).
|
||||
# Refuse a bundle containing the old binary rather than silently shipping it.
|
||||
wlan_module=$UO/modules/sprd_wlan_combo.ko
|
||||
if [ -f "$wlan_module" ] && [ -n "$(find "$U/modules/sprd_wlan_combo" -type f -newer "$wlan_module" -print -quit)" ]; then
|
||||
echo "WLAN source is newer than $wlan_module; rebuild sprd_wlan_combo for $krel" >&2
|
||||
exit 1
|
||||
fi
|
||||
for wireless_driver in sprd_wlan_combo wcn_bsp; do
|
||||
wireless_module=$UO/modules/$wireless_driver.ko
|
||||
[ -s "$wireless_module" ] || { echo "missing $wireless_module" >&2; exit 1; }
|
||||
if [ -n "$(find "$U/modules/$wireless_driver" -type f -newer "$wireless_module" -print -quit)" ]; then
|
||||
echo "$wireless_driver source is newer than $wireless_module; rebuild it for $krel" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
for m in $(cat "$U/module-order.txt"); do
|
||||
[ -f "$UO/modules/$m" ] || { echo "module-order.txt names $m, which was not built" >&2; exit 1; }
|
||||
done
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
#include <linux/io.h>
|
||||
#include <linux/regmap.h>
|
||||
#include <linux/of_device.h>
|
||||
#include <linux/atomic.h>
|
||||
#include <linux/moduleparam.h>
|
||||
|
||||
#include <misc/marlin_platform.h>
|
||||
|
||||
@@ -28,6 +30,36 @@
|
||||
#define SPRD_NORMAL_MEM 0
|
||||
#define SPRD_DEFRAG_MEM 1
|
||||
|
||||
/* Count pressure without printk on every TX scheduling pass. These are
|
||||
* checks/failed submissions, not unique packets or packet-drop counters.
|
||||
* Static storage survives a WCN power cycle; reads never touch the device.
|
||||
*/
|
||||
static atomic64_t tx_credit_limited = ATOMIC64_INIT(0);
|
||||
static atomic64_t tx_zero_credit = ATOMIC64_INIT(0);
|
||||
static atomic64_t tx_push_failures = ATOMIC64_INIT(0);
|
||||
|
||||
static int mu300_tx_fc_stats_get(char *buffer, const struct kernel_param *kp)
|
||||
{
|
||||
return scnprintf(buffer, PAGE_SIZE,
|
||||
"credit_limited_checks=%lld zero_credit_checks=%lld push_failures=%lld\n",
|
||||
(long long)atomic64_read(&tx_credit_limited),
|
||||
(long long)atomic64_read(&tx_zero_credit),
|
||||
(long long)atomic64_read(&tx_push_failures));
|
||||
}
|
||||
|
||||
static const struct kernel_param_ops mu300_tx_fc_stats_ops = {
|
||||
.get = mu300_tx_fc_stats_get,
|
||||
};
|
||||
module_param_cb(mu300_tx_fc_stats, &mu300_tx_fc_stats_ops, NULL, 0444);
|
||||
MODULE_PARM_DESC(mu300_tx_fc_stats, "TX credit checks and failed submissions (not packet drops)");
|
||||
|
||||
static void sc2355_pcie_note_credit_limit(int remaining)
|
||||
{
|
||||
atomic64_inc(&tx_credit_limited);
|
||||
if (remaining <= 0)
|
||||
atomic64_inc(&tx_zero_credit);
|
||||
}
|
||||
|
||||
#define INIT_INTF_SC2355(num, type, out, interval, bsize, psize, max, \
|
||||
threshold, time, in_irq, pending, pop, push, complete, suspend) \
|
||||
{ .channel = num, .hif_type = type, .inout = out, .intr_interval = interval, \
|
||||
@@ -1572,7 +1604,8 @@ int sc2355_pcie_push_link(struct sprd_hif *hif, int chn,
|
||||
time = jiffies - time;
|
||||
|
||||
if (ret) {
|
||||
pr_err("%s: push link fail: %d, chn: %d!\n", __func__, ret,
|
||||
atomic64_inc(&tx_push_failures);
|
||||
pr_err_ratelimited("%s: push link fail: %d, chn: %d!\n", __func__, ret,
|
||||
chn);
|
||||
}
|
||||
return ret;
|
||||
@@ -1937,7 +1970,8 @@ int sc2355_pcie_fc_get_send_num(struct sprd_hif *hif,
|
||||
free_num = atomic_read(&tx_mgmt->xmit_msg_list.free_num);
|
||||
|
||||
if ((free_num + data_num) >= tx_buf_max) {
|
||||
pr_debug("%s, free_num=%d, data_num=%d\n", __func__,
|
||||
sc2355_pcie_note_credit_limit(tx_buf_max - free_num);
|
||||
pr_debug_ratelimited("%s, free_num=%d, data_num=%d\n", __func__,
|
||||
free_num, data_num);
|
||||
return (tx_buf_max - free_num);
|
||||
} else {
|
||||
@@ -1963,7 +1997,9 @@ int sc2355_pcie_fc_test_send_num(struct sprd_hif *hif,
|
||||
free_num = atomic_read(&tx_mgmt->xmit_msg_list.free_num);
|
||||
|
||||
if ((free_num + data_num) >= tx_buf_max) {
|
||||
pr_err("%s,%d free_num=%d, data_num=%d\n",
|
||||
/* Credit exhaustion is normal backpressure, not a firmware error. */
|
||||
sc2355_pcie_note_credit_limit(tx_buf_max - free_num);
|
||||
pr_debug_ratelimited("%s,%d free_num=%d, data_num=%d\n",
|
||||
__func__, __LINE__, free_num, data_num);
|
||||
return (tx_buf_max - free_num);
|
||||
} else {
|
||||
|
||||
@@ -398,7 +398,7 @@ static int tx_eachmode_data(struct sprd_hif *hif, enum sprd_mode mode)
|
||||
else
|
||||
send_num = sc2355_fc_test_send_num(hif, mode, total);
|
||||
if (total != 0 && send_num <= 0) {
|
||||
pr_err("%s, %d: _fc_ no credit!\n", __func__, __LINE__);
|
||||
pr_debug_ratelimited("%s, %d: _fc_ no credit!\n", __func__, __LINE__);
|
||||
return -ENOMEM;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
|
||||
#include <linux/delay.h>
|
||||
#include <linux/timer.h>
|
||||
#include <linux/atomic.h>
|
||||
#include <linux/moduleparam.h>
|
||||
#include <linux/ratelimit.h>
|
||||
#include <misc/marlin_platform.h>
|
||||
#include <misc/wcn_bus.h>
|
||||
#include <linux/pci.h>
|
||||
@@ -39,6 +42,29 @@ static int hisrfunc_line;
|
||||
static int hisrfunc_last_msg;
|
||||
static struct edma_info g_edma = { 0 };
|
||||
|
||||
/* A full pending queue refuses ownership; the caller must retry/free it.
|
||||
* Keep exact rejection counts even when diagnostic messages are throttled.
|
||||
* No timer, workqueue, hardware access or periodic logging is added.
|
||||
*/
|
||||
static atomic64_t edma_pending_full[ARRAY_SIZE(g_edma.chn_sw)];
|
||||
|
||||
static int mu300_edma_stats_get(char *buffer, const struct kernel_param *kp)
|
||||
{
|
||||
int i, len = 0;
|
||||
|
||||
for (i = 0; i < ARRAY_SIZE(edma_pending_full); i++)
|
||||
len += scnprintf(buffer + len, PAGE_SIZE - len, "ch%d=%lld%s", i,
|
||||
(long long)atomic64_read(&edma_pending_full[i]),
|
||||
i == ARRAY_SIZE(edma_pending_full) - 1 ? "\n" : " ");
|
||||
return len;
|
||||
}
|
||||
|
||||
static const struct kernel_param_ops mu300_edma_stats_ops = {
|
||||
.get = mu300_edma_stats_get,
|
||||
};
|
||||
module_param_cb(mu300_edma_stats, &mu300_edma_stats_ops, NULL, 0444);
|
||||
MODULE_PARM_DESC(mu300_edma_stats, "Per-channel pending-queue rejections (not packet drops)");
|
||||
|
||||
static unsigned char *mpool_buffer;
|
||||
static struct dma_buf mpool_dm = {0};
|
||||
|
||||
@@ -1001,11 +1027,16 @@ static int edma_pending_q_buffer(int chn, void *head, void *tail, int num)
|
||||
{
|
||||
struct edma_pending_q *q;
|
||||
struct edma_info *edma = edma_info();
|
||||
static DEFINE_RATELIMIT_STATE(full_rs, DEFAULT_RATELIMIT_INTERVAL, 1);
|
||||
|
||||
q = &(edma->chn_sw[chn].pending_q);
|
||||
|
||||
if ((q->wt + 1) % (q->max) == q->rd) {
|
||||
pr_warn_ratelimited("WARN %s(%d) full\n", __func__, chn);
|
||||
atomic64_inc(&edma_pending_full[chn]);
|
||||
if (__ratelimit(&full_rs))
|
||||
pr_warn("WARN %s(%d) full (rejected submissions=%lld)\n",
|
||||
__func__, chn,
|
||||
(long long)atomic64_read(&edma_pending_full[chn]));
|
||||
return ERROR;
|
||||
}
|
||||
q->ring[q->wt].head = head;
|
||||
|
||||
@@ -314,7 +314,7 @@ CONFIG_CPU_FREQ_GOV_USERSPACE=y
|
||||
CONFIG_CPU_FREQ_GOV_ONDEMAND=y
|
||||
CONFIG_ENERGY_MODEL=y
|
||||
CONFIG_SPRD_SIP_SVC=y
|
||||
CONFIG_ARM_SPRD_CPUFREQ_V2=y
|
||||
CONFIG_ARM_SPRD_CPUFREQ_V2=m
|
||||
CONFIG_CPU_IDLE=y
|
||||
CONFIG_ARM_PSCI_CPUIDLE=y
|
||||
CONFIG_CPU_IDLE_GOV_MENU=y
|
||||
|
||||
@@ -25,6 +25,39 @@ static struct device *dev;
|
||||
static struct cluster_info *pclusters;
|
||||
static unsigned long boot_done_timestamp;
|
||||
|
||||
/* Verified UMS9620 SML boot ABI. This mutates CPU and SRAM tables, so never
|
||||
* repeat DVFS_INIT, unload this driver, or expose a runtime voltage setter.
|
||||
* See docs/cpu-voltage.zh-CN.md for firmware identity and recovery policy.
|
||||
*/
|
||||
static int voltage_offset_uv[3];
|
||||
static unsigned int voltage_offset_count;
|
||||
static bool firmware_initialized;
|
||||
module_param_array(voltage_offset_uv, int, &voltage_offset_count, 0444);
|
||||
MODULE_PARM_DESC(voltage_offset_uv, "Boot offsets for three domains in uV (-50000..25000, step 3125)");
|
||||
|
||||
static int sprd_voltage_flag(u32 *flag)
|
||||
{
|
||||
int i, uv;
|
||||
u32 encoded;
|
||||
|
||||
if (voltage_offset_count && voltage_offset_count != 3)
|
||||
return -EINVAL;
|
||||
*flag &= 0xff;
|
||||
for (i = 0; i < ARRAY_SIZE(voltage_offset_uv); i++) {
|
||||
uv = voltage_offset_uv[i];
|
||||
if (uv < -50000 || uv > 25000 || uv % 3125)
|
||||
return -ERANGE;
|
||||
if (uv && !of_machine_is_compatible("sprd,ums9620"))
|
||||
return -EOPNOTSUPP;
|
||||
/* Firmware: ceil(magnitude_mV * 1000 / 3125) selector steps. */
|
||||
encoded = abs(uv) / 1000;
|
||||
if (uv < 0)
|
||||
encoded |= 0x80;
|
||||
*flag |= encoded << (8 * (i + 1));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* cluster common interface */
|
||||
static struct cluster_info *sprd_cluster_info(u32 cpu_idx)
|
||||
{
|
||||
@@ -514,6 +547,41 @@ static int sprd_cpufreq_offline(struct cpufreq_policy *policy)
|
||||
return 0;
|
||||
}
|
||||
|
||||
static ssize_t show_scaling_voltage_table(struct cpufreq_policy *policy, char *buf)
|
||||
{
|
||||
struct cluster_info *cluster = policy->driver_data;
|
||||
u64 freq, volt;
|
||||
int i, ret, len = 0;
|
||||
|
||||
mutex_lock(&cluster->mutex);
|
||||
for (i = 0; i < cluster->table_entry_num && len < PAGE_SIZE - 64; i++) {
|
||||
ret = cluster->pair_get(cluster->id, i, &freq, &volt);
|
||||
if (ret) { len = ret; break; }
|
||||
len += sysfs_emit_at(buf, len, "%llu %llu\n", freq / 1000, volt);
|
||||
}
|
||||
mutex_unlock(&cluster->mutex);
|
||||
return len;
|
||||
}
|
||||
cpufreq_freq_attr_ro(scaling_voltage_table);
|
||||
|
||||
static ssize_t show_scaling_voltage_offset(struct cpufreq_policy *policy, char *buf)
|
||||
{
|
||||
struct cluster_info *cluster = policy->driver_data;
|
||||
return sysfs_emit(buf, "%d\n", cluster->id < 3 ? voltage_offset_uv[cluster->id] : 0);
|
||||
}
|
||||
cpufreq_freq_attr_ro(scaling_voltage_offset);
|
||||
|
||||
static ssize_t show_scaling_voltage_domain(struct cpufreq_policy *policy, char *buf)
|
||||
{
|
||||
struct cluster_info *cluster = policy->driver_data;
|
||||
return sysfs_emit(buf, "%u\n", cluster->id);
|
||||
}
|
||||
cpufreq_freq_attr_ro(scaling_voltage_domain);
|
||||
|
||||
static struct freq_attr *sprd_cpufreq_attr[] = {
|
||||
&scaling_voltage_table, &scaling_voltage_offset, &scaling_voltage_domain, NULL,
|
||||
};
|
||||
|
||||
static struct cpufreq_driver sprd_cpufreq_driver = {
|
||||
.name = "sprd-cpufreq-v2",
|
||||
.flags = CPUFREQ_NEED_INITIAL_FREQ_CHECK |
|
||||
@@ -529,6 +597,7 @@ static struct cpufreq_driver sprd_cpufreq_driver = {
|
||||
.online = sprd_cpufreq_online,
|
||||
.offline = sprd_cpufreq_offline,
|
||||
.register_em = cpufreq_register_em_with_opp,
|
||||
.attr = sprd_cpufreq_attr,
|
||||
};
|
||||
|
||||
/* init inerface */
|
||||
@@ -775,6 +844,11 @@ static int sprd_cpufreq_probe(struct platform_device *pdev)
|
||||
dev_info(dev, "%s: probe sprd cpufreq v2 driver\n", __func__);
|
||||
|
||||
flag = sprd_cpufreq_get_debug_flag();
|
||||
ret = sprd_voltage_flag(&flag);
|
||||
if (ret)
|
||||
return ret;
|
||||
if (firmware_initialized)
|
||||
return -EBUSY;
|
||||
if ((flag & 0xFF) == SPRD_DVFS_DEBUG_MAGIC) {
|
||||
dev_info(dev, "%s: disable apcpu dvfs for debug!\n", __func__);
|
||||
return 0;
|
||||
@@ -792,6 +866,7 @@ static int sprd_cpufreq_probe(struct platform_device *pdev)
|
||||
return ret;
|
||||
}
|
||||
|
||||
firmware_initialized = true;
|
||||
ret = pclusters->dvfs_init(flag);
|
||||
if (ret) {
|
||||
dev_err(dev, "%s: init dvfs device error\n", __func__);
|
||||
@@ -917,6 +992,7 @@ static struct platform_driver sprd_cpufreq_platform_driver = {
|
||||
.driver = {
|
||||
.name = "sprd-cpufreq-v2",
|
||||
.of_match_table = sprd_cpufreq_of_match,
|
||||
.suppress_bind_attrs = true,
|
||||
},
|
||||
.probe = sprd_cpufreq_probe,
|
||||
};
|
||||
|
||||
@@ -168,11 +168,25 @@ config SPRD_SIP_SVC
|
||||
append_once('drivers/cpufreq/Makefile', 'sprd-cpufreq-v2-driver.o', 'obj-$(CONFIG_ARM_SPRD_CPUFREQ_V2) += sprd-cpufreq-v2-driver.o\n')
|
||||
append_once('drivers/cpufreq/Kconfig.arm', 'ARM_SPRD_CPUFREQ_V2', '''
|
||||
config ARM_SPRD_CPUFREQ_V2
|
||||
bool "Unisoc UMS9620 cpufreq (v2, ATF DVFS)"
|
||||
tristate "Unisoc UMS9620 cpufreq (v2, ATF DVFS)"
|
||||
depends on SPRD_SIP_SVC && NVMEM
|
||||
select PM_OPP
|
||||
''')
|
||||
# PCIe RC for the Marlin3 (SC2355) Wi-Fi/BT chip: vendor pcie-sprd glue ported to the 6.18 DWC host API
|
||||
cp = os.path.join(tree, 'drivers/cpufreq/Kconfig.arm')
|
||||
ct = open(cp).read()
|
||||
ct = ct.replace('bool "Unisoc UMS9620 cpufreq (v2, ATF DVFS)"',
|
||||
'tristate "Unisoc UMS9620 cpufreq (v2, ATF DVFS)"')
|
||||
open(cp, 'w').write(ct)
|
||||
# The vendor driver updates scheduler frequency invariance after DVFS. Mainline
|
||||
# has no export for modular cpufreq drivers; retain the call, export GPL-only.
|
||||
ap = os.path.join(tree, 'drivers/base/arch_topology.c')
|
||||
at = open(ap).read()
|
||||
if 'EXPORT_SYMBOL_GPL(topology_set_freq_scale)' not in at:
|
||||
start = at.index('void topology_set_freq_scale(')
|
||||
end = at.index('\n}', start) + 2
|
||||
at = at[:end] + '\nEXPORT_SYMBOL_GPL(topology_set_freq_scale);' + at[end:]
|
||||
open(ap, 'w').write(at)
|
||||
append_once('drivers/pci/controller/dwc/Makefile', 'pcie-sprd.o', 'obj-$(CONFIG_PCIE_SPRD) += pcie-sprd-misc.o pcie-sprd.o\n')
|
||||
append_once('drivers/pci/controller/dwc/Kconfig', 'config PCIE_SPRD', '''
|
||||
config PCIE_SPRD
|
||||
|
||||
Reference in new issue
Block a user