diff --git a/docs/CPU-THERMAL.md b/docs/CPU-THERMAL.md new file mode 100644 index 00000000..e8cd57e6 --- /dev/null +++ b/docs/CPU-THERMAL.md @@ -0,0 +1,63 @@ +# CPU 温控管理 + +CPU 设置页的温控功能使用标准 thermal sysfs,不调用 AT,不依赖 MU300 温区编号。 +与 E5 对齐到单个温区、单个 passive trip 的粒度:温度实时显示、逐项阈值、 +实际 CPU cooling 绑定和降温等级、开机持久化、恢复启动基线。 +critical/hot 阈值和 hysteresis 只读,不提供关闭保护或任意 sysfs 写入。 +页面固定按“频率 → 电压 → 温控”排列。三块独立提交和恢复,保存一块不会提交、 +覆盖或校验另一块尚未保存的编辑;频率与温控各自有开机自动应用开关。 + +## F50 主线内核 + +原厂 DT 的 19 个物理传感器没有独立 trips。`virtual-sensor@0` 的 `thmzone-cells` +引用 11 个物理温区,原厂 `soc-thmzone` 上才有 70°C 被动监测、85°C CPU 降频、 +110°C 临界保护。过去 6/7 主线缺失 `virtual-thermal` 驱动,虽然有 cpufreq +cooling devices,却没有原厂虚拟温区将二者连接。 + +`upstream/modules/mu300_thermal` 恢复该虚拟传感器:取 DT 引用温区的最高温度, +复用原厂 trips、polling 和 cooling maps;物理传感器未就绪则 deferred probe。 +任一读取失败返回错误,不把失败解释为低温。两套受支持内核的物理传感器均内置。 +模块由真实 rootfs 的 `extra-modules` 加载,不在 initramfs 启动,也不增加常驻工作线程。 +5.4 保留自身实现。 + +`thermal-guard` 只有在原厂温区启用、所有现有 CPU cooling devices 都已绑定后, +才让内核接管频率限制,避免两套控制器争用。缺少绑定时仍使用旧兜底。 +主线仍保留原来的 105°C 紧急关机保护及温度 LED 提示;插件不能改该保护。 + +## 配置与保护 + +- 可写项必须是具有 CPU cooling 绑定的温区内、内核允许写入的 passive trip。 +- 调整范围 40–100°C,且不高于最低 hot/critical trip 减 10°C;步进 1°C。 +- 同温区 passive trips 必须递增且至少间隔 1°C;所有输入先验证再写入。 +- 降低阈值时先改低位,提高阈值时先改高位;写后回读,失败逆序回滚。 +- 通过现有 CPU 写锁串行化;页面隐藏时不轮询,实时刷新不覆盖正在编辑的值。 +- 只改温控时不重写未修改的频率项;已保存的频率请求不会被临时温控限频覆盖。 + 已接受的频率上限写入若被实际 CPU cooling device 限制,不误判为写入失败。 +- `/etc/unisoc-modem/cpu.json` 使用 v2 的独立 `frequency` / `thermal` 配置段。 + 写锁内原子更新所选段,保留另一段。取消自动应用、恢复基线均只清除所选段; + 两段都清除时才删除文件。温控按名称而非易变编号匹配。 + v1 纯频率和旧合并配置均兼容;读取和启动回放不修改旧文件,首次保存时迁移。 + 拒绝旧页面提交的混合请求,提示刷新,防止一次点击误改两块。 + 名称重复、温区缺失或只读时拒绝,不盲目写入。 +- S99 捕获 `/run/unisoc-cpu-defaults.json` 后回放配置;晚出现的温区在首次修改前补录。 + 两个配置段独立回放,一项能力缺失或验证失败不阻断另一项。 + “恢复启动基线”仅恢复对应区域的本次启动记录值并取消该项开机应用。热安装首次捕获的是 + 当时实际值,不宣称是任意固件的出厂默认。 +- 电压继续独立保存、重启生效,未改变电压恢复保护。 + +## 验证 + +`tests/cpu_thermal_fixture.sh` 在隔离 OpenWrt ucode 环境测试发现能力、写保护、 +范围与顺序、保存/启动回放、恢复基线、持久化失败回滚、重复名称和缺失绑定。 +`test_device_scripts.py` 覆盖原生降频接管后保留用户频率上限与紧急关机,缺失绑定恢复兜底。 + +2026-10-10:6.18.54 和 7.2.8 模块均编译成功;7.2.8 F50 热加载识别原厂温区, +三个 CPU 簇绑定正确。实机验证保存/启动回放代码/恢复基线;短暂降低触发阈值, +确认三个 cooling devices 进入非零等级,降频期间使用恢复基线操作成功, +随后确认 step_wise 已解除限制,三个 cooling states 均回到 0。 +未实际加热到危险温度,未进行整机冷启动或 6.18 实机验证。 +前端覆盖 Aurora/Bootstrap 明暗色、中文/英文/土耳其语、360/1280 px,共 24 组。 + +2026-10-11:补充频率/温控独立保存、取消自启、恢复、回放失败隔离、v1 配置迁移与 +旧混合请求拒绝测试。`tests/dashboard_cpu_sections_browser.py` 验证 24 组布局的区域顺序、 +独立提交/恢复以及保留另一块的未提交草稿(包括无效草稿)。本轮不修改内核或电压逻辑。 diff --git a/docs/KERNEL-CAPABILITIES.md b/docs/KERNEL-CAPABILITIES.md new file mode 100644 index 00000000..2c1e5d5e --- /dev/null +++ b/docs/KERNEL-CAPABILITIES.md @@ -0,0 +1,95 @@ +# MU300 6.18 / 7.2 内核能力 + +两套主线内核使用同一个 `upstream/mu300-mainline.config`。 +本次对齐 E5 的 eBPF、追踪与可选容器网络能力;**不内置 Docker、containerd、runc, +也不创建容器网络或启动采集任务**。这不是看板插件依赖,安装看板不会启用追踪。 + +## 能力范围 + +- KVM:ARM64 硬件虚拟化、vhost-net、vhost-vsock。KVM 内建,可选设备按需加载。 +- 容器:cgroup v2、memory/CPU/IO/pids 控制器、namespace、seccomp、OverlayFS、 + veth、bridge/netfilter、IPVS、macvtap/ipvlan/vxlan 等。 +- eBPF:syscall、cgroup BPF、JIT、BPF events、stream parser、内核与模块 BTF。 + `CONFIG_BPF_UNPRIV_DEFAULT_OFF=y` 保留非特权 BPF 默认限制。 +- 追踪:perf / ARM PMU、kprobe/uprobe events、ftrace、function / function graph、 + dynamic ftrace、syscall tracing 和完整 kallsyms。功能编译进内核,不自动启动会话。 +- 可选网络诊断/流控模块:FQ、HTB、TBF、PRIO、NETEM,u32/flower/matchall 分类器, + BPF/mirred/police/gact/skbedit/ct 动作,IFB、socket diagnostics、IPVTAP、Geneve。 + 不替换正在使用的 qdisc,不修改 USB、Wi-Fi、SIPA 或 fw4 的运行配置。 + +## 构建与防漏 + +构建镜像增加 `pahole` 以生成 BTF。先重新构建工具镜像: + +```sh +docker build -t mu300-mainline-build upstream +``` + +然后使用现有 `upstream/build.sh` 和 `upstream/build-modules.sh`,分别设置 +`KV=6.18.54` 或 `KV=7.2.8`,每个版本使用自己的 `OUTDIR`。 +两个版本的模块构建不得并行共享同一个 `/src/mod-build`。 + +本轮产物单独保存在 `upstream/out-features-6.18`、`upstream/out-features-7.2`, +未覆盖旧的已验证产物。后续 TF / bundle 打包时,使用 `MU300_UPSTREAM_OUT` +明确指定对应目录;单独构建 OpenWrt rootfs 时用 `MU300_MAINLINE_OUT`。 +不要把新 Image 与旧目录中的同版本模块混用。 + +- `build.sh` 验证请求的 Kconfig 是否真正生效;不能静默丢弃不支持的选项。 +- `check-container-support.py` 检查实际构建配置、Image/模块清单和必要模块。 + TF 包、内核 bundle、OpenWrt rootfs 都沿用该检查,旧的缺功能内核会被拒绝。 +- 内核自带模块用 `INSTALL_MOD_STRIP=1`;vendor 模块也移除 DWARF,保留 `.BTF`。 + 构建后逐一检查实际模块的 `.BTF` 段,防止缺少 vmlinux 时跳过生成却继续打包。 + 检查管道读完整个 `readelf` 输出,避免 `grep -q` 在 `pipefail` 下造成 SIGPIPE 误报。 +- 不向 initramfs 的模块列表加入追踪或容器网络模块。 + +内核能力不能通过替换网页或脚本热应用。需要用匹配的 Image 和整套模块更新并重启, +不可将新模块单独混入仍运行旧内核的机器,即使 `uname -r` 相同。 + +## 验证边界 + +2026-10-11 本地构建验证: + +- Linux 6.18.54:Image 28,669,960 字节,82 个模块;Image、模块 BTF 与清单检查通过。 +- Linux 7.2.8:Image 30,107,656 字节,84 个模块;Image、模块 BTF 与清单检查通过。 +- 使用实际设备输入分别生成本地 TF 启动镜像作容量验证(未写入设备)。 + 6.18 / 7.2 有效负载末端分别为 40,614,144 / 42,051,840 字节, + 均未覆盖从 50,331,648 字节开始的持久日志区。 +- 全量仓库回归测试 283 项:280 通过、3 跳过。BTF 管道修正后专项 15 项重新通过。 +- 首次构建阶段没有构建 rootfs / Magisk ZIP,也没有更新或重启实机。 + +构建通过只证明编译与产物完整性。实机应在更新内核后另行检查 +`/sys/kernel/btf/vmlinux`、JIT 功能、可加载 BPF 程序、可用的 trace events, +并验证 KVM ioctl/虚拟机和实际容器。只看到 `/dev/kvm` 或打开配置项不等于所有负载已测。 +默认不需要开 tracer、加载 BPF 程序或安装 Docker 来使用路由器。 + +## 2026-10-11 实机应用与验收 + +用户随后授权将 DNS 修复与新内核一起落地。F50 从 7.2.8 `#7` 更新到 `#10`, +通过本地 kernel bundle 更新 Linux 所在的 boot_b 和匹配的 84 个模块;未重装 rootfs。 +写入后逐个校验模块 SHA-256,并确认 network、wireless、cpu.json 三份配置未改变。 +保留 TF 卡完整 boot_b、旧模块和 boot 元数据备份,也下载了一份到本机。 +同版本号不代表模块兼容,回滚时必须恢复旧 boot **以及旧模块目录**。 + +实机通过: + +- eBPF 程序加载、JIT 编译(测试程序产生 56 字节机器码)、test-run 返回值校验。 +- KVM API 12、创建 VM/vCPU、ARM vCPU 初始化。没有运行完整客户机 OS。 +- `perf_event_open`;独立 net/mount/UTS/IPC/cgroup namespace 的创建与退出。 +- 内核 BTF、WLAN/温控模块 BTF、syscall trace events 存在,默认 tracer 为 `nop`。 +- `vhost_net`、`act_bpf` 可加载且带 BTF;测试后卸载,不留常驻诊断任务。 +- USB 管理、5 GHz/80 MHz 热点、AT `OK`、IPv4/IPv6 HTTPS 均通过; + 持续运行超过五分钟,默认启动仍为 Linux,连续失败计数为 0。 + +用于这些有限范围验证的程序在 `tests/kernel_capabilities_probe.c`。 +Docker/containerd/runc 没有安装;完整虚拟机、Docker 容器及长时间压力测试仍未进行。 +日志仍有供应商 SIPC 重复注册 sysfs 调试目录的提示和 GICv2 emulation 不可用提示, +不能把本次基本功能验收理解为所有驱动日志都已消除。 + +DNS 显示空值的原因是旧 `sed` 只识别单行数组,ubus 实际返回多行 JSON。 +看板现在用 `jsonfilter` 读取已有 WAN/WAN6 快照的顶层 `dns-server`,合并去重; +不取 inactive 项,不拿本机 loopback resolver 冒充上游 DNS,不新增 RPC/AT 请求或缓存。 +`tests/dashboard_dns_fixture.sh` 已在 OpenWrt 容器和 F50 上通过真实 jsonfilter 验证。 + +本次 DNS 修复后的完整测试在 WSL 的 `MU300_TEST_SHELLS=dash,bash` 下为 +285 项、281 通过、4 跳过。WSL BusyBox 1.30.1 和 Windows 原生运行 Unix 测试的 +尝试出现兼容性失败,未将其算作通过;真实 OpenWrt ash/jsonfilter 的 DNS fixture 单独通过。 diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js index bed14e0a..06332e23 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js @@ -300,7 +300,54 @@ var DASH_I18N = { '最近转发:': ['Last forwarding: ', 'Son yönlendirme: '], '最近投递记录': ['Recent deliveries', 'Son teslimatlar'], 'CPU 设置': ['CPU settings', 'CPU ayarları'], + "频率、电压、温控分别保存。频率和温控即时生效,电压重启后生效。": ["Frequency, voltage and thermal settings are saved separately. Frequency and thermal settings apply immediately; voltage applies after reboot.", "Frekans, voltaj ve sıcaklık ayarları ayrı kaydedilir. Frekans ve sıcaklık hemen, voltaj yeniden başlatmada uygulanır."], + "仅控制本区域;未勾选时只应用本次,并取消本区域的开机设置。": ["Controls this section only. When unchecked, apply for this session and remove only this section’s startup settings.", "Yalnızca bu bölümü yönetir. İşaretli değilse bu oturum için uygular ve yalnızca bu bölümün açılış ayarlarını kaldırır."], + "应用温控设置": ["Apply thermal settings", "Sıcaklık ayarlarını uygula"], + "应用频率设置": ["Apply frequency settings", "Frekans ayarlarını uygula"], + "应用温控设置?": ["Apply thermal settings?", "Sıcaklık ayarları uygulansın mı?"], + "应用频率设置?": ["Apply frequency settings?", "Frekans ayarları uygulansın mı?"], + "恢复温控启动基线?": ["Restore thermal boot baseline?", "Başlangıç sıcaklık ayarları geri yüklensin mi?"], + "恢复频率启动基线?": ["Restore frequency boot baseline?", "Başlangıç frekans ayarları geri yüklensin mi?"], + "仅恢复本次启动记录的温控阈值并取消温控开机应用;不修改频率或电压设置。": ["Restore only thermal thresholds recorded for this boot and disable thermal startup settings. Frequency and voltage settings are unchanged.", "Yalnızca bu açılışın sıcaklık eşiklerini geri yükler ve sıcaklık açılış ayarlarını kapatır. Frekans ve voltaj ayarları değişmez."], + "仅恢复本次启动记录的频率并取消频率开机应用;不修改温控或电压设置。": ["Restore only frequencies recorded for this boot and disable frequency startup settings. Thermal and voltage settings are unchanged.", "Yalnızca bu açılışın frekanslarını geri yükler ve frekans açılış ayarlarını kapatır. Sıcaklık ve voltaj ayarları değişmez."], + "温控阈值将立即应用;提高阈值可能增加温度。不修改频率或电压设置。": ["Thermal thresholds apply immediately; raising them may increase temperature. Frequency and voltage settings are unchanged.", "Sıcaklık eşikleri hemen uygulanır; yükseltmek sıcaklığı artırabilir. Frekans ve voltaj ayarları değişmez."], + "降低频率可能降低吞吐量;提高最低频率可能增加功耗和温度。不修改温控或电压设置。": ["Lower frequencies may reduce throughput; higher minimum frequencies may increase power use and temperature. Thermal and voltage settings are unchanged.", "Düşük frekans verimi azaltabilir; yüksek alt frekans güç tüketimini ve sıcaklığı artırabilir. Sıcaklık ve voltaj ayarları değişmez."], + "正在应用温控设置…": ["Applying thermal settings…", "Sıcaklık ayarları uygulanıyor…"], + "正在应用频率设置…": ["Applying frequency settings…", "Frekans ayarları uygulanıyor…"], + "温控设置已应用": ["Thermal settings applied", "Sıcaklık ayarları uygulandı"], + "频率设置已应用": ["Frequency settings applied", "Frekans ayarları uygulandı"], + "请刷新页面后分别应用频率或温控设置": ["Reload the page and apply frequency or thermal settings separately", "Sayfayı yenileyip frekans veya sıcaklık ayarlarını ayrı ayrı uygulayın"], + "频率与温控即时应用;电压偏移独立保存,重启后生效。": ["Frequency and thermal settings apply immediately; voltage offsets are saved separately and apply after reboot.", "Frekans ve sıcaklık ayarları hemen uygulanır; voltaj ofsetleri ayrı kaydedilir ve yeniden başlatmada uygulanır."], + "温控管理": ["Thermal management", "Sıcaklık yönetimi"], + "按实际温区调整被动阈值;临界保护与回差只读,保留内核降频绑定。": ["Adjust passive thresholds for actual thermal zones. Critical protection and hysteresis are read-only; kernel cooling bindings are preserved.", "Gerçek sıcaklık bölgelerinin pasif eşiklerini ayarlayın. Kritik koruma ve histerezis salt okunurdur; çekirdek soğutma bağlantıları korunur."], + "温区已禁用": ["Thermal zone disabled", "Sıcaklık bölgesi devre dışı"], + "内核温控": ["Kernel thermal control", "Çekirdek sıcaklık denetimi"], + "降频触发温度": ["Throttling threshold", "Frekans düşürme eşiği"], + "被动温控起点": ["Passive monitoring threshold", "Pasif izleme eşiği"], + "临界保护温度": ["Critical protection threshold", "Kritik koruma eşiği"], + "高温保护温度": ["Hot protection threshold", "Yüksek sıcaklık koruma eşiği"], + "只读阈值": ["Read-only threshold", "Salt okunur eşik"], + "回差": ["Hysteresis", "Histerezis"], + "只读": ["Read-only", "Salt okunur"], + "降温等级(当前 / 最大)": ["Cooling state (current / maximum)", "Soğutma seviyesi (mevcut / en yüksek)"], + "当前内核没有可写的 CPU 被动温控阈值,仅显示实际传感器。": ["This kernel exposes no writable passive CPU thermal thresholds; actual sensors are shown read-only.", "Bu çekirdekte yazılabilir pasif CPU sıcaklık eşiği yok; gerçek sensörler salt okunur gösterilir."], + "温度传感器": ["Temperature sensors", "Sıcaklık sensörleri"], + "提高阈值可能增加温度;此处不会关闭内核临界保护或设备紧急保护。": ["Raising thresholds may increase temperature. Kernel critical protection and device emergency protection are not disabled here.", "Eşikleri yükseltmek sıcaklığı artırabilir. Çekirdek kritik koruması ve cihaz acil koruması burada kapatılmaz."], + "应用频率与温控": ["Apply frequency & thermal settings", "Frekans ve sıcaklık ayarlarını uygula"], + "恢复启动基线": ["Restore boot baseline", "Başlangıç ayarlarını geri yükle"], + "恢复启动基线?": ["Restore boot baseline?", "Başlangıç ayarları geri yüklensin mi?"], + "恢复本次启动记录的频率与温控阈值,并取消开机自动应用;不修改电压。": ["Restore frequency and thermal thresholds recorded for this boot and disable automatic application at startup. Voltage is unchanged.", "Bu açılışta kaydedilen frekans ve sıcaklık eşiklerini geri yükle ve açılışta otomatik uygulamayı kapat. Voltaj değişmez."], + "频率与温控阈值将立即应用。降低频率可能降低吞吐量;提高最低频率或温控阈值可能增加功耗和温度。": ["Frequency and thermal thresholds apply immediately. Lower frequencies may reduce throughput; higher minimum frequencies or thermal thresholds may increase power use and temperature.", "Frekans ve sıcaklık eşikleri hemen uygulanır. Düşük frekans verimi azaltabilir; yüksek alt frekans veya sıcaklık eşikleri güç tüketimini ve sıcaklığı artırabilir."], + "温控配置无效": ["Invalid thermal settings", "Geçersiz sıcaklık ayarları"], + "温区不存在或名称不唯一": ["Thermal zone is missing or its name is ambiguous", "Sıcaklık bölgesi yok veya adı benzersiz değil"], + "只能调整可写的 CPU 被动温控阈值": ["Only writable passive CPU thermal thresholds can be adjusted", "Yalnızca yazılabilir pasif CPU sıcaklık eşikleri ayarlanabilir"], + "温控阈值超出保护范围": ["Thermal threshold is outside the protection limits", "Sıcaklık eşiği koruma sınırlarının dışında"], + "被动温控阈值必须至少相隔 1°C 并递增": ["Passive thresholds must increase with at least 1°C separation", "Pasif eşikler en az 1°C aralıkla artmalıdır"], + "温控配置回读不一致": ["Thermal settings did not match readback", "Sıcaklık ayarları geri okumayla eşleşmedi"], + "无法读取 CPU 启动基线": ["Could not read CPU boot baseline", "CPU başlangıç ayarları okunamadı"], + "无法保存 CPU 启动基线": ["Could not save CPU boot baseline", "CPU başlangıç ayarları kaydedilemedi"], 'SIM 卡管理': ['SIM management', 'SIM yönetimi'], + '切换上网卡后,看板、锁定和 AT 的查看卡槽会同步;仍可手动查看另一张卡。': ['Switching the data SIM also updates the SIM viewed by the dashboard, network locks and AT terminal. You can still view the other SIM manually.', 'Veri SIM kartı değiştirildiğinde panel, ağ kilitleri ve AT terminalinde görüntülenen SIM de güncellenir. Diğer SIM kartını yine elle görüntüleyebilirsiniz.'], '切换上网卡': ['Switch data SIM', 'Veri SIM kartını değiştir'], '默认上网卡': ['Default data SIM', 'Varsayılan veri SIM kartı'], '当前上网卡': ['Active data SIM', 'Etkin veri SIM kartı'], @@ -600,6 +647,14 @@ var DASH_I18N = { '调用失败': ['Request failed', 'İstek başarısız'], '正在断开数据连接': ['Disconnecting data', 'Veri bağlantısı kesiliyor'], '正在拨号': ['Connecting data', 'Veri bağlantısı kuruluyor'], + '断开数据连接': ['Disconnect data', 'Veri bağlantısını kes'], + '建立数据连接': ['Connect data', 'Veri bağlantısı kur'], + '将断开蜂窝数据连接,依赖此连接的设备将无法上网。': ['Cellular data will disconnect. Devices using this connection will lose internet access.', 'Hücresel veri bağlantısı kesilecek. Bu bağlantıyı kullanan cihazlar internet erişimini kaybedecek.'], + '将建立蜂窝数据连接,可能产生流量费用。': ['A cellular data connection will be established. Data charges may apply.', 'Hücresel veri bağlantısı kurulacak. Veri ücreti uygulanabilir.'], + '关闭 Wi-Fi 热点': ['Turn off Wi-Fi hotspot', 'Wi-Fi erişim noktasını kapat'], + '打开 Wi-Fi 热点': ['Turn on Wi-Fi hotspot', 'Wi-Fi erişim noktasını aç'], + '热点客户端会断开;若正通过此热点管理设备,需要重新连接后才能继续访问。': ['Hotspot clients will disconnect. If you are managing the device through this hotspot, reconnect to regain access.', 'Erişim noktasına bağlı cihazların bağlantısı kesilecek. Cihazı bu erişim noktasından yönetiyorsanız erişmek için yeniden bağlanmanız gerekecek.'], + '将使用已保存的配置开启 Wi-Fi 热点。': ['The Wi-Fi hotspot will start using the saved settings.', 'Wi-Fi erişim noktası kayıtlı ayarlarla açılacak.'], '关闭蜂窝射频': ['Turn off cellular radio', 'Hücresel radyoyu kapat'], '打开蜂窝射频': ['Turn on cellular radio', 'Hücresel radyoyu aç'], '蜂窝连接会中断': ['Cellular connectivity will be interrupted', 'Hücresel bağlantı kesilecek'], diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/cpu.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/cpu.js index 81f61617..844cb6e7 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/cpu.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/cpu.js @@ -13,6 +13,7 @@ function node(tag, text, cls) { if (cls) e.className = cls; return e; } function mhz(n) { return n == null ? '--' : (n / 1000) + ' MHz'; } +function degrees(n) { return n == null ? '--' : (n / 1000).toFixed(1) + ' °C'; } function select(values, value, label) { var e = node('select'); values.forEach(function(v) { var o = node('option', label ? label(v) : v); o.value = v; e.appendChild(o); }); @@ -83,6 +84,14 @@ var CSS = ` .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} +.mud-cpu-thermal-trips{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,200px),1fr));gap:14px;margin-top:16px} +.mud-cpu-thermal-readonly{display:block;padding:10px 0;color:var(--text,#222);font-size:.9rem;font-variant-numeric:tabular-nums} +.mud-cpu-thermal-cooling{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px} +.mud-cpu-sensors{margin-top:20px;border-top:1px solid var(--hairline,#ddd);padding-top:16px} +.mud-cpu-sensors>summary{cursor:pointer;font-size:.8rem;color:var(--text,#222)} +.mud-cpu-sensor-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,215px),1fr));gap:8px 20px;margin-top:14px} +.mud-cpu-sensor{display:flex;justify-content:space-between;gap:10px;padding:8px 0;border-bottom:1px solid var(--hairline,#ddd);font-size:.75rem;color:var(--text-muted,#777)} +.mud-cpu-sensor strong{flex-shrink:0;color:var(--text,#222);font-variant-numeric:tabular-nums} @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}} `; @@ -93,7 +102,7 @@ return view.extend({ 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')); + 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('频率与调速策略', '即时生效')); @@ -115,31 +124,104 @@ return view.extend({ grid.append(card); if (p.writable) self.inputs.push({ p: p, gov: gov, lo: lo, hi: hi }); }); 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', 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); 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) }; }); - if (changes.some(function(c) { return !Number.isInteger(c.min) || !Number.isInteger(c.max) || c.min > c.max; })) { M.toast(M.translate('CPU 配置无效'), { type: 'error' }); return; } - self.busy = true; - M.confirmBox('应用 CPU 设置?', '降低频率可能降低吞吐量;提高最低频率可能增加功耗和温度。').then(function(yes) { - if (!yes) return; - M.busy(button, true); - var toast = M.toast('正在应用 CPU 设置…', { type: 'busy', timeout: 0 }); - return apply(JSON.stringify({ changes: changes, persist: persist.checked })).then(function(r) { - if (!r.ok) throw new Error(r.rollback === false ? 'CPU 设置失败且回滚不完整,请检查实际状态' : r.error || 'CPU 配置无效'); - M.toast(M.translate('CPU 设置已应用'), { type: 'success' }); - }).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 thermalSection = node('section', null, 'mud-card mud-cpu-section'); + thermalSection.append(heading('温控管理', '即时生效', '按实际温区调整被动阈值;临界保护与回差只读,保留内核降频绑定。')); + this.thermalInputs = []; + this.thermalLive = []; + (data.zones || []).filter(function(z) { return z.trips.length; }).forEach(function(z) { + var card = node('div', null, 'mud-cpu-cluster'), head = node('div', null, 'mud-cpu-heading'); + var copy = node('div'), temp = node('strong', degrees(z.temp), 'mud-cpu-thermal-readonly'); + copy.append(node('h4', z.name), node('p', M.translate(z.mode === 'disabled' ? '温区已禁用' : '内核温控') + ' · ' + (z.policy || '--'), 'mud-note')); + head.append(copy, temp); card.append(head); + var live = { name: z.name, temp: temp, cooling: [] }; self.thermalLive.push(live); + var trips = node('div', null, 'mud-cpu-thermal-trips'); + z.trips.forEach(function(t) { + var title = t.type === 'passive' ? (t.throttles_cpu ? '降频触发温度' : '被动温控起点') : t.type === 'critical' ? '临界保护温度' : t.type === 'hot' ? '高温保护温度' : '只读阈值'; + var input; + if (t.writable) { + input = node('input'); input.type = 'number'; input.min = z.minimum / 1000; input.max = z.maximum / 1000; input.step = z.step / 1000; input.value = t.temp / 1000; + self.thermalInputs.push({ zone: z.name, trip: t.id, input: input }); + } else input = node('span', degrees(t.temp), 'mud-cpu-thermal-readonly'); + var row = field(title, input); + row.append(node('small', '#' + t.id + ' · ' + M.translate('回差') + ' ' + degrees(t.hysteresis) + (t.writable ? ' · ' + input.min + '–' + input.max + ' °C' : ' · ' + M.translate('只读')), 'mud-note')); + trips.append(row); + }); + card.append(trips); + var devices = node('div', null, 'mud-cpu-thermal-cooling'); + z.cooling.forEach(function(c) { + var badge = node('span', c.type + ' · ' + c.state + '/' + c.max_state, 'mud-cpu-badge'); + badge.title = M.translate('降温等级(当前 / 最大)'); devices.append(badge); live.cooling.push({ id: c.id, node: badge }); + }); + card.append(devices); thermalSection.append(card); + }); + if (!self.thermalInputs.length) thermalSection.append(node('p', M.translate('当前内核没有可写的 CPU 被动温控阈值,仅显示实际传感器。'), 'mud-note')); + var sensors = node('details', null, 'mud-cpu-sensors'), sensorGrid = node('div', null, 'mud-cpu-sensor-grid'); + sensors.append(node('summary', M.translate('温度传感器') + ' · ' + (data.zones || []).filter(function(z) { return !z.trips.length; }).length)); + (data.zones || []).filter(function(z) { return !z.trips.length; }).forEach(function(z) { + var row = node('div', null, 'mud-cpu-sensor'), temp = node('strong', degrees(z.temp)); + row.append(node('span', z.name), temp); sensorGrid.append(row); self.thermalLive.push({ name: z.name, temp: temp, cooling: [] }); + }); + sensors.append(sensorGrid); thermalSection.append(sensors); + thermalSection.append(node('p', M.translate('提高阈值可能增加温度;此处不会关闭内核临界保护或设备紧急保护。'), 'mud-note mud-cpu-warning')); + function controlsFor(scope, target, enabled) { + var isThermal = scope === 'thermal'; + target.dataset.scope = scope; + var controls = node('div', null, 'mud-cpu-actions'), persist = node('input'); + persist.type = 'checkbox'; persist.checked = !!(isThermal ? data.thermal_persist : data.persist); + if (isThermal) self.thermalPersist = persist; else self.persist = persist; + var label = node('label', null, 'mud-cpu-persist'), copy = node('span'); + copy.append(node('span', M.translate('开机自动应用')), node('span', M.translate('仅控制本区域;未勾选时只应用本次,并取消本区域的开机设置。'), 'mud-note')); + label.append(persist, copy); + var save = node('button', M.translate(isThermal ? '应用温控设置' : '应用频率设置'), 'mud-btn on'); + var reset = node('button', M.translate('恢复启动基线'), 'mud-btn'); + save.disabled = reset.disabled = persist.disabled = !enabled; + controls.append(label, reset, save); target.append(controls); + function reflect(r) { + // Never replace unsaved edits or persistence choices in another section. + if (isThermal) { + (r.zones || []).forEach(function(z) { self.thermalInputs.forEach(function(x) { if (x.zone === z.name) z.trips.forEach(function(t) { if (x.trip === t.id) x.input.value = t.temp / 1000; }); }); }); + persist.checked = !!r.thermal_persist; + } else { + (r.policies || []).forEach(function(p) { self.inputs.forEach(function(x) { if (x.p.id === p.id) { x.p = p; x.gov.value = p.governor; x.lo.value = p.min; x.hi.value = p.max; } }); }); + persist.checked = !!r.persist; + } + } + function submit(defaults) { + if (self.busy) return; + var payload = { scope: scope, persist: persist.checked }; + if (defaults) payload = { scope: scope, reset: true }; + else if (isThermal) { + if (self.thermalInputs.some(function(x) { return x.input.value.trim() === '' || !x.input.checkValidity(); })) { M.toast('温控阈值超出保护范围', { type: 'error' }); return; } + payload.thermal = self.thermalInputs.map(function(x) { return { zone: x.zone, trip: x.trip, temp: Math.round(Number(x.input.value) * 1000) }; }); + } else { + payload.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) }; }); + if (self.inputs.some(function(x) { return x.lo.value.trim() === '' || x.hi.value.trim() === ''; }) || + payload.changes.some(function(c) { return !Number.isInteger(c.min) || !Number.isInteger(c.max) || c.min > c.max; })) { M.toast('CPU 配置无效', { type: 'error' }); return; } + } + var title = defaults ? (isThermal ? '恢复温控启动基线?' : '恢复频率启动基线?') : (isThermal ? '应用温控设置?' : '应用频率设置?'); + var message = defaults ? (isThermal ? '仅恢复本次启动记录的温控阈值并取消温控开机应用;不修改频率或电压设置。' : '仅恢复本次启动记录的频率并取消频率开机应用;不修改温控或电压设置。') : + (isThermal ? '温控阈值将立即应用;提高阈值可能增加温度。不修改频率或电压设置。' : '降低频率可能降低吞吐量;提高最低频率可能增加功耗和温度。不修改温控或电压设置。'); + self.busy = true; + M.confirmBox(title, message).then(function(yes) { + if (!yes) return; + var button = defaults ? reset : save; M.busy(button, true); + var toast = M.toast(isThermal ? '正在应用温控设置…' : '正在应用频率设置…', { type: 'busy', timeout: 0 }); + return apply(JSON.stringify(payload)).then(function(r) { + if (!r.ok) throw new Error(r.rollback === false ? 'CPU 设置失败且回滚不完整,请检查实际状态' : r.error || 'CPU 配置无效'); + reflect(r); M.toast(isThermal ? '温控设置已应用' : '频率设置已应用', { type: 'success' }); + }).catch(function(e) { M.toast(M.translate(e.message), { type: 'error' }); }).finally(function() { toast.close(); M.busy(button, false); }); + }).finally(function() { self.busy = false; }); + } + save.onclick = function() { submit(false); }; + reset.onclick = function() { submit(true); }; + } + controlsFor('frequency', frequency, !!this.inputs.length); + controlsFor('thermal', thermalSection, !!this.thermalInputs.length); 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); + section.dataset.scope = 'voltage'; + root.append(section, thermalSection); 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); @@ -224,6 +306,14 @@ return view.extend({ 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 = p.current == null ? '--' : p.current / 1000; }); + self.thermalLive.forEach(function(x) { + var z = (r.zones || []).find(function(z) { return z.name === x.name; }); + x.temp.textContent = degrees(z ? z.temp : null); + x.cooling.forEach(function(entry) { + var c = z && z.cooling.find(function(c) { return c.id === entry.id; }); + entry.node.textContent = c ? c.type + ' · ' + c.state + '/' + c.max_state : '--'; + }); + }); }).catch(function() {}).finally(function() { self.inflight = false; }); }; poll.add(this.refresh, 2); diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js index a0b08cd9..86d24c40 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js @@ -282,42 +282,50 @@ return view.extend({ if (op === 'wifi') { self._wifiBusy = false; btn.disabled = false; } }); }; + /* Keep one confirmation/action in flight. Cancel, Escape and leaving + * this view must never turn into a control request. */ + var confirmAction = function(btn, title, body, options, op, arg, note) { + if (self._disposed || self._quickPending || btn.disabled) return; + self._quickPending = true; + return M.confirmBox(title, body, options).then(function(go) { + if (!go || self._disposed || !root.isConnected) return; + return act(op, arg, note, btn); + }).finally(function() { self._quickPending = false; }); + }; q('btn-data').onclick = function() { var up = self.lastInfo && self.lastInfo.wan && self.lastInfo.wan.up; - act('data', up ? 'down' : 'up', up ? '正在断开数据连接…' : '正在拨号…', this); + return confirmAction(this, up ? '断开数据连接' : '建立数据连接', + up ? '将断开蜂窝数据连接,依赖此连接的设备将无法上网。' : '将建立蜂窝数据连接,可能产生流量费用。', + { danger: !!up }, 'data', up ? 'down' : 'up', up ? '正在断开数据连接…' : '正在拨号…'); }; q('btn-radio').onclick = function() { var on = self.lastCell && self.lastCell.cfun === 1; - var btn = this; - (on - ? M.confirmBox('关闭蜂窝射频', '蜂窝连接会中断。', { danger: true }) - : M.confirmBox('打开蜂窝射频', '将执行 SFUN 上电序列(最多约 1 分钟)。') - ).then(function(go) { if (go) act('radio', on ? 'off' : 'on', null, btn); }); + return confirmAction(this, on ? '关闭蜂窝射频' : '打开蜂窝射频', + on ? '蜂窝连接会中断。' : '将执行 SFUN 上电序列(最多约 1 分钟)。', + { danger: !!on }, 'radio', on ? 'off' : 'on'); }; q('btn-wifi').onclick = function() { var wifi = self.lastInfo && self.lastInfo.wifi; if (!wifi || wifi.available === 0 || wifi.pending || self._wifiBusy) return; var on = self.lastInfo && self.lastInfo.wifi && self.lastInfo.wifi.up; - act('wifi', on ? 'off' : 'on', null, this); + return confirmAction(this, on ? '关闭 Wi-Fi 热点' : '打开 Wi-Fi 热点', + on ? '热点客户端会断开;若正通过此热点管理设备,需要重新连接后才能继续访问。' : '将使用已保存的配置开启 Wi-Fi 热点。', + { danger: !!on }, 'wifi', on ? 'off' : 'on'); }; q('btn-modem').onclick = function() { - var btn = this; - M.confirmBox('重启调制解调器', '蜂窝连接会中断 1-2 分钟。', { danger: true }) - .then(function(go) { if (go) act('modem-reset', null, null, btn); }); + return confirmAction(this, '重启调制解调器', '蜂窝连接会中断 1-2 分钟。', + { danger: true }, 'modem-reset', null); }; q('btn-reboot').onclick = function() { - var btn = this; - M.confirmBox('重启整个设备', '所有连接会断开。', { danger: true }) - .then(function(go) { if (go) act('reboot', null, null, btn); }); + return confirmAction(this, '重启整个设备', '所有连接会断开。', + { danger: true }, 'reboot', null); }; q('btn-android').onclick = function() { - var btn = this; - M.confirmBox('切换到 Android 系统', + return confirmAction(this, '切换到 Android 系统', '下次启动将进入 Android 并立即重启,此管理页面与蜂窝共享都会断开。\n' + '回到 OpenWrt:在 Android 上执行 mu300-next-boot linux 后重启;\n' + '或什么都不做,连续 5 次开机未完成会自动回退。', - { danger: true, okText: '切换并重启' }) - .then(function(go) { if (go) act('os', 'android', '正在武装 Android 引导并重启…', btn); }); + { danger: true, okText: '切换并重启' }, 'os', 'android', '正在武装 Android 引导并重启…'); }; q('reveal').onclick = function() { self.identShown = !self.identShown; diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/sim.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/sim.js index 6b6f1cdb..c5f70141 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/sim.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/sim.js @@ -12,20 +12,40 @@ errors.dual_boot_required='双卡尚未共同初始化,请重启后检查状 function message(s){return M.translate(errors[s]||s);} function el(tag,text,cls) { var n=document.createElement(tag); if(text!=null)n.textContent=text; if(cls)n.className=cls; return n; } function card(n) { return n===0||n===1 ? 'SIM '+(n+1) : M.translate('未连接'); } +var CSS = ` +.mud-sim-page .mud-sim-panel{padding:20px;min-width:0} +.mud-sim-page .mud-sim-panel h3{margin:0 0 10px;padding:0;border:0;font-size:1rem;font-weight:600;color:var(--text,#222)} +.mud-sim-page .mud-sim-intro{margin:0 0 16px;line-height:1.65} +.mud-sim-page .mud-data-sim{display:grid;gap:10px;margin:0;padding:14px;border:1px solid var(--hairline,var(--border-color,#ddd));border-radius:10px;min-width:0} +.mud-sim-page .mud-data-sim-controls{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px} +.mud-sim-page .mud-data-sim-controls label{flex:1;min-width:110px;font-weight:600;margin:0;color:var(--text,#222)} +.mud-sim-page .mud-data-sim-controls select{width:auto;min-width:100px;max-width:100%;margin:0} +.mud-sim-page .mud-data-sim-controls .mud-btn{margin:0;max-width:100%;white-space:normal} +.mud-sim-page .mud-sim-status{display:flex;flex-wrap:wrap;gap:6px 18px;padding:10px 0 0;border-top:1px solid var(--hairline,var(--border-color,#ddd));font-size:.8rem;line-height:1.6;color:var(--text-muted,#777)} +.mud-sim-page .mud-sim-status span{min-width:0;overflow-wrap:anywhere} +.mud-sim-page .mud-note{line-height:1.65;overflow-wrap:anywhere} +.mud-sim-page .mud-data-sim .mud-note{margin:0} +@media(max-width:480px){.mud-sim-page .mud-sim-panel{padding:16px}.mud-sim-page .mud-data-sim{padding:12px}.mud-sim-page .mud-data-sim-controls label{flex-basis:100%}.mud-sim-page .mud-data-sim-controls select{flex:1;min-width:0}.mud-sim-page .mud-data-sim-controls .mud-btn{flex:1}.mud-sim-page .mud-sim-status{flex-direction:column;gap:3px}} +`; return view.extend({ load:function() { return Promise.all([M.callSimGet(),get()]); }, render:function(data) { M.injectCss(); M.localizeMenu(); - var self=this, root=this.root=el('div',null,'mud'); - root.append(el('h2',M.translate('SIM 卡管理'))); - var panel=el('section',null,'mud-card'); root.append(panel); - var actual=el('p'), saved=el('p'), connection=el('p'), select=el('select'), button=el('button',M.translate('切换上网卡'),'mud-btn on'); - panel.append(actual,saved,connection); + var self=this, root=this.root=el('div',null,'mud mud-sim-page'); + root.append(el('style',CSS)); + var panel=el('section',null,'mud-card mud-sim-panel'); root.append(panel); + panel.append(el('h3',M.translate('SIM 卡管理'))); + panel.append(el('p',M.translate('切换上网卡后,看板、锁定和 AT 的查看卡槽会同步;仍可手动查看另一张卡。'),'mud-note mud-sim-intro')); + var controls=el('div',null,'mud-data-sim'); panel.append(controls); + var actual=el('span'), saved=el('span'), connection=el('span'), select=el('select'), button=el('button',M.translate('切换上网卡'),'mud-btn'); + select.id='mud-data-sim-select'; button.type='button'; [0,1].forEach(function(n) { var o=el('option',card(n)); o.value=n; select.append(o); }); - var row=el('div'); row.style.cssText='display:flex;gap:12px;flex-wrap:wrap;align-items:center'; - var label=el('label',M.translate('默认上网卡')+' '); label.append(select); row.append(label,button); panel.append(row); - panel.append(el('p',M.translate('切换会短暂中断蜂窝网络,成功后作为开机默认上网卡;不会切换 USB 或 Wi-Fi。'),'mud-note')); - panel.append(el('p',M.translate('欠费或无信号不影响选卡;数据连接失败不会自动切回。'),'mud-note')); + var row=el('div',null,'mud-data-sim-controls'); + var label=el('label',M.translate('默认上网卡')); label.htmlFor=select.id; + row.append(label,select,button); controls.append(row); + var summary=el('div',null,'mud-sim-status'); summary.append(actual,connection,saved); controls.append(summary); + controls.append(el('p',M.translate('切换会短暂中断蜂窝网络,成功后作为开机默认上网卡;不会切换 USB 或 Wi-Fi。'),'mud-note')); + controls.append(el('p',M.translate('欠费或无信号不影响选卡;数据连接失败不会自动切回。'),'mud-note')); function paint(r,initial) { actual.textContent=M.translate('当前上网卡')+':'+card(r.actual_sim); saved.textContent=M.translate('开机默认')+':'+card(r.saved_sim); diff --git a/openwrt/luci-app-mu300/root/etc/init.d/unisoc-cpu b/openwrt/luci-app-mu300/root/etc/init.d/unisoc-cpu index d105c51c..1fda8339 100644 --- a/openwrt/luci-app-mu300/root/etc/init.d/unisoc-cpu +++ b/openwrt/luci-app-mu300/root/etc/init.d/unisoc-cpu @@ -3,7 +3,6 @@ START=99 STOP=89 start() { - [ -f /etc/unisoc-modem/cpu.json ] || return 0 /usr/libexec/unisoc-modem/cpu boot | logger -t unisoc-cpu } shutdown() { diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cpu-thermal.uc b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cpu-thermal.uc new file mode 100644 index 00000000..56102f6f --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cpu-thermal.uc @@ -0,0 +1,75 @@ +// Standard thermal sysfs only. No sensor numbers, PMIC writes or AT dependencies. +import * as fs from 'fs'; +const ROOT=getenv('MU300_THERMAL_SYS') || '/sys/class/thermal'; +function text(path) { return trim(fs.readfile(path) || ''); } +function num(path) { let v=text(path); return match(v,/^-?[0-9]+$/)?int(v):null; } +export function zones() { + let out=[]; + for (let id in sort(fs.lsdir(ROOT) || [])) { + if (!match(id,/^thermal_zone[0-9]+$/)) continue; + let path=ROOT+'/'+id, cooling=[], trips=[]; + for (let entry in sort(fs.lsdir(path) || [])) { + if (!match(entry,/^cdev[0-9]+$/)) continue; + let kind=text(path+'/'+entry+'/type'); + if (!length(kind)) continue; + push(cooling,{id:entry,type:kind,state:num(path+'/'+entry+'/cur_state'),max_state:num(path+'/'+entry+'/max_state'),trip:num(path+'/'+entry+'_trip_point'),cpu:!!match(kind,/^cpufreq/)}); + } + for (let entry in fs.lsdir(path) || []) { + let m=match(entry,/^trip_point_([0-9]+)_temp$/); + if (!m) continue; + let index=int(m[1]), kind=text(path+'/trip_point_'+index+'_type'), value=num(path+'/'+entry); + push(trips,{id:index,type:kind,temp:value,hysteresis:num(path+'/trip_point_'+index+'_hyst'), + throttles_cpu:!!length(filter(cooling,c=>c.cpu && c.trip==index)), + writable:kind=='passive' && value!=null && !!length(filter(cooling,c=>c.cpu)) && !!(fs.stat(path+'/'+entry)?.mode & 128) && text(path+'/mode')!='disabled'}); + } + trips=sort(trips,(a,b)=>a.id-b.id); + let critical=map(filter(trips,t=>(t.type=='critical'||t.type=='hot') && t.temp!=null),t=>t.temp-10000); + let maximum=100000; for (let c in critical) if(clength(filter(z.cooling,c=>c.type==kind && c.state>0)))); +}; +export function plan(input,current) { + if(type(input)!='array' || length(input)>128) die('温控配置无效'); + let seen={}, steps=[]; + for(let item in input) { + if(type(item)!='object' || length(keys(item))!=3 || type(item.zone)!='string' || type(item.trip)!='int' || type(item.temp)!='int') die('温控配置无效'); + let found=filter(current,z=>z.name==item.zone); + if(length(found)!=1) die('温区不存在或名称不唯一'); + let z=found[0], t=filter(z.trips,t=>t.id==item.trip)[0], key=z.id+':'+item.trip; + if(!t?.writable || seen[key]) die('只能调整可写的 CPU 被动温控阈值'); + if(item.tempz.maximum || item.temp%z.step) die('温控阈值超出保护范围'); + seen[key]=true; + push(steps,{path:ROOT+'/'+z.id+'/trip_point_'+t.id+'_temp',before:t.temp,value:item.temp,zone:z.id,trip:t.id}); + } + for(let z in current) { + if(!length(filter(steps,s=>s.zone==z.id))) continue; + let previous=null; + for(let t in z.trips) { + if(t.type!='passive') continue; + let change=filter(steps,s=>s.zone==z.id && s.trip==t.id)[0], temp=change?change.value:t.temp; + if(temp==null || (previous!=null && temp-previous<1000)) die('被动温控阈值必须至少相隔 1°C 并递增'); + previous=temp; + } + } + // Lower low trips first; raise high trips first. Intermediate ordering is safe too. + return sort(steps,(a,b)=>{ + let da=a.valuex.zone==t.zone && x.trip==t.trip))) { + push(stored.thermal,t); added=true; + } + if(!added) return stored; + } else stored={boot:id,changes:map(filter(current,p=>p.writable),p=>({id:p.id,cpus:p.cpus,governor:p.governor,min:p.min,max:p.max})),thermal:thermal.settings(zones)}; + let text=sprintf('%J\n',stored), tmp=DEFAULTS+'.new'; + if(fs.writefile(tmp,text)!=length(text) || !fs.chmod(tmp,384) || !fs.rename(tmp,DEFAULTS)) { + fs.unlink(tmp); die('无法保存 CPU 启动基线'); + } + return stored; } function write(id,key,value) { let s=''+value; @@ -34,6 +75,10 @@ function write(id,key,value) { sleep(10); actual=read(id,key); } let ok=written==length(s)+1 && actual==s; + // scaling_max_freq reports the effective policy cap, not the caller's QoS + // request. A successfully accepted max request may remain thermally capped. + if(!ok && key=='scaling_max_freq' && written==length(s)+1 && + match(actual,/^[0-9]+$/) && int(actual)32) + if(type(input)!='object') return {ok:0,error:'CPU 配置无效'}; + let scope=input.scope || 'frequency', config=saved(); + if(scope!='frequency' && scope!='thermal') return {ok:0,error:'CPU 配置无效'}; + // A stale combined UI must never apply or erase the other section. + if((scope=='frequency' && input.thermal!=null) || (scope=='thermal' && input.changes!=null)) + return {ok:0,error:'请刷新页面后分别应用频率或温控设置'}; + if(input.reset===true) { + let base=baseline(current,zones); + input=scope=='frequency'?{changes:base.changes,persist:false}:{thermal:base.thermal,persist:false}; + } + let changes=scope=='frequency'?input.changes:[], trips=scope=='thermal'?input.thermal:[]; + if(type(input.persist)!='bool' || type(changes)!='array' || length(changes)>32 || + (scope=='frequency' && !length(changes)) || (scope=='thermal' && !length(trips || []))) return {ok:0,error:'CPU 配置无效'}; - for(let c in input.changes) { + try { steps=thermal.plan(trips,zones); } catch(e) { return {ok:0,error:e.message || ''+e}; } + for(let c in changes) { let p=byid[c?.id]; if(!p?.writable || seen[c.id] || c.cpus!=p.cpus || type(c.min)!='int' || type(c.max)!='int' || c.min>c.max || c.minp.hardware_max || index(p.governors,c.governor)<0 || @@ -59,30 +117,55 @@ function apply(input) { return {ok:0,error:'CPU 配置无效'}; seen[c.id]=true; } - let changed=[], error=null, rollback=true; - for(let c in input.changes) { + baseline(current,zones); + let desired=map(filter(current,p=>p.writable),p=>({id:p.id,cpus:p.cpus,governor:p.governor,min:p.min,max:p.max})); + // Retain saved QoS requests when only thermal settings are edited; never + // replace them with the temporary caps produced by the thermal governor. + for(let c in (config.frequency?.changes || [])) for(let p in desired) if(p.id==c.id && p.cpus==c.cpus) { + p.governor=c.governor; p.min=c.min; p.max=c.max; + } + for(let c in changes) for(let p in desired) if(p.id==c.id) { + p.governor=c.governor; p.min=c.min; p.max=c.max; + } + let changed=[], thermal_changed=[], error=null, rollback=true; + for(let c in changes) { let p=byid[c.id]; push(changed,p); if(!set(p,c)) { error='CPU 配置回读不一致'; break; } } - if(!error && input.persist) { - let text=sprintf('%J\n',{version:1,persist:true,changes:input.changes}), tmp=CONFIG+'.new'; - if(fs.writefile(tmp,text)!=length(text) || !fs.chmod(tmp,384) || !fs.rename(tmp,CONFIG)) { - fs.unlink(tmp); error='无法保存 CPU 设置'; - } - } else if(!error && !input.persist && fs.stat(CONFIG) && !fs.unlink(CONFIG)) error='无法保存 CPU 设置'; + if(!error) for(let step in steps) { + push(thermal_changed,step); + if(!thermal.write(step,false)) { error='温控配置回读不一致'; break; } + } + if(!error && !replay) { + let profile=scope=='frequency'?{changes:desired}:{thermal:thermal.settings(thermal.zones())}; + if(!save_scope(config,scope,input.persist?profile:null)) error='无法保存 CPU 设置'; + } if(error) { + for(let step in reverse(thermal_changed)) if(!thermal.write(step,true)) rollback=false; for(let p in reverse(changed)) if(!set(p,p)) rollback=false; return {ok:0,error,rollback,failed_write}; } - return {ok:1,policies:policies(),persist:input.persist}; + let flags=persist_flags(saved()); + return {ok:1,scope,policies:policies(),zones:thermal.zones(),persist:flags.persist,thermal_persist:flags.thermal_persist}; } let action=ARGV[0] || 'get', result; try { - if(action=='get') result={ok:1,policies:policies(),persist:saved()?.persist===true}; - else if(action=='forget') result=(!fs.stat(CONFIG) || fs.unlink(CONFIG)) ? {ok:1,persist:false} : {ok:0,error:'无法保存 CPU 设置'}; + if(action=='get') { + let flags=persist_flags(saved()); + result={ok:1,policies:policies(),zones:thermal.zones(),persist:flags.persist,thermal_persist:flags.thermal_persist}; + } + else if(action=='forget') result=save_scope(saved(),'frequency',null) ? {ok:1,persist:false} : {ok:0,error:'无法保存 CPU 设置'}; else if(action=='boot') { + baseline(policies(),thermal.zones()); let config=saved(); - result=!fs.stat(CONFIG)?{ok:1,skipped:true}:config?.version==1?apply(config):{ok:0,error:'CPU 配置无效'}; + let frequency={ok:1,skipped:true}, therm={ok:1,skipped:true}; + // Each domain replays independently; missing thermal support must not + // prevent restoring frequency settings (or vice versa). + if(config.frequency!=null) try { frequency=apply({scope:'frequency',changes:config.frequency.changes,persist:true},true); } + catch(e) { frequency={ok:0,error:'CPU 配置无效'}; } + if(config.thermal!=null) try { therm=apply({scope:'thermal',thermal:config.thermal.thermal,persist:true},true); } + catch(e) { therm={ok:0,error:'温控配置无效'}; } + result={ok:frequency.ok && therm.ok?1:0,frequency,thermal:therm}; } else if(action=='apply') { let text=fs.stdin.read(16385); result=length(text)>16384?{ok:0,error:'CPU 配置无效'}:apply(json(text)); diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/dashboard-info b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/dashboard-info index ddb2b9ed..5af3a47c 100644 --- a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/dashboard-info +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/dashboard-info @@ -112,7 +112,16 @@ LAN_DEVICE=$(cfg lan_device); LAN_DEVICE=${LAN_DEVICE:-br-lan} WIFI_DEVICE=$(cfg wifi_device); WIFI_DEVICE=${WIFI_DEVICE:-wlan0} USB_DEVICE=$(cfg usb_device); USB_DEVICE=${USB_DEVICE:-usb0} jaddr4() { printf '%s' "$1" | sed -n 's/.*"address": *"\([^"]*\)".*/\1/p' | head -n1; } -jarr_dns() { printf '%s' "$1" | sed -n 's/.*"dns-server": *\[\([^]]*\)\].*/\1/p' | tr -d '"' ; } +wan_dns_servers() { + # ubus pretty-prints arrays over multiple lines. Parse only the top-level + # active DNS list, never inactive.dns-server or the loopback resolv.conf. + # Reuse the two status snapshots: no additional RPC, AT request or cache. + local snapshot + for snapshot in "$@"; do + [ -n "$snapshot" ] || continue + jsonfilter -s "$snapshot" -e '@["dns-server"][*]' 2>/dev/null || : + done | awk 'NF && !seen[$0]++ { printf "%s%s", sep, $0; sep=", " }' +} wan_up=$(jval "$WANJSON" up) [ "$wan_up" = "true" ] && wan_up=1 || wan_up=0 @@ -122,7 +131,7 @@ wan_ip4=$(jaddr4 "$WANJSON") wan6_up=$(jval "$WAN6JSON" up) [ "$wan6_up" = "true" ] && wan6_up=1 || wan6_up=0 wan6_ip=$(t2 ip -6 addr show "$DATA_DEVICE" 2>/dev/null | awk '/inet6 [23]/{split($2,s,"/"); print s[1]; exit}') -wan_dns=$(jarr_dns "$WANJSON") +wan_dns=$(wan_dns_servers "$WANJSON" "$WAN6JSON") apn=$(t3 uci -q get "network.$DATA_IFACE.apn") [ -n "$apn" ] || apn="(SIM default)" diff --git a/rootfs/overlay/opt/mu300/bin/extra-modules b/rootfs/overlay/opt/mu300/bin/extra-modules index 76bceea4..6743e446 100755 --- a/rootfs/overlay/opt/mu300/bin/extra-modules +++ b/rootfs/overlay/opt/mu300/bin/extra-modules @@ -8,6 +8,12 @@ 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' +# Mainline: retain the factory virtual sensor, trip points and CPU cooling maps. +# Vendor 5.4 keeps its own implementation. Missing/failed module leaves the +# existing thermal-guard fallback in charge. +if [ -f "$M/mu300_thermal.ko" ] && ! [ -d /sys/module/mu300_thermal ]; then + insmod "$M/mu300_thermal.ko" || echo 'virtual thermal load failed' +fi 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 \ diff --git a/rootfs/overlay/opt/mu300/bin/thermal-guard b/rootfs/overlay/opt/mu300/bin/thermal-guard index a7dd5bec..36f3386a 100755 --- a/rootfs/overlay/opt/mu300/bin/thermal-guard +++ b/rootfs/overlay/opt/mu300/bin/thermal-guard @@ -1,7 +1,8 @@ #!/bin/sh -# Thermal safety for kernels without SoC trip points (mainline: the stock DT only has trips on the vendor virtual -# zone). Reads the hottest on-die sensor every 5 s: above HOT caps every cpufreq policy one step lower, below COOL -# lifts the cap one step, above CRIT powers off. The 5.4 vendor kernel throttles itself, so there it only watches. +# Thermal safety for kernels without functional CPU cooling bindings. The mainline virtual sensor, when +# available, restores the stock DT trips and lets native cooling handle frequency limits. Otherwise above HOT +# caps each policy one step lower, below COOL lifts the cap. Mainline keeps CRIT emergency shutdown either way. +# The 5.4 vendor kernel throttles/protects itself, so there this script only watches. # On every kernel: the SoC at HOT or (U30 Air) the battery at BATT_HOT (tenths of a degree, as power_supply reports it) sets # off the LED alarm (mu300-led alarm: a red and blue siren), until the SoC is down to COOL and the battery to # BATT_COOL. @@ -17,6 +18,33 @@ throttle=1 for z in "$R"/sys/class/thermal/thermal_zone*; do [ -e "$z/trip_point_0_temp" ] && { throttle=0; echo "kernel thermal trips present: only the LED alarm here"; break; } done +legacy_throttle=$throttle +[ -d "$R/sys/module/mu300_thermal" ] && legacy_throttle=1 + +# The mainline virtual sensor can probe after this service starts. Only hand +# frequency control over when every existing CPU cooling device is bound to +# the enabled stock zone. Keep our more conservative 105 C shutdown protection. +native_cpu_cooling() { + local zone mode kind dev link found count=0 + [ -d "$R/sys/module/mu300_thermal" ] || return 1 + for zone in "$R"/sys/class/thermal/thermal_zone*; do + read -r kind < "$zone/type" 2>/dev/null || continue + [ "$kind" = soc-thmzone ] || continue + read -r mode < "$zone/mode" 2>/dev/null || continue + [ "$mode" = enabled ] || return 1 + for dev in "$R"/sys/class/thermal/cooling_device*; do + read -r kind < "$dev/type" 2>/dev/null || continue + case "$kind" in cpufreq-*) ;; *) continue ;; esac + count=$((count + 1)); found=0 + for link in "$zone"/cdev[0-9]*; do + [ "$link" -ef "$dev" ] && { found=1; break; } + done + [ "$found" = 1 ] || return 1 + done + [ "$count" -gt 0 ] && return 0 + done + return 1 +} hottest() { local max=0 t @@ -55,9 +83,15 @@ step() { # the alarm's state outlives a restart of this service, so a cooled device is never left flashing ALARM=$R/run/mu300/thermal-alarm while :; do + throttle=$legacy_throttle + emergency=$legacy_throttle + if [ -d "$R/sys/module/mu300_thermal" ]; then + throttle=1; emergency=1 + native_cpu_cooling && throttle=0 + fi t=$(hottest) b=$(battery) - if [ "$t" -ge "$CRIT" ] && [ "$throttle" = 1 ]; then + if [ "$t" -ge "$CRIT" ] && [ "$emergency" = 1 ]; then logger -t thermal-guard "critical temperature ${t} mC, powering off" poweroff elif [ "$t" -ge "$HOT" ] && [ "$throttle" = 1 ]; then diff --git a/tests/cpu_fixture.sh b/tests/cpu_fixture.sh index abf316b5..5ce3ecae 100755 --- a/tests/cpu_fixture.sh +++ b/tests/cpu_fixture.sh @@ -4,7 +4,9 @@ set -eu lib=$1 base=$(mktemp -d /tmp/mu300-cpu-test.XXXXXX) export MU300_CPU_SYS=$base/sys MU300_CPU_CONFIG=$base/cpu.json -mkdir -p "$MU300_CPU_SYS/policy0" "$MU300_CPU_SYS/policy4" +export MU300_THERMAL_SYS=$base/thermal MU300_CPU_DEFAULTS=$base/defaults.json MU300_CPU_BOOT_ID=$base/boot +mkdir -p "$MU300_CPU_SYS/policy0" "$MU300_CPU_SYS/policy4" "$MU300_THERMAL_SYS" +printf 'cpu-fixture-boot\n' > "$base/boot" for id in policy0 policy4; do d=$MU300_CPU_SYS/$id printf '0 1\n' > "$d/affected_cpus" diff --git a/tests/cpu_thermal_fixture.sh b/tests/cpu_thermal_fixture.sh new file mode 100644 index 00000000..c417d24b --- /dev/null +++ b/tests/cpu_thermal_fixture.sh @@ -0,0 +1,166 @@ +#!/bin/sh +# Isolated filesystem only; no live thermal, CPU or modem access. +set -eu +lib=$1 +base=$(mktemp -d /tmp/mu300-thermal-test.XXXXXX) +export MU300_CPU_SYS=$base/cpu MU300_THERMAL_SYS=$base/thermal +export MU300_CPU_CONFIG=$base/config.json MU300_CPU_DEFAULTS=$base/defaults.json MU300_CPU_BOOT_ID=$base/boot +mkdir -p "$MU300_CPU_SYS" "$MU300_THERMAL_SYS" +p=$MU300_CPU_SYS/policy0 +mkdir -p "$p" +printf '0 1 2 3\n' > "$p/affected_cpus" +printf 'test\n' > "$p/scaling_driver" +printf 'schedutil performance\n' > "$p/scaling_available_governors" +printf 'schedutil\n' > "$p/scaling_governor" +printf '100\n' > "$p/scaling_min_freq" +printf '300\n' > "$p/scaling_max_freq" +printf '100\n' > "$p/cpuinfo_min_freq" +printf '300\n' > "$p/cpuinfo_max_freq" +printf '100 200 300\n' > "$p/scaling_available_frequencies" +printf 'boot-one\n' > "$base/boot" +# Baseline before a deferred virtual sensor probes; merge it before first edit. +ucode "$lib" boot >/dev/null +z=$MU300_THERMAL_SYS/thermal_zone19 +c=$MU300_THERMAL_SYS/cooling_device0 +mkdir -p "$z" "$c" +printf 'soc-thmzone\n' > "$z/type" +printf '42000\n' > "$z/temp" +printf 'enabled\n' > "$z/mode" +printf 'step_wise\n' > "$z/policy" +printf 'cpufreq-cpu0\n' > "$c/type" +printf '0\n' > "$c/cur_state" +printf '9\n' > "$c/max_state" +ln -s "$c" "$z/cdev0" +printf '1\n' > "$z/cdev0_trip_point" +for i in 0 1 2; do + printf '1000\n' > "$z/trip_point_${i}_hyst" + printf 'passive\n' > "$z/trip_point_${i}_type" +done +printf 'critical\n' > "$z/trip_point_2_type" +printf '70000\n' > "$z/trip_point_0_temp" +printf '85000\n' > "$z/trip_point_1_temp" +printf '110000\n' > "$z/trip_point_2_temp" +call() { ucode "$lib" "$@"; } +check() { jsonfilter -s "$1" -e "$2"; } +out=$(call get) +test "$(check "$out" '@.zones[0].trips[0].writable')" = true +test "$(check "$out" '@.zones[0].trips[0].throttles_cpu')" = false +test "$(check "$out" '@.zones[0].trips[1].throttles_cpu')" = true +test "$(check "$out" '@.zones[0].trips[2].writable')" = false +test "$(jsonfilter -i "$base/defaults.json" -e '@.thermal[*].zone' | wc -l)" = 0 +call boot >/dev/null +for entry in \ + '{"zone":"soc-thmzone","trip":2,"temp":90000}' \ + '{"zone":"soc-thmzone","trip":0,"temp":85000}' \ + '{"zone":"soc-thmzone","trip":1,"temp":70000}' \ + '{"zone":"soc-thmzone","trip":1,"temp":101000}' \ + '{"zone":"soc-thmzone","trip":0,"temp":39000}' \ + '{"zone":"soc-thmzone","trip":0,"temp":70500}' \ + '{"zone":"../soc-thmzone","trip":0,"temp":71000}' \ + '{"zone":"soc-thmzone","trip":0,"temp":"71000"}'; do + if printf '{"scope":"thermal","thermal":[%s],"persist":false}' "$entry" | call apply > "$base/result"; then echo "accepted invalid $entry"; exit 1; fi + test "$(cat "$z/trip_point_0_temp")" = 70000 + test "$(cat "$z/trip_point_1_temp")" = 85000 +done +payload='{"scope":"thermal","thermal":[{"zone":"soc-thmzone","trip":0,"temp":69000},{"zone":"soc-thmzone","trip":1,"temp":84000}],"persist":true}' +printf '%s' "$payload" | call apply > "$base/result" +test "$(cat "$z/trip_point_0_temp")" = 69000 +test -f "$base/config.json" +printf '70000\n' > "$z/trip_point_0_temp" +printf '85000\n' > "$z/trip_point_1_temp" +printf 'boot-two\n' > "$base/boot" +call boot >/dev/null +test "$(cat "$z/trip_point_1_temp")" = 84000 +printf '{"scope":"thermal","reset":true}' | call apply >/dev/null +test "$(cat "$z/trip_point_0_temp")" = 70000 +test "$(cat "$z/trip_point_1_temp")" = 85000 +test ! -f "$base/config.json" +# A persistence failure rolls all thermal writes back. +if printf '%s' "$payload" | MU300_CPU_CONFIG="$base/missing/config" call apply > "$base/result"; then exit 1; fi +test "$(jsonfilter -i "$base/result" -e '@.rollback')" = true +test "$(cat "$z/trip_point_0_temp")" = 70000 +test "$(cat "$z/trip_point_1_temp")" = 85000 +# No CPU binding => read-only. Duplicate names => refuse ambiguous writes. +mv "$z/cdev0" "$z/hidden-cdev" +out=$(call get) +test "$(check "$out" '@.zones[0].trips[0].writable')" = false +if printf '%s' "$payload" | call apply >/dev/null; then exit 1; fi +mv "$z/hidden-cdev" "$z/cdev0" +printf 'disabled\n' > "$z/mode" +if printf '%s' "$payload" | call apply >/dev/null; then exit 1; fi +printf 'enabled\n' > "$z/mode" +mkdir "$MU300_THERMAL_SYS/thermal_zone20" +printf 'soc-thmzone\n' > "$MU300_THERMAL_SYS/thermal_zone20/type" +if printf '%s' "$payload" | call apply >/dev/null; then exit 1; fi +test "$(cat "$z/trip_point_2_temp")" = 110000 +test "$(cat "$z/trip_point_1_hyst")" = 1000 +rm "$MU300_THERMAL_SYS/thermal_zone20/type" +rmdir "$MU300_THERMAL_SYS/thermal_zone20" +# Independent frequency and thermal saves, resets, persistence and boot replay. +freq='{"scope":"frequency","changes":[{"id":"policy0","cpus":"0 1 2 3","governor":"performance","min":100,"max":200}],"persist":true}' +printf '%s' "$freq" | call apply >/dev/null +test "$(cat "$z/trip_point_0_temp")" = 70000 +printf '%s' "$payload" | call apply >/dev/null +test "$(cat "$p/scaling_max_freq")" = 200 +test "$(cat "$p/scaling_governor")" = performance +out=$(call get) +test "$(check "$out" '@.persist')" = true +test "$(check "$out" '@.thermal_persist')" = true +thermal_profile=$(jsonfilter -i "$base/config.json" -e '@.thermal') +printf '{"scope":"frequency","reset":true}' | call apply >/dev/null +test "$(cat "$p/scaling_max_freq")" = 300 +test "$(cat "$z/trip_point_0_temp")" = 69000 +test "$(jsonfilter -i "$base/config.json" -e '@.thermal')" = "$thermal_profile" +test "$(check "$(call get)" '@.persist')" = false +printf '%s' "$freq" | call apply >/dev/null +frequency_profile=$(jsonfilter -i "$base/config.json" -e '@.frequency') +printf '{"scope":"thermal","reset":true}' | call apply >/dev/null +test "$(cat "$z/trip_point_0_temp")" = 70000 +test "$(cat "$p/scaling_max_freq")" = 200 +test "$(jsonfilter -i "$base/config.json" -e '@.frequency')" = "$frequency_profile" +test "$(check "$(call get)" '@.thermal_persist')" = false +printf '%s' "$payload" | call apply >/dev/null +# Cancelling one section's auto-apply preserves the other's profile and values. +printf '%s' "$payload" | sed 's/"persist":true/"persist":false/' | call apply >/dev/null +test "$(jsonfilter -i "$base/config.json" -e '@.frequency')" = "$frequency_profile" +test "$(cat "$z/trip_point_0_temp")" = 69000 +printf '%s' "$payload" | call apply >/dev/null +# A stale combined UI is rejected before touching either domain or config. +before=$(cat "$base/config.json") +if printf '{"changes":[],"thermal":[],"persist":false}' | call apply >/dev/null; then exit 1; fi +test "$(cat "$base/config.json")" = "$before" +# Missing thermal capability must not block valid frequency startup settings. +printf 'disabled\n' > "$z/mode" +printf '300\n' > "$p/scaling_max_freq" +if call boot > "$base/result"; then exit 1; fi +test "$(cat "$p/scaling_max_freq")" = 200 +test "$(jsonfilter -i "$base/result" -e '@.frequency.ok')" = 1 +test "$(jsonfilter -i "$base/result" -e '@.thermal.ok')" = 0 +test "$(cat "$base/config.json")" = "$before" +printf 'enabled\n' > "$z/mode" +# Invalid frequency profile must not prevent the valid thermal replay either. +ucode -e 'import * as fs from "fs"; let p=getenv("MU300_CPU_CONFIG"), c=json(fs.readfile(p)); c.frequency.changes[0].max=999; fs.writefile(p,sprintf("%J",c));' +printf '70000\n' > "$z/trip_point_0_temp" +printf '85000\n' > "$z/trip_point_1_temp" +if call boot > "$base/result"; then exit 1; fi +test "$(jsonfilter -i "$base/result" -e '@.frequency.ok')" = 0 +test "$(jsonfilter -i "$base/result" -e '@.thermal.ok')" = 1 +test "$(cat "$z/trip_point_0_temp")" = 69000 +test "$(cat "$p/scaling_max_freq")" = 200 +# Old combined profiles remain readable and replayable; first scoped save +# atomically migrates them without silently erasing the untouched half. +printf '%s\n' '{"version":1,"persist":true,"changes":[{"id":"policy0","cpus":"0 1 2 3","governor":"performance","min":100,"max":200}],"thermal":[{"zone":"soc-thmzone","trip":0,"temp":69000},{"zone":"soc-thmzone","trip":1,"temp":84000}]}' > "$base/config.json" +before=$(cat "$base/config.json") +call get >/dev/null +call boot >/dev/null +test "$(cat "$base/config.json")" = "$before" +printf '{"scope":"frequency","reset":true}' | call apply >/dev/null +test "$(jsonfilter -i "$base/config.json" -e '@.version')" = 2 +test "$(check "$(call get)" '@.thermal_persist')" = true +test "$(cat "$z/trip_point_0_temp")" = 69000 +printf '{"scope":"thermal","reset":true}' | call apply >/dev/null +test ! -e "$base/config.json" +test "$(cat "$p/scaling_max_freq")" = 300 +test "$(cat "$z/trip_point_0_temp")" = 70000 +echo 'PASS independent frequency/thermal save, reset, auto-apply, boot failure isolation, legacy migration and stale UI rejection' +echo 'PASS thermal discovery, limits, ordering, binding, persistence, boot, reset, rollback, read-only critical/hysteresis' diff --git a/tests/dashboard_cpu_sections_browser.py b/tests/dashboard_cpu_sections_browser.py new file mode 100644 index 00000000..59127bb4 --- /dev/null +++ b/tests/dashboard_cpu_sections_browser.py @@ -0,0 +1,80 @@ +from pathlib import Path +from playwright.sync_api import sync_playwright +import re + +top=Path(__file__).resolve().parents[1] +js=top/'openwrt/luci-app-mu300/htdocs/luci-static/resources' +common=(js/'mu300/common.js').read_text(encoding='utf-8') +cpu=(js/'view/mu300/cpu.js').read_text(encoding='utf-8') +with sync_playwright() as p: + browser=p.chromium.launch(headless=True,executable_path='C:/Users/kano/AppData/Local/ms-playwright/chromium-1024/chrome-win/chrome.exe') + for theme in ('aurora','bootstrap'): + for dark in (False,True): + for lang in ('zh-cn','en','tr'): + for width in (360,1280): + page=browser.new_page(viewport={'width':width,'height':900}) + errors=[]; page.on('pageerror',lambda e:errors.append(str(e))) + page.route('http://mu300.test/**',lambda r:r.fulfill(body='',content_type='text/html')) + page.goto('http://mu300.test/') + bg,surface,text,muted,border=('#15171b','#202329','#eee','#a5a9b0','#383c44') if dark else ('#f4f5f7','#fff','#202329','#626874','#dce0e6') + tokens={'surface':surface,'surface-sunken':bg,'text':text,'text-muted':muted,'hairline':border,'brand':'#447bee'} if theme=='aurora' else {'background-color-high':surface,'background-color-low':bg,'text-color-high':text,'text-color-medium':muted,'text-color-low':muted,'border-color-low':border,'primary-color-high':'#447bee'} + page.add_style_tag(content='html{'+''.join(f'--{k}:{v};' for k,v in tokens.items())+'}body{margin:16px;background:'+bg+';color:'+text+';font-family:Arial,sans-serif}*{box-sizing:border-box}') + page.evaluate('''([common,cpu,lang])=>{ + window.L={env:{lang}}; window.requests=[]; + window.data={ok:1,persist:false,policies:[0,4,7].map((id,i)=>({id:'policy'+id,cpus:['0 1 2 3','4 5 6','7'][i],driver:'sprd-cpufreq-v2',governors:['schedutil','performance'],governor:'schedutil',frequencies:[408000,1000000,1800000],min:408000,max:1800000,hardware_min:408000,hardware_max:1800000,current:1000000,writable:true})),zones:[{name:'soc-thmzone',id:'thermal_zone19',temp:42000,minimum:40000,maximum:100000,step:1000,mode:'enabled',policy:'step_wise',trips:[{id:0,type:'passive',temp:70000,hysteresis:1000,writable:true,throttles_cpu:false},{id:1,type:'passive',temp:85000,hysteresis:1000,writable:true,throttles_cpu:true},{id:2,type:'critical',temp:110000,hysteresis:2000,writable:false}],cooling:[{id:'cdev0',type:'cpufreq-cpu0',state:0,max_state:9}]},{name:'lit0-thmzone',id:'thermal_zone7',temp:40000,trips:[],cooling:[]}],voltage:{supported:false}}; + const rpc={declare:o=>(payload)=>{if(o.method==='cpu_apply'){requests.push(JSON.parse(payload));}return Promise.resolve(data);}}; + const M=new Function('rpc','baseclass','L',common)(rpc,{extend:o=>o},L); + window.view=new Function('view','rpc','poll','M',cpu)({extend:o=>o},rpc,{add(){},remove(){}},M); + document.body.append(view.render(data)); + }''',[common,cpu,lang]) + assert page.evaluate('document.documentElement.scrollWidth <= innerWidth'),(theme,dark,lang,width,'overflow') + if lang!='zh-cn': + assert not re.search(r'[\u4e00-\u9fff]',page.locator('.mud-cpu').inner_text()),page.locator('.mud-cpu').inner_text() + assert page.locator('.mud-cpu-section').evaluate_all("es=>es.map(e=>e.dataset.scope)")==['frequency','voltage','thermal'] + assert page.locator('.mud-cpu-thermal-trips input').count()==2 + thermal=page.locator('[data-scope="thermal"]') + frequency=page.locator('[data-scope="frequency"]') + freqmax=frequency.locator('.mud-cpu-range select').nth(1) + freqmax.select_option('1000000') + page.locator('.mud-cpu-thermal-trips input').first.fill('69') + page.evaluate('view.refresh()') + assert page.locator('.mud-cpu-thermal-trips input').first.input_value()=='69' + page.evaluate('view.persist.checked=true;view.thermalPersist.checked=true') + # Thermal cancellation cannot write. Applying it preserves frequency edits. + thermal.locator('.mud-cpu-actions .mud-btn.on').click() + page.keyboard.press('Escape') + assert page.evaluate('requests.length')==0 + thermal.locator('.mud-cpu-actions .mud-btn.on').click() + if lang!='zh-cn': assert not re.search(r'[\u4e00-\u9fff]',page.locator('.mud-dlg').inner_text()) + page.locator('.mud-dlg [data-r="1"]').click() + page.wait_for_function('requests.length===1 && !view.busy') + sent=page.evaluate('requests[0]') + assert sent['thermal'][0]=={'zone':'soc-thmzone','trip':0,'temp':69000} + assert sent['scope']=='thermal' and sent['persist'] and 'changes' not in sent + assert freqmax.input_value()=='1000000' + assert page.evaluate('view.persist.checked') + # Invalid unfinished thermal input must not block a frequency save. + page.locator('.mud-cpu-thermal-trips input').first.fill('20') + page.evaluate('view.thermalPersist.checked=true') + frequency.locator('.mud-cpu-actions .mud-btn.on').click() + page.locator('.mud-dlg [data-r="1"]').click() + page.wait_for_function('requests.length===2 && !view.busy') + sent=page.evaluate('requests[1]') + assert sent['scope']=='frequency' and 'thermal' not in sent and sent['persist'] + assert sent['changes'][0]['max']==1000000 + assert page.locator('.mud-cpu-thermal-trips input').first.input_value()=='20' + assert page.evaluate('view.thermalPersist.checked') + # Each reset is scoped; even the unsubmitted other draft survives. + for scope,section in [('frequency',frequency),('thermal',thermal)]: + before=page.evaluate('requests.length') + section.locator('.mud-cpu-actions .mud-btn:not(.on)').click() + if lang!='zh-cn': assert not re.search(r'[\u4e00-\u9fff]',page.locator('.mud-dlg').inner_text()) + page.locator('.mud-dlg [data-r="1"]').click() + page.wait_for_function('n=>requests.length===n+1 && !view.busy',arg=before) + assert page.evaluate('requests[requests.length-1]')=={'scope':scope,'reset':True} + if scope=='frequency': assert page.locator('.mud-cpu-thermal-trips input').first.input_value()=='20' + assert not errors,errors + if theme=='aurora' and lang=='zh-cn':page.screenshot(path=str(top/f'work/cpu-thermal-{width}-{dark}.png'),full_page=True) + page.close() + browser.close() +print('PASS 24 CPU layouts: frequency/voltage/thermal order, independent apply/reset/auto-apply, preserved other drafts, zh/en/tr, Aurora/Bootstrap light/dark, mobile/desktop') diff --git a/tests/dashboard_dns_fixture.sh b/tests/dashboard_dns_fixture.sh new file mode 100644 index 00000000..c877cd78 --- /dev/null +++ b/tests/dashboard_dns_fixture.sh @@ -0,0 +1,32 @@ +#!/bin/sh +# Run with OpenWrt's real jsonfilter; does not touch networking or AT. +set -eu +info=${1:?dashboard-info path required} +command -v jsonfilter >/dev/null +eval "$(sed -n '/^wan_dns_servers() {/,/^}/p' "$info")" +check() { + expected=$1; shift + actual=$(wan_dns_servers "$@") + [ "$actual" = "$expected" ] || { + printf 'DNS mismatch: expected <%s>, got <%s>\n' "$expected" "$actual" >&2 + exit 1 + } +} +wan='{ + "up": true, + "dns-server": [ + "58.20.127.238", + "58.20.127.170" + ], + "inactive": {"dns-server": ["192.0.2.99"]} +}' +check '58.20.127.238, 58.20.127.170' "$wan" '' +check '58.20.127.238, 58.20.127.170, 2001:db8::53' "$wan" \ + '{"dns-server":["58.20.127.238","2001:db8::53","2001:db8::53"]}' +check '2001:db8::53' '{"dns-server":[]}' '{"dns-server":["2001:db8::53"]}' +check '2001:db8::53' 'invalid JSON' '{"dns-server":["2001:db8::53"]}' +check '' '' '' +check '' '{"dns-server":[]}' '{"inactive":{"dns-server":["192.0.2.99"]}}' +check '' '{"dns-server":null}' '{}' +check '1.1.1.1, 2606:4700:4700::1111' '{"dns-server":["1.1.1.1","2606:4700:4700::1111"]}' +echo 'PASS dashboard DNS: multiline/compact, IPv4/IPv6, dedup, missing, malformed, inactive excluded' diff --git a/tests/dashboard_quick_controls.js b/tests/dashboard_quick_controls.js new file mode 100644 index 00000000..b4a45354 --- /dev/null +++ b/tests/dashboard_quick_controls.js @@ -0,0 +1,63 @@ +'use strict'; +const assert = require('assert'), fs = require('fs'), path = require('path'); +const source = fs.readFileSync(path.join(__dirname, '../openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js'), 'utf8'); +const tick = async () => { for (let i=0; i<20; i++) await Promise.resolve(); }; +function fixture(on) { + const buttons = {}, requests = [], dialogs = []; + let decide, complete; + const root = {isConnected:true, querySelector(id) { + return buttons[id] || (buttons[id] = {disabled:false, addEventListener(){}}); + }}; + const M = { + confirmBox(title,body,options) { dialogs.push({title,body,options}); return new Promise(resolve => { decide=resolve; }); }, + callAct(op,arg) { requests.push([op,arg]); return new Promise(resolve => { complete=resolve; }); }, + busy(btn,on) { btn.busy=on; }, toast(){} + }; + const view = new Function('view','uci','R','M','L',source)( + {extend:o=>o},{},{},M,{resolveDefault:p=>p.catch(()=>undefined)}); + view.refreshLock = () => {}; + view.wire(root); + view.lastInfo = {wan:{up:on},wifi:{available:1,up:on,pending:false}}; + view.lastCell = {cfun:on?1:0}; + return {view,root,buttons,requests,dialogs,decide:v=>decide(v),complete:()=>complete({ok:1})}; +} +(async()=>{ + const cases = [ + ['data',true,'data','down'], ['data',false,'data','up'], + ['radio',true,'radio','off'], ['radio',false,'radio','on'], + ['wifi',true,'wifi','off'], ['wifi',false,'wifi','on'], + ['modem',true,'modem-reset',null], ['reboot',true,'reboot',null], ['android',true,'os','android'] + ]; + for (const [id,on,op,arg] of cases) { + for (const decision of ['cancel','confirm','unload','detach']) { + const f=fixture(on), button=f.buttons['#mud-btn-'+id]; + button.onclick(); + assert.equal(f.dialogs.length,1,id); + assert.equal(f.requests.length,0,id+' executed before confirmation'); + button.onclick(); f.buttons['#mud-btn-reboot'].onclick(); + assert.equal(f.dialogs.length,1,'duplicate confirmation'); + if (decision==='unload') f.view.unload(); + if (decision==='detach') f.root.isConnected=false; + // Even if polling changes state, send only the explicit confirmed target. + f.view.lastInfo.wan.up=!on; f.view.lastCell.cfun=on?0:1; + f.view.lastInfo.wifi.up=!on; + f.decide(decision!=='cancel'); await tick(); + if (decision==='confirm') { + assert.deepEqual(f.requests,[[op,arg]],id); + button.onclick(); assert.equal(f.requests.length,1,'duplicate in-flight request'); + assert(button.busy); + f.complete(); await tick(); + assert(!button.busy && !button.disabled,id+' left busy'); + } else assert.equal(f.requests.length,0,id+' must not execute after '+decision); + assert(!f.view._quickPending,id+' left confirmation locked'); + } + } + for(const state of ['pending','unavailable','busy']) { + const f=fixture(true); + if(state==='pending')f.view.lastInfo.wifi.pending=true; + if(state==='unavailable')f.view.lastInfo.wifi.available=0; + if(state==='busy')f.view._wifiBusy=true; + f.buttons['#mud-btn-wifi'].onclick(); assert.equal(f.dialogs.length,0,state); + } + console.log('PASS: all six quick controls confirmed; on/off, cancellation, leaving view, duplicate clicks, busy cleanup and fixed targets'); +})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/tests/dashboard_sim.js b/tests/dashboard_sim.js index b402e6ac..78439ad0 100644 --- a/tests/dashboard_sim.js +++ b/tests/dashboard_sim.js @@ -28,6 +28,12 @@ const tick=async()=>{for(let i=0;i<30;i++)await Promise.resolve();}; const view=new Function('view','rpc','poll','M','document',fs.readFileSync(dir+'/view/mu300/sim.js','utf8'))( {extend:o=>o},rpc,{add(){},remove(){}},M,{createElement:element}); const root=view.render([{slots:2},{ok:1,ready:true,saved_sim:0,actual_sim:0}]); + const section=find(root,'section'), row=find(section,'select'); + assert(root.className.includes('mud-sim-page')); + assert(find(section,'h3'), 'heading belongs inside the card'); + assert.equal(find(section,'label').htmlFor,row.id); + assert.equal(find(section,'button').type,'button'); + assert(find(root,'style').textContent.includes('@media(max-width:480px)')); find(root,'select').value='1';find(root,'button').onclick();await tick(); assert.equal(common.selectedSlot(),outcome==='done'?'1':'0',outcome); assert.equal(requests,outcome==='cancel'?0:1); diff --git a/tests/kernel_capabilities_probe.c b/tests/kernel_capabilities_probe.c new file mode 100644 index 00000000..7e4c920a --- /dev/null +++ b/tests/kernel_capabilities_probe.c @@ -0,0 +1,114 @@ +/* On-device smoke test; no daemon, interface attachment, guest boot or mounts. + * Build: aarch64-linux-gnu-gcc -static -O2 -Wall -Wextra -o probe this-file.c + * Run as root, preferably under timeout. All resources close on process exit. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void fail(const char *what) { perror(what); exit(1); } +static int bpf_call(enum bpf_cmd cmd, union bpf_attr *attr) +{ + return syscall(__NR_bpf, cmd, attr, sizeof(*attr)); +} + +static void check_bpf(void) +{ + struct bpf_insn code[] = { + { .code = BPF_ALU64 | BPF_MOV | BPF_K, .dst_reg = BPF_REG_0, .imm = 64 }, + { .code = BPF_JMP | BPF_EXIT }, + }; + char log[8192] = {0}; + union bpf_attr attr = {0}; + attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER; + attr.insn_cnt = sizeof(code) / sizeof(code[0]); + attr.insns = (uintptr_t)code; + attr.license = (uintptr_t)"GPL"; + attr.log_buf = (uintptr_t)log; + attr.log_size = sizeof(log); + attr.log_level = 1; + int fd = bpf_call(BPF_PROG_LOAD, &attr); + if (fd < 0) { fprintf(stderr, "%s", log); fail("BPF_PROG_LOAD"); } + struct bpf_prog_info info = {0}; + memset(&attr, 0, sizeof(attr)); + attr.info.bpf_fd = fd; + attr.info.info_len = sizeof(info); + attr.info.info = (uintptr_t)&info; + if (bpf_call(BPF_OBJ_GET_INFO_BY_FD, &attr) < 0) fail("BPF prog info"); + if (!info.jited_prog_len) { fprintf(stderr, "BPF program was not JIT compiled\n"); exit(1); } + unsigned char packet[64] = {0}; + packet[12] = 8; packet[14] = 0x45; packet[17] = 50; + memset(&attr, 0, sizeof(attr)); + attr.test.prog_fd = fd; + attr.test.data_in = (uintptr_t)packet; + attr.test.data_size_in = sizeof(packet); + attr.test.repeat = 1; + if (bpf_call(BPF_PROG_TEST_RUN, &attr) < 0) fail("BPF_PROG_TEST_RUN"); + if (attr.test.retval != 64) { fprintf(stderr, "BPF wrong return value\n"); exit(1); } + printf("PASS eBPF load/JIT/test-run: JIT bytes=%u return=%u\n", info.jited_prog_len, attr.test.retval); + close(fd); +} + +static void check_kvm(void) +{ + int fd = open("/dev/kvm", O_RDWR | O_CLOEXEC); + if (fd < 0) fail("open /dev/kvm"); + int api = ioctl(fd, KVM_GET_API_VERSION, 0); + if (api != KVM_API_VERSION) { fprintf(stderr, "Unexpected KVM API %d\n", api); exit(1); } + int vm = ioctl(fd, KVM_CREATE_VM, 0); + if (vm < 0) fail("KVM_CREATE_VM"); + struct kvm_vcpu_init init = {0}; + if (ioctl(vm, KVM_ARM_PREFERRED_TARGET, &init) < 0) fail("KVM_ARM_PREFERRED_TARGET"); + int cpu = ioctl(vm, KVM_CREATE_VCPU, 0); + if (cpu < 0) fail("KVM_CREATE_VCPU"); + if (ioctl(cpu, KVM_ARM_VCPU_INIT, &init) < 0) fail("KVM_ARM_VCPU_INIT"); + printf("PASS KVM API=%d VM/vCPU creation and ARM init (no guest boot)\n", api); + close(cpu); close(vm); close(fd); +} + +static void check_perf(void) +{ + struct perf_event_attr attr = {0}; + attr.size = sizeof(attr); + attr.type = PERF_TYPE_SOFTWARE; + attr.config = PERF_COUNT_SW_CPU_CLOCK; + attr.disabled = 1; + int fd = syscall(__NR_perf_event_open, &attr, 0, -1, -1, 0); + if (fd < 0) fail("perf_event_open"); + close(fd); + puts("PASS perf_event_open (disabled event closed)"); +} + +static void check_namespaces(void) +{ + fflush(stdout); + pid_t pid = fork(); + if (pid < 0) fail("fork"); + if (pid == 0) { + if (unshare(CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWCGROUP) < 0) + fail("isolated namespaces"); + _exit(0); + } + int status; + if (waitpid(pid, &status, 0) < 0) fail("waitpid"); + if (!WIFEXITED(status) || WEXITSTATUS(status)) exit(1); + puts("PASS isolated net/mount/UTS/IPC/cgroup namespaces"); +} + +int main(void) +{ + check_bpf(); check_kvm(); check_perf(); check_namespaces(); + return 0; +} diff --git a/tests/test_container_support.py b/tests/test_container_support.py index 3b1cedfa..54d57315 100644 --- a/tests/test_container_support.py +++ b/tests/test_container_support.py @@ -52,6 +52,40 @@ class ContainerSupport(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'KVM'): support.check(self.out) + def test_incomplete_ebpf_or_tracing_cannot_ship(self): + for feature in ('BPF_JIT', 'DEBUG_INFO_BTF', 'DEBUG_INFO_BTF_MODULES', + 'PERF_EVENTS', 'KPROBE_EVENTS', 'FUNCTION_GRAPH_TRACER', + 'BPF_UNPRIV_DEFAULT_OFF'): + with self.subTest(feature=feature): + self.config[feature] = 'n' + self.write_config() + self.manifests() + with self.assertRaisesRegex(ValueError, feature): + support.check(self.out) + self.config[feature] = 'y' + + def test_bpf_network_module_cannot_be_omitted(self): + (self.out / 'modules/act_bpf.ko').unlink() + self.manifests() + with self.assertRaisesRegex(ValueError, 'act_bpf'): + support.check(self.out) + + def test_btf_build_dependencies_and_no_early_debug_modules(self): + self.assertIn('pahole', (TOP/'upstream/Dockerfile').read_text()) + self.assertIn('--strip-debug', (TOP/'upstream/build-modules.sh').read_text()) + self.assertIn('BTF missing from built module', (TOP/'upstream/build-modules.sh').read_text()) + self.assertIn('BTF missing from the linked kernel', (TOP/'upstream/build.sh').read_text()) + for script in ('build.sh', 'build-modules.sh'): + btf_checks = [line for line in (TOP/'upstream'/script).read_text().splitlines() + if 'readelf' in line and '|' in line] + self.assertTrue(btf_checks) + for line in btf_checks: + self.assertNotIn('grep -Eq', line) # SIGPIPE under pipefail + self.assertIn('>/dev/null', line) + early = (TOP/'upstream/module-order.txt').read_text() + for name in ('act_bpf', 'sch_netem', 'ifb', 'ipvtap', 'geneve'): + self.assertNotIn(name, early) + def test_old_builtin_cpufreq_cannot_silently_omit_voltage(self): self.config['ARM_SPRD_CPUFREQ_V2'] = 'y' self.write_config() diff --git a/tests/test_cpu_thermal.py b/tests/test_cpu_thermal.py new file mode 100644 index 00000000..253e4789 --- /dev/null +++ b/tests/test_cpu_thermal.py @@ -0,0 +1,43 @@ +"""Thermal capability, safety boundaries and installation coverage.""" +import shutil +import subprocess +import unittest +from helpers import TOP + +APP = TOP / 'openwrt/luci-app-mu300' + +class CpuThermal(unittest.TestCase): + def test_module_uses_factory_sensor_trips_and_no_new_worker(self): + source = (TOP/'upstream/modules/mu300_thermal/mu300_thermal.c').read_text() + for token in ('thmzone-cells', 'thermal_zone_get_zone_by_name', 'devm_thermal_of_zone_register', '-EPROBE_DEFER', 'hottest = max'): + self.assertIn(token, source) + for token in ('kthread_run', 'schedule_delayed_work', '.set_trips', '110000', '85000'): + self.assertNotIn(token, source) + self.assertIn('mu300_thermal', (TOP/'upstream/build-modules.sh').read_text()) + self.assertNotIn('mu300_thermal', (TOP/'upstream/module-order.txt').read_text()) + self.assertIn('mu300_thermal.ko', (TOP/'rootfs/overlay/opt/mu300/bin/extra-modules').read_text()) + + def test_installer_requires_backend_and_fresh_module(self): + for name in ('tools/build-openwrt-tf-magisk.sh','tools/make-release.sh'): + self.assertIn('./usr/libexec/unisoc-modem/cpu-thermal.uc', (TOP/name).read_text()) + for name in ('upstream/make-bundle.sh','tools/build-openwrt-tf-magisk.sh'): + self.assertIn('sprd_wlan_combo wcn_bsp mu300_thermal', (TOP/name).read_text()) + + def test_generic_ui_and_readonly_critical(self): + source = (APP/'root/usr/libexec/unisoc-modem/cpu-thermal.uc').read_text() + self.assertIn("writable:kind=='passive'", source) + self.assertIn('t.temp-10000', source) + self.assertNotIn('thermal_zone19', source) + self.assertNotIn('AT+', source) + view = (APP/'htdocs/luci-static/resources/view/mu300/cpu.js').read_text() + for token in ("controlsFor('frequency'", "controlsFor('thermal'", 'payload.thermal', 'throttles_cpu','hysteresis','reset: true','checkValidity','self.thermalLive'): + self.assertIn(token, view) + self.assertIn('root.append(section, thermalSection)', view) + self.assertIn('thermal_persist', view) + translations = (APP/'htdocs/luci-static/resources/mu300/common.js').read_text() + for label in ('温控管理','降频触发温度','被动温控起点','临界保护温度','恢复启动基线?','温控配置回读不一致'): + self.assertIn(label, translations) + + @unittest.skipUnless(shutil.which('ucode') and shutil.which('jsonfilter'), 'run cpu_thermal_fixture.sh in OpenWrt container') + def test_fake_sysfs(self): + subprocess.run(['sh',str(TOP/'tests/cpu_thermal_fixture.sh'),str(APP/'root/usr/libexec/unisoc-modem/cpu.uc')],check=True,timeout=30) diff --git a/tests/test_dashboard_backport.py b/tests/test_dashboard_backport.py index ad411d9d..0ceb259e 100644 --- a/tests/test_dashboard_backport.py +++ b/tests/test_dashboard_backport.py @@ -12,6 +12,12 @@ JS = PKG / 'htdocs/luci-static/resources' class Refresh(unittest.TestCase): + @unittest.skipUnless(shutil.which('node'), 'Node required') + def test_all_quick_controls_require_confirmation(self): + result = subprocess.run(['node', str(TOP / 'tests/dashboard_quick_controls.js')], + capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + @unittest.skipUnless(shutil.which('node'), 'Node required') def test_scheduler_and_counter_resets(self): result = subprocess.run(['node', str(TOP / 'tests/dashboard_refresh.js'), diff --git a/tests/test_dashboard_info.py b/tests/test_dashboard_info.py index f4fecb10..dc3570bd 100644 --- a/tests/test_dashboard_info.py +++ b/tests/test_dashboard_info.py @@ -1,6 +1,8 @@ """Hot-path shell helpers must preserve the dashboard's JSON wire values.""" import json import shlex +import shutil +import unittest from helpers import ShellTest, TOP @@ -9,6 +11,21 @@ INFO = TOP / 'openwrt' / 'luci-app-mu300' / 'root' / 'usr' / 'libexec' / 'unisoc class DashboardInfo(ShellTest): + def test_dns_reuses_both_status_snapshots(self): + script = INFO.read_text() + self.assertIn('wan_dns=$(wan_dns_servers "$WANJSON" "$WAN6JSON")', script) + helper = script[script.index('wan_dns_servers() {'):script.index('\nwan_up=')] + self.assertIn('jsonfilter -s "$snapshot"', helper) + self.assertNotIn('ubus call', helper) + self.assertNotIn('jarr_dns', script) + + @unittest.skipUnless(shutil.which('jsonfilter'), 'also run fixture in OpenWrt container/device') + def test_dns_with_real_jsonfilter(self): + for shell in self.each_shell(): + result = self.script(shell, TOP/'tests/dashboard_dns_fixture.sh', INFO) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('PASS dashboard DNS', result.stdout) + def station_code(self): script = INFO.read_text() helpers = script[script.index('n_or_null() {'):script.index('# ------------------------------------------------------------- temperature')] diff --git a/tests/test_device_scripts.py b/tests/test_device_scripts.py index 495f4c12..30e1f13b 100644 --- a/tests/test_device_scripts.py +++ b/tests/test_device_scripts.py @@ -389,6 +389,34 @@ class ThermalGuard(ShellTest): self.device('u30air') self.assertEqual(self.round(shell, 110000), ['poweroff', 'mu300-led alarm on']) # mainline: critical + def test_mainline_native_cooling_keeps_emergency_and_user_caps(self): + for shell in self.each_shell(): + shutil.rmtree(self.root, ignore_errors=True) + self.device('f50') + (self.root / 'sys/module/mu300_thermal').mkdir(parents=True) + z = self.root / 'sys/class/thermal/thermal_zone0' + z.mkdir(parents=True) + (z / 'type').write_text('soc-thmzone\n') + (z / 'mode').write_text('enabled\n') + c = z.parent / 'cooling_device0' + c.mkdir() + (c / 'type').write_text('cpufreq-cpu0\n') + (z / 'cdev0').symlink_to(c) + p = self.root / 'sys/devices/system/cpu/cpufreq/policy0' + p.mkdir(parents=True) + (p / 'scaling_available_frequencies').write_text('400000 800000 1200000\n') + (p / 'scaling_max_freq').write_text('800000\n') + (p / 'cpuinfo_max_freq').write_text('1200000\n') + self.round(shell, 40000, trips=True) + self.assertEqual((p / 'scaling_max_freq').read_text().strip(), '800000') + self.round(shell, 86000, trips=True) + self.assertEqual((p / 'scaling_max_freq').read_text().strip(), '800000') + self.assertIn('poweroff', self.round(shell, 106000, trips=True)) + # A disabled zone or missing CPU binding must restore fallback. + (z / 'cdev0').unlink() + self.round(shell, 86000, trips=True) + self.assertEqual((p / 'scaling_max_freq').read_text().strip(), '400000') + class Nfc(ShellTest): """mu300-nfc against a fake FM11NT08: 1 KiB behind a stub i2ctransfer, which answers only while a stub gpioset diff --git a/tests/test_optional_controls.py b/tests/test_optional_controls.py index 41e44be8..2e9ae1df 100644 --- a/tests/test_optional_controls.py +++ b/tests/test_optional_controls.py @@ -44,7 +44,7 @@ record_delivery test def test_cpu_validation_and_no_platform_voltage_writes(self): source=(LIB/'cpu.uc').read_text() self.assertNotIn('voltage_offset',source) - self.assertNotIn('thermal_zone',source) + self.assertIn("import * as thermal from './cpu-thermal.uc'",source) self.assertIn('c.cpus!=p.cpus',source) self.assertIn('reverse(changed)',source) self.assertIn('index(p.frequencies,c.min)<0',source) diff --git a/tests/test_wifi_tx_logging.py b/tests/test_wifi_tx_logging.py index bbf82266..0444ced4 100644 --- a/tests/test_wifi_tx_logging.py +++ b/tests/test_wifi_tx_logging.py @@ -128,5 +128,5 @@ int main(void) { 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('for wireless_driver in sprd_wlan_combo wcn_bsp mu300_thermal; do', packaging) self.assertIn('-newer "$wireless_module"', packaging) diff --git a/tools/build-openwrt-tf-magisk.sh b/tools/build-openwrt-tf-magisk.sh index 152cdcae..b729fe7e 100755 --- a/tools/build-openwrt-tf-magisk.sh +++ b/tools/build-openwrt-tf-magisk.sh @@ -51,8 +51,9 @@ done # The TF path packages modules directly rather than going through make-bundle.sh. # 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 +for wireless_driver in sprd_wlan_combo wcn_bsp mu300_thermal; do wireless_module=$UO/modules/$wireless_driver.ko + [ -s "$wireless_module" ] || { echo "missing $wireless_module" >&2; exit 1; } 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 @@ -79,6 +80,7 @@ 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-thermal.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 \ diff --git a/tools/make-release.sh b/tools/make-release.sh index 5851187a..af4dc351 100755 --- a/tools/make-release.sh +++ b/tools/make-release.sh @@ -92,6 +92,7 @@ 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-thermal.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 \ diff --git a/upstream/Dockerfile b/upstream/Dockerfile index b27fe783..e08a3eb7 100644 --- a/upstream/Dockerfile +++ b/upstream/Dockerfile @@ -2,5 +2,5 @@ FROM ubuntu:26.04 ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential gcc-aarch64-linux-gnu bc bison flex libssl-dev libelf-dev lz4 cpio kmod python3 curl device-tree-compiler xz-utils ca-certificates \ + build-essential gcc-aarch64-linux-gnu bc bison flex libssl-dev libelf-dev lz4 cpio kmod python3 curl device-tree-compiler xz-utils ca-certificates pahole \ && rm -rf /var/lib/apt/lists/* diff --git a/upstream/build-modules.sh b/upstream/build-modules.sh index 96927cd4..8c29a5b8 100644 --- a/upstream/build-modules.sh +++ b/upstream/build-modules.sh @@ -8,7 +8,7 @@ K=/src/linux-$KV O=/src/out-$KV OUT=/work/${OUTDIR:-out} # as in build.sh # every out-of-tree module, in dependency order (wlan/bt use wcn_bsp, the PMIC watchdog and Mali the modem's headers) -mods=${*:-wcn_bsp sprd_wlan_combo sprdbt_tty sprd_modem sprd_pmic_wdt mali} +mods=${*:-wcn_bsp sprd_wlan_combo sprdbt_tty sprd_modem sprd_pmic_wdt mali mu300_thermal} mkdir -p $OUT/modules # a full build starts clean, so no module of another kernel release ends up next to the new ones [ $# -gt 0 ] || rm -f $OUT/modules/*.ko $OUT/modules/*.log @@ -55,9 +55,22 @@ for m in $mods; do name=$(basename "$ko" | tr - _) ! grep -Fqx "$name" "$O/modules.in-tree.names" || { echo "vendor/in-tree module collision: $name" >&2; exit 1; } cp "$ko" "$OUT/modules/" + # Keep compact .BTF/.BTF.ext but do not ship multi-megabyte DWARF + # from vendor modules now that DEBUG_INFO_BTF_MODULES is enabled. + "${CROSS_COMPILE:-}strip" --strip-debug "$OUT/modules/$(basename "$ko")" done < <(find /src/mod-build/$m -name '*.ko') done # Evidence covers every module (including vendor dependencies), not just a shortlist. +if grep -qx 'CONFIG_DEBUG_INFO_BTF_MODULES=y' "$OUT/kernel.config"; then + # A missing vmlinux can silently skip external-module BTF generation. + # Verify the actual stripped payload rather than trusting Kconfig alone. + for ko in "$OUT"/modules/*.ko; do + # Consume all output: grep -q can SIGPIPE readelf under pipefail. + "${CROSS_COMPILE:-}readelf" -SW "$ko" | grep -E '\.BTF[[:space:]]+PROGBITS' >/dev/null || { + echo "BTF missing from built module: $ko" >&2; exit 1; + } + done +fi (cd "$OUT" && sha256sum Image kernel.config modules/*.ko > modules.sha256) python3 /work/check-container-support.py "$OUT" ls -la $OUT/modules/*.ko diff --git a/upstream/build.sh b/upstream/build.sh index cc1582de..c0f25499 100644 --- a/upstream/build.sh +++ b/upstream/build.sh @@ -46,6 +46,12 @@ make O=$O ARCH=arm64 -j"$(nproc)" Image > $O/build.log 2>&1 || { echo "--- end of build.log:"; tail -25 $O/build.log || true exit 1 } +if grep -qx 'CONFIG_DEBUG_INFO_BTF=y' "$O/.config"; then + # Consume all output: grep -q can SIGPIPE readelf under pipefail. + "${CROSS_COMPILE:-}readelf" -SW "$O/vmlinux" | grep -E '\.BTF[[:space:]]+PROGBITS' >/dev/null || { + echo 'BTF missing from the linked kernel' >&2; exit 1; + } +fi cpp -nostdinc -undef -D__DTS__ -x assembler-with-cpp -I include -I scripts/dtc/include-prefixes \ /work/dts/ums9620-mu300.dts | dtc -I dts -O dtb -o $O/ums9620-mu300.dtb - mkdir -p $OUT diff --git a/upstream/check-container-support.py b/upstream/check-container-support.py index 0c52f042..8b1750b1 100644 --- a/upstream/check-container-support.py +++ b/upstream/check-container-support.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Refuse old Images or incomplete module sets in either TF or kernel bundles.""" +"""Verify KVM/container/eBPF capabilities and complete TF/kernel module sets.""" import argparse import hashlib import re @@ -11,7 +11,11 @@ BUILTIN = '''VIRTUALIZATION KVM IKCONFIG IKCONFIG_PROC CGROUPS MEMCG BLK_CGROUP CGROUP_SCHED CGROUP_PIDS CPUSETS CGROUP_BPF CFS_BANDWIDTH BLK_DEV_THROTTLING NAMESPACES UTS_NS IPC_NS USER_NS PID_NS NET_NS SECCOMP SECCOMP_FILTER POSIX_MQUEUE VETH BRIDGE TUN OVERLAY_FS NF_CONNTRACK NF_NAT NF_TABLES NFT_COMPAT -NETFILTER_XT_MATCH_CONNTRACK NETFILTER_XT_TARGET_MASQUERADE'''.split() +NETFILTER_XT_MATCH_CONNTRACK NETFILTER_XT_TARGET_MASQUERADE +BPF BPF_SYSCALL BPF_JIT BPF_EVENTS BPF_STREAM_PARSER BPF_UNPRIV_DEFAULT_OFF +DEBUG_INFO_BTF DEBUG_INFO_BTF_MODULES KALLSYMS_ALL FTRACE FUNCTION_TRACER +FUNCTION_GRAPH_TRACER DYNAMIC_FTRACE FTRACE_SYSCALLS KPROBES KPROBE_EVENTS +UPROBES UPROBE_EVENTS PERF_EVENTS ARM_PMU'''.split() MODULES = { 'VHOST_NET': 'vhost_net', 'VSOCKETS': 'vsock', 'VHOST_VSOCK': 'vhost_vsock', 'BRIDGE_NETFILTER': 'br_netfilter', 'NETFILTER_XT_MATCH_ADDRTYPE': 'xt_addrtype', @@ -20,6 +24,17 @@ MODULES = { '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', + 'NETFILTER_XT_NAT': 'xt_nat', + 'NET_SCH_FQ': 'sch_fq', 'NET_SCH_HTB': 'sch_htb', + 'NET_SCH_TBF': 'sch_tbf', 'NET_SCH_PRIO': 'sch_prio', + 'NET_SCH_NETEM': 'sch_netem', 'NET_CLS_U32': 'cls_u32', + 'NET_CLS_FLOWER': 'cls_flower', 'NET_CLS_MATCHALL': 'cls_matchall', + 'NET_ACT_BPF': 'act_bpf', 'NET_ACT_MIRRED': 'act_mirred', + 'NET_ACT_POLICE': 'act_police', 'NET_ACT_GACT': 'act_gact', + 'NET_ACT_SKBEDIT': 'act_skbedit', 'NET_ACT_CT': 'act_ct', + 'IFB': 'ifb', 'NETLINK_DIAG': 'netlink_diag', + 'UNIX_DIAG': 'unix_diag', 'PACKET_DIAG': 'af_packet_diag', + 'IPVTAP': 'ipvtap', 'GENEVE': 'geneve', } @@ -118,5 +133,5 @@ if __name__ == '__main__': if args.rootfs: check_rootfs(args.output, args.rootfs, release) except (OSError, ValueError) as error: - parser.exit(1, f'KVM/container build check: {error}\n') - print('KVM/container build checks passed (runtime verification still required)') + parser.exit(1, f'KVM/container/eBPF build check: {error}\n') + print('KVM/container/eBPF build checks passed (runtime verification still required)') diff --git a/upstream/make-bundle.sh b/upstream/make-bundle.sh index b7724895..260da905 100755 --- a/upstream/make-bundle.sh +++ b/upstream/make-bundle.sh @@ -30,7 +30,7 @@ done # 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. -for wireless_driver in sprd_wlan_combo wcn_bsp; do +for wireless_driver in sprd_wlan_combo wcn_bsp mu300_thermal; 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 diff --git a/upstream/modules/mu300_thermal/Makefile b/upstream/modules/mu300_thermal/Makefile new file mode 100644 index 00000000..c34a97b2 --- /dev/null +++ b/upstream/modules/mu300_thermal/Makefile @@ -0,0 +1 @@ +obj-m += mu300_thermal.o diff --git a/upstream/modules/mu300_thermal/mu300_thermal.c b/upstream/modules/mu300_thermal/mu300_thermal.c new file mode 100644 index 00000000..d998dd7c --- /dev/null +++ b/upstream/modules/mu300_thermal/mu300_thermal.c @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Restore the stock virtual-thermal zone using its DT sensor list/trips/maps. + * Physical sensors are built into both supported MU300 mainline kernels. + * No invented temperatures, DT rewrites, or additional polling worker. + */ +#include +#include +#include +#include +#include + +struct mu300_virtual { + unsigned int count; + struct thermal_zone_device *sensor[]; +}; + +static int mu300_virtual_temp(struct thermal_zone_device *tz, int *temp) +{ + struct mu300_virtual *v = thermal_zone_device_priv(tz); + int hottest = INT_MIN, value, ret; + unsigned int i; + + for (i = 0; i < v->count; i++) { + ret = thermal_zone_get_temp(v->sensor[i], &value); + if (ret) + return ret; /* Never turn an unreadable sensor into a cold reading. */ + hottest = max(hottest, value); + } + *temp = hottest; + return 0; +} + +static const struct thermal_zone_device_ops mu300_virtual_ops = { + .get_temp = mu300_virtual_temp, +}; + +static int mu300_virtual_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct device_node *node; + struct thermal_zone_device *tz; + struct mu300_virtual *v; + int count, i; + + if (!of_machine_is_compatible("sprd,ums9620")) + return -ENODEV; + count = of_count_phandle_with_args(dev->of_node, "thmzone-cells", NULL); + if (count <= 0 || count > 32) + return -EINVAL; + v = devm_kzalloc(dev, struct_size(v, sensor, count), GFP_KERNEL); + if (!v) + return -ENOMEM; + v->count = count; + for (i = 0; i < count; i++) { + node = of_parse_phandle(dev->of_node, "thmzone-cells", i); + if (!node) + return -EINVAL; + v->sensor[i] = thermal_zone_get_zone_by_name(node->name); + of_node_put(node); + if (IS_ERR(v->sensor[i])) + return dev_err_probe(dev, -EPROBE_DEFER, "physical thermal zone not ready\n"); + } + tz = devm_thermal_of_zone_register(dev, 0, v, &mu300_virtual_ops); + if (IS_ERR(tz)) + return dev_err_probe(dev, PTR_ERR(tz), "virtual thermal registration failed\n"); + dev_info(dev, "stock virtual thermal zone active (%d sensors)\n", count); + return 0; +} + +static const struct of_device_id mu300_virtual_match[] = { + { .compatible = "virtual-thermal" }, + { } +}; +MODULE_DEVICE_TABLE(of, mu300_virtual_match); + +static struct platform_driver mu300_virtual_driver = { + .probe = mu300_virtual_probe, + .driver = { + .name = "mu300-virtual-thermal", + .of_match_table = mu300_virtual_match, + .suppress_bind_attrs = true, + }, +}; +module_platform_driver(mu300_virtual_driver); +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("MU300 stock virtual thermal sensor for mainline kernels"); diff --git a/upstream/mu300-mainline.config b/upstream/mu300-mainline.config index 3e9e61fb..526b94c5 100644 --- a/upstream/mu300-mainline.config +++ b/upstream/mu300-mainline.config @@ -428,3 +428,49 @@ CONFIG_MACVTAP=m CONFIG_IPVLAN=m CONFIG_VXLAN=m CONFIG_FUSE_FS=m + +# E5-aligned eBPF and observability capabilities. No tracing session or BPF +# program is started automatically; unprivileged BPF remains disabled. +CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y +CONFIG_DEBUG_INFO_BTF=y +CONFIG_DEBUG_INFO_BTF_MODULES=y +CONFIG_KALLSYMS_ALL=y +CONFIG_FTRACE=y +CONFIG_FUNCTION_TRACER=y +CONFIG_FUNCTION_GRAPH_TRACER=y +CONFIG_DYNAMIC_FTRACE=y +CONFIG_FTRACE_SYSCALLS=y +CONFIG_KPROBES=y +CONFIG_KPROBE_EVENTS=y +CONFIG_UPROBES=y +CONFIG_UPROBE_EVENTS=y +CONFIG_PERF_EVENTS=y +CONFIG_ARM_PMU=y +CONFIG_BPF=y +CONFIG_BPF_JIT=y +CONFIG_BPF_EVENTS=y +CONFIG_BPF_STREAM_PARSER=y +CONFIG_BPF_UNPRIV_DEFAULT_OFF=y + +# Optional container/TC networking, loaded on demand, never in the initramfs. +CONFIG_NETFILTER_XT_NAT=m +CONFIG_NET_SCH_FQ=m +CONFIG_NET_SCH_HTB=m +CONFIG_NET_SCH_TBF=m +CONFIG_NET_SCH_PRIO=m +CONFIG_NET_SCH_NETEM=m +CONFIG_NET_CLS_U32=m +CONFIG_NET_CLS_FLOWER=m +CONFIG_NET_CLS_MATCHALL=m +CONFIG_NET_ACT_BPF=m +CONFIG_NET_ACT_MIRRED=m +CONFIG_NET_ACT_POLICE=m +CONFIG_NET_ACT_GACT=m +CONFIG_NET_ACT_SKBEDIT=m +CONFIG_NET_ACT_CT=m +CONFIG_IFB=m +CONFIG_NETLINK_DIAG=m +CONFIG_UNIX_DIAG=m +CONFIG_PACKET_DIAG=m +CONFIG_IPVTAP=m +CONFIG_GENEVE=m