Add UFS installation and resumable online F2FS shrink

Complete U30 Air UFS storage and SIPA lifecycle fixes, carry online preserve-data resizing into the installer, and align SMS, dashboard, release packaging and build documentation. Remove obsolete VPN payload integration.
This commit is contained in:
kanoqwq committed 2026-10-29 22:54:58 +08:00
1 parent 0043a5d87c
commit fe52afe3fc
161 files changed
+4640 -1234

No files matched your search

+3
View File
@@ -1,5 +1,8 @@
# Hardware and modem fixes
- Before adapting UFS hardware, read `docs/UFS-PORTING.zh-CN.md`. It records
the U30 Air investigation, 512/4K geometry contract, trial boot recovery,
and the separate E5/Changxing 60 follow-up. Do not use fastboot.
- Use each model's stock Android firmware behavior as the reference for power,
charging, battery accounting, radio initialization and reconnection.
- Prefer the actual device's driver/RIL binary and device tree over a merely
+1
View File
@@ -160,6 +160,7 @@ def main():
'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),
'etc/mu300-storage.sh': (text(HERE.parent / 'rootfs/overlay/opt/mu300/lib/storage.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():
+14 -15
View File
@@ -148,6 +148,8 @@ load_vendor_modules() {
# misc and boot slots: where they are is known only once the eMMC is there, and its driver (sdhci-sprd) is one of
# the vendor modules - an earlier lookup found nothing (U30 Air: misc-NOT-FOUND, no persistent log). So this runs
# after load_vendor_modules; the opposite Android slot is restored only after the rootfs is known.
. /etc/mu300-storage.sh
internal_disk=
misc=
linux_slot=
detect_linux_slot() {
@@ -172,18 +174,17 @@ find_partitions() {
attempts=200; scan_every=10; fast_wait=1
fi
for n in $(seq 1 "$attempts"); do
for u in /sys/class/block/mmcblk*p*/uevent; do
grep -qx PARTNAME=misc "$u" 2>/dev/null && misc=/dev/$(basename "$(dirname "$u")")
done
internal_disk=$(mu300_storage_disk)
misc_node=$(mu300_storage_part misc "${internal_disk:-__missing__}")
misc=${misc_node:+/dev/$misc_node}
[ -b "$misc" ] && break
if [ "$fast_wait" = 1 ]; then usleep 100000; else sleep 1; fi
[ $((n % scan_every)) != 0 ] || mdev -s
done
[ -b "$misc" ] || misc=
detect_linux_slot || { bootdev=; return 1; }
for u in /sys/class/block/mmcblk*p*/uevent; do
grep -qx "PARTNAME=boot_$linux_slot" "$u" 2>/dev/null && bootdev=/dev/$(basename "$(dirname "$u")")
done
boot_node=$(mu300_storage_part "boot_$linux_slot" "${internal_disk:-__missing__}")
bootdev=${boot_node:+/dev/$boot_node}
[ -b "$bootdev" ] || bootdev=
echo "$bootdev" > /run/bootdev
log "stage=persist-target dev=${bootdev:-none} slot=$linux_slot misc=${misc:-none}"
@@ -397,6 +398,7 @@ root_region_valid() {
# Validate both GPT boundaries BEFORE dd or losetup. Some Android MMC
# drivers wedge on out-of-device reads instead of returning an error (#65).
case $1 in ''|*[!0-9]*) return 1 ;; esac
[ "$internal_disk" = mmcblk0 ] || return 1
disk_sectors=$(cat /sys/block/mmcblk0/size) || return 1
case $disk_sectors in ''|*[!0-9]*) return 1 ;; esac
[ "$1" -gt 0 ] && [ $(( $1 % 512 )) -eq 0 ] || return 1
@@ -437,13 +439,9 @@ find_root_offset() {
# 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 "$internal_disk" ] || return 1
name=$(mu300_storage_part mu300root "$internal_disk") || return 1
candidate=/dev/$name
[ -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
@@ -591,7 +589,7 @@ if [ "$root_mounted" = 1 ] && rootdir=$(pick_root) && [ -n "$rootdir" ]; then
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 ;;
"/dev/${internal_disk}"p[0-9]*|"/dev/${internal_disk}"[0-9]*) echo "$internal_disk@mu300root" > /run/mu300-root-dev ;;
*) [ -z "$sd_root" ] || echo "$sd_root" > /run/mu300-root-dev ;;
esac
echo "$DEVICE" > /run/mu300/device
@@ -681,8 +679,9 @@ log "stage=ready"
A=/android
cp -a $A/dev/__properties__ /dev/__properties__
mkdir -p /dev/block/by-name
for u in /sys/class/block/mmcblk0p*/uevent; do
for u in /sys/class/block/${internal_disk:-__missing__}*/uevent; do
d=$(basename "$(dirname "$u")")
case "$d" in "${internal_disk}"p[0-9]*|"${internal_disk}"[0-9]*) ;; *) continue ;; esac
n=$(sed -n 's/^PARTNAME=//p' "$u")
ln -sf /dev/$d /dev/block/$d
[ -n "$n" ] && ln -sf /dev/$d /dev/block/by-name/$n
+1 -1
View File
@@ -25,7 +25,7 @@ desktop helpers and ADB in `desktop/` and `tools/`.
| start-installer | Choose a method |
| install-to-tf-card | Original TF worker; format the first TF partition, or the whole unpartitioned card |
| install-to-userdata-image | EXPERIMENTAL plaintext userdata image; may damage Android F2FS |
| install-to-internal-storage | Independent `mu300root`; use unallocated eMMC first, otherwise offline userdata shrink |
| install-to-internal-storage | Independent `mu300root`; use unallocated internal storage first, otherwise offline userdata shrink |
| reinstall-internal-system | Erase and reinstall only existing `mu300root` |
| resume-internal-install | Continue after encrypted-data preparation and Android reset |
| switch-to-openwrt | Verify misc and restart into installed Linux |
+4 -3
View File
@@ -6,6 +6,7 @@ set -o pipefail
P=${MU300_PAYLOAD_DIR:?};T=${MU300_INSTALL_TMP:?}
. "$P/desktop-settings.env"
. "$P/ext4-geometry.sh"
. "$P/storage-lib.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.
@@ -15,12 +16,12 @@ P=${MU300_PAYLOAD_DIR:?};T=${MU300_INSTALL_TMP:?}
disk=${1:?disk};cid=${2:?cid};total=${3:?sectors};start=${4:?start};need=${5:?size}
want=${6:?image checksum};front=${7:?GPT front sectors};tail=${8:?GPT backup start}
node=${disk##*/}
case "$disk" in /dev/block/mmcblk[0-9]) ;; *) exit 1 ;; esac
[ -b "$disk" ] || { echo 'eMMC block device required' >&2; exit 1; }
case "$disk" in /dev/block/mmcblk[0-9]*|/dev/block/sd[a-z]*) ;; *) exit 1 ;; esac
[ -b "$disk" ] || { echo 'Internal storage block device required / 需要内置存储块设备' >&2; exit 1; }
for value in "$total" "$start" "$need" "$front" "$tail"; do
case "$value" in ''|*[!0-9]*) exit 1 ;; esac
done
[ "$(cat /sys/class/block/$node/device/cid)" = "$cid" ]
[ "$(mu300_storage_identity "$node")" = "$cid" ]
[ "$(cat /sys/class/block/$node/size)" = "$total" ]
[ "$front" -ge 3 ] && [ "$front" -le 4096 ]
[ "$tail" -ge "$((total-4096))" ] && [ "$tail" -lt "$total" ]
+4 -3
View File
@@ -5,11 +5,12 @@ set -o pipefail
P=${MU300_PAYLOAD_DIR:?};T=${MU300_INSTALL_TMP:?}
. "$P/desktop-settings.env"
. "$P/ext4-geometry.sh"
. "$P/storage-lib.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
node=${dev##*/};disk=$(mu300_storage_parent "$node")
case "$node" in mmcblk[0-9]*p[0-9]*|sd[a-z]*[0-9]) ;; *) exit 1 ;; esac
grep -qx PARTNAME=mu300root "/sys/class/block/$node/uevent"
[ "$(cat /sys/class/block/$disk/device/cid)" = "$expected_cid" ]
[ "$(mu300_storage_identity "$disk")" = "$expected_cid" ]
[ "$(cat /sys/class/block/$node/size)" = "$expected_sectors" ]
[ -z "$(ls -A /sys/class/block/$node/holders)" ]
identity=$(cat /sys/class/block/$node/dev)
+2 -1
View File
@@ -30,7 +30,8 @@ part_fsck() {
install_part_pending() {
. /etc/part-progress.sh
local dev=$1 node=${1##*/} disk=${1%p*}
local dev=$1 node=${1##*/} disk
disk=/dev/$(mu300_storage_parent "$node") || return 1
local mp=/part-install img dft lo rc cur target need low hi pstart pend found out ptarget raw want got datafs dataopts shift
[ -b "$dev" ] || { part_fail 'userdata missing'; return 1; }
# The request: sizes chosen by flash.py on the Android side.
+24 -16
View File
@@ -2,7 +2,7 @@
// The SD card's partition table, for the card install's update (openwrt/device-install-image.sh): OpenWrt
// has no sgdisk, and the card's root is mounted while it runs, so the kernel is not asked to re-read the
// table -- a partition added here is written through the whole disk at its offset, and appears as a node
// at the next boot. GPT only, 512-byte sectors; both copies (primary and backup) are rewritten.
// at the next boot. GPT with 512B/4KiB logical blocks; public geometry uses 512-byte sectors; both copies (primary and backup) are rewritten.
//
// mu300-gpt list DISK N START END NAME, one line per partition
// mu300-gpt uuid DISK N the unique GUID of partition N
@@ -52,15 +52,23 @@ let cmd = ARGV[0], disk = ARGV[1];
if (!(cmd in ['list', 'add', 'uuid', 'plan', 'resize', 'carve-userdata']) || !disk)
die('usage: mu300-gpt list DISK | uuid DISK N | add DISK NAME SECTORS | resize DISK NAME SECTORS | plan DISK NAME:SECTORS ...');
let h = fs.open(disk, (cmd == 'add' || cmd == 'resize' || cmd == 'carve-userdata') ? 'r+' : 'r') || die(`${disk}: ${fs.error()}`);
// Detect real GPT logical blocks before interpreting its LBA fields.
let sizes = [];
for (let size in [512, 4096]) {
h.seek(size, 0);
if (h.read(8) == 'EFI PART') push(sizes, size);
}
if (length(sizes) != 1) die('missing or ambiguous GPT logical block size');
let block = sizes[0], factor = int(block / 512);
function rd(lba, count) {
h.seek(lba * 512, 0);
let s = h.read(count * 512);
if (length(s) != count * 512)
h.seek(lba * block, 0);
let s = h.read(count * block);
if (length(s) != count * block)
die(`${disk}: short read at sector ${lba}`);
return s;
}
function wr(lba, s) {
h.seek(lba * 512, 0);
h.seek(lba * block, 0);
h.write(s) == length(s) || die(`${disk}: write failed at sector ${lba}`);
}
@@ -70,15 +78,15 @@ function load(lba) {
if (substr(hd, 0, 8) != 'EFI PART')
die(`no GPT header at sector ${lba}`);
let hsize = le(hd, 12, 4);
if (hsize < 92 || hsize > 512)
if (hsize < 92 || hsize > block)
die(`odd GPT header size ${hsize}`);
if (crc32(put(substr(hd, 0, hsize), 16, lebytes(0, 4))) != le(hd, 16, 4))
die(`the GPT header at sector ${lba} fails its checksum`);
let g = { lba: lba, hd: hd, hsize: hsize, alt: le(hd, 32, 8), first: le(hd, 40, 8), last: le(hd, 48, 8),
let g = { lba: lba, hd: hd, hsize: hsize, alt: le(hd, 32, 8), first: le(hd, 40, 8) * factor, last: (le(hd, 48, 8) + 1) * factor - 1,
elba: le(hd, 72, 8), num: le(hd, 80, 4), esize: le(hd, 84, 4) };
if (g.esize != 128 || g.num < 1 || g.num > 1024)
die(`odd GPT table (${g.num} entries of ${g.esize} bytes)`);
g.tab = substr(rd(g.elba, int((g.num * 128 + 511) / 512)), 0, g.num * 128);
g.tab = substr(rd(g.elba, int((g.num * 128 + block - 1) / block)), 0, g.num * 128);
if (crc32(g.tab) != le(hd, 88, 4))
die(`the GPT table of the header at sector ${lba} fails its checksum`);
return g;
@@ -102,7 +110,7 @@ for (let i = 0; i < p.num; i++) {
break;
name += (c < 128) ? chr(c) : '?';
}
push(parts, { n: i + 1, start: le(e, 32, 8), end: le(e, 40, 8), name: name });
push(parts, { n: i + 1, start: le(e, 32, 8) * factor, end: (le(e, 40, 8) + 1) * factor - 1, name: name });
}
if (cmd == 'list') {
@@ -145,7 +153,7 @@ function available() {
return gaps;
}
function allocation(name, want) {
if (!match(name ?? '', /^[A-Za-z0-9_-]{1,36}$/) || type(want) != 'int' || want < 2048)
if (!match(name ?? '', /^[A-Za-z0-9_-]{1,36}$/) || type(want) != 'int' || want < 2048 || want % factor)
die('invalid partition request: name and integer size >= 2048 sectors required');
for (let x in parts)
if (x.name == name)
@@ -167,7 +175,7 @@ function allocation(name, want) {
// end: the caller must have shrunk the filesystem inside it first, while it
// was unmounted. Growing may use free space after it and needs no more.
function resize_range(name, want) {
if (type(want) != 'int' || want < 2048)
if (type(want) != 'int' || want < 2048 || want % factor)
die('invalid resize request: an integer size >= 2048 sectors is required');
let target = null;
for (let x in parts)
@@ -222,8 +230,8 @@ if (cmd == 'plan') {
function commit(tab) {
let tcrc = lebytes(crc32(tab), 4);
for (let g in [b, p]) {
let rest = length(tab) % 512;
wr(g.elba, tab + (rest ? substr(rd(g.elba + int(length(tab) / 512), 1), rest) : ''));
let rest = length(tab) % block;
wr(g.elba, tab + (rest ? substr(rd(g.elba + int(length(tab) / block), 1), rest) : ''));
let hd = put(g.hd, 88, tcrc);
hd = put(hd, 16, lebytes(0, 4));
hd = put(hd, 16, lebytes(crc32(substr(hd, 0, g.hsize)), 4));
@@ -235,7 +243,7 @@ function commit(tab) {
if (cmd == 'resize') {
let range = resize_range(ARGV[2], +ARGV[3]);
let entry = substr(p.tab, (range[2] - 1) * 128, 128);
entry = put(entry, 40, lebytes(range[1], 8));
entry = put(entry, 40, lebytes(int((range[1] + 1) / factor) - 1, 8));
commit(put(p.tab, (range[2] - 1) * 128, entry));
h.close();
print(`${ARGV[2]} ${range[2]} ${range[0]} ${range[1]}\n`);
@@ -261,7 +269,7 @@ if (cmd == 'carve-userdata') {
available();
carve = [r[1] + 1, r[1] + root_size];
let entry = substr(p.tab, (r[2] - 1) * 128, 128);
p.tab = put(p.tab, (r[2] - 1) * 128, put(entry, 40, lebytes(r[1], 8)));
p.tab = put(p.tab, (r[2] - 1) * 128, put(entry, 40, lebytes(int((r[1] + 1) / factor) - 1, 8)));
}
let name = carve ? 'mu300root' : ARGV[2], want = +ARGV[3];
let range = carve || allocation(name, want);
@@ -275,7 +283,7 @@ for (let i = 0; i < length(name); i++)
uname += chr(ord(name, i), 0);
// the Linux filesystem type, 0FC63DAF-8483-4772-8E79-3D69D8477DE4, in GPT's byte order
let linux = chr(0xAF, 0x3D, 0xC6, 0x0F, 0x83, 0x84, 0x72, 0x47, 0x8E, 0x79, 0x3D, 0x69, 0xD8, 0x47, 0x7D, 0xE4);
let entry = linux + guid + lebytes(start, 8) + lebytes(end, 8) + lebytes(0, 8) + uname;
let entry = linux + guid + lebytes(int(start / factor), 8) + lebytes(int((end + 1) / factor) - 1, 8) + lebytes(0, 8) + uname;
entry += lebytes(0, 128 - length(entry));
commit(put(p.tab, empty * 128, entry));
h.close();
+5 -4
View File
@@ -28,15 +28,16 @@ $request
EOF
[ -z "$extra" ] && [ "${#token}" = 32 ] && [ "${#cid}" = 32 ] && [ "${#bc}" = 64 ] || part_reject
case "$token$cid$bc" in *[!0-9a-f]*) part_reject ;; esac
case "$node" in mmcblk[0-9]p[0-9]*) ;; *) part_reject ;; esac
case "$node" in mmcblk[0-9]*p[0-9]*|sd[a-z]*[0-9]) ;; *) part_reject ;; esac
case "$node" in *[!a-z0-9]*) part_reject ;; esac
for actual in "$start" "$previous" "$target" "$need"; do
case "$actual" in ''|0*|*[!0-9]*) part_reject ;; esac
[ "${#actual}" -le 12 ] || part_reject
done
dev=/dev/$node disk=/dev/${node%p*}
dev=/dev/$node
disk=/dev/$(mu300_storage_parent "$node") || part_reject
[ -b "$dev" ] && [ -b "$disk" ] && [ -b "$misc" ] || part_reject
[ "$(cat /sys/class/block/${node%p*}/device/cid)" = "$cid" ] || part_reject
[ "$(mu300_storage_identity "${disk##*/}")" = "$cid" ] || part_reject
grep -qx PARTNAME=userdata /sys/class/block/$node/uevent || part_reject
[ "$(cat /sys/class/block/$node/start)" = "$start" ] || part_reject
[ "$(cat /sys/class/block/$node/size)" = "$previous" ] || part_reject
@@ -47,7 +48,7 @@ EOF
*) [ "$target" -ge 4194304 ] && [ "$need" -ge 4194304 ] &&
[ "$((target + need))" -le "$previous" ] || part_reject ;;
esac
for u in /sys/class/block/${node%p*}p*/uevent; do
for u in /sys/class/block/${disk##*/}*/uevent; do
grep -qx PARTNAME=mu300root "$u" && part_reject
done
[ -z "$part_rejected" ] || return 0
+7 -8
View File
@@ -1,13 +1,12 @@
# Desktop-only storage policy; this file is never added to the Magisk boot.
. /etc/mu300-storage.sh
desktop_part() {
local match= u
for u in /sys/class/block/mmcblk*p*/uevent; do
grep -qx "PARTNAME=$1" "$u" 2>/dev/null || continue
[ -z "$match" ] || return 1
match=/dev/$(basename "$(dirname "$u")")
done
[ -n "$match" ] && echo "$match"
local disk node
disk=$(mu300_storage_disk) || return 1
node=$(mu300_storage_part "$1" "$disk") || return 1
printf '/dev/%s\n' "$node"
}
desktop_storage_start() {
DESKTOP_MODE=$(cat /etc/mu300-desktop-root-mode)
DESKTOP_LINUX_BC=/etc/misc-bc-slot-b-trial.bin
@@ -29,7 +28,7 @@ desktop_storage_start() {
local d identity cid node start before target actual
d=$(desktop_part userdata) || { part_fail 'userdata identity'; return 1; }
IFS=: read -r cid node start before target < /etc/mu300-desktop-identity
[ "$d" = "/dev/$node" ] && [ "$cid" = "$(cat /sys/class/block/${node%p*}/device/cid)" ] &&
[ "$d" = "/dev/$node" ] && [ "$cid" = "$(mu300_storage_identity "$(mu300_storage_parent "$node")")" ] &&
[ "$start" = "$(cat /sys/class/block/$node/start)" ] || { part_fail 'wrong installation device'; return 1; }
actual=$(cat /sys/class/block/$node/size)
[ "$actual" = "$before" ] || [ "$actual" = "$target" ] || { part_fail 'userdata geometry changed'; return 1; }
+1
View File
@@ -55,6 +55,7 @@ def build(base, assets, mode, live, android_slot, prepare=None, identity=None):
'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)}
files['etc/mu300-internal-ext4.sh']=((assets/'internal-ext4.sh').read_bytes(),stat.S_IFREG|0o644)
files['etc/mu300-storage.sh']=((assets/'storage-lib.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)
+37 -104
View File
@@ -102,6 +102,8 @@ def payload_rootfs(root,tf=False):
yield target
def package_root():
if Path(__file__).name == 'OpenWrt-Installer.py':
return Path(__file__).resolve().parent
here=Path(sys.executable if getattr(sys,'frozen',False) else __file__).resolve().parent
return here.parent if here.name=='desktop' else here
@@ -136,84 +138,25 @@ def allocation(before, part_mib):
if target<4194304 or need<4194304: raise ValueError('At least 2 GiB is required for each system')
return target,need
def gpt_backup_layout(primary, backup, sectors):
def header(raw,at):
if len(raw)!=512 or raw[:8]!=b'EFI PART':raise ValueError('Invalid GPT header')
size=struct.unpack_from('<I',raw,12)[0]
if not 92<=size<=512:raise ValueError('Invalid GPT header size')
check=bytearray(raw[:size]);expected=struct.unpack_from('<I',check,16)[0];check[16:20]=bytes(4)
if zlib.crc32(check)!=expected:raise ValueError('GPT header checksum failed')
current,alternate=struct.unpack_from('<QQ',raw,24)
table,count,entrysize=struct.unpack_from('<QII',raw,72)
if current!=at or count<1 or count>1024 or entrysize!=128:raise ValueError('Unsupported GPT geometry')
return alternate,table,(count*entrysize+511)//512,raw[56:72],raw[80:92]
a=header(primary,1);b=header(backup,sectors-1)
if a[0]!=sectors-1 or b[0]!=1 or a[3:]!=b[3:]:raise ValueError('GPT copies disagree')
front=a[1]+a[2];tail=b[1]
if not (2<=a[1]<front<=4096 and sectors-4096<=tail and tail+b[2]==sectors-1):raise ValueError('GPT backup range is invalid')
return front,tail
def gpt_space(first,last,sectors):
"""Validate both on-disk GPT copies and return aligned, genuinely unallocated ranges."""
primary=first[512:1024];backup=last[-512:]
front,tail=gpt_backup_layout(primary,backup,sectors)
if len(first)!=front*512 or len(last)!=(sectors-tail)*512:
raise ValueError('Incomplete GPT snapshot')
start,end=struct.unpack_from('<QQ',primary,40)
if (start,end)!=struct.unpack_from('<QQ',backup,40) or not front<=start<=end<tail:
raise ValueError('GPT usable bounds disagree or overlap metadata')
table,count,entry=struct.unpack_from('<QII',primary,72)
data=first[table*512:table*512+count*entry]
if data!=last[:count*entry] or zlib.crc32(data)!=struct.unpack_from('<I',primary,88)[0]:
raise ValueError('GPT table checksum/copy mismatch')
parts=[];empty=[]
for i in range(count):
raw=data[i*entry:(i+1)*entry]
if raw[:16]==bytes(16):empty.append(i);continue
a,b=struct.unpack_from('<QQ',raw,32)
name=raw[56:128].decode('utf-16-le').split('\0',1)[0]
if not start<=a<=b<=end:raise ValueError('GPT partition outside usable bounds: '+name)
parts.append({'n':i+1,'start':a,'end':b,'name':name})
at=start;gaps=[]
for part in sorted(parts,key=lambda p:p['start'])+[{'start':end+1,'end':end}]:
if part['start']<at:raise ValueError('Overlapping GPT partitions')
aligned=(at+2047)//2048*2048
limit=(part['start']//2048)*2048
if limit>aligned:gaps.append((aligned,limit-aligned))
at=part['end']+1
return {'front':front,'tail':tail,'parts':parts,'empty':empty,'gaps':gaps,
'largest':max((size for _,size in gaps),default=0) if empty else 0}
def gpt_add_root(first,last,sectors,offset,need):
info=gpt_space(first,last,sectors)
if any(p['name']=='mu300root' for p in info['parts']):raise ValueError('mu300root already exists')
if not info['empty'] or need<4194304 or offset%2048 or need%2048 or not any(
offset>=a and offset+need<=a+n for a,n in info['gaps']):
raise ValueError('Requested root is not in an aligned GPT free range')
idx=info['empty'][0];entry=bytearray(128)
entry[:16]=uuid.UUID('0fc63daf-8483-4772-8e79-3d69d8477de4').bytes_le
entry[16:32]=uuid.uuid4().bytes_le
struct.pack_into('<QQ',entry,32,offset,offset+need-1)
name='mu300root'.encode('utf-16-le');entry[56:56+len(name)]=name
copies=[]
for raw,header_offset,table_offset in ((first,512,struct.unpack_from('<Q',first,584)[0]*512),(last,len(last)-512,0)):
new=bytearray(raw);new[table_offset+idx*128:table_offset+(idx+1)*128]=entry
count=struct.unpack_from('<I',new,header_offset+80)[0]
struct.pack_into('<I',new,header_offset+88,zlib.crc32(new[table_offset:table_offset+count*128]))
struct.pack_into('<I',new,header_offset+16,0)
hsize=struct.unpack_from('<I',new,header_offset+12)[0]
struct.pack_into('<I',new,header_offset+16,zlib.crc32(new[header_offset:header_offset+hsize]))
copies.append(bytes(new))
gpt_space(*copies,sectors)
return copies
def free_root_range(info,need):
if not info['empty']:return None
# Old MU300 installs may live outside GPT at this fixed raw offset. Such
# an area is retained even though a partition table calls it unallocated.
gaps=info.get('safe_gaps',info['gaps'])
candidates=[(n,a) for a,n in gaps if n>=need]
return max(candidates)[1] if candidates else None
# This script is loaded from the package before Adapter can bind package_root.
# A frozen host's sys.executable is tools/backend, not this external script's
# directory. Resolve sibling resources from __file__ in both host modes.
_entry_path = Path(__file__).resolve()
_support = _entry_path.parent
if _entry_path.name == 'OpenWrt-Installer.py':
_support = _support/'desktop'
elif not (_support/'gpt.py').is_file():
_support = _support.parent/'installer/backend'
_gpt_path = _support/'gpt.py'
_spec=importlib.util.spec_from_file_location('mu300_storage_gpt',_gpt_path)
_gpt=importlib.util.module_from_spec(_spec);_spec.loader.exec_module(_gpt)
gpt_backup_layout=_gpt.gpt_backup_layout
gpt_space=_gpt.gpt_space
gpt_add_root=_gpt.gpt_add_root
free_root_range=_gpt.free_root_range
_storage_path = _gpt_path.with_name('storage.py')
_spec=importlib.util.spec_from_file_location('mu300_storage',_storage_path)
_storage=importlib.util.module_from_spec(_spec);_spec.loader.exec_module(_storage)
def encrypted(properties, source, raw_magic):
# FBE can have a perfectly readable filesystem superblock. A filesystem
@@ -364,24 +307,13 @@ class Android:
print(result,end='');return result
def storage(self):
out=self.shell('set -e; d=$(readlink -f /dev/block/by-name/userdata); n=${d##*/}; b=${n%p*}; '+
'echo NODE=$n; echo CID=$(cat /sys/class/block/$b/device/cid); echo START=$(cat /sys/class/block/$n/start); '+
'echo SIZE=$(cat /sys/class/block/$n/size); echo DISK_SIZE=$(cat /sys/class/block/$b/size); '+
'echo FREE=$(df -Pk /data | tail -n1 | awk \'{print $4}\'); '+
'echo STATE=$(getprop ro.crypto.state); echo TYPE=$(getprop ro.crypto.type); '+
'echo SOURCE=$(awk \'$2=="/data" {print $1;exit}\' /proc/mounts); '+
'echo MAGIC=$(dd if="$d" bs=1 skip=1024 count=4 2>/dev/null | od -An -tx1 | tr -d " \\n"); '+
'echo EXT=$(dd if="$d" bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d " \\n"); '+
'for u in /sys/class/block/${b}p*/uevent; do if grep -qx PARTNAME=mu300root "$u"; then n=${u%/uevent}; echo ROOT=${n##*/}; fi; done')
result=dict(l.split('=',1) for l in out.splitlines() if '=' in l)
if not re.fullmatch(r'mmcblk\d+p\d+',result['NODE']) or not re.fullmatch('[a-f0-9]{32}',result['CID']):raise ValueError('Invalid eMMC identity')
for n in ('START','SIZE','DISK_SIZE','FREE'):result[n]=int(result[n])
return result
return _storage.parse_inventory(self.shell(_storage.inventory_script(package_root())))
def gpt(self,s):
disk='/dev/block/'+s['NODE'].split('p')[0]
primary=self.read(f'dd if={disk} bs=512 skip=1 count=1 2>/dev/null')
backup=self.read(f'dd if={disk} bs=512 skip={s["DISK_SIZE"]-1} count=1 2>/dev/null')
disk='/dev/block/'+_storage.disk_node(s['NODE'])
primary_cmd,backup_cmd=_storage.gpt_header_commands(s)
primary=self.read(primary_cmd)
backup=self.read(backup_cmd)
front,tail=gpt_backup_layout(primary,backup,s['DISK_SIZE'])
first=self.read(f'dd if={disk} bs=512 count={front} 2>/dev/null')
last=self.read(f'dd if={disk} bs=512 skip={tail} count={s["DISK_SIZE"]-tail} 2>/dev/null')
@@ -406,10 +338,10 @@ class Android:
return info
def prepare_payload(self,root,tf=False,with_rootfs=True):
names=['busybox','android-bootchain.sh','bootchain.sh','switch.sh','mu300-vendor-from-device.sh','rootfs-critical.sha256','rootfs.requirements']
names=['storage-lib.sh','busybox','android-bootchain.sh','bootchain.sh','switch.sh','mu300-vendor-from-device.sh','rootfs-critical.sha256','rootfs.requirements']
if tf:names+=['android-install.sh','tf-install-worker.sh','tf-storage.sh','tf-stage.sh','payload.sha256']
for n in names:
source=root/'desktop'/n if n in ('android-bootchain.sh','bootchain.sh') else payload_file(root,n)
source=root/'desktop'/n if n in ('storage-lib.sh','android-bootchain.sh','bootchain.sh') else payload_file(root,n)
self.push(source,n)
if with_rootfs:
with payload_rootfs(root,tf=tf) as archive:
@@ -431,9 +363,10 @@ class Android:
def backup(self,path,s):
path.mkdir(parents=True,exist_ok=False)
path.joinpath('identity.json').write_text(json.dumps({**s,'serial':self.serial,'android_slot':self.slot},indent=2)+'\n')
disk='/dev/block/'+s['NODE'].split('p')[0]
primary=self.read(f'dd if={disk} bs=512 skip=1 count=1 2>/dev/null')
alternate=self.read(f'dd if={disk} bs=512 skip={s["DISK_SIZE"]-1} count=1 2>/dev/null')
disk='/dev/block/'+_storage.disk_node(s['NODE'])
primary_cmd,backup_cmd=_storage.gpt_header_commands(s)
primary=self.read(primary_cmd)
alternate=self.read(backup_cmd)
front,tail=gpt_backup_layout(primary,alternate,s['DISK_SIZE'])
items={'misc-head.bin':'dd if=/dev/block/by-name/misc bs=4096 count=1',
'gpt-first.bin':f'dd if={disk} bs=512 count={front}',
@@ -450,7 +383,7 @@ class Android:
first=path.joinpath('gpt-first.bin').read_bytes();last=path.joinpath('gpt-last.bin').read_bytes()
if len(first)!=front*512 or len(last)!=(s['DISK_SIZE']-tail)*512:raise ValueError('Incomplete GPT backup')
table,count,entry=struct.unpack_from('<QII',primary,72)
primary_table=first[table*512:table*512+count*entry]
primary_table=first[table*s.get('SECTOR_SIZE',512):table*s.get('SECTOR_SIZE',512)+count*entry]
backup_table=last[:count*entry]
if primary_table!=backup_table or zlib.crc32(primary_table)!=struct.unpack_from('<I',primary,88)[0]:raise ValueError('GPT table checksum/copy mismatch')
path.joinpath('SHA256SUMS').write_text(''.join(digest(path/n)+' '+n+'\n' for n in items))
@@ -638,13 +571,13 @@ def install(args,root,manifest):
free_max=space['largest']//2048//4*4
shrink_max=(s['SIZE']//2048-2048)//4*4
maximum=max(free_max,shrink_max)
print(f'eMMC / 闪存: {s["DISK_SIZE"]/2097152:.2f} GiB; GPT unused / 未分配可用: {free_max/1024:.2f} GiB')
print(f'Internal storage / 内置存储: {s["DISK_SIZE"]/2097152:.2f} GiB; GPT unused / 未分配可用: {free_max/1024:.2f} GiB')
size=image_size(args.size or input(f'OpenWrt partition GiB / 分区大小 [4], max {maximum/1024:.2f}: ') or '4',maximum)
offset=free_root_range(space,size*2048)
if offset is not None:
if GUI:GUI.validate_plan('GPT unallocated space',capacity=size*1048576,gap_start=offset)
if args.format_userdata:raise ValueError('Free-space installation preserves userdata; omit --format-userdata')
confirm(f'Use {size/1024:.2f} GiB of unallocated eMMC space; Android userdata is preserved / 使用未分配空间,不缩容、不格式化 Android。Selected raw range will be overwritten / 所选空闲区域原始内容将被覆盖。')
confirm(f'Use {size/1024:.2f} GiB of unallocated internal storage; Android userdata is preserved / 使用未分配空间,不缩容、不格式化 Android。Selected raw range will be overwritten / 所选空闲区域原始内容将被覆盖。')
backup=base/(time.strftime('%Y%m%d-%H%M%S')+'-'+s['CID'][-8:]);a.backup(backup,s)
if (backup/'gpt-first.bin').read_bytes()!=space['first'] or (backup/'gpt-last.bin').read_bytes()!=space['last']:
raise ValueError('GPT changed during preflight; nothing was installed')
@@ -725,7 +658,7 @@ def free_write(a,root,m,manifest,s,space,offset,sectors):
a.run('"$BB" sh "$P/android-image.sh"')
checksum=a.shell('sha256sum '+a.t+'/openwrt.ext4.new').split()[0]
if not re.fullmatch('[a-f0-9]{64}',checksum):raise ValueError('Invalid image checksum')
disk='/dev/block/'+s['NODE'].split('p')[0]
disk='/dev/block/'+_storage.disk_node(s['NODE'])
a.run('"$BB" sh "$P/android-write-free.sh" '+env_args([
disk,s['CID'],s['DISK_SIZE'],offset,sectors,checksum,space['front'],space['tail']]),**({'effect':'root-free-write'} if GUI else {}))
# Independent verification after the device-side comparison, before
@@ -734,7 +667,7 @@ def free_write(a,root,m,manifest,s,space,offset,sectors):
f'dd if={disk} bs=512 skip={space["tail"]} count={s["DISK_SIZE"]-space["tail"]} 2>/dev/null')!=last:
raise ValueError('GPT readback failed; boot selection was not changed')
live=a.live();a.flash(boot(root,m,'part',live,a.slot),m.boot_control(live,a.slot))
return Outcome('success',f'Installed in unallocated eMMC: {sectors/2097152:.2f} GiB; Android preserved / 未分配空间安装完成,Android 数据保留。',
return Outcome('success',f'Installed in unallocated internal storage: {sectors/2097152:.2f} GiB; Android preserved / 未分配空间安装完成,Android 数据保留。',
'Reboot the device manually; the new partition appears after reboot / 手动重启后新分区生效。')
def env_args(values):
+4
View File
@@ -52,6 +52,10 @@ unset MU300_DEPLOY_ROOT
# its original scripts stay byte-for-byte unchanged.
shutil.copyfile(TOP/'tools/android-bootchain.sh', dest/'android-bootchain.sh')
shutil.copyfile(TOP/'installer/backend/windows_mtp.py', dest/'windows_mtp.py')
shutil.copyfile(TOP/'installer/backend/storage.py', dest/'storage.py')
shutil.copyfile(TOP/'installer/backend/gpt.py', dest/'gpt.py')
shutil.copyfile(TOP/'rootfs/overlay/opt/mu300/lib/storage.sh', dest/'storage-lib.sh')
shutil.copyfile(TOP/'rootfs/overlay/opt/mu300/lib/storage.sh', assets/'storage-lib.sh')
shutil.copyfile(TOP/'android/magisk/mu300-linux-switch/bootchain.sh', dest/'bootchain.sh')
for p in (TOP/'desktop/boot').iterdir():
if p.is_file(): shutil.copyfile(p, assets/p.name)
+2 -154
View File
@@ -1,154 +1,2 @@
"""MU300 desktop updates, shared with CLI and older compatible package entries."""
import getpass
import json
import os
from pathlib import Path
import re
import secrets
import struct
import tempfile
LEGACY_LAYOUT_PROBE = '''set -eu
[ / -ef /mnt/mu300-disk/openwrt ] || { echo 'running root is not the MU300 OpenWrt container' >&2; exit 1; }
d=$(readlink -f "$(cat /run/mu300/disk-dev)")
case "$d" in /dev/loop[0-9]*) ;; *) echo 'legacy root is not a loop device' >&2; exit 1 ;; esac
[ -b "$d" ]
n=${d##*/}
id=$(cat /sys/class/block/$n/dev)
awk -v id="$id" '$3 == id && $5 == "/mnt/mu300-disk" {for (i=7;i<=NF;i++) if ($i == "-" && $(i+1) == "ext4") ok=1} END {exit !ok}' /proc/self/mountinfo
backing=$(readlink -f "$(cat /sys/class/block/$n/loop/backing_file)")
[ "$backing" = /dev/mmcblk0 ]
end=0
for p in /sys/class/block/mmcblk0p*; do
[ -r "$p/start" ] || continue
start=$(cat "$p/start"); size=$(cat "$p/size")
case "$start:$size" in *[!0-9:]*|:*|*:) exit 1 ;; esac
next=$((start + size))
[ "$next" -le "$end" ] || end=$next
done
printf 'MU300-LEGACY-LAYOUT-V1\\n%s\\n%s\\n' "$d" "$backing"
cat /sys/class/block/$n/loop/offset /sys/class/block/$n/size /sys/class/block/mmcblk0/size /sys/class/block/$n/loop/sizelimit
printf '%s\\n' "$end"
'''
def legacy_layout(client, root, execute, read_exact):
"""Prove the mounted hidden-area layout using bounded, read-only evidence."""
values = execute(client, LEGACY_LAYOUT_PROBE).strip().splitlines()
if (len(values) != 8 or values[0] != 'MU300-LEGACY-LAYOUT-V1'
or not re.fullmatch(r'/dev/loop[0-9]+', values[1]) or values[2] != '/dev/mmcblk0'
or any(not re.fullmatch(r'[0-9]+', v) for v in values[3:])):
raise ValueError('Cannot verify legacy hidden-area layout / 无法确认旧版隐藏区域布局,已停止更新')
offset, sectors, disk_sectors, limit, partition_end = map(int, values[3:])
if (not offset or offset % 512 or sectors <= 0 or partition_end <= 0
or offset//512 < partition_end or offset//512+sectors > disk_sectors-34
or limit not in (0, sectors*512)):
raise ValueError('Legacy root overlaps GPT partitions or exceeds eMMC bounds / 旧版根区域与分区重叠或超出 eMMC 范围')
# The legacy boot searches the first aligned region after GPT, then its
# saved ROOT_OFFSET. Do not accept a region the packaged boot cannot find.
original = (Path(root)/'desktop/files/boot/original-init').read_text(encoding='utf-8')
defaults = re.findall(r'^ROOT_OFFSET=([0-9]+)\b', original, re.MULTILINE)
offsets = {(partition_end//4096+1)*4096*512, *map(int, defaults)}
if offset not in offsets:
raise ValueError('Packaged legacy boot cannot locate this root offset / 安装包启动逻辑无法定位当前旧版根区域,已停止更新')
superblock = read_exact(client, f'dd if={values[1]} bs=1024 skip=1 count=1 2>/dev/null', 1024)
if (len(superblock) != 1024 or superblock[56:58] != b'\x53\xef'
or superblock[120:136].rstrip(b'\0') != b'mu300root'):
raise ValueError('Legacy root is not a verified mu300root ext4 filesystem / 旧版根区域不是可确认的 mu300root ext4 文件系统')
log_size = struct.unpack_from('<I', superblock, 24)[0]
blocks = struct.unpack_from('<I', superblock, 4)[0]
if struct.unpack_from('<I', superblock, 96)[0] & 0x80:
blocks |= struct.unpack_from('<I', superblock, 336)[0] << 32
capacity = blocks*(1024 << log_size) if log_size <= 6 else 0
if not 0 < capacity <= sectors*512:
raise ValueError('Legacy ext4 capacity exceeds its loop extent / 旧版 ext4 容量超出挂载区域')
return dict(mode='legacy', device=values[1], backing=values[2], offset=offset,
sectors=sectors, disk_sectors=disk_sectors, limit=limit,
partition_end=partition_end, capacity=capacity)
def update_mu300(api, args, root):
"""Reuse native config/vendor migration, locking, swap and verified writes."""
import paramiko
root = Path(root)
gui = api.get('GUI')
execute, read_exact = api['ssh_exec'], api['ssh_read_exact']
if gui and not args.host:
raise ValueError('Enter the management address in the GUI / 请在图形界面填写管理地址')
host = args.host or input('Device IP / 设备 IP [192.168.77.1]: ').strip() or '192.168.77.1'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(host, username='root', password=gui.password if gui else os.environ.get('MU300_SSH_PASSWORD') or getpass.getpass('SSH root password: '),
timeout=15, look_for_keys=False, allow_agent=False)
if gui:
gui.validate_ssh(client)
info = execute(client, '''set -e
cat /run/mu300/device
cat /run/mu300/linux-slot
cat /run/mu300/misc-dev
if [ -s /etc/mu300/desktop-mode ]; then cat /etc/mu300/desktop-mode; else
d=$(cat /run/mu300/disk-dev)
case "$d" in /dev/mmcblk[1-9]*) echo sd ;; *) echo legacy ;; esac
fi''').strip().splitlines()
if (len(info) != 4 or info[0] not in ('f50', 'v50', 'u30air') or info[1] not in ('a', 'b')
or not re.fullmatch(r'/dev/mmcblk\d+p\d+', info[2])):
raise ValueError('Not a supported MU300 runtime')
mode = info[3]
if mode not in ('sd', 'part', 'data-image', 'legacy'):
raise ValueError('Unsupported root layout / 不支持的根区域布局: '+mode)
layout = legacy_layout(client, root, execute, read_exact) if mode == 'legacy' else None
if layout and gui:
planned = gui.ctx.record['plan']['openwrt_bytes']
if planned != layout['capacity']:
raise ValueError('Legacy root capacity changed since review / 旧版根区域容量与确认计划不一致,请重新检查设备')
gui.ctx.record['update_layout'] = layout
gui.ctx.store.save(gui.ctx.record)
gui.ctx.log(f'Verified legacy eMMC hidden-area root: offset={layout["offset"]}, '
f'capacity={layout["capacity"]}, loop_sectors={layout["sectors"]}; preserving layout', scope='update')
family = json.loads((root/'desktop/manifest.json').read_text(encoding='utf-8'))['kernel']
running = execute(client, 'uname -r').strip()
if not running.startswith(family+'.'):
raise ValueError('Kernel family mismatch: running '+running+', package '+family)
live = read_exact(client, f'dd if={info[2]} bs=1 skip=2048 count=32', 32)
slot = 'b' if info[1] == 'a' else 'a'
module = api['module'](root)
newboot = api['boot'](root, module, mode, live, slot)
control = module.boot_control(live, slot)
if gui:
gui.ctx.boundary()
else:
api['confirm']('Update OpenWrt while preserving settings and disk size; then reboot / 保留配置及容量更新,完成后重启。')
# Stage on disk, never upload a complete rootfs to the device's tmpfs.
destination = '/mnt/mu300-disk/.mu300-desktop-'+secrets.token_hex(6)
execute(client, 'mkdir -m 700 '+destination)
def send(local, name):
api['ssh_upload'](client, local, destination+'/'+name)
if execute(client, 'sha256sum '+destination+'/'+name).split()[0] != api['digest'](local):
raise ValueError('SSH upload checksum: '+name)
with api['payload_rootfs'](root) as archive:
send(archive, 'mu300-openwrt-rootfs.tar.gz')
for name in ('local-update.sh', 'mu300-update-library.sh'):
send(root/'desktop'/name, name)
send(api['payload_file'](root, 'busybox'), 'busybox')
for name in ('rootfs-critical.sha256', 'rootfs.requirements'):
send(api['payload_file'](root, name), name)
with tempfile.TemporaryDirectory() as temp:
for name, data in (('boot-desktop.img', newboot), ('misc-linux.bin', control)):
path = Path(temp)/name
path.write_bytes(data)
send(path, name)
if layout and legacy_layout(client, root, execute, read_exact) != layout:
raise ValueError('Legacy root layout changed during upload; nothing committed / 上传期间旧版根区域发生变化,未执行更新写入')
command = 'chmod 700 '+destination+'/busybox && sh '+destination+'/local-update.sh '+destination
if gui:
gui.action('update-commit', lambda: execute(client, command))
else:
execute(client, command)
finally:
client.close()
return api['Outcome']('success', 'Update verified; device is rebooting / 更新校验完成,设备正在重启。',
'Wait for OpenWrt to start / 等待 OpenWrt 启动。')
"""Source-tree compatibility entry; release packaging uses this same backend."""
from installer.backend.mu300_update import *
+16
View File
@@ -115,3 +115,19 @@ manifest、SHA-256 和单份 boot/rootfs。`.building-*` 不是正式包。
报告每个包的完整路径、构建提交、校验结果及失败项。原生 Mac 冒烟通过不等于
设备硬件验证;本次本地构建不得擅自连接或刷入用户机器。
## 在线保数据缩容工具
图形安装器的 F2FS 在线缩容使用仓库内置的静态 ARM64 小工具。
修改 installer/device/f2fs-online.c 后,在既有 WSL 工作区通过固定入口执行:
```sh
python3 tools/build-release.py run --workspace /home/kano/openwrt-build \
--label online-f2fs-helper -- python3 installer/build-online-helper.py
```
构建器先跑原生 C 回归,再生成 installer/device/f2fs-online-arm64 和 build.json。
Windows/macOS 原生打包消费同一受源码哈希绑定的工具,不另找 Android Python,
不为此重编内核或复制 rootfs。源变化必须重编工具及两个原生安装器;禁止修改
指纹绕过。工作流、证据及硬件验收边界见 ONLINE-F2FS-INSTALL-20261029.zh-CN.md。
@@ -0,0 +1,24 @@
# 看板未插卡与射频关闭的状态区分(2026-10-27)
## 原因与改动
主页原先仅按 CFUN=0 显示“无线电已关”,未读取已有的按槽 SIM 状态。无卡省电时射频关闭,使物理缺卡被显示成了射频设置。
现在 sysinfo 的 modem.sims 返回两个槽位的 `{slot,state}`,主页按正在查看的槽位选取。确认 absent 时优先显示“未插卡”,清除该次显示中的旧运营商、身份、小区和信号;缓存未知不猜无卡,已插卡且 RF 关闭仍显示“无线电已关”。缓存对象不原地修改,原有射频开关、AT 时序与刷新频率不变。
## 两仓库的数据来源
- MU300:复用现有 AT owner 的 `/run/mu300-registration/simN.json`;校验槽号、状态以及 SIM 已上电标记 `sim-powerN`。owner 不存活时返回 unknown,不因空 ICCID 或 CFUN=0 推断 absent。
- E5:复用 `/run/t551m-sims.json`,核对行槽号、明确的 present/registration、monotonic updated 与 15 秒有效期;过期、未来时间、错误类型或无 owner 返回 unknown。没有新增 HTTP 路径上的 AT 请求。
- 返回两个槽位是因为 sysinfo 为共享请求,而用户可以查看非上网卡;不能只返回当前数据卡的缺卡状态。
- common.js 补齐中文、英语和土耳其语的“未插卡”。
## 验证与范围
- 两仓库浏览器回归覆盖:缺卡覆盖 RF-off/旧 RAT、清除旧身份信号、已插卡 RF-off、未知不猜缺卡、槽位隔离、重新注册恢复,以及已有的慢/快缓存合并场景。
- MU300:9 项 dashboard info、14 项 native snapshot、缺卡翻译专项及快捷控制通过。
- E5:2 项 SIM presence、8 项 native snapshot、缺卡翻译专项及快捷控制通过。
- ucode 测试复用已有 `mu300-openwrt-ra-native:25.12.5` 容器,仅访问临时夹具;不是物理插拔验收。
- 通用 MU300 翻译测试另发现 HEAD 原有 TTL 菜单缺少 PO 条目,未计为本次缺卡翻译检查通过,也未在本次顺带改动。
本次已按设备存储身份复核后热应用到连接的 U30 Air UFS,实机 sysinfo 返回 SIM1 absent、SIM2 ready;AT owner PID 前后相同。没有在 E5 实机部署,也没有为此重新发布包。U30 部署回执位于 MU300 工作区 `work/u30air-ufs-20261027/sim-display-deploy.json`,设备只保留一份本次三个文件的小备份。
@@ -0,0 +1,9 @@
# 修改管理地址后旧 192.168.77.1 仍可访问
已确认代码缺陷:preinit 使用临时 `192.168.77.1`,LAN 接管时却只删除与当前桥地址相同的 USB 地址。用户更换网段后,临时地址不再与桥地址相同,因此残留在 usb0/rndis0 上,继续作为 Linux 本机地址响应。
修复公共 `10-mu300-usb` 交接脚本:处理 `lan/ifup` 与 `lan/ifupdate`;在桥具备 IPv4 后,清理已桥接 USB 成员上的全局 IPv4,让 `/etc/config/network` 管理的 LAN 地址仅归属 br-lan。保留未桥接接口、桥上的用户地址及 IPv6。不增加轮询、USB 重枚举或链路关闭。
验证:`test_upstream_stability.py` 6 项、`test_usb_management.py` 23 项通过。另在隔离 Linux 网络命名空间中运行实际交接脚本,确认启动及地址更新后旧本机路由消失、新桥地址和额外地址、IPv6、链路保留。E5 仓库同时修复其默认第二管理地址及旧配置迁移。
尚未实机修改地址验证,未部署、未重新打包。早期启动/救援阶段仍可临时使用默认地址;正常 LAN 接管后应移除。
+14
View File
@@ -107,3 +107,17 @@ python3 tools/build-release.py run --workspace /home/kano/openwrt-build --label
工具文件逐项按发布包内 `diff-tool.json` 核验,保留 Mac App 签名内容和可执行权限,
不解压固件、不重新编译;输出 ZIP 与 SHA256,已有目标不覆盖。
## 仅修复外部安装器 Python 入口
当变更只涉及 `desktop/installer.py` 的外部入口逻辑时,可流式修补已验证发布,
不重新构建固件或未变化的原生后端:
```sh
python3 tools/build-release.py repair-installer --workspace /home/kano/openwrt-build \
--profiles mu300-7.2 --source-release /absolute/repo/release/<verified-task> --label installer-entry-fix
```
新包同步替换根目录和 desktop 的入口及清单;boot、rootfs、Magisk 内容保持相同。
此入口不用于修补内置后端、驱动或任意其他脚本。此类依赖改变仍应走对应构建。
发布前通过实际冻结程序加载包内入口、CLI 和 GUI Adapter 的无设备测试,不能只测试 hello。
@@ -4,6 +4,10 @@
“源码覆盖”“编译通过”“已部署”和“用户实际验证”分别记录,不能互相替代。
新机型先确认硬件及原厂行为,再选择公共实现;不要按 SoC 相同整包复制板级策略。
UFS 机型先读 [UFS 适配指南与畅行 60 交接清单](UFS-PORTING.zh-CN.md),
本次实机过程见 [U30 Air UFS 适配记录](U30AIR-UFS-ADAPTATION-20261027.zh-CN.md)。
其中区分原厂调查、临时诊断启动、恢复和尚未验收的功能,不将 UFS 当成仅换盘符。
U30 Air 网页充电控制另见 [接口、机型隔离与测试记录](U30AIR-WEB-CHARGING-20261016.zh-CN.md)。
先检查已有驱动的可写控制接口,不复制 Android 专有 sysfs 路径,不用 inotify 冒充 SOC 事件。
@@ -0,0 +1,59 @@
# 在线 F2FS 保数据缩容与续装修复(2026-10-29)
## 本次安装报错的确认原因
畅行60的原 Android 在 B、OpenWrt 目标在 A。电脑已经完成空闲区 GPT
分区创建,但旧 GUI 的 free-space 续装记录漏存 android_slot/linux_slot。
续装代码把缺失角色按历史 A/B 处理,误报槽位改变,尚未写入 OpenWrt 根。
这不是在线缩容失败,也没有理由重新缩容或清空 Android。
新记录显式保存动态角色;旧记录仅从绑定的原电脑事务恢复角色,核对
串号、CID、userdata 几何、GPT effect 和记录路径,不从当前槽位猜原角色。
真正槽位改变仍停止。已修复本机该条续装记录,原件另存;没有因此写设备。
## 新的图形安装器流程(两仓库)
1. 已有足够未分配空间时直接使用,既不缩容也不清空。
2. 否则默认优先 Android 在线 F2FS 保数据方案;原离线清空方案保留为可选项。
3. 只读确认实际挂载源、双超级块、UUID、完整 userdata 映射和空间。
支持公共 eMMC/UFS 拓扑及 512/4096 GPT;块级 FDE、多层映射、未知偏移
不伪装成已支持。FBE/metadata 加密使用 Android 已建立的解密映射。
4. 先备份原 GPT/启动链,metadata 加密时另存有大小限制的 metadata 备份到电脑。
不备份整个 userdata,不改 NV,不靠 initramfs 解密。
5. 静态 ARM64 工具在 /dev 内执行,先做当前相同容量的能力检查(不是缩容 dry run),
再由原厂 Android 内核的 F2FS_IOC_RESIZE_FS 搬移尾部数据。一个脱离 ADB
会话的加锁 worker 连续完成缩容、备 GPT、主 GPT、flush 与回读。
6. 写入阶段取消会延迟至文件系统/GPT 一致。ADB 断开不自动启动格式化。
中断后核对原表/候选表;只有已知新文件系统和已知 GPT 副本才能续写。
未知中间状态停止供恢复,不能猜测成功或直接擦除。
7. 正常重启 Android,确认新 boot ID、映射大小、UUID、双超级块及空闲范围,
再交给现有空闲区安装流程。E5 创建根分区后还可能再正常重启一次刷新节点。
原始缩容前 GPT 备份仍保留为卸载归还空间的依据。
8. 内核拒绝在线操作时先证明未改变文件系统/GPT;然后用户可输入 yes
生成清空数据的新计划,仍需重新勾选确认才可执行。不会自动擦除。
本次接入的是统一 Tauri GUI 的规划和事务流程。原独立 CLI 脚本仍保留原有
离线安装行为,不宣称所有旧 CLI 也已自动改用在线缩容。
## 构建与维护
- 核心:installer/backend/online_shrink.py;两仓库相同协议与实现。
- 设备工具:installer/device/f2fs-online.c、build.json 和静态 ARM64 可执行文件。
- 修改 C 后通过固定入口运行 installer/build-online-helper.py,先执行原生 C
几何/真实临时文件写入回读测试,再交叉编译;没有复制内核或 rootfs。
- 原生安装器构建检查源码/二进制指纹,冻结后端内置工具;不依赖 Android Python。
- 本次变更后旧 EXE/App 指纹会失效,不能改元数据冒充重编,正式包需重新构建安装器。
- 电脑 metadata 备份可能包含加密密钥,只应与私人安装记录一起保管。
## 已验证与边界
- 之前经授权的畅行60:实际保留加密 Android 在线释放64 GiB,正常重启后核验
双超级块、UUID、包列表、文件和映射容量;见 E5 仓库 docs/CHANGXING60-ONLINE-SHRINK-20261029.zh-CN.md。
- 本次另以新静态工具只读 inspect 核验同机原容量仍保持;没有再次缩容或写 GPT/NV。
- 源码测试覆盖 eMMC/512 与 UFS/4K 的 GPT 精确改动及卸载原始布局恢复;A/B
新旧续装记录;内核拒绝、ADB 在启动后中断、已知混合 GPT、副本校验、取消延迟、
Android 在提交期间重启、显式后备确认和新计划二次确认。
- 生产前端浏览器检查中英文、小窗口、默认在线/主动离线、取消/重新打开时清空
yes、nonce 绑定、新清空计划不得自动开始;保留既有帮助、日志、toast、无线 ADB。
- 这些不等于两仓库每个机型的原厂内核都通过了真实在线缩容。新 detached worker
的完整整机安装及断电硬件验收尚未执行,不能把模拟测试称为硬件通过。
+18
View File
@@ -0,0 +1,18 @@
# 发布内容中的旧 VPN 集成清理
2026-10-29 按用户要求清理项目自身已经不提供的旧入口,不根据关键词删改第三方主题。
- 删除旧控制脚本、OpenWrt/systemd 服务、配置示例及仅为这些功能使用的下载脚本和测试。
- 删除终端菜单、服务列表、看板快照、RPC/action 中的旧入口和状态探测。
- 构建器不再下载或挂载这些旧组件。保留归档排除检查,防止旧输入重新带入可执行程序。
- 清理空的 LuCI 菜单父节点;另有用户插件提供子菜单时保留父节点,并更新 APK 文件
校验记录。归档清理两遍流式读取,不展开另一份完整 rootfs。
- 升级继续保留用户插件和配置;DNS 修复保留端口归属、实际监听、其他解析器和用户确认
等约束,移除对已删除内置服务的启用标志判断。自定义解析器占用端口的回归仍通过。
Aurora 自带样式和图标不删除、不修改。通用协议支持、WireGuard 等内核配置、第三方
软件版权信息和用户自行安装的功能不在此次清理范围内。没有修改既有发布包,也不保证
网盘审核结果;这些源代码变更需下一次正常组包才进入新固件。
回归包括归档排除和主题保留、菜单及 APK 文件记录、用户包/DNS 升级、实际 ucode
看板快照及修改过的 shell 脚本语法检查;不访问实机。
@@ -0,0 +1,39 @@
# 后台短信发送与未插卡看板检查(2026-10-28)
## 已确认并修复
- **发送失败的协议缺陷已复现**:发送器从 `25f8d0ce5` 起使用 `AT+SPACTCARD=0/1;+CMGS=…<CR>PDU<Ctrl-Z>` 原子选卡提交;`f0b5ad43` 引入的 ucode 守护进程却只允许裸 `AT+CMGS/CMGW` 携带 CR,因此后台网页发送和短信转发的合法提交在到达基带前被拒绝。现在校验器接受可选的单个 `SPACTCARD=[01];` 前缀,原样向原通道发送;其他命令拼接、非法卡号、LF、非十六进制或缺 Ctrl-Z 仍拒绝。FIFO 和 ubus 共用同一校验器。
- `mu300-at` 的 `exec 9<> "$DIR/cmd" 2>/dev/null` 会永久改变自身 stderr,导致后续 FIFO 超时、空应答和不完整应答的错误被吞掉。改为局部重定向,仅隐藏打开 FIFO 的系统错误;具体失败原因仍交还调用方。
- `mu300-sms send` 保留提交阶段的错误输出和退出状态。没有 `+CMGS` 且没有基带错误时,明确报告“没有提交确认、投递状态未知”,不再只有空白 `submit failed`。
- 未插卡过滤曾将整个 `ident` 清空,连设备 IMEI、厂商、模组型号和固件一起隐藏。现在仅清除卡身份和驻网数据,保留设备身份及真实射频状态;已同步 E5 公共页面。后端原有身份读取不依赖驻网成功,无须增加 AT 查询。
## 未证实的群友归因
尚未复现“继承后台环境、信号或描述符必然导致发送失败”。当前正常 FIFO 客户端使用单调时钟与原子应答文件轮询,不用 `read -t` 等待 FIFO 回复;`read -t` 出现在 shell 能力探测及无守护进程时的直连路径。
清空环境会移除 `MU300_SIM_SLOT`,使发送器不再添加选卡前缀,恰好绕开上述拒绝,但也失去了发送卡槽保证。这是对“干净环境恢复”的代码解释,不能当成对群友实际进程状态的采集证明。
没有加入 `env -i`、新会话包装或失败重发。前者可能丢失卡槽和事务锁环境;后者可能在 Ctrl-Z 已提交而确认丢失时重复发送。原有 SMSC 刷新、IMS、PDU 模式及 CMGS 顺序不变,收发通道所有权不变。
短信转发调用相同发送器,因此共享客户端修正;转发历史仍使用既有 `delivery_failed` 分类。E5 发送走 ModemManager/E5SMS,没有套用 MU300 FIFO 客户端改动。
## 本地验证及限制
- FIFO 客户端边界 10 项、发送事务/后台任务 12 项、短信池/RPC 5 项、任务 UI 1 项、身份缓存 5 项、转发历史 5 项、转发模板 3 项通过。
- 后台事务覆盖 BusyBox ash sender/client、忽略和屏蔽信号、继承 fd8/fd9、SIM2、单一锁持有者及单次 CMGS。
- 两仓库 Chrome 页面测试通过:冷启动未插卡 IMEI、移除卡身份清除、射频关闭、双卡隔离及重新插卡恢复。
- E5 双卡发送离线测试 3 项通过。
- 使用连接的 U30 Air 的原生 ucode/BusyBox,在独立 `/tmp` 目录运行生产发送器、真实 FIFO 客户端及守护进程,对端是模拟基带,ubus 与真实服务隔离。修前 SIM1/SIM2 均复现拒绝,修后两卡全链路通过;每次 5 条命令、仅一次 CMGS,卡号、通道及锁清理均正确。测试结束清理临时文件,不替换设备上的服务。
- 新增协议/全链路测试 4 项及既有守护进程的 PDU、拒绝非法请求、FIFO 应答、命令串行、SIM 缓存 5 项共 9 项通过。日志保存在 `work/sms-background-20261028/broker-before.log` 和 `broker-regression.log`。
上述软件链路缺陷已在原生运行环境中复现并修复;对端使用模拟基带,没有发送真实短信、没有改 NV,也没有热部署。运营商实际投递及群友 F50 的最终发送/转发效果尚未实机验收。
## 换行正文的独立缺陷及修复
`utf8_to_ucs2` 原先按行 `print`,将正文的换行变成十六进制串里的真实 LF,随后被客户端的 FIFO 单行校验拒绝;仅含换行的正文还可能被错误编码为空内容。短信转发模板的来源行与正文之间本来就有 LF,因此单行原文也会踩中。
现在将每个原始 LF 编成 `000A`、CR 编成 `000D`,十六进制串始终只有一行;保留首尾空行、CRLF、中文及代理对。增加一个输入记录终止符,让 POSIX/BusyBox awk 都能精确保留尾部 LF,不依赖 BusyBox 不一致的 NUL 记录分隔行为。CMGS 长度及 UDL 从正确编码后的字节计算。
同时修复转发从池文件读正文时命令替换吞掉尾部空行的问题,仅移除存储格式附加的一个终止 LF。两仓库的转发长度检查均计入全部 LF;E5 发送器读取文本文件时保留 CRLF,不经 Python 通用换行转换。
回归:发送事务 14 项、转发模板/长度 4 项、转发历史/正文读取 6 项通过;原生 ucode 双卡完整模拟链路 4 项通过,包含多行中文、CRLF 及尾部空行的 UTF-16 字节校验。原生 jshn/ucode 的隔离转发夹具验证 JSON、模板 JSON、纯文本、钉钉、SMTP Base64 和短信转发正文,所有传输端均被替换,无实际外发。E5 长度检查及双卡发送共 5 项通过。
@@ -0,0 +1,60 @@
# U30 Air 4.4V 电池限制电压复核(2026-10-28)
用户确认原厂电池标签标称 3.85V、充电限制电压 4.4V。这是该电芯的标注,不能再把当前充电器的 4.304V 目标等同于电芯的额定充电上限,也不能仅凭标签断言原厂始终按 4.4V 充电。
## 只读实机结果
当前连接的 U30 Air UFS 版:
- BQ `constant_charge_voltage=4304000`,状态 Full。
- FGU 电量 100%、电池电压 `4260000`。
- 原厂传入 DT `battery/constant-charge-voltage-max-microvolt=4300000`。
- `batt_cap_learn/bcl_battery_count0`、`count1` 的 `bcl,battery-limit-charge-voltage` 均为 `4400`。
- `battery/ir-cv-offset-microvolt=100000`。
这次没有写充电寄存器、电量计、NV 或切换系统。上述属性区分充电器目标与电池实测值,不把 FGU 的其他电压属性当成充电芯片寄存器。
## 原厂参考源码
只读使用既有 `mu300-kernel` Docker volume 的 `zte-u30air` 源码,没有下载或复制内核。已登记版本为 `b50db5b6224c11db42a246e8fcdaad1e1d59f478`;它是原厂 GPL 参考,不能冒充当前 UFS 设备完全相同的运行固件。
- `drivers/vendor/common/power/battery_capacity_learning.c:1087` 读取 `battery-limit-charge-voltage`;约 1204 行通过 `POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN` 返回选中电池的该值。这证明 4.4V 参数提供给上层,尚不证明它最终被下发给 BQ。
- `drivers/power/supply/charger-manager-sqc-v8.c:2481` 的补偿采用基础电压加平均电流乘电阻,并受上下界约束;其中 CP 状态另使用偏移。不能把 DT 的 100mV 参数直接理解为普通尾充固定加 100mV。
- `drivers/vendor/common/sqc_v8/sqc_charger_hal.c:1104` 将上层指定的充电电压传给 charger ops。最终 SQC 用户态策略选择何值仍需核对。
## 初轮结论(后续已核实最终配置,见下一节)
当前补丁确认对齐了 4.3V 基础配置及已核验原厂寄存器编码,不能据此宣称完整对齐原厂最终充电策略。此前 4.272V 结论已在旧文更正为基础目标 4.304V;本次进一步明确这也不是对电芯额定上限的证明。
需核实 SQC 上层如何结合选中电池的 4.4V、温度、老化和补偿决定最终电压,再决定是否修改 OpenWrt 控制。标签确认不能替代该步骤;本轮未将设备固定改为 4.4V。
## 本机 SQC 最终配置已提取并核实
用户要求对齐原厂后,从连接的 U30 Air UFS 版原始 super 分区只读解析 LP 与 EROFS,按 `/run/mu300/android-slot` 动态选择 vendor 槽位。只读取相关元数据和目标文件的块,电脑端保留稀疏元数据文件;没有复制整个 vendor、挂载 userdata、修改分区、写 NV 或切换系统。
本机 vendor 身份:`ZTE/U30Air/U30Air:13/TP1A.220624.014/20241014.163923:user/release-keys`。
| 原厂文件 | SHA-256 |
| --- | --- |
| `/vendor/bin/sqc_daemon` | `aa7263f496726b5e56b734c0f2076ddc91b621218647347afb3650e4f58f03be` |
| `/vendor/etc/.tp/sqc_charger.conf` | `4a20fee6985f14d2d8e149eb8ed348fa10a70dea2c66f60da5cefebba234eef2` |
压缩簇解压后检验 ELF;附带 `.gnu_debugdata` 的 XZ 校验通过。利用原厂附带符号与 ARM64 反汇编确认:
- `of_property_read_s32` 在 `0x125e8`、`of_property_read_u32_array` 在 `0x12854` 使用上述配置文件路径。
- `sqc_parse_dt` 在 `0x1160c` 等处读取 `sqc,max_vbat_mv`,不是从电池学习模块直接采用 4400。
- 实际配置 `sqc,max_vbat_mv = <4300>`。
- `sqc,fcv` 的 15 个值为 `4100 4300 4300 4200 4100 / 4200 4300 4300 4200 4100 / 4300 4300 4300 4300 4100`,最高也是 4300。
因此,“4.4V 电池标签或 BCL 额定参数意味着原厂最终必然设置 4.4V”的推断不成立;本机原厂 SQC 明确采用最高 4300mV 的策略。当前 OpenWrt 从基础配置取得 4300000,再按已核验的原厂 BQ 编码设置 `REG04=0x70`、目标 4304000,与这个正常充电目标匹配。之前 eMMC U30 Air 原厂 Android 的实时 `REG04=0x70` 采样也与之吻合,详见 BC1.2 报告。
没有将电池标签上限写成固定目标,也没有凭 BCL 参数增加 100mV。保留用户此前明确要求的电流配置与限充选择;电流偏好不用于推导电压。
## 配套驱动验证
从既有 `mu300-mainline-clean-tf-7-2` volume 只读核对已准备的两个驱动,分别运行现有 `tests/bq256xx_stock_cv.py`,均通过:4300mV 对应 4304000µV、901 个输入的寄存器编码、其他位保留、低压电池、缺少 battery-info、I/O 错误及非电池板隔离。两套源码不是相同文件,不跨内核替换模块。
- 7.2.8 驱动 SHA-256:`81dd27a259bfff80cab9ee05b92dfef543132d73cf11d74189f99f8a33e00094`。
- 6.18.54 驱动 SHA-256:`abb0b2dd735938675d7ae711d4b31301554e591e365b6aacd95d323262fe08e2`。
本次对齐结论限定为本机固件的充电电压来源和正常充电目标;不冒充移植完成整个 SQC 温度/老化/充电阶段管理器,也不以原厂的一次采样代替完整充满测试。本轮充电电压无需再修改,没有重新编译内核、刷入或改写设备充电参数。调查资料在 `work/u30air-charge-voltage-20261028/`。
+88
View File
@@ -0,0 +1,88 @@
# U30 Air UFS:SIPA 线程修复与原厂无线对照
## 结论
2026-10-27 在已连接的 U30 Air UFS 上,修复并部署了 SIPA 两个线程
长期停留在创建阶段 D 状态的问题。无线初始化的两个拒绝回包经同机原厂
Android 实测也存在,不能认定为本次 OpenWrt 移植引入的驱动缺陷。
本轮未更换无线固件、修改 RF INI、校准数据、功率表、休眠策略或蜂窝 AT 顺序。
## SIPA 修复
涉及 `upstream/modules/sprd_modem/sipa_v3/sipa_skb_send.c` 和
`sipa_skb_recv.c`,6.18/7.2 的 MU300、F50、V50、U30 Air 共用。
旧实现通过 `kthread_create()` 创建 sender/receiver 线程,只有首次资源恢复
才调用 `wake_up_process()`。未建立蜂窝数据连接时,两个线程长期处于尚未执行
工作函数的 D 状态,引发 hung-task 告警并抬高负载,而非阻塞在 UFS I/O。
改为创建时运行工作函数,在可中断等待队列中等待原有首次 resume 事件:
- 首次 resume 前通过 `init_flag` 短路条件,禁止访问 FIFO/MMIO,包括队列已有
工作、意外唤醒和信号中断的情况;不提前开启 SIPA 硬件或改变资源握手顺序。
- resume 清除初始标记并唤醒原有队列,后续保持既有发送回收和收包补充路径。
- 等待条件包含停止请求,信号中断不误进入硬件处理。
- 线程注册 devm 停止动作,释放结构前停止;同时修正 sender 的 devm 分配对象
使用裸 `kfree()` 的错误路径,初始化回调前先初始化等待队列。
- receiver 数组初始化失败时直接返回错误,避免继续发布不完整对象。
`tests/test_sipa_worker_lifecycle.py` 抽取真实工作函数,用 pthread 等待队列执行
首次 resume 前等待、已有待办、意外唤醒、信号中断、resume 后工作以及两阶段
停止测试。与已有 SIPA TX 重试测试合计 3 项通过;这不等于已测试欠费卡的数据传输。
## 无线:同机原厂证据纠正了初步判断
从本机 UFS `super` 的逻辑分区只读提取原厂模块与固件,没有安装整套 Android
根镜像,也未从相似型号替换输入:
| 输入 | SHA-256 |
| --- | --- |
| 本机 vendor_dlkm_a / sprd_wlan_combo.ko | `c55c6fd33210741371ca389aa850dd13d6c28293c5dd78c9ac8a667c64deef61` |
| 本机 odm_a / firmware/wcnmodem.bin | `a3210c08f0702d7bfcfff21f3d09226b38412de79782c1eac9443615ace47e70` |
| 本机 odm_a / firmware/wifi_board_config.ini | `47a4e23d96e7334750fdb52b0f283f8f64949605b8ba9df2d835f00ea1f07a1d` |
后两项与 OpenWrt 当前使用的文件逐字节一致。原厂模块反汇编确认:
- `cmdevt_download_ini +0x1e844` 同样发送 section + 三个保留字节、原始数据、CRC;
第三段 RF 长度同为 129 字节。
- `sc2355_set_power_backoff +0x1f288` 同样向命令 5 发送 18 字节,子类型 `0x11`。
- `sc2355_fcc_fresh_bo +0x345dc` 同样使用上述功率回退路径。
临时启动本机原厂 Android A 槽,读取已有启动日志后恢复原始启动控制信息、
正常重启回 OpenWrt B 槽。Android fingerprint 为
`ZTE/U30Air/U30Air:13/TP1A.220624.014/20241014.163923:user/release-keys`,
WCN 版本 `MARLIN3_20A_RLS2_W24.29.5 / 07-19-2024 09:52:19`。
没有修改原厂 Wi-Fi 配置或开启测试热点。
原厂内核日志原样包含:
- 8.066602 秒:`CMD_DOWNLOAD_INI / SPRD_CMD_STATUS_UNKNOWN_ERROR`。
- 8.113508 秒:`CMD_POWER_SAVE / SPRD_CMD_STATUS_ARG_ERROR`。
OpenWrt 临时命令跟踪把第二项关联到 `sc2355_set_power_backoff`,并非普通
`sc2355_power_save` 休眠开关。所有临时探针及独占 tracing instance 已移除。
因此,已排除“OpenWrt 引入新的报文格式错误”这一初步疑点;原厂固件本身仍会
拒绝这些扩展配置,未证明它们没有性能影响,也没有使固件接受它们的已验证方案。
不把删日志、跳过 RF 配置、换功率表或禁用省电冒充修复。
## 构建与部署
通过 `tools/build-release.py run` 复用已有构建 volume,6.18.54、7.2.8 的
sprd_modem 配套模块均编译通过。7.2.8 实机与构建 vmlinux BTF SHA-256 同为
`be01d4db0f8c9daff839127cb2a10f5f4b622248a80acca1845ae6df3fa31371`。
实机只替换根文件系统及当前 Linux B 槽 initramfs 中的 `sipa-core.ko`。
启动镜像只追加该模块覆盖段;逐项验证 kernel、其余 CPIO 文件、启动参数和
48 MiB 之后的持久日志区保持,Android boot A 的完整哈希未变。
刷入后回读校验成功,未使用 fastboot、未修改 NV 或重新安装系统。
重启后两个线程均为 S 状态,栈已进入各自工作函数的等待点;此前约 3 的 load
降至约 0.6(短窗口,不能视为续航测量)。AT broker/URC、USB 管理网络与
5 GHz 热点正常,ext4 错误数仍为 0。卡欠费,未测试蜂窝吞吐和资源活动状态。
恢复 OpenWrt 后再次核对模块 SHA-256 为
`a3c160a104eb710949912b1abeb1f3152097ede3cf3dea5e92239c4f6b60533e`。
源码、两条内核的模块缓存及本机已更新,既有发布 ZIP 尚未重新打包。
本机证据、原始启动镜像和部署收据保存在
`work/u30air-ufs-20261027/driver-fixes/`,含敏感设备日志,不应整体公开。
@@ -0,0 +1,129 @@
# U30 Air UFS 版本:存储适配与验证记录
后续机型使用 [通用 UFS 适配指南](UFS-PORTING.zh-CN.md),其中包含单位合约、
踩坑、恢复流程及 E5 仓库畅行 60 的待办。本文仅记录本台实际证据。
已接入两条主线内核的 UFS 驱动,并将安装、启动、基带分区映射、更新和卸载接到统一存储描述。
**已在实机分别启动 7.2.8 和 6.18.54 的诊断 initramfs,验证 UFS 只读访问;尚未完成完整 OpenWrt 安装验收。** 两次测试通过 Android ADB/root 临时写入备用 boot B 和 32 字节启动控制,当前 Android A 的 boot 未改。测试结束恢复原 boot B 和原启动控制并校验;未改 GPT、未格式化 userdata、未写 NV。后续禁止使用 fastboot。已有 LAN 地址修复保持原样。
## 实机证据
| 项目 | 本机值 |
| --- | --- |
| Android 固件 | `U30Air_SPV1.0.0B04`,fingerprint `ZTE/U30Air/U30Air:13/TP1A.220624.014/20241014.163923:user/release-keys` |
| 内核 | `5.4.254-android12-9-gb50b8ab9329f` |
| 平台 | UMS9620;当前 Android A 槽 |
| 存储 | Samsung `KLUGGARHGB-B0E1`,revision `0901`,UFS 3.1 |
| 用户 LUN | `/dev/block/sda`,1,023,678,611,456 字节,953.375 GiB |
| 其他 LUN | sdb、sdc 各 4 MiB,不能视作普通空闲盘或安装目标 |
| 控制器 | `22000000.ufs`,设备树 `sprd,ufshc`,模块 `ufs_sprd_qogirn6pro` |
| 逻辑/物理块 | 均为 4096 字节 |
| userdata | `sda75`,GPT LBA 1,534,464~249,921,023,1,017,391,349,760 字节 |
| userdata 加密 | `ro.crypto.state=encrypted`、`ro.crypto.type=file`;fstab 有 fileencryption/keydirectory,实际 `/data` 来自 dm-39 |
| 已有 OP 分区 | 未发现 `mu300root` |
| 原厂省电 | `power/control=auto`,时钟门控开启、延迟 10 ms,rpm/spm level 3;未改动 |
主、备 GPT 头 CRC、表 CRC 和两份分区条目一致性均已在电脑端验证。固件原始 DTB、内核配置、GPT 小范围快照及摘要在 `work/u30air-ufs-20261027/`。未读取整盘、userdata 内容或 NV;另保存两槽 boot 与启动控制以恢复临时内核测试。
## 首要问题:不能仅替换 mmcblk0 为 sda
### 与既有 U30 Air 的非存储部分对照
本机仍是 UMS9620/T760,Marlin3+SC2355 PCIe 无线、UMP9620 PMIC/FGU/Type-C、I2C6 的 BQ2560x 兼容充电器、ZTE LDO 灯控以及 cpufreq-v2 均对应现有 U30 Air 适配路径,应复用这些功能而非重新建立一套机型业务。
与此前 eMMC U30 Air 保存的 `work/u30air-charge-early-full-20261022/battery-dt.json` 比较:50 项值一致;确认一项实际参数差异:`battery/charge-term-current-microamp` 旧机为 300000,本机为 420000。旧采集中的若干字符串以 Python bytes 表示,与当前 DTS 的纯文本显示差异不算硬件差异;`name` 为旧采集的节点名称,不是当前 FDT 缺失硬件。
因此结论是“主要适配存储,复用 U30 Air 业务并读取本机参数”,而非“除 UFS 外所有参数逐字相同”。当前没有完整的旧 eMMC 原机 FDT 可逐节点对照,尚不能保证所有 GPIO、射频固件和板级参数完全一致。
另只读提取本机 SML A:完整 SHA-256 为 `6e3b9234525ace117a503925c8f8db0ed05e1679bd773d4731b56334140f5a2f`,与现有完整镜像允许列表不同;但原已验证 U30 Air 的可执行载荷范围 `[0x200,0x23150)` 哈希仍为 `119f874110ce04f9623cda30b85bae35b2ad7da494a1a26c1f7553f9f64bb1fd`,完全一致。两槽 SML 完整文件相同;与原已验证镜像相比,仅签名/认证区域不同,可执行载荷一致。已将本机完整哈希加入 U30 Air 调压识别,不按 SoC 泛化放行。实际调压效果尚未做整机验证。
这台机器 GPT 的 LBA 单位是 **4096 字节**,但 Linux sysfs 的 `start`、`size` 仍以 **512 字节**为单位。例如 userdata 的 GPT 起始 LBA 是 1,534,464,sysfs start 是 12,275,712;它们描述相同的字节偏移。
修改前两条主线发布内核配置未接入这颗 QogirN6Pro UFS 控制器;本次已补入配置与专用驱动。`boot/module-order*.txt` 中存在 UFS 模块名称是旧 vendor 内核路径,不能证明 6.18/7.2 内核已经支持 UFS。
另外,本机 SCSI WWID 是 `eui.53414d53554e4700`,内容只是厂商字符串,**不能当作唯一身份**。实际 UFS string descriptor 的 serial_number 可读;应使用这个序列号,结合 LUN、控制器归属、容量和分区几何验证。报告不公开原始序列号。
## 已实现的公共路径
### 1. 内核驱动与原机设备树
- 为两条发布内核接入 UFS core、platform 及 UMS9620/QogirN6Pro host/PHY;保持现有 eMMC 路径。
- 以本机 DTB 的 clocks、resets、regulator、PHY SRAM、两个 efuse 校准项为准。不能将另一款 SoC 的 `ufs-sprd` 直接绑定到同名 compatible。
- 本机已存在 `mu300-kernel` Docker volume 中的 U30 Air vendor 源码可作为移植输入,无需复制整棵源码或重新下载内核。缓存源码 HEAD `b50db5b6224c11db42a246e8fcdaad1e1d59f478`,其中 `ufs-sprd-qogirn6pro.c` 1240 行;它与本机 kernel build ID 不同,不能声称已核对为完全相同的原厂版本。
- 移植需核对新旧 UFS variant ops,特别是原厂的 PHY initialization、hibern8、reset、efuse 和 suspend/resume;不以关闭休眠或降速替代适配。
### 2. 统一存储描述与扇区单位
- 从 userdata 的实际父设备解析系统盘,确认其为本机控制器 LUN;不假设 UFS 永远是 sda,也不扫描 USB 硬盘后随意接受同名分区。
- 存储描述包含介质类型、父盘、分区号、逻辑块大小、容量和设备身份。eMMC 保留 CID;UFS 使用可验证的 serial descriptor。
- 容量/偏移计算使用字节或明确的 512-byte sector 单位;GPT 层单独按设备逻辑块大小转换。主备 GPT 读取、CRC、表写入、回读都使用同一逻辑块大小。
- 分区命名不能再使用 `${node%p*}`、`${disk}pN`:分别支持 `mmcblk0p75` 与 `sda75`。
### 3. 启动、基带、安装和更新一起接通
| 范围 | 已修改的入口 |
| --- | --- |
| 启动槽位、日志落盘 | `boot/init` 的 misc/boot 搜索;`early-recorder` |
| 内部根分区 | `desktop/boot/storage.sh`、`part-prepare.sh`、`install-part.sh`;旧 free-region 模式不可对 UFS 沿用固定偏移 |
| 基带分区映射 | `android-vendor-start` 和 `boot/init` 的 mmcblk0 PARTNAME 枚举 |
| 安装器探测、备份、分区 | `desktop/installer.py`、`installer/backend/adapter.py`、`gpt.py` |
| Android 分区写入 | `desktop/android-write-part.sh`、`android-write-free.sh` 的 CID、父盘与分区节点验证 |
| 更新与卸载 | `service.py`、`mu300_update.py`、`desktop/update_control.py`、卸载事务/worker 的身份和几何验证 |
| 系统切换/OTA | 检查所有 misc、boot、根设备正则和持久记录,不将 sda 分区拒为非法设备 |
基带、LED、充电、CPU 等仍属于 U30 Air。存储介质应作为独立维度,不凭型号建立一套重复业务实现。
### 4. 验证与首次安装边界
已完成下述源码及只读实机验证。完整 OpenWrt、实际分区写入及升级卸载仍需单独验收;本次未生成正式发布包,旧发布包不会因源码改变而自动支持 UFS。
本机容量基本已分配给加密 userdata,没有可直接容纳 OpenWrt 的大块 GPT 空闲区。若使用当前“加密 userdata 清空后缩容”的安装方案,需要另行取得用户对清空 Android 数据及分配大小的明确授权;本次没有此授权,也没有执行。不要尝试从 initramfs 挂载加密 userdata 获取安装载荷。
## 驱动实现与实际结果
- 新驱动在 `upstream/port/drivers/ufs/host/ufs-sprd-qogirn6pro.[ch]`,由现有 port 安装入口加入 Kconfig/Makefile;两条内核都内建 UFS core/platform 和本驱动。
- 保留本机原厂 PHY/DME 初始化、双 lane efuse、Hibern8 时钟/参考时钟切换和 suspend/resume 顺序。5.4 的私有 RPMB/crypto 回调没有冒充主线 API;不宣称可解密 Android userdata。
- 适配中确认 efuse lane1 为 `0x96910000`,最高位为 1。原逻辑若混用有符号错误码与校准值会误判;现使用返回码与 `u32` 输出分离。实机两条内核均正确读取两条 lane 的校准值。
- 7.2.8 在约 0.87 秒、6.18.54 在约 0.94 秒创建用户 LUN 及全部 75 个分区。GPT 前 32 KiB 的摘要与 Android 下采集结果相同。
- 6.18.54 做了 15 次间隔 2 秒的 GPT 读取,以及 3 次连续 32 MiB 读取;摘要各自一致,未见 UFS I/O 错误。它们只是小范围只读测试,不能证明长期写入或断电可靠性。
- 实机保持 `power/control=auto`、`clkgate_enable=1`、门控延迟 10 ms、rpm/spm level 3。没有以禁用休眠或降速替代适配;未执行整机 suspend 验收。
- 普通 eMMC 机型的原始偏移 legacy root 路径保留,仅在确认系统盘为 mmcblk0 时使用,不对 UFS 硬套旧偏移。
## 回归证据
- Windows 安装器测试:352 项运行,环境适用项通过,74 项按条件跳过。
- Linux 卸载 worker 回归:22 项全部通过,覆盖实际 BusyBox worker 的重置、空闲区安装撤销、中断续接及 Android A/B 两种槽位。
- UFS 专项覆盖 512/4096 字节 GPT 主备校验、空闲区增删、userdata 缩容后的布局还原、设备身份、外接 USB 同名分区排除和不对齐请求拒绝。
- 实际运行发布的 ucode GPT 工具,在自有稀疏测试文件验证 list/plan/carve/uuid/resize/add、重复请求拒绝;独立 Python 编解码器检查 CRC 与边界。没有对设备运行这些写分区测试。
- 卸载 initramfs 中统一存储库位于 `openwrt-uninstall/storage.sh`,纳入同目录 SHA256SUMS,回归检查归档内每项均可按清单定位和核验。
- 完整 Image 和模块两套均构建通过;日志分别在 `out/build-logs/20261027-110214-ufs-kernel-72-5169/`、`out/build-logs/20261027-110548-ufs-kernel-618-5341/`。没有复制新的内核源码/对象树。
## 尚未完成
1. 完整 OpenWrt 下的蜂窝、无线、灯控、充电、CPU 调频调压等使用原有 U30 Air 业务,但本台 UFS 机尚未逐项整机验收。
2. 本机原 userdata 加密且占用剩余大部分 GPT 空间;继续内置安装需要明确的清空授权和分配大小。本次未获授权,故未分区或格式化。
3. 正式安装器及固件发布包尚未重新编译组装;两套内核产物已经更新,不能混用旧模块或旧安装器发布。
4. 本机 DT 还声明了未能发现卡的 `22200000.sdio` 非可移除 MMC 控制器,诊断内核有一次初始化失败日志。它不影响本轮 UFS 读取;尚无依据修改此节点或把它当成反复掉盘。
以上“未完成”不能写成已通过硬件验证。后续适配 UFS 机型应沿用统一存储层,板级 compatible、PHY、efuse 与充电参数仍须核对该机原厂证据。
## 本次执行过程与证据位置
时间为 2026-10-27 UTC+8;原始记录在本仓库 `work/u30air-ufs-20261027/`。
| 阶段 | 操作、结论与证据 |
| --- | --- |
| 原厂只读调查 | `summary.json`、`inventory-live.json`、`stock-live.dtb/dts`、`stock.config`、`ufs-sysfs.txt`、`ufs-policy.json`。summary 的 hardware_mutations=false 是这个初始阶段的快照,不是后续诊断启动从未写 boot 的声明 |
| GPT 核验 | `gpt-first-32k.bin`、`gpt-last-24k.bin`、`gpt-layout.json` 和 `gpt-live-shared-proof.json`;base64 传输纠正 su 通道对二进制的 CRLF 改写风险后,验证两头两表及 CRC |
| 非存储复用判断 | `nonstorage-comparison.json`、`sml-comparison.json`。没有将“同是 U30 Air”当作充电参数和 SML 一定相同的证据 |
| 驱动与双内核构建 | 保留 vendor PHY/efuse/Hibern8,修正校准值与错误码混用;分别解决 6.18/7.2 API 差异,构建完整 Image 与模块,日志路径见上 |
| 早期引导失败经验 | 一次 bootloader RAM 引导返回 OK,实际仍是原 Android,未计为新内核验证;后续按用户要求禁用 fastboot。最终使用 ADB/root 备用槽试启动。未包装 LK 的早期构造镜像没有刷入 |
| 7.2.8 试启动 | 19:22:37 经 ADB/root 写备用 B 和当次试启动记录,`probe-live-report.txt` 记录实际内核及 75 分区;19:27:21 恢复原 boot B 与原控制记录,`trial-state.json` 状态 restored |
| 诊断通道完善 | 第一版 telnet 连接 EOF 是缺少 devpts;第二版挂载 devpts,控制台可执行只读命令。关闭连接前未确认命令执行,也不能当作已重启,最终以实机重枚举和 Android 版本核验 |
| 6.18.54 试启动 | 19:29:20 经 ADB/root 开始,`probe-618-report.txt`、`probe-618-repeated.txt`、`probe-618-extended.txt` 保存只读结果;19:32:40 完成还原,`trial-state-618.json` 状态 restored |
| 最终收尾 | 两槽恢复后 SHA256 均为 `452a2bc393fc1f538fe462639780b4f259df8efd2f80da998d3616ec0088779b`;原启动控制按当次原始 32 字节回读验证,GPT 前 32 KiB 与初始快照一致。删除本次设备端上传目录,保留电脑端备份,`inventory-final.json` 用最终公共库在 Android 再次验证拓扑 |
不是整盘备份,也未碰 NV/IMEI 或 Android userdata 数据。内核读盘成功后仍保留“完整 OpenWrt 未安装”的边界;后续安装需独立处理加密 data 授权与空间选择。
离线运行记录:`installer-tests-final.log`(352 项运行、74 跳过)、`uninstall-linux-final.log`(22 项通过),以及源码中的 `tests/test_ufs_storage.py`、`tests/ufs_gpt_runtime.py`。后者对 512/4096 两类稀疏文件实际运行 ucode GPT 工具,不向本机块设备写入。
@@ -0,0 +1,79 @@
# U30 Air UFS 启动与运行只读检查(2026-10-27)
后续处置见 [SIPA 修复与同机原厂无线对照](U30AIR-SIPA-WIFI-20261027.zh-CN.md):
SIPA 已修复部署;两条无线拒绝回包在同机原厂 Android 中也已实测确认,
不能将下文初步疑点当作 OpenWrt 新引入的缺陷。
## 范围与结论
对象为已安装 OpenWrt 的 U30 Air UFS,Linux 7.2.8 #73,根分区
`/dev/sda76`。本轮通过 USB 网络 SSH 读取现有日志、sysfs、进程栈和
现有状态缓存,没有重启、重拨、发送测试 AT、切换射频、修改充电或存储参数。
用户确认 SIM 欠费,本轮不把注册失败、WAN 未连接视作驱动缺陷。
UFS 和根文件系统在观察窗口内正常,但不能据此认定整机所有驱动无缺陷。
发现 SIPA 未启动线程的长期 D 状态告警,以及无线固件拒绝初始化命令,需分别处理。
## 已确认正常的项目
- 同一次启动持续到 1362.76 秒,检查期间 boot ID 未变。
- initramfs 记录加载模块 26 个、失败 0 个,1.43 秒进入 switch_root;
该数字不代表完整系统、热点或蜂窝联网耗时。
- UFS 绑定 `ufshcd-sprd`,SCSI 设备状态 `running`。根分区容量约 7.8 GiB,
ext4 保持 `rw,noatime`,`errors_count=0`。
- 完整内核日志未见 UFS timeout、ext4 error/warning;未见 SIPA overflow、
`push link fail` 或 `CMD_TX_DATA` 固件错误。此结论仅覆盖已有日志和当前负载。
- AT owner bridge connected,六个命令 broker 均 open/idle,队列 0、silent 0;
两个 URC 通道 open,没有“模组消失”的证据。
- USB 网络有实际管理流量;热点处于 ENABLED,信道 36、5180 MHz。
- CPU 调频策略均为 schedutil,温区约 39–41°C,电池温度约 33.4°C。
5 秒 CPU 总体忙碌率约 13.34%,iowait 为 0%;这个短样本不能代表续航。
- 接电脑时充电器输入限制 500 mA,实际充电器 CV 属性 4.304 V。
这不能用于判断独立充电器的最大充电功率。
## 确认存在的异常现象
### SIPA 线程未启动,产生 hung-task 和负载污染
`sipa-free-1`、`sipa-fill-recv-1` 均处于 D 状态,栈仅包含
`kthread → ret_from_fork`,各只有 1 次 voluntary context switch。
内核累计报告 10 次相应 hung-task,随后达到告警次数上限。
代码对应 `upstream/modules/sprd_modem/sipa_v3/sipa_skb_send.c`、
`sipa_skb_recv.c`:创建使用 `kthread_create()`,启动依赖之后的
sender/receiver resume。当前蜂窝未建立数据连接,线程仍停在首次启动前。
这可以解释 D 状态告警及 load average 被抬高;不是 UFS I/O 堵塞的栈,
也不能仅凭此认定蜂窝传输死锁或两个线程正在消耗 CPU。
后续修正应核对首次启动、资源恢复和退出的完整生命周期,不应通过关闭
hung-task 检测、关闭休眠或在硬件未准备时强行启动工作线程掩盖现象。
### Wi-Fi 初始化命令被固件拒绝
两轮无线初始化中,第三段 RF INI 下载各出现一次
`CMD_DOWNLOAD_INI / SPRD_CMD_STATUS_UNKNOWN_ERROR`;
另各出现一次 `CMD_POWER_SAVE / SPRD_CMD_STATUS_ARG_ERROR`。
热点最终启动成功,但不能把这些回包视作配置已经生效。
运行固件报告 drv_version=2、fw_version=2、fw_ver=57488。
RF 段格式及功耗/功率子命令需要结合本机原厂驱动核对;现有回包没有给出
POWER_SAVE 的具体子类型,不能据此断言全部省电功能失效。
### 其他待核对项
- FGU 的 `constant_charge_voltage` 属性为 4.712 V,与实际充电器的
4.304 V 属性不同。前者不是实测电池电压;需核对属性实现与电池表,
目前没有实际以 4.712 V 充电的证据,未修改参数。
- `bss_load_update_period=60` 导致约每 6 秒一次 change_beacon;
最后日志快照共 210 次。确认有周期更新和日志,但不能据此认定会掉线。
当前没有连接的 Wi-Fi 客户端,未验证吞吐、延迟与多客户端稳定性。
- 启动时有 UFS 校准数据初次获取失败、FGU IIO 获取失败,之后设备成功绑定,
最终 deferred 列表为空。另有 PCIe 重试、遗留 eMMC 控制器探测失败及
regulatory.db 缺失等启动告警;需要分别对照原厂和初始化顺序,不能统一当作 UFS 故障。
## 证据
本机调查文件保存在
`work/u30air-ufs-20261027/runtime-audit-211319/`,包含完整 dmesg、
运行状态、线程栈、CPU 短采样和最终健康快照。日志用于本地诊断,不应直接公开
可能含设备身份的信息。本次仅新增检查记录,没有修改设备驱动或配置。
+199
View File
@@ -0,0 +1,199 @@
# UFS 新机型适配指南
更新:2026-10-27。供 MU300、E5 两仓库的后续 Agent 使用;第一份实际案例是 U30 Air UFS 版,下一台计划调查 E5 仓库的畅行 60。
**这是一份方法与交接记录,不是所有 UFS 设备已获支持的声明。** 当前 UFS 驱动和公共存储层改动位于 MU300 工作区;本指南同步到 E5 不代表 E5 已经移植代码。畅行 60 尚未连接调查,不能预填其 SoC、UFS 控制器、扇区、槽位或加密情况。
## 先读与边界
1. 阅读本仓库 `AGENTS.md`、`docs/NEW-DEVICE-STOCK-ADAPTATION.zh-CN.md`;编译前再读 `docs/LOCAL-BUILD.zh-CN.md`、`docs/AGENT-BUILD.zh-CN.md`。
2. 用户明确禁止使用 fastboot。使用已确认设备的 ADB/root 通道;若此通道不可用,保留现场并说明,不擅自换启动协议。
3. 初始调查只读。临时写备用 boot 与启动控制、变更 GPT、格式化 userdata、写 NV 是不同操作,应按实际授权分别处理。适配授权不等于清空 Android 授权。
4. Android 不固定在 A,OpenWrt 不固定在 B。所有备份、试启动、故障日志和恢复均由当次实机槽位及镜像身份决定。
5. 每个结论标明“原厂证据/源码覆盖/编译/只读启动/完整系统/长期硬件验收”。不能拿编译或小范围读取替代写入、掉电及休眠恢复验收。
## 1. 先确定实际介质、控制器和原厂行为
连接多台设备时所有 ADB 命令显式指定序列号;不要按网关或第一台设备猜目标。先进入选定设备的 Android shell,再取得 root,保存以下证据:
| 类别 | 必须记录 |
| --- | --- |
| 原厂版本 | 型号、board_id、fingerprint、内核版本、内核配置、原始 DTB/DTBO、相关驱动版本/哈希 |
| 启动链 | 当前 Android 槽、备用槽、两槽 boot 大小/哈希、实际 misc 别名和控制记录格式、两槽 BSP 差异 |
| 存储拓扑 | userdata 别名解析后的节点、sysfs 父盘、SCSI 地址/LUN、UFS controller 路径、driver/compatible |
| 几何 | 父盘及 userdata 的 sysfs size/start、逻辑块大小、物理块大小、GPT 主备头与表、CRC、分区范围 |
| 身份 | 厂商、产品、revision、UFS serial descriptor 是否存在;报告隐藏原始序列号 |
| 加密 | ro.crypto.state/type、实际 /data 挂载源、fstab 的 fileencryption/metadata/keydirectory 设置 |
| 原厂省电 | power/control、clkgate_enable/delay、rpm/spm level、实际可读取的 UFS 错误与链路状态 |
Android root shell 的只读采集示例(`<父盘>`、`<userdata节点>` 和控制器路径必须先人工/程序核实):
```sh
getprop ro.build.fingerprint
getprop ro.boot.slot_suffix
getprop ro.crypto.state
getprop ro.crypto.type
uname -r
readlink -f /dev/block/by-name/userdata
awk '$2=="/data" {print $1,$3,$4}' /proc/mounts
cat /sys/class/block/<父盘>/queue/logical_block_size
cat /sys/class/block/<父盘>/queue/physical_block_size
cat /sys/class/block/<父盘>/size
cat /sys/class/block/<userdata节点>/start /sys/class/block/<userdata节点>/size
readlink -f /sys/class/block/<父盘>/device
```
by-name 的所在目录也需核实,不能假设所有 Android 都用示例路径。命令缺失时选择同一只读操作的已确认工具,不把读取失败解释成容量为零或“没有分区”。
### 本次实际案例
- U30 Air,`U30Air_SPV1.0.0B04`,原厂内核 `5.4.254-android12-9-gb50b8ab9329f`。
- Samsung KLUGGARHGB-B0E1,UFS 3.1,用户 LUN 为 sda,953.375 GiB;sdb/sdc 各 4 MiB,均不能当成安装空盘。
- compatible 为 `sprd,ufshc`,控制器 `22000000.ufs`,逻辑与物理块均为 4096 字节。
- userdata 为 sda75,FBE+metadata 加密,Android 实际 /data 来自 dm-39。
- SCSI WWID `eui.53414d53554e4700` 解码只是 SAMSUNG,不能作唯一身份。实际 UFS serial descriptor 可读。
- 与旧 eMMC U30 Air 的电池 DT 对照,50 项一致,但终止充电电流从 300000 变为 420000 µA。说明可复用机型业务,却不能假设所有板级参数完全相同。
## 2. 分清四种单位与设备命名
| 数据 | 单位/含义 |
| --- | --- |
| sysfs 的 start、size | 固定为 512 字节 sector;即使设备是 4Kn 也不变 |
| GPT 头与分区条目的 LBA | 实际设备逻辑块,本次为 4096 字节 |
| ext4/F2FS 的 block | 文件系统自己定义;不得从 UFS 逻辑块推导 |
| 用户界面的 GiB | 字节数除以 2^30 |
统一对上层输出字节或明确的 512-byte sectors,仅在 GPT 编解码边界换算:
```text
factor = logical_block_bytes / 512
start512 = gpt_start_lba * factor
end512_inclusive = (gpt_end_lba + 1) * factor - 1
gpt_start_lba = start512 / factor
gpt_end_lba = (end512_inclusive + 1) / factor - 1
backup_header_lba = disk_size512 / factor - 1
```
整数除法前验证对齐;不允许默默截断。4Kn 上请求 2049 个 512-byte sectors 必须拒绝,不能写成 256 个逻辑块。
本机例子:userdata GPT 起点 1534464 × 4096 = sysfs 起点 12275712 × 512。把它当 512B GPT 会差八倍。
节点分别为 `mmcblk0p75` 和 `sda75`。不要用 `${node%p*}` 或 `${disk}pN` 处理所有介质,也不要假设用户 LUN 总为 sda。从 userdata 的真实 sysfs 父盘建立拓扑,并确认它属于内置 MMC/UFS 控制器;排除 USB/SATA 盘及其同名 userdata 分区。多个内置匹配项不能猜选。
UFS 身份使用实际 serial descriptor,结合 manufacturer 和 LUN 生成带介质域标识的摘要;本次兼容旧事务 CID 字段宽度,使用 SHA256(`ufs:厂商:serial:LUN`) 前 32 个十六进制字符。字段叫 CID 不代表 UFS 有 eMMC CID;状态中另有 STORAGE_KIND。不存在唯一身份时明确拒绝写入,不以通用 WWID、容量或 sda 名字代替。
## 3. GPT 不能只改单个解析器
同时处理电脑与设备两端:
- 按实际逻辑块读取主头 LBA 1 和盘尾备份头,再由头确定表范围。不要固定备份“前 34、后 33 个 512B sectors”。
- 检查两头 CRC、两表 CRC/内容、磁盘 GUID、表条目大小/数量、可用区域和分区不重叠;所有读取/写入范围检查使用一致单位。
- 保留 protective MBR、无关分区条目、唯一 GUID、属性和头所在逻辑块的其他字节。
- 新增、缩容、扩容、重装、续装、卸载归还空间都走同一个单位约定;不要只让首次安装能识别。
- 写入时先完成并校验备份 GPT,再写主 GPT,flush 后回读;失败保留原备份和事务记录。
- Android userdata 内文件系统的空闲空间,不等于 GPT 未分配空间。容量大也不能直接在其尾部覆盖。
- 旧 eMMC 固定裸偏移安装是显式的历史模式,不把其 ROOT_OFFSET 或 GPT 尾预留套到 UFS。
## 4. 内核以本机 DT 和原厂驱动为参照
同一厂商的主线 UFS 驱动并不保证适配同一 DT binding。本例原厂使用 `sprd,ufshc`,而主线另有 `sprd,ums9620-ufs`;不能仅改 compatible 就认为 PHY、reset 和 efuse 已对齐。
本次使用既有 Docker volume 中的 ZTE U30 Air vendor 源码为参照,缓存 HEAD 为 `b50db5b6224c11db42a246e8fcdaad1e1d59f478`。它与实机内核 build ID 不同,必须如实记录;结合实机 DT 与启动结果核对,不宣称二者是完全同版。
移植核对表:
1. clocks/父时钟、resets、regulator、syscon、PHY SRAM 和两个 lane 的 efuse。
2. PHY/DME 初始化与 reset 顺序;efuse provider 未就绪应保留 probe defer。
3. Hibern8 的参考时钟与 hclk 切换、时钟门控延迟及 suspend/resume 顺序。不能靠关闭省电、降速、定时 reset 来掩盖不稳定。
4. UFS variant ops 在各目标内核的 API、const 参数、协商前后参数所有权和 remove/PM 接口。
5. 旧 Android 5.4 的私有 RPMB、HPB、crypto 回调不可直接挪入主线;未实现的能力不置位。能读原始 LUN 不意味着能解密 Android /data。
6. UFS 用户 LUN 需要在挂载根之前可用,选择内建或完整配套的 initramfs 模块;rootfs 里有模块名不代表早期可启动。
**已踩的坑:** lane1 校准值 `0x96910000` 的最高位为 1。有符号 int 同时承载错误码和校准结果会误判;应使用 int 返回码加独立 u32 输出,并检查 nvmem 返回长度与字节序。
本例 6.18 与 7.2 的 `pwr_change_notify` 回调签名不同,按已核验目标内核 API 显式适配;不能只编过其中一条线。新增驱动仅绑定对应 compatible,普通 eMMC 板不应额外探测不存在的 UFS。
## 5. 公共接入面与代码入口
MU300 本次实现的源文件可作为移植参考(尚未提交/发布时,应核对当前工作区,不能假设远端已有):
| 范围 | MU300 入口 | 迁入 E5 时必须核对 |
| --- | --- | --- |
| 存储拓扑/身份 | `rootfs/overlay/opt/mu300/lib/storage.sh`、`installer/backend/storage.py` | 保留 E5 命名与运行布局,统一来源,拒绝旧/新算法静默回退 |
| GPT | `installer/backend/gpt.py`、`desktop/boot/mu300-gpt` | 对照 E5 的 Python 与设备侧 GPT 工具,统一 512/4K 转换 |
| 早期启动 | `boot/init`、`boot/build-boot-image.py` | E5 的 boot、misc、vendor/NV 发现、根挂载及日志区,不照搬固定偏移 |
| 离线安装 | `desktop/boot/storage.sh`、`part-prepare.sh`、`install-part.sh` | E5 的 `boot/part-prepare.sh`、`boot/install-part.sh` 及各阶段载荷交接 |
| Android 写入 | `desktop/android-write-part.sh`、`android-write-free.sh` | E5 对应写入脚本的父盘、身份、硬范围和 flush/readback |
| 用户态运行 | `android-vendor-start`、`early-recorder`、`mu300-update` | E5 基带/NV 分区映射、启动健康确认和更新入口 |
| 安装器及卸载 | `installer/backend/{adapter,service,install_evidence,uninstall,uninstall_worker,mu300_update}.py` | 本仓库每条更新/续装/卸载路径,不能只替换 GUI 探测 |
| 分发 | `desktop/package.py`、`desktop/boot_image.py`、`installer/build.py`、`installer/package_gui.py` | Python、冻结 EXE、Mac 后端、诊断/卸载 ramdisk 都携带同一库并计入源码指纹 |
特别注意:卸载 worker 需要的存储库必须与其 SHA256SUMS 使用同一归档命名空间。本例为 `openwrt-uninstall/storage.sh`;把库放到 `/etc` 却按工作目录校验,会使实际卸载失败。测试须逐项核验归档清单所指文件确实存在且摘要一致。
调压、LED、充电和基带逻辑保持原有机型隔离。以本机 SML 为例:A/B 全文件哈希相同,与已验证旧固件仅认证区域不同、可执行载荷一致后,才补完整固件哈希识别;不因 SoC 相同给所有 SML 放行。
## 6. 小范围诊断启动与恢复流程
首次用只读 initramfs 确认存储,不直接启动会写 userdata/NV 的整套业务。
1. 从当前 Android 读取并校验当前槽、目标备用槽、两槽 boot、原启动控制;保存电脑端备份。BSP 是否不同先比较,不能擅自覆盖当前 Android 槽。
2. 使用本机 boot 容器/DT 及匹配的 Image、模块。MU300 现有 LK 需要 `upstream/wrap-image.py` 的加载地址包装;换 Image 后必须重新包装,不能复用旧 Image.lk,也不能假设畅行 60 使用相同包装。
3. 通过 ADB/root 写已核验备用 boot,flush 并回读完整摘要,再按本机已有编解码器写一轮试启动记录。只动明确的控制范围,不重写整个 misc。
4. 诊断 initramfs 不挂载 Android、不启基带、不写 NV;报告保存在内存。用独立 USB 地址,DHCP 不下发默认网关/DNS,避免测试电脑改走设备上网。
5. 诊断环境的 BusyBox shell/命令、NCM 和控制台需实测;telnet console 需要挂载 devpts,否则“端口能连但立刻 EOF”是诊断环境问题,不能认定 UFS 坏了。
6. 设置有界回退。本次 probe 在 180 秒尝试强制重启且保留 bootloader 试启动次数回退;这不是任何死锁都能保证恢复,不能代替电脑备份。
7. 先读取型号、版本、LUN、分区和小范围 GPT 摘要;再做间隔读取与有限连续读取。采集省电状态、错误计数/日志,不为通过测试关闭门控。
8. 返回 Android 后核对真实槽位及当前镜像身份,恢复原备用 boot 与**当次备份的原 32 字节控制记录**;回读摘要,再确认 GPT 不变。不要生成一份“默认 A”的记录冒充恢复。
9. 清理且仅清理本次在设备建立的上传目录;保留电脑端镜像、日志和恢复回执。不要因一次诊断顺便清理其他 Agent 的备份或 NV。
另一项失败经验:早期一次 bootloader RAM 引导虽然返回 OK,实机仍进入原 Android;因此返回 OK 不能算新内核启动成功。后续用户已禁止 fastboot,不再使用该方式。验收以真实 uname、驱动绑定、分区和新 init 的证据为准。
## 7. 二进制传输及测试边界
- 本机发现 Android `su -c` 链路可能将原始二进制 LF 变为 CRLF。备份读回电脑须使用已验证的二进制传输实现;本次用设备端 base64 编码、电脑端解码并核对长度/哈希。不要拿损坏的 DTB/GPT 推导硬件结论。
- 初期构造的未做 LK 包装的诊断镜像在刷入前即替换,没有作为有效实机测试;记录应区分“构造过”与“部署过”。
- 避免整盘备份/扫描。按任务读取 BSP、boot、GPT 和必要固件;IMEI/NV、serial 不进公开报告。
- FBE/metadata 加密与 UFS 是独立维度。即使原始 LUN 可读,也不能从 initramfs 读取被加密的安装载荷;需要已完成的两阶段安装/外部传输流程及用户明确清空授权。
验证至少覆盖:
| 层次 | 必测内容 |
| --- | --- |
| 512/4096 离线几何 | 主备 CRC、空闲区增删、缩容布局恢复、不对齐拒绝、损坏与重复请求拒绝、拒绝后原表未变化 |
| 身份和拓扑 | eMMC 不回归、UFS 非 sda 的命名、USB 同名 userdata 排除、重复内置标签拒绝、LUN 边界 |
| 实际设备工具 | 运行发布的 ucode/BusyBox worker,而非仅 Python 镜像;独立解析器检查输出 |
| 更新与卸载 | 两种 Android 槽位、重装/续装、保容量、恢复工作环境、备用 boot 和清单资源完整性 |
| 内核只读启动 | 实际 uname/driver/LUN、几何一致、GPT 摘要一致、空闲后恢复读取、有限连续读及错误日志 |
| 完整系统 | 基带、WAN、热点、USB、充电/OTG、LED、CPU、NV 来源;不能靠临时脚本绕过正式发现路径 |
| 长期硬件 | 正常写入/flush、重启、空闲恢复、实际 suspend/resume;有授权与恢复条件再做掉电场景 |
本次真实结果:两条内核均识别 75 分区;6.18 做 15 次间隔 2 秒的 GPT 读取及 3 次 32 MiB 连续读取,分别摘要一致,未见 UFS I/O 错误。门控开启、10 ms、rpm/spm level 3、power/control=auto;这不证明长期写入或整机 suspend 已通过。
MU300 对应回归入口(WSL 中运行;Windows 可运行环境适用的安装器测试):
```sh
python3 tests/test_ufs_storage.py
python3 tests/ufs_gpt_runtime.py
python3 -m unittest discover -s installer/tests
python3 -m unittest discover -s installer/tests -p test_uninstall.py
python3 -m unittest discover -s tests -p test_boot_partition_wait.py
python3 -m unittest discover -s tests -p test_update_layouts.py
python3 -m unittest discover -s tests -p test_u30air_integration.py
```
`ufs_gpt_runtime.py` 使用本机已有 OpenWrt Docker 镜像和自有稀疏文件,不访问物理设备;Linux 与 Windows 的跳过项/依赖不同,报告实际运行结果,不能把跳过写成通过。MU300 的 U30 专项报告为 `docs/U30AIR-UFS-ADAPTATION-20261027.zh-CN.md`。
## 8. 畅行 60 的下一次交接清单
以下在 E5 仓库完成,目前均未宣称适配:
- [ ] 设备接入后先记录真实型号、SoC、原厂版本、DT/驱动、UFS 拓扑和加密;“畅行 60”名称不能代替硬件证据。
- [ ] 比较 E5 既有内核是否已经有对应 UFS 控制器和原厂 binding;有可用原厂驱动时先核对其行为,不默认移入 MU300 的主线驱动。
- [ ] 移植统一存储身份与 512/4K GPT 合约。2026-10-27 核对 E5 `installer/backend/gpt.py` 仍固定 512 字节;`boot/part-prepare.sh` 仍限制 mmcblk 节点并读 MMC CID,不能直接在 UFS 上执行分区计划。
- [ ] 扫 E5 安装器、boot、NV 分区发现、更新、卸载、切系统和日志位置的 MMC 假设,保留 E5 自身 NV 保留/同步事务,不能因盘符变化漏掉它们。
- [ ] 用实际新机 DT 建立独立 device profile;板级差异进 profile,纯存储修复进公共层,不能顺手更改现有 E5/T551M/M8 等板的充电、显示、AT 时序。
- [ ] 编译通过 `tools/build-release.py`,仅用登记的已有工作区/准备脚本;不新克隆完整内核、不重复导出 rootfs、不迁 C 盘。
- [ ] 先完成只读诊断启动和恢复回执,再做完整系统及有授权的安装验收。内核、BTF、initramfs/rootfs 模块必须来自同一构建。
- [ ] 构建 Windows/macOS 安装器时将新资源纳入冻结载荷和源码指纹;更新完整包/OTA/Diff Studio 的实际设备校验也要覆盖 UFS。
交付时分别列出源码、构建、部署、用户验收与未测试项,保留明确的下一步,不写“UFS 都一样,直接复制就能用”。
+15 -3
View File
@@ -40,6 +40,12 @@ Linux、Intel Mac 或需要 Python 命令行入口时,可使用 **OpenWrt-Inst
选择需要分给 OpenWrt 的容量。安装器优先使用已有未分配空间;不足时才需要缩小 Android 用户数据分区。最终计划会列出 Android 保留空间、OpenWrt 分配空间,以及是否会清空数据。
图形安装器默认优先在线保数据缩容,支持 eMMC 和 UFS。F2FS 的搬移与缩小由正在运行的 Android 内核完成,FBE/metadata 加密的数据通过 Android 已解密映射处理,无需在 initramfs 解密。成功后正常重启 Android、校验主备超级块、UUID、映射容量及 GPT,再继续安装。不会清空 Android,也不需要重新设置 Magisk。
若文件系统、映射或原厂内核不支持,会说明原因。在线尝试失败后,只有确认文件系统和 GPT 均未改变才提供清空数据的后备方案;输入 `yes` 仅生成新计划,仍须单独确认清空影响。状态不明时保留日志和备份,不能直接格式化。也可在“需要缩容时”主动选择原有离线清空方案;已有足够未分配空间时不需要缩容或清空。
请在整个缩容和 GPT 提交期间保持供电。ADB 断开不会终止设备内的缩容事务;重连后从原记录继续,不要另建安装任务。不能提供准确百分比时会显示当前阶段和耗时,不会虚报进度。未经本机硬件测试的内核仍需实际验证,不能只凭 eMMC/UFS 类型判断支持。
**“使用全部已分配的 OpenWrt 分区容量”建议保持开启**:例如分配 10 GiB,安装完成后便使用这 10 GiB,不会额外占用 Android 的剩余空间。
首次启动会进行离线分区准备,可能需要数分钟,完成后设备会自动重启一次。数据较多时可能更久,请保持供电,不要因暂时没有画面而强制重启。
@@ -48,7 +54,7 @@ Linux、Intel Mac 或需要 Python 命令行入口时,可使用 **OpenWrt-Inst
### 加密 userdata:重置后自动续装
如果加密的 Android 用户数据分区必须缩容,**Android 应用、账号、照片和内部存储会全部清空**。请先自行备份个人数据,并仔细核对安装计划中的重置提示。
只有选择了清空数据的离线缩容方案时,**Android 应用、账号、照片和内部存储会全部清空**;在线保数据方案不执行重置。请先自行备份个人数据,并仔细核对安装计划中的重置提示。
1. 保持安装器运行及设备供电,等待分区准备和恢复出厂完成。设备可能重启多次。
2. 进入 Android 后,完成初始设置。
@@ -176,13 +182,19 @@ For internal installation, choose the capacity to allocate to OpenWrt. Available
Leave **Use all allocated OpenWrt partition capacity** enabled to fill the chosen allocation. For example, allocating 10 GiB gives OpenWrt that 10 GiB without taking additional space from Android.
The graphical installer prefers online F2FS preservation on eMMC and UFS when shrinking is required. Android’s running kernel relocates data through the mounted/decrypted volume, including supported FBE/metadata-encrypted layouts. The installer commits GPT and reboots Android normally to verify both superblocks, UUID, mapping capacity and the reclaimed gap before installation continues. No Android setup or Magisk reinstallation is needed after this path.
Unsupported filesystems, mappings or kernels are explained. If an attempted resize fails, an erase-data fallback is offered only after verifying the filesystem and GPT are unchanged. Type `yes` to generate a new erase-data plan, then review and confirm it separately. Unknown intermediate states require recovery rather than automatic formatting. The original offline erase-data option remains selectable. Existing sufficient unallocated space is always used without shrinking or resetting Android.
Keep power connected through resize and GPT commit. A detached device-side worker survives ADB loss; reconnect and resume the saved transaction. Kernel support requires hardware validation, not just identifying the storage as eMMC or UFS.
The first boot performs offline partition preparation. This may take several minutes or longer with more data, then the device restarts automatically. Keep power connected and do not force a restart because the screen is temporarily blank.
To replace an existing internal OpenWrt installation, choose Reinstall internal partition under Advanced options. No TF card is needed.
### Encrypted userdata and reset
If encrypted Android userdata must be resized, **all Android apps, accounts, photos and internal storage will be erased**. Back up personal files first and review the reset warning in the installation plan.
Only the erase-data offline fallback resets Android: **all Android apps, accounts, photos and internal storage will be erased**. Online preservation does not reset Android. Back up personal files first and review the reset warning in the installation plan.
1. Keep the installer running and the device powered while partition preparation and factory reset finish. The device may restart more than once.
2. Complete Android initial setup.
@@ -272,4 +284,4 @@ Check the original computer’s transaction directory and any exported full back
#### When is data erased?
TF installation erases the selected card target. Reinstallation replaces existing OpenWrt and its settings. Encrypted userdata that must be resized requires an Android reset. Review the final plan and back up data before confirming.
TF installation erases the selected card target. Reinstallation replaces existing OpenWrt and its settings. An explicitly selected offline erase-data shrink resets Android; the online preservation path does not. Review the final plan and back up data before confirming.
+20 -1
View File
@@ -20,7 +20,7 @@ Stages include `uninstall_prepare`, `uninstall_offline`, existing Android setup/
On a paused uninstall, `resume`/`retry` optionally accept an explicitly selected `serial` if the ADB endpoint changed. The new connection must already have Android debugging/root ready and match the original CID, profile and planned Android slot. The coordinator acquires CID/serial ownership before its read-only probe, saves only the transport change and retains the original boot/layout evidence. Connection history uses nested `serial` fields and is redacted from public snapshots. No automatic rebinding or device writes occur during this selection. Imported uninstall snapshots are also revalidated semantically: recomputing checksums cannot authorize changes to NV/unrelated entries, a different root range or suppressing a required reset.
Commands are allowlisted in both Rust and Python: hello, snapshot, list, package, devices, adb_connect, adb_disconnect, probe, probe_update, plan, start, resume, retry, cancel, can_close, export, import, diagnostics, verify_openwrt. There is no shell/exec command. A frontend-selected serial is checked against an actual device. All device ADB operations use that serial; eMMC CID and profile are rechecked after reset. SSH maintenance binds the key fingerprint between planning and execution; final verification binds the hardware CID. A plan cannot become executable without `confirmed:true` on its persisted transaction ID.
Commands are allowlisted in both Rust and Python: hello, snapshot, list, package, devices, adb_connect, adb_disconnect, probe, probe_update, plan, start, resume, retry, cancel, can_close, export, import, diagnostics, verify_openwrt, online_fallback. There is no shell/exec command. A frontend-selected serial is checked against an actual device. All device ADB operations use that serial; eMMC CID and profile are rechecked after reset. SSH maintenance binds the key fingerprint between planning and execution; final verification binds the hardware CID. A plan cannot become executable without `confirmed:true` on its persisted transaction ID.
`adb_connect` accepts one validated `address` (IPv4, hostname or bracketed IPv6, optional port defaulting to 5555). It invokes only the host ADB connect service, then enumerates devices; readiness comes from that list, never connect-output text. The result contains `endpoint`, `state` and `devices` (with a `wireless` flag). No package verification is needed. During an installation, connection is allowed only at safe Android setup/authorization waits and cannot rebind the transaction. `adb_disconnect` requires an exact observed wireless `serial`, returns the remaining devices, and is rejected while a worker is active. It also acquires the shared serial device mutex, so another installer cannot disconnect a transport in use. It cannot disconnect USB devices or all devices. Neither command enables debugging, runs a device shell, pairs Android, restarts ADB or changes network adapters/routes.
@@ -70,3 +70,22 @@ Schema 3 extends schema 2 with `installation_evidence`: hashes of the installed
On import/restart, before/after snapshots are recomputed from the saved **current** layout using the adjacent-root rule. Hash changes cannot authorize a wider target or alter unrelated entries. Once armed, resume uses the new uninstall record, not any original installation record or deleted root markers. Recovery from an interrupted inactive-boot write still requires exact saved GPT/misc/Android checks; when boot staging alone must be retried, the original Linux boot proof comes from its checksummed **new uninstall backup** while root evidence is checked live. Completed GPT work and formatting are never replayed. If this new record is lost while `openwrt.uninstall=1` is staged, the existing pending-operation guard still stops new plans; absence of an old installation record is not permission to guess an interrupted removal.
`notice` events carry a fixed localized `code` (`mtp_disabled` or `mtp_disable_failed`) and optional device `label`. Only the MU300 adapter enables the Windows wired-ADB MTP workaround for a selected device; enumeration alone, wireless ADB, macOS and the E5 adapter are unchanged. Windows problem code 22 confirms successful disable. A failure only emits a warning and does not stop the original workflow. MTP is never automatically re-enabled.
Online F2FS internal installation (protocol 1 extension): the plan may contain
`shrink_strategy: online-f2fs`, `new_sectors` (512-byte units), `target_blocks`
(4096-byte F2FS blocks), and a preserved-data impact. Only the active Android
kernel resizes the mounted volume. A single detached native worker owns the
filesystem/GPT commit; ADB loss and cancellation cannot split that operation.
The host retains original/candidate GPT, UUID, role/boot identity and bounded
metadata-encryption backup. Known mixed copies resume from readback; unknown
bytes require recovery. Android is rebooted normally before installation uses
the reclaimed gap. The original pre-shrink backup remains the uninstall origin.
`online_fallback` accepts only a transaction ID, saved nonce and literal `yes`.
It is available after a verified unchanged failed attempt, with no active worker.
It re-probes the selected device and generates a new **unconfirmed** erase-data
plan; it does not format anything. The UI must show that plan and require normal
`start` confirmation again. Existing offline and explicitly selected format paths
are retained. Unsupported initial layouts explain `online_unavailable` in the
reviewed plan. No automatic erase follows a failed resize or transport error.
+16 -22
View File
@@ -14,7 +14,7 @@ import sys
import time
from types import SimpleNamespace
from . import gpt
from . import gpt, storage as storage_io
from .state import Pending, RecoveryRequired, atomic_json, sha
from .transport import Adb, push_chunks
from .boot_image import boot_installed_e5, boot_installed_mu300
@@ -264,25 +264,16 @@ class Adapter:
device['profile'] = self.legacy.android_profile(device['model'] + '\n' + properties['ro.product.device'], properties['ro.board.platform'])
# Trial boot uses only the boot signature, boot-chain check and misc.
# Do not access the root filesystem to detect an installation.
text = self.adb.shell('set -e; d=$(readlink -f /dev/block/by-name/userdata); n=${d##*/}; b=${n%p*}; '
'echo NODE=$n; echo CID=$(cat /sys/class/block/$b/device/cid); '
'echo START=$(cat /sys/class/block/$n/start); echo SIZE=$(cat /sys/class/block/$n/size); '
'echo DISK_SIZE=$(cat /sys/class/block/$b/size); '
'echo FREE=$(df -Pk /data | tail -n1 | awk \'{print $4}\'); '
'echo SOURCE=$(awk \'$2=="/data" {print $1;exit}\' /proc/mounts); '
'for u in /sys/class/block/${b}p*/uevent; do '
'grep -qE "^PARTNAME=(e5root|mu300root)$" "$u" && { n=${u%/uevent}; echo ROOT=${n##*/}; } || true; done; '
'cards=""; for p in /sys/class/block/mmcblk*; do k=${p##*/}; '
text = self.adb.shell(storage_io.inventory_script(self.root), root=True)
storage = storage_io.parse_inventory(text)
# Removable MMC detection remains separate from internal UFS LUNs.
cards = self.adb.shell('cards=""; for p in /sys/class/block/mmcblk*; do k=${p##*/}; '
'case $k in *p[0-9]*|*boot*) continue;; esac; '
'[ "$k" = "$b" ] || cards="$cards $k"; done; '
'[ "$(cat "$p/device/type" 2>/dev/null)" = SD ] || continue; cards="$cards $k"; done; '
'set -- $cards; if [ "$#" -eq 1 ]; then '
'if [ -b /dev/block/"${1}p1" ]; then echo TF=/dev/block/"${1}p1"; '
'elif [ -b /dev/block/"$1" ]; then echo TF=/dev/block/"$1"; fi; fi', root=True)
storage = dict(line.split('=', 1) for line in text.splitlines() if '=' in line)
if not re.fullmatch(r'mmcblk\d+p\d+', storage['NODE']) or not re.fullmatch('[a-f0-9]{32}', storage['CID']):
raise ValueError('Cannot establish eMMC identity / 无法确认闪存身份')
for key in ('START', 'SIZE', 'DISK_SIZE', 'FREE'):
storage[key] = int(storage[key])
'if [ -b /dev/block/"${1}p1" ]; then echo /dev/block/"${1}p1"; '
'elif [ -b /dev/block/"$1" ]; then echo /dev/block/"$1"; fi; fi',root=True).strip()
if cards: storage['TF'] = cards
encrypted = properties['ro.crypto.state'] == 'encrypted' or properties['ro.crypto.type'] in ('file', 'block') or storage['SOURCE'].startswith(('/dev/block/dm-', '/dev/mapper/'))
device.update(cid=storage['CID'], storage=storage, encrypted=encrypted,
encryption_state=properties['ro.crypto.state'], encryption_type=properties['ro.crypto.type'],
@@ -323,10 +314,11 @@ class Adapter:
return device
def read_gpt(self, storage):
disk = '/dev/block/' + storage['NODE'].split('p')[0]
disk = '/dev/block/' + storage_io.disk_node(storage['NODE'])
sectors = storage['DISK_SIZE']
primary = self.adb.read(f'dd if={disk} bs=512 skip=1 count=1 2>/dev/null')
backup = self.adb.read(f'dd if={disk} bs=512 skip={sectors-1} count=1 2>/dev/null')
primary_cmd,backup_cmd=storage_io.gpt_header_commands(storage)
primary = self.adb.read(primary_cmd)
backup = self.adb.read(backup_cmd)
front, tail = gpt.gpt_backup_layout(primary, backup, sectors)
first = self.adb.read(f'dd if={disk} bs=512 count={front} 2>/dev/null')
last = self.adb.read(f'dd if={disk} bs=512 skip={tail} count={sectors-tail} 2>/dev/null')
@@ -469,13 +461,15 @@ class Adapter:
data = dict(node=s['NODE'], cid=s['CID'], start=s['START'], size=s['SIZE'])
state = dict(version=2, phase='awaiting-android', token=token, serial=record['device']['serial'],
model=record['device']['model'], data=data, target=s['SIZE'], need=plan['openwrt_bytes']//512,
android_slot=record['device']['slot'].removeprefix('_'),
linux_slot='b' if record['device']['slot']=='_a' else 'a',
root_start=plan['gap_start'], grow=int(args.grow_fs), raw_size=raw, apn='',
ssid=m.default_hotspot_name(), key=secrets.token_urlsafe(12),
boot_sha=sha(self.root/'files/boot.img'), image_sha=sha(self.root/'files/openwrt.ext4.gz'))
path = directory/'transaction.json'
atomic_json(path, state)
self.saved(path, state)
disk = '/dev/block/'+s['NODE'].split('p')[0]
disk = '/dev/block/'+storage_io.disk_node(s['NODE'])
for name, content in [('before-first', space['first']), ('before-last', space['last']), ('new-first', first), ('new-last', last),
('marker', ('E5-PART-PREPARED-V2 '+token+'\n').encode().ljust(512, b'\0'))]:
local = directory/(name+'.bin')
+29 -14
View File
@@ -3,34 +3,47 @@ import struct
import uuid
import zlib
def sector_size(first):
matches = [n for n in (512,4096) if first[n:n+8] == b'EFI PART']
if len(matches) != 1: raise ValueError('Missing or ambiguous GPT logical sector size')
return matches[0]
def gpt_backup_layout(primary, backup, sectors):
block = len(primary)
if block not in (512,4096) or len(backup) != block or sectors % (block//512):
raise ValueError('Unsupported GPT logical sector size')
factor = block//512
logical_sectors = sectors//factor
def header(raw,at):
if len(raw)!=512 or raw[:8]!=b'EFI PART':raise ValueError('Invalid GPT header')
if len(raw)!=block or raw[:8]!=b'EFI PART':raise ValueError('Invalid GPT header')
size=struct.unpack_from('<I',raw,12)[0]
if not 92<=size<=512:raise ValueError('Invalid GPT header size')
if not 92<=size<=block:raise ValueError('Invalid GPT header size')
check=bytearray(raw[:size]);expected=struct.unpack_from('<I',check,16)[0];check[16:20]=bytes(4)
if zlib.crc32(check)!=expected:raise ValueError('GPT header checksum failed')
current,alternate=struct.unpack_from('<QQ',raw,24)
table,count,entrysize=struct.unpack_from('<QII',raw,72)
if current!=at or count<1 or count>1024 or entrysize!=128:raise ValueError('Unsupported GPT geometry')
return alternate,table,(count*entrysize+511)//512,raw[56:72],raw[80:92]
a=header(primary,1);b=header(backup,sectors-1)
if a[0]!=sectors-1 or b[0]!=1 or a[3:]!=b[3:]:raise ValueError('GPT copies disagree')
front=a[1]+a[2];tail=b[1]
if not (2<=a[1]<front<=4096 and sectors-4096<=tail and tail+b[2]==sectors-1):raise ValueError('GPT backup range is invalid')
return alternate,table,(count*entrysize+block-1)//block,raw[56:72],raw[80:92]
a=header(primary,1);b=header(backup,logical_sectors-1)
if a[0]!=logical_sectors-1 or b[0]!=1 or a[3:]!=b[3:]:raise ValueError('GPT copies disagree')
front=(a[1]+a[2])*factor;tail=b[1]*factor
if not (2*factor<=a[1]*factor<front<=4096 and sectors-4096<=tail and tail+b[2]*factor==sectors-factor):raise ValueError('GPT backup range is invalid')
return front,tail
def gpt_space(first,last,sectors):
"""Validate both on-disk GPT copies and return aligned, genuinely unallocated ranges."""
primary=first[512:1024];backup=last[-512:]
block=sector_size(first);factor=block//512
primary=first[block:2*block];backup=last[-block:]
front,tail=gpt_backup_layout(primary,backup,sectors)
if len(first)!=front*512 or len(last)!=(sectors-tail)*512:
raise ValueError('Incomplete GPT snapshot')
start,end=struct.unpack_from('<QQ',primary,40)
if (start,end)!=struct.unpack_from('<QQ',backup,40) or not front<=start<=end<tail:
start_lba,end_lba=struct.unpack_from('<QQ',primary,40)
start,end=start_lba*factor,(end_lba+1)*factor-1
if (start_lba,end_lba)!=struct.unpack_from('<QQ',backup,40) or not front<=start<=end<tail:
raise ValueError('GPT usable bounds disagree or overlap metadata')
table,count,entry=struct.unpack_from('<QII',primary,72)
data=first[table*512:table*512+count*entry]
data=first[table*block:table*block+count*entry]
if data!=last[:count*entry] or zlib.crc32(data)!=struct.unpack_from('<I',primary,88)[0]:
raise ValueError('GPT table checksum/copy mismatch')
parts=[];empty=[]
@@ -38,6 +51,7 @@ def gpt_space(first,last,sectors):
raw=data[i*entry:(i+1)*entry]
if raw[:16]==bytes(16):empty.append(i);continue
a,b=struct.unpack_from('<QQ',raw,32)
a,b=a*factor,(b+1)*factor-1
name=raw[56:128].decode('utf-16-le').split('\0',1)[0]
if not start<=a<=b<=end:raise ValueError('GPT partition outside usable bounds: '+name)
parts.append({'n':i+1,'start':a,'end':b,'name':name})
@@ -48,11 +62,12 @@ def gpt_space(first,last,sectors):
limit=(part['start']//2048)*2048
if limit>aligned:gaps.append((aligned,limit-aligned))
at=part['end']+1
return {'front':front,'tail':tail,'parts':parts,'empty':empty,'gaps':gaps,
return {'sector_size':block,'front':front,'tail':tail,'parts':parts,'empty':empty,'gaps':gaps,
'largest':max((size for _,size in gaps),default=0) if empty else 0}
def gpt_add_root(first,last,sectors,offset,need,root_name="mu300root"):
info=gpt_space(first,last,sectors)
block=info['sector_size'];factor=block//512
if any(p['name']==root_name for p in info['parts']):raise ValueError('mu300root already exists')
if not info['empty'] or need<4194304 or offset%2048 or need%2048 or not any(
offset>=a and offset+need<=a+n for a,n in info['gaps']):
@@ -60,10 +75,10 @@ def gpt_add_root(first,last,sectors,offset,need,root_name="mu300root"):
idx=info['empty'][0];entry=bytearray(128)
entry[:16]=uuid.UUID('0fc63daf-8483-4772-8e79-3d69d8477de4').bytes_le
entry[16:32]=uuid.uuid4().bytes_le
struct.pack_into('<QQ',entry,32,offset,offset+need-1)
struct.pack_into('<QQ',entry,32,offset//factor,(offset+need)//factor-1)
name=root_name.encode('utf-16-le');entry[56:56+len(name)]=name
copies=[]
for raw,header_offset,table_offset in ((first,512,struct.unpack_from('<Q',first,584)[0]*512),(last,len(last)-512,0)):
for raw,header_offset,table_offset in ((first,block,struct.unpack_from('<Q',first,block+72)[0]*block),(last,len(last)-block,0)):
new=bytearray(raw);new[table_offset+idx*128:table_offset+(idx+1)*128]=entry
count=struct.unpack_from('<I',new,header_offset+80)[0]
struct.pack_into('<I',new,header_offset+88,zlib.crc32(new[table_offset:table_offset+count*128]))
+4 -3
View File
@@ -4,6 +4,7 @@ Only fixed, small files are read from an idle ext4 partition. No mount, repair,
device-side helper, executable from the installed system or filesystem write.
This proves a known installation, not the historical size of Android userdata.
"""
from . import storage as storage_io
import hashlib
import re
import stat
@@ -152,9 +153,9 @@ def inspect_installation(adapter, device, root, *, boot_backup=None):
"""Return fresh, device-bound evidence. Caller has already validated both GPTs."""
try:
adb = adapter.adb
storage = device['storage']; disk = storage['NODE'].split('p')[0]
node = disk+'p'+str(root['n']); capacity = (root['end']-root['start']+1)*512
if (not re.fullmatch(r'mmcblk\d+p\d+',node) or storage.get('ROOT') != node or
storage = device['storage']; disk = storage_io.disk_node(storage['NODE'])
node = storage_io.part_node(disk,root['n']); capacity = (root['end']-root['start']+1)*512
if (not re.fullmatch(r'(?:mmcblk\d+p|sd[a-z]+)[1-9][0-9]*',node) or storage.get('ROOT') != node or
storage.get('ROOT_START') != root['start'] or storage.get('ROOT_SIZE')*512 != capacity):
raise ValueError('Kernel OpenWrt node differs from verified GPT; reboot Android / 内核分区节点与 GPT 不符,请重启 Android')
# Android must not have the target mounted or mapped. Only metadata in
+1 -1
View File
@@ -93,7 +93,7 @@ if [ -s /etc/mu300/desktop-mode ]; then cat /etc/mu300/desktop-mode; else
case "$d" in /dev/mmcblk[1-9]*) echo sd ;; *) echo legacy ;; esac
fi''').strip().splitlines()
if (len(info) != 4 or info[0] not in ('f50', 'v50', 'u30air') or info[1] not in ('a', 'b')
or not re.fullmatch(r'/dev/mmcblk\d+p\d+', info[2])):
or not re.fullmatch(r'/dev/(?:mmcblk\d+p|sd[a-z]+)[1-9][0-9]*', info[2])):
raise ValueError('Not a supported MU300 runtime')
mode = info[3]
if mode not in ('sd', 'part', 'data-image', 'legacy'):
+346
View File
@@ -0,0 +1,346 @@
"""Android-owned F2FS resize; the offline formatter remains a separate choice.
Geometry is in bytes/512-byte sectors at the host boundary, GPT logical blocks
only inside table edits. The kernel works through the mounted decrypted volume.
No userspace decryption, raw-offset Linux root, or forced BLKRRPART is used.
"""
import hashlib
import json
import os
from pathlib import Path
import re
import secrets
import shlex
import struct
import sys
import time
from . import gpt, storage
from .state import Pending, RecoveryRequired, atomic_json, sha
from .uninstall import android_volume, partition, table, with_table
class OnlineDecision(Exception):
"""No data was changed; an explicit new erase-data plan may be requested."""
def superblocks(raw):
if len(raw) != 8192:
raise ValueError('Incomplete F2FS superblocks / F2FS 超级块读取不完整')
a, b = raw[1024:4096], raw[5120:8192]
if a != b or a[:4] != bytes.fromhex('1020f5f2') or struct.unpack_from('<II', a, 16) != (12, 9):
raise ValueError('F2FS superblocks disagree or are unsupported / F2FS 主备超级块不一致或格式不支持')
sections = struct.unpack_from('<I', a, 24)[0]
blocks = struct.unpack_from('<Q', a, 36)[0]
uuid = a[108:124].hex()
if not 0 < sections <= 65536 or not blocks or blocks % (sections*512) or uuid == '0'*32:
raise ValueError('Invalid F2FS geometry / F2FS 几何无效')
return dict(blocks=blocks, section_blocks=sections*512, uuid=uuid)
def inspect(adapter, device):
"""Read-only eligibility. A same-size ioctl is deferred until confirmation."""
try:
if device.get('encryption_type') == 'block':
raise ValueError('Legacy block encryption is not verified for online resize / 旧式块加密尚未验证在线缩容')
volume = android_volume(adapter.adb, device, allow_small=True)
if volume['filesystem'] != 'f2fs' or volume['mapping_overhead']:
raise ValueError('Online resize requires F2FS with a complete userdata mapping / 在线缩容要求 F2FS 且映射完整覆盖 userdata')
node = volume['source'].rsplit('/',1)[-1]
if node.startswith('dm-'):
slaves = adapter.adb.shell(f'for p in /sys/class/block/{node}/slaves/*; do [ -e "$p" ] && echo "${{p##*/}}"; done; true',root=True).split()
if slaves != [device['storage']['NODE']]:
raise ValueError('Layered or offset encryption mapping is unsupported / 不支持多层或带偏移的加密映射')
elif node != device['storage']['NODE']:
raise ValueError('Android mount is not the selected userdata / Android 挂载源不是所选 userdata')
geometry = superblocks(adapter.adb.read('dd if='+shlex.quote(volume['source'])+' bs=4096 count=2 2>/dev/null'))
if geometry['uuid'] != volume['uuid']:
raise ValueError('Filesystem identity changed while inspecting / 检查期间文件系统身份发生变化')
return dict(available=True, volume=volume, **geometry)
except (ValueError, RecoveryRequired) as error:
return dict(available=False, reason=str(error))
def allocation(device, requested):
info = device['online_shrink']
if not info.get('available'):
raise ValueError('Online resize is unavailable')
s = device['storage']
# Same MiB alignment as the existing offline/uninstall geometry contract.
sectors = ((s['SIZE']-requested//512)//2048)*2048
section = info['section_blocks']
blocks = (sectors*512//4096//section)*section
if (sectors*512 < 2 << 30 or blocks >= info['blocks'] or
blocks*4096 <= device['userdata_bytes']-device['free_bytes']+(2 << 30)):
raise ValueError('Insufficient free space for preserving Android / 保留 Android 数据的缩容空间不足')
return dict(new_sectors=sectors, target_blocks=blocks,
gap_start=s['START']+sectors, android_bytes=sectors*512)
def candidate(pair, sectors, node, old_size, new_size):
info = gpt.gpt_space(*pair,sectors)
data = partition(info,'userdata')
disk = storage.disk_node(node)
if (storage.part_node(disk,data['n']) != node or data['end']-data['start']+1 != old_size or
new_size <= 0 or new_size >= old_size or new_size % 2048):
raise RecoveryRequired('Userdata GPT geometry changed / userdata GPT 几何已变化')
updated = bytearray(table(pair[0]))
scale = info['sector_size']//512
if (data['start']+new_size) % scale:
raise ValueError('Target is not aligned to the logical block size')
struct.pack_into('<Q',updated,(data['n']-1)*128+40,(data['start']+new_size)//scale-1)
result = with_table(pair,updated,sectors)
after = partition(gpt.gpt_space(*result,sectors),'userdata')
if after['end']+1 != data['start']+new_size:
raise ValueError('GPT candidate size differs')
return result
def helper_files():
if getattr(sys,'frozen',False):
directory = Path(sys._MEIPASS)
binary, metadata = directory/'f2fs-online-arm64', directory/'online-helper/build.json'
else:
directory = Path(__file__).resolve().parents[1]/'device'
binary, metadata = directory/'f2fs-online-arm64', directory/'build.json'
info = json.loads(metadata.read_text(encoding='utf-8'))
if (info.get('protocol') != 1 or info.get('architecture') != 'aarch64-static-linux' or
sha(binary) != info.get('binary') or (binary.read_bytes()[:7] != bytes.fromhex('7f454c46020101') or binary.read_bytes()[16:20] != bytes.fromhex('0200b700'))):
raise ValueError('Online resize helper checksum/architecture differs / 在线缩容工具校验或架构不符')
source = directory/'f2fs-online.c'
if source.is_file() and hashlib.sha256(source.read_bytes().replace(b'\r\n',b'\n')).hexdigest() != info['source']:
raise ValueError('Online resize helper is stale; rebuild installer/build-online-helper.py / 在线缩容工具已过期,需要重编')
return binary, metadata
def values(text):
return dict(line.split('=',1) for line in text.splitlines() if '=' in line)
class OnlineShrink:
def __init__(self, adapter):
self.a, self.ctx = adapter, adapter.ctx
self.r = self.ctx.record
self.directory = self.ctx.directory/'online-shrink'
self.remote = '/dev/openwrt-online-'+self.r['id']
self.tool = self.remote+'/f2fs-online'
def pair(self):
j = self.r['online_shrink']
disk = '/dev/block/'+storage.disk_node(self.r['device']['storage']['NODE'])
return (self.a.adb.read(f'dd if={disk} bs=512 count={j["front"]} 2>/dev/null'),
self.a.adb.read(f'dd if={disk} bs=512 skip={j["tail"]} count={j["sectors"]-j["tail"]} 2>/dev/null'))
def files(self):
j = self.r['online_shrink']
output = {}
for name, digest in j['files'].items():
path = self.directory/name
if sha(path) != digest:
raise RecoveryRequired('Online resize recovery file changed / 在线缩容恢复文件校验失败: '+name)
if name != 'metadata.bin':
output[name] = path.read_bytes()
return output
def prepare(self):
d = self.r['device']
actual = self.a.probe(d['serial'],'part')
# Free bytes change normally; only identity and disk geometry bind the plan.
if (any(actual.get(k) != d.get(k) for k in ('cid','slot','profile','boot_id','existing')) or
any(actual['storage'].get(k) != d['storage'].get(k) for k in ('NODE','CID','START','SIZE','DISK_SIZE','SOURCE'))):
raise RecoveryRequired('Device changed since online resize planning / 在线缩容计划后的设备身份或几何已变化')
if any(n*512 >= self.r['plan']['openwrt_bytes'] for _,n in actual['gpt']['safe_gaps']):
raise RecoveryRequired('Free-space layout changed; review a new plan before shrinking / 空闲区布局已变化,请重新生成计划,不再按旧计划缩容')
actual['online_shrink'] = inspect(self.a,actual)
if not actual['online_shrink']['available']:
return self.decision(actual['online_shrink']['reason'], before_prepare=True)
target = allocation(actual,self.r['plan']['openwrt_bytes'])
if any(target.get(k) != self.r['plan'].get(k) for k in ('new_sectors','target_blocks','gap_start','android_bytes')):
raise RecoveryRequired('Online resize target changed; review a new plan / 在线缩容目标发生变化,请重新生成计划')
self.a.backup(d)
self.ctx.boundary()
self.directory.mkdir(parents=True,exist_ok=True)
s = d['storage']; space = self.a.read_gpt(s)
original = space['first'],space['last']
updated = candidate(original,s['DISK_SIZE'],s['NODE'],s['SIZE'],target['new_sectors'])
files = dict(zip(('old-first','old-last','new-first','new-last'),(*original,*updated)))
for name,raw in files.items():
with (self.directory/name).open('wb') as out:
out.write(raw); out.flush(); os.fsync(out.fileno())
# Metadata-encryption keys are a separate bounded recovery input. Never
# back up userdata or a whole device for this operation.
if actual['online_shrink']['volume']['source'].rsplit('/',1)[-1].startswith('dm-'):
node = self.a.adb.shell('readlink -f /dev/block/by-name/metadata',root=True).strip().rsplit('/',1)[-1]
if storage.disk_node(node) != storage.disk_node(s['NODE']):
raise RecoveryRequired('Metadata partition is not on the selected disk / metadata 不在所选磁盘')
try:
self.a.adb.backup_partition('metadata',self.directory/'metadata.bin',self.ctx)
finally:
self.a.adb.cleanup_backup(self.ctx)
self.r['online_shrink'] = dict(version=1,state='prepared',front=space['front'],tail=space['tail'],
sectors=s['DISK_SIZE'],old_blocks=actual['online_shrink']['blocks'],
uuid=actual['online_shrink']['uuid'],boot_id=d['boot_id'],original_plan=dict(self.r['plan']),
files={p.name:sha(p) for p in self.directory.iterdir() if p.is_file()},**target)
self.ctx.store.save(self.r)
def stage(self):
files = self.files()
binary,_ = helper_files()
self.a.adb.shell('umask 077; mkdir -p '+self.remote+'; chmod 700 '+self.remote,root=True)
for name,local in [('f2fs-online',binary)]+[(n,self.directory/n) for n in files if n != 'metadata.bin']:
if self.r['online_shrink']['state'] == 'prepared':
self.ctx.boundary()
remote = self.remote+'/'+name
staged = '/data/local/tmp/online-upload-'+self.r['id']
self.a.adb.call('push',str(local),staged,timeout=60)
try:
self.a.adb.shell(f'set -e; cp {staged} {remote}; chmod 700 {remote}; sync',root=True)
if self.a.adb.shell('sha256sum '+remote,root=True).split()[0] != sha(local):
raise ValueError('Online resize transfer checksum failed / 在线缩容工具传输校验失败')
finally:
self.a.adb.shell('rm -f '+staged,root=True)
def unchanged(self, actual=None):
j = self.r['online_shrink']; files = self.files()
actual = actual or self.a.probe(self.r['device']['serial'],'boot')
info = inspect(self.a,actual)
return (info.get('available') and info['uuid'] == j['uuid'] and info['blocks'] == j['old_blocks'] and
self.pair() == (files['old-first'],files['old-last']))
def decision(self, reason, before_prepare=False):
if not before_prepare and not self.unchanged():
raise RecoveryRequired('Resize changed disk state; erasing fallback is unavailable / 缩容已改变磁盘状态,不能直接转为清空流程: '+reason)
self.r['unsafe'] = False
self.r['online_fallback'] = dict(state='awaiting',nonce=secrets.token_urlsafe(24),reason=reason)
self.ctx.stage('online_fallback','waiting_user')
raise OnlineDecision()
def run(self):
self.a.bind(self.r['device']['serial'])
if 'online_shrink' not in self.r:
self.prepare()
j = self.r['online_shrink']
if j['state'] == 'verified':
return
self.ctx.stage('online_shrink')
# Identify hardware without parsing GPT first: a disconnected commit may
# have written only one copy. Known old/new copy pairs are repaired by
# the native worker; the general probe correctly rejects mixed GPT.
actual = self.a.probe(self.r['device']['serial'],'boot')
if any(actual.get(k) != self.r['device'].get(k) for k in ('cid','slot','profile')):
raise RecoveryRequired('Online resize device identity changed / 在线缩容设备身份发生变化')
original = self.r['device']['storage']; current = actual['storage']
if (any(current.get(k) != original.get(k) for k in ('NODE','START','DISK_SIZE')) or
current.get('SIZE') not in (original['SIZE'],j['new_sectors'])):
raise RecoveryRequired('Online resize kernel partition geometry changed / 在线缩容的内核分区几何不符')
if j['state'] == 'started':
active = self.a.adb.shell(f'if [ -x {self.tool} ]; then {self.tool} lock-status; else echo busy=0; fi',root=True)
if values(active).get('busy') == '1':
return self.wait()
files = self.files(); pair = self.pair()
if any(raw not in (files['old-'+side],files['new-'+side]) for side,raw in zip(('first','last'),pair)):
raise RecoveryRequired('GPT differs from the recorded resize / GPT 与已记录缩容不符')
info = inspect(self.a,actual)
if not info.get('available') or info['uuid'] != j['uuid']:
raise RecoveryRequired('Online resize filesystem identity cannot be verified / 无法确认在线缩容文件系统身份')
if pair == (files['new-first'],files['new-last']) and info['blocks'] == j['target_blocks']:
if (actual['boot_id'] == j.get('commit_boot_id',j['boot_id']) or
actual['storage']['SIZE'] != j['new_sectors']):
# A resumed commit may have happened in a later Android boot.
# Wait against that boot, not the original planning boot UUID.
j['commit_boot_id']=actual['boot_id']
self.r['device']['boot_id']=actual['boot_id']
j['state']='gpt-committed'; self.r['unsafe']=False; self.ctx.store.save(self.r)
self.ctx.boundary()
self.ctx.stage('android_boot','waiting_device')
self.a.adb.call('reboot')
raise Pending()
if actual['storage']['SIZE'] != j['new_sectors'] or info['volume']['mapped_bytes'] != j['new_sectors']*512:
raise RecoveryRequired('Android mapping did not adopt the resized partition / Android 未采用缩容后的映射容量')
actual = self.a.probe(self.r['device']['serial'],'part')
if not any(start <= j['gap_start'] and start+n >= j['gap_start']+self.r['plan']['openwrt_bytes']//512
for start,n in actual['gpt']['safe_gaps']):
raise RecoveryRequired('Reclaimed space is not free / 缩容回收范围不是可用空闲区')
j['state']='verified'; self.r['device']=actual; self.r['unsafe']=False
self.r['plan'].update(target='GPT unallocated space',two_stage=self.a.kind=='e5',offline=False)
self.ctx.store.save(self.r)
self.ctx.log('Online F2FS resize and Android reboot verified; continuing free-space installation',scope='online-shrink')
self.ctx.boundary()
return
# If Android rebooted before GPT commit it may have grown F2FS back.
# Only offer a new explicit plan after proving everything is unchanged.
if actual['boot_id'] != j['boot_id'] and self.unchanged(actual):
return self.decision('Android restarted before the resized GPT was committed / Android 在缩容 GPT 提交前重启,当前布局未改变')
if info['blocks'] not in (j['old_blocks'],j['target_blocks']):
raise RecoveryRequired('Unexpected intermediate F2FS capacity / F2FS 处于无法确认的中间容量')
# A running detached worker must never have its inputs overwritten.
busy = self.a.adb.shell(f'if [ -x {self.tool} ]; then {self.tool} lock-status; else echo busy=0; fi',root=True)
if values(busy).get('busy') != '1':
self.stage()
if info['blocks'] == j['old_blocks']:
try:
self.a.adb.shell(f'{self.tool} probe /data '+shlex.quote(info['volume']['source']),root=True,timeout=60)
except ConnectionError as error:
return self.decision('Kernel online-resize probe failed / 内核在线缩容能力检查失败: '+str(error))
if j['state'] == 'prepared':
self.ctx.boundary()
self.r['unsafe']=True; j['state']='started'; self.ctx.store.save(self.r); self.ctx.snapshot()
disk = '/dev/block/'+storage.disk_node(actual['storage']['NODE'])
command = [self.tool,'start','/data',info['volume']['source'],str(j['old_blocks']),str(j['target_blocks']),
disk,str(j['tail']*512),str(j['sectors']*512),j['uuid'],self.remote]
try:
self.a.adb.shell(shlex.join(command),root=True)
except ConnectionError as error:
try:
idle = values(self.a.adb.shell(self.tool+' lock-status',root=True)).get('busy') == '0'
unchanged = idle and self.unchanged()
except (ConnectionError, OSError, ValueError):
unchanged = False
if unchanged:
return self.decision('Online worker launch was rejected / 在线缩容任务未能启动: '+str(error))
# ADB may have disconnected after fork. The saved recipe and
# worker lock are authoritative; never start an erasing retry.
raise RecoveryRequired('Online resize launch needs readback; reconnect and resume / 在线缩容启动结果待复核,请重连后继续') from None
return self.wait()
def wait(self):
self.r['unsafe']=True; self.ctx.store.save(self.r)
while True:
result = values(self.a.adb.shell(f'cat {self.remote}/status 2>/dev/null; {self.tool} lock-status',root=True))
phase = result.get('phase')
self.ctx.log('Online F2FS phase: '+str(phase),scope='online-shrink')
if phase == 'complete' and result.get('busy') == '0':
# Readback in run() also checks both GPT copies and the UUID.
self.r['unsafe']=False; self.ctx.store.save(self.r)
return self.run()
if result.get('busy') == '0':
if phase in ('unchanged','failed'):
return self.decision('Online resize was rejected (errno '+result.get('errno','?')+') / 内核拒绝在线缩容,原容量已复核')
raise RecoveryRequired('Online worker stopped; resume to verify filesystem/GPT / 在线缩容任务已停止,需继续复核文件系统及 GPT')
# Cancellation is deferred until FS and GPT form a complete pair.
time.sleep(2)
def fallback_plan(service, record, params):
prompt = record.get('online_fallback',{})
if (prompt.get('state') != 'awaiting' or params.get('confirmation') != 'yes' or
not secrets.compare_digest(str(params.get('nonce','')),str(prompt.get('nonce','')))):
raise ValueError('Confirm the erase-data fallback / 请确认清空 Android 的后备方案')
adapter = service.adapter(record['package'],service.active if service.active and service.active.record['id']==record['id'] else None)
actual = adapter.probe(record['device']['serial'],'part')
if any(actual.get(k) != record['device'].get(k) for k in ('cid','slot','profile')):
raise RecoveryRequired('Device changed before fallback / 后备方案前设备身份已变化')
from .state import Context
adapter.ctx = Context(service.store,record,service.emit)
job = OnlineShrink(adapter)
if 'online_shrink' in record and not job.unchanged(actual):
raise RecoveryRequired('Cannot erase an unverified intermediate resize / 无法对未核验的缩容中间状态直接清空')
choices = dict(record['choices'],wipe=True,shrink_strategy='format')
from .service import plan_install
record['plan'] = plan_install(record['package'],actual,choices)
record['choices']=choices; record['device']=actual; record['unsafe']=False
prompt['state']='confirmed'
if 'online_shrink' in record: record['online_shrink']['state']='declined'
record['error']=None
adapter.ctx.stage('plan','ready')
return service.public(record)
+51 -7
View File
@@ -19,8 +19,10 @@ from .adapter import Adapter, installation_committed
from .package import inspect_package
from .state import Cancelled, Context, DeviceLock, Pending, RecoveryRequired, Store, compatible
from .transport import Adb, wireless_serial
from . import storage as storage_io
from .uninstall import Uninstaller, prepare as prepare_uninstall, persist as persist_uninstall
from .uninstall_growth import PreservationUnavailable
from .online_shrink import OnlineShrink, OnlineDecision, inspect as inspect_online, allocation as online_allocation, fallback_plan
METHODS = {'tf', 'part', 'reinstall', 'image', 'boot', 'update', 'uninstall'}
@@ -71,18 +73,32 @@ def plan_install(package, device, choices):
raise ValueError('Internal partition exists; choose update or reinstall / 已存在内置分区,请选择更新或重装')
if size_bytes < 2 << 30:
raise ValueError('OpenWrt needs at least 2 GiB / OpenWrt 至少需要 2 GiB')
if not device['gpt']['empty']:
raise ValueError('No unused GPT entry / GPT 没有可用分区条目')
candidates = [(n, a) for a, n in device['gpt']['safe_gaps'] if n*512 >= size_bytes]
gap = max(candidates)[1] if candidates and device['gpt']['empty'] else None
if gap is not None:
plan.update(gap_start=gap, target='GPT unallocated space', two_stage=package['adapter'] == 'e5')
else:
wipe = device['encrypted'] or bool(choices.get('wipe'))
online = device.get('online_shrink',{})
online_reason = online.get('reason')
if online.get('available') and not choices.get('wipe') and choices.get('shrink_strategy') != 'format':
try:
geometry = online_allocation(device,size_bytes)
except ValueError as error:
online_reason = str(error)
else:
plan.update(geometry,shrink_strategy='online-f2fs',target='Android online F2FS shrink',two_stage=True)
return plan
wipe = device['encrypted'] or bool(choices.get('wipe')) or bool(online.get('available') and online_reason)
android = device['userdata_bytes'] - size_bytes
used = device['userdata_bytes'] - device['free_bytes']
if android < (2 << 30) or (not wipe and android < used+(2 << 30)):
raise ValueError('Insufficient Android retained space / Android 保留空间不足')
plan.update(wipe=wipe, two_stage=wipe, android_bytes=android, target='userdata shrink')
plan['offline'] = True
if online_reason:
plan['online_unavailable'] = online_reason
return plan
@@ -220,6 +236,14 @@ class Service:
return self.adapter().probe(p['serial'], p.get('method', 'part'))
if command == 'probe_update':
return self.probe_update(p)
if command == 'online_fallback':
if self.worker and self.worker.is_alive():
raise ValueError('Wait for the active operation / 请等待当前操作结束')
record = self.store.load(p['transaction'])
with ExitStack() as locks:
for identity in sorted({record['device']['serial'],record['device']['cid']}):
locks.enter_context(DeviceLock(self.store.base,identity))
return fallback_plan(self,record,p)
if command == 'plan':
if not self.package:
raise ValueError('Verify package first')
@@ -258,6 +282,13 @@ class Service:
'model':device['model'],'serial_hint':device['serial'][-4:]}
self.uninstall_reset_prompt = None
else:
if (choices.get('method') == 'part' and not device.get('existing') and
not choices.get('wipe') and choices.get('shrink_strategy') != 'format' and
type(choices.get('size_gib',4)) in (float,int) and
math.isfinite(choices.get('size_gib',4)) and choices.get('size_gib',4) > 0 and
not any(n*512 >= math.ceil(choices.get('size_gib',4)*256)*4194304
for _,n in device.get('gpt',{}).get('safe_gaps',[]))):
device['online_shrink'] = inspect_online(plan_adapter,device)
plan = plan_install(self.package, device, choices)
record = self.store.create(self.package, device, choices, plan)
record['data_directory'] = str(self.store.directory(record['id']))
@@ -268,6 +299,8 @@ class Service:
return self.public(record)
if command in ('start', 'resume', 'retry'):
record = self.store.load(p['transaction'])
if record.get('online_fallback',{}).get('state') == 'awaiting':
raise ValueError('Choose whether to prepare an erase-data plan / 请先选择是否准备清空数据的后备计划')
if record['status'] == 'completed':
return self.public(record)
if (record['choices'].get('method') == 'uninstall' and record['status'] == 'ready' and
@@ -373,13 +406,13 @@ class Service:
profile = read('cat /etc/e5/device-profile' if kind == 'e5' else 'cat /run/mu300/device')
if kind == 'e5' and profile != self.package['profile'] or kind == 'mu300' and profile not in ('f50', 'v50', 'u30air'):
raise ValueError('Wrong OpenWrt profile / OpenWrt 机型不匹配')
cid = read('cat /sys/class/block/mmcblk0/device/cid')
cid = read(storage_io.runtime_identity_script())
if not re.fullmatch('[a-f0-9]{32}', cid):
raise ValueError('Cannot establish OpenWrt eMMC identity')
raise ValueError('Cannot establish OpenWrt internal-storage identity / 无法确认 OpenWrt 内置存储身份')
capacity = int(read("df -Pk / | awk 'END {print $2}'"))*1024
root_dev = read('cat /run/mu300/disk-dev' if kind == 'mu300' else
"readlink -f $(awk '$2==\"/\" {print $1}' /proc/mounts | tail -1)")
if re.fullmatch(r'/dev/(?:block/)?(?:mmcblk\d+(?:p\d+)?|loop\d+)', root_dev):
if re.fullmatch(r'/dev/(?:block/)?(?:mmcblk\d+(?:p\d+)?|sd[a-z]+(?:[1-9][0-9]*)?|loop\d+)', root_dev):
raw = read_bytes(f'dd if={root_dev} bs=1024 skip=1 count=1 2>/dev/null')
capacity = verify_ext4_capacity(raw, 0)
return dict(serial='ssh:'+key, cid=cid, ssh_key=key, host=host, profile=profile,
@@ -396,6 +429,13 @@ class Service:
locks.enter_context(DeviceLock(self.store.base, identity))
if r['choices']['method'] == 'uninstall':
return Uninstaller(self, context, adapter).run()
if (r['plan'].get('shrink_strategy') == 'online-f2fs' and
r.get('online_shrink',{}).get('state') != 'verified'):
try:
OnlineShrink(adapter).run()
except Pending:
self.wait_android(context,adapter)
OnlineShrink(adapter).run()
if r['stage'] in ('openwrt_boot', 'verify_capacity') or installation_committed(r):
self.openwrt_wait_stage(context)
return self.wait_openwrt(context, adapter)
@@ -407,6 +447,8 @@ class Service:
if actual.get('cid') != r['device']['cid'] or actual.get('slot') != r['device']['slot']:
raise ValueError('Device identity or Android slot changed since plan / 设备或 Android 槽位与计划不一致')
# Recompute immediately before execution; do not accept stale TF geometry or GPT gaps.
if r['plan'].get('shrink_strategy') == 'online-f2fs':
actual['online_shrink'] = inspect_online(adapter,actual)
fresh = plan_install(r['package'], actual, r['choices'])
for key in ('wipe', 'target', 'openwrt_bytes', 'android_bytes', 'gap_start', 'target_identity'):
if fresh.get(key) != r['plan'].get(key):
@@ -422,6 +464,8 @@ class Service:
result = adapter.execute()
self.openwrt_wait_stage(context)
self.wait_openwrt(context, adapter)
except OnlineDecision:
return
except Cancelled:
context.stage(r['stage'], 'cancelled')
except BaseException as error:
@@ -434,7 +478,7 @@ class Service:
r['error'] = {'code': ('recovery_required' if isinstance(error, RecoveryRequired) else
'capacity_mismatch' if isinstance(error, FilesystemCapacityError) else 'operation_failed'),
'message': message,
'retryable': not r['unsafe'] or bool(r.get('legacy')) or r['choices']['method'] == 'uninstall'}
'retryable': not r['unsafe'] or bool(r.get('legacy')) or r.get('online_shrink',{}).get('state') in ('prepared','started','gpt-committed') or r['choices']['method'] == 'uninstall'}
context.stage(r['stage'], 'failed')
def wait_android(self, context, adapter):
@@ -507,7 +551,7 @@ class Service:
raise ValueError('Final verification command failed')
return value
def read(script):return read_bytes(script).decode().strip()
cid = read('cat /sys/class/block/mmcblk0/device/cid')
cid = read(storage_io.runtime_identity_script())
if cid != r['device']['cid']:
raise RecoveryRequired('Management address belongs to another device / 管理地址对应另一台设备')
if r['choices']['method'] == 'update':
@@ -525,7 +569,7 @@ class Service:
dev = read("readlink -f $(awk '$2==\"/\" {print $1}' /proc/mounts | tail -1)")
else:
dev = read('cat /run/mu300/disk-dev')
if not re.fullmatch(r'/dev/(?:block/)?(?:mmcblk\d+(?:p\d+)?|loop\d+)', dev):
if not re.fullmatch(r'/dev/(?:block/)?(?:mmcblk\d+(?:p\d+)?|sd[a-z]+(?:[1-9][0-9]*)?|loop\d+)', dev):
raise ValueError('Cannot identify installed root block device')
raw = read_bytes(f'dd if={dev} bs=1024 skip=1 count=1 2>/dev/null')
# Older records may store the growth choice only in choices.
+95
View File
@@ -0,0 +1,95 @@
"""One topology/identity contract for eMMC and UFS installation paths."""
from pathlib import Path
import re
import sys
def disk_node(node):
match = re.fullmatch(r'(mmcblk[0-9]+)p[1-9][0-9]*|(sd[a-z]+)[1-9][0-9]*', node)
if not match:
raise ValueError('Invalid internal partition / 内置分区节点无效: '+str(node))
return match[1] or match[2]
def part_node(disk, number):
if not re.fullmatch(r'mmcblk[0-9]+|sd[a-z]+', disk) or not isinstance(number,int) or number < 1:
raise ValueError('Invalid disk/partition number / 磁盘或分区号无效')
return disk+('p' if disk.startswith('mmcblk') else '')+str(number)
def library(root=None):
# Explicit source/frozen/portable layouts of the same library. An old
# installed OpenWrt need not contain this new helper to be updatable.
if getattr(sys,'frozen',False):
path=Path(sys._MEIPASS)/'storage.sh'
elif Path(__file__).parent.name == 'backend':
path=Path(__file__).resolve().parents[2]/'rootfs/overlay/opt/mu300/lib/storage.sh'
else:
path=Path(__file__).with_name('storage-lib.sh')
return path.read_text(encoding='utf-8')
def inventory_script(root):
return library(root)+r'''
set -e
d=$(readlink -f /dev/block/by-name/userdata)
n=${d##*/}
b=$(mu300_storage_parent "$n")
[ "$(mu300_storage_part userdata "$b")" = "$n" ]
echo NODE=$n
echo DISK=$b
echo STORAGE_KIND=$(mu300_storage_kind "$b")
echo CID=$(mu300_storage_identity "$b")
echo SECTOR_SIZE=$(mu300_storage_sector_size "$b")
echo START=$(cat /sys/class/block/$n/start)
echo SIZE=$(cat /sys/class/block/$n/size)
echo DISK_SIZE=$(cat /sys/class/block/$b/size)
echo FREE=$(df -Pk /data | tail -n1 | awk '{print $4}')
echo STATE=$(getprop ro.crypto.state)
echo TYPE=$(getprop ro.crypto.type)
echo SOURCE=$(awk '$2=="/data" {print $1;exit}' /proc/mounts)
echo MAGIC=$(dd if="$d" bs=1 skip=1024 count=4 2>/dev/null | od -An -tx1 | tr -d ' \n')
echo EXT=$(dd if="$d" bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d ' \n')
for label in mu300root e5root; do
candidate=$(mu300_storage_part "$label" "$b") || continue
echo ROOT=$candidate
done
'''
def parse_inventory(text):
result = dict(line.split('=',1) for line in text.splitlines() if '=' in line)
disk = disk_node(result['NODE'])
if result.get('DISK',disk) != disk or not re.fullmatch('[a-f0-9]{32}',result.get('CID','')):
raise ValueError('Cannot establish storage identity / 无法确认存储身份')
kind = result.get('STORAGE_KIND','emmc')
if kind not in ('emmc','ufs') or (kind == 'emmc') != disk.startswith('mmcblk'):
raise ValueError('Storage type/topology differs / 存储类型与拓扑不匹配')
result['DISK'] = disk
result['STORAGE_KIND'] = kind
result['SECTOR_SIZE'] = int(result.get('SECTOR_SIZE',512))
if result['SECTOR_SIZE'] not in (512,4096):
raise ValueError('Unsupported storage logical block size / 不支持的存储逻辑块大小')
for key in ('START','SIZE','DISK_SIZE','FREE'):
result[key] = int(result[key])
if result[key] < 0:
raise ValueError('Invalid storage geometry / 存储范围无效')
factor = result['SECTOR_SIZE']//512
if any(result[key] % factor for key in ('START','SIZE','DISK_SIZE')):
raise ValueError('Storage alignment differs / 存储对齐不匹配')
if not result['SIZE'] or result['START']+result['SIZE'] > result['DISK_SIZE']:
raise ValueError('Partition exceeds its disk / 分区超出所在磁盘范围')
if result.get('ROOT') and disk_node(result['ROOT']) != disk:
raise ValueError('Root is on another disk / 根分区不在同一磁盘')
return result
def gpt_header_commands(info, prefix='/dev/block/'):
disk = prefix+disk_node(info['NODE'])
block = info.get('SECTOR_SIZE',512)
return (f'dd if={disk} bs={block} skip=1 count=1 2>/dev/null',
f'dd if={disk} bs={block} skip={info["DISK_SIZE"]//(block//512)-1} count=1 2>/dev/null')
def runtime_identity_script():
return library()+'\nd=$(mu300_storage_disk) && mu300_storage_identity "$d"'
+2 -1
View File
@@ -203,11 +203,12 @@ class Adb:
process.communicate(timeout=5)
def backup_partition(self, name, destination, context):
if not re.fullmatch(r'(misc|(?:boot|uboot|sml|teecfg|trustos|vbmeta)_[ab])',name):
if not re.fullmatch(r'(misc|metadata|(?:boot|uboot|sml|teecfg|trustos|vbmeta)_[ab])',name):
raise ValueError('Unsupported backup partition')
source='/dev/block/by-name/'+name
total=4096 if name=='misc' else int(self.shell('blockdev --getsize64 '+source,root=True).strip())
if total<=0:raise ValueError('Invalid backup partition size: '+name)
if name=='metadata' and total>256<<20:raise ValueError('Unexpected metadata partition size')
remote=self._backup_directory(context,total)+'/'+name+'.img'
local=Path(str(destination)+'.partial')
context.log(f'Backing up {name}: {total} bytes; device dd -> adb pull',scope='backup')
+21 -18
View File
@@ -14,7 +14,7 @@ import time
import zlib
import uuid
from . import gpt
from . import gpt, storage as storage_io
from .boot_image import inspect_linux_boot, trial_control
from .state import Cancelled, RecoveryRequired, atomic_json, sha
from .transport import push_chunks
@@ -31,14 +31,16 @@ def partition(info, name):
def table(first):
at, count = struct.unpack_from('<QI', first, 584)
return first[at*512:at*512+count*128]
block = gpt.sector_size(first)
at, count = struct.unpack_from('<QI', first, block+72)
return first[at*block:at*block+count*128]
def with_table(current, updated, sectors):
block = gpt.sector_size(current[0])
output = []
for raw, header, offset in ((current[0], 512, struct.unpack_from('<Q', current[0], 584)[0]*512),
(current[1], len(current[1])-512, 0)):
for raw, header, offset in ((current[0], block, struct.unpack_from('<Q', current[0], block+72)[0]*block),
(current[1], len(current[1])-block, 0)):
raw = bytearray(raw); raw[offset:offset+len(updated)] = updated
struct.pack_into('<I', raw, header+88, zlib.crc32(updated))
struct.pack_into('<I', raw, header+16, 0)
@@ -70,7 +72,7 @@ def device_layout(current, sectors, name):
expands = root['start'] == data['end']+1
target = {**data,'end':root['end']} if expands else data
updated[(root['n']-1)*128:root['n']*128] = bytes(128)
struct.pack_into('<Q',updated,(data['n']-1)*128+40,target['end'])
struct.pack_into('<Q',updated,(data['n']-1)*128+40,(target['end']+1)//(info['sector_size']//512)-1)
return with_table(current,updated,sectors), target, root, expands
@@ -81,7 +83,7 @@ def restored_layout(original, current, sectors, name):
data, root = partition(now, 'userdata'), partition(now, name)
prior = partition(old, 'userdata')
oldtable, newtable = table(original[0]), table(current[0])
if (original[0][568:584] != current[0][568:584] or old['front'] != now['front'] or
if (original[0][old['sector_size']+56:old['sector_size']+72] != current[0][now['sector_size']+56:now['sector_size']+72] or old['front'] != now['front'] or
old['tail'] != now['tail'] or len(oldtable) != len(newtable) or data['n'] != prior['n'] or
data['start'] != prior['start'] or root['n']-1 not in old['empty']):
raise RecoveryRequired('Original GPT identity differs / 原安装备份与当前 GPT 身份不符')
@@ -103,7 +105,7 @@ def restored_layout(original, current, sectors, name):
raise RecoveryRequired('Unallocated-space origin cannot be proven / 无法确认原未分配空间范围')
updated = bytearray(newtable)
updated[(root['n']-1)*128:root['n']*128] = oldtable[(root['n']-1)*128:root['n']*128]
struct.pack_into('<Q', updated, (data['n']-1)*128+40, prior['end'])
struct.pack_into('<Q', updated, (data['n']-1)*128+40, (prior['end']+1)//(now['sector_size']//512)-1)
output = with_table(current,updated,sectors)
verified = gpt.gpt_space(*output, sectors)
if any(p['name'] == name for p in verified['parts']):
@@ -113,7 +115,7 @@ def restored_layout(original, current, sectors, name):
def android_volume(adb, device, *, allow_small=False):
source = adb.shell('readlink -f '+shlex.quote(device['storage']['SOURCE']), root=True).strip()
if not re.fullmatch(r'/dev/(?:block/)?(?:mmcblk\d+p\d+|dm-\d+)', source):
if not re.fullmatch(r'/dev/(?:block/)?(?:mmcblk\d+p\d+|sd[a-z]+[1-9][0-9]*|dm-\d+)', source):
raise RecoveryRequired('Cannot identify Android data mapping / 无法确认 Android data 映射设备')
mapped = int(adb.shell('cat /sys/class/block/'+source.rsplit('/',1)[-1]+'/size', root=True).strip())*512
raw = adb.read('dd if='+source+' bs=1024 skip=1 count=1 2>/dev/null')
@@ -178,8 +180,8 @@ def prepare(adapter, store, device, authorize_reset=None):
after, data, root, expands = device_layout(current,total,name)
proof = inspect_installation(adapter,device,root)
source = None
node = storage['NODE'].split('p')[0]
if (storage['ROOT'] != node+'p'+str(root['n']) or storage['START'] != data['start'] or
node = storage_io.disk_node(storage['NODE'])
if (storage['ROOT'] != storage_io.part_node(node,root['n']) or storage['START'] != data['start'] or
storage['SIZE']*512 != device['userdata_bytes']):
raise RecoveryRequired('Kernel partition nodes differ from GPT; reboot Android / 内核分区节点与 GPT 不符,请重启 Android')
for bootname in ('boot_a','boot_b','misc'):
@@ -224,7 +226,7 @@ def prepare(adapter, store, device, authorize_reset=None):
metadata = {'version':2 if source else 3,'action':action,'reset_authorized':wipe,'total':total,'front':space['front'],'tail':space['tail'],
'tool_hashes':{name:hashlib.sha256(content).hexdigest() for name,content in tools.items()},
'root_start':root['start'],'root_size':root['end']-root['start']+1,
'nodes':{p['name']:node+'p'+str(p['n']) for p in space['parts']
'nodes':{p['name']:storage_io.part_node(node,p['n']) for p in space['parts']
if p['name'] in ('userdata',name,'misc','boot_a','boot_b')}, 'volume':volume}
if proof:
metadata['installation_evidence'] = proof
@@ -264,7 +266,7 @@ class Uninstaller:
raise RecoveryRequired('Incomplete uninstall journal / 卸载记录不完整')
storage = self.r['device']['storage']
if (self.r['package'].get('adapter') not in ('e5','mu300') or
not re.fullmatch(r'mmcblk[0-9]p[1-9][0-9]*',storage.get('NODE',''))):
not re.fullmatch(r'(?:mmcblk[0-9]+p|sd[a-z]+)[1-9][0-9]*',storage.get('NODE',''))):
raise RecoveryRequired('Invalid uninstall disk node / 卸载记录中的磁盘节点无效')
total = storage['DISK_SIZE']
before = (self.files['before-first'],self.files['before-last'])
@@ -299,8 +301,8 @@ class Uninstaller:
raise RecoveryRequired('Uninstall preservation evidence is incomplete / 卸载保数据证据不完整')
info = gpt.gpt_space(*before,total)
data = partition(info,'userdata')
disk = storage['NODE'].split('p')[0]
expected_nodes = {label:disk+'p'+str(partition(info,label)['n'])
disk = storage_io.disk_node(storage['NODE'])
expected_nodes = {label:storage_io.part_node(disk,partition(info,label)['n'])
for label in ('userdata',name,'misc','boot_a','boot_b')}
if (calculated != list(after) or self.meta['total'] != total or self.meta['front'] != info['front'] or
self.meta['tail'] != info['tail'] or self.meta['nodes'] != expected_nodes or
@@ -317,7 +319,7 @@ class Uninstaller:
def current(self):
adb = self.adapter.adb
disk = '/dev/block/'+self.r['device']['storage']['NODE'].split('p')[0]
disk = '/dev/block/'+storage_io.disk_node(self.r['device']['storage']['NODE'])
front, tail, total = (self.meta[k] for k in ('front','tail','total'))
return (adb.read(f'dd if={disk} bs=512 count={front} 2>/dev/null'),
adb.read(f'dd if={disk} bs=512 skip={tail} count={total-tail} 2>/dev/null'))
@@ -393,7 +395,7 @@ class Uninstaller:
if android_header[:8] != b'ANDROID!' or android_header == linux_header:
raise RecoveryRequired('Current Android boot cannot be distinguished from Linux / 无法区分当前 Android 与 Linux 启动镜像')
nodes = self.meta['nodes']; rootname = 'e5root' if self.adapter.kind == 'e5' else 'mu300root'
request = [device['cid'],device['storage']['NODE'].split('p')[0],nodes['userdata'],nodes[rootname],
request = [device['cid'],storage_io.disk_node(device['storage']['NODE']),nodes['userdata'],nodes[rootname],
nodes['misc'],nodes['boot_'+slot],nodes['boot_'+other]]
request += [self.meta[k] for k in ('total','front','tail','root_start','root_size')]
request += [int(self.r['plan']['wipe']),boot_bytes,android_sha]
@@ -403,6 +405,7 @@ class Uninstaller:
volume['filesystem_bytes'],volume.get('uuid','0'*32)]
files = {'openwrt-uninstall/'+name:content for name,content in self.files.items()}
files.update(tools)
files['openwrt-uninstall/storage.sh'] = storage_io.library(self.adapter.root).encode()
files.update({'openwrt-uninstall/request':(':'.join(map(str,request))+'\n').encode(),
'openwrt-uninstall/before-bcb':before[:2048],
'openwrt-uninstall/recovery-bcb':bytes(bcb) if self.r['plan']['wipe'] else bytes(2048),
@@ -426,7 +429,7 @@ class Uninstaller:
for local, name in ((path,'boot.img'),(self.folder/'trial.bin','trial.bin')):
push_chunks(adb.call,lambda script:adb.shell(script,root=True),local,remote+'/'+name,self.ctx)
bootdev = '/dev/block/by-name/boot_'+other
disk = '/dev/block/'+device['storage']['NODE'].split('p')[0]
disk = '/dev/block/'+storage_io.disk_node(device['storage']['NODE'])
layout_checks = (
f'[ "$(dd if={disk} bs=512 count={self.meta["front"]} | sha256sum | cut -d" " -f1)" = {hashlib.sha256(self.files["before-first"]).hexdigest()} ]; '
f'[ "$(dd if={disk} bs=512 skip={self.meta["tail"]} count={self.meta["total"]-self.meta["tail"]} | sha256sum | cut -d" " -f1)" = {hashlib.sha256(self.files["before-last"]).hexdigest()} ]; ')
+4 -3
View File
@@ -33,6 +33,7 @@ idle_partition() {
}
# BEGIN DEVICE WORKER
. /openwrt-uninstall/storage.sh
mkdir -p /run/openwrt-uninstall
exec >>/run/openwrt-uninstall/debug.log 2>&1
fail() {
@@ -49,9 +50,9 @@ sha256sum -c SHA256SUMS
IFS=: read -r cid disk_node data_node root_node misc_node android_node linux_node total front tail start root_size wipe boot_bytes boot_sha action data_start data_size fs_before fs_uuid extra < request
[ -z "$extra" ] && [ "${#cid}" = 32 ] && [ "${#boot_sha}" = 64 ]
case "$cid$boot_sha" in *[!0-9a-f]*) exit 2 ;; esac
case "$disk_node" in mmcblk[0-9]) ;; *) exit 2 ;; esac
case "$disk_node" in mmcblk[0-9]*|sd[a-z]*) ;; *) exit 2 ;; esac
for node in "$data_node" "$root_node" "$misc_node" "$android_node" "$linux_node"; do
case "$node" in "$disk_node"p[0-9]*) ;; *) exit 2 ;; esac
case "$node" in "$disk_node"p[0-9]*|"$disk_node"[0-9]*) ;; *) exit 2 ;; esac
case "$node" in *[!a-z0-9]*) exit 2 ;; esac
done
for n in "$total" "$front" "$tail" "$start" "$root_size" "$boot_bytes"; do
@@ -75,7 +76,7 @@ misc=/dev/$misc_node
android=/dev/$android_node
linux=/dev/$linux_node
[ "$android_node" != "$linux_node" ]
[ "$(cat /sys/class/block/$disk_node/device/cid)" = "$cid" ]
[ "$(mu300_storage_identity "$disk_node")" = "$cid" ]
[ "$(cat /sys/class/block/$disk_node/size)" = "$total" ]
[ "$front" -ge 3 ] && [ "$front" -le 4096 ] && [ "$tail" -gt "$((total-4096))" ] && [ "$tail" -lt "$total" ]
[ "$start" -ge "$front" ] && [ "$((start%8))" = 0 ] && [ "$root_size" -ge 4194304 ] && [ "$((start+root_size))" -le "$tail" ]
+34
View File
@@ -0,0 +1,34 @@
"""Build the single static ARM64 Android online-F2FS helper in the Linux workspace.
Run through tools/build-release.py run; no kernel/rootfs rebuild or downloads.
Native Windows/macOS packaging consumes the checked, source-bound executable.
"""
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile
HERE = Path(__file__).resolve().parent
def main():
source = HERE/'device/f2fs-online.c'
with tempfile.TemporaryDirectory(prefix='f2fs-online-') as temp:
test = Path(temp)/'test'
subprocess.run(['cc','-O2','-Wall','-Wextra','-Werror',str(HERE/'device/test-f2fs-online.c'),'-o',str(test)],check=True)
subprocess.run([str(test)],check=True)
output = HERE/'device/f2fs-online-arm64'
pending = output.with_suffix('.pending')
subprocess.run(['aarch64-linux-gnu-gcc','-static','-O2','-Wall','-Wextra','-Werror',
str(source),'-o',str(pending)],check=True)
subprocess.run(['aarch64-linux-gnu-strip',str(pending)],check=True)
pending.replace(output)
(HERE/'device/build.json').write_text(json.dumps({
'source':hashlib.sha256(source.read_bytes().replace(b'\r\n',b'\n')).hexdigest(),
'binary':hashlib.sha256(output.read_bytes()).hexdigest(),
'architecture':'aarch64-static-linux','protocol':1},indent=2)+'\n',encoding='utf-8')
if __name__ == '__main__':
main()
+5
View File
@@ -39,6 +39,8 @@ def main():
mac = target == 'macos-arm64'
if mac:
os.environ.setdefault('MACOSX_DEPLOYMENT_TARGET', '11.0')
from backend.online_shrink import helper_files
helper_files() # reject missing/stale native input before freezing a backend
before = sources()
npm = 'npm' if mac else 'npm.cmd'
if not a.skip_ui:
@@ -58,6 +60,9 @@ def main():
'--add-data', str(HERE.parent/'openwrt/luci-app-unisoc-ota/htdocs/luci-static/resources/unisoc-ota/errors.js')+os.pathsep+'.',
'--add-data', str(HERE.parent/'openwrt/luci-app-unisoc-ota/root/usr/share/rpcd/acl.d/unisoc-ota.json')+os.pathsep+'.',
'--add-data', str(HERE/'ota-native/lz4raw-aarch64.so')+os.pathsep+'.',
'--add-data',str(HERE.parent/'rootfs/overlay/opt/mu300/lib/storage.sh')+os.pathsep+'.',
'--add-data', str(HERE/'device/f2fs-online-arm64')+os.pathsep+'.',
'--add-data', str(HERE/'device/build.json')+os.pathsep+'online-helper',
'--collect-all','paramiko','--collect-all','dissect.extfs',HERE/'backend_entry.py')
artifact = HERE/('artifacts/macos-arm64' if mac else 'artifacts/windows')
artifact.mkdir(parents=True,exist_ok=True)
+6
View File
@@ -0,0 +1,6 @@
{
"source": "82f06646aac3389f87c085280b4af39c84818b27f1b26a79a016f70583b87a1b",
"binary": "357f4907cc35b2b67f14410a3cfbbad04d62dc3f59c08f711f09f8514993496d",
"architecture": "aarch64-static-linux",
"protocol": 1
}
Binary file not shown.
+297
View File
@@ -0,0 +1,297 @@
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/fs.h>
#include <linux/magic.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/statvfs.h>
#include <unistd.h>
#define F2FS_RESIZE _IOW(0xf5, 16, uint64_t)
#define SB_BYTES 3072
struct geometry {
uint64_t blocks, section_blocks;
unsigned char uuid[16];
};
static uint32_t le32(const unsigned char *p)
{
return (uint32_t)p[0] | (uint32_t)p[1] << 8 |
(uint32_t)p[2] << 16 | (uint32_t)p[3] << 24;
}
static uint64_t le64(const unsigned char *p)
{
return le32(p) | (uint64_t)le32(p + 4) << 32;
}
static int decode(const unsigned char *raw, struct geometry *g)
{
const unsigned char *a = raw + 1024, *b = raw + 5120;
if (le32(a) != 0xf2f52010 || le32(b) != 0xf2f52010 ||
memcmp(a, b, SB_BYTES) || le32(a + 16) != 12 ||
le32(a + 20) != 9 || !le32(a + 24) || le32(a + 24) > 65536) {
errno = EINVAL;
return -1;
}
g->blocks = le64(a + 36);
g->section_blocks = 512ULL * le32(a + 24);
memcpy(g->uuid, a + 108, 16);
if (!g->blocks || g->blocks % g->section_blocks) {
errno = EINVAL;
return -1;
}
return 0;
}
static int read_geometry(int fd, struct geometry *g)
{
void *buffer = NULL;
int error = posix_memalign(&buffer, 4096, 8192);
if (error) { errno = error; return -1; }
ssize_t n = pread(fd, buffer, 8192, 0);
int rc = n == 8192 ? decode(buffer, g) : -1;
if (n >= 0 && n != 8192) errno = EIO;
free(buffer);
return rc;
}
static int parse_count(const char *s, uint64_t *result)
{
if (!*s || *s == '0') return -1;
for (const char *p = s; *p; p++) if (*p < '0' || *p > '9') return -1;
errno = 0;
unsigned long long n = strtoull(s, NULL, 10);
if (errno || !n || n > UINT64_MAX / 4096) return -1;
*result = n;
return 0;
}
static int validate_target(const struct geometry *g, uint64_t expected,
uint64_t target, uint64_t used)
{
if (expected != g->blocks || !target || target >= expected ||
target % g->section_blocks || target > UINT64_MAX / 4096 ||
used > UINT64_MAX - (1ULL << 30) || target * 4096 <= used + (1ULL << 30)) {
errno = EINVAL;
return -1;
}
return 0;
}
static int failure(const char *stage)
{
fprintf(stderr, "FAILED stage=%s errno=%d message=%s\n", stage, errno, strerror(errno));
return 1;
}
/* One detached worker owns resize + GPT commit. All payloads live in /dev,
* not the mounted userdata being resized. Disconnecting ADB does not kill it.
* The host supplies verified original/candidate GPT copies; the worker compares
* both immediately before mutation and never accepts unrelated disk bytes. */
struct image { unsigned char *p; size_t n; };
static struct image load_image(const char *name)
{
struct image out = {0};
int fd = open(name, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
struct stat st;
if (fd < 0 || fstat(fd, &st) || !S_ISREG(st.st_mode) ||
st.st_size < 512 || st.st_size > (2 << 20) || st.st_size % 512) goto done;
out.n = st.st_size; out.p = malloc(out.n);
if (!out.p || read(fd, out.p, out.n) != (ssize_t)out.n) {
free(out.p); out.p = NULL; out.n = 0;
}
done:
if (fd >= 0) close(fd);
return out;
}
static int matches(int fd, const struct image *image, uint64_t at)
{
unsigned char *p = malloc(image->n);
if (!p) return 0;
int ok = pread(fd, p, image->n, at) == (ssize_t)image->n && !memcmp(p, image->p, image->n);
free(p); return ok;
}
static int commit_image(int fd, const struct image *image, uint64_t at)
{
return pwrite(fd, image->p, image->n, at) == (ssize_t)image->n &&
!fsync(fd) && matches(fd, image, at);
}
static void receipt(const char *phase, int error)
{
int fd = open("status.new", O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0600);
if (fd < 0) return;
dprintf(fd, "phase=%s\nerrno=%d\npid=%ld\n", phase, error, (long)getpid());
fsync(fd); close(fd); rename("status.new", "status");
}
static int worker_command(int argc, char **argv)
{
/* start MOUNT DECRYPTED OLD TARGET DISK TAIL_BYTE DISK_BYTES UUID WORK */
if (argc != 11) { errno = EINVAL; return failure("worker-arguments"); }
uint64_t expected, target, tail, disk_bytes;
if (parse_count(argv[4], &expected) || parse_count(argv[5], &target) ||
parse_count(argv[7], &tail) || parse_count(argv[8], &disk_bytes) ||
strlen(argv[9]) != 32 || strncmp(argv[10], "/dev/openwrt-online-", 20)) {
errno = EINVAL; return failure("worker-values");
}
int lock = open("/dev/openwrt-f2fs-online.lock", O_CREAT | O_RDWR | O_NOFOLLOW, 0600);
if (lock < 0 || flock(lock, LOCK_EX | LOCK_NB)) return failure("worker-lock");
if (chdir(argv[10])) return failure("worker-directory");
struct image old_first = load_image("old-first"), old_last = load_image("old-last"),
new_first = load_image("new-first"), new_last = load_image("new-last");
if (!old_first.p || !old_last.p || !new_first.p || !new_last.p ||
old_first.n != new_first.n || old_last.n != new_last.n ||
tail >= disk_bytes || tail + old_last.n != disk_bytes || old_first.n >= tail) {
errno = EINVAL; return failure("worker-gpt-inputs");
}
int mount_fd = open(argv[2], O_RDONLY | O_DIRECTORY | O_CLOEXEC),
raw_fd = open(argv[3], O_RDONLY | O_DIRECT | O_CLOEXEC),
disk_fd = open(argv[6], O_RDWR | O_CLOEXEC);
struct stat ms, rs, ds;
struct statfs fs;
struct statvfs volume;
struct geometry g;
uint64_t actual_bytes, mapped_bytes;
char uuid[33];
if (mount_fd < 0 || raw_fd < 0 || disk_fd < 0 ||
fstat(mount_fd, &ms) || fstat(raw_fd, &rs) || fstat(disk_fd, &ds) ||
!S_ISBLK(rs.st_mode) || !S_ISBLK(ds.st_mode) || ms.st_dev != rs.st_rdev ||
fstatfs(mount_fd, &fs) || fs.f_type != F2FS_SUPER_MAGIC ||
fstatvfs(mount_fd, &volume) || (volume.f_flag & ST_RDONLY) ||
ioctl(disk_fd, BLKGETSIZE64, &actual_bytes) || actual_bytes != disk_bytes ||
ioctl(raw_fd, BLKGETSIZE64, &mapped_bytes) || read_geometry(raw_fd, &g) ||
g.blocks > mapped_bytes / 4096 || target >= expected || target % g.section_blocks)
return failure("worker-identity");
for (int i=0; i<16; i++) snprintf(uuid+i*2, 3, "%02x", g.uuid[i]);
if (strcmp(uuid, argv[9]) || (g.blocks != expected && g.blocks != target) ||
!(matches(disk_fd, &old_first, 0) || matches(disk_fd, &new_first, 0)) ||
!(matches(disk_fd, &old_last, tail) || matches(disk_fd, &new_last, tail))) {
errno = EINVAL; return failure("worker-stale-state");
}
if (g.blocks == expected && (!matches(disk_fd, &old_first, 0) || !matches(disk_fd, &old_last, tail) ||
!volume.f_frsize || volume.f_blocks < volume.f_bfree ||
(volume.f_blocks-volume.f_bfree) > UINT64_MAX/volume.f_frsize ||
validate_target(&g, expected, target, (volume.f_blocks-volume.f_bfree)*volume.f_frsize))) {
errno = EINVAL; return failure("worker-target");
}
/* Inherit ignored SIGHUP before fork: adb may close the shell immediately
* after the parent returns, before the child gets scheduled for setsid. */
signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN);
pid_t child = fork();
if (child < 0) return failure("worker-fork");
if (child) { printf("worker_started=%ld\n", (long)child); return 0; }
setsid(); signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN);
int log = open("worker.log", O_CREAT | O_WRONLY | O_APPEND | O_NOFOLLOW, 0600);
int nil = open("/dev/null", O_RDONLY);
if (log < 0 || nil < 0) _exit(1);
dup2(nil, 0); dup2(log, 1); dup2(log, 2); close(nil); close(log);
if (g.blocks == expected) {
receipt("shrinking", 0);
if (syncfs(mount_fd)) { receipt("failed", errno); _exit(1); }
int rc = ioctl(mount_fd, F2FS_RESIZE, &target), error = errno;
/* Some errors can occur after mutation. Read back before deciding. */
if (read_geometry(raw_fd, &g)) { receipt("recovery", errno); _exit(1); }
if (g.blocks == expected && rc) { receipt("unchanged", error); _exit(1); }
if (g.blocks != target) { receipt("recovery", EIO); _exit(1); }
}
receipt("committing", 0);
if (syncfs(mount_fd) || !commit_image(disk_fd, &new_last, tail) ||
!commit_image(disk_fd, &new_first, 0)) { receipt("recovery", EIO); _exit(1); }
receipt("complete", 0);
close(disk_fd); close(raw_fd); close(mount_fd); close(lock); _exit(0);
}
int main(int argc, char **argv)
{
if (argc == 2 && !strcmp(argv[1], "lock-status")) {
int fd = open("/dev/openwrt-f2fs-online.lock", O_CREAT | O_RDWR | O_NOFOLLOW, 0600);
if (fd < 0) return failure("worker-lock-status");
puts(flock(fd, LOCK_EX | LOCK_NB) ? "busy=1" : "busy=0");
close(fd); return 0;
}
if (argc > 1 && !strcmp(argv[1], "start")) return worker_command(argc, argv);
if (argc < 4 || (strcmp(argv[1], "inspect") && strcmp(argv[1], "probe") &&
strcmp(argv[1], "shrink")) ||
(!strcmp(argv[1], "shrink") ? argc != 6 : argc != 4)) {
fprintf(stderr, "usage: %s inspect|probe MOUNT BLOCKDEV; shrink MOUNT BLOCKDEV EXPECTED_BLOCKS TARGET_BLOCKS\n", argv[0]);
return 2;
}
int mount_fd = open(argv[2], O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (mount_fd < 0) return failure("open-mount");
int raw_fd = open(argv[3], O_RDONLY | O_DIRECT | O_CLOEXEC);
if (raw_fd < 0) return failure("open-decrypted-device");
struct stat mount_stat, device_stat;
struct statfs fs;
struct statvfs volume;
struct geometry before, after;
uint64_t mapped_bytes;
if (fstat(mount_fd, &mount_stat) || fstat(raw_fd, &device_stat) ||
fstatfs(mount_fd, &fs) || fstatvfs(mount_fd, &volume)) return failure("stat");
if (!S_ISBLK(device_stat.st_mode) || mount_stat.st_dev != device_stat.st_rdev ||
fs.f_type != F2FS_SUPER_MAGIC || volume.f_flag & ST_RDONLY) {
errno = EINVAL; return failure("mount-device-identity");
}
if (ioctl(raw_fd, BLKGETSIZE64, &mapped_bytes) ||
read_geometry(raw_fd, &before)) return failure("read-superblocks");
if (!volume.f_frsize || before.blocks > mapped_bytes / 4096 || volume.f_blocks < volume.f_bfree ||
(volume.f_blocks - volume.f_bfree) > UINT64_MAX / volume.f_frsize) {
errno = EINVAL; return failure("geometry");
}
uint64_t used = (volume.f_blocks - volume.f_bfree) * volume.f_frsize;
printf("blocks=%" PRIu64 "\nblock_size=4096\nsection_blocks=%" PRIu64
"\nmapped_bytes=%" PRIu64 "\nused_bytes=%" PRIu64 "\n",
before.blocks, before.section_blocks, mapped_bytes, used);
printf("uuid="); for (int i=0; i<16; i++) printf("%02x", before.uuid[i]); puts("");
fflush(stdout);
if (!strcmp(argv[1], "inspect")) return 0;
if (!strcmp(argv[1], "probe")) {
/* Exact current size is a supported no-op, not a shrink dry run. */
uint64_t same = before.blocks;
if (ioctl(mount_fd, F2FS_RESIZE, &same)) return failure("same-size-probe");
if (read_geometry(raw_fd, &after) || before.blocks != after.blocks ||
before.section_blocks != after.section_blocks || memcmp(before.uuid, after.uuid, 16)) {
errno = EIO; return failure("probe-readback");
}
puts("same_size_probe=OK");
return 0;
}
uint64_t expected, target;
if (parse_count(argv[4], &expected) || parse_count(argv[5], &target) ||
validate_target(&before, expected, target, used)) {
errno = EINVAL; return failure("target");
}
if (syncfs(mount_fd)) return failure("pre-sync");
if (read_geometry(raw_fd, &after) || after.blocks != expected ||
memcmp(before.uuid, after.uuid, sizeof(before.uuid))) {
errno = EIO; return failure("pre-write-identity");
}
printf("ioctl_begin expected=%" PRIu64 " target=%" PRIu64 "\n", expected, target);
fflush(stdout);
if (ioctl(mount_fd, F2FS_RESIZE, &target)) return failure("resize-ioctl");
if (syncfs(mount_fd)) return failure("post-sync");
if (read_geometry(raw_fd, &after) || after.blocks != target ||
memcmp(before.uuid, after.uuid, sizeof(before.uuid))) {
errno = EIO; return failure("resize-readback");
}
printf("resize_verified=OK\nblocks=%" PRIu64 "\n", after.blocks);
close(raw_fd); close(mount_fd);
return 0;
}
+59
View File
@@ -0,0 +1,59 @@
#define main device_tool_main
#include "f2fs-online.c"
#undef main
#include <assert.h>
static void put32(unsigned char *p, uint32_t n)
{
for (int i = 0; i < 4; i++) p[i] = n >> (i * 8);
}
static void put64(unsigned char *p, uint64_t n)
{
put32(p, n); put32(p + 4, n >> 32);
}
int main(void)
{
unsigned char raw[8192] = {0}, saved[8192];
unsigned char *a = raw + 1024;
struct geometry g;
put32(a, 0xf2f52010); put32(a + 16, 12); put32(a + 20, 9);
put32(a + 24, 1); put64(a + 36, 29008896);
memcpy(raw + 5120, a, SB_BYTES); memcpy(saved, raw, sizeof(raw));
assert(!decode(raw, &g)); assert(g.blocks == 29008896 && g.section_blocks == 512);
assert(!validate_target(&g, 29008896, 12231680, 4ULL << 30));
assert(validate_target(&g, 29008895, 12231680, 0));
assert(validate_target(&g, 29008896, 12231681, 0));
assert(validate_target(&g, 29008896, 0, 0));
assert(validate_target(&g, 29008896, 29008896, 0));
assert(validate_target(&g, 29008896, 12231680, 50ULL << 30));
assert(validate_target(&g, 29008896, 12231680, UINT64_MAX));
uint64_t n;
assert(!parse_count("12231680", &n) && n == 12231680);
const char *bad[] = {"", "0", "0123", "-1", "+1", "1G", " 123", "18446744073709551616"};
for (unsigned i = 0; i < sizeof(bad)/sizeof(*bad); i++) assert(parse_count(bad[i], &n));
for (int copy = 0; copy < 2; copy++) {
memcpy(raw, saved, sizeof(raw)); raw[(copy ? 5120 : 1024)] ^= 1;
assert(decode(raw, &g));
}
for (uint32_t sections = 0; sections <= 65537; sections += 65537) {
memcpy(raw, saved, sizeof(raw)); put32(raw + 1024 + 24, sections);
memcpy(raw + 5120, raw + 1024, SB_BYTES); assert(decode(raw, &g));
}
memcpy(raw, saved, sizeof(raw)); put64(raw + 1024 + 36, 29008895);
memcpy(raw + 5120, raw + 1024, SB_BYTES); assert(decode(raw, &g));
/* Exercise the actual compare/write/fsync/readback primitives on an owned
* temporary regular file. Never open a system block device in this test. */
char temp[] = "/tmp/openwrt-online-native-XXXXXX";
int fd = mkstemp(temp); assert(fd >= 0);
struct image old = { saved, sizeof(saved) }, next = { raw, sizeof(raw) };
assert(commit_image(fd, &old, 0)); assert(matches(fd, &old, 0));
assert(!matches(fd, &next, 0));
assert(commit_image(fd, &next, 8192)); assert(matches(fd, &next, 8192));
close(fd); fd = open(temp, O_RDONLY); assert(fd >= 0);
assert(!commit_image(fd, &old, 8192)); assert(matches(fd, &next, 8192));
close(fd); unlink(temp);
puts("PASS: dual superblocks, exact 64 GiB target, alignment, stale geometry, capacity and invalid arguments; no device ioctl");
return 0;
}
+3
View File
@@ -19,6 +19,9 @@ def digest(path):
def sources():
paths = [HERE/n for n in ('backend_entry.py','build.py','package_gui.py','platform-tools.json','platform-tools-macos.json','GUIDE.md','ota-tool.py','stage-ota.py','build-ota.py','ota-requirements.txt')]
paths += list((HERE/'backend').glob('*.py'))
paths += [HERE.parent/'rootfs/overlay/opt/mu300/lib/storage.sh']
paths += [HERE/'device'/n for n in ('f2fs-online.c','test-f2fs-online.c','f2fs-online-arm64','build.json')]
paths += [HERE/'build-online-helper.py']
paths += list((HERE.parent/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota').glob('*.py'))
paths += [HERE.parent/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota/proxy.sh']
paths += list((HERE/'ota-native').glob('*'))
Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 109 KiB

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 67 KiB

+2 -2
View File
@@ -105,7 +105,7 @@ def child(package):
pass
def exec_command(self, command, **kwargs):
if command == 'cat /sys/class/block/mmcblk0/device/cid':
if (command == 'cat /sys/class/block/mmcblk0/device/cid' or command.endswith('d=$(mu300_storage_disk) && mu300_storage_identity "$d"')):
value = cid.encode()
elif command.startswith('readlink -f') or command == 'cat /run/mu300/disk-dev':
value = b'/dev/mmcblk0p74'
@@ -152,7 +152,7 @@ def child(package):
self.host=host
def exec_command(self,command,**kwargs):
if self.host=='192.0.2.1':
if command!='cat /sys/class/block/mmcblk0/device/cid':
if not (command=='cat /sys/class/block/mmcblk0/device/cid' or command.endswith('d=$(mu300_storage_disk) && mu300_storage_identity "$d"')):
raise AssertionError('Read another router beyond identity')
response=service.dispatch({'protocol':1,'command':'verify_openwrt','params':{
'transaction':record['id'],'host':'192.0.2.2','password':'frozen-private-password'}})
+3 -1
View File
@@ -32,8 +32,10 @@ def child(package):
return 'test-boot'
if script == 'settings get secure user_setup_complete':
return '1'
if script.startswith('set -e; d='):
if 'echo NODE=$n' in script:
return 'NODE=mmcblk1p16\nCID=' + 'b' * 32 + '\nSTART=2048\nSIZE=33554432\nDISK_SIZE=134217728\nFREE=12582912\nSOURCE=/dev/block/mmcblk1p16\nROOT=mmcblk1p20\n'
if script.startswith('cards='):
return ''
if script == 'cat /sys/class/block/mmcblk1p20/start /sys/class/block/mmcblk1p20/size':
return '33556480 8388608'
raise AssertionError('Unexpected simulated read')
+68
View File
@@ -0,0 +1,68 @@
"""Production UI: default strategy and explicit, unconfirmed erase fallback."""
from playwright.sync_api import sync_playwright
from ui_smoke import BRIDGE, fixture_context, layout, settle
ONLINE = r'''
localStorage.setItem('onboarding-v1','seen');
const originalInvoke=window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke=async(command,args={})=>{
if(command==='backend_request' && args.command==='online_fallback'){
window.__fixture.calls.push({command:args.command,params:args.params});
const tx=window.__fixture.tx;
return {...tx,stage:'plan',status:'ready',online_fallback:{...tx.online_fallback,state:'confirmed'},plan:{...tx.plan,shrink_strategy:undefined,wipe:true,offline:true}};
}
const result=await originalInvoke(command,args);
if(command==='backend_request' && args.command==='plan'){
const plan={...result.plan,shrink_strategy:'online-f2fs',wipe:false,offline:false,two_stage:true};
window.__fixture.tx.plan=plan;result.plan=plan;
}
return result;
};
'''
def main():
with sync_playwright() as p:
browser=p.chromium.launch()
for language in ('zh','en'):
context=fixture_context(browser,viewport={'width':800,'height':650})
context.add_init_script(BRIDGE+ONLINE+f"localStorage.setItem('language','{language}');")
page=context.new_page();errors=[];page.on('pageerror',lambda e:errors.append(str(e)))
page.goto('http://127.0.0.1:1420');zh=language=='zh'
page.get_by_role('button',name='安装 OpenWrt' if zh else 'Install OpenWrt',exact=False).click()
select=page.get_by_label('需要缩容时' if zh else 'When shrinking is needed')
assert select.input_value()=='prefer-online'
select.select_option('format');assert select.input_value()=='format'
select.select_option('prefer-online')
page.get_by_role('button',name='校验安装包' if zh else 'Verify package',exact=True).click()
page.get_by_label('请选择设备' if zh else 'Select a device').select_option('fixture-1234')
page.get_by_role('button',name='检查设备' if zh else 'Inspect device',exact=True).click()
page.get_by_role('button',name='查看安装计划' if zh else 'Review installation plan',exact=True).click()
settle(page);layout(page)
page.get_by_text('在线保留 Android 数据缩容' if zh else 'Shrink while preserving Android data',exact=True).wait_for()
start=page.get_by_role('button',name='确认并开始' if zh else 'Confirm and start',exact=True)
assert start.is_disabled();page.locator('.confirmation input').check();start.click();settle(page)
page.evaluate("window.__emitFixture({stage:'online_fallback',status:'waiting_user',online_fallback:{state:'awaiting',nonce:'bound-nonce',reason:'Unsupported kernel / 内核不支持'}})")
dialog=page.get_by_role('dialog');dialog.wait_for();settle(page)
action=dialog.get_by_role('button',name='准备清空数据的计划' if zh else 'Prepare erase-data plan',exact=True)
assert action.is_disabled();dialog.locator('input').fill('YES');assert action.is_disabled()
dialog.locator('input').fill('yes');assert action.is_enabled()
# Dismiss does not send an erase command. Reopen the decision.
dialog.locator('.dialog-footer').get_by_role('button',name='保留当前状态' if zh else 'Keep current state',exact=True).click();settle(page)
assert not [c for c in page.evaluate('window.__fixture.calls') if c['command']=='online_fallback']
page.get_by_role('button',name='在线缩容未完成,是否准备清空数据的方案?' if zh else 'Prepare an erase-data plan instead?',exact=True).click()
assert dialog.locator('input').input_value()==''
dialog.locator('input').fill('yes')
dialog.get_by_role('button',name='准备清空数据的计划' if zh else 'Prepare erase-data plan',exact=True).click();settle(page)
start=page.get_by_role('button',name='确认并开始' if zh else 'Confirm and start',exact=True)
assert start.is_disabled();assert not page.locator('.confirmation input').is_checked()
calls=page.evaluate('window.__fixture.calls')
assert [c for c in calls if c['command']=='online_fallback'][-1]['params']=={'transaction':'a'*32,'nonce':'bound-nonce','confirmation':'yes'}
assert len([c for c in calls if c['command']=='start'])==1
assert not errors,errors
layout(page);context.close()
browser.close()
print('PASS: zh/en, small viewport, default online, explicit format, cancel, nonce/yes and new-plan confirmation')
if __name__=='__main__':main()
+1 -1
View File
@@ -9,7 +9,7 @@ import time
from urllib.request import urlopen
ROOT=Path(__file__).resolve().parents[1]
CHECKS=('ui_smoke','help_smoke','refresh_smoke','method_smoke','ordering_smoke','diagnostics_smoke','update_smoke','support_smoke','wireless_smoke','uninstall_smoke','mtp_smoke')
CHECKS=('ui_smoke','help_smoke','refresh_smoke','method_smoke','ordering_smoke','diagnostics_smoke','update_smoke','support_smoke','wireless_smoke','uninstall_smoke','mtp_smoke','online_shrink_smoke')
def main():
+2 -2
View File
@@ -43,7 +43,7 @@ class CapacityRecovery(unittest.TestCase):
commands = []
def read(command, timeout=15):
commands.append(command)
if command == 'cat /sys/class/block/mmcblk0/device/cid':
if (command == 'cat /sys/class/block/mmcblk0/device/cid' or command.endswith('d=$(mu300_storage_disk) && mu300_storage_identity "$d"')):
value = DEVICE['cid']
elif command == 'cat /proc/sys/kernel/random/boot_id':
value = '22222222-2222-4222-8222-222222222222'
@@ -66,7 +66,7 @@ class CapacityRecovery(unittest.TestCase):
self.service.run(context, adapter)
adapter.probe.assert_not_called()
adapter.execute.assert_not_called()
self.assertTrue(all(command.startswith(('cat ', 'readlink -f', 'dd if=', 'test -s '))
self.assertTrue(all((command.startswith(('cat ', 'readlink -f', 'dd if=', 'test -s ')) or command.endswith('d=$(mu300_storage_disk) && mu300_storage_identity "$d"'))
and 'of=' not in command for command in commands))
return self.store.load(record['id'])
+1 -1
View File
@@ -40,7 +40,7 @@ class FlowBoundaries(unittest.TestCase):
struct.pack_into('<I', raw, 24, 2)
struct.pack_into('<I', raw, 4, ((2 if expected_failure else 4) << 30)//4096)
def read(command, timeout=15):
if command == 'cat /sys/class/block/mmcblk0/device/cid':
if (command == 'cat /sys/class/block/mmcblk0/device/cid' or command.endswith('d=$(mu300_storage_disk) && mu300_storage_identity "$d"')):
value = DEVICE['cid']
elif command.startswith('readlink -f') or command == 'cat /run/mu300/disk-dev':
value = '/dev/mmcblk0p20'
+1 -1
View File
@@ -176,7 +176,7 @@ class MacIntegrationTest(unittest.TestCase):
with patch.object(package_gui, 'HERE', self.installer):
before = package_gui.sources()
for name in names:
if Path(name).suffix not in ('.png', '.ico', '.icns', '.so'):
if Path(name).suffix in ('.py','.ts','.tsx','.json','.toml','.rs','.js','.html','.md','.css','.lock','.txt','.c','.sh'):
(self.installer/name).write_bytes(b'fixture\r\n')
self.assertEqual(package_gui.sources(), before)
(self.installer/'ui/src-tauri/icons/icon.icns').write_bytes(b'fixture\r\n')
+2 -1
View File
@@ -38,8 +38,9 @@ class ReadOnlyAdb:
self.commands.append(script)
if script=='cat /proc/sys/kernel/random/boot_id':return 'boot-fixture'
if script=='settings get secure user_setup_complete':return '1'
if script.startswith('set -e; d='):
if 'echo NODE=$n' in script:
return f'NODE=mmcblk1p16\nCID={CID}\nSTART=2048\nSIZE=33554432\nDISK_SIZE=134217728\nFREE=12582912\nSOURCE=/dev/block/mmcblk1p16\nROOT=mmcblk1p20\n'+('TF=/dev/block/mmcblk0p1\n' if self.card else '')
if script.startswith('cards='):return '/dev/block/mmcblk0p1' if self.card else ''
if script=='cat /sys/class/block/mmcblk1p20/start /sys/class/block/mmcblk1p20/size':return '33556480 8388608'
if script=='test -b /dev/block/mmcblk0p1; echo $?':return '0'
if script=='cat /sys/class/block/mmcblk0p1/size':return '16777216'
+303
View File
@@ -0,0 +1,303 @@
"""Preservation/erase boundaries, real GPT bytes, and restart checkpoints.
No device writes or hardware success claims. Native ioctl is exercised only by
the separately authorized Changxing60 experiment documented in docs/.
"""
from copy import deepcopy
import io
import json
from pathlib import Path
import struct
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import Mock, patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from backend import gpt
from backend.online_shrink import (OnlineShrink, OnlineDecision, allocation, candidate,
fallback_plan, helper_files, inspect, superblocks)
from backend.service import plan_install, Service
from backend.state import Context, Pending, RecoveryRequired, Store, sha
from backend.uninstall import partition, restored_layout, table
import uuid
import zlib
def snapshot(block, sectors=64*2097152):
factor=block//512;total=sectors//factor;count=128;rows=(count*128+block-1)//block
table=bytearray(count*128)
for number,name,start,end in ((1,'misc',2048,4095),(2,'userdata',4096,16*2097152-1)):
e=bytearray(128);e[:16]=uuid.UUID('0fc63daf-8483-4772-8e79-3d69d8477de4').bytes_le
e[16:32]=uuid.UUID(int=number).bytes_le
struct.pack_into('<QQ',e,32,start//factor,(end+1)//factor-1)
text=name.encode('utf-16-le');e[56:56+len(text)]=text;table[(number-1)*128:number*128]=e
def header(at,other,entries):
h=bytearray(block);h[:8]=b'EFI PART';struct.pack_into('<II',h,8,0x10000,92)
struct.pack_into('<QQQQ',h,24,at,other,2+rows,total-2-rows)
h[56:72]=uuid.UUID(int=999).bytes_le
struct.pack_into('<QIII',h,72,entries,count,128,zlib.crc32(table))
struct.pack_into('<I',h,16,zlib.crc32(h[:92]));return h
first=bytes(block)+header(1,total-1,2)+table
last=table+header(total-1,1,total-1-rows)
return first,last,sectors
def sb(blocks=3932160):
raw=bytearray(8192);s=bytearray(3072)
struct.pack_into('<I',s,0,0xf2f52010)
struct.pack_into('<II',s,16,12,9);struct.pack_into('<I',s,24,1)
struct.pack_into('<Q',s,36,blocks);s[108:124]=bytes(range(1,17))
raw[1024:4096]=s;raw[5120:8192]=s
return bytes(raw)
def device(block=4096):
first,last,total=snapshot(block)
data=partition(gpt.gpt_space(first,last,total),'userdata')
size=data['end']-data['start']+1
d=dict(serial='fixture',cid='a'*32,profile='fixture',model='fixture',slot='_b',boot_id='before',
readiness='ready',encrypted=True,encryption_type='file',existing=False,free_bytes=12<<30,
userdata_bytes=size*512,storage=dict(NODE='sdb'+str(data['n']),CID='a'*32,START=data['start'],
SIZE=size,DISK_SIZE=total,SOURCE='/dev/block/dm-7'),gpt=dict(safe_gaps=[],empty=[3]))
d['online_shrink']=dict(available=True,blocks=3932160,section_blocks=512,uuid=bytes(range(1,17)).hex(),
volume={'source':'/dev/block/dm-7','mapped_bytes':size*512})
return d,(first,last),total
class OnlineTests(unittest.TestCase):
def test_two_superblocks_and_format_rejection(self):
self.assertEqual(superblocks(sb())['blocks'],3932160)
for offset in (1024,5120,1060,5228):
raw=bytearray(sb());raw[offset]^=1
with self.subTest(offset=offset),self.assertRaises(ValueError):superblocks(raw)
with self.assertRaises(ValueError):superblocks(sb()[:-1])
def test_prefer_online_but_keep_explicit_format_and_existing_free_space(self):
for kind in ('e5','mu300'):
for slot in ('_a','_b'):
d,_,_=device();d['slot']=slot;p={'adapter':kind}
plan=plan_install(p,d,dict(method='part',size_gib=4))
self.assertEqual(plan['shrink_strategy'],'online-f2fs');self.assertFalse(plan['wipe'])
self.assertTrue(plan['two_stage']);self.assertEqual(plan['new_sectors']%2048,0)
original=plan_install(p,d,dict(method='part',size_gib=4,shrink_strategy='format',wipe=True))
self.assertTrue(original['wipe']);self.assertTrue(original['offline'])
self.assertNotIn('shrink_strategy',original)
d['gpt']['safe_gaps']=[(100000000,100000000)]
gap=plan_install(p,d,dict(method='part',size_gib=4))
self.assertEqual(gap['target'],'GPT unallocated space');self.assertFalse(gap['wipe'])
def test_insufficient_online_space_offers_clearly_destructive_plan(self):
d,_,_=device();d['free_bytes']=1<<30
plan=plan_install({'adapter':'e5'},d,dict(method='part',size_gib=4))
self.assertTrue(plan['wipe']);self.assertIn('online_unavailable',plan)
d['gpt']['empty']=[]
with self.assertRaisesRegex(ValueError,'GPT'):plan_install({'adapter':'e5'},d,dict(method='part',size_gib=4))
def test_real_512_4kn_emmc_ufs_gpt_and_uninstall_origin(self):
for block,nodekind in ((512,'mmcblk1p'),(4096,'sdb')):
d,pair,total=device(block);data=partition(gpt.gpt_space(*pair,total),'userdata')
node=nodekind+str(data['n']);new=(data['end']-data['start']+1-8388608)//2048*2048
resized=candidate(pair,total,node,d['storage']['SIZE'],new)
old,newtable=table(pair[0]),table(resized[0]);at=(data['n']-1)*128
self.assertEqual(old[:at+40]+old[at+48:],newtable[:at+40]+newtable[at+48:])
for name in ('e5root','mu300root'):
root=gpt.gpt_add_root(*resized,total,data['start']+new,8388608,name)
restored,prior,_,grew=restored_layout(pair,root,total,name)
self.assertEqual(prior['end'],data['end']);self.assertTrue(grew)
self.assertEqual(tuple(restored),pair)
with self.assertRaises(RecoveryRequired):candidate(pair,total,node,d['storage']['SIZE']+1,new)
def test_mapping_and_encryption_eligibility_do_not_mutate(self):
d,_,_=device();a=SimpleNamespace(adb=Mock())
volume=dict(source='/dev/block/dm-7',mapping_overhead=0,filesystem='f2fs',uuid=d['online_shrink']['uuid'])
a.adb.shell.return_value=d['storage']['NODE'];a.adb.read.return_value=sb()
with patch('backend.online_shrink.android_volume',return_value=volume):
self.assertTrue(inspect(a,d)['available'])
a.adb.shell.return_value='sdc4'
self.assertFalse(inspect(a,d)['available'])
volume['mapping_overhead']=4096
self.assertFalse(inspect(a,d)['available'])
volume['mapping_overhead']=0;d['encryption_type']='block'
self.assertFalse(inspect(a,d)['available'])
self.assertFalse(any(' of=' in str(c) for c in a.adb.mock_calls))
def job(self,temp):
d,pair,total=device();store=Store(Path(temp));plan=plan_install({'adapter':'e5'},d,dict(method='part',size_gib=4))
r=store.create({'adapter':'e5'},d,dict(method='part',size_gib=4),plan)
ctx=Context(store,r,lambda *_:None);a=SimpleNamespace(ctx=ctx,kind='e5',bind=Mock(),adb=Mock(),probe=Mock(return_value=deepcopy(d)))
a.adb.shell.return_value='busy=0'
job=OnlineShrink(a);job.directory.mkdir()
new=tuple(candidate(pair,total,d['storage']['NODE'],d['storage']['SIZE'],plan['new_sectors']))
files=dict(zip(('old-first','old-last','new-first','new-last'),(*pair,*new)))
for n,raw in files.items():(job.directory/n).write_bytes(raw)
r['online_shrink']=dict(version=1,state='started',front=len(pair[0])//512,tail=total-len(pair[1])//512,
sectors=total,uuid=d['online_shrink']['uuid'],old_blocks=d['online_shrink']['blocks'],boot_id='before',
**{k:plan[k] for k in ('target_blocks','new_sectors','gap_start')},files={n:sha(job.directory/n) for n in files})
return job,r,a,pair,new
def test_new_gpt_old_boot_only_reboots_never_repeats_resize(self):
with tempfile.TemporaryDirectory() as temp:
job,r,a,old,new=self.job(temp);info=dict(r['device']['online_shrink'],blocks=r['online_shrink']['target_blocks'])
with patch.object(job,'pair',return_value=new),patch('backend.online_shrink.inspect',return_value=info),patch.object(job,'stage') as stage:
with self.assertRaises(Pending):job.run()
stage.assert_not_called();a.adb.call.assert_called_once_with('reboot')
self.assertEqual(r['online_shrink']['state'],'gpt-committed')
def test_commit_resumed_in_later_android_boot_waits_for_that_boot(self):
with tempfile.TemporaryDirectory() as temp:
job,r,a,_,new=self.job(temp)
a.probe.return_value=deepcopy(r['device']);a.probe.return_value['boot_id']='intermediate'
info=dict(r['device']['online_shrink'],blocks=r['online_shrink']['target_blocks'])
with patch.object(job,'pair',return_value=new),patch('backend.online_shrink.inspect',return_value=info):
with self.assertRaises(Pending):job.run()
self.assertEqual(r['device']['boot_id'],'intermediate')
self.assertEqual(r['online_shrink']['commit_boot_id'],'intermediate')
a.adb.call.assert_called_once_with('reboot')
def test_reboot_verifies_uuid_capacity_mapping_and_gap_before_install(self):
with tempfile.TemporaryDirectory() as temp:
job,r,a,old,new=self.job(temp);actual=deepcopy(r['device']);actual['boot_id']='after'
actual['storage']['SIZE']=r['online_shrink']['new_sectors']
actual['gpt']['safe_gaps']=[(r['plan']['gap_start'],r['plan']['openwrt_bytes']//512)]
a.probe.return_value=actual
info=dict(r['device']['online_shrink'],blocks=r['online_shrink']['target_blocks'],volume={'mapped_bytes':actual['storage']['SIZE']*512})
with patch.object(job,'pair',return_value=new),patch('backend.online_shrink.inspect',return_value=info):
job.run()
self.assertEqual(r['online_shrink']['state'],'verified');self.assertFalse(r['unsafe'])
self.assertEqual(r['device']['boot_id'],'after');self.assertEqual(r['plan']['target'],'GPT unallocated space')
a.adb.call.assert_not_called()
def test_erasing_decision_requires_unchanged_verified_state(self):
with tempfile.TemporaryDirectory() as temp:
job,r,a,old,new=self.job(temp)
with patch.object(job,'unchanged',return_value=False):
with self.assertRaises(RecoveryRequired):job.decision('ioctl error')
self.assertNotIn('online_fallback',r)
with patch.object(job,'unchanged',return_value=True):
with self.assertRaises(OnlineDecision):job.decision('unsupported')
self.assertFalse(r['unsafe']);self.assertFalse(r['plan']['wipe'])
self.assertEqual(r['online_fallback']['state'],'awaiting')
def test_prepare_backs_up_before_launch_and_rejects_changed_installation(self):
with tempfile.TemporaryDirectory() as temp:
job,r,a,pair,_=self.job(temp);r.pop('online_shrink')
space=gpt.gpt_space(*pair,r['device']['storage']['DISK_SIZE'])
a.read_gpt=Mock(return_value=dict(space,first=pair[0],last=pair[1]))
a.backup=Mock();a.adb.shell.return_value='sdb3'
def metadata(name,path,context):
a.backup.assert_called_once();self.assertEqual(name,'metadata')
path.write_bytes(b'private metadata fixture')
a.adb.backup_partition.side_effect=metadata
with patch('backend.online_shrink.inspect',return_value=r['device']['online_shrink']):
job.prepare()
self.assertEqual(r['online_shrink']['state'],'prepared');self.assertIn('metadata.bin',r['online_shrink']['files'])
self.assertEqual(set(job.files()),{'old-first','old-last','new-first','new-last'})
a.adb.call.assert_not_called()
r.pop('online_shrink');a.backup.reset_mock();a.probe.return_value['existing']=True
with self.assertRaises(RecoveryRequired):job.prepare()
a.backup.assert_not_called()
def test_new_format_plan_requires_nonce_yes_and_unchanged_readback(self):
with tempfile.TemporaryDirectory() as temp:
job,r,a,_,_=self.job(temp);r['online_fallback']=dict(state='awaiting',nonce='one',reason='unsupported')
service=SimpleNamespace(active=None,adapter=Mock(return_value=a),store=job.ctx.store,emit=lambda *_:None,public=lambda r:r)
for params in ({},{'nonce':'bad','confirmation':'yes'},{'nonce':'one','confirmation':'no'}):
with self.assertRaises(ValueError):fallback_plan(service,r,params)
with patch.object(OnlineShrink,'unchanged',return_value=False):
with self.assertRaises(RecoveryRequired):fallback_plan(service,r,dict(nonce='one',confirmation='yes'))
with patch.object(OnlineShrink,'unchanged',return_value=True):
fallback_plan(service,r,dict(nonce='one',confirmation='yes'))
self.assertTrue(r['plan']['wipe']);self.assertEqual(r['status'],'ready')
self.assertEqual(r['choices']['shrink_strategy'],'format');a.adb.call.assert_not_called()
def test_helper_hash_and_frozen_resource_layout(self):
binary,metadata=helper_files();info=json.loads(metadata.read_text())
with tempfile.TemporaryDirectory() as temp:
directory=Path(temp);(directory/'online-helper').mkdir()
(directory/'f2fs-online-arm64').write_bytes(binary.read_bytes())
(directory/'online-helper/build.json').write_text(json.dumps(info))
with patch.object(sys,'frozen',True,create=True),patch.object(sys,'_MEIPASS',str(directory),create=True):
helper_files()
(directory/'f2fs-online-arm64').write_bytes(b'corrupt')
with self.assertRaises(ValueError):helper_files()
def simulate(self, temp, *, interrupt=False, reject=False, cancel=False, mixed=False, launch_reject=False):
job,r,a,old,new=self.job(temp)
r['online_shrink']['state']='prepared'
service=Service('.',job.ctx.store,io.StringIO())
service.openwrt_wait_stage=Mock();service.wait_openwrt=Mock()
ctx=job.ctx;a.password='';a.execute=Mock()
machine=dict(pair=old,blocks=r['online_shrink']['old_blocks'],boot='before',launches=0)
if mixed:
machine.update(pair=(old[0],new[1]),blocks=r['online_shrink']['target_blocks'])
r['online_shrink']['state']='started'
def current(*_):
d=deepcopy(r['device']);d['boot_id']=machine['boot']
if machine['boot']=='after':
d['storage']['SIZE']=r['online_shrink']['new_sectors']
d['userdata_bytes']=d['storage']['SIZE']*512
d['gpt']['safe_gaps']=[(r['plan']['gap_start'],r['plan']['openwrt_bytes']//512)]
return d
def info(*_):
d=current();return dict(available=True,blocks=machine['blocks'],section_blocks=512,
uuid=r['online_shrink']['uuid'],volume=dict(source='/dev/block/dm-7',mapped_bytes=d['userdata_bytes']))
def shell(command,**_):
if 'lock-status' in command:
if command.startswith('cat '):return 'phase=complete\nbusy=0'
return 'busy=0'
if ' probe /data ' in command:
if reject:raise ConnectionError('errno=25')
return 'same_size_probe=OK'
if ' start /data ' in command:
machine['launches']+=1
if launch_reject:raise ConnectionError('permission denied before fork')
machine['pair']=new;machine['blocks']=r['online_shrink']['target_blocks']
if cancel:ctx.cancel=True
if interrupt and machine['launches']==1:raise ConnectionError('ADB disconnected after fork')
return 'worker_started=42'
raise AssertionError(command)
def call(command):
self.assertEqual(command,'reboot');machine['boot']='after'
a.adb.shell.side_effect=shell;a.adb.call.side_effect=call;a.probe.side_effect=current
with patch.object(OnlineShrink,'pair',side_effect=lambda:machine['pair']),patch.object(OnlineShrink,'stage'),patch('backend.online_shrink.inspect',side_effect=info),patch('backend.service.inspect_online',side_effect=info):
service.run(ctx,a)
if interrupt:
self.assertEqual(r['status'],'failed');self.assertTrue(r['error']['retryable'])
a.execute.assert_not_called()
# A new coordinator loads the durable recipe; never repeats ioctl.
r=job.ctx.store.load(r['id']);ctx=Context(job.ctx.store,r,lambda *_:None);a.ctx=ctx
service.run(ctx,a)
return r,a,machine
def test_coordinator_first_install_and_post_launch_adb_loss(self):
for interrupt,mixed in ((False,False),(True,False),(False,True)):
with self.subTest(interrupt=interrupt,mixed=mixed),tempfile.TemporaryDirectory() as temp:
r,a,m=self.simulate(temp,interrupt=interrupt,mixed=mixed)
self.assertEqual(r['online_shrink']['state'],'verified',r.get('error'))
self.assertFalse(r['plan']['wipe']);self.assertEqual(r['device']['boot_id'],'after')
self.assertEqual(m['launches'],1);a.execute.assert_called_once()
def test_coordinator_rejected_ioctl_never_calls_installer_or_wipes(self):
with tempfile.TemporaryDirectory() as temp:
r,a,m=self.simulate(temp,reject=True)
self.assertEqual(r['online_fallback']['state'],'awaiting');self.assertFalse(r['plan']['wipe'])
self.assertEqual(m['launches'],0);a.execute.assert_not_called();a.adb.call.assert_not_called()
def test_rejected_worker_launch_offers_fallback_only_after_unchanged_readback(self):
with tempfile.TemporaryDirectory() as temp:
r,a,m=self.simulate(temp,launch_reject=True)
self.assertEqual(r['online_fallback']['state'],'awaiting');self.assertFalse(r['unsafe'])
self.assertFalse(r['plan']['wipe']);a.execute.assert_not_called();a.adb.call.assert_not_called()
def test_cancel_during_worker_is_deferred_until_gpt_is_sealed(self):
with tempfile.TemporaryDirectory() as temp:
r,a,m=self.simulate(temp,cancel=True)
self.assertEqual(r['status'],'cancelled');self.assertFalse(r['unsafe'])
self.assertEqual(r['online_shrink']['state'],'gpt-committed')
self.assertEqual(m['launches'],1);a.execute.assert_not_called()
if __name__=='__main__':unittest.main()
+1 -1
View File
@@ -64,7 +64,7 @@ class OpenwrtConfirmation(unittest.TestCase):
struct.pack_into('<I',raw,4,(expected//2 if bad_capacity else expected)//4096)
def read(command,timeout=15):
reads.append((targets[-1][0],command))
if command=='cat /sys/class/block/mmcblk0/device/cid':
if (command=='cat /sys/class/block/mmcblk0/device/cid' or command.endswith('d=$(mu300_storage_disk) && mu300_storage_identity "$d"')):
value=DEVICE['cid'] if targets[-1][0]=='192.0.2.2' else '0'*32
elif command.startswith('readlink -f'):value='/dev/mmcblk0p20'
elif command.startswith('dd if='):value=bytes(raw)
+12 -1
View File
@@ -324,6 +324,8 @@ class Journal(unittest.TestCase):
context=self.plan();base=boot(family)
root=Path(self.temp.name)/('package-'+family+'-'+slot);(root/'files').mkdir(parents=True)
(root/'files/boot.img').write_bytes(base)
(root/'desktop').mkdir()
(root/'desktop/storage-lib.sh').write_bytes((Path(__file__).resolve().parents[2]/'rootfs/overlay/opt/mu300/lib/storage.sh').read_bytes())
self.adapter.root=root
self.adapter.legacy=SimpleNamespace(payload_file=lambda root,name:root/'files/boot.img')
other='b' if slot=='a' else 'a'
@@ -363,6 +365,13 @@ class Journal(unittest.TestCase):
size=struct.unpack_from('<I',generated,12)[0]
files={n:b for archive in archives(generated[8192:8192+size]) for n,b,_ in entries(archive)}
self.assertIn(b'--wipe_data',files['openwrt-uninstall/recovery-bcb'])
helper=files['openwrt-uninstall/storage.sh']
self.assertIn(b'mu300_storage_identity()',helper)
sums=files['openwrt-uninstall/SHA256SUMS'].decode().splitlines()
for row in sums:
digest,name=row.split(' ',1)
self.assertEqual(digest,hashlib.sha256(files['openwrt-uninstall/'+name]).hexdigest())
self.assertTrue(any(row.endswith(' storage.sh') for row in sums))
def test_other_device_is_refused_before_layout_or_boot_writes(self):
context=self.plan();self.adapter.probe=Mock(return_value={**self.device,'cid':'0'*32})
@@ -431,6 +440,7 @@ class OfflineGpt(unittest.TestCase):
(path/'size').write_text('8')
(path/'start').write_text(str(GIB//512))
(folder/'sys/class/block/mmcblk0/device/cid').write_text(IDENTITY)
(folder/'sys/class/block/mmcblk0/device/type').write_text('MMC\n')
(folder/'sys/class/block/mmcblk0/size').write_text(str(SECTORS))
android_node,linux_node=('mmcblk0p1','mmcblk0p2') if slot=='a' else ('mmcblk0p2','mmcblk0p1')
android=b'A'*4096;boot_sha=hashlib.sha256(android).hexdigest()
@@ -454,7 +464,8 @@ class OfflineGpt(unittest.TestCase):
sums=''.join(hashlib.sha256(path.read_bytes()).hexdigest()+' '+path.name+'\n'
for path in (folder/'work').iterdir())
(folder/'work/SHA256SUMS').write_text(sums)
worker=WORKER.replace('/openwrt-uninstall',str(folder/'work'))
storage_lib=(Path(__file__).resolve().parents[2]/'rootfs/overlay/opt/mu300/lib/storage.sh').read_text()
worker=WORKER.replace('. /openwrt-uninstall/storage.sh',storage_lib).replace('/openwrt-uninstall',str(folder/'work'))
worker=worker.replace('/sys/',str(folder/'sys')+'/').replace('/dev/',str(folder/'dev')+'/')
worker=worker.replace('/proc/self/mountinfo',str(folder/'proc/mountinfo')).replace('/run/',str(folder/'run')+'/')
worker=worker.replace('while :; do sleep 10; done','exit "$rc"',1)
+1 -1
View File
@@ -70,7 +70,7 @@ class UpdateLifecycle(unittest.TestCase):
raw=bytearray(1024);raw[56:58]=b'\x53\xef'
struct.pack_into('<I',raw,24,2);struct.pack_into('<I',raw,4,(4<<30)//4096)
def read(command,timeout=15):
if command=='cat /sys/class/block/mmcblk0/device/cid':value=DEVICE['cid']
if (command=='cat /sys/class/block/mmcblk0/device/cid' or command.endswith('d=$(mu300_storage_disk) && mu300_storage_identity "$d"')):value=DEVICE['cid']
elif command=='cat /proc/sys/kernel/random/boot_id':
if read_disconnect and not read_losses:
read_losses.append(True)
+1 -1
View File
@@ -8,7 +8,7 @@ use std::{collections::HashMap, io::{BufRead, BufReader, Write}, path::PathBuf,
use tauri::{Emitter, Manager, State};
use tokio::sync::oneshot;
const COMMANDS: &[&str] = &["hello","snapshot","list","package","devices","adb_connect","adb_disconnect","probe","probe_update","plan","start","resume","retry","cancel","can_close","export","import","diagnostics","verify_openwrt","ota_analyze","ota_export","ota_export_index","ota_package","ota_probe","ota_apply","ota_status","ota_reboot"];
const COMMANDS: &[&str] = &["hello","snapshot","list","package","devices","adb_connect","adb_disconnect","probe","probe_update","plan","start","resume","retry","cancel","can_close","export","import","diagnostics","verify_openwrt","online_fallback","ota_analyze","ota_export","ota_export_index","ota_package","ota_probe","ota_apply","ota_status","ota_reboot"];
struct Bridge {
input: Mutex<Option<ChildStdin>>,
pending: Mutex<HashMap<u64, oneshot::Sender<Result<Value, String>>>>,
+2 -2
View File
@@ -7,7 +7,7 @@ export const helpStrings = {
introTitles:['准备设备和安装包','选择适合你的安装方式','等待、续装与保留备份'],
introBodies:[
['完整解压安装包,从根目录 OpenWrt-Installer.exe 启动,无需另装 Python、Node 或 Rust。','先备份需要保留的数据,保持设备供电。使用数据线连接;只有无线 ADB 时,在设备选择区展开“无线 ADB 连接”,填写地址并连接。','在 Android 开启 USB 调试、允许电脑调试并准备好 root;连接多台设备时,必须明确选择目标设备。'],
['首次安装从“安装 OpenWrt”开始。TF 卡只格式化选定目标,不重新划卡;内置分区会先检查未分配空间。','核对最终计划里的机型、写入目标、Android 保留空间和数据影响。需要重置时,Android 用户数据会被清空。','已装好 OpenWrt 时可选择更新或临时启动;重装和有 F2FS 损坏风险的实验性镜像放在高级选项。'],
['首次安装从“安装 OpenWrt”开始。TF 卡只格式化选定目标,不重新划卡;内置分区会先检查未分配空间,不足时优先在线保数据缩容。','核对最终计划里的机型、写入目标、Android 保留空间和数据影响。需要重置时,Android 用户数据会被清空。','已装好 OpenWrt 时可选择更新或临时启动;重装和有 F2FS 损坏风险的实验性镜像放在高级选项。'],
['首次离线分区准备可能需要数分钟,之后会自动重启。预期断线、Android 初始化和授权都是等待状态。','重置后完成 Android 初始化、开启 USB 调试并允许授权。已有 root 会直接使用;只有 root 不可用时才需要恢复 Magisk。','安装记录自动保存在电脑。关闭或重启后从“继续未完成的安装”恢复;换电脑前导出完整事务与备份。电脑记录和备份都丢失时,目前无法仅凭设备自动重建续装记录。'],
],
noAction:'开始安装前,请核对设备、写入目标和数据影响,并备份重要文件。', currentHelp:'查看当前步骤帮助',
@@ -20,7 +20,7 @@ export const helpStrings = {
introTitles:['Prepare your device and package','Choose an installation path','Wait, resume and keep backups'],
introBodies:[
['Extract the complete package and run OpenWrt-Installer.exe at its root. No separate Python, Node or Rust is required.','Back up important files and keep the device powered. Connect by data cable, or use Wireless ADB connection in the device section and enter its address.','Enable USB debugging on Android, authorize this computer and have root ready. When several devices are connected, select the intended device explicitly.'],
['Use Install OpenWrt for a first installation. TF installation formats only the selected target without repartitioning the card. Internal installation checks unallocated space first.','Review the model, write target, retained Android space and data impact in the final plan. A required Android reset erases its user data.','For installed OpenWrt, choose update or a one-time boot. Reinstallation and the experimental image option, which can damage F2FS, live under Advanced options.'],
['Use Install OpenWrt for a first installation. TF installation formats only the selected target without repartitioning the card. Internal installation checks unallocated space first, then prefers online preservation when shrinking is needed.','Review the model, write target, retained Android space and data impact in the final plan. A required Android reset erases its user data.','For installed OpenWrt, choose update or a one-time boot. Reinstallation and the experimental image option, which can damage F2FS, live under Advanced options.'],
['The first offline preparation may take several minutes and then reboot automatically. Expected USB disconnects, Android setup and authorization are waiting states.','After a reset, complete Android setup, enable USB debugging and grant authorization. Working root is accepted immediately; restore Magisk only if root is unavailable.','Installation records are saved automatically on the computer. After closing or restarting, choose Continue an unfinished installation. Export the full transaction and backups before moving computers. If both records and backups are lost, this version cannot reconstruct a record from the device alone.'],
],
noAction:'Before installing, check the device, write target and data impact, and back up important files.', currentHelp:'Help for this step',
+6 -2
View File
@@ -48,11 +48,13 @@ export const strings = {
updateImpact:'保留设置、分区容量和本机固件。设备会自动重启以应用更新,网络会暂时断开,请保持供电。', bootImpact:'仅本次启动进入 OpenWrt,保留已有系统和设置,不改变默认启动设置。',
updateReboot:'更新已提交,设备将自动重启', updateReconnecting:'设备正在重启,等待重新连接', updateRebootDesc:'设备将自动重启以应用更新,期间网络会暂时断开。请保持供电并等待,安装器将在确认设备重启、重新连接并校验实际容量后显示完成。',
updateNext:'设备已重启,更新已通过校验。请打开管理地址检查服务;原设置、容量和本机固件保留,事务记录仍保存在电脑上。',
shrinkMethod:'需要缩容时', shrinkPrefer:'优先在线保留 Android 数据(推荐)', shrinkFormat:'使用原有清空 Android 数据的离线方案',
onlineTitle:'在线保留 Android 数据缩容', onlineDesc:'优先由 Android 内核搬移尾部数据并缩小 F2FS,更新分区表后正常重启校验,再继续安装。不会清空 Android;若内核不支持或空间不足,将等待你选择后备方案。缩容及分区表写入期间请勿断电。', onlineFallbackTitle:'在线缩容未完成,是否准备清空数据的方案?', onlineFallbackDesc:'已核验当前数据布局未改变。输入 yes 仅生成清空 Android 数据的安装计划;仍需查看并确认新计划后才会执行。取消可保留现状。', onlineFallbackAction:'准备清空数据的计划', onlineCancel:'保留当前状态', onlineUnavailable:'在线保数据方案不可用:',
firstBoot:'首次启动会进行离线分区准备,可能需要数分钟,完成后设备会自动重启一次。',
accept:'我已核对设备、写入目标和数据影响,并已备份需要保留的文件。', start:'确认并开始', back:'返回', progress:'安装进度',
steps:['检查与计划','准备与备份','设备重启与授权','安装与校验','完成'],
running:'正在执行', waiting_user:'等待用户操作', waiting_device:'等待设备重连', failed:'操作失败', completed:'已完成', cancelled:'已暂停', readyStatus:'等待确认',
stages:{uninstall_prepare:'准备离线卸载',uninstall_restore_boot:'恢复 Android 启动',uninstall_offline:'等待离线卸载及 Android 返回',verify_android:'验证 Android 恢复容量',firmware_extract:'提取本机固件',firmware_convert:'转换本机音频与蓝牙固件',plan:'安装计划已就绪',prepare:'准备安装',backup:'备份 GPT、misc 与启动链',android_boot:'等待 Android 开机',android_setup:'请完成 Android 初始设置',usb_debugging:'请启用 USB 调试',debug_authorization:'请在设备上允许调试',magisk:'请安装或恢复 Magisk',root_permission:'请允许 root 请求',root_ready:'root 已就绪,继续安装',recheck:'复核分区与事务状态',transfer_install:'传输及安装系统',verify_capacity:'扩容与最终容量校验',openwrt_boot:'等待启动 OpenWrt',complete:'安装完成'},
stages:{online_shrink:'在线缩容并校验 GPT(请勿断电)',online_fallback:'等待选择缩容后备方案',uninstall_prepare:'准备离线卸载',uninstall_restore_boot:'恢复 Android 启动',uninstall_offline:'等待离线卸载及 Android 返回',verify_android:'验证 Android 恢复容量',firmware_extract:'提取本机固件',firmware_convert:'转换本机音频与蓝牙固件',plan:'安装计划已就绪',prepare:'准备安装',backup:'备份 GPT、misc 与启动链',android_boot:'等待 Android 开机',android_setup:'请完成 Android 初始设置',usb_debugging:'请启用 USB 调试',debug_authorization:'请在设备上允许调试',magisk:'请安装或恢复 Magisk',root_permission:'请允许 root 请求',root_ready:'root 已就绪,继续安装',recheck:'复核分区与事务状态',transfer_install:'传输及安装系统',verify_capacity:'扩容与最终容量校验',openwrt_boot:'等待启动 OpenWrt',complete:'安装完成'},
waitingAndroid:'保持设备供电。进入 Android 后完成初始设置、开启开发者选项及 USB 调试,并允许此电脑调试。若 root 仍可用,会直接继续;否则恢复 Magisk 并允许 root 请求。这里没有等待时限。',
rebootNow:'请现在手动重启设备', rebootManual:'设备端安装操作已结束。请使用设备的正常重启功能进入 OpenWrt;已开始重启或已进入 OpenWrt 时,无需重复重启。',
rebootAutomatic:'已发送自动重启请求,请等待设备开机。若设备仍停留在原系统且未开始重启,请使用设备的正常重启功能。',
@@ -116,10 +118,12 @@ export const strings = {
updateImpact:'Keep settings, partition capacity and local firmware. The device restarts after updating and its network briefly disconnects. Keep power connected.',bootImpact:'Start OpenWrt for this boot. Keep existing systems, settings and the default boot choice.',
updateReboot:'Update submitted; device restarting', updateReconnecting:'Device restarting; waiting to reconnect', updateRebootDesc:'The device will automatically restart to apply the update and its network will briefly disconnect. Keep power connected. Completion follows a confirmed restart, reconnection and actual-capacity verification.',
updateNext:'The device restarted and the update passed verification. Open its management address to check services. Settings, capacity and local firmware are retained; the transaction remains on this computer.',
shrinkMethod:'When shrinking is needed', shrinkPrefer:'Prefer online data preservation (recommended)', shrinkFormat:'Use the original offline erase-data method',
onlineTitle:'Shrink while preserving Android data', onlineDesc:'Android’s kernel relocates tail data and shrinks F2FS. The installer commits GPT, reboots Android to verify the result, then continues installation. Android is preserved. Unsupported kernels or insufficient space require a separate fallback choice. Do not remove power during resize/GPT commit.', onlineFallbackTitle:'Prepare an erase-data plan instead?', onlineFallbackDesc:'The current data layout has been verified unchanged. Type yes to prepare a plan that erases Android data. You must review and confirm that new plan before it runs. Cancel to keep the current state.', onlineFallbackAction:'Prepare erase-data plan', onlineCancel:'Keep current state', onlineUnavailable:'Online preservation unavailable:',
firstBoot:'The first boot performs offline partition preparation. This may take several minutes; the device will reboot automatically once it finishes.',
accept:'I checked the device, write target and data impact, and backed up the files I need.',start:'Confirm and start',back:'Back',progress:'Installation progress',steps:['Checks and plan','Prepare and back up','Restart and authorize','Install and verify','Complete'],
running:'Running',waiting_user:'Waiting for you',waiting_device:'Waiting for device',failed:'Failed',completed:'Completed',cancelled:'Paused',readyStatus:'Awaiting confirmation',
stages:{uninstall_prepare:'Preparing offline removal',uninstall_restore_boot:'Restoring Android boot',uninstall_offline:'Waiting for offline removal and Android',verify_android:'Verifying restored Android capacity',firmware_extract:'Extracting this device’s firmware',firmware_convert:'Converting device audio and Bluetooth firmware',plan:'Installation plan ready',prepare:'Preparing installation',backup:'Backing up GPT, misc and boot chain',android_boot:'Waiting for Android to boot',android_setup:'Complete Android initial setup',usb_debugging:'Enable USB debugging',debug_authorization:'Allow debugging on the device',magisk:'Install or restore Magisk',root_permission:'Allow the root request',root_ready:'Root is ready; continuing installation',recheck:'Rechecking partitions and transaction',transfer_install:'Transferring and installing the system',verify_capacity:'Growing and verifying actual capacity',openwrt_boot:'Waiting for OpenWrt to start',complete:'Installation complete'},
stages:{online_shrink:'Resizing online and verifying GPT — keep power connected',online_fallback:'Waiting for resize fallback choice',uninstall_prepare:'Preparing offline removal',uninstall_restore_boot:'Restoring Android boot',uninstall_offline:'Waiting for offline removal and Android',verify_android:'Verifying restored Android capacity',firmware_extract:'Extracting this device’s firmware',firmware_convert:'Converting device audio and Bluetooth firmware',plan:'Installation plan ready',prepare:'Preparing installation',backup:'Backing up GPT, misc and boot chain',android_boot:'Waiting for Android to boot',android_setup:'Complete Android initial setup',usb_debugging:'Enable USB debugging',debug_authorization:'Allow debugging on the device',magisk:'Install or restore Magisk',root_permission:'Allow the root request',root_ready:'Root is ready; continuing installation',recheck:'Rechecking partitions and transaction',transfer_install:'Transferring and installing the system',verify_capacity:'Growing and verifying actual capacity',openwrt_boot:'Waiting for OpenWrt to start',complete:'Installation complete'},
waitingAndroid:'Keep power connected. Complete Android setup, enable developer options and USB debugging, then authorize this computer. Existing working root is accepted immediately; otherwise restore Magisk and grant root. There is no waiting deadline.',
rebootNow:'Restart the device now', rebootManual:'Device installation operations have finished. Use the device’s normal restart control to enter OpenWrt. If it is already restarting or running OpenWrt, do not restart it again.',
rebootAutomatic:'An automatic restart was requested. Wait for the device to boot. If it stays in the previous system without restarting, use its normal restart control.',
+23 -3
View File
@@ -47,9 +47,13 @@ function App() {
const [planOrigin, setPlanOrigin] = useState<View>('install');
const [size, setSize] = useState('4');
const [grow, setGrow] = useState(true);
const [shrinkMode, setShrinkMode] = useState('prefer-online');
const [host, setHost] = useState('192.168.9.1');
const [password, setPassword] = useState('');
const [accepted, setAccepted] = useState(false);
const [onlineInput, setOnlineInput] = useState('');
const [onlineDismissed, setOnlineDismissed] = useState(false);
useEffect(() => {setOnlineInput('');setOnlineDismissed(false);}, [tx?.online_fallback?.nonce]);
const [resetPrompt, setResetPrompt] = useState<ResetPrompt>();
const [busy, setBusy] = useState(false);
const [logs, setLogs] = useState<string[]>([]);
@@ -217,7 +221,7 @@ function App() {
if (next === 'update') setMethod('update');
};
const plan = async (resetToken?: string) => {
const value = await task(() => request<Transaction | ResetPrompt>('plan', {serial, choices: {method, size_gib: Number(size), grow, host}, password, reset_token:resetToken}));
const value = await task(() => request<Transaction | ResetPrompt>('plan', {serial, choices: {method, size_gib: Number(size), grow, host, shrink_strategy:shrinkMode, wipe:method === 'part' && shrinkMode === 'format'}, password, reset_token:resetToken}));
if (value && 'confirmation_required' in value) {
setResetPrompt(value); reportError(value.reason); return;
}
@@ -229,6 +233,7 @@ function App() {
if (value) {acceptTransaction(value); setView('progress'); setLogOpen(true); setSince(Date.now()); setTransfer(undefined);}
};
const continueRecord = async (record: Transaction) => {
if (record.online_fallback?.state === 'awaiting') {acceptTransaction(record,false);setView('progress');setOnlineDismissed(false);return;}
if (record.status === 'ready') {
acceptTransaction(record, false); setPlanOrigin('resume'); setAccepted(false); setView('plan');
} else await start('resume', record);
@@ -270,6 +275,7 @@ function App() {
const observer = new ResizeObserver(revealCurrent);observer.observe(list);
return () => observer.disconnect();
}, [current, lang]);
const waitingOnline = tx?.online_fallback?.state === 'awaiting';
const active = tx && ['running', 'waiting_device', 'waiting_user'].includes(tx.status);
const openHelp = useCallback(() => {
setHelpTopic(view === 'advanced' && method === 'uninstall' || ['plan','progress'].includes(view) && tx?.choices.method === 'uninstall' ? 'uninstall' : view === 'resume' || view === 'progress' && (['failed','completed'].includes(tx?.status || '') || tx?.stage === 'openwrt_boot') ? 'recovery' : view === 'progress' && ['android_boot','android_setup'].includes(tx?.stage || '') ? 'reset' : view === 'progress' && tx?.status.startsWith('waiting') ? 'faq' : view === 'plan' ? 'storage' : view === 'home' ? 'start' : 'purpose');
@@ -344,6 +350,7 @@ function App() {
{view !== 'update' && view !== 'boot' && <section><h2>{view === 'advanced' ? t.advanced : t.install}</h2><div className="method-options" role="group" aria-label={view === 'advanced' ? t.advanced : t.install}>{(view === 'advanced' ? ['reinstall','image','uninstall'] : ['tf','part','reinstall']).map(m => <button disabled={busy} key={m} aria-pressed={method === m} className={method === m ? 'selected' : ''} onClick={() => setMethod(m)}>{m === 'tf' ? <Usb size={17}/> : <HardDrive size={17}/>}{(t as unknown as Record<string,string>)[m]}{(m === 'tf' && device?.tf || m === 'reinstall' && device?.existing) && <span>{t.recommended}</span>}</button>)}</div>
{method === 'uninstall' && <div className="alert danger"><CircleAlert size={18}/><p>{t.uninstallHelp}</p></div>}
{method === 'image' && <div className="alert danger"><CircleAlert size={18}/><strong>{t.experimental}</strong></div>}
{method === 'part' && <label className="size-field">{t.shrinkMethod}<select disabled={busy} value={shrinkMode} onChange={e => setShrinkMode(e.target.value)}><option value="prefer-online">{t.shrinkPrefer}</option><option value="format">{t.shrinkFormat}</option></select></label>}
{['part','image'].includes(method) && <label className="size-field">{t.size}<input disabled={busy} type="number" min="2" step="0.25" value={size} onChange={e => setSize(e.target.value)}/></label>}
{['part','reinstall'].includes(method) && <label className="checkbox-label"><input disabled={busy} type="checkbox" checked={grow} onChange={e => setGrow(e.target.checked)}/><div>{t.grow}<small>{t.growHelp}</small></div></label>}
</section>}
@@ -351,7 +358,9 @@ function App() {
</>}
{view === 'plan' && tx && <><div className="eyebrow">{tx.choices.method === 'uninstall' ? t.reviewUninstall : t.review}</div><h1 tabIndex={-1}>{tx.device.model}</h1><p className="intro">{tx.package.name} · ••••{tx.device.serial.slice(-4)}</p>{tx.choices.method === 'uninstall' && impactNotice}<div className="page-scroll scroll-area"><section>{tx.choices.method === 'uninstall' && tx.plan.layout_source === 'device' && <p className="device-hint">{t.uninstallDeviceBounds}</p>}<dl className="plan-list"><div><dt>{tx.choices.method === 'uninstall' ? t.operationMethod : t.installMethod}</dt><dd>{tx.choices.method === 'boot' ? t.boot : tx.choices.method === 'update' ? t.update : (t as unknown as Record<string,string>)[tx.choices.method]}</dd></div><div><dt>{tx.choices.method === 'uninstall' ? t.uninstallTarget : t.target}</dt><dd>{tx.plan.target}</dd></div><div><dt>{tx.choices.method === 'uninstall' ? t.androidAllocation : t.android}</dt><dd>{tx.choices.method === 'uninstall' && <>{gib(tx.plan.previous_android_bytes)} → </>}{gib(tx.plan.android_bytes)}</dd></div><div><dt>{tx.choices.method === 'uninstall' ? t.release : t.allocation}</dt><dd>{tx.choices.method === 'boot' ? '—' : gib(tx.plan.openwrt_bytes)}</dd></div>{tx.choices.method === 'uninstall' ? <><div><dt>{t.reclaim}</dt><dd>{gib(tx.plan.reclaimed_bytes)}</dd></div>{!!tx.plan.released_unallocated_bytes && <div><dt>{t.unallocatedRelease}</dt><dd>{gib(tx.plan.released_unallocated_bytes)}</dd></div>}</> : <div><dt>{t.grow}</dt><dd>{tx.plan.grow ? <Check size={17}/> : '—'}</dd></div>}</dl></section>
{tx.choices.method !== 'uninstall' && impactNotice}
{(tx.plan.offline || tx.plan.two_stage) && <div className="alert"><RefreshCw size={20}/><p>{tx.choices.method === 'uninstall' ? t.uninstallFirstBoot : t.firstBoot}</p></div>}
{tx.plan.shrink_strategy === 'online-f2fs' && <div className="alert"><ShieldCheck size={20}/><div><strong>{t.onlineTitle}</strong><p>{t.onlineDesc}</p></div></div>}
{tx.plan.online_unavailable && <div className="alert danger"><CircleAlert size={20}/><p>{t.onlineUnavailable} {tx.plan.online_unavailable}</p></div>}
{tx.plan.shrink_strategy !== 'online-f2fs' && (tx.plan.offline || tx.plan.two_stage) && <div className="alert"><RefreshCw size={20}/><p>{tx.choices.method === 'uninstall' ? t.uninstallFirstBoot : t.firstBoot}</p></div>}
</div><label className="checkbox-label confirmation"><input disabled={busy} type="checkbox" checked={accepted} onChange={e => setAccepted(e.target.checked)}/>{tx.choices.method === 'uninstall' ? t.uninstallAccept : t.accept}</label>
<div className="actions"><Button disabled={busy} variant="outline" onClick={() => {setView(planOrigin); setAccepted(false);}}>{t.back}</Button><Button variant={tx.plan.wipe || tx.choices.method === 'uninstall' ? 'destructive' : 'default'} disabled={!accepted || busy} onClick={() => start('start')}>{tx.choices.method === 'uninstall' ? t.startUninstall : t.start}<ArrowRight size={16}/></Button></div>
</>}
@@ -373,7 +382,8 @@ function App() {
{tx.error && <div className="alert danger"><CircleAlert size={20}/><div><p className="error-message">{tx.error.message}</p><Button className="copy-diagnostics" variant="outline" disabled={busy} onClick={copyDiagnostics}><Copy size={15}/>{t.copyDiagnostics}</Button></div></div>}
</section>}</>} </div>
{waitingForOpenwrt && <div className="verification-controls"><div className="form-grid"><label>{t.host}<input disabled={busy} value={host} onChange={e => setHost(e.target.value)} autoComplete="off"/></label><label>{t.password}<input disabled={busy} type="password" value={password} onChange={e => setPassword(e.target.value)} autoComplete="off"/></label></div>{tx.choices.method !== 'uninstall' && <p className="device-hint login-hint">{['update','boot'].includes(tx.choices.method) ? t.existingLogin : t.defaultLogin}</p>}{tx.details?.verification_error && <p className="verification-error" role="status">{tx.details.verification_error}</p>}</div>}
{tx.status !== 'completed' && <div className="actions">{waitingForOpenwrt && <Button disabled={busy || !host.trim()} onClick={() => task(async () => (await request<{accepted:boolean}>('verify_openwrt', {transaction:tx.id, host:host.trim(), password})).accepted, t.verificationRequested)}><CheckCircle2 size={16}/>{t.confirmOpenwrt}</Button>}{active ? <Button variant="outline" disabled={busy} onClick={() => task(async () => (await request<{accepted:boolean}>('cancel')).accepted, t.pauseRequested)}><Pause size={16}/>{t.pause}</Button> : <Button disabled={busy || tx.error?.retryable === false} onClick={() => start('retry')}>{t.retry}<RotateCcw size={16}/></Button>}</div>
{waitingOnline && <Button variant="outline" onClick={() => {setOnlineDismissed(false);setOnlineInput('');}}>{t.onlineFallbackTitle}</Button>}
{tx.status !== 'completed' && !waitingOnline && <div className="actions">{waitingForOpenwrt && <Button disabled={busy || !host.trim()} onClick={() => task(async () => (await request<{accepted:boolean}>('verify_openwrt', {transaction:tx.id, host:host.trim(), password})).accepted, t.verificationRequested)}><CheckCircle2 size={16}/>{t.confirmOpenwrt}</Button>}{active ? <Button variant="outline" disabled={busy} onClick={() => task(async () => (await request<{accepted:boolean}>('cancel')).accepted, t.pauseRequested)}><Pause size={16}/>{t.pause}</Button> : <Button disabled={busy || tx.error?.retryable === false} onClick={() => start('retry')}>{t.retry}<RotateCcw size={16}/></Button>}</div>
}
<div className="backup-actions"><Button disabled={busy} variant="outline" onClick={exportBackup}><Download size={16}/>{t.exportBackup}</Button><Button disabled={busy} variant="ghost" onClick={openData}><FolderOpen size={16}/>{t.openData}</Button></div>
</>}
@@ -384,6 +394,16 @@ function App() {
</main></div><footer><span><ShieldCheck size={13}/>OpenWrt Installer · v1.0</span><span>USB / SSH · {pkg?.profile || '—'}</span></footer>
<Suspense fallback={<div className="help-loading" role="status"><LoaderCircle size={17} className="spin"/>{t.running}</div>}>{helpOpen && <HelpCenter language={lang} open={helpOpen} onOpenChange={setHelpOpen} initialTopic={helpTopic} onGuide={showGuide}/>}
{guideOpen && <GettingStarted language={lang} open={guideOpen} onOpenChange={changeGuide}/>}</Suspense>
{waitingOnline && !onlineDismissed && <Dialog open onOpenChange={open => {if (!open) {setOnlineDismissed(true);setOnlineInput('');}}}>
<DialogContent closeLabel={t.onlineCancel}>
<div className="dialog-heading"><DialogTitle>{t.onlineFallbackTitle}</DialogTitle><DialogDescription>{t.onlineFallbackDesc}</DialogDescription></div>
<div className="scroll-area"><p className="error-message">{tx?.online_fallback?.reason}</p><label>yes<input value={onlineInput} onChange={e => setOnlineInput(e.target.value)} autoComplete="off" spellCheck={false} placeholder="yes"/></label></div>
<div className="dialog-footer"><Button variant="outline" onClick={() => {setOnlineDismissed(true);setOnlineInput('');}}>{t.onlineCancel}</Button><Button variant="destructive" disabled={busy || onlineInput !== 'yes'} onClick={() => void task(async () => {
const next = await request<Transaction>('online_fallback',{transaction:tx!.id,nonce:tx!.online_fallback!.nonce,confirmation:onlineInput});
acceptTransaction(next);setAccepted(false);setView('plan');setOnlineInput('');
})}>{t.onlineFallbackAction}</Button></div>
</DialogContent>
</Dialog>}
{resetPrompt && <Dialog open onOpenChange={open => {if (!open && !busy) setResetPrompt(undefined);}}>
<DialogContent closeLabel={help.close} className="removal-reset-dialog">
<div className="dialog-heading"><DialogTitle>{t.uninstallResetQuestion}</DialogTitle><DialogDescription>{resetPrompt.model} · ••••{resetPrompt.serial_hint}</DialogDescription></div>
+3 -2
View File
@@ -6,7 +6,8 @@ export interface Package {path: string; name: string; adapter: string; profile:
export interface ResetPrompt {confirmation_required: 'format_android'; reason: string; reset_token: string; model: string; serial_hint: string}
export interface Transaction {
id: string; status: string; stage: string; device: Device; package: Package;
choices: {method: string; host?: string}; plan: {wipe: boolean; data_action?: string; preservation_error?: string; layout_source?: 'original_record' | 'device'; released_unallocated_bytes?: number; two_stage: boolean; offline?: boolean; openwrt_bytes: number; android_bytes?: number; previous_android_bytes?: number; reclaimed_bytes?: number; target: string; grow?: boolean; experimental?: boolean; gap_start?: number};
choices: {method: string; host?: string}; plan: {wipe: boolean; data_action?: string; preservation_error?: string; layout_source?: 'original_record' | 'device'; released_unallocated_bytes?: number; shrink_strategy?: string; online_unavailable?: string; two_stage: boolean; offline?: boolean; openwrt_bytes: number; android_bytes?: number; previous_android_bytes?: number; reclaimed_bytes?: number; target: string; grow?: boolean; experimental?: boolean; gap_start?: number};
online_fallback?: {state:'awaiting'|'confirmed'; nonce:string; reason:string};
uninstall_armed?: boolean; completed: string[]; unsafe: boolean; updated: number; revision?: number;
stage_started_at?: number; stage_finished_at?: number;
details?: {host?: string; tool?: string; reboot_manually?: boolean; boot_confirmed?: boolean; verification_error?: string; connection_state?: string}; error?: {message: string; retryable: boolean; code: string};
@@ -20,7 +21,7 @@ export const native = <T = string | null>(command: string, args?: Record<string,
export const gib = (bytes = 0) => (bytes / 1073741824).toFixed(2) + ' GiB';
export function stateGroup(stage: string): number {
if (['plan', 'package', 'device', 'environment'].includes(stage)) return 0;
if (['backup', 'prepare','uninstall_prepare','firmware_extract','firmware_convert'].includes(stage)) return 1;
if (['online_shrink', 'online_fallback', 'backup', 'prepare','uninstall_prepare','firmware_extract','firmware_convert'].includes(stage)) return 1;
if (['uninstall_offline','android_boot', 'android_setup', 'usb_debugging', 'debug_authorization', 'magisk', 'root_permission', 'root_ready', 'recheck'].includes(stage)) return 2;
if (['transfer_install', 'verify_capacity', 'verify_android', 'uninstall_restore_boot', 'openwrt_boot'].includes(stage)) return 3;
return 4;
+25
View File
@@ -0,0 +1,25 @@
{
"date": "2026-10-29",
"scope": "source, native helper and browser; no additional device shrink",
"native_helper_sha256": "357f4907cc35b2b67f14410a3cfbbad04d62dc3f59c08f711f09f8514993496d",
"covered": [
"eMMC 512 and UFS 4096 GPT",
"A/B free-space resume",
"kernel reject and explicit wipe fallback",
"ADB loss after fork",
"known mixed GPT recovery",
"cancel deferred until sealed GPT",
"commit in a later Android boot",
"zh/en fallback dialog and fresh confirmation"
],
"hardware": "Changxing60 64GiB preserve-data shrink was previously validated. This implementation only ran read-only inspect; detached worker install/power-loss acceptance not performed.",
"release": "EXE/App and full firmware packages have not been rebuilt for this change.",
"unit_regression": {
"run": 368,
"skipped": 74,
"failed": 0
},
"focused_online_tests": 16,
"slot_resume_tests": "E5-specific",
"browser": "zh/en online strategy and explicit erase fallback passed; MU300 complete 12-suite browser regression passed; E5 existing 11 suites and new suite passed"
}
+18
View File
@@ -52,5 +52,23 @@
"exit": 0,
"output": "Wireless ADB smoke passed: retry, Enter connect without package, explicit multi-device target, exact disconnect, USB protection, authorization/offline, bound Android resume and unsafe-stage exclusion, bilingual 800x650 layout; no real device access\r\n",
"error": ""
},
{
"test": "uninstall_smoke",
"exit": 0,
"output": "PASS: reset consent/cancel, original-record and device-evidence plans, preservation/release/reset impacts, bilingual UI, Android completion, bounded layout; simulated backend only\r\n",
"error": ""
},
{
"test": "mtp_smoke",
"exit": 0,
"output": "MTP toast: Chinese/English success/warning, one notification, no confirmation dialog\r\n",
"error": ""
},
{
"test": "online_shrink_smoke",
"exit": 0,
"output": "PASS: zh/en, small viewport, default online, explicit format, cancel, nonce/yes and new-plan confirmation\r\n",
"error": ""
}
]
+1 -1
View File
@@ -160,7 +160,7 @@ apk_retry() {
done
}
apk_retry update >/dev/null
# openssl-util: mu300-vpn fetches the VPN server certificate with it to pin, for links that ask for allowInsecure;
# openssl-util: general TLS certificate inspection and maintenance tools;
# i2c-tools, gpiod-tools: mu300-usb (the charger of the U30 Air) and mu300-nfc (its NFC tag)
apk_retry add --allow-untrusted /in/wifi-sae/*.apk >/dev/null
# The cipher capability helper needs the section omitted by reduced iw builds.
@@ -857,6 +857,7 @@ var DASH_I18N = {
'锁定': ['Lock', 'Kilitle'],
'已运行': ['Uptime', 'Çalışma süresi'],
'无线电已关': ['Radio off', 'Radyo kapalı'],
'未插卡': ['No SIM card', 'SIM kart takılı değil'],
'未驻留小区': ['No serving cell', 'Bağlı olunan hücre yok'],
'无应答': ['No response', 'Yanıt yok'],
'信号': ['Signal', 'Sinyal'],
@@ -446,10 +446,21 @@ return view.extend({
/* A newer successful read supersedes the slow tier's old failure. */
delete c.error;
}
var viewedSlot = Number(c && c.card != null ? c.card : M.selectedSlot());
var sim = i.modem && i.modem.sims && i.modem.sims[viewedSlot];
var absent = !!(sim && sim.state === 'absent' && Number(sim.slot) === viewedSlot);
// SIM removal clears subscription/network data, while equipment identity
// and the real RF readback remain meaningful without a card.
if (absent) {
var equipment = c && c.ident;
c = { card: sim.slot, cfun: c && c.cfun, ident: equipment ? {
imei: equipment.imei, mfg: equipment.mfg, model: equipment.model, fw: equipment.fw
} : null };
}
this.lastCell = c;
/* 慢档数据(邻区/运营商/身份)只在整份缓存的时间戳变化时重绘 */
var fullTs = [c && c.card, st.cell && st.cell.ts, st.cell && st.cell.partial || 0,
st.cell && st.cell.neigh_pending || 0, c && c.error || ''].join(':');
st.cell && st.cell.neigh_pending || 0, c && c.error || '', absent ? 'absent' : ''].join(':');
var slowChanged = fullTs !== this.lastFullTs;
this.lastFullTs = fullTs;
@@ -465,8 +476,8 @@ return view.extend({
var label = M.qLabel(rsrp, rsrq, sinr), score = M.qScore({ rsrp: rsrp, rsrq: rsrq, sinr: sinr });
var col = M.qCol(label);
var rat = '--';
if (c && !c.error) {
var rat = absent ? '未插卡' : '--';
if (!absent && c && !c.error) {
var nr = c.nr && c.nr.band ? true : false;
var lte = c.lte && c.lte.band ? true : false;
if (nr && lte) rat = '5G NSA';
@@ -530,7 +541,7 @@ return view.extend({
M.set('apn', w.apn || '--');
M.set('sess', w.uptime ? M.fmtUptime(w.uptime) : '--');
var regmap = { 0: '未注册', 1: '已注册', 2: '搜索中', 3: '注册被拒', 4: '未知', 5: '已注册(漫游)', 7: '仅紧急', 8: '仅紧急', 10: '已注册' };
var reg = '--';
var reg = absent ? '未插卡' : '--';
if (c && c.reg) {
reg = regmap[c.reg.stat] || ('状态 ' + c.reg.stat);
if (c.reg.tac) reg += ' · TAC ' + c.reg.tac;
@@ -100,7 +100,7 @@ m_act() {
case "$arg" in on) enabled=1;; off) enabled=0;; *) printf '{"ok":0,"error":"Invalid radio request"}\n'; return;; esac
"$DASH/data-sim" start "radio-${MU300_SIM_SLOT:-0}-$enabled"
;;
modem-reset|reboot|poweroff|vpn)
modem-reset|reboot|poweroff)
setsid "$DASH/action" "$op" "$arg" >/dev/null 2>&1 &
printf '{"ok":1,"started":1,"op":"%s"}\n' "$op$arg"
;;
@@ -4,7 +4,6 @@
# mu300-dash-act data up|down netifd wan interface up/down (no AT in-band)
# mu300-dash-act wifi on|off uci wireless disabled flag + wifi up/down
# mu300-dash-act modem-reset the SFUN 5/3/2/4 sequence mobile-data uses for sim-reset
# mu300-dash-act vpn start|stop /etc/init.d/mu300-vpn
# mu300-dash-act reboot|poweroff orderly restart/shutdown, after a 3 s grace for the HTTP reply
#
# Every op prints one JSON line on stdout. The rpcd backend (/usr/libexec/rpcd/mu300dash)
@@ -53,14 +52,6 @@ case "${1:-}:${2:-}" in
fi
ok "modem-reset"
;;
vpn:start|vpn:stop)
if [ -x /etc/init.d/mu300-vpn ]; then
/etc/init.d/mu300-vpn "$2" >/dev/null 2>&1
ok "vpn $2"
else
fail "vpn $2" "VPN integration is not provided by this platform"
fi
;;
reboot:|poweroff:)
sleep 3 # the reply has to make it out first
"$1" # procd stops services and unmounts normally; never force
@@ -95,7 +86,7 @@ case "${1:-}:${2:-}" in
fi
;;
*)
echo "usage: $0 radio on|off | data up|down | wifi on|off | modem-reset | vpn start|stop | reboot | poweroff | os android" >&2
echo "usage: $0 radio on|off | data up|down | wifi on|off | modem-reset | reboot | poweroff | os android" >&2
printf '{"ok":0,"error":"unknown op"}\n'
exit 2
;;
@@ -608,7 +608,8 @@ device_info_sms() {
printf '%s%s' "$_model" "${nickname:+ ($nickname)}"
}
sms_units() {
printf '%s' "$1" | LC_ALL=C awk '
# The added terminator lets NR>1 count every original LF, including tails.
printf '%s\n' "$1" | LC_ALL=C awk '
BEGIN { for (i=1; i<256; i++) ord[sprintf("%c",i)]=i; count=0 }
NR>1 { count++ }
{
@@ -817,7 +818,11 @@ process_sms() {
_scts=$(msg_field "$_file" scts)
_source=$(msg_field "$_file" source)
_coding=$(msg_field "$_file" coding)
_body=$(msg_body "$_file")
# Command substitution strips all trailing LF. Protect them with a
# sentinel, then remove only store_msg's single file terminator.
_body=$(msg_body "$_file"; printf '.')
_body=${_body%.}
_body=${_body%"$NL"}
last_id=$_id
save_state || { write_result storage_failed "$power_last_result"; return 1; }
_processed=$((_processed + 1))
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff. Show more