fix: restore U30 Air battery events and low-power shutdown

This commit is contained in:
kanoqwq committed 2026-10-18 18:18:31 +08:00
1 parent 8c51448728
commit 99e1316a7c
17 files changed
+736 -1

No files matched your search

+139
View File
@@ -0,0 +1,139 @@
# 原厂低电量关机:E5、T551M、VIPME M8、U30 Air
2026-10-18。第 1~5 节记录最初的只读原厂分析;随后实现见第 6 节。未给实机放电做关机实测。
## 结论与证据范围
正常低电量关机由原厂电量/充电驱动、Health HAL、Android `BatteryService` 和系统关机流程共同完成。不能只保留电量显示、等待电池硬件掉电,也不能任意增加一个 5% 或 1% 阈值替代原厂判断。
- E5、M8:已经直接反汇编各自原厂 `services.jar`,确认 `shouldShutdownLocked()` 和 `shutdownIfNoPowerLocked()` 的有效指令逻辑一致。
- 四款机型:均反汇编本机原厂 `sprd-charger-manager.ko`;确认欠压判断、默认关机模式及 Android 模式的通知行为。
- T551M、U30 Air:这轮没有取得对应的 `services.jar`,不把 E5/M8 的上层判断称为这两款机型已经逐指令验证的结果。
- 原厂电压、关机模式来自本机二进制与原厂 DT;相近 vendor 源码仅用于辅助命名和结构解释。
## 1. Android 的正常低电量关机判断
以下来自 E5/M8 本机 `services.jar`,不是直接套用 AOSP 默认值。
`BatteryService.shouldShutdownLocked()` 可概括为:
```text
如果 Health HAL 支持 batteryCapacityLevel:
仅当它为 CRITICAL 时请求关机
否则:
batteryLevel <= 0
且 batteryPresent 为 true
且 batteryStatus 不是 CHARGING
```
要特别注意:上层支持 `capacity_level` 时,不会再额外用“插着 USB 就不关机”或“百分比必须等于 0”覆盖它。原厂驱动负责在计算 CRITICAL 时考虑有效充电、电流、电压等条件。
条件成立后,`shutdownIfNoPowerLocked()` 向 Handler 投递任务;任务检查 Android 系统已 ready,发送 `com.android.internal.intent.action.REQUEST_SHUTDOWN`:
- `android.intent.extra.KEY_CONFIRM=false`,不要求用户确认;
- `android.intent.extra.REASON="battery"`;
- 经正常系统关机流程,而不是在界面程序里直接强制断电。
E5 原厂 `ShutdownThread.run()` 可见关机广播、ActivityManager/PackageManager 关闭、关闭无线,最后进入 `rebootOrShutdown()` 和 `PowerManagerService.lowLevelShutdown()`。这轮未进一步逐指令分析 Android init 的全部文件系统卸载实现,不能把它与 OpenWrt 的 procd 当作同一实现。
`processValuesLocked()` 已调用上述判断;不是依靠短信、网页或用户操作才触发。具体 HAL 更新频率不据 AOSP 默认定时器作推断。
## 2. 内核的持续欠压路径
四款机型的原厂 DT 都给出 `cm-shutdown-voltage=3100000`,即 3.10 V。它是欠压路径的一个阈值,不代表系统只有低于 3.10 V 才可能因正常电量耗尽关机。
从各自原厂 `.ko` 的 `cm_uvlo_check_work` 可确认:
1. 成功读取实际电池端电压;读取错误不按一个有效的 0 V 样本参与比较。
2. 电压不超过 `shutdown_voltage + 120000 µV` 时累计,否则清零。
3. 累计至少 5 次后,如果内部显示 SOC 四舍五入后的百分比不大于 1,进入关机处理;否则还要端电压不超过 `shutdown_voltage` 才进入关机处理,并走原有写入 0 电量的分支。
4. 低压期间以 200 jiffies 排队复查。四份原厂配置都为 `CONFIG_HZ=250`,对应约 800 ms,实际调度可能更晚。不能笼统写成“电量低于 1% 持续 4 秒就关机”,因为它还有电压条件和首次任务调度。
原厂欠压任务继续复查的电压门槛存在机型差异:
| 机型 | 原厂复查条件 | 原厂最终欠压阈值 | 连续计数 |
| --- | --- | --- | --- |
| E5 | 端电压小于 3.20 V | 3.10 V | 至少 5 次 |
| T551M | 端电压小于 3.40 V | 3.10 V | 至少 5 次 |
| VIPME M8 | 端电压小于 3.40 V | 3.10 V | 至少 5 次 |
| U30 Air | 端电压小于 3.40 V | 3.10 V | 至少 5 次 |
门槛来自函数末尾的复查分支。首次进入欠压任务的全部调用点和各机型温度特例尚未逐一完成二进制核对,不把此表当作完整电池保护策略。
四份原厂 `charger_manager_probe` 都先将 `cm-uvlo-shutdown-mode` 默认初始化为 **2(Android)**,再尝试读取 DT 覆盖;已有四份原厂 DT 未设置该属性。E5/T551M/U30 Air 可见独立 `cm_shutdown_handle`,M8 对应逻辑被编译器内联到欠压函数中。
Android 模式下会停止容量更新工作、把对外 UI 容量置为 0,并执行 `power_supply_changed()`,将关机决定交给上层。模式 0 是 `orderly_poweroff`,模式 1 是 `kernel_power_off`,不能把“二进制包含这两个符号”误当作原厂正常情况下直接采用它们。
U30 Air 的 `cm_shutdown_handle` 还有一个全局状态为 1 时直接进入 `kernel_power_off()` 的分支。这轮尚未完成该全局状态所有写入点的追踪,不能将它随意等同于 USB 在线或正常运行的默认行为。
## 3. 为什么不能仅参照相近源码
E5 原厂 `charger_get_property` 确实暴露 `CAPACITY_LEVEL`;原厂 Health 服务中也保留了读取 `capacity_level` 的路径和状态转换字符串。
核对 E5 `.ko` 内联的临界电量充电例外时,发现实际指令中的电压比较是 3.00 V / 3.40 V,而留存相近源码的宏是 3.30 V / 3.20 V。欠压复查门槛也有原厂 E5 3.20 V 与当前移植源码 3.25 V 的差异。
因此不能把源码里的宏直接标成“E5 原厂参数”。后续修改应优先利用原厂等效的 `capacity_level` 决策,在确实缺少该状态的机型中按本机驱动证据补齐;不要全机型硬塞同一电压门槛。
## 4. 初次审查时 OpenWrt 的缺口
- E5/T551M/M8 移植侧保留了充电管理和 Android 式容量通知,但没有 Android `BatteryService`,目前没有找到接管这一正常关机请求的公共服务。
- U30 Air 的 mainline FGU 有低压中断、容量校准和 `power_supply_changed()`,其驱动 `.shutdown` 回调用于“系统已经关机时保存 SOC”,并非主动发起低电量关机。当前 7.2 配置没有启用 `CONFIG_CHARGER_MANAGER`,也没有找到对应用户态低电量关机接管。
- 适配方向应是接入电源事件,按本机可用的临界状态/原厂条件,调用 OpenWrt 正常关机流程;无电池的 F50/V50 不进入这条策略。不要改 AT 顺序、NV、SOC 编码或用任意固定百分比盖过驱动状态。
- 上述为实现前的审查结论;后续实现、验证与尚未完成的实机验证见第 6 节。
## 5. 固件来源及复核标识
| 机型 | 原厂版本标识 | `sprd-charger-manager.ko` SHA-256 |
| --- | --- | --- |
| E5 | Android 13;`UNISOC/ums9158_1h10_cmcc/ums9158_1h10:13/TP1A.220624.014/2024112822:user/release-keys`;内核 `5.15.119-android13-8-gf0c1c2c751e6-dirty` | `45dd82b92ff16626ccac77fe802c06fccdd3eda68ba0175b17a41c9a0f828d07` |
| T551M | `onetouch/TYT_00CM_FIH/TYT:13/TP1A.220624.014/551MCM08:user/release-keys`;内核 `5.15.123-android13-8-g2054f18da766-ab10` | `bf2717c9ea32e8fe6b1c08e90f5c3cb74c96be9c383d77271291c27dbd157ae6` |
| VIPME M8 | Android 13;`UNISOC/ums9157_2h10_native/ums9157_2h10:13/TP1A.220624.014/wangqingpeng01181306:user/release-keys`;内核 `5.4.210` | `e74ad1138aa269fd2b8394ccdd587ebd95e82512b6ca440475707f1999298dc9` |
| U30 Air | 已留存本机 Android A 槽模块;内核 `5.4.254-android12-9-g9444efdc6885` | `b192f17e0be983b4e9a6a4310b8bb4bab12a93a334b364883dcd42d4967ce05e` |
`services.jar` SHA-256:
- E5:`865cdef80249bd3c98edb4a226f357651a0990afa3ee858aba4cf211553c9aec`
- M8:`7dce09f3a90e6487ab00a8627dfd967f65ceb79d361f8b7eba72c264f33da752`
离线反汇编和函数地址保存在 WSL `/home/kano/low-battery-stock-20261018/`,其中 `stock-module-evidence.json` 记录四款模块的来源、哈希和函数范围。E5 `cm_uvlo_check_work=0xdb7c`、`cm_shutdown_handle=0xdd28`;T551M 分别为 `0xd634`、`0xd7e4`;U30 Air 分别为 `0x5e84`、`0x6048`;M8 内联逻辑位于 `cm_uvlo_check_work=0xcdfc`。
## 6. 低电量关机实现
两仓库使用同一份 `policy.uc`、`guard.uc`、`read.uc`、`events.uc`、`watch.uc`;板级差异保留在各自 `adapter.uc`,不共存另一套旧低电量关机逻辑。
- `unisoc-battery` 由 procd 管理,启动时先订阅事件再读取一次当前电池状态。
- `/etc/hotplug.d/power_supply/80-unisoc-battery` 将内核电源事件发送给监听器,监听器重新读取 sysfs,不信任事件附带的百分比或关机指令。
- 正常电量时阻塞等待 ubus/uloop,**没有定时轮询**。充电限制关闭或暂停不影响低电量保护。
- 有效 `capacity_level=Critical` 直接请求正常关机;该属性不可用时,使用有效的 0% + 电池存在 + 状态不是 Charging。属性存在但读取失败或值无效时,不擅自当成“不支持”改走另一条百分比判定。缺失/无效数值不转换为 0。
- 调用 `/sbin/poweroff`,没有 `-f`、直接 reboot 系统调用或人为缩短 procd 停服务/卸载流程。每个已接受的请求只执行一次;进程由 procd 在正常关机中停止,不留下磁盘锁或持久化标记。
- E5/T551M/M8 由已有 charger-manager 保留临界状态的充电例外、温度和欠压判断,本次不修改其电压宏、电量计保存或 AT/NV 路径。三个板级 stager 和公共完整 rootfs 构建均启用服务,旧基础镜像重组时也会安装所需文件及启动链接。
### U30 Air 的额外适配
mainline `sc27xx_fuel_gauge` 原来的低压/库仑计中断只在 suspend 路径启用,正常 headless 运行不能据此保证有电量事件。`0022-power-UMP9620-awake-battery-events.patch` 接通已有硬件事件:
- 仅 UMP9620,且此前已有的本机电池 policy probe 门槛仍先于硬件初始化;无电池 F50/V50 不进入这个 FGU 路径。
- 两个 IRQ handler 注册成功后启用已有的低压和 **1% 库仑计变化**中断,resume 恢复该掩码;实际电池取出时屏蔽,重新插入时开启。其他 PMIC 保持原行为。
- 不增加内核周期工作,不改电量表、保存格式、校准、充电电流或 AT 时序。库仑计中断通知可使低电量保护不再依赖用户打开看板读取 SOC。
用户态为 U30 Air 补上本机持续欠压条件:最终电压来自 DT `cm-shutdown-voltage`,偏移 120 mV、至少 5 个有效低压样本、800 ms 间隔;电压样本读取失败不计为低压,电压恢复则清空计数。
mainline 首次低压硬件告警使用电池 DT 的设计最低电压,本机为 3.45 V,略高于原厂复查门槛 3.40 V。因此适配中的**监测窗口**取两者较高值,在首次硬件告警后继续观察,避免清除一次中断后漏掉后续压降。这个窗口只决定什么时候暂时复查;**关机条件不提高**,仍是本机的持续低压计数及 SOC/3.10 V 条件。电压回升离开告警区即撤销定时器。
服务和事件入口都只允许 U30 Air,F50/V50 不启动守护进程、不运行充电操作,也不会因虚假 FGU 读数关机。
### 验证与发布状态
测试入口(Linux/WSL,使用本地已有 ARM64 OpenWrt 镜像且禁用测试容器网络):
```sh
python3 openwrt/tests/battery-guard.py
```
- 各仓库 45 项真实固件 ucode 策略/输入解析检查;E5 另有 4 项板级适配,MU300 另有 9 项。
- 真实 hotplug → ubus → uloop 测试:正常状态无定时读取、内核入口事件可触发、重复事件只产生一次模拟关机、SIGTERM 正常退出。
- 真实 800 ms 定时器与事件突发交错测试,以及首次硬件告警后继续压降的回归;所有关机操作都是模拟回调。
- E5 三个 model stager、幂等启动链接及完整构建入口检查;MU300 init 中执行真实 model 门槛,确认 F50/V50 不启动。
- MU300 两套实际内核源码提取 C helper 编译运行测试:非 UMP 隔离、寄存器掩码、I/O 错误、插拔电池、IRQ 注册顺序、resume 恢复;6.18.54 和 7.2.8 的 FGU 对象均已交叉编译通过。
本次没有物理低电量放电、插拔电池或满载压降验证,不据离线测试宣称实机关机已验证。之前已生成的 `20261018-full-012536` 安装包未被修改,仍不含本功能。U30 Air 生效还需要重编译并配套安装 FGU 内核模块,不能只部署用户态脚本就声称完整生效。
+3 -1
View File
@@ -176,6 +176,7 @@ printf "127.0.0.1\tlocalhost\n\n::1\tlocalhost ip6-localhost ip6-loopback\nff02:
printf "mu300\n" > $R/etc/hostname # the real one comes from uci (etc/uci-defaults/90-mu300)
cp -a /in/opt-mu300 $R/opt/mu300
cp -a /in/overlay/. $R/
chmod 0755 $R/etc/init.d/unisoc-battery $R/etc/hotplug.d/power_supply/80-unisoc-battery
mkdir -p $R/etc/mu300
cp /in/block-mount.build-id $R/etc/mu300/block-mount.build-id
cp /in/wifi-sae/build-id $R/etc/mu300/wifi-sae.build-id
@@ -278,10 +279,11 @@ unset root_hash
# enable the services (rc.common "enable" needs ubus, which is not running in the build container)
# accounts still those of the image until an installer or mu300-update puts the device ones in place
: > $R/etc/.mu300-accounts-from-image
for s in mu300-accounts mu300-cpu-driver mu300-vendor mu300-hw mu300-post mu300-toolkit mu300-atd mu300-network-recovery mu300-modem-log mu300-wifi-client mu300-buttons mu300-ndp mu300-smsd mu300-user-packages ttyd; do
for s in mu300-accounts mu300-cpu-driver mu300-vendor mu300-hw mu300-post mu300-toolkit mu300-atd mu300-network-recovery mu300-modem-log mu300-wifi-client mu300-buttons mu300-ndp mu300-smsd mu300-user-packages unisoc-battery ttyd; do
n=$(sed -n "s/^START=//p" $R/etc/init.d/$s)
ln -sf ../init.d/$s $R/etc/rc.d/S$n$s
done
ln -sf ../init.d/unisoc-battery $R/etc/rc.d/K08unisoc-battery
if [ -d /in/luci-plugin ]; then
n=$(sed -n "s/^START=//p" $R/etc/init.d/unisoc-modem-ui)
ln -sf ../init.d/unisoc-modem-ui $R/etc/rc.d/S$n"unisoc-modem-ui"
@@ -0,0 +1,5 @@
#!/bin/sh
case "$ACTION" in add|change|remove) ;; *) exit 0 ;; esac
[ "$(cat /run/mu300/device 2>/dev/null)" = u30air ] || exit 0
# procd dispatches only kernel power-supply events. The guard rereads sysfs.
ubus send unisoc.battery '{}' >/dev/null 2>&1
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh /etc/rc.common
START=86
STOP=08
USE_PROCD=1
start_service() {
[ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ] || return 0
procd_open_instance
procd_set_param command /usr/bin/ucode /usr/libexec/unisoc-battery/watch.uc
procd_set_param respawn 3600 5 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
@@ -0,0 +1,30 @@
import * as fs from 'fs';
import { snapshot, text } from './read.uc';
export function profile(root) {
root = root ?? '';
// F50/V50 have no battery: never infer presence from their synthetic FGU.
if (text(root + '/run/mu300/device') != 'u30air') return null;
const raw = fs.readfile(root + '/sys/firmware/devicetree/base/charger-manager/cm-shutdown-voltage');
let voltage = null;
if (raw != null && length(raw) == 4)
voltage = ord(raw, 0) * 16777216 + ord(raw, 1) * 65536 + ord(raw, 2) * 256 + ord(raw, 3);
if (!(voltage > 0)) die('battery-guard: U30 Air stock shutdown voltage is missing\n');
// The first hardware alarm uses the battery design minimum (3.45 V on
// stock U30 Air), above the stock 3.40 V recheck gate. Keep watching that
// alarm band until voltage recovers, without changing shutdown thresholds.
const alarm = fs.readfile(root + '/sys/firmware/devicetree/base/battery/voltage-min-design-microvolt');
let alarm_uv = 3400000;
if (alarm != null && length(alarm) == 4) {
const value = ord(alarm, 0) * 16777216 + ord(alarm, 1) * 65536 + ord(alarm, 2) * 256 + ord(alarm, 3);
if (value > alarm_uv) alarm_uv = value;
}
// Stock 5.4.254 cm_uvlo_check_work: 5 samples, 200 jiffies at HZ=250.
return { uvlo: { shutdown_uv: voltage, offset_uv: 120000,
check_below_uv: alarm_uv, interval_ms: 800, samples: 5 } };
};
export function sample(root) {
root = root ?? '/sys/class/power_supply';
return snapshot(root, ['sc27xx-fgu', 'battery']);
};
@@ -0,0 +1,23 @@
import * as ubus from 'ubus';
import * as uloop from 'uloop';
import { create_guard } from './guard.uc';
export function run_guard(board, read, poweroff) {
uloop.init();
const bus = ubus.connect(null, 2);
if (!bus) die('battery-guard: ubus unavailable\n');
let guard;
const timer = uloop.timer(-1, () => guard.tick());
guard = create_guard(board, {
read,
schedule: delay => timer.set(delay),
cancel: () => timer.set(-1),
poweroff,
});
const event = bus.listener('unisoc.battery', () => guard.event());
if (!event) die('battery-guard: event subscription failed\n');
const term = uloop.signal(15, () => uloop.end());
const interrupt = uloop.signal(2, () => uloop.end());
guard.event(); // Check boot state after subscribing, before blocking in epoll.
uloop.run();
};
@@ -0,0 +1,28 @@
import { assess } from './policy.uc';
// One owner. Events cannot accelerate or postpone the board's UVLO timer.
export function create_guard(profile, runtime) {
const state = { active: false, count: 0 };
let scheduled = false, shutting_down = false;
function evaluate(tick) {
if (tick) scheduled = false;
if (shutting_down) return;
const result = assess(runtime.read(), profile, state, tick);
if (result.reason) {
shutting_down = true;
runtime.cancel();
runtime.poweroff(result.reason);
}
else if (result.next != null) {
if (!scheduled) {
scheduled = true;
runtime.schedule(result.next);
}
}
else if (scheduled) {
runtime.cancel();
scheduled = false;
}
}
return { event: () => evaluate(false), tick: () => evaluate(true) };
};
@@ -0,0 +1,36 @@
// Android BatteryService semantics; board-specific UVLO comes from the adapter.
export function assess(sample, profile, state, tick) {
if (!sample || sample.present !== 1) {
state.active = false;
state.count = 0;
return {};
}
if (sample.level_supported) {
if (sample.level == 'Critical') return { reason: 'critical' };
}
else if (sample.capacity === 0 && sample.status != null && sample.status != 'Charging') {
return { reason: 'empty' };
}
const uvlo = profile.uvlo;
if (!uvlo) return {};
if (sample.voltage == null || sample.capacity == null) {
// A failed read is not a new low-voltage sample.
return state.active ? { next: uvlo.interval_ms } : {};
}
if (sample.voltage >= uvlo.check_below_uv) {
state.active = false;
state.count = 0;
return {};
}
if (sample.voltage > uvlo.shutdown_uv + uvlo.offset_uv)
state.count = 0;
else if (tick || !state.active)
state.count++;
state.active = true;
if (state.count >= uvlo.samples && (sample.capacity <= 1 || sample.voltage <= uvlo.shutdown_uv))
return { reason: 'undervoltage' };
return { next: uvlo.interval_ms };
};
@@ -0,0 +1,30 @@
import * as fs from 'fs';
export function text(path) {
const value = fs.readfile(path);
return value == null ? null : trim(value);
};
export function number(path, maximum) {
const value = text(path);
if (value == null || !match(value, /^(0|[1-9][0-9]*)$/)) return null;
const result = int(value);
return result >= 0 && (maximum == null || result <= maximum) ? result : null;
};
export function snapshot(root, names) {
for (let name in names) {
const path = root + '/' + name;
if (text(path + '/type') != 'Battery') continue;
const status = text(path + '/status');
return {
present: number(path + '/present', 1),
capacity: number(path + '/capacity', 100),
level_supported: fs.stat(path + '/capacity_level') != null,
level: text(path + '/capacity_level'),
status: index(['Unknown', 'Charging', 'Discharging', 'Not charging', 'Full'], status) >= 0 ? status : null,
voltage: number(path + '/voltage_now'),
};
}
return null;
};
@@ -0,0 +1,11 @@
import { profile, sample } from './adapter.uc';
import { run_guard } from './events.uc';
const board = profile();
if (!board) exit(0);
run_guard(board, () => sample(), reason => {
print('battery-guard: requesting orderly poweroff (' + reason + ')\n');
// No forced reboot/poweroff: procd stops services and unmounts normally.
if (system('/sbin/poweroff') != 0)
die('battery-guard: poweroff failed\n');
});
+39
View File
@@ -0,0 +1,39 @@
import * as fs from 'fs';
import { profile } from '/guard/adapter.uc';
let checks = 0;
function check(value, name) {
if (!value) die('FAIL: ' + name + '\n');
checks++;
}
const root = '/fixtures';
if (ARGV[0] == 'e5') {
check(profile(root) == null, 'no board profile');
for (let model in ['e5', 't551m', 'm8']) {
fs.writefile(root + '/etc/e5/device-profile', model + '\n');
const board = profile(root);
check(board != null && !board.uvlo, 'kernel keeps existing voltage policy: ' + model);
}
}
else {
for (let model in ['f50', 'v50', 'mu300', '', 'unknown']) {
fs.writefile(root + '/run/mu300/device', model + '\n');
check(profile(root) == null, 'batteryless or unadapted board: ' + model);
}
fs.writefile(root + '/run/mu300/device', 'u30air\n');
const path = root + '/sys/firmware/devicetree/base/charger-manager/cm-shutdown-voltage';
fs.writefile(path, chr(0) + chr(0x2f) + chr(0x4d) + chr(0x60));
const board = profile(root);
check(board.uvlo.shutdown_uv === 3100000, 'stock big-endian DT shutdown voltage');
check(board.uvlo.interval_ms === 800 && board.uvlo.samples === 5 &&
board.uvlo.offset_uv === 120000 && board.uvlo.check_below_uv === 3400000,
'stock U30 UVLO qualification');
const alarm = root + '/sys/firmware/devicetree/base/battery/voltage-min-design-microvolt';
fs.writefile(alarm, chr(0) + chr(0x34) + chr(0xa4) + chr(0x90));
check(profile(root).uvlo.check_below_uv === 3450000, 'DT hardware alarm arms UVLO before a later voltage dip');
fs.writefile(path, 'bad');
let rejected = false;
try { profile(root); } catch (e) { rejected = true; }
check(rejected, 'malformed DT cannot become an invented threshold');
}
print('PASS: ' + checks + ' board adapter checks\n');
+60
View File
@@ -0,0 +1,60 @@
#!/bin/sh
# Isolated container only. /tests/battery-events.uc replaces poweroff with a counter.
set -eu
mkdir -p /var/run/ubus /etc/e5 /run/mu300
printf 'e5\n' > /etc/e5/device-profile
printf 'u30air\n' > /run/mu300/device
ubusd &
bus_pid=$!
guard_pid=
trap 'test -z "$guard_pid" || kill "$guard_pid" 2>/dev/null || :; kill "$bus_pid" 2>/dev/null || :' EXIT
n=0
until ubus list >/dev/null 2>&1; do
n=$((n + 1)); [ "$n" -lt 50 ]; sleep 1
done
ucode /tests/battery-events.uc &
guard_pid=$!
n=0
until [ -s /fixtures/reads ]; do
n=$((n + 1)); [ "$n" -lt 50 ]; sleep 1
done
before=$(cat /fixtures/reads)
sleep 1
[ "$(cat /fixtures/reads)" = "$before" ]
[ ! -e /fixtures/offcount ]
printf '{"present":1,"capacity":20,"level_supported":true,"level":"Critical","status":"Charging","voltage":3800000}' > /fixtures/state.json
ACTION=change /sbin/hotplug-call power_supply
n=0
until [ -s /fixtures/offcount ]; do
n=$((n + 1)); [ "$n" -lt 50 ]; sleep 1
done
ACTION=change /sbin/hotplug-call power_supply
sleep 1
[ "$(cat /fixtures/offcount)" = 1 ]
[ "$(cat /fixtures/reason)" = critical ]
kill "$guard_pid"
wait "$guard_pid"
guard_pid=
printf 'PASS: real hotplug -> ubus -> uloop, no idle reads, one mocked poweroff, SIGTERM exit\n'
rm /fixtures/offcount /fixtures/reads /fixtures/reason
printf '{"present":1,"capacity":1,"level_supported":false,"status":"Discharging","voltage":3220000}' > /fixtures/state.json
ucode /tests/battery-events.uc uvlo &
guard_pid=$!
n=0
until [ -s /fixtures/reads ]; do
n=$((n + 1)); [ "$n" -lt 50 ]; sleep 1
done
for i in 1 2 3 4 5 6 7 8 9 10; do ACTION=change /sbin/hotplug-call power_supply; done
[ ! -e /fixtures/offcount ]
n=0
until [ -s /fixtures/offcount ]; do
n=$((n + 1)); [ "$n" -lt 60 ]; sleep 1
done
[ "$(cat /fixtures/offcount)" = 1 ]
[ "$(cat /fixtures/reason)" = undervoltage ]
kill "$guard_pid"
wait "$guard_pid"
guard_pid=
printf 'PASS: real 800ms UVLO timers complete despite event bursts; no forced or real poweroff\n'
+17
View File
@@ -0,0 +1,17 @@
import * as fs from 'fs';
import { run_guard } from '/guard/events.uc';
const board = ARGV[0] == 'uvlo' ? {
uvlo: { shutdown_uv: 3100000, offset_uv: 120000, check_below_uv: 3400000,
interval_ms: 800, samples: 5 },
} : {};
function increment(name) {
fs.writefile('/fixtures/' + name, '' + (int(fs.readfile('/fixtures/' + name) ?? '0') + 1));
}
run_guard(board, () => {
increment('reads');
return json(fs.readfile('/fixtures/state.json'));
}, reason => {
increment('offcount');
fs.writefile('/fixtures/reason', reason);
});
+70
View File
@@ -0,0 +1,70 @@
"""Real ucode policy/board tests and offline build wiring; no hardware writes."""
from pathlib import Path
import os
import runpy
import subprocess
import tempfile
TOP = Path(__file__).resolve().parents[2]
OVERLAY = TOP/'openwrt/overlay'
HERE = Path(__file__).resolve().parent
FAMILY = 'e5' if (TOP/'devices/battery-guard.py').is_file() else 'mu300'
def main():
with tempfile.TemporaryDirectory(prefix='battery-guard-test-') as directory:
root = Path(directory)
for name in ('battery', 'etc/e5', 'run/mu300',
'sys/firmware/devicetree/base/charger-manager', 'sys/firmware/devicetree/base/battery'):
(root/name).mkdir(parents=True, exist_ok=True)
runner = ['docker', 'run', '--pull', 'never', '--rm', '--network', 'none',
'--platform', 'linux/arm64',
'-v', str(OVERLAY/'usr/libexec/unisoc-battery')+':/guard:ro',
'-v', str(root)+':/fixtures',
'-v', str(HERE)+':/tests:ro', 'mu300-openwrt-base:25.12.5']
subprocess.run([*runner, 'ucode', '/tests/battery-guard.uc'], check=True)
subprocess.run([*runner, 'ucode', '/tests/battery-adapter.uc', FAMILY], check=True)
# Compile the actual service entrypoint, not only its policy imports.
subprocess.run([*runner, 'ucode', '-c', '-o', '/tmp/watch.ucb', '/guard/watch.uc'], check=True)
(root/'state.json').write_text('{"present":1,"capacity":40,"voltage":3800000}')
events_runner = runner[:-1] + ['-v', str(OVERLAY/'etc/hotplug.d/power_supply/80-unisoc-battery')+
':/etc/hotplug.d/power_supply/80-unisoc-battery:ro', runner[-1]]
subprocess.run([*events_runner, 'sh', '/tests/battery-events.sh'], check=True, timeout=30)
if FAMILY == 'e5':
stage = runpy.run_path(str(TOP/'devices/battery-guard.py'))['stage']
offline = root/'offline'
offline.mkdir()
stage(offline)
stage(offline)
for name in ('S86unisoc-battery', 'K08unisoc-battery'):
link = offline/'etc/rc.d'/name
assert link.is_symlink() and os.readlink(link) == '../init.d/unisoc-battery'
for name in ('devices/e5/stage.py', 'devices/m8/stage.py', 'devices/t551m/configure-rootfs.py'):
assert "devices/battery-guard.py" in (TOP/name).read_text()
# No Debian/base or profile assembler can leave only a dangling rc link.
assert 'unisoc-battery' in (TOP/'openwrt/build-rootfs.sh').read_text()
print('PASS: three model stagers, idempotent offline service deployment, full build entry')
else:
service = (OVERLAY/'etc/init.d/unisoc-battery').read_text()
for model in ('f50', 'v50', 'mu300', 'u30air'):
# Execute the real init function with a simulated model probe.
body = service.replace('/opt/mu300/bin/mu300-device 2>/dev/null', 'printf "$BOARD"')
shell = '''
procd_open_instance() { printf 'OPEN\n'; }
procd_set_param() { :; }
procd_close_instance() { :; }
''' + body + '\nstart_service\n'
result = subprocess.run(['sh', '-c', shell], env={**os.environ, 'BOARD':model},
capture_output=True, text=True, check=True)
assert ('OPEN' in result.stdout) == (model == 'u30air'), model
builder = (TOP/'openwrt/build-rootfs.sh').read_text()
assert 'mu300-user-packages unisoc-battery ttyd' in builder
assert 'K08unisoc-battery' in builder
print('PASS: F50/V50 exclusion and both mainline kernel build paths')
for name in ('etc/init.d/unisoc-battery', 'etc/hotplug.d/power_supply/80-unisoc-battery'):
subprocess.run(['sh', '-n', str(OVERLAY/name)], check=True)
if __name__ == '__main__':
main()
+111
View File
@@ -0,0 +1,111 @@
// Run with the actual firmware ucode runtime; every poweroff is a mock.
import * as fs from 'fs';
import { assess } from '/guard/policy.uc';
import { create_guard } from '/guard/guard.uc';
import { snapshot } from '/guard/read.uc';
let checks = 0;
function check(value, name) {
if (!value) die('FAIL: ' + name + '\n');
checks++;
}
function sample(extra) {
const result = { present: 1, capacity: 40, level_supported: false, status: 'Discharging', voltage: 3800000 };
for (let key in keys(extra ?? {})) result[key] = extra[key];
return result;
}
function reason(s) { return assess(s, {}, { count: 0 }, false).reason; }
check(reason(sample({ level_supported: true, level: 'Critical', capacity: 20, status: 'Charging' })) == 'critical', 'HAL critical owns charging exception');
for (let level in ['Low', 'Normal', 'High', 'Full', 'Unknown', null, '', 'garbage'])
check(!reason(sample({ level_supported: true, level, capacity: 0 })), 'supported noncritical or unreadable level: ' + level);
for (let status in ['Discharging', 'Not charging', 'Full', 'Unknown'])
check(reason(sample({ capacity: 0, status })) == 'empty', 'unsupported level empty: ' + status);
check(!reason(sample({ capacity: 0, status: 'Charging' })), 'empty while charging');
check(!reason(sample({ capacity: 0, status: null })), 'status read failure');
check(!reason(sample({ capacity: null })), 'capacity read failure');
check(!reason(sample({ capacity: 1 })), 'one percent alone is not a shutdown threshold');
for (let present in [0, null])
check(!reason(sample({ present, level_supported: true, level: 'Critical' })), 'absent or unreadable presence');
const board = { uvlo: { shutdown_uv: 3100000, offset_uv: 120000,
check_below_uv: 3400000, interval_ms: 800, samples: 5 } };
let current = sample(), requests = [], delays = [], cancels = 0;
function make_guard() {
return create_guard(board, {
read: () => current,
poweroff: why => push(requests, why),
schedule: ms => push(delays, ms),
cancel: () => cancels++,
});
}
let guard = make_guard();
guard.event();
check(length(delays) == 0 && length(requests) == 0, 'normal voltage idle without timer');
current = sample({ capacity: 1, voltage: 3220000 });
guard.event();
check(length(delays) == 1 && delays[0] == 800, 'stock UVLO interval');
for (let i = 0; i < 100; i++) guard.event();
check(length(delays) == 1 && length(requests) == 0, 'event burst neither advances samples nor postpones timer');
for (let i = 0; i < 3; i++) guard.tick();
check(length(requests) == 0, 'four low samples cannot shut down');
guard.tick();
check(length(requests) == 1 && requests[0] == 'undervoltage', 'fifth low sample plus rounded one percent');
for (let i = 0; i < 10; i++) { guard.tick(); guard.event(); }
check(length(requests) == 1, 'only one poweroff per accepted shutdown');
requests = []; delays = []; cancels = 0;
guard = make_guard(); current = sample({ capacity: 20, voltage: 3200000 });
guard.event();
for (let i = 0; i < 8; i++) guard.tick();
check(length(requests) == 0, 'low voltage above final threshold with SOC above one');
current.voltage = 3100000; guard.tick();
check(length(requests) == 1, 'final undervoltage independent of a wrong high SOC');
requests = []; delays = []; cancels = 0;
guard = make_guard(); current = sample({ capacity: 1, voltage: 3200000 });
guard.event(); guard.tick();
current.voltage = null; guard.tick(); guard.tick();
check(length(requests) == 0, 'I/O errors never count as low samples');
current.voltage = 3300000; guard.tick(); // within alarm band but above count threshold
current.voltage = 3200000;
for (let i = 0; i < 4; i++) guard.tick();
check(length(requests) == 0, 'voltage recovery resets consecutive count');
current.voltage = 3400000; guard.event();
check(cancels == 1, 'leaving low-voltage band disarms timer');
current = sample({ capacity: 0, status: 'Charging' });
guard.event();
check(length(requests) == 0, 'charging at boot is not the unsupported-level empty case');
current.status = 'Not charging'; guard.event(); guard.event();
check(length(requests) == 1 && requests[0] == 'empty', 'charger-online pause does not hide an empty discharging battery');
const alarm_board = { uvlo: { shutdown_uv: 3100000, offset_uv: 120000,
check_below_uv: 3450000, interval_ms: 800, samples: 5 } };
const alarm_state = { count: 0, active: false };
let alarm = assess(sample({ capacity: 20, voltage: 3440000 }), alarm_board, alarm_state, false);
check(alarm.next == 800 && !alarm.reason && alarm_state.count == 0, 'first DT voltage alarm arms monitoring without changing shutdown threshold');
for (let i = 0; i < 5; i++)
alarm = assess(sample({ capacity: 20, voltage: 3100000 }), alarm_board, alarm_state, true);
check(alarm.reason == 'undervoltage', 'continued voltage dip is caught without requiring a second hardware alarm');
// Real sysfs-like input parser: no missing read may turn into 0 percent.
const root = '/fixtures', path = root + '/battery';
function put(name, value) { fs.writefile(path + '/' + name, value); }
put('type', 'Battery\n'); put('present', '1\n'); put('capacity', '0\n');
put('status', 'Discharging\n'); put('voltage_now', '3100000\n');
check(reason(snapshot(root, ['battery'])) == 'empty', 'real parser reads zero capacity');
for (let value in ['', 'error', '-1', '101', '1.5']) {
put('capacity', value);
check(!reason(snapshot(root, ['battery'])), 'invalid capacity is not empty: ' + value);
}
put('capacity', '0\n'); fs.unlink(path + '/status');
check(!reason(snapshot(root, ['battery'])), 'missing status file');
put('status', 'Charging\n');
check(!reason(snapshot(root, ['battery'])), 'real parser charging');
put('status', 'Discharging\n'); put('capacity_level', 'Low\n');
check(!reason(snapshot(root, ['battery'])), 'supported capacity level takes precedence');
put('capacity_level', 'Critical\n');
check(reason(snapshot(root, ['battery'])) == 'critical', 'real parser critical');
put('present', '0\n');
check(!reason(snapshot(root, ['battery'])), 'physical battery removed');
print('PASS: ' + checks + ' native ucode low-battery checks; all poweroffs mocked\n');
+51
View File
@@ -0,0 +1,51 @@
"""Compile real UMP9620 IRQ helper; no device, register or poweroff access."""
from pathlib import Path
import subprocess
import sys
import tempfile
kernel = Path(sys.argv[1])
source = (kernel/'drivers/power/supply/sc27xx_fuel_gauge.c').read_text()
start = source.index('static int ump9620_fgu_enable_events(')
a = source.index('{', start)
b, depth = a+1, 1
while depth:
depth += (source[b] == '{') - (source[b] == '}')
b += 1
function = source[start:b]
model = r'''
#include <assert.h>
#include <errno.h>
static int ump9620_info, other_info, writes, failure, last_value;
#define SC27XX_FGU_INT_EN 0x14
#define SC27XX_FGU_LOW_OVERLOAD_INT 1
#define SC27XX_FGU_CLBCNT_DELTA_INT 4
struct sc27xx_fgu_data {void *var; int regmap,base,bat_present;};
static int regmap_update_bits(int map,int address,int mask,int value)
{ assert(map==7 && address==0x114 && mask==5); last_value=value; writes++; return failure; }
'''
tests = r'''
int main(void) {
struct sc27xx_fgu_data data={.var=&other_info,.regmap=7,.base=0x100,.bat_present=1};
assert(!ump9620_fgu_enable_events(&data)); assert(writes==0);
data.var=&ump9620_info;
assert(!ump9620_fgu_enable_events(&data)); assert(writes==1 && last_value==5);
failure=-EIO; assert(ump9620_fgu_enable_events(&data)==-EIO); assert(writes==2);
failure=0; data.bat_present=0; assert(!ump9620_fgu_enable_events(&data)); assert(writes==3 && last_value==0);
data.bat_present=1; assert(!ump9620_fgu_enable_events(&data)); assert(writes==4 && last_value==5);
}
'''
with tempfile.TemporaryDirectory() as directory:
path = Path(directory)
(path/'events.c').write_text(model+function+tests)
subprocess.run(['cc','-Wall','-Werror',str(path/'events.c'),'-o',str(path/'events')], check=True)
subprocess.run([str(path/'events')], check=True)
probe = source[source.index('static int sc27xx_fgu_probe('):source.index('#ifdef CONFIG_PM_SLEEP')]
assert probe.index('!ump9620_has_battery_policy()') < probe.index('devm_request_threaded_irq')
assert probe.rindex('ump9620_fgu_enable_events(data)') > probe.rindex('devm_request_threaded_irq')
resume = source[source.index('static int sc27xx_fgu_resume('):source.index('static int sc27xx_fgu_suspend(')]
assert resume.index('return ump9620_fgu_enable_events(data)') < resume.index('ret = regmap_update_bits(')
assert 'sc27xx_fgu_cap_to_clbcnt(data, 1)' in source
detect = source[source.index('static irqreturn_t sc27xx_fgu_bat_detection'):source.index('static int sc27xx_fgu_calibration')]
assert detect.index('data->bat_present = !!state') < detect.index('ump9620_fgu_enable_events(data)')
print('PASS: actual FGU helper, non-UMP isolation, I/O failure, IRQ registration order, resume and existing 1% delta')
@@ -0,0 +1,69 @@
power: supply: UMP9620 deliver battery events while OpenWrt is awake
The FGU already programs a 1-percent coulomb delta and a DT-derived low
voltage alarm. Only enabling them in suspend leaves normal headless
operation without power_supply changes. Arm the existing hardware alarms
after both IRQ handlers are registered and restore them on resume.
Only UMP9620 participates; its probe already requires the stock enabled
battery policy node. Do not add a polling timer or touch charge/SOC tables.
Battery removal disarms those interrupts; insertion arms them again.
--- a/drivers/power/supply/sc27xx_fuel_gauge.c
+++ b/drivers/power/supply/sc27xx_fuel_gauge.c
@@ -1114,6 +1114,22 @@
return IRQ_HANDLED;
}
+/* UMP9620 battery boards need capacity/low-voltage events while awake too.
+ * The mainline suspend-only mask leaves a headless OpenWrt with no Health
+ * monitor. The delta is already configured by hw_init as one percent.
+ * Batteryless boards never probe this FGU (ump9620_has_battery_policy).
+ */
+static int ump9620_fgu_enable_events(struct sc27xx_fgu_data *data)
+{
+ unsigned int mask = SC27XX_FGU_LOW_OVERLOAD_INT | SC27XX_FGU_CLBCNT_DELTA_INT;
+
+ if (data->var != &ump9620_info)
+ return 0;
+
+ return regmap_update_bits(data->regmap, data->base + SC27XX_FGU_INT_EN,
+ mask, data->bat_present ? mask : 0);
+}
+
static irqreturn_t sc27xx_fgu_bat_detection(int irq, void *dev_id)
{
struct sc27xx_fgu_data *data = dev_id;
@@ -1129,6 +1145,8 @@
}
data->bat_present = !!state;
+ if (ump9620_fgu_enable_events(data))
+ dev_err(data->dev, "failed to update battery event mask\n");
mutex_unlock(&data->lock);
@@ -1483,6 +1501,12 @@
return ret;
}
+ ret = ump9620_fgu_enable_events(data);
+ if (ret) {
+ dev_err(dev, "failed to enable awake battery events: %d\n", ret);
+ return ret;
+ }
+
return 0;
}
@@ -1491,6 +1515,9 @@
{
struct sc27xx_fgu_data *data = dev_get_drvdata(dev);
int ret;
+
+ if (data->var == &ump9620_info)
+ return ump9620_fgu_enable_events(data);
ret = regmap_update_bits(data->regmap, data->base + SC27XX_FGU_INT_EN,
SC27XX_FGU_LOW_OVERLOAD_INT |