fix: harden MU300 storage updates and align shared device fixes

Boot independent mu300root partitions from generic ramdisks, preserve explicit
desktop targets and check update layout compatibility before replacing systems
or modules. Share internal ext4 checks and include the complete kernel bundle
in update identity. Add trial boot selection without changing the saved default.

Adapt upstream #283 timing-failure fallback for mainline eMMC initialization,
without normal-boot downgrades or a production fault-injection interface.

Accept legitimate ext4 growth tails, filter unsupported Wi-Fi cipher choices
without silently changing saved settings, and match U30 Air battery LED colors
to the confirmed stock policy. Record regression scope and RF research evidence.

Validation: 169 shared tests passed (1 skipped), 191 installer backend tests
passed (4 skipped), plus cipher/browser regression and actual MMC object builds
with the 6.18.54 and 7.2.8 configurations. No device deployment or release rebuild.
This commit is contained in:
kanoqwq committed 2026-10-17 20:20:49 +08:00
1 parent 34c5012934
commit 5161859dd0
45 files changed
+1370 -100

No files matched your search

+1
View File
@@ -10,3 +10,4 @@
*.ko binary
# Patch files contain unified-diff context markers followed by source indentation.
kernel/patches/*.patch whitespace=-blank-at-eol,-space-before-tab,-blank-at-eof
upstream/patches/*.patch whitespace=-blank-at-eol,-space-before-tab,-blank-at-eof
+1
View File
@@ -156,6 +156,7 @@ def main():
'bin/logdw': (a.logdw.read_bytes(), stat.S_IFREG | 0o755),
'etc/ueventd-perms.sh': (text(a.ueventd_perms), stat.S_IFREG | 0o755),
'etc/module-order': (text(a.module_order), stat.S_IFREG | 0o644),
'etc/mu300-internal-ext4.sh': (text(HERE / 'internal-ext4.sh'), stat.S_IFREG | 0o644),
}
dirs = {'bin', 'sbin', 'etc', 'proc', 'sys', 'dev', 'run', 'tmp', 'root', 'config', 'linux-modules'}
for name in a.module_order.read_text().split():
+44 -3
View File
@@ -414,10 +414,36 @@ find_root_offset() {
done
return 1
}
# An internal GPT root uses the same container filesystem as the free region.
# Do not scan the card or accept two partitions with the same name.
find_gpt_root() {
local candidate= p name label magic
[ "$(cat /sys/block/mmcblk0/device/type 2>/dev/null)" = MMC ] || return 1
for p in /sys/block/mmcblk0/mmcblk0p*/uevent; do
grep -qx PARTNAME=mu300root "$p" 2>/dev/null || continue
[ -z "$candidate" ] || return 1
name=${p%/uevent}; name=${name##*/}
candidate=/dev/$name
done
[ -n "$candidate" ] && [ -b "$candidate" ] || return 1
dd if="$candidate" of=/run/root-super bs=512 count=8 2>/dev/null || return 1
[ "$(wc -c < /run/root-super)" = 4096 ] || return 1
magic=$(od -An -tx2 -j1080 -N2 /run/root-super | tr -d ' \n')
label=$(dd if=/run/root-super bs=1 skip=1144 count=16 2>/dev/null | tr -d '\000')
[ "$magic" = ef53 ] && [ "$label" = mu300root ] && echo "$candidate"
}
# A TF-only image must never fall through to the eMMC free-region probe.
root_target=$(cat /etc/mu300-root-target 2>/dev/null)
# A desktop boot can retain a TF-only marker from its base segment. Its
# explicit partition choice must survive a generic init appended by updates.
case $(cat /etc/mu300-desktop-root-mode 2>/dev/null) in
part) root_target=part ;;
sd) root_target=sd ;;
legacy) root_target=auto ;;
esac
# Generic images retain the bounded internal-root fallback.
sd_root=
if [ "$root_target" != part ]; then
for n in $(seq 1 8); do
seen=
for d in /dev/mmcblk[1-9]p1 /dev/mmcblk[1-9]; do
@@ -435,6 +461,7 @@ for n in $(seq 1 8); do
[ -n "$seen" ] && break
mdev -s; sleep 1
done
fi
log "stage=sd-scan dev=${sd_root:-none} blocks=$(ls /dev/mmcblk[1-9]* 2>/dev/null | tr '\n' ',')"
# No additional wait or second mount: the root scan has established the TF
# device, and the root mount lets us read the current (journaled) policy.
@@ -446,18 +473,27 @@ if [ -n "$sd_root" ]; then
mount -t ext4 -o noatime "$sd_root" /disk 2>>/run/rootmount.err && root_mounted=1
log "stage=sd-root dev=$sd_root mounted=$root_mounted"
fi
[ "$root_mounted" = 1 ] && read_usb_boot_policy
setup_usb_gadget
internal_root=
if [ "$root_mounted" = 0 ] && [ "$root_target" != sd ]; then
if found=$(find_root_offset); then
if [ "$root_target" != part ] && found=$(find_root_offset); then
[ "$found" = "$ROOT_OFFSET" ] || log "stage=root-offset found=$found (default $ROOT_OFFSET)"
ROOT_OFFSET=$found
internal_root=1
elif gp=$(find_gpt_root); then
rootloop=$gp
. /etc/mu300-internal-ext4.sh
if desktop_ext4_check "$gp" && mount -t ext4 -o noatime "$gp" /disk 2>>/run/rootmount.err; then
root_mounted=1
log "stage=root-part dev=$gp"
else
log "stage=root-part-failed dev=$gp"
fi
else
log "stage=root-offset not-found (no internal mount attempted)"
fi
fi
[ "$root_mounted" = 1 ] && read_usb_boot_policy
[ "${DESKTOP_USB_READY:-}" = 1 ] || setup_usb_gadget
mkdir -p /newroot
# busybox mount only sets up a loop for regular files; for a block device the loop options would
# be handed to ext4 (EINVAL), so attach the loop explicitly and verify its offset
@@ -534,6 +570,11 @@ if [ "$root_mounted" = 1 ] && rootdir=$(pick_root) && [ -n "$rootdir" ]; then
[ "$linux_slot" = a ] && echo b > /run/mu300/android-slot || echo a > /run/mu300/android-slot
[ -n "$misc" ] && echo "$misc" > /run/mu300/misc-dev
echo "$rootloop" > /run/mu300/disk-dev
case "$rootloop" in
/dev/loop*) [ -z "$internal_root" ] || echo 'mmcblk0@region' > /run/mu300-root-dev ;;
/dev/mmcblk0p*) echo 'mmcblk0@mu300root' > /run/mu300-root-dev ;;
*) [ -z "$sd_root" ] || echo "$sd_root" > /run/mu300-root-dev ;;
esac
echo "$DEVICE" > /run/mu300/device
init=/sbin/init
[ -x /newroot/lib/systemd/systemd ] && init=/lib/systemd/systemd
+22
View File
@@ -0,0 +1,22 @@
# A known-bad internal filesystem must be repaired OFFLINE, before switch_root.
# Clean filesystems only read the two-byte state field; no full boot-time scan.
desktop_ext4_check() {
local state magic rc
magic=$(od -An -tx2 -j1080 -N2 "$1" | tr -d ' \n') || return 1
[ "$magic" = ef53 ] || return 1
state=$(od -An -tu2 -j1082 -N2 "$1" | tr -d ' \n') || return 1
case $state in ''|*[!0-9]*) return 1 ;; esac
[ "$((state & 2))" != 0 ] || [ -e /etc/mu300-desktop-fsck-force ] || return 0
# Keep the recovery console reachable during a slow/failing offline check.
# Healthy boots still load the saved USB mode before binding the gadget.
if [ "${DESKTOP_USB_READY:-}" != 1 ]; then
setup_usb_gadget
DESKTOP_USB_READY=1
fi
log "stage=desktop-root-fsck dev=$1"
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib:/repair/usr/lib \
/repair/usr/sbin/e2fsck -fy "$1" > /run/mu300-root-fsck.log 2>&1
rc=$?
[ "$rc" -le 2 ] || { log "stage=desktop-root-fsck-failed rc=$rc"; return 1; }
log "stage=desktop-root-fsck-done rc=$rc"
}
+2 -2
View File
@@ -5,6 +5,7 @@ set -eu
set -o pipefail
P=${MU300_PAYLOAD_DIR:?};T=${MU300_INSTALL_TMP:?}
. "$P/desktop-settings.env"
. "$P/ext4-geometry.sh"
. "$P/android-loop.sh"
# BusyBox's losetup lacks a size-limit option. Use Android Toybox explicitly;
# PATH in the installer intentionally points at BusyBox for other applets.
@@ -73,8 +74,7 @@ repair=$P/desktop/files/boot/repair
if [ "${GROW_FS:-1}" = 1 ]; then
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/resize2fs" -f "$loop" "$((need/8))"
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/e2fsck" -fn "$loop"
low=$(od -An -tu4 -j1028 -N4 "$loop" | tr -d ' \n');high=$(od -An -tu4 -j1360 -N4 "$loop" | tr -d ' \n')
[ "$high" = 0 ] && [ "$low" = "$((need/8))" ]
ext4_verify_grown "$loop" "$need" || { echo 'root filesystem geometry does not fill free range' >&2; exit 1; }
fi
mount -t ext4 -o ro,noload "$loop" "$T/image-root"
mounted=1
+5 -2
View File
@@ -4,6 +4,7 @@ set -eu
set -o pipefail
P=${MU300_PAYLOAD_DIR:?};T=${MU300_INSTALL_TMP:?}
. "$P/desktop-settings.env"
. "$P/ext4-geometry.sh"
dev=${1:?root device}; expected_cid=${2:?cid}; expected_sectors=${3:?size}; expected_sha=${4:?image checksum}
node=${dev##*/};disk=${node%p*}
case "$node" in mmcblk[0-9]p[0-9]*) ;; *) exit 1 ;; esac
@@ -32,8 +33,10 @@ repair=$P/desktop/files/boot/repair
}
if [ "${GROW_FS:-1}" = 1 ]; then
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/resize2fs" -f "$dev" "$((expected_sectors/8))"
low=$(od -An -tu4 -j1028 -N4 "$dev" | tr -d ' \n');high=$(od -An -tu4 -j1360 -N4 "$dev" | tr -d ' \n')
[ "$high" = 0 ] && [ "$low" = "$((expected_sectors/8))" ]
fi
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/e2fsck" -fn "$dev"
if [ "${GROW_FS:-1}" = 1 ]; then
ext4_verify_grown "$dev" "$expected_sectors" || { echo 'root filesystem geometry does not fill target' >&2; exit 1; }
fi
mount -t ext4 -o ro,noload "$dev" "$T/image-root"
trap 'umount "$T/image-root" 2>/dev/null || :' EXIT
+25
View File
@@ -0,0 +1,25 @@
# Shared by the offline TF and internal-partition installers.
# Call only after successful resize2fs and read-only e2fsck. A tiny final
# block group cannot always hold its metadata; resize2fs may omit that group.
ext4_verify_grown() {
ext4_dev=$1 ext4_sectors=$2
case "$ext4_sectors" in ''|0|*[!0-9]*) return 1;; esac
ext4_magic=$(od -An -tx2 -j 1080 -N 2 "$ext4_dev" | tr -d ' \n')
ext4_blocks=$(od -An -tu4 -j 1028 -N 4 "$ext4_dev" | tr -d ' \n')
ext4_high=$(od -An -tu4 -j 1360 -N 4 "$ext4_dev" | tr -d ' \n')
ext4_shift=$(od -An -tu4 -j 1048 -N 4 "$ext4_dev" | tr -d ' \n')
ext4_group=$(od -An -tu4 -j 1056 -N 4 "$ext4_dev" | tr -d ' \n')
[ "$ext4_magic" = ef53 ] && [ "$ext4_shift" = 2 ] && [ "$ext4_high" = 0 ] || return 1
case "$ext4_blocks:$ext4_group" in *[!0-9:]*|:*|*:) return 1;; esac
[ "$ext4_group" -gt 0 ] && [ "$ext4_group" -le 32768 ] || return 1
[ "$((ext4_group & (ext4_group - 1)))" = 0 ] || return 1
ext4_want=$((ext4_sectors / 8))
[ "$ext4_blocks" -gt 0 ] && [ "$ext4_blocks" -le "$ext4_want" ] || return 1
# Still reject an old 2 GiB filesystem on a much larger target. Only the
# exact requested size or its last complete block group is admissible.
if [ "$ext4_blocks" != "$ext4_want" ]; then
[ "$ext4_blocks" = "$((ext4_want / ext4_group * ext4_group))" ] || return 1
fi
printf 'EXT4 geometry verified: %s/%s blocks; unused tail %s blocks\n' \
"$ext4_blocks" "$ext4_want" "$((ext4_want - ext4_blocks))"
}
+4 -6
View File
@@ -59,12 +59,10 @@ part_fail() {
}
part_grow_ext4() {
# Resize offline: online resize can be unavailable in the installation kernel.
local dev=$1 sectors=$2 blocks low high shift actual
local dev=$1 sectors=$2 blocks
. /etc/ext4-geometry.sh || return 1
blocks=$((sectors / 8))
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib:/repair/usr/lib /repair/usr/sbin/resize2fs -f "$dev" "$blocks" > /run/part-growfs.log 2>&1 || return 1
low=$(od -An -tu4 -j 1028 -N 4 "$dev" | tr -d ' \n')
high=$(od -An -tu4 -j 1360 -N 4 "$dev" | tr -d ' \n')
shift=$(od -An -tu4 -j 1048 -N 4 "$dev" | tr -d ' \n')
# Our root images use 4 KiB blocks. Do not report success on a 2 GiB FS.
[ "$shift" = 2 ] && [ "$high" = 0 ] && [ "$low" = "$blocks" ]
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib:/repair/usr/lib /repair/usr/sbin/e2fsck -fn "$dev" >> /run/part-growfs.log 2>&1 || return 1
ext4_verify_grown "$dev" "$sectors"
}
+1 -22
View File
@@ -37,28 +37,7 @@ desktop_storage_start() {
DESKTOP_MODE=part ;;
esac
}
# A known-bad internal filesystem must be repaired OFFLINE, before switch_root.
# Clean filesystems only read the two-byte state field; no full boot-time scan.
desktop_ext4_check() {
local state magic rc
magic=$(od -An -tx2 -j1080 -N2 "$1" | tr -d ' \n') || return 1
[ "$magic" = ef53 ] || return 1
state=$(od -An -tu2 -j1082 -N2 "$1" | tr -d ' \n') || return 1
case $state in ''|*[!0-9]*) return 1 ;; esac
[ "$((state & 2))" != 0 ] || [ -e /etc/mu300-desktop-fsck-force ] || return 0
# Keep the recovery console reachable during a slow/failing offline check.
# Healthy boots still load the saved USB mode before binding the gadget.
if [ "${DESKTOP_USB_READY:-}" != 1 ]; then
setup_usb_gadget
DESKTOP_USB_READY=1
fi
log "stage=desktop-root-fsck dev=$1"
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib:/repair/usr/lib \
/repair/usr/sbin/e2fsck -fy "$1" > /run/mu300-root-fsck.log 2>&1
rc=$?
[ "$rc" -le 2 ] || { log "stage=desktop-root-fsck-failed rc=$rc"; return 1; }
log "stage=desktop-root-fsck-done rc=$rc"
}
. /etc/mu300-internal-ext4.sh
desktop_mount_root() {
local d u magic label n datafs dev loops
+2 -1
View File
@@ -54,7 +54,8 @@ def build(base, assets, mode, live, android_slot, prepare=None, identity=None):
files={'init':(desktop_init((assets/'original-init').read_text(encoding='utf-8')),stat.S_IFREG|0o755),
'etc/mu300-desktop-root-mode':((mode+'\n').encode(),stat.S_IFREG|0o644),
'etc/mu300-desktop-storage.sh':((assets/'storage.sh').read_bytes(),stat.S_IFREG|0o644)}
for name in ('part-prepare.sh','part-progress.sh','install-part.sh'):
files['etc/mu300-internal-ext4.sh']=((assets/'internal-ext4.sh').read_bytes(),stat.S_IFREG|0o644)
for name in ('part-prepare.sh','part-progress.sh','install-part.sh','ext4-geometry.sh'):
files['etc/'+name]=((assets/name).read_bytes(),stat.S_IFREG|0o644)
files['usr/share/mu300-gpt']=((assets/'mu300-gpt').read_bytes(),stat.S_IFREG|0o755)
repair=assets/'repair'
+1
View File
@@ -405,6 +405,7 @@ class Android:
self.shell('chmod 755 '+self.bb+' '+self.p+'/*.sh')
if not tf:
for n in ('android-image.sh','android-write-part.sh','android-write-free.sh','android-loop.sh'):self.push(root/'desktop'/n,n)
self.push(root/'desktop/files/boot/ext4-geometry.sh','ext4-geometry.sh')
for p in (root/'desktop/files/boot/repair').rglob('*'):
if p.is_file():self.push(p,p.relative_to(root).as_posix())
self.shell('chmod -R u+rx '+self.p+'/desktop/files/boot/repair')
+1
View File
@@ -55,6 +55,7 @@ unset MU300_DEPLOY_ROOT
for p in (TOP/'desktop/boot').iterdir():
if p.is_file(): shutil.copyfile(p, assets/p.name)
shutil.copyfile(TOP/'boot/init', assets/'original-init')
shutil.copyfile(TOP/'boot/internal-ext4.sh', assets/'internal-ext4.sh')
shutil.copyfile(TOP/'boot/build-boot-image.py', assets/'build-boot-image.py')
shutil.copyfile(TOP/'rootfs/overlay/opt/mu300/bin/mu300-update', dest/'mu300-update-library.sh')
spec=importlib.util.spec_from_file_location('repair_prepare',TOP/'desktop/prepare-tools.py')
@@ -0,0 +1,107 @@
# 蜂窝发射功率控制可行性评估
日期:2026-10-17。仅评估,不实现、不部署功率控制,不发送功率设置命令。
后续针对“提高功率”的原厂 CP 固件查证、NR 最大 PA 参数边界、E5 / M8 原厂 EngineerMode 的完整命令格式与新增只读查询,见 [提高功率定向查证](MODEM-TX-POWER-INCREASE-EVIDENCE-20261017.zh-CN.md)。
## 结论
已找到可复用的原厂**功率回退**接口,值得继续研究。当前证据不足以推出“任意设定发射功率 / 精确 dBm 调节 / 增强功率”的功能,也不足以直接发布可调档位:参数单位、有效范围、不同频段的映射和实际效果尚未确认。
控制通道本身不需要新的内核驱动;现有 AT owner 可以承担传输。主要缺口是固件参数语义和结果验证,不是补一个网页滑块。
继续查证后,确认 E5、M8 原厂工程应用可以生成指定 dBm 的 `SPMAXRFPWR` NR 工程测试命令,应用校验范围为 `-43..27`,并有明确清除命令。不过它需要指定频点、带宽、调制和天线,包含连续波模式;原厂另一个 LTE PA 测试流程还明确要求飞行模式。这些测试入口不能作为已经验证的联网增强功能。应用允许输入 27,也不能证明实际输出或正常联网的最大功率是 27 dBm。
## 原厂二进制证据
从本地保存的原厂 vendor 提取 `libimpl-ril.so`,不是依据同平台网上命令猜测。
| 机型 | 架构 | `downgradeRadioPower` 地址 | 确认内容 |
| --- | --- | --- | --- |
| U30 Air | AArch64 | `0x6a1a0` | 完整命令组装、发送、完成回调和 HAL 请求链 |
| 荣悦 E5 | AArch64 | `0x6a5c0` | 相同的命令组装与应答判断 |
| VIPME M8 | AArch64 | `0x69ae0` | 相同的命令组装与应答判断 |
| T551M | ARM / Thumb | 符号 `0x51e2d`,指令起点 `0x51e2c` | 相同的双整数加载、条件追加与命令发送结构 |
U30 Air 原厂 `librilcore.so` 另有导出符号:
```text
ExtRadioNetwork::setRadioPowerFallback(int, bool, int)
```
反汇编确认:第一个 int 是请求序号;bool 和末尾 int 被作为两个请求参数发往 `RADIO_POWER_FALLBACK`(请求号 4032),再分发到 `downgradeRadioPower`。U30 Air 的分发表地址 `0x1b042`,对应分支 `0x6a684`。
RIL 的命令组装等价于:
```text
cmd = "AT+SPPOWERFB=" + 第一个数据参数
若第一个数据参数为 1,且第二个数据参数 >= 0:
cmd += "," + 第二个数据参数
向该请求的 SIM socket 发送,按 AT 传输结果与 final response success 判定完成。
```
这里的 `>= 0` 只是 RIL 的组装条件,**不是固件允许任意非负数的证据**。函数没有读取发射功率的返回值。HAL 方法名、bool 参数和函数名共同支持“启用 / 取消功率回退”的解释;各模式的电气效果尚未做写入测试。
来源版本:
- U30 Air vendor:`ZTE/U30Air/U30Air:13/TP1A.220624.014/20241127.203422:user/release-keys`。
- E5 vendor:`UNISOC/ums9158_1h10_cmcc/ums9158_1h10:13/TP1A.220624.014/2024112822:user/release-keys`。
- T551M vendor:`onetouch/TYT_00CM_FIH/TYT:13/TP1A.220624.014/551MCM08:user/release-keys`。
- M8:本地原厂 ROM 提取目录 `vipme_m8/erofs/vendor_a/lib64/libimpl-ril.so`;此条不据此推定所有 M8 固件版本一致。
- F50 / V50 未在本轮分别核对原厂 RIL 与运行固件,不能因为与 U30 Air 共用仓库就直接启用。
SHA-256:
```text
U30 libimpl-ril.so a0e8e71fa1f4afda302f7471abd419f9f861256ebe7a63a4421c00cdb0c8b3ec
E5 libimpl-ril.so c0e86a5a6d7402a3d126e411fdb956deb8a6454763d55505c3ba64f839d0c14b
M8 libimpl-ril.so 9cbd0703dc8d8babeacde5d2779f82ad61c6f8b85668663d6a41bc63ee4a5a12
T551M libimpl-ril.so 142e7467f86dd484b7e20e3bfc2780b5132821661e0980c38b4e478dacd67630
U30 librilcore.so cb68b650d52e1a2bc4f645c0db6ecf077c0044d36233d03bc1b80c9f0cf8c050
```
## U30 Air 实机只读查询
已复核设备身份 `u30air`;使用原 `/usr/libexec/unisoc-modem/at`,`MU300_SIM_SLOT=0`,每条超时 3 秒。没有打开 tty 另抢通道。
运行固件返回:
```text
Platform Version: MOCORTM_V2_23A_W25.03.2_Debug
Project Version: QogirN6Pro_PS
BASE Version: 5G_MODEM_V2_23A_W25.03.2
HW Version: ums9620_modem
01-14-2025 10:14:02
```
| 查询 | 实际返回 | 能得出的结论 |
| --- | --- | --- |
| `AT+SPPOWERFB?` | `+CME ERROR: 65536014` | 本轮未取得当前状态;不能把传输工具退出码 0 当作设置成功 |
| `AT+SPPOWERFB=?` | `+SPPOWERFB:(),(),()`,随后 `OK` | 固件能处理测试形式,但没有给出枚举或范围;不证明设置形式的效果 |
两条功率相关只读查询各约 0.08–0.10 秒返回。没有发送 `SPPOWERFB` 设置、SFUN / CFUN 设置,没有改 NV、重启基带或改变网络配置。
## 现有软件支持与缺口
- 两仓库没有已实现的 `SPPOWERFB` 功率设置功能。现有 AT 入口可传递此类请求,公共网络操作锁和每 SIM 寻址可复用;不需要复制拨号流程。
- E5 的 Unisoc ModemManager 插件没有实现对应 SAR 功率后端。ModemManager 的通用 SAR API 存在,不等于当前 Unisoc 设备已经支持。
- 当前查询无法回读设置。如果未来实现,只能区分“命令已接受 / 最后请求的设置 / 实际状态未知”,不能将本地保存值冒充基带实测值。
- RIL 按 SIM socket 发命令,不足以证明双卡的功率限额互相独立。共享射频、LTE / NR 并发、不同频段和天线的作用范围仍未知。
- 当前参数是功率上限、衰减量还是档位索引,尚未确认;数字越大是否降得越多,也未确认。不能凭命令名给参数贴 dBm、dB、百分比标签。
- 是否立即生效、断网 / 切卡 / 重启后是否保留、是否覆盖厂商 SAR / 热管理策略,尚未确认。本轮不增加自动回放。
- 未确认可用的实际发射功率读取字段。RSRP / RSRQ / SINR 是接收侧指标,不能用来证明发射功率设置已生效;Speedtest 也不能替代功率测量。
## 后续实现判断
较合适的目标是**原厂功率回退模式**,在确认固件映射后提供有限、可解释的选项;先保留默认行为,避免暴露没有依据的任意数值。
进入实现前还需:确认参数映射、确认可恢复默认、进行受控写入与实际功率 / 链路效果验证,并分别确认 LTE / NR 和双卡范围。这些均未在本轮执行。
若只能得到 OK 而不能确认物理效果,则不应将其发布成精确功率控制功能。若目标是提高原厂允许的最大发射功率,本次没有找到可支持该目标的证据。
通用参考:
- [ModemManager SAR 接口定义](https://raw.githubusercontent.com/linux-mobile-broadband/ModemManager/main/introspection/org.freedesktop.ModemManager1.Modem.Sar.xml):SAR level 的映射由设备厂商定义,可能按频段、天线变化;该通用说明不能替代本机映射表。
- [3GPP TS 38.213 / ETSI TS 138 213](https://www.etsi.org/deliver/etsi_ts/138200_138299/138213/17.02.00_60/ts_138213v170200p.pdf):上行发射功率受网络功控和终端最大功率预算共同约束,不能将一个限制参数等同于持续固定输出功率。
离线原始材料位于本机 `e5-linux/work/tx-power-audit-20261017/`,包含 RIL 副本、反汇编、字符串交叉引用、请求分发表校验和只读查询 JSON;不随刷机包分发原厂二进制。
@@ -0,0 +1,142 @@
# 提高蜂窝发射功率:定向查证结果
2026-10-17,承接 [功率控制评估](MODEM-TX-POWER-EVALUATION-20261017.zh-CN.md)。本轮继续只读分析,未发送功率设置命令。
## 目前能确切给出的结论
1. `AT+SPPOWERFB=0` 的完整命令能从原厂 HAL / RIL 的关闭功率回退分支确认。它是**取消额外功率回退**的命令,不是任意提高原厂最大发射功率的命令。未在本轮下发或测量实际效果;无法读取当前回退状态,因此不能声称当前设备执行后一定增大发射功率。
2. 实际 U30 Air 基带固件另有直接的发射功率控制候选;继续提取 E5、M8 的原厂工程应用后,还确认了 `SPMAXRFPWR` 的完整 NR 参数排列、应用输入范围和清除命令。但这属于射频工程测试入口,不能当作正常联网的增强开关。
3. 不把命令名字、测试形式返回 OK、参数被接受或 Speedtest 变快,当作物理输出功率已提高的证据。
## 固件来源
在 SSH 身份确认为 U30 Air、Android 来源槽为 a 后,只读获取 `/dev/block/by-name/nr_modem_a`,共 52,428,800 字节。没有读取或写入 NV 分区。
设备与本机副本 SHA-256 一致:
```text
e68abc37850110356e2a45d92071cf72d811377089851c0ec35d2969406d8007
```
运行基带版本为上一报告中实测的 `MOCORTM_V2_23A_W25.03.2_Debug / QogirN6Pro_PS`。以下偏移均为该固件文件偏移,不是设备物理地址,不可用于直接写内存。
## 找到的候选
| 固件线索 | 偏移 | 本轮证据 / 限制 |
| --- | --- | --- |
| `+SPTXPWRCTL` | `0x1e139cc` | 固件含命令名称与测试格式;实机仅确认测试形式,最后两个参数的单位和含义未知 |
| `+SPPWRFBCFG` | `0x1e11cb4` | 功率回退配置候选;没有状态回读结果,不据名字判断其是否修改持久配置 |
| `+SPPOWERFB` | `0x1e13db0` | 与原厂 RIL 组装出的回退命令吻合 |
| `set nr power_control` | `0x17d0cd8` | NR 工程命令分派中存在;不据名字推定它是联网功率增强接口 |
| `set nr max PA power` | `0x17d0e14` | 已追到解析、范围检查及向下游发送参数的代码;仍缺参数完整语义和实际射频验证 |
| `+SPMAXRFPWR` | `0x1e13794` | 固件另有相关 TX power / RX RSSI 输出字符串;未确认它可在保持正常联网的前提下读取或设置功率 |
| `+SPPOWERSWEEP` / `+SPPOWERSWEEPWAY` | `0x1e13f08` / `0x1e14058` | 仅识别到命令和握手定时器线索;没有当作日常联网设置使用 |
## NR 最大 PA 功率分支
NR 命令名比较位于 `0x17d0a2a`,匹配后经 `0x17d0b0c` 到 `0x17d0fc4` 的处理分支。处理结构为三个数值参数:
```text
AT+SP5GCMDS="set nr max PA power",<参数一>,<参数二>,<参数三>
```
这只是已识别的解析结构,**不是可以照抄数值执行的提功率步骤**。
- 前两个参数各自都必须为 `1..23` 或 `255`,否则进入错误分支。具体比较见 `0x17d0fca–0x17d0fe2`。
- 代码并未允许把前两个参数设成 `26` 或 `30`。不能将这个入口宣传成可任意调整上限。
- `255` 是单独放行的特殊值;尚未确认是自动、保持、无效或其他语义,不能解释为 255 dBm 或解除限额。
- 第三个参数按一个字节读取,其模式含义未确认。
- `0x1326bb2` 转交到 `0x146a092`,后者将两个 32 位数值和一个字节放入消息,并以消息号 `0x2ee1` 发送到下游。
- 尚未完整确认两个功率参数各自对应哪一条射频路径、单位、特殊值、恢复方式与是否持久化;本轮不猜测两个参数就是两张 SIM 或两根天线。
因此,即使观察到最大值 23,也只能确认**解析器数值上界**,不能跳过单位和实际效果验证就直接向用户推荐数值组合。
## 新增实机只读查询
均通过已有 `/usr/libexec/unisoc-modem/at`、SIM 0 作用域执行,单条超时 3 秒,没有另开 tty。
| 查询 | 返回 |
| --- | --- |
| `AT+SPTXPWRCTL?` | `+CME ERROR: 65536014` |
| `AT+SPTXPWRCTL=?` | `+SPTXPWRCTL:(0-1),(0-1),(0-4),(),()`,随后 OK |
| `AT+SPPWRFBCFG?` | `+CME ERROR: 65536014` |
| `AT+SPPWRFBCFG=?` | `+SPPWRFBCFG: (0-2),(),()`,随后 OK |
`()` 没有给出有效范围或单位,不能补成猜测值。工具退出码 0 只说明完成了传输,`CME ERROR` 仍然是 AT 错误。
## 继续查证:原厂 EngineerMode 的精确功率设置入口
### 来源和交叉核验
直接提取本机留存的原厂 `system_ext/app/EngineerMode/EngineerMode.apk`,解析 `classes7.dex` 与资源表,没有从网络教程推测参数。
| 原厂应用 | APK SHA-256 |
| --- | --- |
| E5 | `45b959c8567e42ad18ab91be215ec4c2c463b22061e065b933daa1dff0ad35fb` |
| M8 | `1bab3fa951fb7e40fdf3d83b3bc1ac52b9988ee17214c718cbcbb26bc32a76a1` |
两份 APK 的 `NrSendPowerImpl`、`NrSendPowerPrefActivity` 和 `RfSendPowerImpl` 反编译结果分别相同。这个结论只覆盖应用端代码;不能据此认为两款机器或 U30 Air 的 CP 固件、射频硬件和校准值也相同。
### NR:`AT+SPMAXRFPWR`
`com.unisoc.engineermode.modules.hardware.rfsendpower.NrSendPowerImpl.setMaxPower()` 的实际格式为:
```text
AT+SPMAXRFPWR=16,1,1,<band>,<arfcn>,<power>,<bandWidth>,<antNumber>,<scs>,<modulationType>,<mimoType>,<group>,<dbmFlag>
```
所有选择框都直接传入从 0 开始的选项索引,而不是显示文字或其数值。原厂资源表对应如下:
| 字段 | 原厂应用实际传值 |
| --- | --- |
| `band` | 从已选 NR 频段名去掉 `NR_BAND_N` 前缀 |
| `arfcn` | 用户输入的频点字符串,不是自动读取当前服务小区 |
| `power` | 输入框原样传值;界面校验整数 `-43..27`,标签为 dBm |
| `bandWidth` | `0..11` 依次为 5、10、15、20、25、30、40、50、60、80、90、100 MHz |
| `antNumber` | `0=ANT0`、`1=ANT1`、`2=ANT2` |
| `scs` | `0=15 kHz`、`1=30 kHz` |
| `modulationType` | `0=CW`、`1=BSPK`(原资源拼写)、`2=QPSK`、`3=QAM16`、`4=QAM64`、`5=QAM256` |
| `mimoType` | `0=按 antNumber 开启天线`、`1=开启全部天线` |
| `group` | `0=SA`、`1=NSA` |
| `dbmFlag` | `0=positive dbm`、`1=negative dbm` |
原厂 `clearMaxPower()` 明确发送:
```text
AT+SPMAXRFPWR=16,1,0
```
以上是**原厂应用生成的工程命令与清除命令**,不是经过实测的联网提功率步骤。尤其注意:
- `27` 是应用的输入校验上限,不证明实际硬件能够输出 27 dBm,也不证明它高于该频段的原厂联网上限。
- 应用同时传 `power` 字符串和独立的 `dbmFlag`;负数与该标志如何组合,需要 CP 侧进一步确认,不能自行简化。
- 应用仅按返回字符串含 `OK` 判断成功,没有用功率仪证明实际输出。
- 该页面单独指定频点、调制方式和天线,包含 `CW` 连续波选项。这些证据将其定位为射频工程测试入口,不能把设置后的输出当成仍受正常联网调度的上行数据传输。
- 尚未追完这个 NR 页面之外的全部状态管理,也未证明固件强制检查飞行模式;不声称“应用必定自动进入飞行模式”。
### 旧制式:`AT+SPMAXRF` 与 PA 测试流程
`RfSendPowerImpl` 的生成方式是:
```text
AT+SPMAXRF=<bandEnum>,<operation>,<dbm>,<freq>,0,0
```
这个实现的枚举只有 GSM850/900、DCS1800/1900、TD19/21 和 WCDMA B1/2/5/8,**没有 LTE 频段枚举**,不能把 WCDMA 枚举 `7` 当作 LTE B7。
另外,原厂 `PATesterActivity` 确实有 LTE 的 `SPMAXRF` 测试序列。例如它的 `FDD_BAND1` 项包含发送、读取、停止三个步骤,采用固定频点和 23 的测试功率。该测试流程明确调用 `openAirplan()` 打开飞行模式,并在返回时关闭飞行模式;其用途是 PA 检测,不是正常联网时提高上限。这里不将这套测试序列包装成日常提功率功能。
### 其他候选没有凭名字补参数
对 E5、M8 两份 APK 的全部 DEX 扫描,未找到 `SPTXPWRCTL`、`SPPWRFBCFG`、`SPPOWERFB`、`SPPOWERBF` 或 `set nr max PA power` 的直接字符串调用。该结果不能排除其他系统服务、原生库或动态组装命令的调用,但目前没有应用端参数说明可用于补齐它们。
本轮还追查了 NR 工程消息 `0x2ee1`:消息长度分派确实为 `0x1c`,与前述最大 PA 功率发送结构一致;另外一些同立即数的命中实际是缓存长度,不能当作处理器交叉引用。尚未找到足以确认两个功率参数完整物理语义的接收端证据。
## 还没有的证据
- 没有确认当前设备正在被额外回退,也没有取消回退前后的功率对比。
- 没有完成 NR 最大 PA 功率参数的物理含义、恢复值及持久化行为验证。
- 没有证明任一候选可在正常联网时突破原厂最大发射功率。
- 没有将 U30 Air 固件中的私有参数套用到 E5、T551M、M8、F50 或 V50。上一报告只证明部分机型的 RIL 共用回退命令,不证明整套 CP 工程命令相同。
原始材料保存在本机 `e5-linux/work/tx-power-audit-20261017/`:固件副本及哈希、功率字符串偏移、NR 工程分派反汇编、下游函数片段和只读查询 JSON。不会将原厂固件副本加入提交或刷机包。
@@ -0,0 +1,56 @@
# MU300 公共问题同步与扩散验证
日期:2026-10-17。基于维护中的 `clean-tf-7.2`,本轮工作分支为 `fix/shared-issues-20261017`。对应 E5 仓库本轮 issue 修复,逐项核对可复用部分;未修改上游分支。
## 实际修复
### 1. 内置分区正常扩容被误判失败
MU300 的 Android 独立分区写入、利用未分配空间安装,以及 initramfs 离线扩容,都要求 ext4 的块数与目标容量完全一致。但 `resize2fs` 遇到不足以容纳元数据的末尾小块组时,可以成功扩容而不使用这段尾部空间。原检查会把这种合法结果当成失败。
三个路径共用 `desktop/boot/ext4-geometry.sh`。成功扩容且只读 fsck 通过后,接受目标块数或目标内最后一个完整块组边界;仍拒绝大幅欠扩容、越界、错误块大小及无效块组。不会把大分区上残留的旧 2 GiB 文件系统认作成功。
助手脚本已接入电脑端载荷上传和 initramfs 构建。缺失依赖会在写入前失败。保留设备身份、分区大小、镜像摘要、邻接区域和 GPT 检查;利用空闲空间的路径仍在文件系统验证成功后提交 GPT。显式不扩容选项保持有效。
新脚本不放进影响续装载荷身份的工具目录;测试确认仅新增该脚本不会改变原有关键载荷身份,不会无故拒绝待完成的续装记录。发布包普通文件清单仍校验它。
### 2. Wi-Fi 页面提供驱动不支持的密码套件
原生 LuCI 列出 GCMP、GCMP-256、CCMP-256 等选项,但不核对当前无线芯片能力。新增只读能力查询,按当前 radio 对应 PHY 的 IEEE 密码套件编号筛选候选项。其他无线芯片按各自能力显示;查询失败保持原有选项,不能把能力未知误认成不支持。
扩散检查同时覆盖 E5 侧曾发现的关联问题:若旧配置用了不支持的套件,直接移除选项会让原生 select 自动选择 `auto`。现在保留当前旧值并标记不支持,保存时明确提示用户主动选择合法项,避免修改热点名称时顺带改变密码套件。
查询使用现有 ucode、ubus、iw 和随固件提供的 BusyBox;不新增 Python 运行依赖、服务或常驻轮询。只打开无线配置弹窗时查询,不进入基带启动链。中英土三语言提示均验证。
干净 rootfs 构建、插件安装及首次初始化已接入同一补丁器;重复执行不会重复修改。源文件结构不符合预期时不写入半成品。移除可选看板插件前,会撤销本轮对原生 LuCI 的引用;测试确认恢复后的无线页面与原文件字节一致。
## 未照搬的部分
- MU300 无实体屏幕,不移植 E5 屏幕锁屏、唤醒和导航代码。
- 原生 TF/Magisk 安装直接格式化后解包,不经过上述镜像扩容检查,原生安装文件未改动。
- MU300 使用自带工具链,不存在 E5 对 Magisk BusyBox 路径的同一依赖问题。
- E5 的充电器和 TF 电源时序属于不同硬件实现,未复制到 MU300/U30 Air。
- 未更改 AT 顺序、开机回放、基带重连、NV、无线内核驱动或运行时省电策略。本轮不增加正常开机的 fsck 或轮询。
## 扩散验证
23 组 unittest 共发现 **197 项:195 项通过,2 项跳过,无失败**。另有真实 Chromium 原生 select 验证通过。
覆盖范围包括:
- 真实 ext4 临时稀疏文件:完整扩容、合法尾部省略、欠扩容拒绝、证明文件保留,以及实际 initramfs 扩容函数。
- 真实临时 loop、挂载及 GPT:相邻区域保护、摘要失败不提交 GPT、GPT 被改变时提前退出,以及不扩容选项。所有块写入仅针对测试临时文件。
- 安装器、启动镜像、启动链、TF 格式化与容量检查、续装身份、更新互斥锁。
- 隔离 ARM64 容器执行实际 ucode:能力解析、真实 ubus 缺 radio 的失败分支、实际打包 LuCI 源码补丁、幂等与卸载还原、异常源码不被部分写入。
- Chromium 执行实际 LuCI `ui.Select`:三语言、三种不支持的旧套件、其他 PHY 能力及查询失败;验证旧值不会自动变为 `auto`。
- U30 Air 灯光、PD、充电控制、V50 灯光、热点、信道和 USB 稳定性相关回归。保留本轮开始前已有的 U30 Air 灯光更改。
两项跳过的原因:现有信道测试的 `MU300_WRT_IMAGE` 可选在线工具安装用例未启用;启动链的“非 root 必须拒绝”用例在 root 测试环境下按原测试规则跳过。不能将它们计为已验证。新增密码套件测试使用独立的离线容器环境变量,已实际执行。
验证期间另修正两个测试环境问题:BusyBox 内建 `ip` 绕过 PATH 桩,改为显式测试函数;充电容器未运行系统初始化,补建 `/run` 并等待测试监听器就绪。这些修改仅在测试夹具中,没有改充电或 USB 运行代码来迎合测试。
详细执行日志和汇总位于忽略目录 `work/shared-issues-20261017/`,最终汇总为 `FINAL-VERIFICATION.json`。`git diff --check` 通过。
## 验证边界
本轮为源码修改和离线扩散验证,未连接设备写入、刷机、修改 NV 或重打发布包。源码提交不代表已验证发布包或实机结果。实际无线接入、特定存储设备的电气稳定性不能由本轮离线结果替代。密码套件筛选不构成对 WPA3 固件密钥来源安全性的重新认证,也未改动此前的 SAE 桥接实现。
+13
View File
@@ -0,0 +1,13 @@
# U30 Air 电量灯颜色
按照用户确认的原厂实机行为调整;本轮未另行逆向原厂灯控程序或实机部署。
| 状态 | 低于 50% | 50% 及以上 |
| --- | --- | --- |
| 非充电,灯仍在显示时间内 | 蓝色常亮 | 白色常亮 |
| Charging | 蓝色呼吸 | 白色呼吸 |
| Full | 白色常亮 | 白色常亮 |
保留原硬件呼吸周期、亮度设置、充电保持点亮、拔电重置显示倒计时、过期熄灭、迟到事件互斥和热告警。移除普通低电量红闪分支,避免与原厂的 50% 分色规则冲突。网页 LED 配置的中英土说明同步修改。
只作用于 U30 Air 的电池灯;F50、V50 的独立灯控不变。没有新增轮询或动画进程。离线测试覆盖 0 / 15 / 49 / 50 / 51 / 100%、蓝白硬件呼吸切换、Full 停止呼吸和已有插拔熄灭时序。本次未更新此前发布包。
@@ -0,0 +1,55 @@
# 上游启动/更新问题同步与扩散验证
日期:2026-10-17。范围为 MU300 维护分支的公共实现,适用于 F50、V50、U30 Air;没有将 E5 的硬件实现搬入本仓库。本轮继续在 `fix/shared-issues-20261017` 工作,保留此前未提交更改。
## 来源与问题确认
- [#290](https://github.com/dikeckaan/mu300-linux/issues/290):V50 经桌面安装器安装到独立 GPT 分区后,运行上游内置更新,通用 init 替换桌面 init,找不到根分区,进入约 302 秒的救援回退。`pmic-wdt-NOT-ready` 是这条失败路径的后续现象,不能直接当成基带或 watchdog 根因。
- [PR #295](https://github.com/dikeckaan/mu300-linux/pull/295)、[PR #296](https://github.com/dikeckaan/mu300-linux/pull/296):更新前核对布局,通用启动镜像识别 `mu300root`。按本分支的现有 init、TF 选择和桌面更新架构适配,没有整套替换为上游脚本。
- [#226](https://github.com/dikeckaan/mu300-linux/issues/226)、[PR #283](https://github.com/dikeckaan/mu300-linux/pull/283):部分 eMMC 在 HS400ES 初始化阶段持续返回 `-84`,重复初始化仍选择同一个失败模式,最终没有 `mmcblk0`,固件和系统也无法读取。上游报告者已确认新版冷启动恢复;这不是本轮对我方设备的实测结果。
## 实际修改
### 通用启动镜像与布局检查
通用 init 在原有 TF/未分配空间路径之外,支持内部 eMMC 上唯一名为 `mu300root`、ext4 标签也完全匹配的 GPT 分区。不会选中 TF 上的同名分区,也不接受重复名称或前缀相似的标签。
默认启动选择保持原逻辑:合法 TF 优先,之后是既有内部空闲区域,再检查独立分区。桌面安装器明确选择独立分区时,则保留这一明确选择,不扫描 TF 或另一片内部区域。
扩散检查发现,桌面启动镜像可以继承底层 TF 镜像的 `mu300-root-target=sd`。因此新 init 明确读取桌面 `part` 策略,避免“虽然增加了分区扫描,却仍被旧 TF-only 标记挡住”。`sd` 策略依旧禁止访问内部根区域。
通用与桌面分区启动共用 `boot/internal-ext4.sh` 中的原有离线检查,不新增另一套修复。健康文件系统只读取状态,跳过完整 fsck;确认错误的内部根在挂载前检查。新文件接入普通、通用 ramdisk 和桌面附加 ramdisk,更新后不会丢失对应检查。挂载后的 USB 模式策略仍在配置 gadget 前读取。
主线内核包声明 `gpt-root` 能力。更新器在系统目录切换、模块替换和写 boot 前核对布局,不兼容的内核包提前停止。userdata 镜像不交给不能启动它的通用 init;仍使用桌面安装器的对应更新流程,不为了识别布局挂载 Android userdata。
### 本地内核包与临时启动
更新器原先只用 Image+generic ramdisk 计算安装身份,模块则在启动镜像校验之前就会替换。现在身份覆盖完整内核包;不同模块/能力内容不会仅因 Image 和 init 相同被报告为已安装。
模块写入移到启动镜像头、AVB 边界和镜像容量检查之后。验证通过的同一包重复执行仍跳过;不可用布局和错误启动头均不修改模块。
新增统一的 `mu300-next-boot --trial`:与已有切系统操作使用同一锁,重置失败次数并设置可回退的 Linux 试启动,不改变用户保存的默认系统。更新后使用已安装系统中的这份工具,避免仍运行在旧根目录时调用旧 API。若无法设置试启动会明确说明,不把“已写入 boot”误报为没有写入。
### eMMC 失败模式降级
新增 `0021-mmc-failed-timing-falls-back.patch`,采用 PR #283 的 MMC core 部分:仅时序初始化失败后,删除该 host 中失败的能力,让现有初始化重试选择下一模式,顺序为 HS400ES → HS200 → HS/DDR52 → HS。移除介质的错误不降低能力;正常 HS400ES 成功路径不降级。
不新增固定等待、重试轮询、默认降速或休眠限制。没有移植生产内核故障注入参数,也不修改 AT、开机回放、拨号或 NV。
## 验证
- 24 组公共回归共 **170 项:169 项通过,1 项按 root 环境条件跳过,无失败**。最后提取公共 fsck 后,受影响的通用启动、桌面 fsck、桌面安装器、ramdisk、TF 和静态回归重新通过。
- 图形安装器后端另有 **195 项:191 项通过、4 项按仓库/环境适用条件跳过,无失败**,覆盖更新、切系统、续装及卸载工作流。
- 实际执行 init 的存储选择代码,覆盖旧 TF 标记+明确 part、TF 优先、region 优先、分区不存在、挂载失败、重复分区、错误标签及非 MMC 设备。
- 实际执行更新函数,覆盖不兼容/缺失包在 `apply_one` 前拒绝,模块内容不同的本地包更新,同一包重复跳过,以及错误启动头不替换模块。
- 实际执行 `mu300-next-boot --trial`,在临时 misc 文件验证 A/B 两个 Linux 槽、CRC、尝试次数、只改 32 字节控制区,以及 android/linux/未保存默认值均保持原样。
- MMC 测试编译执行补丁的实际 C 函数,覆盖各级能力掩码、卡自身能力和 `ENOMEDIUM`。补丁分别零 fuzz 应用于本地 6.18.54、7.2.8 源码副本,并使用各自实际配置与编译命令生成 `mmc.o` 通过。源码/输出卷只读,编译产物仅在临时目录;没有把对象编译说成整包或实机验证。
- 其余扩散覆盖独立分区临时 loop/GPT、TF 容量与格式化、两槽启动链、原生部署文件保留、更新锁、SIPA TX 重试、电源回调、FGU、热点及 U30 Air PD/灯光。
- shell 语法及 `git diff --check` 通过。详细日志位于忽略目录 `work/upstream-refresh-20261017/`。
## 未证实或未操作的部分
- [#276](https://github.com/dikeckaan/mu300-linux/issues/276) 的 SIPA 下行冻结仍没有由现有日志确定新的驱动根因。保留此前已验证的 SIPA 修复,不以常驻保活、关闭省电或重复拨号声称解决。本轮相关源码未改,TX/电源回调回归通过。
- [#220](https://github.com/dikeckaan/mu300-linux/issues/220) 的特定 F50 启动卡死仍在上游调查;上游已排除早先猜测的 watchdog 标志。本轮不改 miscdata 或 watchdog 设置。
- 上游 PR #297 的旧安装器布局识别没有整套搬入:本仓库桌面安装器已经管理独立分区;原生 Magisk TF 部署脚本保持原样。
- 本轮没有部署设备、写 NV 或更新发布产物。存储冷启动和蜂窝冻结仍需对应硬件复测;源码提交不代表已验证发布包或实机结果。
+1
View File
@@ -219,6 +219,7 @@ if [ -d /in/luci-plugin ]; then
chmod 0600 $R/etc/config/mu300-charge
chmod 0755 $R/etc/init.d/mu300-charge $R/etc/hotplug.d/power_supply/75-mu300-charge $R/usr/libexec/rpcd/mu300-charge
ucode $R/usr/libexec/unisoc-modem/disable-channel-analysis $R
ucode $R/usr/libexec/unisoc-modem/filter-wifi-ciphers $R
chmod 0755 $R/etc/init.d/unisoc-cpu
chmod 0600 $R/etc/config/unisoc_apn
chmod 0755 $R/etc/init.d/unisoc-modem-ui $R/etc/init.d/unisoc-sms-forward $R/etc/init.d/unisoc-traffic $R/etc/hotplug.d/net/90-unisoc-usb-host $R/etc/hotplug.d/iface/90-unisoc-usb-host $R/usr/libexec/rpcd/mu300dash $R/usr/libexec/unisoc-modem/*
+12 -1
View File
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-mu300
PKG_VERSION:=1.2.0
PKG_RELEASE:=18
PKG_RELEASE:=19
PKG_LICENSE:=MIT
PKG_MAINTAINER:=MU300 Linux contributors
PKGARCH:=all
@@ -61,6 +61,7 @@ define Package/luci-app-mu300/postinst
cp -a "$$old"/. "$$state"/
fi
ucode /usr/libexec/unisoc-modem/disable-channel-analysis || exit 1
ucode /usr/libexec/unisoc-modem/filter-wifi-ciphers || exit 1
rm -f /tmp/luci-indexcache /tmp/luci-modulecache/* 2>/dev/null
uci -q get luci.languages.tr >/dev/null || uci set luci.languages.tr='Türkçe'
uci commit luci
@@ -97,4 +98,14 @@ define Package/luci-app-mu300/postrm
exit 0
endef
define Package/luci-app-mu300/prerm
#!/bin/sh
[ -n "$${IPKG_INSTROOT}" ] || {
if [ "$$1" = remove ]; then
ucode /usr/libexec/unisoc-modem/filter-wifi-ciphers '' --remove || exit 1
fi
}
exit 0
endef
$(eval $(call BuildPackage,luci-app-mu300))
@@ -0,0 +1,33 @@
'use strict';
'require fs';
const suites = {ccmp:['4'],ccmp256:['10'],gcmp:['8'],gcmp256:['9'],tkip:['2'],'tkip+ccmp':['2','4']};
function apply(option, capabilities) {
if (!Array.isArray(capabilities?.suites)) return; // Unknown is not unsupported.
const supported = value => !suites[value] || suites[value].every(n => capabilities.suites.includes('00-0f-ac:' + n));
const keys = option.keylist || [], labels = option.vallist || [];
option.keylist = keys.filter(supported);
option.vallist = labels.filter((_, i) => supported(keys[i]));
const read = option.cfgvalue, validate = option.validate;
option.cfgvalue = function(section) {
const value = read.call(this, section);
// Missing choices make a native select silently select its first item.
// Retain only the existing invalid value; do not permit saving it.
if (suites[value] && !this.keylist.includes(value))
this.value(value, value.toUpperCase() + ' (' + _('Unsupported') + ')');
return value;
};
option.validate = function(section, value) {
if (!supported(value))
return /^zh/.test(L.env.lang) ? '无线驱动不支持此密码套件,请选择支持的套件。' :
/^tr/.test(L.env.lang) ? 'Kablosuz sürücüsü bu şifreleme paketini desteklemiyor. Desteklenen bir paket seçin.' :
'The wireless driver does not support this cipher. Select a supported cipher.';
return typeof validate === 'function' ? validate.call(this, section, value) : true;
};
}
return {
load: radio => fs.exec_direct('/usr/libexec/unisoc-modem/wifi-ciphers', [radio], 'json').catch(() => ({})),
apply
};
@@ -0,0 +1,2 @@
#!/bin/sh
exec /usr/bin/ucode /usr/libexec/unisoc-modem/filter-wifi-ciphers
@@ -0,0 +1,31 @@
#!/usr/bin/ucode
// Apply once to the pinned LuCI view, on clean builds and package installation.
import { readfile, writefile, rename, unlink } from 'fs';
let path = (ARGV[0] || '') + '/www/luci-static/resources/view/network/wireless.js';
let text = readfile(path);
let removing = ARGV[1] == '--remove';
if (text == null || (index(text, 'mu300CipherSupport') >= 0) != removing) exit(0);
function once(pattern, transform, label) {
let count = 0;
text = replace(text, pattern, m => { count++; return transform(m); });
if (count != 1) die('Unexpected LuCI source for cipher filtering: ' + label + '\n');
}
if (removing) {
once(/'require mu300\.wifi-ciphers as mu300CipherSupport';/g, m => '', 'remove import');
once(/return network\.getWifiNetwork\(s\.section\)\.then\(async function\(radioNet\)\s*\{\nconst mu300CipherCaps = await mu300CipherSupport\.load\(radioNet\.getWifiDeviceName\(\)\);\n/g,
m => replace(replace(m, 'async function(', 'function('), /\nconst mu300CipherCaps[^\n]+\n/, ''), 'remove modal lookup');
once(/mu300CipherSupport\.apply\(o, mu300CipherCaps\);\n/g, m => '', 'remove filter');
} else {
once(/'use strict';/g, m => m + "'require mu300.wifi-ciphers as mu300CipherSupport';", 'imports');
once(/return network\.getWifiNetwork\(s\.section\)\.then\(function\(radioNet\)\s*\{/g,
m => replace(m, 'function(', 'async function(') + '\n' +
'const mu300CipherCaps = await mu300CipherSupport.load(radioNet.getWifiDeviceName());\n', 'modal');
once(/const crypto_modes\s*=\s*\[\];/g,
m => 'mu300CipherSupport.apply(o, mu300CipherCaps);\n' + m, 'cipher controls');
}
let tmp = path + '.cipher.tmp';
if (writefile(tmp, text) != length(text) || !rename(tmp, path)) {
unlink(tmp);
die('Cannot update LuCI cipher choices\n');
}
@@ -0,0 +1,3 @@
#!/usr/bin/ucode
import { capabilities } from '/usr/libexec/unisoc-modem/wifi-ciphers.uc';
print(sprintf('%J\n', capabilities(ARGV[0])));
@@ -0,0 +1,31 @@
// Read-only nl80211 capability lookup. No PHY reset, interface or UCI writes.
import * as fs from 'fs';
import * as ubus from 'ubus';
export function parse(text) {
let section = false, suites = [];
for (let line in split(text || '', '\n')) {
if (trim(line) == 'Supported Ciphers:') { section = true; continue; }
if (!section) continue;
if (!match(trim(line), /^\*/)) break;
let m = match(line, /\(([0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}):([0-9]+)\)/);
if (m) push(suites, lc(m[1]) + ':' + m[2]);
}
return suites;
};
export function capabilities(radio) {
if (type(radio) != 'string' || !match(radio, /^[a-zA-Z0-9_]{1,64}$/)) return {};
let bus = ubus.connect(null, 2);
if (!bus) return {};
let found;
try { found = bus.call('iwinfo', 'phyname', {section:radio}); } catch (e) {}
bus.disconnect();
if (type(found?.phyname) != 'string' || !match(found.phyname, /^phy[0-9]+$/)) return {};
let pipe = fs.popen('/opt/mu300/bin/busybox timeout 3 /usr/sbin/iw phy ' + found.phyname + ' info', 'r');
if (!pipe) return {};
let text = pipe.read('all'), code = pipe.close();
if (code != 0) return {};
let suites = parse(text);
return length(suites) ? {phy:found.phyname, suites} : {};
};
@@ -0,0 +1,6 @@
{
"luci-mod-network-config": {
"description": "Read wireless cipher capabilities",
"read": {"file": {"/usr/libexec/unisoc-modem/wifi-ciphers": ["exec"]}}
}
}
@@ -26,7 +26,7 @@ const labels = {
'LED timeout (seconds)': ['状态灯自动熄灭(秒)', 'LED kapanma süresi (saniye)'],
'While charging lamps stay on. Otherwise 0 keeps them on; press the power key to show them again.': ['充电时状态灯保持点亮;未充电时 0 表示常亮,熄灭后短按电源键可再次点亮。', 'Şarjda ışıklar açık kalır. Diğer durumlarda 0 sürekli açık tutar; yeniden göstermek için güç tuşuna basın.'],
'U30 Air: network blue on 4G, white on 5G, red without data. Wi-Fi blue on 2.4 GHz, white on 5 GHz. These lamps support on/off only.': ['U30 Air:网络灯 4G 蓝色、5G 白色、无数据红色;Wi-Fi 灯 2.4 GHz 蓝色、5 GHz 白色。这两组灯仅支持开关。', 'U30 Air: 4G mavi, 5G beyaz, veri yoksa kırmızı. Wi-Fi: 2.4 GHz mavi, 5 GHz beyaz. Bu ışıklar yalnızca açılıp kapatılabilir.'],
'Charging: breathing blue; full or normal battery: white; low battery: blinking red.': ['充电时蓝色呼吸;充满或正常电量时白色;低电量时红色闪烁。', 'Şarjda yumuşakça parlayan mavi; dolu veya normal pil beyaz; düşük pil yanıp sönen kırmızı.'],
'Below 50%: blue; from 50%: white. Breathing while charging; steady white when full.': ['低于 50% 蓝色,50% 起白色;充电时对应颜色呼吸,充满后白色常亮。', '%50 altında mavi, %50 ve üzerinde beyaz. Şarjda aynı renk yumuşakça parlar; dolunca sabit beyaz yanar.'],
'Signal lamp (LTE / 5G / no service)': ['信号灯(4G / 5G / 无信号)', 'Sinyal ışığı (4G / 5G / servis yok)'],
'Signal lamp brightness': ['信号灯亮度', 'Sinyal ışığı parlaklığı'],
'Wi-Fi hotspot lamp': ['Wi-Fi 热点灯', 'Wi-Fi erişim noktası ışığı'],
@@ -139,7 +139,7 @@ return view.extend({
}
if (u30air) {
o = s.option(form.Flag, 'battery', label('Battery lamp'), label('Charging: breathing blue; full or normal battery: white; low battery: blinking red.'));
o = s.option(form.Flag, 'battery', label('Battery lamp'), label('Below 50%: blue; from 50%: white. Breathing while charging; steady white when full.'));
o.default = '1'; o.rmempty = false;
o = s.option(form.Value, 'battery_brightness', label('Battery lamp brightness'));
o.datatype = 'range(0,255)'; o.default = '255'; o.rmempty = false;
+3 -6
View File
@@ -172,7 +172,9 @@ battery() {
# Charger online changes before the fuel-gauge status sometimes does.
# A stale "Charging"/"Full" must not keep the charging indication alive.
[ "$KEEP_LIT" != 0 ] || status=Discharging
# Stock U30 Air: blue below 50%, white from 50%; Full is steady white.
color=sc27xx:green
[ "$cap" -ge 50 ] || color=sc27xx:blue
mkdir -p "$STATE"
previous_power=$(cat "$STATE/.external-power" 2>/dev/null)
echo "$KEEP_LIT" > "$STATE/.external-power"
@@ -180,14 +182,9 @@ battery() {
echo $(( $(uptime_s) + TIMEOUT )) > "$STATE/.awake-until"
fi
rm -f "$STATE/.battery-blink" "$STATE/.battery-breathe"
case $status in
Charging) color=sc27xx:blue ;;
Full) ;;
*) if [ "$cap" -le 15 ]; then color=sc27xx:red; fi ;;
esac
[ "$status" != Full ] || color=sc27xx:green
case "$status:$color" in
Charging:*) echo "$color" > "$STATE/.battery-breathe" ;;
*:sc27xx:red) echo "$color" > "$STATE/.battery-blink" ;;
esac
for channel in sc27xx:red sc27xx:green sc27xx:blue; do
value=0; [ "$channel" != "$color" ] || value=1
+4 -2
View File
@@ -4,6 +4,7 @@
# mu300-next-boot android next reboot (and later ones) go to Android
# mu300-next-boot attempts [N] show, or set, how many boots in a row may fail before Android takes over (1-6)
# mu300-next-boot --rearm used by mu300-boot-ok.service after a successful boot
# mu300-next-boot --trial try an updated Linux boot without changing the saved default
# mu300-next-boot status
# The Linux slot is armed with tries=N+1 and successful=0. LK decrements tries on every boot and rolls back to Android's slot
# (Android) when it finds tries=1, so N boots that never reach mu300-boot-ok land in Android on the next one.
@@ -117,7 +118,7 @@ set_default() (
# Include the successful-boot rearm in the same lock: an Android selection
# must not be overwritten by a concurrently finishing startup service.
case "${1:-status}" in
linux|android|--rearm|attempts)
linux|android|--rearm|--trial|attempts)
exec 9>/run/openwrt-default-boot.lock
flock -n 9 || { echo "boot control busy" >&2; exit 1; } ;;
esac
@@ -125,6 +126,7 @@ esac
case "${1:-status}" in
linux) set_default linux; echo "default boot: linux" ;;
android) set_default android; echo "next boot: android (opposite slot)" ;;
--trial) clear_boot_tries; arm_linux ;;
attempts)
if [ -z "${2:-}" ]; then attempts; exit 0; fi
case $2 in [1-6]) ;; *) echo "attempts must be 1-6 (the slot's tries field has room for 7)" >&2; exit 2 ;; esac
@@ -137,5 +139,5 @@ case "${1:-status}" in
echo "failed boots in a row before Android: $(attempts)"
d=$(disk_dir) && [ -f "$d/boot-tries" ] && echo "boots since the last good one: $(cat "$d/boot-tries")"
slot_state ;;
*) echo "usage: $0 linux|android|attempts [N]|status" >&2; exit 2 ;;
*) echo "usage: $0 linux|android|--trial|attempts [N]|status" >&2; exit 2 ;;
esac
+82 -29
View File
@@ -109,6 +109,39 @@ bundle_runs_here() {
grep -qx './devices' "$2" || return 1
untar -xzf "$1" -C "$3" ./devices && grep -qw "$_me" "$3/devices"
}
# Read the root device, never mount Android userdata to guess an installation.
# The desktop init records disk-dev; newer generic init also names the layout.
root_layout() {
_sys=${MU300_SYSROOT:-}
_ref=$(cat "$_sys/run/mu300-root-dev" 2>/dev/null)
case $_ref in *@mu300root) echo part; return ;; *@*) echo region; return ;; esac
_rd=$(cat "$_sys/run/mu300/disk-dev" 2>/dev/null); _rn=${_rd##*/}
case $_rn in
loop[0-9]*)
_back=$(cat "$_sys/sys/class/block/$_rn/loop/backing_file" 2>/dev/null)
case $_back in /dev/mmcblk[0-9]*) echo region ;; ?*) echo image ;; *) echo unknown ;; esac
return ;;
mmcblk[0-9]*)
if grep -qx PARTNAME=mu300root "$_sys/sys/class/block/$_rn/uevent" 2>/dev/null; then echo part; return; fi
_disk=${_rn%p*}
if [ "$(cat "$_sys/sys/class/block/$_disk/device/type" 2>/dev/null)" = SD ]; then echo sd; return; fi ;;
esac
echo unknown
}
bundle_finds_root() { # BUNDLE LIST: must run before modules, root or boot writes
_layout=$(root_layout)
case $_layout in
image)
echo 'boot: userdata image needs the desktop installer to preserve its storage policy; nothing installed' >&2
return 1 ;;
part)
if ! grep -qx './features' "$2" || ! tar -xzOf "$1" ./features 2>/dev/null | grep -qx gpt-root; then
echo 'boot: this kernel cannot boot the independent mu300root partition (gpt-root missing); nothing installed' >&2
return 1
fi ;;
esac
return 0
}
# the directory the running system booted from (it stays in use under any name until the reboot)
is_root() { [ -d "$1" ] && [ / -ef "$1" ]; }
running_os() { [ -e /etc/openwrt_release ] && echo openwrt || echo ubuntu; }
@@ -625,6 +658,14 @@ write_boot() { # write_boot DEV PSIZE BODY VBMETA FOOTER
rm -f "$3.all"
}
unlock_for_trial() {
# After a root update / still refers to the old system. Use the tool in
# the installed system, not a chain of probes against deprecated APIs.
_next=$DISK/$(running_os)/opt/mu300/bin/mu300-next-boot
[ -x "$_next" ] || _next=${MU300_BIN:-/opt/mu300/bin}/mu300-next-boot
"$_next" --trial
}
boot_update() { # boot_update TAG (MU300_KERNEL_BUNDLE=FILE uses a local mu300-kernel.tar.gz instead)
tag=$1
dev=$(part_dev "$BOOT_PART") || { echo "boot: no $BOOT_PART partition found, boot image not updated" >&2; return 1; }
@@ -653,37 +694,12 @@ boot_update() { # boot_update TAG (MU300_KERNEL_BUNDLE=FILE uses a local mu30
printf 'boot: the kernel of %s does not support the %s; the boot image is unchanged\n' "$tag" "$(this_device)" >&2
rm -rf "$tmp"; return 1
fi
bundle_finds_root "$bundle" "$tmp/list" || return 1
untar -xzf "$bundle" -C "$tmp" ./Image ./ramdisk-generic.lz4 || { echo "boot: unpacking $bundle failed" >&2; return 1; }
[ -s "$tmp/Image" ] && [ -s "$tmp/ramdisk-generic.lz4" ] || { echo "boot: no kernel in the bundle" >&2; return 1; }
# A kernel the systems were not built with (the mainline bundle) brings its modules along: they go into every
# installed system before the boot image changes, next to the ones of the other kernel, which stay for a
# switch back. Ubuntu keeps them under extra/ and indexes them; OpenWrt keeps them flat and loads by path.
if grep -qx './kernel.release' "$tmp/list"; then
untar -xzf "$bundle" -C "$tmp" ./kernel.release ./modules || { echo "boot: unpacking the modules failed" >&2; return 1; }
for f in modules.builtin modules.builtin.modinfo; do
if grep -qx "./$f" "$tmp/list"; then untar -xzf "$bundle" -C "$tmp" "./$f" || true; fi
done
krel=$(cat "$tmp/kernel.release")
case $krel in ''|*/*|.*) echo "boot: bad kernel release '$krel' in the bundle" >&2; return 1 ;; esac
for os in $(installed_systems); do
case $os in ubuntu) d=$DISK/$os/lib/modules/$krel/extra ;; *) d=$DISK/$os/lib/modules/$krel ;; esac
mkdir -p "$d" && cp "$tmp"/modules/*.ko "$d/" || { echo "boot: installing the modules into $os failed" >&2; return 1; }
# Built-in -> module transitions (cpufreq voltage profiles) need
# fresh indexes on OpenWrt too, not only on Ubuntu.
for f in modules.builtin modules.builtin.modinfo; do
[ ! -f "$tmp/$f" ] || cp "$tmp/$f" "$DISK/$os/lib/modules/$krel/" || return 1
done
if [ "$os" = ubuntu ]; then
# what the kernel has built in (bundles from v2026.09.29 on): modprobe of a built-in driver then
# succeeds, and depmod stops warning
for f in modules.builtin modules.builtin.modinfo; do [ ! -f "$tmp/$f" ] || cp "$tmp/$f" "$DISK/$os/lib/modules/$krel/"; done
[ -e "$DISK/$os/lib/modules/$krel/modules.order" ] || : > "$DISK/$os/lib/modules/$krel/modules.order"
if command -v depmod >/dev/null; then depmod -b "$DISK/$os" "$krel" 2>/dev/null || true; fi
fi
done
printf 'boot: %s modules for %s installed into: %s\n' "$(ls "$tmp/modules" | wc -l | tr -d ' ')" "$krel" "$(installed_systems)"
fi
id=$(cat "$tmp/Image" "$tmp/ramdisk-generic.lz4" | sha256sum | cut -d' ' -f1)
# Modules/features are part of the payload too. Equal Image+init bytes do
# not make a different local bundle an already-installed update.
id=$(sha256sum < "$bundle" | cut -d' ' -f1)
# the image in boot_b now: stock header page, kernel, ramdisk; AVB footer in the last 64 bytes
dd if="$dev" of="$tmp/hdr" bs=4096 count=1 2>/dev/null
@@ -727,6 +743,35 @@ boot_update() { # boot_update TAG (MU300_KERNEL_BUNDLE=FILE uses a local mu30
cp "$tmp/footer" "$tmp/newfooter"
{ bytes "$nosize" 8 be; bytes "$nosize" 8 be; bytes "$vbs" 8 be; } | poke "$tmp/newfooter" 12
# A kernel the systems were not built with (the mainline bundle) brings its modules along: they go into every
# installed system before the boot image changes, next to the ones of the other kernel, which stay for a
# switch back. Ubuntu keeps them under extra/ and indexes them; OpenWrt keeps them flat and loads by path.
if grep -qx './kernel.release' "$tmp/list"; then
untar -xzf "$bundle" -C "$tmp" ./kernel.release ./modules || { echo "boot: unpacking the modules failed" >&2; return 1; }
for f in modules.builtin modules.builtin.modinfo; do
if grep -qx "./$f" "$tmp/list"; then untar -xzf "$bundle" -C "$tmp" "./$f" || true; fi
done
krel=$(cat "$tmp/kernel.release")
case $krel in ''|*/*|.*) echo "boot: bad kernel release '$krel' in the bundle" >&2; return 1 ;; esac
for os in $(installed_systems); do
case $os in ubuntu) d=$DISK/$os/lib/modules/$krel/extra ;; *) d=$DISK/$os/lib/modules/$krel ;; esac
mkdir -p "$d" && cp "$tmp"/modules/*.ko "$d/" || { echo "boot: installing the modules into $os failed" >&2; return 1; }
# Built-in -> module transitions (cpufreq voltage profiles) need
# fresh indexes on OpenWrt too, not only on Ubuntu.
for f in modules.builtin modules.builtin.modinfo; do
[ ! -f "$tmp/$f" ] || cp "$tmp/$f" "$DISK/$os/lib/modules/$krel/" || return 1
done
if [ "$os" = ubuntu ]; then
# what the kernel has built in (bundles from v2026.09.29 on): modprobe of a built-in driver then
# succeeds, and depmod stops warning
for f in modules.builtin modules.builtin.modinfo; do [ ! -f "$tmp/$f" ] || cp "$tmp/$f" "$DISK/$os/lib/modules/$krel/"; done
[ -e "$DISK/$os/lib/modules/$krel/modules.order" ] || : > "$DISK/$os/lib/modules/$krel/modules.order"
if command -v depmod >/dev/null; then depmod -b "$DISK/$os" "$krel" 2>/dev/null || true; fi
fi
done
printf 'boot: %s modules for %s installed into: %s\n' "$(ls "$tmp/modules" | wc -l | tr -d ' ')" "$krel" "$(installed_systems)"
fi
# keep the current image for rollback-boot, then write
cp "$tmp/body" "$BOOTDIR/prev.body"; cp "$tmp/vbmeta" "$BOOTDIR/prev.vbmeta"; cp "$tmp/footer" "$BOOTDIR/prev.footer"
cat "$BOOTDIR/installed.tag" > "$BOOTDIR/prev.tag" 2>/dev/null || echo installer > "$BOOTDIR/prev.tag"
@@ -743,6 +788,7 @@ boot_update() { # boot_update TAG (MU300_KERNEL_BUNDLE=FILE uses a local mu30
echo "$tag" > "$BOOTDIR/installed.tag"
kernel_choice > "$BOOTDIR/installed.kernel"
sync
unlock_for_trial || echo 'boot: image verified, but the Linux trial could not be armed; select OpenWrt before rebooting' >&2
rm -rf "$tmp"
[ -n "${MU300_KERNEL_BUNDLE:-}" ] || rm -f "$bundle"
printf 'boot: updated to %s (kernel %s bytes, ramdisk %s bytes). If it does not start, the device falls back\n' "$tag" "$nksz" "$nrsz"
@@ -884,6 +930,13 @@ apply() {
# a release without this bundle leaves the boot image alone (boot_update says so); anything else stops here
[ "$r" = 0 ] || [ "$r" = 2 ] || { offline_hint; die "nothing was changed; run mu300-update apply again to continue the download"; }
fi
# Refuse an incompatible init before apply_one can rename any system.
candidate=${MU300_KERNEL_BUNDLE:-${boot_asset:+$STAGE/$boot_asset}}
if [ -n "$candidate" ]; then
[ -s "$candidate" ] || die 'missing kernel bundle; nothing installed'
tar -tzf "$candidate" > "$STAGE/boot-list" || die 'unreadable kernel bundle; nothing installed'
bundle_finds_root "$candidate" "$STAGE/boot-list" || die 'incompatible root layout; use the desktop installer'
fi
echo "all files are here and verified; from now on the network is not needed"
pause_data
+54
View File
@@ -0,0 +1,54 @@
"""Render MU300 cipher controls with the actual pinned LuCI Select, offline."""
import argparse
from pathlib import Path
from playwright.sync_api import sync_playwright
TOP=Path(__file__).resolve().parents[1]
def main():
parser=argparse.ArgumentParser()
parser.add_argument('--wireless',type=Path,required=True)
parser.add_argument('--ui',type=Path,required=True)
args=parser.parse_args()
text=args.wireless.read_text(encoding='utf-8')
start=text.rfind('o=',0,text.index("'cipher',"));end=text.index('const crypto_modes',start)
controls=text[start:end]
native=args.ui.read_text(encoding='utf-8');native=native[native.index('const UISelect='):native.index('const UIDropdown=')]
feature=(TOP/'openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/wifi-ciphers.js').read_text(encoding='utf-8')
with sync_playwright() as p:
chrome=Path('C:/Program Files/Google/Chrome/Application/chrome.exe')
browser=p.chromium.launch(**({'executable_path':str(chrome)} if chrome.exists() else {}))
page=browser.new_page();errors=[];page.on('pageerror',lambda e:errors.append(str(e)))
result=page.evaluate('''async ([source,native,feature])=>{
const E=(tag,attrs,children=[])=>{const e=document.createElement(tag);for(const [k,v] of Object.entries(attrs||{}))if(v!=null)e.setAttribute(k,v);for(const c of children)e.append(c);return e;};
const L={env:{lang:'en'},isObject:x=>x&&typeof x==='object'};
const base={extend(methods){function Widget(...args){this.__init__(...args)}Widget.prototype={setUpdateEvents(){},setChangeEvents(){},...methods};return Widget;}};
const Select=new Function('UIElement','L','E','dom','_',native+';return UISelect;')(base,L,E,{bindClassInstance(){}},x=>x);
const support=new Function('fs','L','_',feature)({exec_direct:()=>Promise.reject(new Error('unavailable'))},L,x=>x);
const factory=new Function('ss','form','_','uci','support','caps','let o;'+source+';support.apply(o,caps);return o;');
function make(suites,saved) {const option={keylist:[],vallist:[],depends(){},value(v,label){this.keylist.push(v);this.vallist.push(label)}};return factory({children:[{option:'encryption',write(){}}],taboption(){return option}},{ListValue:{}},x=>x,{get(){return saved}},support,{suites});}
const checks=[];
for(const language of ['zh-cn','en','tr']){
L.env.lang=language;
for(const cipher of ['gcmp','gcmp256','ccmp256']){
const control=make(['00-0f-ac:4'],'sae+'+cipher);
const labels=()=>Object.fromEntries(control.keylist.map((k,i)=>[k,control.vallist[i]]));
const old=new Select(cipher,labels(),{sort:control.keylist.slice()});document.body.append(old.render());
const value=control.cfgvalue('id');const current=new Select(value,labels(),{sort:control.keylist});document.body.append(current.render());
checks.push({before:old.getValue(),after:current.getValue(),expected:cipher,valid:control.validate('id',current.getValue())});
}
}
const another=make(['00-0f-ac:4','00-0f-ac:8'],'sae+gcmp');
return {checks,other:another.validate('id',another.cfgvalue('id')),unknown:await support.load('radio0')};
}''',[controls,native,feature])
for check in result['checks']:
assert check['before']=='auto' and check['after']==check['expected'],check
assert isinstance(check['valid'],str),check
assert result['other'] is True and result['unknown']=={},result
assert not errors,errors
browser.close()
print('PASS: native LuCI select, 3 languages, saved invalid ciphers, independent PHY and failed capability read')
if __name__=='__main__':main()
+1
View File
@@ -89,6 +89,7 @@ class GenericRamdisk(unittest.TestCase):
self.assertEqual(r.returncode, 0, r.stderr)
files = cpio_files(unlz4_legacy(out.read_bytes()))
self.assertEqual(files['init'][1], (BOOT / 'init').read_bytes())
self.assertEqual(files['etc/mu300-internal-ext4.sh'][1],(BOOT/'internal-ext4.sh').read_bytes())
self.assertTrue(files['init'][0] & 0o111, 'init is not executable')
self.assertEqual(files['etc/module-order'][1], (BOOT / 'module-order.txt').read_bytes())
for n in (BOOT / 'module-order.txt').read_text().split():
+13 -8
View File
@@ -139,7 +139,8 @@ class ChargeControl(unittest.TestCase):
def test_real_watch_receives_events_and_checks_soc_without_events(self):
docker=['docker','exec',self.container]
subprocess.run(docker+['/bin/sh','-c','mkdir -p /var/run/ubus; /sbin/ubusd >/tmp/charge-ubus.log 2>&1 &'],check=True)
# The base image has not run procd, which normally creates /run.
subprocess.run(docker+['/bin/sh','-c','mkdir -p /run /var/run/ubus; /sbin/ubusd >/tmp/charge-ubus.log 2>&1 &'],check=True)
for attempt in range(30):
if subprocess.run(docker+['ubus','list'],capture_output=True).returncode==0:break
time.sleep(.1)
@@ -150,22 +151,26 @@ class ChargeControl(unittest.TestCase):
'MU300_CHARGE_SYS=/fixture/power MU300_CHARGE_STATE=/fixture/state.json '
'MU300_CHARGE_TYPEC=/fixture/typec MU300_CHARGE_DEVICE=u30air '
'/usr/bin/ucode /usr/libexec/unisoc-modem/charge-watch.uc')
watcher=subprocess.Popen(docker+['/bin/sh','-c',command],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
watch_log=self.fixture/'watch.log'
errors=watch_log.open('wb');self.addCleanup(errors.close)
watcher=subprocess.Popen(docker+['/bin/sh','-c',command],stdout=subprocess.PIPE,stderr=errors)
def wait_for(predicate,seconds):
deadline=time.monotonic()+seconds
while time.monotonic()<deadline:
if watcher.poll() is not None:
self.fail(watcher.communicate()[1].decode())
self.fail(watch_log.read_text())
if predicate():return
time.sleep(.1)
self.fail('Charge policy did not react in time')
self.fail('Charge policy did not react in time: '+watch_log.read_text())
try:
wait_for(lambda:(self.fixture/'watch.pid').exists(),3)
# Wait only in the fixture for the listener registration.
time.sleep(.3)
self.write(self.battery/'capacity',70)
subprocess.run(docker+['ubus','send','mu300.charge','{}'],check=True)
wait_for(lambda:(self.charger/'charge_type').read_text()=='Fast',3)
# Under ARM emulation startup can exceed a fixed 300 ms sleep.
# Retry fixture-only events until the listener is actually ready.
def event_received():
subprocess.run(docker+['ubus','send','mu300.charge','{}'],check=True)
return (self.charger/'charge_type').read_text()=='Fast'
wait_for(event_received,3)
# Real FGU percentages do not generate regular change events.
self.write(self.battery/'capacity',90)
wait_for(lambda:(self.charger/'charge_type').read_text()=='N/A',33)
+7 -1
View File
@@ -20,12 +20,13 @@ class RealLoop(unittest.TestCase):
self.assertEqual(p.returncode,0,p.stdout+p.stderr)
return p.stdout
def fixture(self,wrong_file=False,changed_gpt=False):
def fixture(self,wrong_file=False,changed_gpt=False,grow=True):
for tool in ('losetup','mkfs.ext4','debugfs','e2fsck','resize2fs','mount','bash'):
if not shutil.which(tool):self.skipTest('missing fixture tool '+tool)
with tempfile.TemporaryDirectory(prefix='mu300-free-range-') as tmp:
base=Path(tmp);disk=base/'disk';stage=base/'stage';stage.mkdir()
payload=base/'payload';payload.mkdir()
(payload/'desktop-settings.env').write_text('GROW_FS='+str(int(grow))+'\n')
total=6*2097152;first,last=snapshot(total,[('userdata',2048,2*2097152-1)])
start=2*2097152;need=2*2097152
newfirst,newlast=m.gpt_add_root(first,last,total,start,need)
@@ -51,6 +52,7 @@ class RealLoop(unittest.TestCase):
loader=repair/'lib/ld-musl-aarch64.so.1';loader.write_text('#!/bin/sh\nshift 2\nexec "$@"\n');loader.chmod(0o755)
for tool in ('e2fsck','resize2fs'):(repair/'usr/sbin'/tool).symlink_to(shutil.which(tool))
shutil.copyfile(TOP/'desktop/android-loop.sh',payload/'android-loop.sh')
shutil.copyfile(TOP/'desktop/boot/ext4-geometry.sh',payload/'ext4-geometry.sh')
sysroot=base/'sys';(sysroot/'device').mkdir(parents=True)
(sysroot/'device/cid').write_text('a'*32);(sysroot/'size').write_text(str(total))
script=(TOP/'desktop/android-write-free.sh').read_text()
@@ -77,11 +79,15 @@ class RealLoop(unittest.TestCase):
f.seek((start+need)*512);self.assertEqual(f.read(len(after)),after)
if changed_gpt:
f.seek(start*512);self.assertEqual(f.read(4096),bytes(4096))
elif not wrong_file:
f.seek(start*512+1028);blocks=int.from_bytes(f.read(4),'little')
self.assertEqual(blocks*4096,need*512 if grow else 32<<20)
finally:
self.assertFalse(self.command('losetup','-j',str(disk)).strip(),'fixture loop leaked')
def test_real_ext4_grows_to_selected_size_and_adjacent_ranges_survive(self):self.fixture()
def test_bad_root_file_never_commits_partition_table(self):self.fixture(wrong_file=True)
def test_changed_gpt_aborts_before_touching_free_range(self):self.fixture(changed_gpt=True)
def test_explicit_no_growth_keeps_original_filesystem_size(self):self.fixture(grow=False)
if __name__=='__main__':unittest.main()
+1 -1
View File
@@ -4,7 +4,7 @@ from helpers import ShellTest, TOP
class DesktopFsck(ShellTest):
def test_clean_error_and_unknown_filesystems(self):
source=(TOP/'desktop/boot/storage.sh').read_text()
function=source[source.index('desktop_ext4_check() {'):source.index('\ndesktop_mount_root()')]
function=(TOP/'boot/internal-ext4.sh').read_text()
loader=self.tmp/'loader'
loader.write_text('#!/bin/sh\necho "$*" >> "$STUBLOG/fsck"\nexit "${TEST_FSCK_RC:-0}"\n')
loader.chmod(0o755)
+5 -1
View File
@@ -174,6 +174,7 @@ class Desktop(unittest.TestCase):
old=self.payload_manifest();new=self.payload_manifest(relocated=True)
new['desktop']['OpenWrt-Installer.exe']='c'*64
new['desktop']['docs/DESKTOP-INSTALL.md']='d'*64
new['desktop']['desktop/files/boot/ext4-geometry.sh']='e'*64
self.assertEqual(installer.resume_payload_id(old),installer.resume_payload_id(new))
for field in ('boot-linux.img','mu300-openwrt.tar.gz','rootfs.requirements','busybox'):
changed=copy.deepcopy(new);changed['magisk']['payload/'+field]='e'*64
@@ -423,9 +424,10 @@ desktop_free_loop
def test_boot_append_leaves_kernel_original_frame_and_log_tail_intact(self):
with tempfile.TemporaryDirectory() as t:
assets=Path(t);(assets/'repair').mkdir()
for n in ('storage.sh','install-part.sh','part-prepare.sh','part-progress.sh','mu300-gpt'):
for n in ('storage.sh','install-part.sh','part-prepare.sh','part-progress.sh','ext4-geometry.sh','mu300-gpt'):
(assets/n).write_bytes((TOP/'desktop/boot'/n).read_bytes())
for n,source in (('original-init',TOP/'boot/init'),('build-boot-image.py',TOP/'boot/build-boot-image.py')):(assets/n).write_bytes(source.read_bytes())
(assets/'internal-ext4.sh').write_bytes((TOP/'boot/internal-ext4.sh').read_bytes())
(assets/'repair/manifest.json').write_text('{"sha256":{}}')
ram=frame(b'original ramdisk');kernel=b'K'*4096
base=bytearray(64<<20);base[:8]=b'ANDROID!';struct.pack_into('<II',base,8,len(kernel),len(ram));struct.pack_into('<I',base,40,4)
@@ -439,6 +441,8 @@ desktop_free_loop
rs=struct.unpack_from('<I',out,12)[0]
streams=unpack_frames(out[8192:8192+rs]);self.assertEqual(streams[0],b'original ramdisk')
contents=cpio_files(streams[-1]);self.assertEqual(contents['etc/mu300-desktop-root-mode'],(mode+'\n').encode())
self.assertEqual(contents['etc/ext4-geometry.sh'],(assets/'ext4-geometry.sh').read_bytes())
self.assertEqual(contents['etc/mu300-internal-ext4.sh'],(assets/'internal-ext4.sh').read_bytes())
if mode=='prepare':self.assertEqual(contents['etc/mu300-desktop-prepare'],b'request\n')
else:
self.assertNotIn('etc/mu300-desktop-prepare',contents)
+61
View File
@@ -0,0 +1,61 @@
"""Real offline ext4 growth on sparse files; never operates on hardware."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from helpers import TOP, shells
CHECKER=TOP/'desktop/boot/ext4-geometry.sh'
@unittest.skipUnless(os.name=='posix' and all(shutil.which(n) for n in ('mkfs.ext4','resize2fs','e2fsck','debugfs')), 'Linux ext4 tools required')
class Geometry(unittest.TestCase):
def verify(self,shell,image,sectors):
return subprocess.run(shell+['-c','. "$1"; ext4_verify_grown "$2" "$3"','verify',str(CHECKER),str(image),str(sectors)],capture_output=True,text=True)
def test_exact_and_tiny_tail_growth_preserves_contents(self):
with tempfile.TemporaryDirectory() as temp:
root=Path(temp);image=root/'root.ext4';proof=root/'proof';proof.write_text('OpenWrt firmware proof')
subprocess.run(['mkfs.ext4','-q','-F','-b','4096',str(image),'128M'],check=True,capture_output=True)
subprocess.run(['debugfs','-w','-R',f'write {proof} /proof',str(image)],check=True,capture_output=True)
for wanted,actual in [(65536,65536),(65787,65536),(81920,81920)]:
with image.open('r+b') as f:f.truncate(wanted*4096)
subprocess.run(['resize2fs',str(image)],check=True,capture_output=True)
subprocess.run(['e2fsck','-fn',str(image)],check=True,capture_output=True)
with image.open('rb') as f:f.seek(1028);self.assertEqual(int.from_bytes(f.read(4),'little'),actual)
for shell in shells():
result=self.verify(shell,image,wanted*8)
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
self.assertEqual(subprocess.check_output(['debugfs','-R','cat /proof',str(image)],stderr=subprocess.DEVNULL),proof.read_bytes())
for sectors in [32768*8,10*32768*8]:
for shell in shells():self.assertNotEqual(self.verify(shell,image,sectors).returncode,0)
def test_initramfs_worker_reaches_valid_partial_group_and_rejects_noop(self):
with tempfile.TemporaryDirectory() as temp:
root=Path(temp);image=root/'root.ext4';loader=root/'loader'
loader.write_text('#!/bin/sh\nshift 2\nexec "$@"\n');loader.chmod(0o755)
source=(TOP/'desktop/boot/part-progress.sh').read_text().replace('/etc/ext4-geometry.sh',str(CHECKER))
source=source.replace('/repair/lib/ld-musl-aarch64.so.1',str(loader)).replace('/repair/usr/sbin/resize2fs',shutil.which('resize2fs')).replace('/repair/usr/sbin/e2fsck',shutil.which('e2fsck')).replace('/run/part-growfs.log',str(root/'grow.log'))
for shell in shells():
image.unlink(missing_ok=True)
subprocess.run(['mkfs.ext4','-q','-F','-b','4096',str(image),'128M'],check=True,capture_output=True)
with image.open('r+b') as f:f.truncate(65792*4096)
result=subprocess.run(shell+['-c',source+'\npart_grow_ext4 "$1" 526336','fixture',str(image)],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stderr+(root/'grow.log').read_text())
noop=root/'noop';noop.write_text('#!/bin/sh\nexit 0\n');noop.chmod(0o755)
result=subprocess.run(shell+['-c',source.replace(shutil.which('resize2fs'),str(noop))+'\npart_grow_ext4 "$1" 2621440','fixture',str(image)],capture_output=True,text=True)
self.assertNotEqual(result.returncode,0)
def test_missing_helper_stops_desktop_workers_before_any_write(self):
with tempfile.TemporaryDirectory() as temp:
root=Path(temp);(root/'desktop-settings.env').touch()
for name in ('android-write-part.sh','android-write-free.sh'):
result=subprocess.run(['busybox','ash',str(TOP/'desktop'/name)],env=dict(os.environ,MU300_PAYLOAD_DIR=str(root),MU300_INSTALL_TMP=str(root)),capture_output=True,text=True)
self.assertNotEqual(result.returncode,0)
self.assertIn('ext4-geometry.sh',result.stderr)
self.assertFalse((root/'openwrt.ext4.new').exists())
if __name__=='__main__':unittest.main()
+80
View File
@@ -0,0 +1,80 @@
"""Execute generic init storage selection with fake sysfs and regular files."""
from helpers import TOP, ShellTest
INIT=(TOP/'boot/init').read_text()
class GenericRoot(ShellTest):
def setUp(self):
super().setUp()
self.dev=self.tmp/'dev';self.dev.mkdir()
self.sys=self.tmp/'sys';self.run=self.tmp/'run';self.run.mkdir()
self.etc=self.tmp/'etc';self.etc.mkdir()
(self.etc/'mu300-internal-ext4.sh').write_bytes((TOP/'boot/internal-ext4.sh').read_bytes())
(self.sys/'block/mmcblk0/device').mkdir(parents=True)
(self.sys/'block/mmcblk0/device/type').write_text('MMC\n')
self.part('mmcblk0p76','mu300root','mu300root')
def part(self,name,partname,label):
disk=name.split('p')[0]
p=self.sys/'block'/disk/name;p.mkdir(parents=True,exist_ok=True)
(p/'uevent').write_text('PARTNAME='+partname+'\n')
raw=bytearray(4096);raw[1080:1082]=bytes.fromhex('53ef');raw[1144:1144+len(label)]=label.encode()
(self.dev/name).write_bytes(raw)
def local(self,text):
return text.replace('/sys/',str(self.sys)+'/').replace('/dev/',str(self.dev)+'/').replace('/run/',str(self.run)+'/').replace('/etc/',str(self.etc)+'/').replace('[ -b ','[ -f ')
def test_only_unique_internal_partition_with_exact_ext4_label_is_selected(self):
start=INIT.index('find_gpt_root() {');function=self.local(INIT[start:INIT.index('\n}',start)+2])
for shell in self.each_shell():
for case,want in [('good',True),('prefix',False),('duplicate',False),('not-mmc',False)]:
self.part('mmcblk0p76','mu300root','mu300rootX' if case=='prefix' else 'mu300root')
self.part('mmcblk1p1','mu300root','mu300root')
(self.sys/'block/mmcblk0/device/type').write_text('SD\n' if case=='not-mmc' else 'MMC\n')
extra=self.sys/'block/mmcblk0/mmcblk0p77/uevent'
extra.unlink(missing_ok=True)
if case=='duplicate':self.part('mmcblk0p77','mu300root','mu300root')
r=self.sh(shell,function+'\nfind_gpt_root')
self.assertEqual(r.returncode,0 if want else 1,r.stderr)
self.assertEqual(r.stdout.strip(),str(self.dev/'mmcblk0p76') if want else '')
def test_explicit_desktop_partition_overrides_old_tf_marker(self):
start=INIT.index('# A TF-only image must never fall through')
end=INIT.index('# busybox mount only',start)
code=self.local(INIT[start:end]).replace('/disk',str(self.tmp/'disk')).replace('/newroot',str(self.tmp/'newroot'))
card=self.dev/'mmcblk1p1';card.write_bytes(bytearray(4096))
p=self.sys/'class/block/mmcblk1p1';p.mkdir(parents=True);(p/'size').write_text('8192\n')
prefix='''log(){ :; }
sleep(){ echo sleep >> "$STUBLOG/events"; }
mdev(){ :; }
setup_usb_gadget(){ :; }
read_usb_boot_policy(){ :; }
find_root_offset(){ echo region >> "$STUBLOG/events"; [ "$REGION" = 1 ] && { echo 4096; return 0; }; return 1; }
find_gpt_root(){ echo part >> "$STUBLOG/events"; [ "$PART" = 1 ] && { echo "$GPPATH"; return 0; }; return 1; }
mount(){ [ "$MOUNT_FAIL" != 1 ]; }
ROOT_OFFSET=4096
'''
cases=[('part','sd',1,1,0,True),('part','sd',1,1,1,False),('part','sd',1,0,0,False),
('','sd',1,1,0,False),('','',0,1,0,True),('','',1,1,0,False)]
for shell in self.each_shell():
for mode,target,region,part,fail,mounted in cases:
(self.etc/'mu300-desktop-root-mode').write_text(mode+'\n');(self.etc/'mu300-root-target').write_text(target+'\n')
events=self.tmp/'events';events.unlink(missing_ok=True)
r=self.sh(shell,prefix+code+'\necho "result=$root_mounted internal=$internal_root"',
REGION=region,PART=part,MOUNT_FAIL=fail,GPPATH=self.dev/'mmcblk0p76')
self.assertEqual(r.returncode,0,r.stderr)
self.assertIn('result='+str(int(mounted)),r.stdout)
calls=events.read_text().splitlines() if events.exists() else []
if mode=='part':
self.assertEqual(calls,['part'])
self.assertIn('internal=',r.stdout)
elif target=='sd':self.assertEqual(calls,[])
elif region:self.assertEqual(calls,['region'])
raw=bytearray(4096);raw[1080:1082]=bytes.fromhex('53ef');raw[1144:1152]=b'mu300sd\0';card.write_bytes(raw)
(self.etc/'mu300-desktop-root-mode').write_text('');(self.etc/'mu300-root-target').write_text('')
events.unlink(missing_ok=True)
r=self.sh(shell,prefix+code+'\necho "result=$root_mounted"',REGION=1,PART=1,MOUNT_FAIL=0,GPPATH=self.dev/'mmcblk0p76')
self.assertEqual(r.returncode,0,r.stderr);self.assertIn('result=1',r.stdout)
self.assertFalse(events.exists(),'valid TF must win without probing internal roots')
card.write_bytes(bytearray(4096))
+59
View File
@@ -0,0 +1,59 @@
"""Compile/execute the patch's real fallback function against fake MMC caps."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from helpers import TOP
class Timing(unittest.TestCase):
@unittest.skipUnless(shutil.which('cc'),'C compiler required')
def test_failed_mode_only_and_card_removal_preserves_capabilities(self):
patch=(TOP/'upstream/patches/0021-mmc-failed-timing-falls-back.patch').read_text()
code='\n'.join(line[1:] for line in patch.splitlines() if line.startswith(('+',' ')) and not line.startswith('+++'))
start=code.index('static void mmc_timing_fallback(')
function=code[start:code.index('\n}',start)+2]
before=r'''
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#define EXT_CSD_CARD_TYPE_HS400ES 1
#define EXT_CSD_CARD_TYPE_HS200 2
#define EXT_CSD_CARD_TYPE_HS400 4
#define EXT_CSD_CARD_TYPE_DDR_52 8
#define MMC_CAP2_HS400_ES 1
#define MMC_CAP2_HS200 6
#define MMC_CAP2_HS400 24
#define MMC_CAP_DDR 3
struct mmc_host {unsigned caps,caps2;};
struct mmc_card {struct mmc_host *host; unsigned mmc_avail_type; struct {unsigned raw_card_type;} ext_csd;};
static unsigned warnings; static const char *last_failed,*last_next;
static const char *mmc_hostname(struct mmc_host *h){(void)h;return "mmc0";}
#define pr_warn(fmt,name,failed,error,next) do {(void)(fmt);(void)(name);(void)(error);warnings++;last_failed=failed;last_next=next;} while(0)
'''
after=r'''
int main(void) {
struct mmc_host h={.caps=MMC_CAP_DDR,.caps2=31};
struct mmc_card c={.host=&h,.mmc_avail_type=1|2|4|8,.ext_csd={.raw_card_type=2|8}};
mmc_timing_fallback(&c,-ENOMEDIUM); assert(h.caps2==31&&h.caps==3&&!warnings);
mmc_timing_fallback(&c,-EILSEQ); assert(h.caps2==6&&h.caps==3&&warnings==1);
assert(!strcmp(last_failed,"HS400ES")&&!strcmp(last_next,"HS200"));
c.mmc_avail_type=2|8; mmc_timing_fallback(&c,-EIO);
assert(h.caps2==0&&h.caps==3&&warnings==2&&!strcmp(last_next,"HS/DDR52"));
c.mmc_avail_type=8; mmc_timing_fallback(&c,-EILSEQ);
assert(!h.caps&&!h.caps2&&warnings==3&&!strcmp(last_failed,"DDR52")&&!strcmp(last_next,"HS"));
c.mmc_avail_type=0;mmc_timing_fallback(&c,-EIO);assert(warnings==3);
h.caps=0;h.caps2=31;c.mmc_avail_type=1;c.ext_csd.raw_card_type=0;
mmc_timing_fallback(&c,-EIO);assert(!strcmp(last_next,"HS"));
puts("PASS: only failed timing removes capabilities, removal untouched, complete ladder and supported-card modes");
return 0;
}
'''
with tempfile.TemporaryDirectory() as directory:
source=Path(directory)/'test.c';binary=Path(directory)/'test'
source.write_text(before+function+after)
subprocess.run(['cc','-Wall','-Wextra','-Werror',str(source),'-o',str(binary)],check=True,capture_output=True)
result=subprocess.run([str(binary)],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
+38 -13
View File
@@ -36,10 +36,10 @@ esac""")
for shell in self.each_shell():
self.apply(shell,'online-5g');self.apply(shell,'wifi-on')
self.assertEqual([self.value(n) for n in ['net_blue','zte-ldo0','zte-ldo1','zte-ldo2']],['0','1','1','0'])
self.assertEqual(self.value('sc27xx:blue'),'255');self.assertEqual(self.value('sc27xx:green'),'0')
self.assertEqual(self.value('sc27xx:green'),'255');self.assertEqual(self.value('sc27xx:blue'),'0')
self.apply(shell,'online-4g')
self.assertEqual(self.value('net_blue'),'1');self.assertEqual(self.value('zte-ldo0'),'0')
self.assertEqual(self.value('zte-ldo1'),'1');self.assertEqual(self.value('sc27xx:blue'),'255')
self.assertEqual(self.value('zte-ldo1'),'1');self.assertEqual(self.value('sc27xx:green'),'255')
self.apply(shell,'offline');self.assertEqual(self.value('keyboard-backlight'),'1')
self.apply(shell,'wifi-off');self.assertEqual(self.value('zte-ldo1'),'0')
@@ -47,14 +47,15 @@ esac""")
for shell in self.each_shell():
self.apply(shell,'online-5g');self.apply(shell,'wifi-on')
self.apply(shell,'refresh',TEST_SIGNAL='0',TEST_WIFI='0',TEST_BATTERY='0')
self.assertTrue(all(self.value(n)=='0' for n in ['zte-ldo0','zte-ldo1','sc27xx:blue']))
self.assertTrue(all(self.value(n)=='0' for n in ['zte-ldo0','zte-ldo1','sc27xx:green']))
self.apply(shell,'refresh',TEST_BRIGHTNESS='40')
self.assertEqual(self.value('zte-ldo0'),'1');self.assertEqual(self.value('zte-ldo1'),'1');self.assertEqual(self.value('sc27xx:blue'),'40')
self.assertEqual(self.value('zte-ldo0'),'1');self.assertEqual(self.value('zte-ldo1'),'1');self.assertEqual(self.value('sc27xx:green'),'40')
def test_battery_states_and_timeout(self):
for shell in self.each_shell():
(self.battery/'status').write_text('Discharging\n');(self.battery/'capacity').write_text('10\n')
self.apply(shell,'battery');self.assertEqual(self.value('sc27xx:red'),'255')
self.apply(shell,'battery');self.assertEqual(self.value('sc27xx:blue'),'255')
self.assertEqual(self.value('sc27xx:red'),'0')
(self.battery/'status').write_text('Full\n');self.apply(shell,'battery')
self.assertEqual(self.value('sc27xx:green'),'255');self.assertEqual(self.value('sc27xx:red'),'0')
(self.battery/'status').write_text('Discharging\n')
@@ -86,17 +87,41 @@ esac""")
def test_charging_uses_hardware_rise_hold_fall_rest(self):
for shell in self.each_shell():
blue=self.lamps/'sc27xx:blue'
(blue/'trigger').write_text('[none] timer pattern\n');(blue/'hw_pattern').write_text('');(blue/'repeat').write_text('0\n')
self.apply(shell,'battery',TEST_BRIGHTNESS='40')
self.assertEqual((blue/'trigger').read_text().strip(),'pattern')
self.assertEqual((blue/'hw_pattern').read_text().strip(),'0 625 40 750 0 625 0 250')
self.assertEqual((blue/'repeat').read_text().strip(),'-1')
self.assertFalse((blue/'delay_on').exists())
for channel in ('blue','green'):
lamp=self.lamps/('sc27xx:'+channel)
(lamp/'trigger').write_text('[none] timer pattern\n');(lamp/'hw_pattern').write_text('');(lamp/'repeat').write_text('0\n')
for cap, channel, other in [(49,'blue','green'),(50,'green','blue'),(100,'green','blue')]:
(self.battery/'capacity').write_text(str(cap)+'\n')
# Real sysfs retains the list of supported triggers after a
# write; ordinary fixture files must restore that list.
for name in ('blue','green'):
(self.lamps/('sc27xx:'+name)/'trigger').write_text('[none] timer pattern\n')
self.apply(shell,'battery',TEST_BRIGHTNESS='40')
lamp=self.lamps/('sc27xx:'+channel)
self.assertEqual((lamp/'trigger').read_text().strip(),'pattern')
self.assertEqual((lamp/'hw_pattern').read_text().strip(),'0 625 40 750 0 625 0 250')
self.assertEqual((lamp/'repeat').read_text().strip(),'-1')
self.assertEqual(self.value('sc27xx:'+other),'0')
self.assertFalse((lamp/'delay_on').exists())
(self.battery/'status').write_text('Full\n');self.apply(shell,'battery')
self.assertEqual((blue/'trigger').read_text().strip(),'none');self.assertEqual(self.value('sc27xx:green'),'255')
self.assertEqual((self.lamps/'sc27xx:green/trigger').read_text().strip(),'none')
self.assertEqual(self.value('sc27xx:green'),'255');self.assertEqual(self.value('sc27xx:blue'),'0')
(self.battery/'status').write_text('Charging\n')
def test_remaining_charge_color_boundary_never_changes_timeout(self):
for shell in self.each_shell():
(self.battery/'status').write_text('Discharging\n')
self.script(shell,BIN/'mu300-led','wake',**dict(self.extra,TEST_TIMEOUT='60'))
deadline=self.root/'run/mu300/led/.awake-until'
before=deadline.read_text()
for cap, channel in [(0,'blue'),(15,'blue'),(49,'blue'),(50,'green'),(51,'green'),(100,'green')]:
(self.battery/'capacity').write_text(str(cap)+'\n')
self.apply(shell,'battery',TEST_TIMEOUT='60')
self.assertEqual(self.value('sc27xx:'+channel),'255')
self.assertEqual(self.value('sc27xx:red'),'0')
self.assertFalse((self.root/'run/mu300/led/.battery-breathe').exists())
self.assertEqual(deadline.read_text(),before)
def test_unplug_ignores_stale_fgu_charging_and_stays_dark_after_events(self):
for shell in self.each_shell():
online=self.root/'sys/class/power_supply/bq256xx-charger/online'
+1
View File
@@ -244,6 +244,7 @@ class Update(ShellTest):
self.assertEqual('v50' in boards,expected)
self.assertIn('f50',boards)
self.assertIn('u30air',boards)
self.assertEqual((stage/'b/features').read_text().splitlines(),['sdcard','linux-slot','gpt-root'])
if __name__ == '__main__':
+167
View File
@@ -0,0 +1,167 @@
"""Real updater/boot selection against temporary files; no devices or network."""
import hashlib
import io
import struct
import subprocess
import tarfile
import zlib
from pathlib import Path
from helpers import BIN, TOP, ShellTest
def bundle(path, features='', module=b'new module'):
files={'./Image': b'new kernel', './ramdisk-generic.lz4': b'\x02\x21\x4c\x18generic',
'./devices': b'f50 u30air v50\n', './kernel.release': b'7.2.8\n',
'./modules/driver.ko': module, './modules.builtin': b'driver builtin\n'}
if features: files['./features']=features.encode()
with tarfile.open(path,'w:gz') as archive:
directory=tarfile.TarInfo('./modules');directory.type=tarfile.DIRTYPE;directory.mode=0o755;archive.addfile(directory)
for name,data in files.items():
info=tarfile.TarInfo(name);info.size=len(data);archive.addfile(info,io.BytesIO(data))
class UpdateBase(ShellTest):
def setUp(self):
super().setUp()
self.root=self.tmp/'root';(self.root/'run/mu300').mkdir(parents=True)
self.disk=self.tmp/'disk';(self.disk/'openwrt/etc/mu300').mkdir(parents=True)
(self.disk/'.mu300-update').mkdir()
(self.disk/'openwrt/etc/mu300/image-version').write_text('old\n')
self.plain=self.tmp/'plain.tar.gz';bundle(self.plain)
self.gpt=self.tmp/'gpt.tar.gz';bundle(self.gpt,'sdcard\ngpt-root\n')
def up(self,shell,code,**env):
return self.sh(shell,f'. "{BIN}/mu300-update"; '+code,MU300_LIB=1,MU300_DISK=self.disk,
MU300_SYSROOT=self.root,MU300_BIN=BIN,**env)
class Layouts(UpdateBase):
def test_actual_trial_updates_only_misc_and_does_not_change_saved_default(self):
run=self.tmp/'trial-run';(run/'mu300').mkdir(parents=True)
area=self.tmp/'trial-disk';(area/'.mu300').mkdir(parents=True)
conf=self.tmp/'default-boot';misc=self.tmp/'misc';script=self.tmp/'next-boot'
source=(BIN/'mu300-next-boot').read_text().replace('/run/',str(run)+'/')
source=source.replace('/mnt/mu300-disk',str(area)).replace('CONF=/etc/mu300/default-boot','CONF='+str(conf))
script.write_text(source)
(run/'mu300/misc-dev').write_text(str(misc)+'\n')
(area/'.mu300/boot-attempts').write_text('3\n')
for slot in ('a','b'):
bc=bytearray(32);bc[:4]=('_'+slot).encode()+b'\0\0';bc[4:10]=b'BCAB\x01\x02'
bc[12],bc[14]=(0x2f,0x9e) if slot=='a' else (0x9e,0x2f)
struct.pack_into('<I',bc,28,zlib.crc32(bc[:28]))
(run/'mu300/linux-slot').write_text(slot+'\n')
(run/'mu300/misc-bc-linux-trial.bin').write_bytes(bc)
(run/'mu300/misc-bc-android.bin').write_bytes(bc)
for default in ('android','linux',None):
conf.unlink(missing_ok=True)
if default:conf.write_text(default+'\n')
(area/'.mu300/boot-tries').write_text('8\n')
before=b'P'*4096;misc.write_bytes(before)
result=subprocess.run(['bash',str(script),'--trial'],capture_output=True,text=True,timeout=10)
self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual(conf.read_text() if conf.exists() else None,default+'\n' if default else None)
after=misc.read_bytes();self.assertEqual(after[:2048],before[:2048]);self.assertEqual(after[2080:],before[2080:])
block=after[2048:2080];self.assertEqual(block[12 if slot=='a' else 14],0x4f)
self.assertEqual(struct.unpack_from('<I',block,28)[0],zlib.crc32(block[:28]))
self.assertEqual((area/'.mu300/boot-tries').read_text(),'0\n')
def test_root_device_detection_does_not_mount_userdata(self):
sys=self.root/'sys/class/block'
for name,back in [('loop0','/dev/mmcblk0'),('loop1','/mu300-data/mu300linux/openwrt.ext4')]:
p=sys/name/'loop';p.mkdir(parents=True);(p/'backing_file').write_text(back+'\n')
p=sys/'mmcblk0p76';p.mkdir();(p/'uevent').write_text('PARTNAME=mu300root\n')
p=sys/'mmcblk1/device';p.mkdir(parents=True);(p/'type').write_text('SD\n')
for shell in self.each_shell():
for dev,want in [('/dev/mmcblk0p76','part'),('/dev/loop0','region'),('/dev/loop1','image'),
('/dev/mmcblk1p1','sd'),('/dev/loop9','unknown'),('/dev/mmcblk0p3','unknown')]:
(self.root/'run/mu300/disk-dev').write_text(dev+'\n')
result=self.up(shell,'mount(){ echo unexpected >&2; return 1; }; root_layout')
self.assertEqual((result.returncode,result.stdout.strip(),result.stderr),(0,want,''))
def test_apply_refuses_before_system_or_module_changes(self):
for shell in self.each_shell():
for layout,archive,ok in [('part',self.plain,False),('part',self.gpt,True),
('image',self.gpt,False),('sd',self.plain,True),('region',self.plain,True),
('part',self.tmp/'missing.tar.gz',False)]:
events=self.tmp/'events';events.unlink(missing_ok=True)
(self.disk/'.mu300-update').mkdir(exist_ok=True)
code='''root_layout(){ echo "$LAYOUT"; }
fetch_verified(){ return 0; }
df(){ printf 'Filesystem K Used Avail\nfake 999999999 0 999999999\n'; }
is_root(){ return 1; }
pause_data(){ echo pause >> "$STUBLOG/events"; }
resume_data(){ :; }
apply_one(){ echo root >> "$STUBLOG/events"; }
boot_update(){ echo boot >> "$STUBLOG/events"; }
apply openwrt
'''
result=self.up(shell,code,MU300_SELF_UPDATED=1,MU300_RELEASE='new',MU300_KERNEL_BUNDLE=archive,LAYOUT=layout)
self.assertEqual(result.returncode,0 if ok else 1,result.stdout+result.stderr)
self.assertEqual(events.read_text().splitlines() if events.exists() else [],['pause','root','boot'] if ok else [])
def test_trial_arming_uses_installed_system_tool(self):
tool=self.disk/'openwrt/opt/mu300/bin/mu300-next-boot';tool.parent.mkdir(parents=True)
tool.write_text('#!/bin/sh\n[ "$1" = --trial ] || exit 1\necho new-tool\n');tool.chmod(0o755)
for shell in self.each_shell():
result=self.up(shell,'running_os(){ echo openwrt; }; unlock_for_trial')
self.assertEqual((result.returncode,result.stdout),(0,'new-tool\n'),result.stderr)
class BootUpdate(UpdateBase):
def fixture(self):
dev=self.tmp/'boot.bin';raw=bytearray(2<<20);raw[:8]=b'ANDROID!'
struct.pack_into('<II',raw,8,4096,4096);struct.pack_into('<I',raw,40,4)
raw[4096:8192]=b'K'*4096;raw[8192:8196]=bytes.fromhex('02214c18')
raw[12288:16384]=b'V'*4096;raw[-64:-60]=b'AVBf'
struct.pack_into('>QQQ',raw,len(raw)-52,12288,12288,4096);dev.write_bytes(raw)
module=self.disk/'openwrt/lib/modules/7.2.8/driver.ko';module.parent.mkdir(parents=True,exist_ok=True);module.write_bytes(b'old module')
return dev,module
def run_boot(self,shell,archive,dev):
code='''part_dev(){ echo "$FAKE_BOOT"; }
this_device(){ echo f50; }
root_layout(){ echo "$LAYOUT"; }
running_os(){ echo openwrt; }
cat(){ case "$1" in /sys/class/block/boot.bin/size) echo 4096;; *) command cat "$@";; esac; }
sync(){ :; }
unlock_for_trial(){ echo trial >> "$STUBLOG/events"; }
write_boot(){
echo write >> "$STUBLOG/events"
command cat "$3" "$4" > "$1"
dd if="$5" of="$1" bs=64 seek=$(($2/64-1)) conv=notrunc 2>/dev/null
}
boot_update test
'''
return self.up(shell,code,MU300_KERNEL_BUNDLE=archive,FAKE_BOOT=dev,LAYOUT='part')
def test_changed_modules_in_local_bundle_cannot_be_silently_skipped(self):
for shell in self.each_shell():
dev,module=self.fixture();events=self.tmp/'events';events.unlink(missing_ok=True)
bundle(self.gpt,'gpt-root\n',b'module A')
result=self.run_boot(shell,self.gpt,dev);self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual(module.read_bytes(),b'module A')
expected=hashlib.sha256(self.gpt.read_bytes()).hexdigest()
self.assertEqual((self.disk/'boot/installed.id').read_text().strip(),expected)
count=events.read_text().count('write')
result=self.run_boot(shell,self.gpt,dev);self.assertEqual(result.returncode,0,result.stderr)
self.assertIn('already up to date',result.stdout)
self.assertEqual(events.read_text().count('write'),count)
bundle(self.gpt,'gpt-root\n',b'module B')
result=self.run_boot(shell,self.gpt,dev);self.assertEqual(result.returncode,0,result.stderr)
self.assertNotIn('already up to date',result.stdout)
self.assertEqual(module.read_bytes(),b'module B')
self.assertEqual(events.read_text().count('write'),count+1)
def test_incompatible_layout_and_invalid_boot_leave_modules_untouched(self):
for shell in self.each_shell():
for bad in ('layout','header'):
dev,module=self.fixture();events=self.tmp/'events';events.unlink(missing_ok=True)
if bad=='header':
with dev.open('r+b') as stream:stream.write(b'bad boot')
before=dev.read_bytes()
result=self.run_boot(shell,self.plain if bad=='layout' else self.gpt,dev)
self.assertNotEqual(result.returncode,0,result.stdout+result.stderr)
self.assertEqual(module.read_bytes(),b'old module')
self.assertEqual(dev.read_bytes(),before)
self.assertFalse(events.exists())
+3
View File
@@ -103,6 +103,9 @@ case "$*" in
esac
exit 0
''')
# Some BusyBox builds prefer internal applets over PATH. A shell
# function must win so this fixture can never call the host's ip.
source='ip() { "$STUBLOG/stubs/ip" "$@"; }\n'+source
for shell in self.each_shell():
for address in ('192.168.77.1/24', '192.168.77.1/16', '192.168.88.1/24'):
for name in ('bridged', 'ip-calls'):
+84
View File
@@ -0,0 +1,84 @@
"""Actual ucode patch/capability parsing and generated LuCI controls, offline."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import time
import unittest
import uuid
from helpers import TOP
FEATURE=TOP/'openwrt/luci-app-mu300'
IMAGE=os.environ.get('MU300_WIFI_TEST_IMAGE')
@unittest.skipUnless(IMAGE and shutil.which('docker'),'MU300_WIFI_TEST_IMAGE required')
class UcodeCiphers(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp=tempfile.TemporaryDirectory(prefix='mu300-ciphers-');cls.fixture=Path(cls.temp.name)
cls.name='mu300-ciphers-'+uuid.uuid4().hex[:8]
subprocess.run(['docker','run','-d','--network','none','--platform','linux/arm64','--name',cls.name,
'-v',str(FEATURE/'root')+':/feature:ro','-v',str(cls.fixture)+':/fixture',
'-v',str(FEATURE/'root/usr/libexec/unisoc-modem')+':/usr/libexec/unisoc-modem:ro',IMAGE,'sleep','3600'],check=True,stdout=subprocess.DEVNULL)
@classmethod
def tearDownClass(cls):
subprocess.run(['docker','rm','-f',cls.name],check=True,stdout=subprocess.DEVNULL);cls.temp.cleanup()
def run_ucode(self,*args):
return subprocess.run(['docker','exec',self.name,'ucode',*args],capture_output=True,text=True,timeout=30)
def test_parse_real_suite_ids_and_unknown_radio(self):
program='''import { parse, capabilities } from '/usr/libexec/unisoc-modem/wifi-ciphers.uc';
const text='Supported Ciphers:\\n * CCMP-128 (00-0f-ac:4)\\n * GCMP-256 (00-0f-ac:9)\\nAvailable Antennas:\\n * fake (00-0f-ac:8)';
print(sprintf('%J', {suites:parse(text), unknown:capabilities('radio;reboot'), missing:capabilities('radio0')}));'''
result=self.run_ucode('-e',program)
self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual(json.loads(result.stdout),{'suites':['00-0f-ac:4','00-0f-ac:9'],'unknown':{},'missing':{}})
def test_actual_view_patch_idempotence_and_frontend(self):
source=os.environ.get('MU300_WIFI_TEST_WIRELESS')
if not source:self.skipTest('MU300_WIFI_TEST_WIRELESS required')
target=self.fixture/'root/www/luci-static/resources/view/network/wireless.js';target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(Path(source).read_bytes())
script='/feature/usr/libexec/unisoc-modem/filter-wifi-ciphers'
result=self.run_ucode(script,'/fixture/root');self.assertEqual(result.returncode,0,result.stderr)
first=target.read_bytes();result=self.run_ucode(script,'/fixture/root');self.assertEqual(result.returncode,0,result.stderr);self.assertEqual(first,target.read_bytes())
subprocess.run(['node','--check',str(target)],check=True)
text=target.read_text();start=text.rfind('o=',0,text.index("'cipher',"));end=text.index('const crypto_modes',start)
code=text[start:end]
module=(FEATURE/'htdocs/luci-static/resources/mu300/wifi-ciphers.js').read_text()
program='''const assert=require('assert');const [source,module]=JSON.parse(process.argv[1]);
const support=new Function('fs','L','_',module)({}, {env:{lang:'zh-cn'}},x=>x);
const factory=new Function('ss','form','_','uci','mu300CipherSupport','mu300CipherCaps','let o;'+source+';return o;');
function controls(suites,saved='psk2') {const opt={keylist:[],vallist:[],depends(){},value(v,label){this.keylist.push(v);this.vallist.push(label)}};return factory({children:[{option:'encryption',write(){}}],taboption(){return opt}},{ListValue:{}},x=>x,{get(){return saved}},support,{suites});}
const native=controls(['00-0f-ac:2','00-0f-ac:4']);assert.deepStrictEqual(native.keylist,['auto','ccmp','tkip','tkip+ccmp']);assert.strictEqual(native.validate('id','ccmp'),true);
for(const c of ['gcmp','gcmp256','ccmp256']) {const old=controls(['00-0f-ac:4'],'sae+'+c);assert.strictEqual(old.cfgvalue('id'),c);assert(old.keylist.includes(c));assert.strictEqual(typeof old.validate('id',c),'string');old.cfgvalue('id');assert.strictEqual(old.keylist.filter(v=>v===c).length,1);assert.strictEqual(old.keylist.length,old.vallist.length);}
const other=controls(['00-0f-ac:4','00-0f-ac:8','00-0f-ac:9','00-0f-ac:10']);assert.deepStrictEqual(other.keylist,['auto','ccmp','ccmp256','gcmp','gcmp256']);assert.strictEqual(other.validate('id','gcmp'),true);
assert.strictEqual(controls(undefined).keylist.length,7);
'''
subprocess.run(['node','-e',program,json.dumps([code,module])],check=True)
# Removing the optional package must not leave a dangling LuCI import.
result=self.run_ucode(script,'/fixture/root','--remove');self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual(target.read_bytes(),Path(source).read_bytes())
result=self.run_ucode(script,'/fixture/root','--remove');self.assertEqual(result.returncode,0,result.stderr)
def test_patch_failure_does_not_write_partial_view(self):
target=self.fixture/'bad/www/luci-static/resources/view/network/wireless.js';target.parent.mkdir(parents=True,exist_ok=True);target.write_text("'use strict';unrecognized source")
before=target.read_bytes();r=self.run_ucode('/feature/usr/libexec/unisoc-modem/filter-wifi-ciphers','/fixture/bad')
self.assertNotEqual(r.returncode,0);self.assertEqual(before,target.read_bytes())
def test_live_bus_without_radio_does_not_break_the_view(self):
subprocess.run(['docker','exec',self.name,'sh','-c','mkdir -p /run /var/run/ubus; ubusd >/tmp/wifi-cipher-ubus.log 2>&1 &'],check=True)
for _ in range(30):
if subprocess.run(['docker','exec',self.name,'ubus','list'],capture_output=True).returncode==0:break
time.sleep(.1)
else:self.fail('Fixture ubus did not start')
result=self.run_ucode('-e',"import { capabilities } from '/usr/libexec/unisoc-modem/wifi-ciphers.uc'; print(sprintf('%J', capabilities('radio0')));")
self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual(json.loads(result.stdout),{})
if __name__=='__main__':unittest.main()
+1
View File
@@ -63,5 +63,6 @@ if grep -qx 'CONFIG_LEDS_AW9523B=y' "$UO/kernel.config"; then
devices="$devices v50"
fi
echo "$devices" > "$W/b/devices"
printf 'sdcard\nlinux-slot\ngpt-root\n' > "$W/b/features"
tar -C "$W/b" -czf "$OUT" .
echo "$OUT: kernel $krel, $(ls "$W/b/modules" | wc -l | tr -d ' ') modules, ramdisk segment $(wc -c < "$W/b/ramdisk-generic.lz4" | tr -d ' ') bytes"
@@ -0,0 +1,103 @@
mmc: retry a failed eMMC timing at the next lower supported mode
Adapted from dikeckaan/mu300-linux PR #283 (2026-10-17):
https://github.com/dikeckaan/mu300-linux/pull/283
Preserve normal HS400ES operation. Only failed timing initialisation lowers
host capabilities before the existing rescan retries. No new sleeps/retries,
no SD changes, and no production fault-injection parameter.
--- a/drivers/mmc/core/mmc.c
+++ b/drivers/mmc/core/mmc.c
@@ -1549,6 +1549,50 @@
__func__, err);
}
return err;
+}
+
+/*
+ * A bus timing that failed to come up is not tried again on this host: the
+ * next initialisation (mmc_rescan's next attempt, a reset or a resume) takes
+ * the next slower one, HS400ES -> HS200 -> HS/DDR52 -> HS. Some eMMC and host
+ * pairs fail the HS400ES switch with CRC errors at a cold boot and work at
+ * HS200; without this the card was given up after mmc_rescan's attempts, every
+ * one of them at HS400ES. The new card line ("new HS200 MMC card") tells which
+ * timing was taken in the end.
+ */
+static void mmc_timing_fallback(struct mmc_card *card, int err)
+{
+ struct mmc_host *host = card->host;
+ const char *failed, *next;
+
+ if (err == -ENOMEDIUM)
+ return;
+
+ if (card->mmc_avail_type & EXT_CSD_CARD_TYPE_HS400ES) {
+ host->caps2 &= ~(MMC_CAP2_HS400_ES | MMC_CAP2_HS400);
+ failed = "HS400ES";
+ } else if (card->mmc_avail_type & (EXT_CSD_CARD_TYPE_HS200 |
+ EXT_CSD_CARD_TYPE_HS400)) {
+ host->caps2 &= ~(MMC_CAP2_HS200 | MMC_CAP2_HS400);
+ failed = "HS200";
+ } else if (card->mmc_avail_type & EXT_CSD_CARD_TYPE_DDR_52) {
+ host->caps &= ~MMC_CAP_DDR;
+ failed = "DDR52";
+ } else {
+ return;
+ }
+
+ if (host->caps2 & MMC_CAP2_HS200 &&
+ card->ext_csd.raw_card_type & EXT_CSD_CARD_TYPE_HS200)
+ next = "HS200";
+ else if (host->caps & MMC_CAP_DDR &&
+ card->ext_csd.raw_card_type & EXT_CSD_CARD_TYPE_DDR_52)
+ next = "HS/DDR52";
+ else
+ next = "HS";
+
+ pr_warn("%s: %s failed (%d), the next initialisation uses %s\n",
+ mmc_hostname(host), failed, err, next);
}
/*
@@ -1831,7 +1875,7 @@
*/
err = mmc_select_timing(card);
if (err)
- goto free_card;
+ goto timing_failed;
if (mmc_card_hs200(card)) {
host->doing_init_tune = 1;
@@ -1843,12 +1887,12 @@
host->doing_init_tune = 0;
if (err)
- goto free_card;
+ goto timing_failed;
} else if (mmc_card_hs400es(card)) {
if (host->ops->execute_hs400_tuning) {
err = host->ops->execute_hs400_tuning(host, card);
if (err)
- goto free_card;
+ goto timing_failed;
}
} else {
/* Select the desired bus width optionally */
@@ -1856,7 +1900,7 @@
if (err > 0 && mmc_card_hs(card)) {
err = mmc_select_hs_ddr(card);
if (err)
- goto free_card;
+ goto timing_failed;
}
}
@@ -1963,6 +2007,8 @@
return 0;
+timing_failed:
+ mmc_timing_fallback(card, err);
free_card:
if (!oldcard)
mmc_remove_card(card);