feat: add desktop deployment and isolate F50/V50 profiles

Add desktop installation, resume and update flows while retaining the Magisk TF entry point and one shared rootfs payload. Adapt V50 LEDs, dual SIM, CPU and NFC behavior and isolate hardware profiles. Add default boot notices and eMMC suspend and write compatibility fixes with runtime power management preserved.
This commit is contained in:
kanoqwq committed 2026-10-14 17:39:21 +08:00
1 parent 3cbf37fcd8
commit f6b0668d2e
80 files changed
+5073 -89

No files matched your search

+13
View File
@@ -1,5 +1,9 @@
# Linux on the ZTE F50 / MU300 and U30 Air
V50/MU3351 desktop-installer support and the new LED driver are documented in
[the V50 adaptation record](docs/V50-MU3351-20261014.zh-CN.md), including what has
been checked on hardware and what remains unverified.
[![Latest Release](https://img.shields.io/github/v/release/dikeckaan/mu300-linux?logo=github)](https://github.com/dikeckaan/mu300-linux/releases/latest)
[![Total Downloads](https://img.shields.io/github/downloads/dikeckaan/mu300-linux/total?color=blue&logo=github)](https://github.com/dikeckaan/mu300-linux/releases)
[![Stars](https://img.shields.io/github/stars/dikeckaan/mu300-linux?logo=github)](https://github.com/dikeckaan/mu300-linux/stargazers)
@@ -13,6 +17,15 @@ to it at any time.
Think of it as a Raspberry Pi that already has a 5G modem, a Wi-Fi access point and 32 GB of storage inside.
OpenWrt TF ZIPs can also be extracted and used with the [desktop installer](desktop/README.md):
TF deployment, userdata images, independent internal partitions and SSH updates.
The original Magisk TF installation remains unchanged.
Desktop independent-partition installation checks GPT free ranges first. If the
chosen size fits, it adds `mu300root` there and preserves Android userdata,
including encrypted userdata. Only insufficient contiguous space requires a
userdata shrink/reset. This desktop path writes a new GPT entry; the legacy
raw-region installation described below leaves GPT unchanged on 64 GB devices.
The **ZTE U30 Air** is supported too: the same board and chip with a battery. The installer recognises which one it
is talking to; see [Supported devices](#supported-devices).
@@ -52,8 +52,10 @@ bc_setup() {
command -v getprop >/dev/null 2>&1 || { bc_refuse "this is not Android: the boot chain is only ever copied from Android"; return 1; }
_m="$(getprop ro.product.model) / $(getprop ro.product.device)"
case $_m in
'V50 / MU3351')
[ "$(getprop ro.board.platform)" = ums9620 ] || { bc_refuse 'V50 is not the UMS9620 platform'; return 1; } ;;
*U30Air*|*U30_Air*|*"U30 Air"*|*MU300*|*F50*|*mu300*) ;;
*) bc_refuse "this is not a ZTE F50/MU300 or U30 Air ($_m)"; return 1 ;;
*) bc_refuse "this is not a ZTE F50/MU300, V50/MU3351 or U30 Air ($_m)"; return 1 ;;
esac
case $(getprop ro.boot.slot_suffix) in
_a) BC_A=a; BC_L=b ;;
+2 -2
View File
@@ -125,8 +125,8 @@ def main():
help='modules built for another device of this family (u30air=out/u30air): they go to '
'linux-modules/NAME/ with boot/module-order-NAME.txt, and init loads them in place of the '
'ones of the same name when it runs on that device')
ap.add_argument('--device', help='the device this image is for (f50, u30air): written to /etc/mu300-device, '
'which init trusts over its own guess from the device tree')
ap.add_argument('--device', choices=['f50', 'v50', 'u30air'],
help='fallback board identity in /etc/mu300-device; the live device tree takes priority')
ap.add_argument('--root-target', choices=['sd'],
help='TF-only device segment: never probe an internal eMMC root when TF fails')
ap.add_argument('--trial-guard', type=int, metavar='SECONDS',
+10 -6
View File
@@ -87,14 +87,18 @@ echo 1 > /proc/sys/kernel/sysrq
# Which device this is. The ZTE U30 Air is the F50's board with a battery: ZTE's SQC charger stack, USB-PD, LEDs.
# It runs the same kernel with its own build of a few modules (linux-modules/u30air/, see kernel/build-u30air.sh)
# and its own load order; without them the charger manager never probes and USB stays down. The installer names
# the device in /etc/mu300-device (the device segment of the ramdisk, which the generic segment of an update does
# not replace); without that file the stock device tree tells: only the U30 Air's has the charger policy service.
if [ -s /etc/mu300-device ]; then
DEVICE=$(cat /etc/mu300-device)
elif [ -d /proc/device-tree/charger_policy_service ]; then
# the device in /etc/mu300-device. Hardware takes priority: an old installation
# may have labelled a V50 as f50, and updates retain that device ramdisk segment.
if [ -d /proc/device-tree/charger_policy_service ]; then
DEVICE=u30air
else
elif [ -d /proc/device-tree/soc/soc:ap-ahb/i2c@2270000/aw9523b_led@5b ] ||
[ -d /proc/device-tree/soc/ap-ahb/i2c@2270000/aw9523b_led@5b ]; then
DEVICE=v50
elif [ -d /proc/device-tree ]; then
DEVICE=f50
else
DEVICE=$(cat /etc/mu300-device 2>/dev/null)
case $DEVICE in f50|v50|u30air) ;; *) DEVICE=f50 ;; esac
fi
# its modules only for the kernel they were built for (a mainline kernel brings its own set and order)
MODULE_ORDER=/etc/module-order
+10
View File
@@ -0,0 +1,10 @@
{
"source": "e5-linux installer, 2026-10-13 working tree",
"files": {
"boot/install-part.sh": "0a486b69469561ef456a6459faf2e99f4d6233361a380bf3eeb39f612f6c279e",
"boot/part-prepare.sh": "d2df4e25b2a98032bbb5733a25f2931cfabba2115c33bea86649d7b213f7d0fe",
"boot/part-progress.sh": "a6d6a3651f79240119b07a0c3174d402b41c1031daa1617ebd2bcf6bff85955b",
"openwrt/overlay/usr/libexec/e5-gpt": "dda63db567e5916b8772cc5e8fb93e1f1255f229f1702a22118ded9c25d97880"
},
"adaptation": "MU300 container layout, dynamic slots, separate desktop initramfs only"
}
+155
View File
@@ -0,0 +1,155 @@
# MU300 desktop deployment
The same ZIP has two entry points. Installing it in Magisk runs the original
TF deployment script through a small path wrapper. Extracting it on a computer
exposes the desktop installer. The deployment steps are unchanged.
Desktop code is not added to the original Magisk TF boot image.
The ZIP contains only one `payload/mu300-openwrt.tar.gz`. Desktop internal installation
and SSH updates prepare a temporary filtered archive on the computer, excluding
the build machine's proprietary firmware and Android runtime. It is removed
after upload, including when upload fails. TF deployment uses the original
archive directly.
Only `OpenWrt-Installer.exe`, `OpenWrt-Installer.py`, `module.prop` and the
Magisk `customize.sh` entry are top-level files. Original deployment files live
in `payload/`, shortcut scripts in `launchers/`, instructions in `docs/`, and
desktop helpers and ADB in `desktop/` and `tools/`.
| Launcher (.cmd for Windows, .sh for Linux/macOS) | Action |
| --- | --- |
| 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 | Plaintext userdata image with configurable GiB size |
| install-to-internal-storage | Independent `mu300root`; use unallocated eMMC 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 | Select installed Linux without automatic reboot |
| update-openwrt | SSH upload, preserve settings/capacity, then reboot |
Windows uses `OpenWrt-Installer.exe` when included. Otherwise install Python
3.10+ and `pip install paramiko lz4`. Install Android platform-tools and put adb
on PATH, or pass `--adb PATH`. Unix launchers use Python and system adb.
Builders can include Windows platform-tools by setting
`MU300_DESKTOP_ADB_DIR` to a directory containing adb.exe and its two API DLLs.
English filenames are used throughout. Prompts include English and Chinese.
Use `--serial SERIAL` when more than one Android is online.
At the end, the installer shows a final success, failure, cancellation or
next-step status with elapsed time and the next action. Interactive runs wait
for Enter before exiting. A prepared offline-install stage is explicitly
marked as needing another step. `--no-pause` skips the wait for automation;
`--pause` forces it even with redirected input. Windows CMD shortcuts provide
one closing prompt of their own, without a second installer pause.
V50 is accepted only as the exact `V50` / `MU3351` product on `ums9620`.
It shares the F50 kernel family and LAN address; its AW9523B LED controller
needs a kernel built with `CONFIG_LEDS_AW9523B=y`. Historical preview images
without that driver do not provide V50 lighting. Always extract this device's
own firmware. Its tested Android uses FBE. If GPT has enough unused space,
installation preserves encrypted Android data; otherwise it uses reset/resume.
`OpenWrt-Installer.py --check` verifies package files without accessing hardware.
`--check-boot` additionally builds trial desktop boots on the computer to check
the repacker, boot-size limit and unchanged kernel, also without device access.
`--check-rootfs` tests temporary archive preparation without accessing a device.
`--check-resume` checks a connected Android and saved transaction without
uploading payloads or writing the device. Repair packages can resume older
transactions when the boot, rootfs and filesystem tool checksums match. Device,
slot, partition geometry and the on-device token must still match. New records
also save a `package-manifest.json` beside `transaction.json` for portability.
`--probe --serial SERIAL` checks the connected Android's model, encryption,
storage and binary DTB/A/B reads without staging files or writing partitions.
`--size 10` selects 10 GiB. `--host 192.168.78.1` selects U30Air for updates.
The installer never changes the computer's network or firewall settings.
Hotspot keys use visible input. Android image mounting resolves BusyBox's
`/dev/loopN` to Android's real `/dev/block/loopN` before attachment. Reboot
requests use the ADB reboot service rather than waiting for a disconnecting
root shell to return an exit status.
## Storage and encryption
The desktop installer validates both GPT headers and tables against physical
capacity, then measures contiguous, 1 MiB aligned unallocated ranges. These are
different from free space inside `/data`. When a range fits the chosen size,
it installs there without shrinking, formatting or resetting Android, including
FBE/FDE devices. GPT changes, userdata changes and encryption are separate decisions.
`--probe` reports physical capacity and usable GPT gaps without writes.
Free-space installation backs up GPT and both-slot boot-chain files first.
It writes a verified device-specific image through a bounded raw loop, grows
ext4 to the full chosen capacity, checks filesystem and file hashes, then commits
the new GPT entry and verifies both copies. Existing entries and userdata stay
unchanged. Only after these checks does it write the opposite boot and select
OpenWrt. Android is not asked to reread its mounted disk's partition table;
the new partition node appears after reboot. Android Toybox's bounded losetup
is required; BusyBox's unbounded version cannot be substituted.
Detected legacy raw ext4/F2FS systems at known MU300 offsets or gap starts are
excluded from allocation. Unallocated does not guarantee all bytes are empty:
the confirmation warns that the selected raw range is overwritten. Invalid or
disagreeing GPT copies stop installation; the installer does not silently move
the backup GPT or widen its usable bounds. An existing `mu300root` still requires
the reinstall/update action. `--format-userdata` is rejected for a free-gap install.
Only when no suitable gap fits the selected size is userdata shrink considered.
Plaintext F2FS/ext4 uses the preserving workflow: verify a complete image with
this device's runtime, stage it, boot a desktop-only initramfs, check and shrink
the unmounted filesystem, change GPT, write/read back the root, and expand ext4
to the full partition. The initial 2 GiB image is not the installed capacity.
Offline operations print a two-second stage/elapsed heartbeat; copying also
reports bytes. Progress is exposed during that boot at
`http://192.168.77.1:8089/progress.txt` (U30Air: `192.168.78.1`).
USB networking must be enabled to view it. No permanent polling service is added.
FBE/FDE or `--format-userdata` uses two stages. **Android userdata is erased.**
Stage one carries tools and a device-bound plan in the ramdisk; it never tries
to decrypt/read `/data`. It carves the root partition and asks stock Android
recovery to format the smaller userdata. Finish fresh Android setup, re-enable
USB debugging and restore/grant root, then run `resume-internal-install`.
CID, serial, Android slot, geometry and the preparation token must match before
writing the root. Firmware is extracted again from the current Android.
Resume records and pre-install GPT/misc/boot/both-slot boot-chain backups are
stored on the computer under `~/mu300-backups`. Use `--transaction FILE` to
choose a record. Unknown encryption states stop a preserving shrink.
Only the opposite boot slot and differing opposite-slot
`uboot/sml/teecfg/trustos/vbmeta` are written, with backups and readback checks.
Current Android boot and NV/calibration are not overwritten. Deleting a root
partition or blindly restoring a GPT backup is not a rollback. Arbitrary
partition editing is not offered.
## Updates
The computer initiates SSH uploads, avoiding inbound Windows firewall rules.
Known host keys are checked, with explicit trust on first use. Updating uses
MU300's native mutex, config/account preservation, user-package migration and
`openwrt.new`/`openwrt.old` swap. The old directory remains for native rollback.
Runtime firmware comes from the existing installation. A plain filesystem
view excludes live vendor device/proc mounts during copying. Root/boot checks
precede slot selection; boot failures attempt root and boot restoration.
The persistent boot log and filesystem capacity are preserved.
Use the package for the intended kernel family. Legacy raw free-region installs
continue using native `mu300-update`; desktop updating rejects that layout.
## Building
`tools/build-openwrt-tf-magisk.sh` adds desktop deployment by default.
Set `MU300_DESKTOP_TOOLS=/path/to/ARM64-musl-tool-root`; required F2FS,
e2fsprogs and ucode files are listed in `prepare-tools.py`. An ARM64 OpenWrt
root with these packages can provide them. ELF architecture and checksums are
checked. These tools go only into the desktop boot supplement.
`MU300_DESKTOP_INSTALLER=0` builds the original pure Magisk ZIP.
On Windows, install PyInstaller, paramiko and lz4, then run
`python desktop/build-exe.py`. Pass `MU300_DESKTOP_EXE=.../OpenWrt-Installer.exe`
when packaging; the adjacent source fingerprint is required and stale EXEs are
rejected. Python source is always included.
An existing Magisk staging tree can be augmented with
`python desktop/package.py --stage DIR --tools TOOL_ROOT --kernel 7.2`.
All original deployment file contents remain identical; `magisk_layout` maps
their original names to the new locations. `desktop/manifest.json` records
these hashes and every addition, including the Magisk path wrapper.
Hardware installation, especially stock-recovery reset/resume, still needs
real MU300 validation before a release. ZIPs augmented from historical packages
remain historical runtime builds; they must not be advertised as fresh firmware.
+83
View File
@@ -0,0 +1,83 @@
#!/system/bin/sh
# Desktop-only image builder. Never changes GPT, boot or misc.
set -eu
P=${MU300_PAYLOAD_DIR:?}; BB=${MU300_BUSYBOX:?}; T=${MU300_INSTALL_TMP:?}
. "$P/android-loop.sh"
. "$P/desktop-settings.env"
case "$IMAGE_MIB" in ''|*[!0-9]*) exit 1 ;; esac
[ "$IMAGE_MIB" -ge 2048 ]
[ -x /system/bin/mke2fs ] || { echo 'Android /system/bin/mke2fs is required' >&2; exit 1; }
mkdir -p /data/mu300linux "$T/image-root"
[ ! -e /data/mu300linux/part-install.conf ] || { echo 'an internal installation is already pending' >&2; exit 1; }
image=$T/openwrt.ext4.new
[ ! -e "$image" ] || { echo 'unfinished image exists; inspect it before retrying' >&2; exit 1; }
[ "$DESKTOP_MODE" != data-image ] || [ ! -e /data/mu300linux/openwrt.ext4.backup ] || { echo 'previous image backup exists; move it before reinstalling' >&2; exit 1; }
free=$(df -Pk /data | awk 'END {print $4}')
[ "$free" -gt "$((IMAGE_MIB * 1024 + 524288))" ] || { echo 'insufficient userdata staging space' >&2; exit 1; }
truncate -s "$((IMAGE_MIB * 1048576))" "$image"
/system/bin/mke2fs -t ext4 -F -b 4096 -m 1 -E lazy_itable_init=1,lazy_journal_init=1,nodiscard -L mu300root "$image"
loop=$(desktop_free_loop)
losetup "$loop" "$image"
trap 'losetup -d "$loop" 2>/dev/null || :' EXIT
mount -t ext4 "$loop" "$T/image-root"
trap 'umount "$T/image-root" 2>/dev/null || :; losetup -d "$loop" 2>/dev/null || :' EXIT
M=$T/image-root; R=$M/openwrt
mkdir -p "$R"
tar -xzpf "$P/mu300-openwrt.tar.gz" -C "$R"
(cd "$R" && sha256sum -c "$P/rootfs-critical.sha256")
# Use this device's libraries, firmware and Android property snapshot.
rm -rf "$R/opt/mu300/android"
sh "$P/mu300-vendor-from-device.sh" "$R" openwrt
mkdir -p "$M/.mu300" "$M/boot" "$R/etc/mu300"
echo openwrt > "$M/.mu300/boot-os"; echo 5 > "$M/.mu300/boot-attempts"; echo 0 > "$M/.mu300/boot-tries"
echo "$KERNEL" > "$M/boot/kernel"; echo "$KERNEL" > "$M/boot/installed.kernel"
echo linux > "$R/etc/mu300/default-boot"
echo "$DESKTOP_MODE" > "$R/etc/mu300/desktop-mode"
if [ -z "${SSID:-}" ]; then
X=/data/misc/apexdata/com.android.wifi/WifiConfigStoreSoftAp.xml
SSID=$(sed -n 's/.*<string name="WifiSsid">&quot;\(.*\)&quot;<\/string>.*/\1/p; s/.*<string name="WifiSsid">\([^&<]*\)<\/string>.*/\1/p' "$X" 2>/dev/null | head -1)
WIFI_KEY=$(sed -n 's/.*<string name="Passphrase">\(.*\)<\/string>.*/\1/p' "$X" 2>/dev/null | head -1 | sed "s/&amp;/\&/g; s/&lt;/</g; s/&gt;/>/g; s/&quot;/\"/g; s/&apos;/'/g")
[ "${#WIFI_KEY}" -ge 8 ] || SSID=
fi
if [ -n "${SSID:-}" ]; then
printf 'SSID=%s\nPSK=%s\nBAND=5\nCHANNEL=auto\nCOUNTRY=TR\n' "$SSID" "$WIFI_KEY" > "$R/etc/mu300/hotspot.conf"
chmod 600 "$R/etc/mu300/hotspot.conf"
fi
if [ -n "${APN:-}" ]; then
# First-boot defaults are UCI, shared by LuCI, netifd and APN selection.
mkdir -p "$R/etc/uci-defaults"
printf '#!/bin/sh\nuci set network.wan.apn=%s\nuci commit network\n' "$APN" > "$R/etc/uci-defaults/99-desktop-apn"
chmod 755 "$R/etc/uci-defaults/99-desktop-apn"
fi
if [ -n "${PWHASH:-}" ]; then
sed -i "s|^root:[^:]*:|root:$PWHASH:|" "$R/etc/shadow"
rm -f "$R/etc/.mu300-accounts-from-image"
fi
[ -x "$R/sbin/init" ] || [ -L "$R/sbin/init" ]
[ -s "$R/lib/firmware/wcnmodem.bin" ] && [ -x "$R/opt/mu300/android/vendor/bin/modem_control" ]
(cd "$M" && find . -type f -exec sha256sum {} +) > "$T/image.sha256"
umount "$M"; losetup -d "$loop"; trap - EXIT
losetup -r "$loop" "$image"
trap 'losetup -d "$loop" 2>/dev/null || :' EXIT
mount -t ext4 -o ro,noload "$loop" "$M"
trap 'umount "$M" 2>/dev/null || :; losetup -d "$loop" 2>/dev/null || :' EXIT
(cd "$M" && sha256sum -c "$T/image.sha256" >/dev/null)
umount "$M"; losetup -d "$loop"; trap - EXIT
if [ "$DESKTOP_MODE" = data-image ]; then
[ ! -e /data/mu300linux/openwrt.ext4 ] || mv /data/mu300linux/openwrt.ext4 /data/mu300linux/openwrt.ext4.backup
mv "$image" /data/mu300linux/openwrt.ext4
echo 'IMAGE-INSTALLED data-image'
elif [ "$DESKTOP_MODE" = part-stage ]; then
gzip -1 -c "$image" > /data/mu300linux/part-install.img.gz.tmp
gzip -t /data/mu300linux/part-install.img.gz.tmp
mv /data/mu300linux/part-install.img.gz.tmp /data/mu300linux/part-install.img.gz
rm -f "$image"
# install-part's firmware archive is metadata only: the complete device
# runtime is already inside the checked container image.
mkdir -p "$T/metadata/.mu300"
echo openwrt > "$T/metadata/.mu300/boot-os"
tar -cf /data/mu300linux/device-files.tar -C "$T/metadata" .
echo 'IMAGE-INSTALLED part-stage'
else
echo 'IMAGE-INSTALLED partition-write'
fi
+29
View File
@@ -0,0 +1,29 @@
# Android stores block nodes under /dev/block, whereas BusyBox losetup -f
# prints /dev/loopN. Source this helper before attaching an image.
desktop_loop_is_block() { [ -b "$1" ]; }
desktop_free_loop() {
local candidate name index devno major minor node
candidate=$(losetup -f) || return 1
case "$candidate" in /dev/loop[0-9]*|/dev/block/loop[0-9]*) name=${candidate##*/} ;;
*) echo 'cannot identify a free loop device' >&2; return 1 ;;
esac
index=${name#loop}
case "$index" in ''|*[!0-9]*) echo 'invalid loop index' >&2; return 1 ;; esac
if desktop_loop_is_block "/dev/block/$name"; then
echo "/dev/block/$name"
elif desktop_loop_is_block "$candidate"; then
echo "$candidate"
else
# ueventd may not have created a newly allocated loop node yet. Keep
# our fallback in private staging rather than altering global /dev.
devno=$(cat "/sys/class/block/$name/dev") || return 1
major=${devno%:*}; minor=${devno#*:}
case "$major:$minor" in *[!0-9:]*|:*) return 1 ;; esac
[ "$major" = 7 ] && [ "$minor" = "$((index * 8))" ] || return 1
node=${MU300_INSTALL_TMP:?}/$name
[ ! -e "$node" ] || { echo "loop staging node already exists: $node" >&2; return 1; }
mknod "$node" b "$major" "$minor" || return 1
desktop_loop_is_block "$node" || return 1
echo "$node"
fi
}
+80
View File
@@ -0,0 +1,80 @@
#!/system/bin/sh
# Desktop has validated both GPT copies and selected an unallocated range.
# Android keeps userdata mounted; never request BLKRRPART on its parent disk.
set -eu
set -o pipefail
P=${MU300_PAYLOAD_DIR:?};T=${MU300_INSTALL_TMP:?}
. "$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.
[ -x /system/bin/losetup ] && /system/bin/losetup --help 2>&1 | grep -q -- '-S' || {
echo 'Android losetup with -S (bounded loop) is required; nothing written' >&2; exit 1;
}
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; }
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" ]
[ "$(cat /sys/class/block/$node/size)" = "$total" ]
[ "$front" -ge 3 ] && [ "$front" -le 4096 ]
[ "$tail" -ge "$((total-4096))" ] && [ "$tail" -lt "$total" ]
[ "$start" -ge "$front" ] && [ "$need" -ge 4194304 ]
[ "$((start%2048))" = 0 ] && [ "$((need%2048))" = 0 ]
[ "$((start+need))" -le "$tail" ]
for region in before new; do
[ "$(stat -c %s "$P/gpt-$region-first.bin")" = "$((front*512))" ]
[ "$(stat -c %s "$P/gpt-$region-last.bin")" = "$(((total-tail)*512))" ]
done
check_gpt() {
dd if="$disk" of="$T/gpt-check-first.bin" bs=512 count="$front" 2>/dev/null
dd if="$disk" of="$T/gpt-check-last.bin" bs=512 skip="$tail" count="$((total-tail))" 2>/dev/null
cmp -s "$P/gpt-$1-first.bin" "$T/gpt-check-first.bin" &&
cmp -s "$P/gpt-$1-last.bin" "$T/gpt-check-last.bin"
}
check_gpt before || { echo 'GPT changed; no free-space write performed' >&2; exit 1; }
image=$T/openwrt.ext4.new
[ "$(sha256sum "$image" | cut -d' ' -f1)" = "$want" ]
bytes=$(stat -c %s "$image")
[ "$bytes" -gt 0 ] && [ "$bytes" -le "$((need*512))" ] && [ "$((bytes%1048576))" = 0 ]
loop=$(desktop_free_loop)
cleanup() { umount "$T/image-root" 2>/dev/null || :; losetup -d "$loop" 2>/dev/null || :; }
trap cleanup EXIT
/system/bin/losetup -o "$((start*512))" -S "$((need*512))" "$loop" "$disk"
# Confirm the kernel actually honored the hard range bound before any write.
name=${loop##*/}
[ "$(cat /sys/class/block/$name/loop/offset)" = "$((start*512))" ]
[ "$(cat /sys/class/block/$name/loop/sizelimit)" = "$((need*512))" ]
[ "$(blockdev --getsize64 "$loop")" = "$((need*512))" ]
echo 'Writing verified image into unallocated space / 写入未分配空间'
dd if="$image" of="$loop" bs=1048576 conv=fsync
got=$(dd if="$loop" bs=1048576 count="$((bytes/1048576))" | sha256sum | cut -d' ' -f1)
[ "$got" = "$want" ]
repair=$P/desktop/files/boot/repair
# Explicit noninteractive flags: no failed repair may proceed to GPT commit.
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/e2fsck" -pf "$loop" || {
rc=$?; [ "$rc" = 1 ] || exit "$rc";
}
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/resize2fs" -f "$loop" "$((need/8))"
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/e2fsck" -fn "$loop"
low=$(od -An -tu4 -j1028 -N4 "$loop" | tr -d ' \n');high=$(od -An -tu4 -j1360 -N4 "$loop" | tr -d ' \n')
[ "$high" = 0 ] && [ "$low" = "$((need/8))" ]
mount -t ext4 -o ro,noload "$loop" "$T/image-root"
(cd "$T/image-root" && sha256sum -c "$T/image.sha256" >/dev/null)
umount "$T/image-root";losetup -d "$loop";trap - EXIT
check_gpt before || { echo 'GPT changed; verified image left unallocated, boot untouched' >&2; exit 1; }
write_gpt() {
# Backup first, each write flushed; preserve all existing entries and MBR.
dd if="$P/gpt-$1-last.bin" of="$disk" bs=512 seek="$tail" conv=notrunc,fsync &&
dd if="$P/gpt-$1-first.bin" of="$disk" bs=512 conv=notrunc,fsync && check_gpt "$1"
}
if ! write_gpt new; then
echo 'GPT commit failed; restoring original table, boot unchanged' >&2
write_gpt before || echo 'GPT RESTORE FAILED: use the saved computer backup before rebooting' >&2
exit 1
fi
rm -f "$image"
echo FREE-ROOT-VERIFIED
+41
View File
@@ -0,0 +1,41 @@
#!/system/bin/sh
# Write a checked image to an EXISTING independent MU300 root only.
set -eu
set -o pipefail
P=${MU300_PAYLOAD_DIR:?};T=${MU300_INSTALL_TMP:?}
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
grep -qx PARTNAME=mu300root "/sys/class/block/$node/uevent"
[ "$(cat /sys/class/block/$disk/device/cid)" = "$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)
for m in /proc/[0-9]*/mountinfo; do
[ -r "$m" ] || continue
awk -v n="$identity" '$3==n {yes=1} END {exit !yes}' "$m" && { echo 'root partition is mounted'; exit 1; }
done
image=$T/openwrt.ext4.new
[ "$(sha256sum "$image" | cut -d' ' -f1)" = "$expected_sha" ]
size=$(stat -c %s "$image")
[ "$size" -gt 0 ] && [ "$size" -le "$((expected_sectors*512))" ]
dd if="$image" of="$dev" bs=1048576 conv=fsync
[ "$((size % 1048576))" = 0 ]
# Bounded dd exits normally; pipefail catches a short/error read without a
# second 2 GiB staging file on Android data.
actual=$(dd if="$dev" bs=1048576 count="$((size / 1048576))" | sha256sum | cut -d' ' -f1)
[ "$actual" = "$expected_sha" ]
repair=$P/desktop/files/boot/repair
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/e2fsck" -pf "$dev" || {
rc=$?; [ "$rc" = 1 ] || exit "$rc";
}
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/resize2fs" -f "$dev" "$((expected_sectors/8))"
low=$(od -An -tu4 -j1028 -N4 "$dev" | tr -d ' \n');high=$(od -An -tu4 -j1360 -N4 "$dev" | tr -d ' \n')
[ "$high" = 0 ] && [ "$low" = "$((expected_sectors/8))" ]
mount -t ext4 -o ro,noload "$dev" "$T/image-root"
trap 'umount "$T/image-root" 2>/dev/null || :' EXIT
(cd "$T/image-root" && sha256sum -c "$T/image.sha256" >/dev/null)
umount "$T/image-root"
trap - EXIT
rm -f "$image"
echo ROOT-VERIFIED
+274
View File
@@ -0,0 +1,274 @@
# The internal-partition install (flash.py --part), finished from the
# initramfs because this is the only place userdata is unmounted: the vendor
# F2FS is shrunk with raw tools only (docs/FINDINGS.md 48), the partition
# table is changed with mu300-gpt, the image written into the new partition, and
# the boot then restarts once into the new system (a partition created in
# this boot has no kernel node yet, so it cannot be started in this boot).
#
# Order is the safety property: the filesystem shrinks BEFORE the partition
# table changes, so any failure leaves a disk that Android can still mount
# (a partition larger than its filesystem is normal for Android). A failed
# run keeps /data/mu300linux/part-install.conf, and the next boot retries; the
# steps check their own outcome before continuing.
#
# Sourced by boot/init; install_part_pending DEV is called once per boot with
# userdata's device. Logs through the caller's log().
install_part_pending() {
. /etc/part-progress.sh
local dev=$1 node=${1##*/} disk=${1%p*}
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.
mkdir -p "$mp"
datafs=f2fs dataopts=ro,norecovery
if [ "$(od -An -tx2 -j 1080 -N 2 "$dev" | tr -d ' \n')" = ef53 ]; then
datafs=ext4 dataopts=ro,noload
fi
mount -t "$datafs" -o "$dataopts" "$dev" "$mp" 2>/dev/null || { part_fail 'cannot mount plaintext userdata'; return 1; }
[ -f "$mp/mu300linux/part-install.conf" ] || { umount "$mp"; part_stop; return 0; }
PART_MIB= DATA_MIB= GROW_FS= FORMAT_DATA=0
for kv in $(cat "$mp/mu300linux/part-install.conf"); do
case "$kv" in
PART_MIB=*) PART_MIB=${kv#*=} ;;
DATA_MIB=*) DATA_MIB=${kv#*=} ;;
GROW_FS=*) GROW_FS=${kv#*=} ;;
FORMAT_DATA=*) FORMAT_DATA=${kv#*=} ;;
esac
done
part_progress_start
echo "1/6 checking staged image and firmware" > /run/part-status
# Validate the staged payload before shrinking or changing GPT. A damaged
# archive must not leave a newly carved but unusable root partition.
img="$mp/mu300linux/part-install.img.gz" dft="$mp/mu300linux/device-files.tar"
if [ ! -s "$img" ] || [ ! -s "$dft" ] ||
! gzip -t "$img" || ! tar -tf "$dft" >/dev/null; then
umount "$mp"; part_fail 'missing or corrupt installation payload'; return 1
fi
raw=$(set -o pipefail; gzip -dc "$img" | wc -c) || {
umount "$mp"; part_fail 'cannot read installation image'; return 1;
}
case "$GROW_FS" in 1) ;; *) GROW_FS=0 ;; esac
umount "$mp"
[ "$FORMAT_DATA" = 0 ] || { part_fail 'format request requires two-stage installer'; return 1; }
case "${PART_MIB:-}" in ''|*[!0-9]*) part_fail 'bad partition size'; return 1 ;; esac
case "${DATA_MIB:-}" in ''|*[!0-9]*) part_fail 'bad userdata size'; return 1 ;; esac
[ "$PART_MIB" -ge 2048 ] && [ "$DATA_MIB" -ge 2048 ] ||
{ part_fail 'invalid partition/userdata sizes'; return 1; }
target=$((DATA_MIB * 2048)) need=$((PART_MIB * 2048))
[ "$raw" -gt 0 ] && [ "$raw" -le "$((need * 512))" ] || {
part_fail 'image exceeds partition'; return 1;
}
log "stage=part-install start data=$((DATA_MIB >> 10))G part=$((PART_MIB >> 10))G"
# Validate BOTH GPT copies and all planned geometry before moving filesystem
# blocks. A full GPT or impossible allocation must leave userdata untouched.
list=$(/usr/bin/ucode /usr/share/mu300-gpt list "$disk") || { part_fail 'GPT validation'; return 1; }
found=$(echo "$list" | awk '$4 == "mu300root" {print $1}')
if [ -z "$found" ]; then
/usr/bin/ucode /usr/share/mu300-gpt plan "$disk" "resize:userdata:$target" "mu300root:$need" >/run/part-plan || { part_fail 'GPT allocation plan'; return 1; }
fi
# Two-second progress survives fractional /proc/uptime and long operations.
# Everything on the console is plain ASCII: the framebuffer console font
# has no CJK. (The backlight is not touched here.)
echo "1/6 checking userdata" > /run/part-status
# Preserve plaintext ext4 and F2FS; the raw filesystem is never mounted
# during shrink. Encrypted data uses the separate recovery preparation.
if [ "$datafs" = ext4 ]; then
awk -v n="$(cat /sys/class/block/$node/dev)" '$3 == n { found = 1 } END { exit !found }' /proc/self/mountinfo && {
part_fail 'userdata still mounted'; return 1;
}
echo '2/6 checking and shrinking ext4 userdata' > /run/part-status
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib:/repair/usr/lib /repair/usr/sbin/e2fsck -pf "$dev" >/run/part-fsck.log 2>&1
rc=$?; case "$rc" in 0|1) ;; *) part_fail 'ext4 fsck'; return 1 ;; esac
shift=$(od -An -tu4 -j 1048 -N 4 "$dev" | tr -d ' \n')
case "$shift" in 0|1|2|3|4) ;; *) part_fail 'ext4 block size'; return 1 ;; esac
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib:/repair/usr/lib /repair/usr/sbin/resize2fs -f "$dev" "$((target * 512 / (1024 << shift)))" >/run/part-resize.log 2>&1 || {
part_fail 'ext4 shrink'; return 1;
}
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib:/repair/usr/lib /repair/usr/sbin/e2fsck -pf "$dev" >/run/part-shrink-check.log 2>&1
rc=$?; case "$rc" in 0|1) ;; *) part_fail 'ext4 post-shrink fsck'; return 1 ;; esac
low=$(od -An -tu4 -j 1028 -N 4 "$dev" | tr -d ' \n')
high=$(od -An -tu4 -j 1360 -N 4 "$dev" | tr -d ' \n')
[ "$high" = 0 ] && [ "$((low * (1024 << shift) / 512))" = "$target" ] || {
part_fail 'ext4 shrink size'; return 1;
}
else
# 1. the filesystem, raw and unmounted. Its own superblock, not the
# tool's chatter, decides whether the shrink landed.
[ "$(od -An -tx4 -j 1024 -N 4 "$dev" | tr -d ' \n')" = f2f52010 ] ||
{ part_fail 'userdata is not plaintext F2FS/ext4'; return 1; }
awk -v n="$(cat /sys/class/block/$node/dev)" \
'$3 == n { found = 1 } END { exit !found }' /proc/self/mountinfo &&
{ part_fail 'userdata still mounted'; return 1; }
low=$(od -An -tx4 -j 1060 -N 4 "$dev" | tr -d ' \n')
hi=$(od -An -tx4 -j 1064 -N 4 "$dev" | tr -d ' \n')
[ "$hi" = 00000000 ] || { part_fail 'unsupported filesystem size'; return 1; }
cur=$((0x$low * 8))
if [ "$cur" != "$target" ]; then
echo "2/6 shrinking userdata (fsck)" > /run/part-status
log "stage=part-install shrink cur=$((cur / 2048))MiB target=$((target / 2048))MiB"
blockdev --setrw "$dev" || { part_fail 'userdata read-only'; return 1; }
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib \
/repair/sbin/fsck.f2fs -f "$dev" >/run/part-fsck.log 2>&1
rc=$?
case "$rc" in 0|1) ;; *) part_fail "F2FS check failed rc=$rc"; return 1 ;; esac
echo "2/6 shrinking userdata (moving blocks; this can take several minutes)" > /run/part-status
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib \
/repair/sbin/resize.f2fs -s -t "$target" "$dev" \
>/run/part-resize.log 2>&1 </dev/null
rc=$?
[ "$rc" = 0 ] || { part_fail "userdata resize failed rc=$rc (see /run/part-resize.log)"; return 1; }
low=$(od -An -tx4 -j 1060 -N 4 "$dev" | tr -d ' \n')
cur=$((0x$low * 8))
[ "$cur" = "$target" ] ||
{ part_fail "F2FS shrink size mismatch: $((cur / 2048))MiB"; return 1; }
log "stage=part-install shrunk $((target / 2048))MiB"
fi
# Check also when a previous attempt already changed the block count.
# A new count alone cannot prove that all block moves/checkpoints finished.
echo "2/6 verifying shrunk userdata" > /run/part-status
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib \
/repair/sbin/fsck.f2fs -f "$dev" >/run/part-shrink-check.log 2>&1
rc=$?
case "$rc" in 0|1) ;; *) part_fail "shrunk userdata check failed rc=$rc"; return 1 ;; esac
low=$(od -An -tx4 -j 1060 -N 4 "$dev" | tr -d ' \n')
hi=$(od -An -tx4 -j 1064 -N 4 "$dev" | tr -d ' \n')
[ "$hi" = 00000000 ] && [ "$((0x$low * 8))" = "$target" ] || {
part_fail 'shrunk userdata size verification'; return 1;
}
fi
# 2. the partition table, only now. ucode is called by its absolute path
# and its own output is checked: a piped `list` once hid a ucode that
# could not start (a missing library) behind awk's exit status.
echo "3/6 creating the mu300root partition" > /run/part-status
list=$(/usr/bin/ucode /usr/share/mu300-gpt list "$disk") ||
{ part_fail 'GPT list failed'; return 1; }
found=$(echo "$list" | awk '$4 == "mu300root" { print $1 }')
if [ -z "$found" ]; then
/usr/bin/ucode /usr/share/mu300-gpt resize "$disk" userdata "$target" >/dev/null ||
{ part_fail 'GPT resize failed'; return 1; }
out=$(/usr/bin/ucode /usr/share/mu300-gpt add "$disk" mu300root "$need") ||
{ part_fail 'GPT add failed'; return 1; }
set -- $out
pstart=$2 pend=$3
log "stage=part-install partition $1 sectors $pstart-$pend"
else
set -- $(echo "$list" | awk '$4 == "mu300root" { print $1, $2, $3 }')
pstart=$2 pend=$3
log "stage=part-install partition exists $pstart-$pend"
fi
case "$pstart:$pend" in *[!0-9:]*|:*|*:) part_fail 'invalid partition geometry'; return 1 ;; esac
[ $((pstart % 2048)) = 0 ] && [ $((pend - pstart + 1)) -ge "$need" ] || { part_fail 'unaligned or short partition'; return 1; }
# 3. the image, through the whole disk at the partition's offset (the
# kernel's table for this boot predates it)
echo "4/6 writing OpenWrt into the partition" > /run/part-status
mount -t "$datafs" -o "$dataopts" "$dev" "$mp" || { part_fail 'payload remount failed'; return 1; }
img="$mp/mu300linux/part-install.img.gz" dft="$mp/mu300linux/device-files.tar"
[ -f "$img" ] || { umount "$mp"; part_fail 'staged image missing'; return 1; }
log "stage=part-install write $((pstart / 2048))MiB"
gzip -t "$img" || { umount "$mp"; part_fail 'corrupt image'; return 1; }
local producer writer write_rc unpack_rc
[ "$raw" -gt 0 ] && [ "$raw" -le "$((need * 512))" ] || { umount "$mp"; part_fail 'image exceeds partition'; return 1; }
dd if=/dev/zero of="$disk" bs=1048576 seek=$((pstart / 2048)) count=4 conv=fsync 2>/dev/null ||
{ umount "$mp"; part_fail 'initial image write'; return 1; }
rm -f /run/part-pipe
mkfifo /run/part-pipe || { umount "$mp"; part_fail 'pipe'; return 1; }
# The heartbeat's byte counter: /proc/<dd>/io where the kernel accounts it,
# the disk's own sectors-written counter where it does not (a kernel built
# without TASK_IO_ACCOUNTING has no /proc/<pid>/io). part-progress.sh
# prefers the first and falls back to the baseline recorded here; nothing
# else writes the disk while the image is going in.
echo "${disk##*/} $(awk '{print $7}' "/sys/block/${disk##*/}/stat" 2>/dev/null)" > /run/part-disk
gunzip -c "$img" > /run/part-pipe & producer=$!
dd if=/run/part-pipe of="$disk" bs=1048576 seek=$((pstart / 2048)) conv=fsync 2>/run/part-dd.err & writer=$!
echo "$writer $raw" > /run/part-worker
wait "$writer"; write_rc=$?
[ "$write_rc" = 0 ] || kill "$producer" 2>/dev/null
wait "$producer"; unpack_rc=$?
rm -f /run/part-worker /run/part-pipe /run/part-disk
[ "$write_rc:$unpack_rc" = 0:0 ] || { umount "$mp"; part_fail 'image write'; return 1; }
# 4. the new MU300 container: OpenWrt and its device runtime are already in the image
lo=$(losetup -f) && losetup -o $((pstart * 512)) "$lo" "$disk" ||
{ umount "$mp"; part_fail 'root loop failed'; return 1; }
echo "4/6 verifying the complete written image" > /run/part-status
# Keep pipefail local to these checks: init has other intentional short
# reads. Read exactly raw bytes through the newly attached loop device.
want=$(set -o pipefail; gzip -dc "$img" | sha256sum | cut -d' ' -f1) || {
losetup -d "$lo"; umount "$mp"; part_fail 'source image checksum'; return 1;
}
got=$(set -o pipefail; head -c "$raw" "$lo" | sha256sum | cut -d' ' -f1) || {
losetup -d "$lo"; umount "$mp"; part_fail 'image readback'; return 1;
}
[ "$got" = "$want" ] || {
losetup -d "$lo"; umount "$mp"; part_fail 'image readback checksum mismatch'; return 1;
}
mkdir -p /part-root
if [ "$GROW_FS" = 1 ]; then
# The partition as it stands, not the size chosen on the PC: a re-run
# reuses the existing mu300root, and the chosen number can be smaller than
# it -- resizing to that number would shrink a system that works, and
# the superblock check would report the shrink as a success.
ptarget=$((pend - pstart + 1))
echo "5/6 expanding filesystem to $((ptarget / 2048)) MiB (offline)" > /run/part-status
part_grow_ext4 "$lo" "$ptarget" || {
losetup -d "$lo"; umount "$mp"; part_fail 'filesystem expansion/size verification'; return 1;
}
else
echo "5/6 keeping the image's filesystem size" > /run/part-status
fi
echo "6/6 finishing the new root" > /run/part-status
if mount -t ext4 "$lo" /part-root; then
if [ -f "$dft" ]; then
tar -xf "$dft" -C /part-root || { umount /part-root; losetup -d "$lo"; umount "$mp"; part_fail 'firmware archive'; return 1; }
sha256sum "$dft" | cut -d' ' -f1 > /part-root/openwrt/etc/mu300/device-files.stamp
log "stage=part-install device-files"
fi
[ -x /part-root/openwrt/sbin/init ] && [ -s /part-root/openwrt/lib/firmware/wcnmodem.bin ] ||
{ umount /part-root; losetup -d "$lo"; umount "$mp"; part_fail 'incomplete system'; return 1; }
mkdir -p /part-root/.mu300
echo openwrt > /part-root/.mu300/boot-os
echo 5 > /part-root/.mu300/boot-attempts
echo 0 > /part-root/.mu300/boot-tries
echo linux > /part-root/openwrt/etc/mu300/default-boot
echo part > /part-root/openwrt/etc/mu300/desktop-mode
sync
umount /part-root || { part_fail 'root unmount'; return 1; }
else
losetup -d "$lo"; umount "$mp"; part_fail 'new root mount'; return 1
fi
losetup -d "$lo"
umount "$mp"
# The payloads are done with. Removing them is the one write the whole
# flow makes to the vendor F2FS from Linux; a few unlinks with a clean
# unmount, the same bargain boot/init takes for one-boot choices.
if mount -t "$datafs" -o noatime,nodiratime "$dev" "$mp" 2>/dev/null; then
rm -f "$mp/mu300linux/part-install.img.gz" "$mp/mu300linux/part-install.conf" \
"$mp/mu300linux/part-install.settings" "$mp/mu300linux/device-files.tar"
sync
umount "$mp"
log "stage=part-install cleaned"
else
log "stage=part-install clean-skipped"
fi
sync
part_stop
log "stage=part-install done"
# A partition the install created exists in the kernel's table only from
# the next boot (this boot read the table before it existed), so the
# selection cannot start it now: restart once, cleanly, into it. The
# native MU300 boot counter protects the first start.
# LK counts slot b's tries down as it boots it, and one try left on a slot
# that is not successful rolls back at once (nowhere to land but Android):
# this install boot consumed one, so refill the trial before the restart
# -- the next boot is the system's first, and mu300-next-boot rearms it.
write_misc_bc "$DESKTOP_LINUX_BC" part-install-rearm || { part_fail 'boot control write'; return 1; }
cmp -s /run/bc-check.bin "$DESKTOP_LINUX_BC" || { part_fail 'boot control verification'; return 1; }
log "stage=part-install rebooting into the new system"
reboot -f
return 0
}
+282
View File
@@ -0,0 +1,282 @@
#!/usr/bin/ucode
// 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.
//
// mu300-gpt list DISK N START END NAME, one line per partition
// mu300-gpt uuid DISK N the unique GUID of partition N
// mu300-gpt add DISK NAME SECTORS a Linux partition in the largest free gap, 1 MiB aligned: N START END
// mu300-gpt resize DISK NAME SECTORS an existing partition to a new size (shrink, or into free space)
// mu300-gpt plan DISK NAME:SECTORS|resize:NAME:SECTORS ... simulate requests, read-only: NAME N START END
let fs = require('fs');
function die(msg) {
warn(`mu300-gpt: ${msg}\n`);
exit(1);
}
let crctab = [];
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++)
c = (c & 1) ? (0xEDB88320 ^ (c >> 1)) : (c >> 1);
push(crctab, c);
}
function crc32(s) {
let c = 0xFFFFFFFF;
for (let i = 0; i < length(s); i++)
c = crctab[(c ^ ord(s, i)) & 0xFF] ^ (c >> 8);
return c ^ 0xFFFFFFFF;
}
function le(s, off, n) {
let v = 0;
for (let i = n - 1; i >= 0; i--)
v = v * 256 + ord(s, off + i);
return v;
}
function lebytes(v, n) {
let b = [];
for (let i = 0; i < n; i++) {
push(b, chr(v % 256));
v = int(v / 256);
}
return join('', b);
}
function put(s, off, bytes) {
return substr(s, 0, off) + bytes + substr(s, off + length(bytes));
}
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()}`);
function rd(lba, count) {
h.seek(lba * 512, 0);
let s = h.read(count * 512);
if (length(s) != count * 512)
die(`${disk}: short read at sector ${lba}`);
return s;
}
function wr(lba, s) {
h.seek(lba * 512, 0);
h.write(s) == length(s) || die(`${disk}: write failed at sector ${lba}`);
}
// a header and its table, checked
function load(lba) {
let hd = rd(lba, 1);
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)
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),
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);
if (crc32(g.tab) != le(hd, 88, 4))
die(`the GPT table of the header at sector ${lba} fails its checksum`);
return g;
}
let ZERO16 = lebytes(0, 16);
let p = load(1);
let parts = [], empty = -1, free_entries = [];
for (let i = 0; i < p.num; i++) {
let e = substr(p.tab, i * 128, 128);
if (substr(e, 0, 16) == ZERO16) {
if (empty < 0)
empty = i;
push(free_entries, i);
continue;
}
let name = '';
for (let j = 56; j < 128; j += 2) {
let c = le(e, j, 2);
if (!c)
break;
name += (c < 128) ? chr(c) : '?';
}
push(parts, { n: i + 1, start: le(e, 32, 8), end: le(e, 40, 8), name: name });
}
if (cmd == 'list') {
for (let x in parts)
print(`${x.n} ${x.start} ${x.end} ${x.name}\n`);
exit(0);
}
if (cmd == 'uuid') {
let n = +ARGV[2];
if (type(n) != 'int' || n < 1 || n > p.num)
die('uuid: invalid partition number');
let e = substr(p.tab, (n - 1) * 128, 128);
if (substr(e, 0, 16) == ZERO16)
die('uuid: unused partition');
let g = substr(e, 16, 16), out = '';
for (let i in [3, 2, 1, 0, -1, 5, 4, -1, 7, 6, -1, 8, 9, -1, 10, 11, 12, 13, 14, 15])
out += (i < 0) ? '-' : sprintf('%02x', ord(g, i));
print(`${out}\n`);
exit(0);
}
let b = load(p.alt);
if (p.tab != b.tab || p.num != b.num || p.first != b.first || p.last != b.last || b.alt != 1 ||
substr(p.hd, 56, 16) != substr(b.hd, 56, 16))
die('primary and backup GPT disagree; repair the partition table before installing');
// the largest free gap between the usable sectors, the partitions sorted
function available() {
let sorted = sort(parts, (x, y) => x.start - y.start), gaps = [], at = p.first;
for (let x in sorted) {
if (x.start < at || x.end < x.start || x.end > p.last)
die(`invalid/overlapping partition ${x.n} (${x.name})`);
if (x.start > at)
push(gaps, [at, x.start - 1]);
at = x.end + 1;
}
if (p.last >= at)
push(gaps, [at, p.last]);
return gaps;
}
function allocation(name, want) {
if (!match(name ?? '', /^[A-Za-z0-9_-]{1,36}$/) || type(want) != 'int' || want < 2048)
die('invalid partition request: name and integer size >= 2048 sectors required');
for (let x in parts)
if (x.name == name)
die(`partition ${name} already exists`);
let best = null, total = 0, largest = 0;
for (let g in available()) {
let s = int((g[0] + 2047) / 2048) * 2048;
let size = max(0, g[1] - s + 1);
total += size;
largest = max(largest, size);
if (size >= want && (!best || size > best[1] - best[0] + 1))
best = [s, g[1]];
}
if (!best)
die(`insufficient unallocated space on ${disk} for ${name}: required ${want / 2048} MiB, largest aligned gap ${largest / 2048} MiB, total remaining ${total / 2048} MiB; free space inside existing filesystems cannot be used`);
return [best[0], best[0] + want - 1];
}
// An existing partition's new range. Shrinking here only moves the table's
// 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)
die('invalid resize request: an integer size >= 2048 sectors is required');
let target = null;
for (let x in parts)
if (x.name == name) {
if (target)
die(`two partitions are named ${name}; resize by hand`);
target = x;
}
if (!target)
die(`no partition named ${name} to resize`);
let end = target.start + want - 1;
if (end > p.last)
die(`resize of ${name} would end past the last usable sector`);
for (let x in parts)
if (x.n != target.n && x.start <= end && x.end >= target.start)
die(`resize of ${name} to ${want} sectors overlaps partition ${x.n} (${x.name})`);
return [target.start, end, target.n];
}
if (cmd == 'plan') {
let count = length(ARGV) - 2, planned = [];
if (count < 1)
die('plan: specify every NAME:SECTORS or resize:NAME:SECTORS request');
let adds = 0;
for (let i = 0; i < count; i++) {
let request = split(ARGV[i + 2], ':');
if (length(request) == 3 && request[0] == 'resize') {
let range = resize_range(request[1], +request[2]);
for (let x in parts)
if (x.n == range[2])
x.end = range[1]; // later requests see the new layout
push(planned, { n: range[2], start: range[0], end: range[1], name: request[1] });
continue;
}
if (length(request) != 2)
die('plan: expected NAME:SECTORS or resize:NAME:SECTORS');
adds++;
if (adds > length(free_entries))
die(`insufficient GPT entries: required ${adds}, available ${length(free_entries)}; nothing was written`);
let range = allocation(request[0], +request[1]);
let x = { n: free_entries[adds - 1] + 1, start: range[0], end: range[1], name: request[0] };
push(parts, x);
push(planned, x);
}
for (let x in planned)
print(`${x.name} ${x.n} ${x.start} ${x.end}\n`);
exit(0);
}
// Both copies, backup first: a cut in between leaves one good copy that the
// kernel takes (the rest of a last sector the table does not fill is kept).
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 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));
wr(g.lba, hd);
h.flush();
}
}
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));
commit(put(p.tab, (range[2] - 1) * 128, entry));
h.close();
print(`${ARGV[2]} ${range[2]} ${range[0]} ${range[1]}\n`);
exit(0);
}
if (empty < 0)
die('the GPT has no free entry; nothing was written');
let carve = null;
if (cmd == 'carve-userdata') {
// Destructive prepare only: caller authorizes discarding userdata and checks
// that it is unmounted. Commit both geometry edits in one GPT generation.
let length = +ARGV[2], root_size = +ARGV[3], previous = +ARGV[4];
let r = resize_range('userdata', length), original = null;
for (let x in parts) {
if (x.name == 'mu300root') die('mu300root already exists');
if (x.n == r[2]) original = x;
}
if (!original || original.end - original.start + 1 != previous ||
length < 4194304 || root_size < 4194304 || length % 2048 || root_size % 2048 ||
type(root_size) != 'int' || r[1] + root_size > original.end || (r[1] + 1) % 2048)
die('invalid destructive userdata allocation');
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)));
}
let name = carve ? 'mu300root' : ARGV[2], want = +ARGV[3];
let range = carve || allocation(name, want);
let start = range[0], end = range[1];
let guid = fs.readfile('/dev/urandom', 16) || die('no /dev/urandom');
guid = put(guid, 7, chr((ord(guid, 7) & 0x0F) | 0x40)); // version 4
guid = put(guid, 8, chr((ord(guid, 8) & 0x3F) | 0x80)); // variant
let uname = '';
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;
entry += lebytes(0, 128 - length(entry));
commit(put(p.tab, empty * 128, entry));
h.close();
print(`${empty + 1} ${start} ${end}\n`);
+89
View File
@@ -0,0 +1,89 @@
# Destructive first stage, activated by a device-bound boot ramdisk request.
# Userdata is never read/mounted. The stock recovery owns formatting/encryption.
part_prepare() {
local request token cid node start previous target need bc extra dev disk u root_start mark actual rc part_rejected
request=$(cat /etc/mu300-desktop-prepare 2>/dev/null)
[ -n "$request" ] || return 0
. /etc/part-progress.sh
part_progress_start
echo '1/3 verifying destructive partition plan' > /run/part-status
# Nothing is written until the plan has passed every check. A request that
# fails one is not a failure of this boot: the device must go on and boot
# what it would have booted without the request at all (Android), instead of
# parking in the initramfs. part_reject only marks the failure and stops the
# progress heartbeat -- a `return` inside it would return from the helper, not
# from here -- and the gate after the checks is what leaves this function.
# Only a failure after the first destructive write returns 1, which boot/init
# turns into part_fail and a wait for inspection.
part_reject() {
[ -n "${part_rejected:-}" ] && return 0
part_rejected=1
part_stop
log "stage=part-prepare rejected-request"
return 0
}
# Colon-delimited literals only; never source/eval a request.
IFS=: read -r token cid node start previous target need bc extra <<EOF
$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 *[!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*}
[ -b "$dev" ] && [ -b "$disk" ] && [ -b "$misc" ] || part_reject
[ "$(cat /sys/class/block/${node%p*}/device/cid)" = "$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
[ -z "$(ls -A /sys/class/block/$node/holders)" ] || part_reject
awk -v n="$(cat /sys/class/block/$node/dev)" '$3 == n {yes=1} END {exit !yes}' /proc/self/mountinfo && part_reject
case "$target$need$previous" in
*[!0-9]*) part_reject ;;
*) [ "$target" -ge 4194304 ] && [ "$need" -ge 4194304 ] &&
[ "$((target + need))" -le "$previous" ] || part_reject ;;
esac
for u in /sys/class/block/${node%p*}p*/uevent; do
grep -qx PARTNAME=mu300root "$u" && part_reject
done
[ -z "$part_rejected" ] || return 0
# From here on the disk is modified, so the safety timer must not reboot
# into a half-prepared layout, and a failure below is a real failure.
touch /run/stay
# Prepare the stock recovery message before changing geometry. BCB occupies
# bytes 0..2047 (AOSP bootloader_message: command 32 + status 32 + recovery
# 768 + stage 32 + reserved 1184); the A/B boot control at 2048 is preserved
# separately. The vendor flashing tool's erase-userdata writes the same
# block, zeroed in full -- 0x800 bytes with "boot-recovery" at 0 and
# "recovery\n--wipe_data\n" at 0x40.
dd if=/dev/zero of=/run/part-bcb bs=2048 count=1 2>/dev/null || return 1
printf 'boot-recovery' | dd of=/run/part-bcb conv=notrunc 2>/dev/null || return 1
printf 'recovery\n--wipe_data\n--reason=mu300-part-prepare\n' |
dd of=/run/part-bcb bs=1 seek=64 conv=notrunc 2>/dev/null || return 1
printf '%b' "$(echo "$bc" | sed 's/../\\x&/g')" > /run/part-android-bc
[ "$(wc -c < /run/part-android-bc)" = 32 ] || return 1
echo '2/3 rebuilding userdata and reserving OpenWrt partition' > /run/part-status
/usr/bin/ucode /usr/share/mu300-gpt carve-userdata "$disk" "$target" "$need" "$previous" > /run/part-carve.log 2>&1 || return 1
root_start=$((start + target))
actual=$(/usr/bin/ucode /usr/share/mu300-gpt list "$disk") || return 1
[ "$(echo "$actual" | awk '$4 == "mu300root" {print $2, $3}')" = "$root_start $((root_start + need - 1))" ] || return 1
# A durable transaction marker belongs to the new root, not erased /data.
# A second boot cannot repeat the carve: the old geometry check fails.
printf 'MU300-PART-PREPARED-V2 %s\n' "$token" > /run/part-prepared
dd if=/dev/zero of="$disk" bs=4096 seek=$((root_start / 8)) count=1 conv=notrunc,fsync || return 1
dd if=/run/part-prepared of="$disk" bs=512 seek="$root_start" conv=notrunc,fsync || return 1
echo '3/3 rebooting to stock recovery to format Android data' > /run/part-status
dd if=/run/part-bcb of="$misc" bs=1 count=2048 conv=notrunc,fsync || return 1
dd if=/run/part-android-bc of="$misc" bs=1 seek=2048 count=32 conv=notrunc,fsync || return 1
dd if="$misc" of=/run/part-bcb-check bs=1 count=2048 2>/dev/null
dd if="$misc" of=/run/part-bc-check bs=1 skip=2048 count=32 2>/dev/null
cmp -s /run/part-bcb /run/part-bcb-check && cmp -s /run/part-android-bc /run/part-bc-check || return 1
sync; persist
sleep 3
reboot -f
return 1
}
+60
View File
@@ -0,0 +1,60 @@
# Shared installation progress. No fabricated percentage for filesystem work.
part_seconds() { cut -d. -f1 /proc/uptime; }
part_progress_start() {
part_start=$(part_seconds)
touch /run/part-install.running
echo 'Preparing installation' > /run/part-status
(
while [ -e /run/part-install.running ]; do
msg="$(cat /run/part-status 2>/dev/null) | elapsed $(($(part_seconds) - part_start))s"
if [ -s /run/part-worker ]; then
read -r worker total < /run/part-worker
written=$(awk '/^wchar:/ {print $2}' /proc/$worker/io 2>/dev/null)
if [ -z "$written" ] && [ -s /run/part-disk ]; then
# Without per-process io accounting (no /proc/<pid>/io in
# this kernel) the disk's sectors-written counter, sampled
# against install-part.sh's baseline, is the same number.
read -r dname base < /run/part-disk
now=$(awk '{print $7}' "/sys/block/$dname/stat" 2>/dev/null)
case "$now" in ''|*[!0-9]*) ;; *) written=$(( (now - base) * 512 )) ;; esac
fi
if [ "${total:-0}" -gt 0 ] && [ -n "$written" ]; then
[ "$written" -le "$total" ] || written=$total
msg="$msg | $((written / 1048576))/$((total / 1048576)) MiB ($((written * 100 / total))%)"
fi
fi
printf '<3>MU300-INSTALL: %s\n' "$msg" > /dev/kmsg
printf "%s\n" "$msg" > /run/mu300-desktop-www/progress.tmp
mv /run/mu300-desktop-www/progress.tmp /run/mu300-desktop-www/progress.txt
# ttyGS0 may be the preferred console. Write the panel explicitly.
[ ! -c /dev/tty0 ] || printf '\r\033[2K%s\n' "$msg" > /dev/tty0
sleep 2
done
) &
part_beat=$!
}
part_stop() {
rm -f /run/part-install.running /run/part-worker /run/part-disk
[ -z "${part_beat:-}" ] || { kill "$part_beat" 2>/dev/null; wait "$part_beat" 2>/dev/null; }
part_beat=
return 0
}
part_fail() {
echo "FAILED: $* (logs retained; do not retry blindly)" > /run/part-status
cp /run/part-status /run/mu300-desktop-www/progress.txt
log "stage=part-install FAILED: $*"
touch /run/stay
part_stop
return 1
}
part_grow_ext4() {
# Resize offline: online resize can be unavailable in the installation kernel.
local dev=$1 sectors=$2 blocks low high shift actual
blocks=$((sectors / 8))
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib:/repair/usr/lib /repair/usr/sbin/resize2fs -f "$dev" "$blocks" > /run/part-growfs.log 2>&1 || return 1
low=$(od -An -tu4 -j 1028 -N 4 "$dev" | tr -d ' \n')
high=$(od -An -tu4 -j 1360 -N 4 "$dev" | tr -d ' \n')
shift=$(od -An -tu4 -j 1048 -N 4 "$dev" | tr -d ' \n')
# Our root images use 4 KiB blocks. Do not report success on a 2 GiB FS.
[ "$shift" = 2 ] && [ "$high" = 0 ] && [ "$low" = "$blocks" ]
}
+107
View File
@@ -0,0 +1,107 @@
# Desktop-only storage policy; this file is never added to the Magisk boot.
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"
}
desktop_storage_start() {
DESKTOP_MODE=$(cat /etc/mu300-desktop-root-mode)
DESKTOP_LINUX_BC=/etc/misc-bc-slot-b-trial.bin
[ "$linux_slot" != a ] || DESKTOP_LINUX_BC=/etc/misc-bc-slot-a-trial.bin
case "$DESKTOP_MODE" in
prepare|install-part)
touch /run/stay
mkdir -p /run/mu300-desktop-www
echo 'Starting offline installation; waiting for storage checks' > /run/mu300-desktop-www/progress.txt
httpd -p "$NET.1:8089" -h /run/mu300-desktop-www &
. /etc/part-progress.sh
. /etc/part-prepare.sh
. /etc/install-part.sh
if [ "$DESKTOP_MODE" = prepare ]; then
part_prepare || { part_fail 'prepare failed'; while :; do sleep 10; done; }
restore_android; reboot -f
while :; do sleep 10; done
fi
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)" ] &&
[ "$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; }
install_part_pending "$d" || { part_fail 'install failed'; while :; do sleep 10; done; }
DESKTOP_MODE=part ;;
esac
}
# A known-bad internal filesystem must be repaired OFFLINE, before switch_root.
# Clean filesystems only read the two-byte state field; no full boot-time scan.
desktop_ext4_check() {
local state magic rc
magic=$(od -An -tx2 -j1080 -N2 "$1" | tr -d ' \n') || return 1
[ "$magic" = ef53 ] || return 1
state=$(od -An -tu2 -j1082 -N2 "$1" | tr -d ' \n') || return 1
case $state in ''|*[!0-9]*) return 1 ;; esac
[ "$((state & 2))" != 0 ] || [ -e /etc/mu300-desktop-fsck-force ] || return 0
# Keep the recovery console reachable during a slow/failing offline check.
# Healthy boots still load the saved USB mode before binding the gadget.
if [ "${DESKTOP_USB_READY:-}" != 1 ]; then
setup_usb_gadget
DESKTOP_USB_READY=1
fi
log "stage=desktop-root-fsck dev=$1"
/repair/lib/ld-musl-aarch64.so.1 --library-path /repair/lib:/repair/usr/lib \
/repair/usr/sbin/e2fsck -fy "$1" > /run/mu300-root-fsck.log 2>&1
rc=$?
[ "$rc" -le 2 ] || { log "stage=desktop-root-fsck-failed rc=$rc"; return 1; }
log "stage=desktop-root-fsck-done rc=$rc"
}
desktop_mount_root() {
local d u magic label n datafs dev loops
case "$DESKTOP_MODE" in
part)
d=$(desktop_part mu300root) || return 1
desktop_ext4_check "$d" || return 1
mount -t ext4 -o noatime "$d" /disk || return 1
[ -x /disk/openwrt/sbin/init ] && [ -f /disk/.mu300/boot-os ] || { umount /disk; return 1; }
rootloop=$d ;;
data-image)
d=$(desktop_part userdata) || return 1
mkdir -p /mu300-data
datafs=f2fs
[ "$(od -An -tx2 -j 1080 -N2 "$d" | tr -d ' \n')" != ef53 ] || datafs=ext4
# Missing/encrypted payloads must not mount userdata read-write.
case "$datafs" in ext4) mount -t ext4 -o ro,noload "$d" /mu300-data ;; *) mount -t f2fs -o ro,norecovery "$d" /mu300-data ;; esac || return 1
[ -f /mu300-data/mu300linux/openwrt.ext4 ] || { umount /mu300-data; return 1; }
umount /mu300-data || return 1
mount -t "$datafs" -o noatime "$d" /mu300-data || return 1
[ -f /mu300-data/mu300linux/openwrt.ext4 ] || { umount /mu300-data; return 1; }
loops=$(losetup -f)
losetup "$loops" /mu300-data/mu300linux/openwrt.ext4 || return 1
mount -t ext4 -o noatime "$loops" /disk || { losetup -d "$loops"; return 1; }
rootloop=$loops
# Keep the backing mount through switch_root, just like the container.
mkdir -p /disk/openwrt/mnt/mu300-data
mount --move /mu300-data /disk/openwrt/mnt/mu300-data ;;
sd)
for n in $(seq 1 8); do
for d in /dev/mmcblk[1-9]p1 /dev/mmcblk[1-9]; do
[ -b "$d" ] || continue
dd if="$d" of=/run/sd-super bs=512 count=8 2>/dev/null || continue
[ "$(wc -c < /run/sd-super)" = 4096 ] || continue
magic=$(od -An -tx2 -j1080 -N2 /run/sd-super | tr -d ' \n')
label=$(dd if=/run/sd-super bs=1 skip=1144 count=16 2>/dev/null | tr -d '\000')
[ "$magic" = ef53 ] && [ "$label" = mu300sd ] || continue
mount -t ext4 -o noatime "$d" /disk || return 1
rootloop=$d sd_root=$d; return 0
done
mdev -s; sleep 1
done
return 1 ;;
*) return 1 ;;
esac
}
+92
View File
@@ -0,0 +1,92 @@
"""Append a desktop segment to a MU300 boot without changing its kernel or Magisk input."""
import hashlib
import importlib.util
from pathlib import Path
import stat
import struct
import zlib
PERSIST=48<<20
def boot_control(live, android_slot):
if len(live)!=32 or live[4:8]!=b'BCAB' or live[8]!=1 or live[9]&7!=2 or zlib.crc32(live[:28])!=struct.unpack_from('<I',live,28)[0]:
raise ValueError('invalid live A/B boot control')
if android_slot not in ('a','b'): raise ValueError('unknown Android slot')
result=bytearray(live)
linux='b' if android_slot=='a' else 'a'
result[:4]=('_'+linux).encode()+b'\0\0'
result[12],result[14]=(0x9e,0x2f) if android_slot=='a' else (0x2f,0x9e)
result[28:]=struct.pack('<I',zlib.crc32(result[:28]))
return bytes(result)
def desktop_init(original):
# The stock TF init and its filesystem scan remain byte-for-byte unchanged.
start=original.index('# A TF-only image must never fall through')
end=original.index('mkdir -p /newroot',start)
normal=original[start:end]
addon='''# Desktop boot only: native MU300 container layout and explicit target.
. /etc/mu300-desktop-storage.sh
DESKTOP_MODE=$(cat /etc/mu300-desktop-root-mode)
if [ "$DESKTOP_MODE" = legacy ]; then
'''+normal.replace('root_target=$(cat /etc/mu300-root-target 2>/dev/null)','root_target=auto')+'''
else
root_target=sd
sd_root= rootloop= internal_root= root_mounted=0
mkdir -p /disk
case "$DESKTOP_MODE" in prepare|install-part) setup_usb_gadget; DESKTOP_USB_READY=1 ;; esac
desktop_storage_start || { restore_android; reboot -f; while :; do sleep 10; done; }
desktop_mount_root && root_mounted=1
[ "$root_mounted" != 1 ] || read_usb_boot_policy
[ "${DESKTOP_USB_READY:-}" = 1 ] || setup_usb_gadget
fi
'''
return (original[:start]+addon+original[end:]).encode()
def build(base, assets, mode, live, android_slot, prepare=None, identity=None):
if mode not in ('sd','part','data-image','prepare','install-part','legacy'): raise ValueError('unsupported desktop target')
if base[:8]!=b'ANDROID!' or len(base)!=(64<<20) or base[-64:-60]!=b'AVBf' or struct.unpack_from('<I',base,40)[0]!=4: raise ValueError('64 MiB boot v4 with AVB footer required')
assets=Path(assets)
spec=importlib.util.spec_from_file_location('mu300_boot_builder',assets/'build-boot-image.py')
builder=importlib.util.module_from_spec(spec);spec.loader.exec_module(builder)
files={'init':(desktop_init((assets/'original-init').read_text(encoding='utf-8')),stat.S_IFREG|0o755),
'etc/mu300-desktop-root-mode':((mode+'\n').encode(),stat.S_IFREG|0o644),
'etc/mu300-desktop-storage.sh':((assets/'storage.sh').read_bytes(),stat.S_IFREG|0o644)}
for name in ('part-prepare.sh','part-progress.sh','install-part.sh'):
files['etc/'+name]=((assets/name).read_bytes(),stat.S_IFREG|0o644)
files['usr/share/mu300-gpt']=((assets/'mu300-gpt').read_bytes(),stat.S_IFREG|0o755)
repair=assets/'repair'
expected=__import__('json').loads((repair/'manifest.json').read_text())['sha256']
dirs={'etc','usr','usr/bin','usr/share','usr/lib','usr/lib/ucode','lib','repair'}
for name,want in expected.items():
data=(repair/name).read_bytes()
if hashlib.sha256(data).hexdigest()!=want: raise ValueError('repair tool checksum: '+name)
files['repair/'+name]=(data,stat.S_IFREG|0o755)
files[name]=(data,stat.S_IFREG|0o755)
for entry in (name,'repair/'+name):
parts=entry.split('/')
dirs.update('/'.join(parts[:i]) for i in range(1,len(parts)))
files['repair/lib/libc.so']=(b'ld-musl-aarch64.so.1',stat.S_IFLNK|0o777)
files['lib/libc.so']=(b'ld-musl-aarch64.so.1',stat.S_IFLNK|0o777)
if prepare: files['etc/mu300-desktop-prepare']=(prepare.encode()+b'\n',stat.S_IFREG|0o600)
if identity: files['etc/mu300-desktop-identity']=(identity.encode()+b'\n',stat.S_IFREG|0o600)
padded=bytes(2048)+live
aa,lb,ab,la=builder.bootloader_control(padded)
for n,data in [('a',aa),('b',ab),('a-trial',la),('b-trial',lb)]:
files['etc/misc-bc-slot-'+n+'.bin']=(data,stat.S_IFREG|0o644)
ks,rs=struct.unpack_from('<II',base,8)
offset=4096+((ks+4095)&~4095)
if offset+rs>len(base)-64: raise ValueError('invalid boot ramdisk bounds')
ram=base[offset:offset+rs]+builder.lz4_legacy(builder.cpio_archive(dirs,files))
hdr=bytearray(base[:4096]);struct.pack_into('<I',hdr,12,len(ram))
body=bytes(hdr)+base[4096:offset]+ram
body=body.ljust((len(body)+4095)&~4095,b'\0');original_size=len(body)
avb_offset,avb_size=struct.unpack_from('>QQ',base,len(base)-44)
if avb_offset+avb_size>len(base)-64:raise ValueError('invalid AVB bounds')
body+=base[avb_offset:avb_offset+avb_size]
if len(body)>PERSIST:raise ValueError('desktop ramdisk would overlap persistent log; nothing flashed')
body=body.ljust(len(base)-64,b'\0')
footer=bytearray(base[-64:]);struct.pack_into('>QQQ',footer,12,original_size,original_size,avb_size)
return body+bytes(footer)
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
"""Build the optional Windows desktop launcher (pip install pyinstaller paramiko lz4)."""
import hashlib
import json
from pathlib import Path
import subprocess
import sys
HERE=Path(__file__).resolve().parent
out=HERE.parent/'work/desktop-exe';out.mkdir(parents=True,exist_ok=True)
source={n:hashlib.sha256((HERE/n).read_bytes()).hexdigest() for n in ('installer.py','boot_image.py')}
subprocess.run([sys.executable,'-m','PyInstaller','--noconfirm','--clean','--onefile',
'--name','OpenWrt-Installer','--distpath',str(out),'--workpath',str(out/'build'),
'--specpath',str(out),'--hidden-import','lz4.block','--hidden-import','tarfile','--collect-all','paramiko',
str(HERE/'installer.py')],check=True)
if source!={n:hashlib.sha256((HERE/n).read_bytes()).hexdigest() for n in source}:
raise RuntimeError('Installer source changed during EXE compilation; rebuild before packaging')
(out/'OpenWrt-Installer.exe.json').write_text(json.dumps({'source':source},indent=2)+'\n')
print(out/'OpenWrt-Installer.exe')
+14
View File
@@ -0,0 +1,14 @@
# Sourced only by the desktop copy of android-install.sh.
desktop_configure() {
. "$P/desktop-settings.env"
if [ -n "$SSID" ]; then
printf 'SSID=%s\nPSK=%s\nBAND=5\nCHANNEL=auto\nCOUNTRY=TR\n' "$SSID" "$WIFI_KEY" > "$1/etc/mu300/hotspot.conf"
chmod 600 "$1/etc/mu300/hotspot.conf"
fi
if [ -n "$APN" ]; then
mkdir -p "$1/etc/uci-defaults"
printf '#!/bin/sh\nuci set network.wan.apn=%s\nuci commit network\n' "$APN" > "$1/etc/uci-defaults/99-desktop-apn"
chmod 755 "$1/etc/uci-defaults/99-desktop-apn"
fi
echo sd > "$1/etc/mu300/desktop-mode"
}
+810
View File
@@ -0,0 +1,810 @@
#!/usr/bin/env python3
"""MU300 desktop installer. The ZIP's original Magisk deployment is independent."""
import argparse
import base64
from contextlib import contextmanager
import getpass
import hashlib
import importlib.util
import json
import os
from pathlib import Path, PurePosixPath
import re
import secrets
import shlex
import shutil
import struct
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.request
import uuid
import zlib
class Outcome:
def __init__(self,state,message,next_step=''):
self.state=state;self.message=message;self.next_step=next_step
class InstallerCancelled(Exception):
pass
def display_outcome(result,elapsed):
labels={'success':'SUCCESS / 成功','pending':'NEXT STEP REQUIRED / 仍需下一步',
'checked':'CHECK PASSED / 校验通过','failure':'FAILED / 失败','cancelled':'CANCELLED / 已取消'}
print('\n'+'='*56)
print('['+labels[result.state]+'] '+result.message)
if result.next_step:print('Next / 下一步: '+result.next_step)
print(f'Elapsed / 总耗时: {int(elapsed)} s',flush=True)
def run_cli(argv=None):
argv=list(sys.argv[1:] if argv is None else argv)
started=time.monotonic();code=0;result=None
try:
result=main(argv)
if not isinstance(result,Outcome):raise RuntimeError('Operation returned without a completion status')
except (InstallerCancelled,KeyboardInterrupt):
result=Outcome('cancelled','Operation cancelled / 操作已取消。');code=130
except Exception as exc:
result=Outcome('failure',str(exc).strip() or type(exc).__name__);code=1
except SystemExit as exc:
code=exc.code if isinstance(exc.code,int) else 1
if code:result=Outcome('failure','Invalid arguments / 命令行参数无效。')
if result is not None:display_outcome(result,time.monotonic()-started)
interactive=sys.stdin is not None and sys.stdin.isatty()
if '--no-pause' not in argv and ('--pause' in argv or interactive):
try:input('\nPress Enter to exit / 按回车退出… ')
except (EOFError,KeyboardInterrupt):pass
return code
def digest(path):
h=hashlib.sha256()
with open(path,'rb') as f:
for b in iter(lambda:f.read(1048576),b''): h.update(b)
return h.hexdigest()
def payload_file(root,name):
# Legacy previews had the Magisk payload at the top level.
metadata=Path(root)/'desktop/manifest.json'
layout=json.loads(metadata.read_text()).get('magisk_layout',{}) if metadata.is_file() else {}
return Path(root)/layout.get(name,name)
def public_rootfs(source,target):
# One shared rootfs in the ZIP. Desktop paths filter this on the computer,
# so installation/update never uses the build machine's modem runtime.
start=last=time.monotonic()
with tarfile.open(source,'r:gz') as src, tarfile.open(target,'w:gz',compresslevel=6) as dst:
for member in src:
name=PurePosixPath(member.name.removeprefix('./'))
if name.is_absolute() or '..' in name.parts:raise ValueError('unsafe rootfs path')
n=str(name)
if n=='opt/mu300/android' or n.startswith('opt/mu300/android/'):continue
if n.startswith('lib/firmware/') and not (n.startswith('lib/firmware/rtl_nic/') or n in ('lib/firmware/regulatory.db','lib/firmware/regulatory.db.p7s')):continue
dst.addfile(member,src.extractfile(member) if member.isfile() else None)
now=time.monotonic()
if now-last>=2:
print(f' Preparing shared rootfs / 正在准备共享系统包… {int(now-start)} s',flush=True)
last=now
@contextmanager
def payload_rootfs(root,tf=False):
source=payload_file(root,'mu300-openwrt.tar.gz')
if tf:
yield source
return
print('Preparing shared rootfs / 准备共享系统包,剔除构建机固件…',flush=True)
start=time.monotonic()
with tempfile.TemporaryDirectory(prefix='mu300 rootfs ') as temp:
target=Path(temp)/'rootfs.tar.gz'
public_rootfs(source,target)
print(f' Rootfs ready / 系统包准备完成: {time.monotonic()-start:.1f} s',flush=True)
yield target
def package_root():
here=Path(sys.executable if getattr(sys,'frozen',False) else __file__).resolve().parent
return here.parent if here.name=='desktop' else here
def module(root):
spec=importlib.util.spec_from_file_location('desktop_boot_image',root/'desktop/boot_image.py')
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m
def verify(root):
m=json.loads((root/'desktop/manifest.json').read_text())
for n,h in {**m['magisk'],**m['desktop']}.items():
p=(root/n).resolve()
if not p.is_relative_to(root.resolve()) or not p.is_file() or digest(p)!=h:
raise ValueError('Package checksum failed: '+n)
return m
def confirm(message):
print('\n'+message)
if input('Type yes to continue / 输入 yes 继续: ').strip()!='yes': raise InstallerCancelled()
def image_size(text, maximum):
try: size=float(text)
except ValueError: raise ValueError('Image size must be a number in GiB') from None
if not (2<=size<=maximum/1024): raise ValueError(f'Choose 2–{maximum/1024:.2f} GiB')
return int(size*1024)//4*4
def allocation(before, part_mib):
need=part_mib*2048
target=(before-need)//2048*2048
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
def encrypted(properties, source, raw_magic):
# FBE can have a perfectly readable filesystem superblock. A filesystem
# signature alone never grants permission to preserve encrypted files.
if properties.get('state')=='encrypted' or properties.get('type') in ('file','block') or '/dm-' in source or '/mapper/' in source:
return True
if properties.get('state')=='unencrypted' and raw_magic in ('1020f5f2','53ef'): return False
raise ValueError('Encryption state is unknown; refusing a preserving shrink')
def android_profile(model,platform=''):
names=[s.strip().upper() for s in model.splitlines()]
if 'MU3351' in names or 'V50' in names:
if 'MU3351' not in names or 'V50' not in names or platform.strip()!='ums9620':
raise ValueError('V50 requires product MU3351 and the UMS9620 platform')
return 'v50'
if re.search(r'U30.?Air',model,re.I):return 'u30air'
if re.search(r'MU300|F50',model,re.I):return 'f50'
raise ValueError('Not a supported MU300/F50/V50/U30Air: '+model)
def env(values):
return ''.join(k+'='+shlex.quote(str(v))+'\n' for k,v in values.items())
def settings(args, image_mib, mode, kernel):
ssid=input('Hotspot name / 热点名称 [import Android]: ').strip()
key=input('Hotspot key / 热点密码 (visible / 明文输入): ') if ssid else ''
if ssid and (len(ssid.encode())>32 or '\n' in ssid or '\r' in ssid): raise ValueError('SSID must be 1–32 UTF-8 bytes')
if ssid and (not 8<=len(key)<=63 or any(ord(c)<32 or ord(c)>126 for c in key)): raise ValueError('Wi-Fi key must be 8–63 ASCII characters')
apn=input('APN [SIM default / SIM 默认]: ').strip()
if apn and not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]{0,99}',apn):raise ValueError('Invalid APN')
return env({'IMAGE_MIB':image_mib,'DESKTOP_MODE':mode,'KERNEL':kernel,'SSID':ssid,'WIFI_KEY':key,'APN':apn,'PWHASH':''})
class Android:
def __init__(self,args):
self.args=args
self.adb=args.adb or shutil.which('adb') or str(package_root()/'tools/adb.exe')
listing=self.call('devices').decode(errors='replace')
serials=[l.split()[0] for l in listing.splitlines() if len(l.split())==2 and l.split()[1]=='device']
if args.serial: self.serial=args.serial
elif len(serials)==1: self.serial=serials[0]
else: raise ValueError('Specify --serial; expected one online Android device: '+repr(serials))
if self.serial not in serials: raise ValueError('Android is not online: '+self.serial)
if self.shell('id -u',root=False).strip()=='0': self.su=False
else:
self.su=True
if self.shell('id -u').strip()!='0': raise ValueError('Grant the Android su permission and retry')
model=self.shell('getprop ro.product.model; getprop ro.product.device')
self.profile=android_profile(model,self.shell('getprop ro.board.platform').strip())
self.model=model.strip();self.slot=self.shell('getprop ro.boot.slot_suffix').strip().removeprefix('_')
if self.slot not in ('a','b'): raise ValueError('Cannot identify Android slot')
self.linux='b' if self.slot=='a' else 'a'
self.p='/data/local/tmp/mu300-desktop-'+secrets.token_hex(6)
self.t=self.p+'/work';self.bb=self.p+'/busybox'
if not getattr(args,'probe',False):
self.shell('mkdir -p '+self.t+'; chown 2000:2000 '+self.p+' '+self.t+'; chmod 700 '+self.p)
def call(self,*args,timeout=1800,serial=None):
cmd=[self.adb]
selected=serial if serial is not None else getattr(self,'serial',None)
if selected:cmd+=['-s',selected]
proc=subprocess.Popen(cmd+list(args),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
start=time.monotonic()
while True:
try: out,err=proc.communicate(timeout=min(10,timeout));break
except subprocess.TimeoutExpired:
if time.monotonic()-start>timeout:
proc.kill();proc.communicate();raise TimeoutError('ADB operation timed out; do not retry a storage write blindly')
print(f' Working / 正在执行… {int(time.monotonic()-start)} s',flush=True)
if proc.returncode:
message=(err.decode(errors='replace')+'\n'+out.decode(errors='replace')).strip()
raise RuntimeError(message or f'ADB {args[0]} failed, exit {proc.returncode}; check the device connection')
return out
def reboot(self):
# The ADB reboot service acknowledges the request before shutting down;
# a root shell may disconnect before it can return an exit status.
self.call('reboot',timeout=30)
print('Reboot request sent / 已发送重启请求。')
def shell(self,script,root=True,timeout=1800):
# adb shell has an additional remote shell layer; quote its entire
# command. No host shell is used and user input never becomes code.
cmd='su -c '+shlex.quote(script) if root and self.su else 'sh -c '+shlex.quote(script)
text=self.call('shell',cmd,timeout=timeout).decode('utf-8',errors='replace').replace('\r','')
return text
def push(self,path,name):
remote=self.p+'/'+name
parent=shlex.quote(str(Path(remote).parent).replace('\\','/'))
# adb push runs as Android shell even when su is available. Private
# staging belongs to shell; root remains able to consume it.
self.shell('mkdir -p '+parent+'; chown 2000:2000 '+parent+'; chmod 700 '+parent)
self.call('push',str(path),remote)
want=digest(path)
got=self.shell('sha256sum '+shlex.quote(remote)).split()[0]
if got!=want:raise ValueError('Upload checksum failed: '+name)
return remote
def put(self,data,name):
with tempfile.TemporaryDirectory() as t:
p=Path(t)/'upload';p.write_bytes(data.encode() if isinstance(data,str) else data)
return self.push(p,name)
def read(self,command):
# Some rooted Android builds transform raw su output even through
# exec-out. ASCII transport preserves all boot/GPT/misc bytes.
encoded='set -o pipefail; '+command+' | base64'
cmd='su -c '+shlex.quote(encoded) if self.su else 'sh -c '+shlex.quote(encoded)
return base64.b64decode(b''.join(self.call('exec-out',cmd).split()),validate=True)
def run(self,body):
script='#!/system/bin/sh\nset -eu\nP='+self.p+'\nT='+self.t+'\nBB='+self.bb+'\nexport MU300_PAYLOAD_DIR=$P MU300_INSTALL_TMP=$T MU300_BUSYBOX=$BB MU300_KEEP_PAYLOAD=1\nmkdir -p "$T/bin"\n"$BB" --install -s "$T/bin"\nexport PATH="$T/bin:$PATH"\n'+body+'\n'
p=self.put(script,'run.sh')
result=self.shell(self.bb+' nsenter -t 1 -m '+self.bb+' sh '+p)
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
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')
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')
info=gpt_space(first,last,s['DISK_SIZE'])
userdata=[p for p in info['parts'] if p['name']=='userdata']
if len(userdata)!=1 or (userdata[0]['start'],userdata[0]['end']-userdata[0]['start']+1)!=(s['START'],s['SIZE']):
raise ValueError('GPT userdata differs from the running kernel; reboot Android first')
end=max(p['end'] for p in info['parts'])
candidates={27762098176//512,(end//4096+1)*4096}
candidates.update(a for a,_ in info['gaps'])
blocked=[]
for offset in sorted(candidates):
for a,n in info['gaps']:
if a<=offset and offset+4<=a+n:
raw=self.read(f'dd if={disk} bs=512 skip={offset} count=4 2>/dev/null')
if len(raw)!=2048:raise ValueError('Incomplete free-space signature read')
if raw[1080:1082]==b'\x53\xef' or raw[1024:1028]==bytes.fromhex('1020f5f2'):
blocked.append((a,n))
info['safe_gaps']=[gap for gap in info['gaps'] if gap not in blocked]
info['largest']=max((n for _,n in info['safe_gaps']),default=0) if info['empty'] else 0
info['first']=first;info['last']=last
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']
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)
self.push(source,n)
if with_rootfs:
with payload_rootfs(root,tf=tf) as archive:
self.push(archive,'mu300-openwrt.tar.gz')
self.shell('chmod 755 '+self.bb+' '+self.p+'/*.sh')
if not tf:
for n in ('android-image.sh','android-write-part.sh','android-write-free.sh','android-loop.sh'):self.push(root/'desktop'/n,n)
for p in (root/'desktop/files/boot/repair').rglob('*'):
if p.is_file():self.push(p,p.relative_to(root).as_posix())
self.shell('chmod -R u+rx '+self.p+'/desktop/files/boot/repair')
self.run('"$BB" sh "$P/android-bootchain.sh" check')
def live(self):
data=self.read('dd if=/dev/block/by-name/misc bs=1 skip=2048 count=32 2>/dev/null')
if len(data)!=32:raise ValueError('Incomplete misc read')
return data
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')
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}',
'gpt-last.bin':f'dd if={disk} bs=512 skip={tail} count={s["DISK_SIZE"]-tail}'}
for n in ('boot','uboot','sml','teecfg','trustos','vbmeta'):
for slot in ('a','b'):items[f'{n}_{slot}.img']=f'cat /dev/block/by-name/{n}_{slot}'
for n,cmd in items.items():
print('Backing up / 备份:',n)
path.joinpath(n).write_bytes(self.read(cmd+' 2>/dev/null'))
if not path.joinpath(n).stat().st_size:raise ValueError('Empty backup: '+n)
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]
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))
path.joinpath('gpt-layout.json').write_text(json.dumps({'front_sectors':front,'tail_start':tail,'disk_sectors':s['DISK_SIZE']},indent=2)+'\n')
def flash(self,image,bc):
self.put(image,'boot-desktop.img');self.put(bc,'misc-linux.bin')
self.run('''[ "$(getprop ro.boot.slot_suffix)" = "_'''+self.slot+'''" ]
"$BB" sh "$P/android-bootchain.sh" sync "$T/bootchain-backup"
dev=/dev/block/by-name/boot_'''+self.linux+'''
[ "$(blockdev --getsize64 "$dev")" -eq "$(stat -c %s "$P/boot-desktop.img")" ]
dd if="$dev" of="$T/boot-before.img" bs=1048576
dd if="$P/boot-desktop.img" of="$dev" bs=1048576 conv=fsync
dd if="$dev" of="$T/boot-check.img" bs=1048576
if ! cmp -s "$P/boot-desktop.img" "$T/boot-check.img"; then
dd if="$T/boot-before.img" of="$dev" bs=1048576 conv=fsync
dd if="$dev" of="$T/boot-check.img" bs=1048576
cmp -s "$T/boot-before.img" "$T/boot-check.img" || echo 'BOOT RESTORE FAILED; do not switch slots'
exit 1
fi
dd if=/dev/block/by-name/misc of="$T/misc-before.bin" bs=1 skip=2048 count=32
dd if="$P/misc-linux.bin" of=/dev/block/by-name/misc bs=1 seek=2048 conv=notrunc,fsync
dd if=/dev/block/by-name/misc of="$T/misc-check.bin" bs=1 skip=2048 count=32
if ! cmp -s "$P/misc-linux.bin" "$T/misc-check.bin"; then
dd if="$T/misc-before.bin" of=/dev/block/by-name/misc bs=1 seek=2048 conv=notrunc,fsync
exit 1
fi
echo 'BOOT-VERIFIED; OpenWrt selected'
''')
def transaction(path,record):
tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(record,indent=2)+'\n');tmp.replace(path)
def validate_resume(s,r,slot,serial,root_geometry,marker):
if s['CID']!=r['storage']['CID'] or s['NODE']!=r['storage']['NODE'] or s['START']!=r['storage']['START'] or slot!=r['android_slot'] or serial!=r['serial']:
raise ValueError('Resume device/slot differs from the saved transaction')
if s['SIZE']!=r['target'] or root_geometry!=(s['START']+r['target'],r['need']):raise ValueError('Prepared partition geometry differs')
if marker.strip()!=('MU300-PART-PREPARED-V2 '+r['token']).encode():raise ValueError('Preparation token mismatch; refusing to overwrite a root')
def resume_payload_id(manifest):
# Paths, EXE, prompts and upload scripts can change in a repair release.
# Bind the transaction to actual system/boot content and filesystem tools.
layout=manifest.get('magisk_layout',{})
files={}
for name in ('boot-linux.img','mu300-openwrt.tar.gz','rootfs-critical.sha256','rootfs.requirements','busybox'):
h=manifest['magisk'].get(layout.get(name,name),'')
if not re.fullmatch('[a-f0-9]{64}',h):raise ValueError('Incomplete resume payload metadata: '+name)
files[name]=h
for name,h in manifest['desktop'].items():
if name.startswith('desktop/files/boot/repair/'):
files[name]=h
if not any(n.startswith('desktop/files/boot/repair/') for n in files):
raise ValueError('Missing resume filesystem tool checksums')
canonical={'format':1,'layout':'mu300root-container','kernel':manifest['kernel'],'files':files}
return hashlib.sha256(json.dumps(canonical,sort_keys=True,separators=(',',':')).encode()).hexdigest()
def validate_resume_package(root,manifest,r,record):
current=resume_payload_id(manifest)
if r.get('payload_identity'):
if r['payload_identity']!=current:raise ValueError('Resume boot/rootfs/tools differ from the prepared installation')
return current
# Old records bound the entire manifest. Recover that exact metadata first;
# never accept an arbitrary sibling package just because its kernel matches.
candidates=[Path(record).parent/'package-manifest.json',Path(root)/'desktop/manifest.json']
olddir=r.get('package_dir')
if olddir:candidates.append(Path(olddir)/'desktop/manifest.json')
candidates.extend(p/'desktop/manifest.json' for p in Path(root).parent.iterdir() if p.is_dir())
for path in candidates:
if not path.is_file() or digest(path)!=r.get('package'):continue
if resume_payload_id(json.loads(path.read_text()))!=current:
raise ValueError('Resume boot/rootfs/tools differ from the recorded package')
print('Compatible repair package verified / 修复版关键安装载荷一致,可继续续装。')
return current
raise ValueError('Original package metadata is missing; keep its folder or restore package-manifest.json beside the transaction')
def bind_resume_package(root,manifest,r,record):
r['payload_identity']=resume_payload_id(manifest)
r['package']=digest(Path(root)/'desktop/manifest.json')
r['package_dir']=str(Path(root).resolve())
snapshot=Path(record).parent/'package-manifest.json'
temp=snapshot.with_suffix('.tmp')
temp.write_bytes((Path(root)/'desktop/manifest.json').read_bytes());temp.replace(snapshot)
transaction(Path(record),r)
def load_resume(args,root,manifest,a,s):
base=Path(args.backup_dir).expanduser()
record=Path(args.transaction).expanduser() if args.transaction else next(iter(sorted(base.glob('*/transaction.json'),key=lambda p:p.stat().st_mtime,reverse=True)),None)
if not record:raise ValueError('No saved transaction; specify --transaction FILE')
r=json.loads(record.read_text());rootnode=s.get('ROOT')
if not rootnode:raise ValueError('No prepared mu300root found')
geometry=tuple(int(x) for x in a.shell('cat /sys/class/block/'+rootnode+'/start /sys/class/block/'+rootnode+'/size').split())
marker=a.read('dd if=/dev/block/'+rootnode+' bs=512 count=1 2>/dev/null').split(b'\0',1)[0]
validate_resume(s,r,a.slot,a.serial,geometry,marker)
validate_resume_package(root,manifest,r,record)
return record,r,geometry
def boot(root,m,mode,live,slot,**kwargs):
return m.build(payload_file(root,'boot-linux.img').read_bytes(),root/'desktop/files/boot',mode,live,slot,**kwargs)
def check_boot(root):
# Exercise the real packaged repacker, including in a frozen Windows EXE.
# Synthetic A/B data stays entirely on the computer; no ADB/SSH is used.
m=module(root);source=payload_file(root,'boot-linux.img').read_bytes()
kernel_size=struct.unpack_from('<I',source,8)[0]
for slot,mode in (('a','sd'),('b','install-part')):
bc=bytearray(32);bc[:4]=('_'+slot).encode()+b'\0\0';bc[4:8]=b'BCAB';bc[8]=1;bc[9]=2
bc[12],bc[14]=(0x9f,0x1e) if slot=='a' else (0x1e,0x9f)
bc[28:]=struct.pack('<I',zlib.crc32(bc[:28]))
image=boot(root,m,mode,bytes(bc),slot)
if image[4096:4096+kernel_size]!=source[4096:4096+kernel_size] or image[44:55]!=b'loglevel=5\0':
raise ValueError('Desktop boot changed kernel or Linux sentinel')
print('Desktop boot build verified:',mode,'Android slot',slot,'(no device writes)')
def install(args,root,manifest):
a=Android(args);s=a.storage();m=module(root)
print('Device / 设备:',a.model,'Android',a.slot,'Linux',a.linux)
if args.boot_openwrt:
for n in ('busybox','android-bootchain.sh','switch.sh'):
a.push(root/'desktop'/n if n=='android-bootchain.sh' else payload_file(root,n),n)
a.shell('chmod 755 '+a.bb)
a.run('"$BB" sh "$P/android-bootchain.sh" check')
header=a.read('dd if=/dev/block/by-name/boot_'+a.linux+' bs=1 skip=44 count=11 2>/dev/null')
if header!=b'loglevel=5\0':raise ValueError('The other slot does not contain a MU300 Linux boot image')
a.run('"$BB" sh "$P/switch.sh" --no-reboot')
return Outcome('success','OpenWrt selected / 已设置启动 OpenWrt。','Reboot the device manually / 请手动重启设备。')
if args.tf:
sd=a.shell('if [ -b /dev/block/mmcblk1p1 ]; then echo /dev/block/mmcblk1p1; elif [ -b /dev/block/mmcblk1 ]; then echo /dev/block/mmcblk1; fi').strip()
if not sd:raise ValueError('No TF card found; choose an internal-storage method instead')
confirm('This formats '+sd+'; its existing data will be erased / 会清空所选 TF 分区。')
a.prepare_payload(root,tf=True)
custom=settings(args,2048,'sd',manifest['kernel'])
a.put(custom,'desktop-settings.env')
a.push(root/'desktop/configure.sh','desktop-configure.sh')
# Custom desktop choices are a private uploaded copy. Neither the
# original Magisk scripts nor their ZIP checksums are changed.
original=payload_file(root,'android-install.sh').read_text(encoding='utf-8')
hook=' . "$P/desktop-configure.sh"\n desktop_configure "$R"\n'
needle=' rm -rf "$M/$os" && mv "$M/$os.new" "$M/$os"'
if original.count(needle)!=1:raise ValueError('Unsupported Android installer version')
private=original.replace(needle,hook+needle)
a.put(private,'android-install.sh')
live=a.live()
private_boot=boot(root,m,'sd',live,a.slot)
a.put(private_boot,'boot-linux.img')
a.put(hashlib.sha256(private_boot).hexdigest()+'\n','boot-linux.sha256')
replacements={'android-install.sh':hashlib.sha256(private.encode()).hexdigest(),
'boot-linux.img':hashlib.sha256(private_boot).hexdigest(),
'android-bootchain.sh':digest(root/'desktop/android-bootchain.sh'),
'bootchain.sh':digest(root/'desktop/bootchain.sh')}
payload=payload_file(root,'payload.sha256').read_text()
for name,checksum in replacements.items():
payload=re.sub(r'^[a-f0-9]{64}(\s+\*?'+re.escape(name)+r')$',lambda match:checksum+match[1],payload,flags=re.M)
a.put(payload,'payload.sha256')
a.put(env({'SD_MODE':1,'SD_DEV':sd,'FORMAT':1,'SYNC_BOOTCHAIN':1,'OSES':'openwrt','WIPE_LEGACY':0,'UPDATE':0,'BOOT_OS':'openwrt','DEFAULT_LINUX':1,'BOOT_ATTEMPTS':5,'IMPORT_HOTSPOT':1,'KERNEL':manifest['kernel'],'PWHASH':''}),'mu300-install.env')
# The original TF worker handles release, formatting and readback.
# Only its desktop upload has custom settings and fresh A/B blocks.
a.run('export MU300_TF_BOOTDEV=/dev/block/by-name/boot_'+a.linux+'\n"$BB" sh "$P/tf-install-worker.sh"')
return Outcome('success','TF installation verified / TF 安装和写入校验已完成。','Reboot the device manually / 请手动重启设备。')
base=Path(args.backup_dir).expanduser()
if args.resume:
record,r,geom=load_resume(args,root,manifest,a,s)
confirm('Resume installation into the prepared OpenWrt partition / 继续安装到已准备的 OpenWrt 分区。')
bind_resume_package(root,manifest,r,record)
a.prepare_payload(root)
return direct_write(a,root,m,manifest,s,geom[1],record,r)
if args.reinstall_part:
node=s.get('ROOT')
if not node:raise ValueError('No existing mu300root to reinstall')
capacity=int(a.shell('cat /sys/class/block/'+node+'/size').strip())
confirm('Reinstall erases only the existing OpenWrt partition, including its settings / 会清空原 OpenWrt 分区及设置。')
a.prepare_payload(root)
return direct_write(a,root,m,manifest,s,capacity)
# A new partition in a GPT gap never needs to access the encrypted raw
# userdata. Decide this path before requesting a shrink/reset.
if not args.data:
if s.get('ROOT'):raise ValueError('mu300root exists; choose reinstall or update')
space=a.gpt(s)
if any(p['name']=='mu300root' for p in space['parts']):
raise ValueError('GPT already has mu300root; reboot Android to refresh partition nodes, then choose reinstall/update')
if not space['empty']:raise ValueError('GPT has no unused partition entry; nothing was changed')
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')
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 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 / 所选空闲区域原始内容将被覆盖。')
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')
a.prepare_payload(root)
return free_write(a,root,m,manifest,s,space,offset,size*2048)
is_encrypted=encrypted({'state':s['STATE'],'type':s['TYPE']},s['SOURCE'],s['EXT'] if s['EXT']=='53ef' else s['MAGIC'])
if args.data and is_encrypted:raise ValueError('Encrypted userdata cannot host a bootable image. Choose independent-partition installation.')
if args.data:
maximum=(s['FREE']//1024-1024-256)
print(f'Available / 可用: {s["FREE"]/1048576:.2f} GiB; image maximum {maximum/1024:.2f} GiB')
size=image_size(args.size or input('Image size GiB / 镜像大小 [4]: ') or '4',maximum)
confirm('Create a userdata image; an existing image will be retained as a backup / 新建镜像,保留已有镜像备份。')
a.prepare_payload(root)
a.put(settings(args,size,'data-image',manifest['kernel']),'desktop-settings.env')
a.run('"$BB" sh "$P/android-image.sh"')
live=a.live();a.flash(boot(root,m,'data-image',live,a.slot),m.boot_control(live,a.slot))
return Outcome('success','Userdata image and boot verified / userdata 镜像和启动镜像已安装并校验。','Reboot the device manually / 请手动重启设备。')
if s['START']%2048:raise ValueError('userdata starts at an unsupported unaligned sector')
target,need=allocation(s['SIZE'],size)
destructive=is_encrypted or args.format_userdata
if not destructive:
destructive=input('Format Android userdata instead of preserving it? / 是否格式化 Android 数据?[no]: ').strip().lower()=='yes'
if not destructive and (target//2 < (s['SIZE']//2-s['FREE']+1048576)):
raise ValueError('Android data + 1 GiB reserve does not fit the selected smaller userdata')
confirm('Userdata will be formatted and Android reset / userdata 将格式化,Android 数据全部清空。' if destructive else 'Shrink userdata offline while preserving Android data / 离线缩小 userdata,保留 Android 数据。')
backup=base/(time.strftime('%Y%m%d-%H%M%S')+'-'+s['CID'][-8:]);a.backup(backup,s)
live=a.live()
if destructive:
token=secrets.token_hex(16)
aa=bytearray(live);aa[:4]=('_'+a.slot).encode()+b'\0\0';aa[12],aa[14]=(0x9f,0x1e) if a.slot=='a' else (0x1e,0x9f);aa[28:]=struct.pack('<I',zlib.crc32(aa[:28]))
request=':'.join(map(str,(token,s['CID'],s['NODE'],s['START'],s['SIZE'],target,need,bytes(aa).hex())))
r={'format':1,'state':'prepared-request','serial':a.serial,'android_slot':a.slot,'storage':s,'target':target,'need':need,'token':token,'package':digest(root/'desktop/manifest.json')}
bind_resume_package(root,manifest,r,backup/'transaction.json')
a.prepare_payload(root,with_rootfs=False)
a.flash(boot(root,m,'prepare',live,a.slot,prepare=request),m.boot_control(live,a.slot))
print('Saved resume transaction / 续装记录:',backup/'transaction.json')
print('Rebooting to offline partition preparation and stock recovery. Complete Android setup, USB debugging and su; then run resume-internal-install / 重置后重新启用 USB 调试和 root,运行续装入口。')
a.reboot()
return Outcome('pending','Preparation written; offline resize/reset is starting / 准备阶段已写入,设备将离线缩容并重置 Android。',
'Finish Android setup, enable USB debugging and root, then choose 5 to resume / 完成 Android 初始化,启用 USB 调试和 root,再选 5 续装。')
# Use a small, fully verified initial image; offline resize fills ALL space.
a.prepare_payload(root)
a.put(settings(args,2048,'part-stage',manifest['kernel']),'desktop-settings.env')
a.run('"$BB" sh "$P/android-image.sh"')
a.run('printf "PART_MIB='+str(size)+'\\nDATA_MIB='+str(target//2048)+'\\nGROW_FS=1\\nFORMAT_DATA=0\\n" > /data/mu300linux/part-install.conf\nsync')
identity=':'.join(map(str,(s['CID'],s['NODE'],s['START'],s['SIZE'],target)))
a.flash(boot(root,m,'install-part',live,a.slot,identity=identity),m.boot_control(live,a.slot))
print('Offline shrink/install starts after reboot; progress at http://192.168.77.1:8089/progress.txt (U30Air: .78.1). / 重启后开始离线安装。')
a.reboot()
return Outcome('pending','Payload verified; offline shrink/install is starting / 载荷校验通过,设备将离线缩容并安装。',
'Wait for the device to finish and boot OpenWrt / 等待设备完成安装并启动 OpenWrt。')
def direct_write(a,root,m,manifest,s,sectors,record=None,r=None):
node=s['ROOT']
a.put(settings(a.args,2048,'part',manifest['kernel']),'desktop-settings.env')
a.run('"$BB" sh "$P/android-image.sh"')
checksum=a.shell('sha256sum '+a.t+'/openwrt.ext4.new').split()[0]
a.run('"$BB" sh "$P/android-write-part.sh" /dev/block/'+node+' '+s['CID']+' '+str(sectors)+' '+checksum)
live=a.live();a.flash(boot(root,m,'part',live,a.slot),m.boot_control(live,a.slot))
if record:r['state']='installed';transaction(record,r)
return Outcome('success',f'Independent partition installed and verified: {sectors/2097152:.2f} GiB / 独立分区已安装、扩容并校验。',
'Reboot the device manually / 请手动重启设备。')
def free_write(a,root,m,manifest,s,space,offset,sectors):
first,last=gpt_add_root(space['first'],space['last'],s['DISK_SIZE'],offset,sectors)
for name,data in (('gpt-before-first.bin',space['first']),('gpt-before-last.bin',space['last']),
('gpt-new-first.bin',first),('gpt-new-last.bin',last)):
a.put(data,name)
a.put(settings(a.args,2048,'part',manifest['kernel']),'desktop-settings.env')
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]
a.run('"$BB" sh "$P/android-write-free.sh" '+env_args([
disk,s['CID'],s['DISK_SIZE'],offset,sectors,checksum,space['front'],space['tail']]))
# Independent verification after the device-side comparison, before
# writing boot or selecting the alternate slot.
if a.read(f'dd if={disk} bs=512 count={space["front"]} 2>/dev/null')!=first or a.read(
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 数据保留。',
'Reboot the device manually; the new partition appears after reboot / 手动重启后新分区生效。')
def env_args(values):
return ' '.join(shlex.quote(str(v)) for v in values)
def ssh_exec(c,command,timeout=1800):
_,out,_=c.exec_command(command,timeout=timeout)
channel=out.channel;channel.set_combine_stderr(True);start=time.monotonic();last=start
parts=[]
while True:
if channel.recv_ready():
b=channel.recv(65536);parts.append(b);print(b.decode(errors='replace'),end='',flush=True)
elif channel.exit_status_ready():break
else:
time.sleep(.1)
if time.monotonic()-last>=10:print(f' Working… {int(time.monotonic()-start)} s');last=time.monotonic()
if time.monotonic()-start>timeout:raise TimeoutError('SSH timed out; check device status before retrying')
rc=channel.recv_exit_status()
if rc:raise RuntimeError('Remote operation failed, exit '+str(rc))
return b''.join(parts).decode(errors='replace')
def update(args,root):
import paramiko
c=paramiko.SSHClient();known=Path.home()/'.mu300-desktop-known-hosts'
if known.exists():c.load_host_keys(str(known))
class NewKey(paramiko.MissingHostKeyPolicy):
def missing_host_key(self,client,hostname,key):
print('SSH host key:',hostname,key.get_name(),hashlib.sha256(key.asbytes()).hexdigest())
confirm('Trust this device key / 信任此设备密钥?')
client.get_host_keys().add(hostname,key.get_name(),key);client.save_host_keys(str(known))
c.set_missing_host_key_policy(NewKey())
host=args.host or input('Device IP / 设备 IP [192.168.77.1]: ').strip() or '192.168.77.1'
c.connect(host,username='root',password=os.environ.get('MU300_SSH_PASSWORD') or getpass.getpass('SSH root password: '),timeout=15,look_for_keys=False,allow_agent=False)
try:
info=ssh_exec(c,'''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'):raise ValueError('Unsupported root layout; use native mu300-update for legacy installations')
family=json.loads((root/'desktop/manifest.json').read_text())['kernel']
running=ssh_exec(c,'uname -r').strip()
if not running.startswith(family+'.'):raise ValueError('Kernel family mismatch: running '+running+', package '+family)
livehex=ssh_exec(c,f'dd if={info[2]} bs=1 skip=2048 count=32 2>/dev/null | od -An -tx1 -v | tr -d " \\n"').strip()
live=bytes.fromhex(livehex);slot='b' if info[1]=='a' else 'a';m=module(root)
newboot=boot(root,m,mode,live,slot);bc=m.boot_control(live,slot)
confirm('Update OpenWrt while preserving settings and disk size; then reboot / 保留配置及容量更新,完成后重启。')
# Stage on the Linux filesystem: sufficient space for a new root + old
# root and upload, without consuming all tmpfs/RAM on a 256 MiB unit.
p='/mnt/mu300-disk/.mu300-desktop-'+secrets.token_hex(6)
ssh_exec(c,'mkdir -m 700 '+p)
sftp=c.open_sftp()
def send(local,name):
sftp.put(str(local),p+'/'+name)
got=ssh_exec(c,'sha256sum '+p+'/'+name).split()[0]
if got!=digest(local):raise ValueError('SSH upload checksum: '+name)
with 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)
for name in ('rootfs-critical.sha256','rootfs.requirements'):send(payload_file(root,name),name)
with tempfile.TemporaryDirectory() as t:
for name,data in (('boot-desktop.img',newboot),('misc-linux.bin',bc)):
f=Path(t)/name;f.write_bytes(data);send(f,name)
sftp.close()
ssh_exec(c,'sh '+p+'/local-update.sh '+p)
finally:c.close()
return Outcome('success','Update verified; device is rebooting / 更新校验完成,设备正在重启。',
'Wait for OpenWrt to start / 等待 OpenWrt 启动。')
def main(argv=None):
p=argparse.ArgumentParser(description=__doc__)
actions=p.add_mutually_exclusive_group()
for n in ('tf','data','part','reinstall-part','resume','update','boot-openwrt','check','check-boot','check-rootfs','check-resume','probe'):actions.add_argument('--'+n,action='store_true')
pause=p.add_mutually_exclusive_group()
pause.add_argument('--pause',action='store_true',help='wait for Enter after the result, including redirected input')
pause.add_argument('--no-pause',action='store_true',help='exit immediately after the result (automation)')
p.add_argument('--adb');p.add_argument('--serial');p.add_argument('--host');p.add_argument('--size')
p.add_argument('--format-userdata',action='store_true');p.add_argument('--transaction')
p.add_argument('--backup-dir',default=str(Path.home()/'mu300-backups'))
args=p.parse_args(argv);root=package_root();manifest=verify(root)
print('MU300 desktop package verified; kernel',manifest['kernel'])
if args.check:return Outcome('checked','Package checksums passed / 安装包校验通过。')
if args.check_rootfs:
before=digest(payload_file(root,'mu300-openwrt.tar.gz'))
with payload_rootfs(root) as archive:
with tarfile.open(archive) as tar:
print('Desktop rootfs prepared and readable:',len(tar.getmembers()),'members (no device access)')
if digest(payload_file(root,'mu300-openwrt.tar.gz'))!=before:raise ValueError('Shared rootfs changed during preparation')
return Outcome('checked','Shared rootfs preparation passed / 共享 rootfs 准备检查通过。')
if args.check_boot:
check_boot(root);return Outcome('checked','Desktop boot construction passed / 桌面启动镜像构建检查通过。')
if args.check_resume:
args.probe=True
a=Android(args);_,_,geometry=load_resume(args,root,manifest,a,a.storage())
print(f'Resume verified / 续装校验通过: {geometry[1]/2097152:.2f} GiB (no device writes)')
return Outcome('checked',f'Resume record verified: {geometry[1]/2097152:.2f} GiB / 续装记录校验通过。')
if args.probe:
a=Android(args);storage=a.storage();bc=a.live();space=a.gpt(storage)
module(root).boot_control(bc,a.slot) # validate only, never write misc
dt=a.read('cat /sys/firmware/fdt')
if len(dt)<8 or dt[:4]!=bytes.fromhex('d00dfeed') or struct.unpack_from('>I',dt,4)[0]!=len(dt):
raise ValueError('Device tree binary transport verification failed')
print(json.dumps({'profile':a.profile,'model':a.model,'android_slot':a.slot,
'encryption':storage['STATE'],'encryption_type':storage['TYPE'],
'userdata_free_gib':round(storage['FREE']/1048576,2),
'emmc_gib':round(storage['DISK_SIZE']/2097152,2),
'gpt_unused_largest_gib':round(space['largest']/2097152,2),
'gpt_unused_ranges':space['safe_gaps'],
'dtb_bytes':len(dt),'dtb_sha256':hashlib.sha256(dt).hexdigest(),
'device_writes':False},ensure_ascii=False,indent=2))
return Outcome('checked','Read-only device preflight passed / 设备只读预检通过。')
if not any(getattr(args,n) for n in ('tf','data','part','reinstall_part','resume','update','boot_openwrt')):
choices=('tf','data','part','reinstall_part','resume','update','boot_openwrt')
print('1 TF card / TF 卡\n2 Userdata image / userdata 镜像\n3 Independent internal partition / 独立内置分区\n4 Reinstall internal system / 重装独立分区\n5 Resume after Android reset / 重置后续装\n6 Update OpenWrt / 更新\n7 Boot OpenWrt / 启动 OpenWrt')
selected=input('Choose / 选择 [1]: ').strip() or '1'
if selected not in tuple(map(str,range(1,8))):raise ValueError('Invalid menu choice')
setattr(args,choices[int(selected)-1],True)
if args.update:return update(args,root)
return install(args,root,manifest)
if __name__=='__main__':
sys.exit(run_cli())
+87
View File
@@ -0,0 +1,87 @@
#!/bin/sh
# Desktop updates use the same lock, config migration and swap as mu300-update.
set -eu
payload=${1:?upload directory}
case "$payload" in /mnt/mu300-disk/.mu300-desktop-*) ;; *) exit 1 ;; esac
[ "$(dirname "$payload")" = /mnt/mu300-disk ]
token=${payload##*/}; token=${token#.mu300-desktop-}
case "$token" in ''|*[!0-9a-f]*) exit 1 ;; esac
[ "${#token}" = 12 ]
[ ! -L "$payload" ] && [ -d "$payload" ] && [ "$(id -u)" = 0 ]
linux=$(cat /run/mu300/linux-slot)
case "$linux" in a|b) ;; *) exit 1 ;; esac
misc=$(cat /run/mu300/misc-dev)
[ -b "$misc" ] && [ "$(stat -c %s "$payload/misc-linux.bin")" = 32 ]
boot=$payload/boot-desktop.img
[ "$(stat -c %s "$boot")" = 67108864 ]
read -r need inodes < "$payload/rootfs.requirements"
free=$(df -Pk /mnt/mu300-disk | awk 'END {print $4}')
[ "$free" -gt "$((need + 196608))" ] || { echo 'not enough free space to retain the old system'; exit 1; }
# A plain bind does not replicate live vendor /dev or /proc mounts.
view=$payload/plain-disk
mkdir "$view"
mount --bind /mnt/mu300-disk "$view"
trap 'umount "$view" 2>/dev/null || :' EXIT
export MU300_LIB=1 MU300_DISK=$view
. "$payload/mu300-update-library.sh"
unset MU300_LIB
mounted_disk
lock_take
trap 'lock_drop; umount "$view" 2>/dev/null || :' EXIT
dev=$(part_dev "boot_$linux")
[ -b "$dev" ] && [ "$(blockdev --getsize64 "$dev")" = 67108864 ]
backup=$DISK/boot/desktop-backup-$(date +%Y%m%d-%H%M%S)-$$
mkdir -p "$backup"
dd if="$dev" of="$backup/boot.img" bs=1048576 count=64
dd if="$misc" of="$backup/misc.bin" bs=1 skip=2048 count=32
[ "$(stat -c %s "$backup/boot.img")" = 67108864 ] && [ "$(stat -c %s "$backup/misc.bin")" = 32 ]
swapped=0 boot_changed=0 complete=0
finish() {
rc=$?
if [ "$complete" != 1 ]; then
if [ "$boot_changed" = 1 ]; then
dd if="$backup/boot.img" of="$dev" bs=1048576 conv=fsync || echo 'BOOT RESTORE FAILED'
dd if="$dev" of="$payload/restored-boot.img" bs=1048576 count=64
cmp -s "$backup/boot.img" "$payload/restored-boot.img" || echo 'BOOT RESTORE READBACK FAILED'
dd if="$backup/misc.bin" of="$misc" bs=1 seek=2048 conv=notrunc,fsync || echo 'MISC RESTORE FAILED'
fi
if [ "$swapped" = 1 ]; then
mv "$DISK/openwrt" "$DISK/openwrt.failed.$$" && mv "$DISK/openwrt.old" "$DISK/openwrt" || echo 'ROOT RESTORE FAILED'
fi
fi
lock_drop
# Never delete a directory that still holds the plain bind view: that
# would descend into the entire Linux disk. Failed runs retain their logs.
if umount "$view"; then
[ "$complete" != 1 ] || rm -rf "$payload"
else
echo 'plain update view still mounted; uploaded files retained'
fi
exit "$rc"
}
trap finish EXIT
trap 'exit 130' INT TERM HUP
STAGE=$payload
if ! apply_one openwrt desktop-local; then exit 1; fi
swapped=1
(cd "$DISK/openwrt" && sha256sum -c "$payload/rootfs-critical.sha256")
[ -s "$DISK/openwrt/lib/firmware/wcnmodem.bin" ] && [ -x "$DISK/openwrt/opt/mu300/android/vendor/bin/modem_control" ]
# Preserve the persistent log at 48 MiB and update the AVB footer separately.
head -c 50331648 "$boot" > "$payload/boot-head"
tail -c 64 "$boot" > "$payload/boot-footer"
boot_changed=1
dd if="$payload/boot-head" of="$dev" bs=1048576 conv=fsync
dd if="$payload/boot-footer" of="$dev" bs=1 seek=67108800 conv=notrunc,fsync
dd if="$dev" of="$payload/boot-readback" bs=1048576 count=48
dd if="$dev" of="$payload/footer-readback" bs=1 skip=67108800 count=64
cmp -s "$payload/boot-head" "$payload/boot-readback" && cmp -s "$payload/boot-footer" "$payload/footer-readback"
dd if="$payload/misc-linux.bin" of="$misc" bs=1 seek=2048 conv=notrunc,fsync
dd if="$misc" of="$payload/misc-check" bs=1 skip=2048 count=32
cmp -s "$payload/misc-check" "$payload/misc-linux.bin"
echo linux > "$DISK/openwrt/etc/mu300/default-boot"
echo 0 > "$DISK/.mu300/boot-tries"
echo openwrt > "$DISK/.mu300/boot-os"
sync
complete=1
echo 'UPDATE-COMPLETE; old system: openwrt.old; rebooting'
(sleep 3; reboot) </dev/null >/dev/null 2>&1 &
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""Keep original Magisk deployment code in payload/, with a thin entry wrapper."""
import argparse
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import shutil
TOP = Path(__file__).resolve().parents[1]
def sha(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for block in iter(lambda: f.read(1048576), b''): h.update(block)
return h.hexdigest()
def original_files(stage):
return {p.relative_to(stage).as_posix(): sha(p) for p in stage.rglob('*') if p.is_file()}
def assemble(stage, repair, kernel, exe=None):
stage = Path(stage)
if (stage/'desktop').exists(): raise ValueError('desktop already exists; use a clean Magisk staging tree')
before = original_files(stage)
for required in ('busybox', 'boot-linux.img', 'mu300-openwrt.tar.gz', 'payload.sha256'):
if required not in before: raise ValueError('missing original Magisk member: '+required)
layout={}
for name in before:
if name=='module.prop' or name.startswith('META-INF/'):
layout[name]=name
else:
target='payload/'+name
(stage/target).parent.mkdir(parents=True,exist_ok=True)
(stage/name).rename(stage/target)
layout[name]=target
# Magisk still enters at customize.sh. Its deployment script remains
# unchanged, executing with MODPATH pointing at its relocated payload.
(stage/'customize.sh').write_text('''#!/system/bin/sh
MU300_DEPLOY_ROOT=$MODPATH
MODPATH=$MU300_DEPLOY_ROOT/payload
. "$MODPATH/customize.sh"
MODPATH=$MU300_DEPLOY_ROOT
unset MU300_DEPLOY_ROOT
''',newline='\n')
dest = stage/'desktop'; assets = dest/'files/boot'; assets.mkdir(parents=True)
for n in ('installer.py', 'boot_image.py', 'android-image.sh', 'android-write-part.sh', 'android-write-free.sh', 'android-loop.sh', 'local-update.sh', 'configure.sh', 'PORT-SOURCES.json'):
shutil.copyfile(TOP/'desktop'/n, dest/n)
# Desktop fixes must apply even when augmenting an older Magisk archive;
# its original scripts stay byte-for-byte unchanged.
shutil.copyfile(TOP/'tools/android-bootchain.sh', dest/'android-bootchain.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)
shutil.copyfile(TOP/'boot/init', assets/'original-init')
shutil.copyfile(TOP/'boot/build-boot-image.py', assets/'build-boot-image.py')
shutil.copyfile(TOP/'rootfs/overlay/opt/mu300/bin/mu300-update', dest/'mu300-update-library.sh')
spec=importlib.util.spec_from_file_location('repair_prepare',TOP/'desktop/prepare-tools.py')
mod=importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
(assets/'repair').mkdir(); mod.prepare(Path(repair),assets/'repair')
(stage/'docs').mkdir()
shutil.copyfile(TOP/'desktop/README.md',stage/'docs/DESKTOP-INSTALL.md')
shutil.copyfile(TOP/'desktop/installer.py',stage/'OpenWrt-Installer.py')
# Python source runs from the archive root, so resolve its support files there.
if exe:
fingerprint=json.loads(Path(str(exe)+'.json').read_text())
current={n:sha(TOP/'desktop'/n) for n in ('installer.py','boot_image.py')}
if fingerprint['source'] != current: raise ValueError('desktop EXE is stale; rebuild it')
shutil.copyfile(exe,stage/'OpenWrt-Installer.exe')
actions={'start-installer':'','install-to-tf-card':'--tf','install-to-internal-storage':'--part',
'install-to-userdata-image':'--data','reinstall-internal-system':'--reinstall-part',
'resume-internal-install':'--resume','switch-to-openwrt':'--boot-openwrt','update-openwrt':'--update'}
launchers=stage/'launchers';launchers.mkdir()
for name,flags in actions.items():
cmd='@echo off\r\ncd /d "%~dp0.."\r\nif exist "OpenWrt-Installer.exe" (\r\n "OpenWrt-Installer.exe" '+flags+' --no-pause %*\r\n) else (\r\n py -3 "OpenWrt-Installer.py" '+flags+' --no-pause %*\r\n)\r\npause\r\n'
(launchers/(name+'.cmd')).write_bytes(cmd.encode())
(launchers/(name+'.sh')).write_text('#!/bin/sh\ncd "$(dirname "$0")/.." || exit 1\nexec python3 OpenWrt-Installer.py '+flags+' "$@"\n',newline='\n')
(launchers/(name+'.sh')).chmod(0o755)
adb_dir=os.environ.get('MU300_DESKTOP_ADB_DIR')
if adb_dir:
(stage/'tools').mkdir(exist_ok=True)
for n in ('adb.exe','AdbWinApi.dll','AdbWinUsbApi.dll'):
shutil.copyfile(Path(adb_dir)/n,stage/'tools'/n)
after={n:sha(stage/layout[n]) for n in before}
if after!=before: raise ValueError('original Magisk payload changed')
relocated={layout[n]:h for n,h in before.items()}
manifest={'format':2,'kernel':kernel,'magisk':relocated,'magisk_layout':layout,
'desktop':{p.relative_to(stage).as_posix():sha(p) for p in stage.rglob('*') if p.is_file() and p.relative_to(stage).as_posix() not in relocated},
'source':{n:sha(TOP/'desktop'/n) for n in ('installer.py','boot_image.py')}}
(dest/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
return manifest
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--stage',type=Path,required=True);p.add_argument('--tools',type=Path,required=True)
p.add_argument('--kernel',choices=('6.18','7.2'),required=True);p.add_argument('--exe',type=Path)
a=p.parse_args();assemble(a.stage,a.tools,a.kernel,a.exe)
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Build the desktop-only ARM64 maintenance bundle; never install it into Magisk's rootfs."""
import argparse
import hashlib
import json
from pathlib import Path
import shutil
import struct
FILES=('sbin/fsck.f2fs','sbin/resize.f2fs','lib/ld-musl-aarch64.so.1','lib/libf2fs.so.10',
'lib/libuuid.so.1','lib/libgcc_s.so.1','usr/bin/ucode','lib/libucode.so.20230711',
'lib/libjson-c.so.5','usr/lib/ucode/fs.so','usr/sbin/resize2fs','usr/sbin/e2fsck',
'lib/libe2p.so.2','lib/libext2fs.so.2','lib/libcom_err.so.0','lib/libblkid.so.1')
def prepare(source,out):
hashes={}
for name in FILES:
choices=[source/name,source/'usr'/name]
if name=='sbin/resize.f2fs':choices.append(source/'sbin/fsck.f2fs')
found=next((p for p in choices if p.is_file()),None)
if found is None:raise ValueError('missing ARM64 maintenance file: '+name)
data=found.read_bytes()
if data[:6]!=b'\x7fELF\x02\x01' or struct.unpack_from('<H',data,18)[0]!=183:raise ValueError('not ARM64 ELF: '+name)
target=out/name;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data);target.chmod(0o755)
hashes[name]=hashlib.sha256(data).hexdigest()
(out/'manifest.json').write_text(json.dumps({'sha256':hashes},indent=2)+'\n')
return hashes
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--root',type=Path,required=True);p.add_argument('--out',type=Path,required=True)
a=p.parse_args();prepare(a.root,a.out)
+196
View File
@@ -0,0 +1,196 @@
# MU300 双用途安装包移植记录(2026-10-13)
## 范围
把 E5 桌面部署方案迁入 MU300 仓库。ZIP 既可以直接交给 Magisk
执行原 TF 部署,也可以解压后运行英文命名的 Windows/Unix 入口。
MU300 的 `/openwrt` 容器布局、A/B 启动控制和原生更新机制均保留。
没有移植屏幕程序、E5/T551M/M8 驱动或它们的启动镜像。
原 Magisk 的部署脚本、安装 worker、启动链同步、内核、TF init
和原始校验文件内容保留。新版混合包将原部署文件移入 `payload/`,
顶层 `customize.sh` 设置对应 MODPATH 后执行原脚本,再恢复 MODPATH;
仅改变文件位置,部署步骤不变。
`MU300_DESKTOP_INSTALLER=0` 仍然可以生成原来的纯 Magisk 包。
桌面 TF 自定义项使用上传到手机的私有脚本副本,不改原包成员。
## 入口
| 文件名(Windows `.cmd`,Unix `.sh`) | 功能 |
| --- | --- |
| start-installer | 选择部署方式 |
| install-to-tf-card | TF 安装,复用原 worker 的释放挂载、格式化、校验及写 boot 顺序 |
| install-to-userdata-image | 未加密 userdata 内创建指定大小的 ext4 镜像,保留已有镜像备份 |
| install-to-internal-storage | 离线缩小 userdata,建立 `mu300root` 独立分区 |
| reinstall-internal-system | 重装已有独立 OpenWrt 分区 |
| resume-internal-install | Android 格式化完成后的第二阶段续装 |
| switch-to-openwrt | 选择已安装的 Linux 启动槽,完成后手动重启 |
| update-openwrt | 电脑发起 SSH 上传,保配置和容量更新,成功后重启 |
Windows 有 EXE 时直接运行,否则使用 Python。可随包加入 adb.exe
及两个 DLL;Linux/macOS 使用 Python 和系统 adb。多个 Android 在线时
必须显式给 `--serial`,设备模型只接受 MU300/F50/U30Air。
`--check` 检查包;`--check-boot` 在电脑上构造启动镜像,不访问设备。
## userdata 安装
未加密的 F2FS/ext4 默认保数据,也可以明确选择格式化。
先检查完整载荷、GPT 两份表及分配计划,再离线检查和缩小文件系统;
文件系统缩小成功后才更改 GPT。完整写入镜像、回读验证,再离线扩容
到整个分区并核对超级块容量,避免用户选了 10 GiB 却只有 2 GiB。
失败停在安装环境保留日志,不用自动重启掩盖错误。
FBE/FDE 必须走格式化两阶段:
1. 电脑保存 boot、misc、两份完整 GPT 和两槽 BSP 五分区备份,建立
CID/序列号/槽位/几何位置绑定的续装记录。
2. 桌面启动镜像的 ramdisk 携带工具和准备请求;不从加密 `/data`
读取安装载荷。建立独立分区后,请原厂 recovery 格式化缩小的 userdata。
3. 用户完成新 Android 设置、重新启用 USB 调试并恢复/授权 su,运行续装入口。
4. 核对设备、Android 槽、userdata 和 root 几何位置,以及独立分区里的
准备 token。再从当前 Android 提取固件/运行库,构建、写入、校验
并扩容独立系统,最后写另一个 boot 槽并选择 Linux。
续装记录和备份默认在电脑 `~/mu300-backups`。userdata 内镜像法明确
拒绝加密数据;不尝试在 initramfs 解密 Android 数据。
GPT 备份按真实表项数量计算长度,支持超过 128 项的表,不固定只备份 34 扇区。
## 启动及进度
桌面启动镜像在原 MU300 boot 后追加 LZ4/CPIO 段,内核和
`loglevel=5` 启动标记不变;目标模式、准备请求和维护工具放在 ramdisk,
不依赖可能被 `CONFIG_CMDLINE_FORCE` 忽略的额外启动参数。
A/B 控制块从目标机现场 32 字节生成,保留 OEM 字节、重新计算 CRC。
镜像必须在 48 MiB 持久日志区之前结束。
离线步骤每两秒显示真实阶段和耗时;复制时显示实际字节进度。
该次 initramfs 同时提供只读进度:F50/MU300 的
`http://192.168.77.1:8089/progress.txt`,U30Air 的 `192.168.78.1`。
失败状态立即更新,进系统后没有常驻进度轮询服务。
## 更新
电脑经认证 SSH 上传,不要求设备反向访问 Windows HTTP 服务,
避免入站防火墙造成的 `Operation not permitted`。
用原生 `mu300-update` 的同一互斥锁、配置/账号/用户软件包迁移和
目录切换逻辑;新系统检查成功才更换 boot 并选择 Linux。
保留 `openwrt.old`,失败时尝试恢复旧 root、boot 和 misc。
包内只携带一份 `mu300-openwrt.tar.gz`,不再打入第二份 `desktop/files/rootfs.tar.gz`。
桌面内置安装和 SSH 更新在电脑临时生成公共 tar,上传成功或失败后均清理临时文件;
原 Magisk/TF 流程继续直接使用原包。公共 tar 排除构建机的 Android 运行库和专有固件;这些文件从
已安装系统迁移。使用非递归 bind 视图避开活动的 vendor `/dev`、`/proc`
等挂载,避免复制实时设备节点。boot 更新保留 48 MiB 的持久日志区域,
单独更新 AVB footer。成功清理上传目录前必须卸载 bind 视图。
传统原始 eMMC 空闲区域布局由原生 updater 继续处理,桌面更新不猜布局。
## 验证
- 新桌面回归 13 项:FBE 判断、尺寸、GPT 备份范围、A/B CRC/OEM 字节、
错设备续装拒绝、字符串转义、固件来源隔离、boot 重打包和真实原生更新事务。
- 原 TF 回归 19 项;启动链回归 32 项(dash/bash/sh);原更新和锁回归 17 项;
用户软件包回归 34 项。合计 115 项通过。
- 宿主 BusyBox 的独立 applet 查找会绕过启动链测试的假 `dd`,导致该组
故障注入断言失败;没有为让测试通过而改动原启动链。其他列出的测试正常通过。
- 6.18 和 7.2 双用途 ZIP 的 CRC、文件 SHA256 和原 Magisk 18 个成员逐项核对通过。
- 两套包实际运行 Python 和冻结 EXE 的 `--check-boot`;从含空格目录运行
CMD 入口通过。全程无设备写入。
预览包在 `work/desktop-preview/*-20261013-r2.zip`,详细哈希在同目录
`VALIDATION.json`。它们使用已有的 `20261012-2afe136` 运行时包,
不是最新固件全量重编结果。新构建脚本已接上双用途组装。
**MU300 实机缩容、原厂 recovery 重置/续装、完整部署后的重启和更新仍待验证。**
### 2026-10-14:共用一份 rootfs
最新预览包为 `work/desktop-preview/*-20261014-single-rootfs.zip`,
SHA256 和核验结果见同目录 `SINGLE-ROOTFS-VALIDATION.json`。
每包仅含一份 `mu300-openwrt.tar.gz`;原来的 18 个 Magisk 成员逐项校验保持一致。
| 内核系列 | 去重前 | 去重后 | 减少 |
| --- | ---: | ---: | ---: |
| 6.18 | 165.85 MiB | 103.05 MiB | 62.80 MiB |
| 7.2 | 166.47 MiB | 103.61 MiB | 62.86 MiB |
Windows、WSL 分别通过 17 项桌面测试,覆盖 TF 原包复用、内置安装临时过滤、
上传失败清理、更新保留本机固件,以及包内不产生第二份 tar。
两套包的 Python 和冻结 EXE 都通过 `--check-boot`、`--check-rootfs`,
实际临时过滤约 9–10 秒,过程中显示进度,整个检查没有设备写入。
这些仍为历史运行时的安装器预览包,不是重新编译的完整新固件。
### 2026-10-14:Android loop 与续装修复
续装修复包在 `work/desktop-preview/*-20261014-resume-fix.zip`,
报告为同目录 `RESUME-FIX-VALIDATION.json`。仍只携带一份 rootfs,
原 18 个 Magisk 文件保持一致;两套包均通过 Python/EXE 的 boot 和 rootfs 检查。
Windows/WSL 各通过 21 项测试,新增 Android loop 路径解析、可见 Wi-Fi 密码、
ADB reboot 调用以及空错误诊断覆盖。
V50 上已验证实际镜像挂载、完整临时镜像构建和只读复验,现有 8 GiB 分区可继续续装。
第一阶段完成后遇到此问题不需重新缩容。用户当前旧包已做代码修补和经核验的
本地续装绑定更新,旧文件及记录已备份;不要直接换另一份包绕过原记录校验。
### 2026-10-14:修复版续装兼容和精简目录
新包为 `work/desktop-preview/*-20261014-clean-layout.zip`,核验结果见
`CLEAN-LAYOUT-VALIDATION.json`。顶层只保留四个文件:
`OpenWrt-Installer.exe`、`OpenWrt-Installer.py`、`module.prop`、`customize.sh`。
部署载荷放在 `payload/`,快捷入口在 `launchers/`,说明在 `docs/`,
桌面程序资产与 ADB 分别在 `desktop/`、`tools/`。
18 个原部署文件逐项核验内容不变,Magisk 薄入口的 MODPATH 切换/恢复已通过测试。
续装不再要求整个安装器清单逐字节相同,而是比较独立的关键载荷身份:
原 boot、rootfs、关键文件校验表、容量要求、BusyBox、所有文件系统工具及内核系列。
路径搬迁、EXE、输入提示或说明的更改不会改变该身份;系统/内核/工具变化会拒绝。
设备、槽位、分区起点/容量和设备上的准备令牌检查保持原样。
旧记录必须先找回其绑定哈希完全一致的清单,才能推导关键载荷身份,
不能只因同为 7.2 或同机型就放行。当前 V50 原目录已删除,
已利用保留的原清单与修补版文件哈希重建那份清单,验证 SHA256 完全等于
旧记录绑定值,并保存为备份目录中的 `package-manifest.json`。
新版 EXE 对旧记录进行只读续装预检,通过 8.00 GiB 分区、身份、令牌及载荷校验。
没有再次缩容或写独立分区。
新记录同时保存关键载荷身份、源目录及 `package-manifest.json`,
无需长期保留解压目录;记录及备份全部遗失时仍需人工核对恢复,当前没有自动恢复入口。
兼容检查现在先于 rootfs 准备/上传,失败不再白等压缩和传输。
FBE 第一阶段只上传准备工具,不再上传暂时不使用的完整 rootfs。
Windows、WSL 各通过 23 项测试;两套新包通过清单、顶层目录、
Python/EXE boot 构建、实际临时 rootfs 生成及含空格路径的 CMD 入口检查。
### 2026-10-14:优先使用 eMMC 未分配空间
此前新独立分区路径直接按 userdata 大小计算缩容,未查看它后面的 GPT 空闲区。
V50 实机读取显示约 58.25 GiB 总容量;现有 userdata 与 8 GiB OpenWrt 之后
仍有约 32.39 GiB 未分配空间,原安装不必为这 8 GiB 重置 Android。
新流程先校验两份 GPT 的头/表 CRC、边界、分区重叠及可用表项,测量连续对齐空闲区。
能放下所选容量时,使用有 offset/size limit 的原生 Android loop 写系统,
扩容并校验文件、文件系统后再提交 GPT,回读两份副本,最后写 boot 和切槽。
不会在 Android 使用 userdata 时执行整盘重读分区表;新节点在重启后出现。
检测到已知原始偏移的旧 ext4/F2FS 系统会排除相应空闲区。
该路径适用于 FBE/FDE,保持 userdata 大小及数据不变。
只在无足够连续空间时才进入原缩容/重置流程。TF/Magisk 路径保持不变。
已有 `mu300root` 仍要求重装/更新;未知或冲突 GPT 不静默修正。
安装中再次比对原始 GPT 快照,有变化即停止,boot 尚未修改。
新增 GPT/FBE/失败阻断 5 项测试,以及 opt-in Linux root 稀疏文件测试 3 项:
真实 ext4 写入/扩容/校验、错文件不提交 GPT、GPT 中途变化不写空闲区。
后者只作用于临时虚拟磁盘,不访问用户硬盘。27 项既有桌面测试也通过。
新路径目前只有实机只读探测及虚拟磁盘执行验证;没有在现有 V50 再建分区。
历史补充 ZIP 未重打;新版源文件、EXE 需在下次组装时一并纳入校验清单。
## 来源及维护
四个 E5 来源文件的输入 SHA256 记在 `desktop/PORT-SOURCES.json`。
移植后的脚本改用 MU300 名称、容器路径、动态槽位和原生启动确认。
维护工具只要求通用 ARM64 musl 文件,通过 `MU300_DESKTOP_TOOLS` 输入;
代码不依赖 E5 仓库路径。Windows EXE 检查源文件指纹,编译中源码变化
或打包时 EXE 过期都会拒绝。
主要实现:`desktop/installer.py`、`boot_image.py`、`boot/`、
`android-image.sh`、`android-write-part.sh`、`android-write-free.sh`、`local-update.sh`。
组装:`desktop/package.py`、`tools/add-desktop-installer.py`。
验证:`tools/verify-desktop-installer.py`、`tests/test_desktop_installer.py`。
+131
View File
@@ -0,0 +1,131 @@
# 双卡、默认启动提示与 eMMC 调查(2026-10-14)
本轮完成公共代码修正和离线回归,MU300/V50 的网页部分已热部署,后续 E5 也已完成用户态热部署。
后续已按用户要求撤销运行时禁休眠及 `CLK_AUTO` 禁用,当前策略以下文第 3 节为准。
**混合物联卡导致“无模组”的完整原因、V50 旧元数据损坏的唯一底层原因仍未确认。**
已修复能从代码证明的缺陷;以下明确区分这些修复与仍待实机验证的症状。
## 1. E5 仓库的双卡短信隔离
用户报告:物联卡与普通卡混插,不论卡槽顺序均可能异常;双卡收短信后也有人遇到无网、无模组。
这次连接的实机是 V50,并没有取得上述故障组合的 E5/T551M/M8 日志,不能声称已经复现和根治。
找到的明确缺陷是短信存储索引缺少卡槽归属:
- `+CMTI: "SM",<index>` 没有 SIM 编号。
- 当前接收器已记录:在本平台通过主命令口配置 CNMI,两张卡的 CMTI 可能到达同一个 URC 环;环号不能可靠证明短信来自哪张卡。
- 通用 ModemManager 接收 CMTI 后,直接按该索引发无卡号 CMGR,读取的是当前数据卡的存储。
- 另一条公共接收链路 `e5-sms-receive` 则逐卡查询 CCID、CMGL,并分别持久化、合并分段和转发。两条链路因此可能重复读取,甚至读取另一张卡的同号索引。
新增 `rootfs/deb-patches/modemmanager-15-unisoc-sms-isolation.patch`:
1. 安装了公共双卡接收器时,禁止通用 CMTI 回调进行无卡号索引读取。内核的 `sms_events` 与逐卡接收器继续负责接收;原有 CNMI、状态报告及短信发送保留。
2. 未安装公共接收器的系统保留原回调,不直接取消短信接收能力。
3. 通过 MM 执行的卡槽限定短信查询、删除和设置,在成功或 CMS/CME 失败后,都先恢复数据卡的 AT 通道上下文,再返回结果。
4. CMGS/CMGW 的提示符与 PDU 事务不拆分。这项修正不执行 RF 重启或切换数据卡。
缺少 IMS 承载不应单独被视为模块消失。已核对现有 CSCA 查询/回写失败会按非致命结果继续;IMS PDN 的 vendor URC 已有过滤,通用 CGEV 对带 CID 的去激活也按 CID 匹配。
目前没有证据证明 IoT 卡缺少 IMS 就是混插失败的根因,因此没有新增一律关闭 IMS 的策略,也没有把混插与收短信的两种故障判为同一原因。
公共 OpenWrt 包已构建为 `modemmanager-1.24.0-r928.apk`;Debian 构建也通过编号补丁通配列表纳入同一修正。
后续 E5 已部署 MM r928 并确认 Unisoc 插件、CMTI 隔离回调和双卡接收器运行。
对 SIM1/SIM2 分别执行 CNMI 查询后,实际 AT 上下文均恢复到原数据卡 SIM1。
T551M/M8 尚未部署;混合卡、实际来短信及通话的验收仍未完成,不能据此宣称原始故障已根治。
## 2. 两个仓库的临时启动提示
公共看板首页新增提示:当前为临时启动 OpenWrt,是否设为默认启动。E5 仓库的共享屏幕主页也显示相同提示,覆盖 E5、T551M、M8。
- 状态读取各自的 `default-boot` 文件,区别于“当前正在运行哪个 A/B 槽”。没有保存选择时按原有 Android 回退语义提示;非法配置返回 unknown,不伪造确定结果。
- 缺少启动控制素材、受限制的试用镜像禁用设置按钮,并显示原因。
- 网页使用现有主题确认框,补齐中、英、土耳其语。屏幕采用中英文字和二次点按确认,锁屏、息屏时不能触发。
- 用户确认后修改默认启动,不立即重启或切网。下次状态刷新反映保存结果,不增加状态轮询或 AT 请求。
- `boot-status` 在看板进程内以 shell builtin 读取,不读取整份 misc,不启动额外常驻进程。
顺带修正启动控制的写入事务:旧代码先保存 Linux 意图,再写 misc;后者失败会留下错误的默认状态。
现在先暂存配置、备份原 32 字节控制信息,校验写入长度和 misc 回读,成功后再替换配置。
失败时恢复原控制信息和配置;设置与成功启动后的 rearm 使用同一互斥锁,避免互相覆盖。
V50 已部署 6 个相关文件并核对 SHA256。实机独立 `boot-status` 与 `dashboard-info.boot` 均返回:
`default=linux, temporary=false, can_set_default=true`。部署没有改动其启动选择或重启设备。
后续 E5 的网页和屏幕也已部署,二者均正确返回默认 Linux、非临时启动;T551M/M8 尚未部署。
## 3. 公共 eMMC 保护(运行时常驻已撤销)
E5 入口:`devices/common/emmc.py`;MU300 入口:`upstream/port/emmc.py`。两份实现一致。
- 识别非可移除的 MMC 内存宿主,排除 NO_MMC、Wi-Fi SDIO 与 TF/SD 宿主。
- 已撤销宿主 `pm_runtime_forbid`、aggressive PM 能力清除及 runtime 回调直接返回;恢复原有 autosuspend、时钟和 PHY 休眠/恢复路径。
- 已撤销内外 `CLK_AUTO` 禁用,恢复原有空闲自动时钟门控,避免留下运行时常驻的耗电代价。
- 系统休眠保护移入专用的 `mmc_suspend()` 回调:活动 eMMC 先刷缓存再保持卡状态;本来已运行时休眠的卡保持原状态。
- `_mmc_suspend()` 不再包含共用的提前返回,aggressive runtime suspend 能正常执行原有卡休眠/断电。
- 正常关机、驱动移除和欠压处理保留原路径;TF、SDIO 不套用 eMMC 保护条件。
- 清理此前公共常驻及旧 V50/AW9523B 常驻代码,重复处理缓存树不会重新引入禁休眠。
已接入 E5、T551M、M8 的 prepare-kernel,以及公共 Docker/native 构建入口。MU300 的公共 port/install 同样必经此策略。后续机型沿这些公共入口构建即会继承;源码锚点或能力位冲突时构建停止,避免静默遗漏。
另补齐可靠写兼容:E5 已设置 `MMC_CAP2_NO_REL_WR`,MU300 原先没有。新的公共处理让块层以普通写入加缓存刷新的方式实现 FUA 持久化,不直接丢掉 FUA,也不关闭写缓存。
这是一项从 E5 既有路径对齐的兼容保护,不是证明 V50 损坏由 FUA 单独造成。
当前三套最终构建已通过:E5 主线 6.18 的 T551M 配置、MU300 6.18.54、MU300 7.2.8,均构建 Image 和匹配 modules。
E5/M8 的板级完整内核与三个安装包没有在本轮重新打包;新策略未刷入实机。
V50 当前运行的旧 `#17` 仅验证了此前宿主 runtime PM 禁用策略,不能用其正常结果冒充新完整策略的验收。
本次撤销仅修改源码、已准备的构建树和离线构建,没有向实机写入内核或修改 sysfs。
因此 V50 仍运行旧 `#17` 的宿主常驻策略,要改变实机行为仍需部署重新构建的内核。
没有新增轮询,未测量待机电流,也不能保证剩余保护解决所有硬件写入问题。
## 4. V50 inode 不一致:确认到哪一步
历史日志在启动约 9 秒出现 `ext4_lookup: deleted inode referenced`,之后重复报告 49541–49547 等新写入 inode。
目录仍指向这些 inode,但 inode 内容已无效/删除;这说明目录与 inode 元数据版本不一致,而不是“查看目录”的程序删掉了文件。
之前同步后正常重启仍出现新脚本丢失、配置回退,离线 fsck 后也曾复发:fsck 能修现有结构,不能证明底层持久化问题已经解决。
本轮重新只读核对:
| 检查 | 结果 | 能说明什么 |
|---|---|---|
| 根分区 p76 | 起始 37441536 扇区,长度 16777216 扇区 | 与先前通过 CRC 的 GPT 布局一致 |
| EXT4 超级块 | 2097152 × 4096 = 8589934592 字节 | 文件系统正好 8 GiB,与分区相等,无文件系统越界证据 |
| 文件系统 | 直接挂载 p76,带 journal | 不依赖 F2FS userdata 或 loop 镜像 |
| 运行时 PM | 宿主 on/active | 旧 #17 的防自动休眠已生效 |
| 总线 | HS400 enhanced strobe、200 MHz、8 bit | 稳定观察时没有通过降到 HS200 规避问题 |
| 错误计数 | 0,观察时约开机 3548 秒 | 此观察窗口未见新的 EXT4 结构错误 |
| 写缓存/FUA | write back、FUA=1 | 实机仍是新兼容保护部署前的路径 |
此前还确认:已休眠后在 initramfs 设置 `power/control=on` 的恢复实验卡在挂载/fsck 之前;改为 probe 阶段提前禁止休眠后,写入、配置和 SHA256 在正常重启后保留。
这支持宿主恢复链存在问题,但不是某条写请求丢失的完整因果跟踪。
MM/HSQ 的请求路径会通过 `mmc_get_card`/host claim 持有 PM 引用,未发现“request_atomic 没单独取 PM 引用,因此必然在传输中休眠”的简单漏洞,不能拿它作为根因。
现有证据更符合重启前后的元数据持久化/恢复异常;宿主恢复、可靠写及硬件门控是已处理的风险路径。
尚缺失败时的数据块、journal 提交/刷缓存与宿主恢复关联记录,无法区分具体的恢复故障、写顺序/持久化错误或其他存储问题。
**目前不能声称找到了唯一底层根因,也不能保证不会复发。**
### 与 M8 旧问题区分
- M8 内置铃声损坏:已有逐字节证据是构建时把二进制 CRLF 转成 LF;不是 inode 错误的证据。
- 本次找到的旧 EXT4 aborted journal 记录来自 T551M 的 loop 镜像:先发生底层 F2FS SSA/SIT 不一致,随后 loop 写入 I/O 错误和 journal abort。这条因果链与 V50 直接 p76 的现象不同。
- 未在现存 M8 日志找到同样的 deleted-inode 首次故障,不能凭表面相似认定是同一个 bug。
## 5. 验证记录与剩余工作
- 真实启动脚本在临时文件设备上的 9 项测试通过:成功写入、短控制块拒绝、写失败保留配置、配置替换失败回退 misc、临时/持久/unknown/试用状态。
- 实际 MM 回调经过 host C 编译执行:两种数据卡顺序、CMS 错误、恢复失败、避免拆分 PDU 提示符;有/无接收器和父类设置失败的 CMTI 行为通过。
- 短信现有 19 项及分段 14 项回归通过;MM 构建中的通话、SIM 上电和移动重连检查通过。
- Chromium 验证两个 LuCI 页面及实际 staged 屏幕:取消不请求、确认一次请求、保存失败仍提示、限制状态禁用、持久/unknown 隐藏;现有屏幕设置同步回归通过。
- staged ucode API/settings 编译通过;三套内核最终 Image/modules 编译通过;公共内核策略的 fresh、重复应用和 V50 缓存迁移回归通过。
尚待:混合物联卡组合和双卡短信的实机验证;T551M/M8 的新 MM 部署、三个有屏机型的新内核部署;V50 新完整策略下跨重启持久化与长期观察、实际待机功耗测量。
本轮未修改 NV、未重新分区,也未提交或推送代码。MU300 原有桌面安装器和 V50 适配的未提交改动均保留。
### E5 后续热部署结果
用户接入 E5 后核实 `profile=e5`、原内核 `6.18.54-e5-mobile4-g020b970e351e-dirty`,
升级 MM/rpcd APK 至 r928,部署并回读校验 25 个程序及界面文件,保留 E5 屏幕标记与用户配置。
回退备份位于实机 `/root/update-backups/dual-boot-20261014-154323`。
MM 状态 connected、WAN up、热点 ENABLED、屏幕浏览器及双卡短信接收器运行;
通过蜂窝接口测试外网 ICMP 3 发 3 收。跨卡只读查询后的 AT 上下文恢复验证通过。
默认启动仍为原来的 Linux,没有切槽、重启系统或更新内核。
eMMC 宿主实际为 `power/control=auto`、`runtime_status=suspended`,没有强制常驻;
EXT4 错误计数 0。新系统休眠/FUA 内核改动仍待后续内核部署。
+28
View File
@@ -1907,3 +1907,31 @@ down 后复查 disabled,避免恢复期间用户关闭 Wi-Fi 仍被重新打
34 项 RX/TX/WCN/蜂窝相关测试通过,全部 5.4 Wi-Fi 补丁从原始厂商源码
实际应用成功。未部署 MU300 实机,不能把 T551M 的现场结果当作 MU300
验证。详见 [Wi-Fi 对齐记录](WIFI-FORWARDING-20261013.zh-CN.md)。
## 2026-10-14:公共 eMMC 策略与默认启动提示
旧 V50/AW9523B 门槛改为公共非可移除 eMMC 策略,禁用 runtime/system sleep、
内外 CLK_AUTO,并按 E5 既有路径以刷缓存实现 FUA 持久化。TF/SDIO 保留原策略。
6.18.54 与 7.2.8 的最终 Image/modules 编译通过;新完整策略尚未刷入实机。
看板按保存的启动意图提示临时 OpenWrt,用户确认后设置默认,不立即重启。
启动控制写入加入校验、失败回退和 rearm 互斥。V50 已热更新并正确显示默认 Linux。
V50 当前 p76 的 EXT4 8 GiB 与分区长度一致,旧 #17 宿主 on/active、错误计数 0。
旧 inode 不一致属于元数据版本不一致,不能把 fsck、短时稳定或 runtime PM 关联
当作唯一底层根因。M8 的已确认铃声损坏原因也不能混作 inode 故障证据。
详见 [两仓库报告](DUAL-SIM-BOOT-EMMC-20261014.zh-CN.md)。
后续按用户要求撤销公共 eMMC 运行时常驻和 CLK_AUTO 禁用,恢复原有运行时省电。
系统休眠保护改为专用回调,FUA 兼容保留;构建缓存一并迁移。实机仍运行旧 #17,
本次未刷内核或切换运行时 sysfs 策略。
### 2026-10-14:F50 / V50 共用固件的机型隔离
旧 `install.sh` 会把 V50 当成未识别设备,用户确认后写入 f50 标记;
initramfs 又优先相信该标记。现与桌面安装器对齐 V50/MU3351/ums9620 校验,
启动和运行时均以本机设备树为准。跨机恢复配置在 AT 服务启动前纠正卡槽及映射,
同机型自定义设置与短信/流量/APN 数据保留。网页灯控仍按实际 LED 节点隔离。
V50 更新要求包明确支持,主线包和共用 TF 包检查内置 AW9523B 支持。
详见 [V50 记录](V50-MU3351-20261014.zh-CN.md#f50--v50-共用固件的机型隔离)。
本轮仅修改代码与回归验证,未重新编译、打包或刷机。
+247
View File
@@ -0,0 +1,247 @@
# V50 / MU3351 适配记录
## 实机与 F50 对比
2026-10-14 对已连接 V50 做只读检查。产品名 `V50`、设备名 `MU3351`、
SoC T760、平台 `ums9620`、板名 `ums9620_2h10_feimao`,和 F50 属同一内核平台。
三簇 CPU 的频率候选与已有 F50 原厂表一致;无线侧也是 PCIe SC2355,
WCN、WLAN、蓝牙驱动属于同一家族。A/B 分区命名相同。
ZTE [官方支持页](https://www.ztedevices.com/cn/supports/v50/)将 V50 标为 MU3351,
不能和 Blade V50 手机混淆。
- 灯由 I2C3 地址 `0x5b` 的 AW9523B 驱动,F50 的参考 DT 不含此控制器。
V50 同时暴露 `aw_led/red/green/blue` 和 `sc27xx:*`,旧脚本优先选择 PMIC,
因此并不是仅把名字加进白名单即可完成灯光适配。
- 这台 Android 13 的 userdata 是 FBE(`encrypted` / `file`)。
GPT 空闲区域足够时无需缩容或重置;只有必须从 userdata 腾出空间时,
才走清空 userdata、Android 初始化、重新授权 root、续装流程。
这是本机当前状态,不能据此推断所有 V50 或 F50 的加密方式。
- 本轮未检测到插入的 TF 卡,不能因此断言机器没有 TF 卡槽。
- 厂商固件和 Android 运行库仍从安装目标本机提取,不能替换成 F50 的文件。
最初探测阶段仅只读。后续已部署 V50 内核和公共脚本、离线修复 OpenWrt ext4,
写入 Linux B 槽及 misc 的 32 字节启动控制;没有格式化 Android userdata、
更改 GPT、写 Android A 槽或 NV。相同平台不代表所有功能均已实物验证。
## 实现
桌面安装器只接受精确的 `V50` + `MU3351` + `ums9620` 组合;
公共启动链检查与切换模块同步支持,两份 bootchain 脚本保持一致。
initramfs 和运行时依据实际 AW9523B 节点识别为 `v50`,沿用 F50 的核心模块和
`192.168.77.1` LAN 地址。运行时更新允许使用共同内核平台的包。
补入 `CONFIG_LEDS_AW9523B=y` 和 LED 专用驱动,兼容原厂 DT:
仅绑定 `awinic,aw9523b`、`led_enable=1`、`gpio_enable=0`;
验证引脚组、亮度上限和芯片 ID 后初始化。亮度变更使用同步 I2C 写入,
不增加轮询、IRQ 或常驻动画线程,卸载与关机熄灭通道。
这是 6.18/7.2 的新源码,不是把 Android 5.4 ko 强行加载到新内核。
已逆向 Android `aw9523b_brightness_work`(`0x3424`)确认:
`idx` 是 GPIO 引脚编号,并非 DIM 寄存器直接下标。
P0_0–7 对应 `0x24–0x2b`;P1_0–3 对应 `0x20–0x23`;P1_4–7 对应 `0x2c–0x2f`。
`aw9523b_set_led_imax`(`0x35ec`)只使用 DT `default_imax` 的低两位。
保留原厂绿组上限 80、红/蓝/全灯组上限 120。
已进一步逆向原厂 `groupcolor_store`,并结合用户的单组点灯确认修正映射。
原厂 `green` 组实际是白光,不能用 RGB 混色代替;有独立 NET1、NET2、Wi-Fi 灯:
| 灯 | 白色引脚 | 蓝色引脚 | 红色引脚 |
| --- | --- | --- | --- |
| NET1 | 8、11 | 9、12 | 10、13 |
| NET2 | 14、1 | 15、2 | 0、3 |
| Wi-Fi | 4、5 | 6 | 7 |
驱动保留原厂组接口,另提供 `v50:net1:*`、`v50:net2:*`、`v50:wifi:*`
和 16 个原始 pin 类。只有原厂完整掩码匹配才暴露物理组,不盲目套到其他 AW 板。
LuCI 三组独立开关和亮度,包含中/英/土语言。亮度按白光 80、蓝/红 120 限幅。
旧兼容接口在 V50 上不争用 AW,也不误驱动 PMIC。
OpenWrt 把 NET1/NET2 适配为 SIM1/SIM2 注册状态,LTE 蓝、NR 白、无卡熄灭、
离线红;这与原厂按运营商/内置或外置卡定义 NET 灯的策略不同。
Wi-Fi 5 GHz 白、2.4 GHz 蓝。注册变化从现有持久 AT URC 读者传递,
Wi-Fi 使用 ubus 事件,闪烁使用内核 LED timer,不增加常驻 AT 轮询或用户态闪烁线程。
## Android 二进制传输修复
实机 `adb exec-out` 的 `su` 输出仍发生 LF → CRLF 转换:
296523 字节 DTB 读成 296768 字节,按 DTB 头长度截断无法修复。
安装器改成设备端 base64 编码、电脑严格解码,并启用 pipefail,
避免源命令失败被编码器掩盖。覆盖 GPT、misc、boot 的读取和备份。
新传输实机 DTB 长度准确,SHA256 为
`cb078f2cea210bca36a2976dca99eb59c86afdc39ee116f59d608a81b9839870`。
新增 `--probe --serial SERIAL`:只读检查型号、加密、容量、A/B 元数据、DTB,
不创建 Android 暂存目录或写分区。新版冻结 EXE 在本机预检通过:
`v50`、Android A 槽、FBE、userdata 剩余约 18.92 GiB。
新版 bootchain 的只读实机检查也通过:`BOOTCHAIN-PLAN a b`,五个启动链分区两槽一致,
本机这次不需要同步差异分区。
桌面补充目录携带新版 bootchain,安装及切换均使用它;
TF 私有载荷校验清单相应更新,原 ZIP 的 Magisk 文件不被修改。
## 验证和产物边界
- 桌面 15 项、启动链 33 项、设备脚本 33 项、LED 4 项测试通过。
型号/平台拒绝和全部 256 种字节的 CRLF 传输还原均覆盖。
- shell 故障注入使用 dash/bash/sh。宿主 BusyBox 会绕过 PATH 桩命令,
不能用于这些故障注入,不将其误报为实机故障。
- AW 驱动在 6.18.54、7.2.8 分别通过外部模块编译。
- 两套完整 Image 构建成功,均含 `CONFIG_LEDS_AW9523B=y`,
输出在 `upstream/out-v50-6.18.54`、`upstream/out-v50-7.2.8`。
- 新 EXE 的只读实机预检通过。补充包通过 ZIP 校验、Python/EXE A/B boot 构建,
以及含空格路径的 CMD 入口检查。
`work/desktop-preview/*-20261014-v50*.zip` **仅更新桌面安装器**,
继承历史 `20261012-2afe136` 的运行时和内核,原 Magisk 成员保持一致。
它不是包含 AW 灯驱动的完整新版固件,不应宣称 V50 整机已验证。
新内核已部署到 V50;两套新 Image 都包含 AW 驱动和下述 eMMC 修正。
上述历史桌面补充包没有重新构建运行时,不能把实机更新混称为它的内容。
旧 `install.sh/install.ps1` 的 5.4 桌面安装路径不属于本次新增支持范围。
## 双卡、CPU 与其他功能
- 一次性 V50 平台默认值补入 `sim_slots=2`,保留用户选择的上网卡。
NR3 作为第二张卡的 URC 读者,所有 AT 通道所有权在干净启动时配置。
- 双栈启动先读 CPIN。只对已插卡的协议栈执行 SFUN 与模式初始化,
避免仅 SIM2 插卡时给空 SIM1 上电触发 CP 断言。实机确认 SIM1 未插,
SIM2 CPIN READY、CFUN=1、双栈就绪标记存在。注册曾返回 CEREG=8,
不将此描述为成功普通上网;双卡同时插入的网络仍需实物验证。
- V50 原厂 SML 与已支持的 F50 仅认证尾部有差异,DVFS 代码/表逐字节一致。
电压白名单按完整的实际 SML 哈希加入 V50,不放宽未知固件。实机读取支持,
三簇频率/调速器及可写温控接口可用,没有给用户预设降压或改写 SML。
- USB 角色 setter 同步沿用 F50 路径,修正被 U30Air 专属入口拒绝的情况。
本轮未做 V50 OTG 外设实测。
- NFC 已确认 I2C2、地址 `0x57`、AP GPIO189,读到 NFC Forum 能力容器,
NDEF 容量 872 字节;U30Air 使用 GPIO190,不能照搬引脚。
适配器从本机 DT 读取复位 GPIO,并仅接受已验证的 V50 绑定。
热点信息同步、RF 开关与现有文本/URL 功能共用已有 FM11 标签实现。
实机 status/sync 读写复验通过,保留用户自定义文本/URL 不自动改成 Wi-Fi。
OpenWrt 的 `config.change/wireless` 事件已注册,更新热点配置时同步标签,
不增加定时轮询。修正静态 BusyBox 工具路径、短延时及 awk 字符串拼接兼容性。
NFC 8 项测试含真实 BusyBox shell,均通过。
## 收尾时补齐的实机问题
此前恢复了重要配置和脚本,但 `/etc/board.json` 仍是损坏的内容。
Wi-Fi 配置虽已开启,wifi-scripts 在 `find_phy_by_path()` 解析此文件时失败,
netifd 设置 `retry_setup_failed=true`,没有真正启动 AP。
在独立暂存文件中运行原生 board_detect 并校验 JSON,备份坏文件后原子替换,
没有更改 `/etc/config/wireless`。重新应用原无线配置后,hostapd ENABLED,
频率 5180 MHz、信道36、VHT80,wlan0 加入 br-lan,DHCP 服务正常监听67端口。
Wi-Fi 白灯的亮度40符合原127/255配置,并非满亮或集体灯控。
补入公共 `openwrt-board-check`,在 Wi-Fi 初始化后、配置解析前检查生成的 JSON。
合法的自定义内容原样保留;只有不合法时才离线暂存重建、保留坏文件并替换。
生成失败保留原文件,解析大小设上限,正常启动不 fsck、不扫描分区。
真实 OpenWrt ucode/Docker 的保留、修复和失败阻断3项测试通过。
另外发现更新内核后的旧 cpufreq ko 因 BTF 类型不匹配被拒绝加载:
固件白名单已通过,但当时没有任何 policy/scaling_voltage 接口,不能据
`firmware=true` 声称完整电压支持。重新构建与新 Image 匹配的6.18.54/7.2.8模块,
V50 实机在本次启动尚未初始化 DVFS 的前提下第一次加载新驱动,
没有卸载活跃驱动、重复 DVFS_INIT 或写 SML。现在三簇 schedutil 调频恢复,
电压API `supported=true`,31个频点可读,偏移均为0,温控可写接口恢复。
打包增加电压参数及三项 sysfs 表接口检查,旧 CPU 模块不能静默混入。
空卡灯状态另接入已有双栈启动 CPIN 检测结果,直接发 LED presence 事件,
防止一次过早检测后遗留开机闪烁;应急注册也不再沿用正常在线颜色。
实机 NET1(无卡)三色均0,NET2(欠费、应急服务)红灯120。
期间 AT 通道所有者 PID 没有变化,EXT4 错误计数仍为0。
双卡5项、灯控4项、设备脚本35项(dash/bash/sh)检查通过。
蜂窝无法建立普通数据连接由用户确认卡欠费,不继续改动基带模式或 NV。
## EXT4 元数据损坏与 eMMC 恢复
本节记录早期 V50 `#17` 对照。后续公共策略、FUA 兼容及根因确认边界见
[两仓库报告](DUAL-SIM-BOOT-EMMC-20261014.zh-CN.md),不能用旧策略的观察
冒充新完整策略已完成实机验收。
原运行时出现 `ext4_lookup: deleted inode referenced`,含义是目录里的文件名
仍引用某个 inode,但 inode 已处于删除/无效状态。配置和原子替换后的脚本
曾在正常重启后丢失;离线 fsck 修过一次后再次重启仍复发。
因此既不是单纯容量显示错误,也不能把 fsck 当作根因修复。
主要线索是 V50 eMMC runtime PM:运行中宿主自动休眠,实验在 initramfs
写 `power/control=on` 触发的恢复停在挂载/fsck 之前。针对该板的非可移除
eMMC 宿主,在驱动 probe、第一次 autosuspend 之前执行 `pm_runtime_forbid`。
保留 HS400 ES、200 MHz、ADMA 和软件队列;可移除 TF 及其他板不套此策略。
错误分支和移除路径配对释放 PM 引用,不用常驻进程反复唤醒。
在 Android 下离线修复 `mu300root`,恢复配置和脚本、卸载后只读 fsck 校验。
新内核 `7.2.8 #17` 实机显示 `control=on`、`runtime_status=active`。
随后 Linux 写入测试标记、提交配置、同步并正常重启,标记/配置/关键脚本 SHA256
全部保留,EXT4 `errors_count=0`。这是改善的实机证据,但目前还不足以证明
所有旧元数据损坏都由 runtime PM 单独造成,需要继续观察跨重启持久化。
桌面 initramfs 另增加异常 ext4 的离线自动检查:正常 clean 超级块不跑完整
fsck;出现错误标志或明确修复请求才执行 e2fsck,并在检查期间开放 USB 恢复。
不会在挂载中的根分区直接修复,也不会把此前失败的用户态 PM 恢复实验带入最终启动。
## GPT 空闲空间安装
2026-10-14 实机只读确认物理 eMMC 122159104 个 512 字节扇区,约 58.25 GiB。
当前 userdata 为 p75,OpenWrt p76 为 8 GiB;p76 之后仍有约 32.39 GiB
GPT 未分配空间。这证明新安装优先缩 userdata 会造成不必要的 Android 重置。
新桌面路径先校验 GPT 两份副本、usable bounds、分区重叠、空表项,
优先使用足够大的连续空闲区。只在不够时才进入旧缩容逻辑。
FBE/FDE 不阻止空闲区安装;本机固件仍由当前已解锁 Android 提取。
使用原生 Android 有 size limit 的 loop,写入/扩容/只读校验后才提交新 GPT,
最后校验 boot 和切槽。不会要求 Android 重读正在使用的整盘分区表。
旧原始偏移系统签名会排除其所在空闲区域,不静默覆盖已检测的旧系统。
离线 GPT/FBE 路由和失败阻断测试通过;Linux 稀疏虚拟磁盘完成真实 ext4
写入、扩容至 2 GiB、e2fsck、文件校验、GPT 提交,前后保护区未变化。
本机已有独立 OpenWrt,因此仅探测,没有在实机新增分区或再缩 userdata。
## 实机续装:loop 路径修复
用户完成 FBE 缩容与 Android 重置后,续装报 `losetup: ...openwrt.ext4.new: No such file or directory`。
只读检查确认镜像仍存在、大小为 2 GiB。BusyBox `losetup -f` 返回 `/dev/loop31`,
实际 Android 节点是 `/dev/block/loop31`,报错并不表示镜像丢失。
新增 Android loop 解析助手,优先选择真实 block 节点;若 ueventd 尚未创建节点,
按 sysfs 的 major/minor 在私人暂存目录创建,保持对普通 Linux 节点的兼容。
镜像首次/只读挂载失败时也会卸载自己已绑定的 loop,不遗留占用。
第一阶段尾部的空错误发生在 shell 重启断开 ADB 时。改用 ADB reboot 服务,
并给没有 stderr/stdout 的 ADB 失败补充动作与退出状态,不再输出空错误。
Wi-Fi 密码按用户要求改为明文输入,SSH 密码仍使用隐藏输入。
修补用户当前解压目录的 EXE、Python 和镜像脚本,备份旧文件及原续装记录。
修补前完整核验旧包及记录绑定;修改后重新核验所有原 Magisk 文件和 boot/工具资产,
更新该条记录的包绑定,保留设备、槽位、分区几何与令牌,没有放宽通用续装校验。
实机验证:解析到 `/dev/block/loop31`,只读挂载/卸载成功;在原失败的临时镜像内
完成系统解包、提取本机运行库/固件、文件哈希和只读复验,返回 `IMAGE-INSTALLED partition-write`。
现有独立分区 8 GiB,续装身份、几何、令牌和包绑定均通过。
本次修复没有重新缩容、格式化 userdata、写独立分区或切换启动槽。
最终写入与 OpenWrt 首次启动仍由用户继续菜单 5 完成。
后续已将整包清单绑定改为关键载荷身份校验,允许修补版安装器和目录搬迁,
设备、槽位、8 GiB 分区几何及准备令牌检查保留。旧记录的确切原清单已恢复到
电脑备份目录,`clean-layout` 新版 EXE 的只读续装预检通过。
## F50 / V50 共用固件的机型隔离
2026-10-14 补齐代码,尚未重新编译、打包或部署本节改动。
- 旧 `install.sh` 与桌面安装器对齐:V50 必须同时匹配 `V50`、`MU3351` 和
`ums9620`,身份不一致时拒绝安装,不再确认后误标为 F50。ADB 设备选择支持 V50,
仍在存在多台设备时要求选择;不会把 `V500`、`MU33510` 当作匹配项。
- initramfs 和 `mu300-device` 优先采用本机设备树,旧镜像里的 `f50` 标记不能遮盖
V50 的 AW9523B 控制器。F50 也不会因为残留 `v50` 标记被识别成 V50。
只有没有设备树的兼容环境才读取已有标记,并限制为三个支持的机型。
- `mu300-platform-config` 为 F50、V50、U30 Air 记录配置所属机型。
检测到其他机型的配置备份时,启动 AT 服务前重设卡槽数、默认数据卡、
自定义切卡适配器和 SIM 网卡映射;F50/U30 Air 默认单卡,V50 默认双卡。
同机型后续启动不覆盖用户设置;APN、短信、流量账本和网络配置不在清理范围。
没有历史机型标记的旧 F50/U30 Air 配置只补标记,保留既有手动适配,
因此无法追溯识别完全不含来源信息的旧备份。
- 网页 NET1/NET2 专属控件继续要求实际 `v50:net1:white` LED 节点,
相关回归覆盖 F50 页面不出现 NET2、V50 页面显示三组灯。
- V50 内核更新必须由包内 `devices` 明确声明支持;不再像 F50 一样接受无清单旧包。
主线包仅在构建产物的 `kernel.config` 启用内置 AW9523B 驱动时声明 V50。
共用 TF 包也要求该驱动,旧 `install.sh` 不向 V50 提供不受支持的 5.4 安装路径。
验证:机型识别、旧标记纠正、ADB 选择、跨机恢复、F50/V50 灯控、更新包兼容性、
启动镜像、桌面安装器和内核能力检查通过;仅使用模拟设备树、临时目录及测试载荷。
+4
View File
@@ -195,3 +195,7 @@ Python 3 is not installed; installing it for this user Python 3 kurulu değil; b
{1} failed {1} başarısız oldu
waiting for Android to finish starting Android'in açılmasını bitirmesi bekleniyor
which adb device is the F50 or U30 Air? hangi adb cihazı F50 ya da U30 Air?
which adb device is the F50, V50 or U30 Air? hangi adb cihazı F50, V50 ya da U30 Air?
This does not look like a ZTE F50/MU300, V50 or U30 Air. Continue anyway? (yes/no) Bu cihaz ZTE F50/MU300, V50 veya U30 Air gibi görünmüyor. Yine de devam edilsin mi? (yes/no)
V50 requires product V50 / MU3351 on ums9620; refusing installation. V50 için ums9620 platformunda V50 / MU3351 ürün eşleşmesi gerekir; kurulum reddedildi.
V50 requires a compatible mainline kernel (6.18 or 7.2); the legacy 5.4 build is not supported. V50 uyumlu bir ana hat çekirdeği (6.18 veya 7.2) gerektirir; eski 5.4 derlemesi desteklenmez.
Can't render this file because it contains an unexpected character in line 108 and column 18.
+4
View File
@@ -195,3 +195,7 @@ Python 3 is not installed; installing it for this user 未安装 Python 3;正
{1} failed {1} 失败
waiting for Android to finish starting 正在等待 Android 启动完成
which adb device is the F50 or U30 Air? 哪个 adb 设备是 F50 或 U30 Air?
which adb device is the F50, V50 or U30 Air? 哪个 adb 设备是 F50、V50 或 U30 Air?
This does not look like a ZTE F50/MU300, V50 or U30 Air. Continue anyway? (yes/no) 这似乎不是中兴 F50/MU300、V50 或 U30 Air,仍要继续吗?(yes/no)
V50 requires product V50 / MU3351 on ums9620; refusing installation. V50 必须是 ums9620 平台的 V50 / MU3351 产品组合,已拒绝安装。
V50 requires a compatible mainline kernel (6.18 or 7.2); the legacy 5.4 build is not supported. V50 需要兼容的主线内核(6.18 或 7.2),不支持旧版 5.4 构建。
Can't render this file because it contains an unexpected character in line 108 and column 18.
+26 -12
View File
@@ -111,16 +111,22 @@ fi
. "$TOP/tools/linux-mode.sh"
require_android
[ "$(su_do 'id -u')" = 0 ] || die "$(t 'su does not work on the device')"
model="$(su_do 'getprop ro.product.model') / $(su_do 'getprop ro.product.device')"
android_model=$(su_do 'getprop ro.product.model')
android_device=$(su_do 'getprop ro.product.device')
android_platform=$(su_do 'getprop ro.board.platform')
model="$android_model / $android_device"
echo "$(t 'device: {1}' "$model")"
# The U30 Air is the F50's board with a battery: the same kernel and images, a few modules of its own (init
# loads them; the boot image says which device it is for)
case "$model" in
*U30Air*|*U30_Air*|*"U30 Air"*) DEVICE=u30air ;;
*MU300*|*F50*|*mu300*) DEVICE=f50 ;;
*) ask go "$(t 'This does not look like a ZTE F50/MU300 or U30 Air. Continue anyway? (yes/no)')" no; [ "$go" = yes ] || exit 1
DEVICE=f50 ;;
esac
. "$TOP/tools/android-profile.sh"
if DEVICE=$(mu300_android_profile "$android_model" "$android_device" "$android_platform"); then
:
else
profile_error=$?
[ "$profile_error" != 2 ] || die "$(t 'V50 requires product V50 / MU3351 on ums9620; refusing installation.')"
ask go "$(t 'This does not look like a ZTE F50/MU300, V50 or U30 Air. Continue anyway? (yes/no)')" no
[ "$go" = yes ] || exit 1
DEVICE=f50
fi
[ "$DEVICE" != v50 ] || [ "$MODE" != build ] || die "$(t 'V50 requires a compatible mainline kernel (6.18 or 7.2); the legacy 5.4 build is not supported.')"
[ "$(su_do 'getprop ro.boot.slot_suffix')" = _a ] || die "$(t 'Android must be running from slot a')"
# Existing desktop installer targets b; TF Magisk supports either Android slot.
SYNC_BOOTCHAIN=${MU300_SYNC_BOOTCHAIN:-1}
@@ -373,9 +379,14 @@ if [ $MODE = prebuilt ]; then
echo " $(t ' as 6.18; tested less than 6.18')"
echo " $(t 'This can be changed later on the device: sudo mu300-update kernel 5.4|6.18|7.2')"
while :; do
ask kchoice "$(t 'Kernel')" 1
kernel_default=1; [ "$DEVICE" != v50 ] || kernel_default=2
ask kchoice "$(t 'Kernel')" "$kernel_default"
case $kchoice in
1|5.4) if [ "${UBUNTU:-}" = 26.04 ]; then
1|5.4) if [ "$DEVICE" = v50 ]; then
echo " $(t 'V50 requires a compatible mainline kernel (6.18 or 7.2); the legacy 5.4 build is not supported.')"
continue
fi
if [ "${UBUNTU:-}" = 26.04 ]; then
echo " $(t 'Ubuntu 26.04 needs a mainline kernel (6.18 or 7.2): its programs use system calls that 5.4 does not have (tar, for one, cannot unpack folders there).')"
continue
fi
@@ -470,7 +481,10 @@ for f in $files; do
done
rm -rf "$REL/kernel" && mkdir -p "$REL/kernel" && tar -xzf "$REL/mu300-kernel.tar.gz" -C "$REL/kernel"
KOUT=$REL/kernel
[ $DEVICE = f50 ] || [ -d "$KOUT/modules-$DEVICE" ] || die "$(t 'release {1} does not support this device yet; use a newer one' "$RELEASE")"
case $DEVICE in
f50|v50) ;; # V50 shares the base modules; mainline support is checked below.
*) [ -d "$KOUT/modules-$DEVICE" ] || die "$(t 'release {1} does not support this device yet; use a newer one' "$RELEASE")" ;;
esac
BUSYBOX=$KOUT/busybox; LOGDW=$KOUT/logdw
# a mainline kernel (6.18, 7.2): its bundle, unpacked
KMAIN=
+3
View File
@@ -176,6 +176,9 @@ for f in sbin/block lib/libblkid-tiny.so etc/init.d/fstab; do
[ -s "$R/$f" ] || { echo "patched block-mount required file missing: $f" >&2; exit 1; }
done
chmod 0755 $R/opt/mu300/bin/cpu-voltage-platform $R/etc/init.d/mu300-cpu-driver
chmod 0755 $R/opt/mu300/bin/mu300-platform-config
chmod 0755 $R/opt/mu300/bin/v50-led-status
chmod 0755 $R/opt/mu300/bin/openwrt-board-check
chmod 0755 $R/opt/mu300/bin/ra-deprecate $R/opt/mu300/bin/wcn-reopen
chmod 0755 $R/opt/mu300/bin/mu300-user-packages $R/etc/init.d/mu300-user-packages
[ -s $R/www/luci-static/aurora/main.css ] || { echo "Aurora theme assets missing" >&2; exit 1; }
@@ -726,7 +726,18 @@ var DASH_I18N = {
'蜂窝连接会中断 1-2 分钟': ['Cellular connectivity may stop for 1–2 minutes', 'Hücresel bağlantı 1–2 dakika kesilebilir'],
'重启整个设备': ['Restart the entire device', 'Tüm cihazı yeniden başlat'],
'所有连接会断开': ['All connections will be interrupted', 'Tüm bağlantılar kesilecek'],
'切换到 Android 系统': ['Switch to Android', 'Android sistemine geç'],
'启动控制不可用': ['Boot control unavailable', 'Açılış kontrolü kullanılamıyor'],
'启动控制正忙,请稍后重试': ['Boot control is busy; try again later', 'Açılış kontrolü meşgul; sonra tekrar deneyin'],
'启动控制信息无效': ['Invalid boot control information', 'Açılış kontrol bilgisi geçersiz'],
'启动控制回读校验失败': ['Boot control readback verification failed', 'Açılış kontrolü geri okuma doğrulaması başarısız'],
'启动控制回退失败,请检查启动设置': ['Boot control rollback failed; check boot settings', 'Açılış kontrolü geri alma başarısız; açılış ayarlarını kontrol edin'],
'默认启动设置失败,请重试': ['Could not save the default boot; try again', 'Varsayılan açılış kaydedilemedi; tekrar deneyin'],
'当前为临时启动 OpenWrt': ['OpenWrt was booted temporarily', 'OpenWrt geçici olarak başlatıldı'],
'是否将 OpenWrt 设为默认启动?不会立即重启或断网。': ['Make OpenWrt the default boot? This will not reboot or interrupt networking.', 'OpenWrt varsayılan açılsın mı? Yeniden başlatma veya ağ kesintisi olmaz.'],
'设为默认启动': ['Make default boot', 'Varsayılan başlatma yap'],
'以后开机默认进入 OpenWrt;启动失败仍保留 Android 回退。现在不会重启。': ['Future boots will use OpenWrt, with Android fallback if startup fails. No reboot now.', 'Sonraki açılışlar OpenWrt kullanır; başarısızlıkta Android geri dönüşü korunur. Şimdi yeniden başlatılmaz.'],
'当前启动镜像不支持设置默认启动': ['This boot image cannot set a default boot', 'Bu açılış imajı varsayılan başlatmayı ayarlayamaz'],
'切换到 Android 系统': ['Switch to Android', 'Android sistemine geç'],
'下次启动将进入 Android 并立即重启,此管理页面与蜂窝共享都会断开': ['The next boot will enter Android and reboot now. This management page and cellular sharing will disconnect', 'Sonraki açılış Android’e geçecek ve cihaz şimdi yeniden başlayacak. Yönetim sayfası ve hücresel paylaşım kesilecek'],
'回到 OpenWrt:在 Android 上执行 mu300-next-boot linux 后重启': ['To return to OpenWrt, run mu300-next-boot linux in Android and reboot', 'OpenWrt’ye dönmek için Android’de mu300-next-boot linux çalıştırıp yeniden başlatın'],
'或什么都不做,连续 5 次开机未完成会自动回退': ['Or do nothing: five failed boots trigger automatic fallback', 'Ya da hiçbir şey yapmayın: beş başarısız açılışta otomatik geri dönülür'],
@@ -131,6 +131,10 @@ return view.extend({
</div>
</div>
<div class="mud-card mud-boot-notice" id="mud-boot-notice" hidden style="padding:1rem;margin-bottom:1rem;gap:.75rem;align-items:center;flex-wrap:wrap">
<div style="flex:1;min-width:12rem"><b>当前为临时启动 OpenWrt</b><div>是否将 OpenWrt 设为默认启动?不会立即重启或断网。</div></div>
<button class="mud-btn" id="mud-btn-default">设为默认启动</button>
</div>
<div class="mud-card mud-body">
<div class="mud-sec">
@@ -320,6 +324,11 @@ return view.extend({
return confirmAction(this, '重启整个设备', '所有连接会断开。',
{ danger: true }, 'reboot', null);
};
q('btn-default').onclick = function() {
return confirmAction(this, '设为默认启动',
'以后开机默认进入 OpenWrt;启动失败仍保留 Android 回退。现在不会重启。',
{ okText: '确定' }, 'os', 'linux-default');
};
q('btn-android').onclick = function() {
return confirmAction(this, '切换到 Android 系统',
'下次启动将进入 Android 并立即重启,此管理页面与蜂窝共享都会断开。\n' +
@@ -601,6 +610,15 @@ return view.extend({
M.set('fwos', i.fw || '--');
M.set('modem', (i.modem && i.modem.alive ? '在线' : '无应答') + (i.modem && i.modem.atd ? '' : ' · AT 适配器不可用'));
var androidBtn = M.v('btn-android');
var boot = i.boot || {}, notice = M.v('boot-notice'), setDefault = M.v('btn-default');
if (notice) {
notice.hidden = boot.temporary !== true;
notice.style.display = notice.hidden ? 'none' : 'flex';
}
if (setDefault) {
setDefault.disabled = !boot.can_set_default || !!this._quickPending;
setDefault.title = boot.can_set_default ? '' : M.translate('当前启动镜像不支持设置默认启动');
}
if (androidBtn) androidBtn.style.display = i.capabilities && i.capabilities.dualboot ? '' : 'none';
var b;
@@ -85,6 +85,22 @@ case "${1:-}:${2:-}" in
sleep 3 # the reply has to make it out first
reboot
;;
os:linux-default)
if [ ! -x /opt/mu300/bin/mu300-next-boot ]; then
fail "os linux-default" "启动控制不可用"
elif out=$(/opt/mu300/bin/mu300-next-boot linux 2>&1); then
ok "os linux-default"
else
case "$out" in
*"rollback failed"*) message='启动控制回退失败,请检查启动设置' ;;
*"boot control busy"*) message='启动控制正忙,请稍后重试' ;;
*"invalid boot control block size"*) message='启动控制信息无效' ;;
*"misc verify failed"*) message='启动控制回读校验失败' ;;
*) message='默认启动设置失败,请重试' ;;
esac
fail "os linux-default" "$message"
fi
;;
os:android)
# arm inline (fast, failures surface to the page); reboot DETACHED so
# the reply reaches the browser before the box goes down - a reboot
@@ -0,0 +1,24 @@
#!/bin/sh
# Local boot intent only: no AT, misc writes, cache or timer.
boot_status() {
local state=android temporary=true writable=false dir helper runtime slot=b
dir=${BOOT_STATE_DIR:-/etc/mu300}
helper=${BOOT_CONTROL_HELPER:-/opt/mu300/bin/mu300-next-boot}
if [ -e "$dir/default-boot" ]; then
IFS= read -r state < "$dir/default-boot" || :
fi
case "$state" in
linux) temporary=false ;;
android) ;;
*) state=unknown; temporary=null ;;
esac
runtime=${BOOT_RUNTIME_DIR:-/run/mu300}
if [ -r "$runtime/linux-slot" ]; then IFS= read -r slot < "$runtime/linux-slot" || :; fi
if [ -x "$helper" ] && [ -s "$runtime/misc-bc-linux-trial.bin" ] && [ -s "$runtime/misc-bc-android.bin" ]; then
case "$slot" in a|b) writable=true ;; esac
elif [ -x "$helper" ] && [ "$slot" = b ] && [ -s "$runtime/misc-bc-slot-b-trial.bin" ] && [ -s "$runtime/misc-bc-slot-a.bin" ]; then
writable=true
fi
printf '{"default":"%s","temporary":%s,"can_set_default":%s}' "$state" "$temporary" "$writable"
}
[ "${BOOT_STATUS_LIBRARY:-0}" = 1 ] || boot_status
@@ -346,6 +346,10 @@ printf '"wifi":{"available":%d,"enabled":%d,"pending":%d,"section":%s,"radio":%s
"$W_AVAILABLE" "$W_ENABLED" "$W_PENDING" "$(qs "$W_SECTION")" "$(qs "$W_RADIO")" "$(qs "$W_ERROR")" "$W_UP" "$(qs "$W_SSID")" "$(qs "$W_CH")" "$(qs "$W_BAND")" "$(qs "$W_WIDTH")" "$(qs "$W_COUNTRY")" "$(qs "$W_ENC")" "$(n_or_null "$W_HIDDEN")" "$W_HOSTAPD" "${W_CLIST:-}" "$W_CN"
printf '"lan":{"leases":%s,"ip":%s,"list":[%s]},' "$(n_or_null "$LAN_LEASES")" "$(qs "$LAN_IP")" "${LEASES:-}"
printf '"modem":{"alive":%d,"atd":%d,"data_paused":%d},' "$MODEM_ALIVE" "$ATD_OK" "$DATA_PAUSED"
# Source a builtin-only boot snapshot; this never changes startup intent.
BOOT_STATUS_LIBRARY=1
. "${MU300_DASH_BIN:-/usr/libexec/unisoc-modem}/boot-status"
printf '"boot":'; boot_status; printf ','
printf '"capabilities":{"vpn":%d,"dualboot":%d},' "$CAP_VPN" "$CAP_DUALBOOT"
printf '"conns":%s,' "$(n_or_null "$CONNS")"
# The accounting worker publishes one atomic JSON line; no extra RPC or AT
@@ -71,7 +71,7 @@ role_command() {
if [ -n "$cmd" ]; then
[ -x "$cmd" ] || error 'USB role adapter is not executable'
"$cmd" "$1" || error 'USB role adapter failed'
elif [ "$(device_name)" = f50 ]; then
elif [ "$(device_name)" = f50 ] || [ "$(device_name)" = v50 ]; then
[ -w "$ROLE_FILE" ] || error 'USB role switch is unavailable'
printf '%s\n' "$1" > "$ROLE_FILE" || error 'USB role switch failed'
elif command -v mu300-usb >/dev/null 2>&1; then
+2
View File
@@ -30,6 +30,8 @@ wait_and_exec() {
}
start_service() {
# Do not migrate NR3 ownership after daemons have opened the SIPC ttys.
[ ! -x /opt/mu300/bin/mu300-platform-config ] || /opt/mu300/bin/mu300-platform-config
# Optional plugin handshake: reserve nr1's first-command window for the
# platform radio-on path. The generic worker waits for this marker to clear.
[ ! -x /usr/libexec/unisoc-modem/lock ] || : > /run/unisoc-modem-early-hook-pending
+3 -2
View File
@@ -20,11 +20,12 @@ hw_bringup() {
/opt/mu300/bin/extra-modules >/tmp/mu300-extra-modules.log 2>&1
/opt/mu300/bin/zram-start >/dev/null 2>&1
/opt/mu300/bin/wifi-start >/tmp/mu300-wifi-start.log 2>&1
/opt/mu300/bin/openwrt-board-check >>/tmp/mu300-wifi-start.log 2>&1 || return 1
# cfg80211 looked for regulatory.db before the rootfs was mounted; load it now so hostapd sees the country rules
/opt/mu300/bin/regdb-load >>/tmp/mu300-wifi-start.log 2>&1
/opt/mu300/bin/openwrt-wifi-config >>/tmp/mu300-wifi-start.log 2>&1
# the U30 Air's NFC tag: the hotspot's name and password, if that is what it holds (see mu300-nfc)
[ "$(/opt/mu300/bin/mu300-device)" = u30air ] && /opt/mu300/bin/mu300-nfc sync >/tmp/mu300-nfc.log 2>&1
# Supported NFC tags (U30 Air / V50): retain custom text/URLs, synchronize Wi-Fi.
/opt/mu300/bin/mu300-nfc supported 2>/dev/null && /opt/mu300/bin/mu300-nfc sync >/tmp/mu300-nfc.log 2>&1
# apply the country before netifd starts hostapd, otherwise 5 GHz channels are still NO-IR under world rules
country=$(uci -q get wireless.radio0.country)
if [ -n "$country" ]; then
+4
View File
@@ -6,6 +6,10 @@ export PATH="$PATH:/opt/mu300/busybox-bin"
service_triggers() {
procd_add_reload_trigger system
# Config events, not a polling loop. NFC sync keeps custom text/URL tags.
if /opt/mu300/bin/mu300-nfc supported >/dev/null 2>&1; then
procd_add_config_trigger "config.change" wireless /opt/mu300/bin/mu300-nfc sync
fi
}
reload_service() {
@@ -17,7 +17,10 @@ network_state() {
online-4g) led-status online-4g; return ;;
online-5g) led-status online-5g; return ;;
esac
act=$(mu300-at -t 3 'AT+CEREG?' 2>/dev/null | grep '+CEREG:' | head -1 | awk -F, '{print $NF}' | tr -d '" ')
# View the selected data stack, not slot 0 unconditionally.
slot=$(uci -q get unisoc_modem.main.data_sim); [ "$slot" = 1 ] || slot=0
dir=/run/mu300-at; [ "$slot" != 1 ] || dir=/run/mu300-at4
act=$(MU300_AT_DIR=$dir mu300-at -t 3 "AT+SPACTCARD=$slot;+CEREG?" 2>/dev/null | grep '+CEREG:' | head -1 | awk -F, '{print $NF}' | tr -d '" ')
case "$act" in
11|12|13|15) led-status online-5g ;;
*) led-status online-4g ;;
@@ -29,6 +32,7 @@ network_state() {
network_state
wifi_state
[ ! -d /sys/class/leds/v50:net1:white ] || /opt/mu300/bin/v50-led-status sync
ubus listen 2>/dev/null | while IFS= read -r event; do
case "$event" in
*network.interface*) network_state ;;
@@ -25,6 +25,11 @@ const labels = {
'Signal lamp brightness': ['信号灯亮度', 'Sinyal ışığı parlaklığı'],
'Wi-Fi hotspot lamp': ['Wi-Fi 热点灯', 'Wi-Fi erişim noktası ışığı'],
'Wi-Fi lamp brightness': ['Wi-Fi 灯亮度', 'Wi-Fi ışığı parlaklığı'],
'NET1 lamp (SIM 1)': ['NET1 灯(SIM1)', 'NET1 ışığı (SIM 1)'],
'NET2 lamp (SIM 2)': ['NET2 灯(SIM2)', 'NET2 ışığı (SIM 2)'],
'NET1 brightness': ['NET1 亮度', 'NET1 parlaklığı'],
'NET2 brightness': ['NET2 亮度', 'NET2 parlaklığı'],
'Each network lamp shows its own SIM status. Wi-Fi: 5 GHz white, 2.4 GHz blue.': ['两组网络灯分别显示各自 SIM 的注册状态;Wi-Fi:5 GHz 白色、2.4 GHz 蓝色。', 'Ağ ışıkları kendi SIM durumlarını gösterir. Wi-Fi: 5 GHz beyaz, 2.4 GHz mavi.'],
'0–255; 0 is dark. LTE stays blue, 5G white, and no service red.': ['0–255;0 为熄灭。4G 仍为蓝色、5G 为白色、无信号为红色。', '0–255; 0 ışığı kapatır. 4G mavi, 5G beyaz, servis yoksa kırmızı kalır.'],
'0 is dark. Hardware maximum: ': ['0 为熄灭。硬件最大值:', '0 ışığı kapatır. Donanım üst sınırı: '],
'Add LED action': ['添加 LED 动作', 'LED eylemi ekle'],
@@ -73,6 +78,8 @@ return view.extend({
render([leds, plugins]) {
let m, s, o;
const awRgb = !!(leds.aw_led && leds.red && leds.green && leds.blue);
const v50 = !!leds['v50:net1:white'];
let wifiMax = leds['keyboard-backlight'] && Number(leds['keyboard-backlight'].max_brightness);
if (!Number.isInteger(wifiMax) || wifiMax < 1 || wifiMax > 255) wifiMax = 255;
const triggers = [];
@@ -90,14 +97,23 @@ return view.extend({
s = m.section(form.NamedSection, 'mu300_leds', 'mu300_leds', label('Physical status lamps'));
s.anonymous = true;
s.addremove = false;
o = s.option(form.Flag, 'signal', label('Signal lamp (LTE / 5G / no service)'));
if (v50) s.description = label('Each network lamp shows its own SIM status. Wi-Fi: 5 GHz white, 2.4 GHz blue.');
o = s.option(form.Flag, 'signal', label(v50 ? 'NET1 lamp (SIM 1)' : 'Signal lamp (LTE / 5G / no service)'));
o.default = '1';
o.rmempty = false;
o = s.option(form.Value, 'signal_brightness', label('Signal lamp brightness'),
o = s.option(form.Value, 'signal_brightness', label(v50 ? 'NET1 brightness' : 'Signal lamp brightness'),
label('0–255; 0 is dark. LTE stays blue, 5G white, and no service red.'));
o.datatype = 'range(0,255)';
o.default = '255';
o.rmempty = false;
if (v50) {
o = s.option(form.Flag, 'signal2', label('NET2 lamp (SIM 2)'));
o.default = '1'; o.rmempty = false;
o = s.option(form.Value, 'signal2_brightness', label('NET2 brightness'));
o.datatype = 'range(0,255)'; o.default = '255'; o.rmempty = false;
wifiMax = 255; // normalized brightness, scaled to each physical channel
}
if (!awRgb || v50) {
o = s.option(form.Flag, 'wifi', label('Wi-Fi hotspot lamp'));
o.default = '1';
o.rmempty = false;
@@ -106,6 +122,7 @@ return view.extend({
o.datatype = 'range(0,' + wifiMax + ')';
o.default = String(Math.min(127, wifiMax));
o.rmempty = false;
}
s = m.section(form.GridSection, 'led', '');
s.anonymous = true;
@@ -8,7 +8,6 @@ ko=/lib/modules/$(uname -r)/sprd-cpufreq-v2-driver.ko
helper=/usr/libexec/unisoc-modem/cpu-voltage
supported() {
tr '\000' '\n' </sys/firmware/devicetree/base/compatible | grep -qx 'sprd,ums9620' || return 1
expected=ff4782690fd805ff54fe34853ef8ee5c7e51c3259e20077c55373b50a4b259c2
for slot in a b; do
part=/dev/disk/by-partlabel/sml_$slot
[ -b "$part" ] || part=/dev/block/by-name/sml_$slot
@@ -25,7 +24,14 @@ supported() {
real=$(readlink -f "$part") || return 1
[ "$(cat "/sys/class/block/${real##*/}/size")" = 2048 ] || return 1
hash=$(sha256sum "$part") || return 1
[ "${hash%% *}" = "$expected" ] || return 1
# V50 has the same verified executable and DVFS tables as F50; only
# 512 bytes in the authentication trailer differ. Keep an exact hash
# allowlist, never infer voltage support from the SoC name alone.
case ${hash%% *} in
ff4782690fd805ff54fe34853ef8ee5c7e51c3259e20077c55373b50a4b259c2|\
5b3183f17af9b416e71dea61e578c61824e4e1df43737a1179032f4b20466b2b) ;;
*) return 1 ;;
esac
done
}
case ${1:-load} in
+1 -1
View File
@@ -117,5 +117,5 @@ mkdir -p /run/motd.d && chmod 755 /run/motd.d
printf 'MU300 hotspot: SSID "%s" password "%s" (edit /etc/mu300/hotspot.conf)\n' "$SSID" "$PSK" > /run/motd.d/50-mu300-hotspot
chmod 640 /run/motd.d/50-mu300-hotspot
# the U30 Air's NFC tag: the name and password again if that is what it holds (a slow I2C write, in the background)
[ "$(/opt/mu300/bin/mu300-device)" = u30air ] && { /opt/mu300/bin/mu300-nfc sync 2>&1 | logger -t mu300-nfc & }
/opt/mu300/bin/mu300-nfc supported 2>/dev/null && { /opt/mu300/bin/mu300-nfc sync 2>&1 | logger -t mu300-nfc & }
exec hostapd "$HOSTAPD_CONF"
+21 -3
View File
@@ -2,8 +2,9 @@
# MU300/V50 status LED controller.
#
# The F50 has three LED channels under sc27xx:*, where "green" is physically WHITE
# (verified: the vendor's own userspace treats it as white). The V50 has separate
# /sys/class/leds/{red,white,blue}/ paths. This script auto-detects both.
# (verified: the vendor's own userspace treats it as white). V50/MU3351 has an
# AW9523B controller with three independent red/white/blue indicators, AND
# unused sc27xx nodes. Its hardware groups are owned by v50-led-status.
#
# States (one multi-color LED, priority order):
# boot red/white/blue chase - Linux is booting
@@ -21,8 +22,20 @@ export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
LED_ROOT=${MU300_LED_SYSFS_ROOT:-/sys/class/leds}
RUN_DIR=${MU300_LED_RUN_DIR:-/run}
# The V50 has three independently wired red/white/blue indicators.
if [ -d "$LED_ROOT/v50:net1:white" ]; then
exec "${MU300_LED_BACKEND:-/opt/mu300/bin/v50-led-status}" "$@"
fi
[ "$(mu300-device 2>/dev/null)" != v50 ] || exit 0
# --- detect LED paths (F50 sc27xx vs V50 plain)
if [ -d "$LED_ROOT/sc27xx:blue" ]; then
RGB_WHITE=0
if [ -d "$LED_ROOT/aw_led" ] && [ -d "$LED_ROOT/green" ] && [ -d "$LED_ROOT/blue" ]; then
LED_R=$LED_ROOT/red/brightness
LED_W=$LED_ROOT/green/brightness
LED_B=$LED_ROOT/blue/brightness
RGB_WHITE=1
elif [ -d "$LED_ROOT/sc27xx:blue" ]; then
LED_R=$LED_ROOT/sc27xx:red/brightness
LED_W=$LED_ROOT/sc27xx:green/brightness # physically white on the F50
LED_B=$LED_ROOT/sc27xx:blue/brightness
@@ -124,6 +137,11 @@ done
set_rgb() { # R W B (0-255)
[ "$SIGNAL_ENABLED" = 1 ] || set -- 0 0 0
if [ "$RGB_WHITE" = 1 ] && [ "${2:-0}" -gt 0 ]; then
# AW9523B has true RGB: white uses all three groups.
[ "${1:-0}" -ge "$2" ] || set -- "$2" "$2" "${3:-0}"
[ "${3:-0}" -ge "$2" ] || set -- "$1" "$2" "$2"
fi
scaled "${1:-0}" "$SIGNAL_BRIGHTNESS" "$R_MAX" > "$LED_R" 2>/dev/null
scaled "${2:-0}" "$SIGNAL_BRIGHTNESS" "$W_MAX" > "$LED_W" 2>/dev/null
scaled "${3:-0}" "$SIGNAL_BRIGHTNESS" "$B_MAX" > "$LED_B" 2>/dev/null
+7
View File
@@ -141,6 +141,13 @@ for n in ${MU300_AT_URC_CHANNELS-0}; do
while IFS= read -r urc; do
urc=${urc%"$CR"}
capture_cmt "$urc"
# Registration changes already arrive on the persistent URC owner.
# No new AT query or polling timer for V50's second network lamp.
case "$n:$urc" in
0:+CEREG:*|3:+CEREG:*)
[ ! -d /sys/class/leds/v50:net1:white ] ||
/opt/mu300/bin/led-status sim-status "$((n / 3))" "$urc" >/dev/null 2>&1 ;;
esac
printf '%s\n' "$urc" >> "$log"
# cheap cap: start over rather than grow without end, /run is RAM
[ "$(wc -c < "$log" 2>/dev/null || echo 0)" -gt "$URCMAX" ] && : > "$log"
+11 -7
View File
@@ -1,12 +1,16 @@
#!/bin/sh
# Which device this is: f50 or u30air. boot/init writes it to /run/mu300/device; a boot image from before that
# (an older release's or a mainline kernel) does not, so then the device tree tells, the way init decides:
# only the U30 Air's has the charger policy service. (MU300_SYSROOT is for tests/: a fake / to read from.)
# Which board is physically present. A restored rootfs or old boot-image label
# cannot override the live device tree. MU300_SYSROOT provides a fake / in tests.
R=${MU300_SYSROOT:-}
if [ -s "$R/run/mu300/device" ]; then
cat "$R/run/mu300/device"
elif [ -d "$R/proc/device-tree/charger_policy_service" ]; then
if [ -d "$R/proc/device-tree/charger_policy_service" ]; then
echo u30air
else
elif [ -d "$R/proc/device-tree/soc/soc:ap-ahb/i2c@2270000/aw9523b_led@5b" ] ||
[ -d "$R/proc/device-tree/soc/ap-ahb/i2c@2270000/aw9523b_led@5b" ]; then
echo v50
elif [ -d "$R/proc/device-tree" ]; then
echo f50
else
# Compatibility for environments where procfs/device-tree is unavailable.
device=$(cat "$R/run/mu300/device" 2>/dev/null)
case $device in f50|v50|u30air) echo "$device" ;; *) echo f50 ;; esac
fi
+42 -14
View File
@@ -21,45 +21,73 @@ for stream in "$root/mu300-at/urc/stty_nr0.ready" "$root/mu300-at4/urc/stty_nr3.
reader=$(cat "$stream" 2>/dev/null)
[ -n "$reader" ] && kill -0 "$reader" 2>/dev/null || fail 'URC reader not ready'
done
present0=1; present1=1
for card in 0 1; do
pin=$(query "$card" 'AT+CPIN?')
case "$pin" in
*'+CME ERROR: 10'*) [ "$card" != 0 ] && present1=0 || present0=0 ;;
*'+CPIN:'*) ;;
*) fail "SIM $card presence unreadable" ;;
esac
if [ -x /opt/mu300/bin/v50-led-status ]; then
state=present
case "$pin" in *'+CME ERROR: 10'*) state=absent ;; esac
/opt/mu300/bin/v50-led-status sim-presence "$card" "$state" 2>/dev/null || :
fi
done
present() { case $1 in 0) [ "$present0" = 1 ] ;; 1) [ "$present1" = 1 ] ;; *) return 1 ;; esac; }
cf0=$(cfun 0); cf1=$(cfun 1)
if [ "$cf0" = 1 ] && [ "$cf1" = 1 ]; then
if { [ "$present0" = 0 ] || [ "$cf0" = 1 ]; } && { [ "$present1" = 0 ] || [ "$cf1" = 1 ]; }; then
actual=$(query 0 'AT+SPSWDATA?' | sed -n 's/^+SPSWDATA: *\([01]\)$/\1/p')
case "$actual" in 0|1) printf '%s\n' "$actual" > "$root/mu300-data-sim-actual" ;; *) fail 'data SIM readback unavailable' ;; esac
: > "$root/mu300-dual-radio-ready"; exit 0
fi
case "$cf0:$cf1" in
check0=$cf0; check1=$cf1
[ "$present0" != 0 ] || check0=0
[ "$present1" != 0 ] || check1=0
case "$check0:$check1" in
0:0) ;;
0:1|1:0)
echo 'dual-radio: mixed radio power state; fresh dual-SIM boot required' >&2
exit 4 ;;
*) fail 'radio state unreadable' ;;
esac
for card in 0 1; do
query "$card" 'AT+CPIN?' | grep -qx '+CPIN: READY' || fail "SIM $card not ready"
done
# Only a positively absent card is skipped. The E5 RIL comparison found that
# raising an empty first stack with only SIM2 inserted asserts mnphone_api.c.
# A PIN-locked card is still present; registration is handled by the dial path.
modes=$(query 0 'AT+SPTESTMODE?' | sed -n 's/^+SPTESTMODE: *//p' | tr -d ' ')
printf '%s\n' "$modes" | grep -qE '^[0-9]+,[0-9]+,[01](,[0-9]+)*$' || fail 'invalid work mode readback'
pair=$(printf '%s' "$modes" | cut -d, -f1-2)
# No band policy is invented here. Retain the user's existing per-card modes
# and lock replay; T551M-specific NR locks must never be forced onto an F50.
ok 0 'AT+SFUN=2' || fail 'SIM 0 power-on rejected'
ok 1 'AT+SFUN=2' || fail 'SIM 1 power-on rejected'
ok 1 "AT+SPTESTMODEM=$pair" || fail 'SIM 1 mode initialization rejected'
ok 0 "AT+SPTESTMODEM=$pair" || fail 'SIM 0 mode initialization rejected'
for card in 0 1; do
present "$card" || continue
ok "$card" 'AT+SFUN=2' || fail "SIM $card power-on rejected"
done
for card in 1 0; do
present "$card" || continue
ok "$card" "AT+SPTESTMODEM=$pair" || fail "SIM $card mode initialization rejected"
done
if [ -x /usr/libexec/unisoc-modem/lock ]; then
for card in 0 1; do
present "$card" || continue
(
. /usr/libexec/unisoc-modem/sim-scope.sh
sim_scope "$card" && /usr/libexec/unisoc-modem/lock replay early
) || logger -t mu300-dual-radio "SIM $card early replay unverified"
done
fi
ok "$target" 'AT+SPSWDATA' || fail 'data SIM selection rejected'
if present "$target"; then
ok "$target" 'AT+SPSWDATA' || fail 'data SIM selection rejected'
fi
actual=$(query "$target" 'AT+SPSWDATA?' | sed -n 's/^+SPSWDATA: *\([01]\)$/\1/p')
[ "$actual" = "$target" ] || fail 'data SIM readback mismatch'
case "$actual" in 0|1) ;; *) fail 'data SIM readback unavailable' ;; esac
if present "$target"; then [ "$actual" = "$target" ] || fail 'data SIM readback mismatch'; fi
printf '%s\n' "$actual" > "$root/mu300-data-sim-actual"
ok 0 'AT+SFUN=4' 20 || fail 'SIM 0 radio-on rejected'
ok 1 'AT+SFUN=4' 20 || fail 'SIM 1 radio-on rejected'
[ "$(cfun 0)" = 1 ] && [ "$(cfun 1)" = 1 ] || fail 'radio-on readback mismatch'
for card in 0 1; do
present "$card" || continue
ok "$card" 'AT+SFUN=4' 20 || fail "SIM $card radio-on rejected"
[ "$(cfun "$card")" = 1 ] || fail "SIM $card radio-on readback mismatch"
done
: > "$root/mu300-dual-radio-ready"
echo 'dual-radio: both SIM stacks ready' >&2
+10
View File
@@ -30,6 +30,16 @@ LEDS=$R/sys/class/leds
STATE=$R/run/mu300/led
DEVICE=$(${MU300_BIN:-/opt/mu300/bin}/mu300-device)
# V50's controller is owned by led-status. The old compatibility calls must
# not overwrite its RGB state or write the unrelated PMIC channels.
if [ "$DEVICE" = v50 ]; then
case ${1:-}:${2:-} in
alarm:on) exec /opt/mu300/bin/led-status thermal ;;
alarm:off) exec /opt/mu300/bin/led-status refresh ;;
*) exit 0 ;;
esac
fi
case $DEVICE in
u30air) POWER=sc27xx:green DATA=net_blue DATA5G=zte-ldo0 NODATA=keyboard-backlight WIFI5=zte-ldo2 WIFI24=zte-ldo1
DEFAULT_TIMEOUT=60 ;;
+40 -7
View File
@@ -58,10 +58,11 @@ make_bc_linux() {
}
write_bc() {
dd if="$1" of="$MISC" bs=1 seek=2048 conv=notrunc 2>/dev/null
sync
[ "$(wc -c < "$1")" = 32 ] || { echo "invalid boot control block size" >&2; return 1; }
dd if="$1" of="$MISC" bs=1 seek=2048 conv=notrunc 2>/dev/null || return 1
sync || return 1
[ "$(dd if="$MISC" bs=1 skip=2048 count=32 2>/dev/null | od -An -tx1 -v | tr -d ' \n')" = "$(hex_of "$1")" ] \
|| { echo "misc verify failed" >&2; exit 1; }
|| { echo "misc verify failed" >&2; return 1; }
}
arm_linux() {
@@ -70,10 +71,10 @@ arm_linux() {
# above is wrong for this misc and nothing it makes gets written.
if [ "$(make_bc_linux 2 2>/dev/null)" != "$(hex_of "$BC_LINUX")" ]; then
echo "cannot rebuild the slot $LINUX_SLOT block on this system; arming with 1 attempt" >&2
write_bc "$BC_LINUX"; return
write_bc "$BC_LINUX"; return $?
fi
tmp=$(mktemp); bytes_of "$(make_bc_linux $((n + 1)))" > "$tmp"
write_bc "$tmp"; rm -f "$tmp"
write_bc "$tmp" || { rm -f "$tmp"; return 1; }; rm -f "$tmp"
echo "slot $LINUX_SLOT armed: $n failed boot(s) in a row before Android"
}
@@ -89,9 +90,41 @@ slot_state() {
echo " slot a info: ${b:24:2} slot b info: ${b:28:2} (prio | tries<<4 | successful<<7)"
}
# Serialize the complete misc+intent transaction; never advertise a successful
# default change before misc readback. Preserve old misc if persistence fails.
set_default() (
target=$1
mkdir -p "${CONF%/*}" /run || exit 1
candidate=$(mktemp "${CONF}.XXXXXX") || exit 1
previous=$(mktemp /run/openwrt-boot-bc.XXXXXX) || { rm -f "$candidate"; exit 1; }
old_conf=$(mktemp "${CONF}.backup.XXXXXX") || { rm -f "$candidate" "$previous"; exit 1; }
had_conf=false
if [ -e "$CONF" ]; then cp -p "$CONF" "$old_conf" || exit 1; had_conf=true; fi
trap 'rm -f "$candidate" "$previous" "$old_conf"' EXIT
printf '%s\n' "$target" > "$candidate" || exit 1
dd if="$MISC" of="$previous" bs=1 skip=2048 count=32 2>/dev/null || exit 1
[ "$(wc -c < "$previous")" = 32 ] || exit 1
if ( if [ "$target" = linux ]; then arm_linux; else write_bc "$BC_ANDROID"; fi ); then
if mv -f "$candidate" "$CONF" && sync && [ "$(cat "$CONF")" = "$target" ]; then
exit 0
fi
fi
if "$had_conf"; then mv -f "$old_conf" "$CONF"; else rm -f "$CONF"; fi
( write_bc "$previous" ) || echo "boot control rollback failed" >&2
exit 1
)
# Include the successful-boot rearm in the same lock: an Android selection
# must not be overwritten by a concurrently finishing startup service.
case "${1:-status}" in
linux) mkdir -p /etc/mu300; echo linux > "$CONF"; arm_linux; echo "default boot: linux" ;;
android) mkdir -p /etc/mu300; echo android > "$CONF"; write_bc "$BC_ANDROID"; echo "next boot: android (opposite slot)" ;;
linux|android|--rearm|attempts)
exec 9>/run/openwrt-default-boot.lock
flock -n 9 || { echo "boot control busy" >&2; exit 1; } ;;
esac
case "${1:-status}" in
linux) set_default linux; echo "default boot: linux" ;;
android) set_default android; echo "next boot: android (opposite slot)" ;;
attempts)
if [ -z "${2:-}" ]; then attempts; exit 0; fi
case $2 in [1-6]) ;; *) echo "attempts must be 1-6 (the slot's tries field has room for 7)" >&2; exit 2 ;; esac
+32 -8
View File
@@ -1,5 +1,5 @@
#!/bin/sh
# The U30 Air's NFC tag (Ubuntu and OpenWrt): a phone held against the device reads what is written there.
# The U30 Air / V50 NFC tag (Ubuntu and OpenWrt): a phone held against the device reads what is written there.
# mu300-nfc what the tag holds (for Wi-Fi only the network name, never the password)
# mu300-nfc wifi the hotspot's name and password: a phone joins the Wi-Fi with a tap
# mu300-nfc url URL a link the phone opens (https://..., tel:..., mailto:..., geo:...)
@@ -17,12 +17,19 @@
# field-detect interrupt still counts every tap), found by reading the chip with the switch on and off; this
# changes that one byte and nothing else there (the same block holds the tag's I2C address).
# (MU300_SYSROOT, MU300_BIN, MU300_HOTSPOT_CONF are for tests/)
export PATH="$PATH:/opt/mu300/bin:/usr/sbin:/sbin"
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
R=${MU300_SYSROOT:-}
CONF=${MU300_HOTSPOT_CONF:-/etc/mu300/hotspot.conf}
BUS=2 ADDR=0x57 LINE=190 START=16 CFG=0x3bf RF_OFF=0x20
die() { echo "mu300-nfc: $*" >&2; exit 1; }
reset_delay() {
# OpenWrt's small /bin/sleep rejects fractions; the bundled static
# BusyBox supports them. Keep a bounded fallback for minimal systems.
if [ -z "$R" ] && [ -x /opt/mu300/bin/busybox ]; then
/opt/mu300/bin/busybox sleep "$1" || sleep 1
else sleep "$1" 2>/dev/null || sleep 1; fi
}
i2ct() { # i2ctransfer ARGS: i2c-tools when there, else busybox's
if command -v i2ctransfer >/dev/null 2>&1 && [ "$(command -v i2ctransfer)" != /usr/bin/busybox ]; then i2ctransfer -y "$@"
elif [ -z "$R" ] && [ -x /opt/mu300/bin/busybox ]; then /opt/mu300/bin/busybox i2ctransfer -y "$@"
@@ -34,7 +41,7 @@ HOLD=
enable() {
# 5.4: ZTE's fm11tag driver owns the line and offers it in /proc
for f in "$R"/proc/ntag_gpios/*reset*; do
[ -e "$f" ] && { echo 0 > "$f" && HOLD=proc:$f; trap disable EXIT INT TERM; sleep 0.2; return; }
[ -e "$f" ] && { echo 0 > "$f" && HOLD=proc:$f; trap disable EXIT INT TERM; reset_delay 0.2; return; }
done
chip=
for c in "$R"/sys/bus/gpio/devices/gpiochip*; do
@@ -47,7 +54,8 @@ enable() {
else gpioset --mode=signal "$chip" "$LINE=0" </dev/null >/dev/null 2>&1 & fi
HOLD=$!
trap disable EXIT INT TERM
sleep 0.3
reset_delay 0.3
kill -0 "$HOLD" 2>/dev/null || die "cannot acquire NFC reset GPIO $LINE"
}
disable() {
case $HOLD in
@@ -94,7 +102,7 @@ write_ndef() { # write_ndef HEX...: from START, 16 bytes per write, each page o
if [ "$have" != "$page" ]; then
i2ct "$BUS" "w$((n + 2))@$ADDR" $(printf '0x%02x 0x%02x' $((o >> 8)) $((o & 255))) \
$(for x in $page; do printf ' 0x%s' "$x"; done) || die "cannot write the tag"
sleep 0.02 2>/dev/null || sleep 1 # the EEPROM's write cycle
reset_delay 0.02 # the EEPROM's write cycle
[ "$(read16 $o | awk -v n=$n '{ for (i = 1; i <= n; i++) printf " %s", $i }')" = "$page" ] \
|| die "the tag did not keep what was written (write-protected?)"
fi
@@ -112,7 +120,7 @@ rf() { # rf [on|off]: the RF side's switch, shown or set
esac
[ "$n" = "$v" ] && return
i2ct "$BUS" "w3@$ADDR" 0x03 0xbf "$(printf 0x%02x "$n")" || die "cannot write the tag's configuration"
sleep 0.02 2>/dev/null || sleep 1
reset_delay 0.02
[ $(( $(i2ct "$BUS" "w2@$ADDR" 0x03 0xbf r1) )) = "$n" ] || die "the tag did not keep its new configuration"
}
@@ -188,14 +196,30 @@ describe() { # describe HEX: the NDEF message in words (hex on stdin as words)
if (id == 4135) key = l
p += l
}
print "wifi: " ssid (key ? " (with its password)" : " (open)")
# BusyBox awk otherwise parses "ssid (...)" as a function call.
print "wifi: " ssid "" (key ? " (with its password)" : " (open)")
} else print "other: " type
}'
}
# --- main -------------------------------------------------------------------------------------------------------
[ "$(${MU300_BIN:-/opt/mu300/bin}/mu300-device)" = u30air ] || die "only the U30 Air has an NFC tag"
case $("${MU300_BIN:-/opt/mu300/bin}/mu300-device") in
u30air) ;;
v50)
# Stock V50 fm11tag uses the AP GPIO controller, but not U30 Air's
# reset pin. Read its big-endian GPIO cell rather than guessing 190.
prop=$R/proc/device-tree/ntag_fm11_gpio/ntag-reset-gpio
[ -r "$prop" ] && [ "$(wc -c < "$prop")" = 12 ] || die "V50 NFC reset binding missing"
pin=$(od -An -tx1 -j4 -N4 "$prop" | tr -d ' \n')
case "$pin" in *[!0-9a-f]*|'') die "invalid NFC reset GPIO" ;; esac
[ "${#pin}" = 8 ] || die "invalid NFC reset GPIO cell"
LINE=$((0x$pin))
[ "$LINE" = 189 ] || die "unverified V50 NFC reset GPIO"
;;
*) die "this device has no supported NFC tag" ;;
esac
case ${1:-show} in
supported) exit 0 ;;
show|status|wifi|url|text|clear|sync|on|off) ;;
*) sed -n '2,10s/^# \{0,1\}//p' "$0" >&2; exit 2 ;;
esac
@@ -0,0 +1,24 @@
#!/bin/sh
# Board defaults and cross-board restore migration, before AT owners open ttys.
# Same-board preferences, APNs, SMS and traffic history remain user-owned.
export PATH="$PATH:/opt/mu300/bin:/usr/sbin:/sbin"
device=$(mu300-device 2>/dev/null)
case $device in v50) slots=2 ;; f50|u30air) slots=1 ;; *) exit 1 ;; esac
[ "$(uci -q get unisoc_modem.main)" = core ] || exit 0
previous=$(uci -q get unisoc_modem.main.platform_defaults)
[ "$previous" != "$device" ] || exit 0
{
if [ -n "$previous" ]; then
# A different board's backup must not select a nonexistent data SIM or
# carry over its custom adapter / interface mapping. Do not erase data.
printf "set unisoc_modem.main.sim_slots='%s'\n" "$slots"
printf "set unisoc_modem.main.data_sim='0'\n"
for key in data_sim_command sim0_device sim1_device; do
printf "set unisoc_modem.main.%s=''\n" "$key"
done
elif [ "$device" = v50 ]; then
printf "set unisoc_modem.main.sim_slots='2'\n"
fi
printf "set unisoc_modem.main.platform_defaults='%s'\n" "$device"
printf 'commit unisoc_modem\n'
} | uci -q batch
+2 -1
View File
@@ -104,7 +104,8 @@ this_device() { "${MU300_BIN:-/opt/mu300/bin}/mu300-device"; }
# their devices in ./devices; one without it is from before the U30 Air and runs on the F50 only (see boot_update).
bundle_runs_here() {
_me=$(this_device)
[ "$_me" = f50 ] && return 0
# Only F50 predates the manifest. V50 needs its AW9523B-capable bundle.
[ "$_me" != f50 ] || return 0
grep -qx './devices' "$2" || return 1
untar -xzf "$1" -C "$3" ./devices && grep -qw "$_me" "$3/devices"
}
@@ -0,0 +1,30 @@
#!/bin/sh
# Validate generated board metadata, preserving valid custom data and UCI.
# Run once during hardware bring-up, before wifi-scripts parses board.json.
set -eu
R=${MU300_SYSROOT:-}
parser=${MU300_BOARD_UCODE:-ucode}
detector=${MU300_BOARD_DETECTOR:-/bin/board_detect}
config=$R/etc/board.json
valid() {
"$parser" -e 'import {readfile,stat} from "fs"; try { let s=stat(ARGV[0]); if(!s || s.size>1048576) exit(1); let x=json(readfile(ARGV[0])); exit(type(x)=="object"?0:1); } catch(e) { exit(1); }' "$1" >/dev/null 2>&1
}
valid "$config" && exit 0
[ ! -L "$config" ] || { echo 'board.json is a symlink; refusing automatic replacement' >&2; exit 1; }
[ -x "$detector" ] || { echo 'board_detect unavailable; cannot recover board.json' >&2; exit 1; }
temp=$config.rebuild.$$
[ ! -e "$temp" ] || exit 1
trap 'rm -f "$temp"' EXIT
"$detector" "$temp" >/dev/null
valid "$temp" || { echo 'board_detect returned invalid JSON; original retained' >&2; exit 1; }
if [ -f "$config" ]; then
# Do not discard the original evidence or overwrite a previous backup.
backup=$config.corrupt.$$
[ ! -e "$backup" ] || exit 1
cp -p "$config" "$backup"
fi
chmod 0644 "$temp"
mv "$temp" "$config"
trap - EXIT
sync
echo 'Recovered generated board.json; wireless settings retained'
+134
View File
@@ -0,0 +1,134 @@
#!/bin/sh
# Three AW9523B indicators; no PMIC writes, periodic AT checks or blink worker.
export PATH="$PATH:/opt/mu300/bin:/usr/sbin:/sbin"
L=${MU300_LED_SYSFS_ROOT:-/sys/class/leds}
R=${MU300_LED_RUN_DIR:-/run}
[ -w "$L/v50:net1:white/brightness" ] || exit 0
cfg() { uci -q get "system.mu300_leds.$1" 2>/dev/null; }
level() {
case $1 in ''|*[!0-9]*) echo "$2" ;; *)
value=$1
while [ "${value#0}" != "$value" ]; do value=${value#0}; done
value=${value:-0}
if [ "${#value}" -le 3 ] && [ "$value" -le 255 ]; then echo "$value"; else echo "$2"; fi ;;
esac
}
lamp() {
local bank=$1 color=$2 intensity=$3 blink=${4:-0} node channel maximum value
for channel in red white blue; do
node=$L/v50:$bank:$channel
[ -w "$node/brightness" ] || continue
echo none > "$node/trigger" 2>/dev/null
value=0
if [ "$channel" = "$color" ]; then
maximum=$(cat "$node/max_brightness" 2>/dev/null)
maximum=$(level "$maximum" 80)
value=$(( (intensity * maximum + 127) / 255 ))
fi
echo "$value" > "$node/brightness"
if [ "$value" -gt 0 ] && [ "$blink" -gt 0 ] && grep -qw timer "$node/trigger"; then
echo timer > "$node/trigger"
echo "$blink" > "$node/delay_on"
echo "$blink" > "$node/delay_off"
fi
done
}
network() {
local slot=$1 state=$2 key=signal enabled brightness color=none blink=0
[ "$slot" = 0 ] || key=signal2
enabled=$(cfg "$key")
brightness=$(level "$(cfg "${key}_brightness")" 255)
[ "$enabled" != 0 ] || brightness=0
[ ! -f "$R/mu300/thermal-alarm" ] || state=thermal
case $state in
online-4g) color=blue ;;
online-5g) color=white ;;
offline) color=red ;;
boot|registering) color=white; blink=500 ;;
modem) color=blue; blink=500 ;;
thermal) color=red; blink=200 ;;
esac
lamp net$((slot+1)) "$color" "$brightness" "$blink"
}
save_network() {
local slot=$1 state=$2 old
old=$(cat "$R/led-status.sim$slot" 2>/dev/null)
[ "$old" != "$state" ] || return 0
printf '%s\n' "$state" > "$R/led-status.sim$slot"
network "$slot" "$state"
}
wifi() {
local state=$(cat "$R/led-status.wifi" 2>/dev/null) color=none freq
if [ "$state" = on ] && [ "$(cfg wifi)" != 0 ]; then
freq=${MU300_LED_WIFI_FREQ:-$(ubus -t 2 call hostapd.wlan0 get_status 2>/dev/null | jsonfilter -e '@.freq')}
case $freq in 2[0-9][0-9][0-9]) color=blue ;; *) color=white ;; esac
fi
lamp wifi "$color" "$(level "$(cfg wifi_brightness)" 127)"
}
registration() {
local slot=$1 line=$2 query=${3:-0} value stat act state IFS=,
case $slot in 0|1) ;; *) return 1 ;; esac
case $line in '+CEREG:'*) ;; *) return 0 ;; esac
value=$(printf '%s' "${line#*:}" | tr -d ' \r"')
set -f
set -- $value
[ "$query" != 1 ] || { [ "$#" -gt 0 ] && shift; }
stat=${1:-}; act=
# Only full responses carry AcT. A short registration event preserves the
# previous radio generation until a full response is available.
[ "$#" -lt 4 ] || act=$4
case $stat in
1|5)
state=online-4g
case $act in 11|12|13|15) state=online-5g ;;
'') [ "$(cat "$R/led-status.sim$slot" 2>/dev/null)" != online-5g ] || state=online-5g ;;
esac ;;
0|2|3|4|6|7|8|9|10)
state=offline
[ "$(cat "$R/led-status.sim$slot" 2>/dev/null)" != absent ] || state=absent ;;
*) return 0 ;;
esac
save_network "$slot" "$state"
}
case ${1:-} in
current) cat "$R/led-status.state" 2>/dev/null || echo boot ;;
wifi-on|wifi-off)
[ "$1" = wifi-on ] && state=on || state=off
echo "$state" > "$R/led-status.wifi"; wifi ;;
refresh)
for slot in 0 1; do network "$slot" "$(cat "$R/led-status.sim$slot" 2>/dev/null || echo absent)"; done
wifi ;;
sim-status) registration "$2" "$3" "${4:-0}" ;;
sim-presence)
case ${2:-} in 0|1) ;; *) exit 2 ;; esac
case ${3:-} in
absent) save_network "$2" absent ;;
present)
old=$(cat "$R/led-status.sim$2" 2>/dev/null)
case $old in absent|'') save_network "$2" registering ;; esac ;;
*) exit 2 ;;
esac ;;
sync)
for slot in 0 1; do
dir=/run/mu300-at; [ "$slot" != 1 ] || dir=/run/mu300-at4
out=$(MU300_AT_DIR=$dir mu300-at -t 3 "AT+SPACTCARD=$slot;+CPIN?" 2>/dev/null)
if printf '%s' "$out" | grep -q '+CME ERROR: 10'; then
save_network "$slot" absent
else
out=$(MU300_AT_DIR=$dir mu300-at -t 3 "AT+SPACTCARD=$slot;+CEREG?" 2>/dev/null | sed -n '/^+CEREG:/p' | head -n1)
registration "$slot" "$out" 1
fi
done ;;
boot|modem|registering)
echo "$1" > "$R/led-status.state"
for slot in 0 1; do echo "$1" > "$R/led-status.sim$slot"; network "$slot" "$1"; done ;;
thermal) for slot in 0 1; do network "$slot" thermal; done ;;
online-4g|online-5g|offline)
echo "$1" > "$R/led-status.state"
slot=$(cat "$R/mu300-data-sim-actual" 2>/dev/null)
case $slot in 0|1) ;; *) slot=$(uci -q get unisoc_modem.main.data_sim);; esac
[ "$slot" = 1 ] || slot=0
[ "$1" != offline ] || [ "$(cat "$R/led-status.sim$slot" 2>/dev/null)" != absent ] || exit 0
echo "$1" > "$R/led-status.sim$slot"; network "$slot" "$1" ;;
*) exit 2 ;;
esac
+52
View File
@@ -0,0 +1,52 @@
"""Generated board metadata recovery with OpenWrt's real ucode parser.
MU300_WRT_IMAGE=mu300-openwrt-base:25.12.5 python -m unittest discover -s tests -p test_board_recovery.py
"""
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
SCRIPT=Path(__file__).resolve().parents[1]/'rootfs/overlay/opt/mu300/bin/openwrt-board-check'
IMAGE=os.environ.get('MU300_WRT_IMAGE')
@unittest.skipUnless(IMAGE and shutil.which('docker'),'OpenWrt Docker fixture is opt-in')
class BoardRecovery(unittest.TestCase):
def run_case(self,original,generated):
with tempfile.TemporaryDirectory(prefix='mu300-board-') as tmp:
root=Path(tmp);cfg=root/'root/etc/board.json';cfg.parent.mkdir(parents=True)
cfg.write_bytes(original)
wireless=cfg.parent/'config/wireless';wireless.parent.mkdir();wireless.write_bytes(b'USER SETTINGS\n')
(root/'generated').write_bytes(generated)
detector=root/'detector'
detector.write_text('#!/bin/sh\necho invoked >> /fixture/detector-called\ncp /fixture/generated "$1"\n',newline='\n')
# chmod inside the fixture also works on Windows bind mounts.
result=subprocess.run(['docker','run','--rm','--platform','linux/arm64',
'-v',str(SCRIPT)+':/check:ro','-v',str(root)+':/fixture',
'-e','MU300_SYSROOT=/fixture/root','-e','MU300_BOARD_DETECTOR=/fixture/detector',
IMAGE,'sh','-c','chmod +x /fixture/detector; sh /check'],capture_output=True,text=True,timeout=30)
self.assertEqual(wireless.read_bytes(),b'USER SETTINGS\n')
self.assertFalse(list(cfg.parent.glob('board.json.rebuild.*')))
return result,cfg.read_bytes(),[p.read_bytes() for p in cfg.parent.glob('board.json.corrupt.*')],(root/'detector-called').exists()
def test_valid_custom_metadata_is_preserved_without_regeneration(self):
original=b'{"model":{"name":"custom"},"wlan":{"phy0":{"custom":true}}}\n'
r,data,backups,called=self.run_case(original,b'{}')
self.assertEqual(r.returncode,0,r.stderr);self.assertEqual(data,original)
self.assertEqual(backups,[]);self.assertFalse(called)
def test_corrupt_metadata_is_backed_up_and_atomically_replaced(self):
original=b'bad\0JSON\xff';generated=b'{"model":{"name":"V50"}}\n'
r,data,backups,called=self.run_case(original,generated)
self.assertEqual(r.returncode,0,r.stderr);self.assertEqual(data,generated)
self.assertEqual(backups,[original]);self.assertTrue(called)
def test_failed_regeneration_leaves_original_and_wireless_untouched(self):
r,data,backups,called=self.run_case(b'broken',b'[1,2]')
self.assertNotEqual(r.returncode,0);self.assertEqual(data,b'broken')
self.assertEqual(backups,[]);self.assertTrue(called)
if __name__=='__main__':unittest.main()
+13
View File
@@ -105,6 +105,19 @@ class Fixture(ShellTest):
class Check(Fixture):
def test_v50_platform_guard_and_read_only_plan(self):
for shell in self.each_shell():
self.device(model='V50',product='MU3351',differ=('teecfg',))
with self.props.open('a') as f:f.write('ro.board.platform=ums9620\n')
before=self.snapshot()
result=self.run_bc(shell,'check')
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
self.assertIn('BOOTCHAIN-PLAN a b teecfg',result.stdout)
self.assertEqual(self.snapshot(),before)
self.props.write_text(self.props.read_text().replace('ums9620','ums9230'))
self.assertNotEqual(self.run_bc(shell,'check').returncode,0)
self.assertEqual(self.snapshot(),before)
def test_identical(self):
for shell in self.each_shell():
before = self.snapshot()
+7
View File
@@ -65,6 +65,13 @@ class EarlyVoltageDiscovery(ShellTest):
for shell in self.each_shell():
r=self.sh(shell,check+'\nsupported')
self.assertEqual(r.returncode,0,r.stderr)
self.stub('sha256sum','printf "%s %s\\n" 5b3183f17af9b416e71dea61e578c61824e4e1df43737a1179032f4b20466b2b "$1"')
for shell in self.each_shell():
self.assertEqual(self.sh(shell,check+'\nsupported').returncode,0)
self.stub('sha256sum','printf "%s %s\\n" unknown "$1"')
for shell in self.each_shell():
self.assertNotEqual(self.sh(shell,check+'\nsupported').returncode,0)
self.stub('sha256sum','printf "%s %s\\n" 5b3183f17af9b416e71dea61e578c61824e4e1df43737a1179032f4b20466b2b "$1"')
(self.tmp/'sys/class/block/mmcblk0p7/size').write_text('4096\n')
for shell in self.each_shell():
self.assertNotEqual(self.sh(shell,check+'\nsupported').returncode,0)
+87
View File
@@ -0,0 +1,87 @@
"""Opt-in real ext4/GPT fixture on a sparse file, never on a hardware disk.
Linux root: MU300_TEST_FREE_LOOP=1 python3 -m unittest discover -s tests -p test_desktop_free_loop.py
"""
import hashlib
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from test_desktop_free_space import snapshot, m, TOP
@unittest.skipUnless(os.name=='posix' and getattr(os,'geteuid',lambda:1)()==0 and
os.environ.get('MU300_TEST_FREE_LOOP')=='1','opt-in Linux root loop fixture')
class RealLoop(unittest.TestCase):
def command(self,*args):
p=subprocess.run(args,capture_output=True,text=True,timeout=120)
self.assertEqual(p.returncode,0,p.stdout+p.stderr)
return p.stdout
def fixture(self,wrong_file=False,changed_gpt=False):
for tool in ('losetup','mkfs.ext4','debugfs','e2fsck','resize2fs','mount','bash'):
if not shutil.which(tool):self.skipTest('missing fixture tool '+tool)
with tempfile.TemporaryDirectory(prefix='mu300-free-range-') as tmp:
base=Path(tmp);disk=base/'disk';stage=base/'stage';stage.mkdir()
payload=base/'payload';payload.mkdir()
total=6*2097152;first,last=snapshot(total,[('userdata',2048,2*2097152-1)])
start=2*2097152;need=2*2097152
newfirst,newlast=m.gpt_add_root(first,last,total,start,need)
tail=total-len(last)//512
before=b'BEFORE-ROOT-GUARD';after=b'AFTER-ROOT-GUARD!'
with disk.open('wb') as f:f.truncate(total*512)
with disk.open('r+b') as f:
f.write(first);f.seek(tail*512);f.write(last)
f.seek(start*512-len(before));f.write(before)
f.seek((start+need)*512);f.write(after)
for name,data in [('before-first',first),('before-last',last),('new-first',newfirst),('new-last',newlast)]:
(payload/('gpt-'+name+'.bin')).write_bytes(data)
image=stage/'openwrt.ext4.new'
with image.open('wb') as f:f.truncate(32<<20)
self.command('mkfs.ext4','-q','-F','-b','4096',str(image))
marker=base/'marker';marker.write_text('verified root\n')
self.command('debugfs','-w','-R',f'write {marker} /marker',str(image))
checksum='0'*64 if wrong_file else hashlib.sha256(marker.read_bytes()).hexdigest()
(stage/'image.sha256').write_text(checksum+' marker\n');(stage/'image-root').mkdir()
image_hash=hashlib.sha256(image.read_bytes()).hexdigest()
repair=payload/'desktop/files/boot/repair';(repair/'lib').mkdir(parents=True)
(repair/'usr/sbin').mkdir(parents=True)
loader=repair/'lib/ld-musl-aarch64.so.1';loader.write_text('#!/bin/sh\nshift 2\nexec "$@"\n');loader.chmod(0o755)
for tool in ('e2fsck','resize2fs'):(repair/'usr/sbin'/tool).symlink_to(shutil.which(tool))
shutil.copyfile(TOP/'desktop/android-loop.sh',payload/'android-loop.sh')
sysroot=base/'sys';(sysroot/'device').mkdir(parents=True)
(sysroot/'device/cid').write_text('a'*32);(sysroot/'size').write_text(str(total))
script=(TOP/'desktop/android-write-free.sh').read_text()
# Substitute only Android's identity/app binding with fixture data.
# Actual loop ioctls, raw dd, ext4 repair/growth, mount and GPT writes run.
script=script.replace('/dev/block/mmcblk[0-9]',str(disk)).replace('/sys/class/block/$node',str(sysroot))
script=script.replace('[ -b "$disk" ]','[ -f "$disk" ]')
script=script.replace('/system/bin/losetup',shutil.which('losetup')).replace(' -S ',' --sizelimit ')
script=script.replace("grep -q -- '-S'","grep -q -- '--sizelimit'")
job=base/'run.sh';job.write_text(script)
if changed_gpt:
first=b'X'+first[1:]
with disk.open('r+b') as f:f.write(first)
env=dict(os.environ,MU300_PAYLOAD_DIR=str(payload),MU300_INSTALL_TMP=str(stage))
try:
result=subprocess.run(['bash',str(job),str(disk),'a'*32,str(total),str(start),str(need),
image_hash,str(len(first)//512),str(tail)],env=env,capture_output=True,text=True,timeout=120)
if wrong_file or changed_gpt:self.assertNotEqual(result.returncode,0)
else:self.assertEqual(result.returncode,0,result.stdout+result.stderr)
with disk.open('rb') as f:
self.assertEqual(f.read(len(first)),first if wrong_file or changed_gpt else newfirst)
f.seek(tail*512);self.assertEqual(f.read(len(last)),last if wrong_file or changed_gpt else newlast)
f.seek(start*512-len(before));self.assertEqual(f.read(len(before)),before)
f.seek((start+need)*512);self.assertEqual(f.read(len(after)),after)
if changed_gpt:
f.seek(start*512);self.assertEqual(f.read(4096),bytes(4096))
finally:
self.assertFalse(self.command('losetup','-j',str(disk)).strip(),'fixture loop leaked')
def test_real_ext4_grows_to_selected_size_and_adjacent_ranges_survive(self):self.fixture()
def test_bad_root_file_never_commits_partition_table(self):self.fixture(wrong_file=True)
def test_changed_gpt_aborts_before_touching_free_range(self):self.fixture(changed_gpt=True)
if __name__=='__main__':unittest.main()
+97
View File
@@ -0,0 +1,97 @@
"""Partition-table and encrypted-data routing tests; no attached device writes."""
import importlib.util
from pathlib import Path
import struct
import unittest
import uuid
from unittest.mock import Mock, patch
import zlib
TOP=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location('free_installer',TOP/'desktop/installer.py')
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
def snapshot(sectors=64*2097152,parts=None):
if parts is None:parts=[('userdata',2048,32*2097152-1)]
table=bytearray(128*128)
for i,(name,a,b) in enumerate(parts):
table[i*128:i*128+16]=uuid.UUID('0fc63daf-8483-4772-8e79-3d69d8477de4').bytes_le
table[i*128+16:i*128+32]=uuid.uuid4().bytes_le
struct.pack_into('<QQ',table,i*128+32,a,b)
encoded=name.encode('utf-16-le');table[i*128+56:i*128+56+len(encoded)]=encoded
guid=uuid.uuid4().bytes_le
def header(at,alt,tab):
h=bytearray(512);h[:8]=b'EFI PART'
struct.pack_into('<III',h,8,0x10000,92,0)
struct.pack_into('<QQQQ',h,24,at,alt,34,sectors-34)
h[56:72]=guid;struct.pack_into('<QIII',h,72,tab,128,128,zlib.crc32(table))
struct.pack_into('<I',h,16,zlib.crc32(h[:92]));return bytes(h)
return bytes(512)+header(1,sectors-1,2)+table, bytes(table)+header(sectors-1,1,sectors-33)
class FreeSpace(unittest.TestCase):
def test_64gb_gap_is_used_without_changing_userdata_or_other_entries(self):
total=64*2097152;first,last=snapshot(total)
info=m.gpt_space(first,last,total);need=10*2097152
offset=m.free_root_range(info,need)
self.assertEqual(offset,32*2097152)
a,b=m.gpt_add_root(first,last,total,offset,need)
changed=m.gpt_space(a,b,total)
self.assertEqual(changed['parts'][0],info['parts'][0])
self.assertEqual(a[:512],first[:512])
self.assertEqual(a[1024:1152],first[1024:1152])
self.assertEqual(a[1280:],first[1280:])
self.assertEqual(changed['parts'][1],{'n':2,'name':'mu300root','start':offset,'end':offset+need-1})
def test_total_free_does_not_replace_a_contiguous_aligned_gap(self):
total=16*2097152
first,last=snapshot(total,[('userdata',2048,6*2097152-1),('reserved',10*2097152,12*2097152-1)])
info=m.gpt_space(first,last,total)
self.assertGreater(sum(n for _,n in info['gaps']),6*2097152)
self.assertIsNone(m.free_root_range(info,6*2097152))
info['safe_gaps']=[]
self.assertIsNone(m.free_root_range(info,2*2097152))
def test_corrupt_copies_overlap_and_metadata_encroachment_are_rejected(self):
total=64*2097152;first,last=snapshot(total)
bad=bytearray(last);bad[1]^=1
with self.assertRaisesRegex(ValueError,'checksum/copy'):m.gpt_space(first,bad,total)
a,b=snapshot(total,[('userdata',2048,10000),('other',9000,20000)])
with self.assertRaisesRegex(ValueError,'Overlapping'):m.gpt_space(a,b,total)
a,b=snapshot(total,[('userdata',1,10000)])
with self.assertRaisesRegex(ValueError,'outside'):m.gpt_space(a,b,total)
with self.assertRaises(ValueError):m.gpt_space(first,last,total-1)
for off,size in ((2048,2*2097152),(32*2097152+1,2*2097152),(32*2097152,40*2097152)):
with self.assertRaises(ValueError):m.gpt_add_root(first,last,total,off,size)
def test_encrypted_android_with_free_gap_skips_reset_and_offline_shrink(self):
a=Mock();a.model='V50';a.slot='a';a.linux='b';a.args=Mock()
s={'NODE':'mmcblk0p1','START':2048,'SIZE':32*2097152-2048,'DISK_SIZE':64*2097152,
'CID':'a'*32,'STATE':'encrypted','TYPE':'block','SOURCE':'/dev/block/dm-0','EXT':'','MAGIC':''}
first,last=snapshot(s['DISK_SIZE']);space=m.gpt_space(first,last,s['DISK_SIZE'])
space.update(first=first,last=last);a.storage.return_value=s;a.gpt.return_value=space
import tempfile
with tempfile.TemporaryDirectory() as tmp:
args=Mock(boot_openwrt=False,tf=False,resume=False,reinstall_part=False,data=False,
format_userdata=False,size='10',backup_dir=tmp)
def backup(path,storage):
path.mkdir();(path/'gpt-first.bin').write_bytes(first);(path/'gpt-last.bin').write_bytes(last)
a.backup.side_effect=backup
expected=m.Outcome('success','free root')
with patch.object(m,'Android',return_value=a),patch.object(m,'module'),patch.object(m,'confirm'), \
patch.object(m,'encrypted',side_effect=AssertionError('encrypted shrink path')), \
patch.object(m,'free_write',return_value=expected) as write:
self.assertIs(m.install(args,Path(tmp),{}),expected)
self.assertEqual(write.call_args.args[-2:],(32*2097152,10*2097152))
a.reboot.assert_not_called();a.flash.assert_not_called()
def test_failed_image_verification_never_writes_boot_or_selects_a_slot(self):
total=64*2097152;first,last=snapshot(total);space=m.gpt_space(first,last,total)
space.update(first=first,last=last)
a=Mock();a.args=Mock();a.t='/tmp/stage';a.shell.return_value='a'*64+' image'
a.run.side_effect=[None,RuntimeError('image readback failed')]
with patch.object(m,'settings',return_value=''):
with self.assertRaisesRegex(RuntimeError,'readback'):m.free_write(a,TOP,Mock(),{'kernel':'7.2'},
{'NODE':'mmcblk0p1','CID':'a'*32,'DISK_SIZE':total},space,32*2097152,10*2097152)
a.flash.assert_not_called();a.live.assert_not_called()
if __name__=='__main__':unittest.main()
+25
View File
@@ -0,0 +1,25 @@
"""Internal-root repair happens before mounting and skips healthy filesystems."""
from helpers import ShellTest, TOP
class DesktopFsck(ShellTest):
def test_clean_error_and_unknown_filesystems(self):
source=(TOP/'desktop/boot/storage.sh').read_text()
function=source[source.index('desktop_ext4_check() {'):source.index('\ndesktop_mount_root()')]
loader=self.tmp/'loader'
loader.write_text('#!/bin/sh\necho "$*" >> "$STUBLOG/fsck"\nexit "${TEST_FSCK_RC:-0}"\n')
loader.chmod(0o755)
function=function.replace('/repair/lib/ld-musl-aarch64.so.1',str(loader)).replace('/etc/mu300-desktop-fsck-force',str(self.tmp/'force'))
function=function.replace('/run/mu300-root-fsck.log',str(self.tmp/'fsck.log'))
self.stub('log','echo "$*" >> "$STUBLOG/log"')
self.stub('setup_usb_gadget','echo usb-ready >> "$STUBLOG/usb"')
root=self.tmp/'root';calls=self.tmp/'fsck'
for shell in self.each_shell():
for magic,state,rc,ok,called in [(0xef53,1,0,True,False),(0xef53,3,1,True,True),(0xef53,3,4,False,True),(0x1234,3,0,False,False)]:
data=bytearray(4096);data[1080:1084]=magic.to_bytes(2,'little')+state.to_bytes(2,'little')
root.write_bytes(data);calls.unlink(missing_ok=True);(self.tmp/'usb').unlink(missing_ok=True)
r=self.sh(shell,function+'\ndesktop_ext4_check "$TEST_ROOT"',TEST_ROOT=root,TEST_FSCK_RC=str(rc))
self.assertEqual(r.returncode==0,ok,r.stderr)
self.assertEqual(calls.exists(),called)
self.assertEqual((self.tmp/'usb').exists(),called)
if called:self.assertIn('-fy '+str(root),calls.read_text())
self.assertLess(source.index('desktop_ext4_check "$d"'),source.index('mount -t ext4 -o noatime "$d" /disk'))
+410
View File
@@ -0,0 +1,410 @@
"""Desktop boot and archive regressions; these tests never connect to a device."""
import hashlib
import base64
import importlib.util
import io
import json
from pathlib import Path
import struct
import subprocess
import sys
import tarfile
import tempfile
import copy
import unittest
from unittest.mock import patch, Mock
import zlib
TOP=Path(__file__).resolve().parents[1]
def load(name):
spec=importlib.util.spec_from_file_location(name,TOP/'desktop'/(name+'.py'))
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m
installer=load('installer');boot=load('boot_image');package=load('package')
repair=load('prepare-tools')
def live(slot='a'):
x=bytearray(32);x[:4]=('_'+slot).encode()+b'\0\0';x[4:8]=b'BCAB';x[8]=1;x[9]=2
x[12],x[14]=(0x9f,0x1e) if slot=='a' else (0x1e,0x9f)
x[16:28]=b'RESERVE-DATA';x[28:]=struct.pack('<I',zlib.crc32(x[:28]));return bytes(x)
def frame(data):
import lz4.block
return bytes.fromhex('02214c18')+struct.pack('<I',len(data:=lz4.block.compress(data,store_size=False)))+data
def unpack_frames(data):
import lz4.block
pos=0;streams=[]
while pos<len(data):
if data[pos:pos+4]!=bytes.fromhex('02214c18'):raise ValueError('bad LZ4 frame')
pos+=4;stream=b''
while pos<len(data) and data[pos:pos+4]!=bytes.fromhex('02214c18'):
size=struct.unpack_from('<I',data,pos)[0];pos+=4
if not size:break
stream+=lz4.block.decompress(data[pos:pos+size],uncompressed_size=8<<20);pos+=size
streams.append(stream)
return streams
def cpio_files(stream):
pos=0;found={}
while pos+110<=len(stream):
if stream[pos:pos+6]!=b'070701':raise ValueError('bad CPIO record')
size=int(stream[pos+54:pos+62],16);ns=int(stream[pos+94:pos+102],16)
name=stream[pos+110:pos+110+ns-1].decode();pos=(pos+110+ns+3)&~3
data=stream[pos:pos+size];pos=(pos+size+3)&~3
if name=='TRAILER!!!':break
found[name]=data
return found
class Desktop(unittest.TestCase):
def test_interactive_exit_shows_success_next_step_and_waits_once(self):
output=io.StringIO();stdin=Mock();stdin.isatty.return_value=True
with patch.object(installer,'main',return_value=installer.Outcome('success','Installed','Reboot manually')), \
patch.object(installer.sys,'stdin',stdin), patch.object(installer.sys,'stdout',output), \
patch('builtins.input',return_value='') as pause:
self.assertEqual(installer.run_cli([]),0)
pause.assert_called_once()
self.assertIn('[SUCCESS / 成功] Installed',output.getvalue())
self.assertIn('Reboot manually',output.getvalue())
def test_pending_stage_is_not_reported_as_completed_installation(self):
output=io.StringIO();stdin=Mock();stdin.isatty.return_value=True
with patch.object(installer,'main',return_value=installer.Outcome('pending','Preparing Android','Choose 5')), \
patch.object(installer.sys,'stdin',stdin), patch.object(installer.sys,'stdout',output), \
patch('builtins.input',side_effect=AssertionError('automation paused')):
self.assertEqual(installer.run_cli(['--no-pause']),0)
self.assertIn('[NEXT STEP REQUIRED / 仍需下一步]',output.getvalue())
self.assertIn('Choose 5',output.getvalue())
self.assertNotIn('[SUCCESS',output.getvalue())
def test_failure_stays_visible_and_preserves_failure_status(self):
output=io.StringIO();stdin=Mock();stdin.isatty.return_value=True
with patch.object(installer,'main',side_effect=RuntimeError('readback mismatch')), \
patch.object(installer.sys,'stdin',stdin), patch.object(installer.sys,'stdout',output), \
patch('builtins.input',return_value='') as pause:
self.assertEqual(installer.run_cli([]),1)
pause.assert_called_once()
self.assertIn('[FAILED / 失败] readback mismatch',output.getvalue())
def test_cancel_and_redirected_input_never_claim_success_or_block(self):
output=io.StringIO();stdin=Mock();stdin.isatty.return_value=False
with patch.object(installer,'main',side_effect=installer.InstallerCancelled()), \
patch.object(installer.sys,'stdin',stdin), patch.object(installer.sys,'stdout',output), \
patch('builtins.input',side_effect=AssertionError('redirected input paused')):
self.assertEqual(installer.run_cli([]),130)
self.assertIn('[CANCELLED / 已取消]',output.getvalue())
self.assertNotIn('[SUCCESS',output.getvalue())
def payload_manifest(self,relocated=False):
names=('boot-linux.img','mu300-openwrt.tar.gz','rootfs-critical.sha256','rootfs.requirements','busybox')
layout={n:'payload/'+n for n in names} if relocated else {}
return {'kernel':'7.2','magisk_layout':layout,
'magisk':{layout.get(n,n):hashlib.sha256(n.encode()).hexdigest() for n in names},
'desktop':{'desktop/files/boot/repair/usr/sbin/resize2fs':'a'*64,'OpenWrt-Installer.exe':'b'*64}}
def test_resume_identity_allows_installer_repairs_and_relocation_but_not_payload_changes(self):
old=self.payload_manifest();new=self.payload_manifest(relocated=True)
new['desktop']['OpenWrt-Installer.exe']='c'*64
new['desktop']['docs/DESKTOP-INSTALL.md']='d'*64
self.assertEqual(installer.resume_payload_id(old),installer.resume_payload_id(new))
for field in ('boot-linux.img','mu300-openwrt.tar.gz','rootfs.requirements','busybox'):
changed=copy.deepcopy(new);changed['magisk']['payload/'+field]='e'*64
self.assertNotEqual(installer.resume_payload_id(old),installer.resume_payload_id(changed))
changed=copy.deepcopy(new);changed['desktop']['desktop/files/boot/repair/usr/sbin/resize2fs']='f'*64
self.assertNotEqual(installer.resume_payload_id(old),installer.resume_payload_id(changed))
def test_old_resume_record_requires_exact_old_metadata_then_compares_payload(self):
with tempfile.TemporaryDirectory() as t:
base=Path(t);old=base/'old';new=base/'new';backup=base/'backups'
for path in (old/'desktop',new/'desktop',backup):path.mkdir(parents=True)
before=self.payload_manifest();after=self.payload_manifest(relocated=True)
oldmeta=old/'desktop/manifest.json';oldmeta.write_text(json.dumps(before))
(new/'desktop/manifest.json').write_text(json.dumps(after))
record=backup/'transaction.json';r={'package':installer.digest(oldmeta)}
expected=installer.resume_payload_id(after)
self.assertEqual(installer.validate_resume_package(new,after,r,record),expected)
changed=copy.deepcopy(after);changed['magisk']['payload/boot-linux.img']='f'*64
with self.assertRaisesRegex(ValueError,'differ'):installer.validate_resume_package(new,changed,r,record)
oldmeta.unlink()
with self.assertRaisesRegex(ValueError,'metadata is missing'):installer.validate_resume_package(new,after,r,record)
r['payload_identity']=expected
self.assertEqual(installer.validate_resume_package(new,after,r,record),expected)
with self.assertRaisesRegex(ValueError,'differ'):installer.validate_resume_package(new,changed,r,record)
installer.bind_resume_package(new,after,r,record)
self.assertEqual((backup/'package-manifest.json').read_bytes(),(new/'desktop/manifest.json').read_bytes())
def test_hotspot_password_uses_visible_input_and_preserves_spaces(self):
with patch('builtins.input',side_effect=['V50_wifi','1234 5678','']), patch.object(installer.getpass,'getpass',side_effect=AssertionError('hidden Wi-Fi input')):
text=installer.settings(None,2048,'part','7.2')
self.assertIn("WIFI_KEY='1234 5678'",text)
def test_reboot_uses_adb_service_and_does_not_hide_failures(self):
android=object.__new__(installer.Android)
with patch.object(android,'call',return_value=b'') as call, patch.object(android,'shell',side_effect=AssertionError('root shell reboot')):
android.reboot()
call.assert_called_once_with('reboot',timeout=30)
with patch.object(android,'call',side_effect=RuntimeError('device offline')):
with self.assertRaisesRegex(RuntimeError,'offline'):android.reboot()
def test_empty_adb_error_has_action_and_status(self):
android=object.__new__(installer.Android);android.adb='adb';android.serial='TEST'
proc=Mock(returncode=1);proc.communicate.return_value=(b'',b'')
with patch.object(installer.subprocess,'Popen',return_value=proc):
with self.assertRaisesRegex(RuntimeError,'ADB reboot failed, exit 1'):android.call('reboot')
def test_loop_selection_accepts_android_block_nodes_and_linux_nodes(self):
import shutil
bash=Path('C:/Program Files/Git/bin/bash.exe') if sys.platform=='win32' else shutil.which('bash')
if not bash or not Path(bash).exists():self.skipTest('Bash is needed for loop selection fixtures')
helper=(TOP/'desktop/android-loop.sh').read_text()
for candidate,present,want in [('/dev/loop31','/dev/block/loop31','/dev/block/loop31'),
('/dev/block/loop31','/dev/block/loop31','/dev/block/loop31'),
('/dev/loop31','/dev/loop31','/dev/loop31')]:
script=helper+f'''\nlosetup() {{ echo {candidate}; }}
desktop_loop_is_block() {{ [ "$1" = {present} ]; }}
desktop_free_loop
'''
p=subprocess.run([str(bash),'-c',script],capture_output=True,text=True,timeout=15)
self.assertEqual(p.returncode,0,p.stderr);self.assertEqual(p.stdout.strip(),want)
script=helper+'''\nlosetup() { echo /dev/loop31oops; }
mknod() { echo UNEXPECTED-NODE-WRITE; exit 99; }
desktop_free_loop
'''
p=subprocess.run([str(bash),'-c',script],capture_output=True,text=True,timeout=15)
self.assertNotEqual(p.returncode,0);self.assertNotIn('UNEXPECTED',p.stdout)
def test_v50_requires_the_exact_product_and_platform(self):
self.assertEqual(installer.android_profile('V50\r\nMU3351\r\n','ums9620'), 'v50')
for names, platform in [('V50\nMU3351','ums9230'), ('V50\nblade','ums9620'),
('F50\nMU3351','ums9620'), ('Blade V50\nblade','ums9620')]:
with self.subTest(names=names), self.assertRaises(ValueError):
installer.android_profile(names,platform)
self.assertEqual(installer.android_profile('F50\nmu300','ums9620'), 'f50')
self.assertEqual(installer.android_profile('U30 Air\nu30air','ums9620'), 'u30air')
def test_android_binary_reads_survive_su_crlf_translation(self):
android=object.__new__(installer.Android);android.su=True
data=bytes(range(256))*4
transported=base64.encodebytes(data).replace(b'\n',b'\r\n')
with patch.object(android,'call',return_value=transported) as call:
self.assertEqual(android.read('cat /sys/firmware/fdt'),data)
self.assertEqual(call.call_args.args[0],'exec-out')
self.assertIn('set -o pipefail;',call.call_args.args[1])
self.assertIn('| base64',call.call_args.args[1])
with patch.object(android,'call',return_value=b'corrupt!'):
with self.assertRaises(ValueError):android.read('cat /sys/firmware/fdt')
def test_large_gpt_backup_covers_all_entries_and_rejects_bad_crc(self):
sectors=20971520;count=512;rows=count*128//512
def header(at,other,table):
raw=bytearray(512);raw[:8]=b'EFI PART';struct.pack_into('<I',raw,12,92)
struct.pack_into('<QQ',raw,24,at,other);struct.pack_into('<QII',raw,72,table,count,128)
struct.pack_into('<I',raw,16,zlib.crc32(raw[:92]));return bytes(raw)
first=header(1,sectors-1,2);last=header(sectors-1,1,sectors-1-rows)
self.assertEqual(installer.gpt_backup_layout(first,last,sectors),(2+rows,sectors-1-rows))
with self.assertRaises(ValueError):installer.gpt_backup_layout(first[:-1],last,sectors)
bad=bytearray(last);bad[80]^=1
with self.assertRaises(ValueError):installer.gpt_backup_layout(first,bytes(bad),sectors)
def native_fixture(self,failure=False):
import shutil
bash=Path('C:/Program Files/Git/bin/bash.exe') if sys.platform=='win32' else shutil.which('bash')
if not bash or not Path(bash).exists():self.skipTest('Bash is needed for the native updater fixture')
with tempfile.TemporaryDirectory() as t:
base=Path(t);disk=base/'disk';old=disk/'openwrt';stage=base/'stage';stage.mkdir()
files={'etc/config/wireless':b'user settings','etc/mu300/desktop-mode':b'part\n',
'lib/firmware/wcnmodem.bin':b'own firmware','opt/mu300/android/vendor/bin/modem_control':b'own modem'}
for n,data in files.items():p=old/n;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(data)
with tarfile.open(base/'mu300-openwrt.tar.gz','w:gz') as a:
for n,data in (('sbin/init',b'#!/bin/sh\n'),('etc/config/wireless',b'image settings'),
('etc/config/new-service',b'new settings'),('etc/mu300/image-version',b'new\n'),
('lib/firmware/regulatory.db',b'image database'),
('lib/firmware/wcnmodem.bin',b'DONOR firmware'),
('opt/mu300/android/vendor/bin/modem_control',b'DONOR modem')):
m=tarfile.TarInfo(n);m.size=len(data);m.mode=0o755;a.addfile(m,io.BytesIO(data))
with installer.payload_rootfs(base) as archive:
shutil.copyfile(archive,stage/'mu300-openwrt-rootfs.tar.gz')
library=(TOP/'rootfs/overlay/opt/mu300/bin/mu300-update').as_posix()
pre='cp() { case "$*" in *wcnmodem.bin*) return 1;; esac; command cp "$@"; };' if failure else ''
script=f'export MU300_LIB=1 MU300_DISK="{disk.as_posix()}"; . "{library}"; STAGE=.; sync() {{ :; }}; {pre} if apply_one openwrt local; then exit 0; else exit 1; fi'
result=subprocess.run([str(bash),'-c',script],cwd=stage,capture_output=True,text=True,timeout=30)
if failure:
self.assertNotEqual(result.returncode,0,result.stdout+result.stderr)
self.assertFalse((disk/'openwrt.old').exists())
for n,data in files.items():self.assertEqual((old/n).read_bytes(),data)
else:
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
self.assertEqual((old/'etc/config/wireless').read_bytes(),b'user settings')
self.assertEqual((old/'etc/config/new-service').read_bytes(),b'new settings')
self.assertEqual((old/'lib/firmware/wcnmodem.bin').read_bytes(),b'own firmware')
self.assertEqual((old/'opt/mu300/android/vendor/bin/modem_control').read_bytes(),b'own modem')
self.assertEqual((disk/'openwrt.old/etc/config/wireless').read_bytes(),b'user settings')
def test_real_native_update_preserves_configuration_and_device_firmware(self):
self.native_fixture()
def test_real_native_vendor_copy_failure_keeps_old_root(self):
self.native_fixture(failure=True)
def test_boot_control_both_slots_preserve_reserved_bytes(self):
for slot in ('a','b'):
source=live(slot);result=boot.boot_control(source,slot)
self.assertEqual(result[:2],b'_b' if slot=='a' else b'_a')
self.assertEqual(result[16:28],source[16:28])
self.assertEqual(zlib.crc32(result[:28]),struct.unpack_from('<I',result,28)[0])
android=12 if slot=='a' else 14
self.assertTrue(result[android]&128)
def test_corrupt_boot_control_is_rejected(self):
with self.assertRaises(ValueError):boot.boot_control(bytes(32),'a')
with self.assertRaises(ValueError):boot.boot_control(live()[:-1]+b'x','a')
def test_fbe_with_plain_superblock_still_requires_format(self):
self.assertTrue(installer.encrypted({'state':'encrypted','type':'file'},'/dev/block/mmcblk0p40','1020f5f2'))
self.assertTrue(installer.encrypted({'state':'unencrypted'},'/dev/block/dm-0','53ef'))
self.assertFalse(installer.encrypted({'state':'unencrypted','type':''},'/dev/block/mmcblk0p40','53ef'))
with self.assertRaises(ValueError):installer.encrypted({'state':''},'/dev/block/mmcblk0p40','1020f5f2')
def test_fractional_size_and_bounds(self):
self.assertEqual(installer.image_size('6.5',10240),6656)
for value in ('nan','inf','1.9','11','hello'):
with self.subTest(value=value),self.assertRaises(ValueError):installer.image_size(value,10240)
target,need=installer.allocation(32*2097152-34,10240)
self.assertEqual(need,10*2097152);self.assertEqual(target%2048,0)
self.assertLessEqual(target+need,32*2097152-34)
def test_resume_wrong_device_geometry_or_marker_never_pass(self):
s={'CID':'a'*32,'NODE':'mmcblk0p40','START':65536,'SIZE':20971520}
r={'storage':s.copy(),'android_slot':'a','serial':'SERIAL','target':s['SIZE'],'need':8388608,'token':'b'*32}
marker=('MU300-PART-PREPARED-V2 '+r['token']+'\n').encode()
geom=(s['START']+s['SIZE'],r['need'])
installer.validate_resume(s,r,'a','SERIAL',geom,marker)
for args in (({**s,'CID':'c'*32},r,'a','SERIAL',geom,marker),(s,r,'b','SERIAL',geom,marker),
(s,r,'a','WRONG',geom,marker),(s,r,'a','SERIAL',(geom[0],geom[1]-2048),marker),
(s,r,'a','SERIAL',geom,b'WRONG')):
with self.assertRaises(ValueError):installer.validate_resume(*args)
def test_environment_quotes_user_strings(self):
value="my Wi-Fi ' $(touch /tmp/not-run)"
text=installer.env({'SSID':value})
self.assertNotIn('SSID="',text)
import shlex
self.assertEqual(shlex.split(text.split('=',1)[1])[0],value)
def test_public_update_archive_has_no_donor_runtime(self):
with tempfile.TemporaryDirectory() as t:
src=Path(t)/'original.tar.gz';dst=Path(t)/'public.tar.gz'
names=('bin/busybox','lib/firmware/wcnmodem.bin','lib/firmware/regulatory.db',
'lib/firmware/rtl_nic/rtl.bin','opt/mu300/android/vendor/bin/modem_control')
with tarfile.open(src,'w:gz') as f:
for n in names:
m=tarfile.TarInfo('./'+n);m.size=4;f.addfile(m,io.BytesIO(b'data'))
original=src.read_bytes();installer.public_rootfs(src,dst)
self.assertEqual(src.read_bytes(),original)
with tarfile.open(dst) as f:self.assertEqual(set(m.name for m in f),{'./bin/busybox','./lib/firmware/regulatory.db','./lib/firmware/rtl_nic/rtl.bin'})
def test_shared_rootfs_tf_is_unchanged_and_temp_is_cleaned_on_failure(self):
with tempfile.TemporaryDirectory() as t:
root=Path(t);source=root/'mu300-openwrt.tar.gz'
with tarfile.open(source,'w:gz') as tar:
for name in ('bin/busybox','lib/firmware/wcnmodem.bin'):
member=tarfile.TarInfo(name);member.size=1;tar.addfile(member,io.BytesIO(b'B'))
original=source.read_bytes()
with installer.payload_rootfs(root,tf=True) as archive:
self.assertEqual(archive,source)
self.assertEqual(archive.read_bytes(),original)
for fail in (False,True):
try:
with installer.payload_rootfs(root) as archive:
self.assertNotEqual(archive.parent,root)
with tarfile.open(archive) as tar:self.assertEqual(tar.getnames(),['bin/busybox'])
if fail:raise RuntimeError('upload failed')
except RuntimeError as exc:
self.assertTrue(fail);self.assertEqual(str(exc),'upload failed')
self.assertFalse(archive.exists())
self.assertFalse(archive.parent.exists())
self.assertEqual(source.read_bytes(),original)
self.assertEqual(list(root.iterdir()),[source])
def test_android_payload_uses_shared_tf_and_filtered_internal_rootfs(self):
with tempfile.TemporaryDirectory() as t:
root=Path(t);source=root/'mu300-openwrt.tar.gz'
with tarfile.open(source,'w:gz') as tar:
for name in ('bin/busybox','lib/firmware/wcnmodem.bin'):
member=tarfile.TarInfo(name);member.size=1;tar.addfile(member,io.BytesIO(b'B'))
for tf in (False,True):
android=object.__new__(installer.Android);android.bb='/tmp/busybox';android.p='/tmp/payload'
uploads=[]
def upload(path,name):
if name=='mu300-openwrt.tar.gz':
with tarfile.open(path) as tar:uploads.append((Path(path),tar.getnames()))
with patch.object(android,'push',side_effect=upload), patch.object(android,'shell'), patch.object(android,'run'):
android.prepare_payload(root,tf=tf)
self.assertEqual(len(uploads),1)
path,names=uploads[0]
self.assertEqual(names,['bin/busybox','lib/firmware/wcnmodem.bin'] if tf else ['bin/busybox'])
self.assertEqual(path.exists(),tf)
self.assertEqual(path==source,tf)
def test_boot_append_leaves_kernel_original_frame_and_log_tail_intact(self):
with tempfile.TemporaryDirectory() as t:
assets=Path(t);(assets/'repair').mkdir()
for n in ('storage.sh','install-part.sh','part-prepare.sh','part-progress.sh','mu300-gpt'):
(assets/n).write_bytes((TOP/'desktop/boot'/n).read_bytes())
for n,source in (('original-init',TOP/'boot/init'),('build-boot-image.py',TOP/'boot/build-boot-image.py')):(assets/n).write_bytes(source.read_bytes())
(assets/'repair/manifest.json').write_text('{"sha256":{}}')
ram=frame(b'original ramdisk');kernel=b'K'*4096
base=bytearray(64<<20);base[:8]=b'ANDROID!';struct.pack_into('<II',base,8,len(kernel),len(ram));struct.pack_into('<I',base,40,4)
base[44:55]=b'loglevel=5\0';base[4096:8192]=kernel;base[8192:8192+len(ram)]=ram
off=(8192+len(ram)+4095)&~4095;base[off:off+64]=b'V'*64;base[-64:-60]=b'AVBf';struct.pack_into('>IIQQQ',base,len(base)-60,1,0,off,off,64)
before=bytes(base)
for slot in ('a','b'):
out=boot.build(before,assets,'prepare',live(slot),slot,prepare='request')
self.assertEqual(out[4096:8192],kernel);self.assertEqual(out[44:55],b'loglevel=5\0')
rs=struct.unpack_from('<I',out,12)[0]
streams=unpack_frames(out[8192:8192+rs]);self.assertEqual(streams[0],b'original ramdisk')
contents=cpio_files(streams[-1]);self.assertEqual(contents['etc/mu300-desktop-root-mode'],b'prepare\n')
self.assertEqual(contents['etc/mu300-desktop-prepare'],b'request\n')
self.assertNotIn(b'e5root',contents['init'])
self.assertEqual(len(out),len(before));self.assertEqual(out[48<<20:56<<20],before[48<<20:56<<20])
self.assertEqual(bytes(base),before)
def test_tool_architecture_guard(self):
with tempfile.TemporaryDirectory() as t:
source=Path(t)/'source';dest=Path(t)/'dest';source.mkdir();dest.mkdir()
p=source/'sbin/fsck.f2fs';p.parent.mkdir();p.write_bytes(b'not ARM64')
with self.assertRaises(ValueError):repair.prepare(source,dest)
def test_all_original_members_survive_augmentation_and_checks_detect_tampering(self):
with tempfile.TemporaryDirectory() as t:
stage=Path(t)/'stage';tools=Path(t)/'tools';stage.mkdir();tools.mkdir()
for n in ('busybox','boot-linux.img','payload.sha256','customize.sh','module.prop'):(stage/n).write_bytes(('original '+n).encode())
with tarfile.open(stage/'mu300-openwrt.tar.gz','w:gz') as f:
m=tarfile.TarInfo('bin/busybox');m.size=1;f.addfile(m,io.BytesIO(b'B'))
for n in repair.FILES:
p=tools/n;p.parent.mkdir(parents=True,exist_ok=True)
elf=bytearray(64);elf[:6]=b'\x7fELF\x02\x01';struct.pack_into('<H',elf,18,183);p.write_bytes(elf)
(stage/'customize.sh').write_text('ORIGINAL_PAYLOAD=$MODPATH\n[ -f "$MODPATH/boot-linux.img" ]\n')
original=package.original_files(stage)
manifest=package.assemble(stage,tools,'7.2')
self.assertEqual({n:package.sha(stage/manifest['magisk_layout'][n]) for n in original},original)
self.assertEqual([p.relative_to(stage).as_posix() for p in stage.rglob('*.tar.gz')],['payload/mu300-openwrt.tar.gz'])
self.assertEqual({p.name for p in stage.iterdir() if p.is_file()}, {'OpenWrt-Installer.py','customize.sh','module.prop'})
self.assertTrue((stage/'launchers/start-installer.cmd').is_file())
self.assertTrue((stage/'docs/DESKTOP-INSTALL.md').is_file())
self.assertEqual(installer.payload_file(stage,'boot-linux.img'),stage/'payload/boot-linux.img')
import shutil, shlex
bash=Path('C:/Program Files/Git/bin/bash.exe') if sys.platform=='win32' else shutil.which('bash')
if bash and Path(bash).exists():
p=shlex.quote(stage.as_posix());wrapper=shlex.quote((stage/'customize.sh').as_posix())
result=subprocess.run([str(bash),'-c',f'MODPATH={p}; . {wrapper}; printf "%s\\n%s\\n" "$ORIGINAL_PAYLOAD" "$MODPATH"'],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual(result.stdout.splitlines(),[(stage/'payload').as_posix(),stage.as_posix()])
installer.verify(stage)
result=subprocess.run([sys.executable,str(stage/'OpenWrt-Installer.py'),'--check'],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stderr)
(stage/'desktop/configure.sh').write_text('tampered')
with self.assertRaises(ValueError):installer.verify(stage)
if __name__=='__main__':unittest.main()
+64 -6
View File
@@ -5,13 +5,14 @@ import shutil
import time
import unittest
from helpers import BIN, ShellTest
from helpers import BIN, TOP, ShellTest
class Device(ShellTest):
def root(self, device=None, dt_u30=False):
r = self.tmp / 'root'
(r / 'run' / 'mu300').mkdir(parents=True, exist_ok=True)
shutil.rmtree(r / 'proc/device-tree', ignore_errors=True)
if device is not None:
(r / 'run' / 'mu300' / 'device').write_text(device + '\n')
if dt_u30:
@@ -20,7 +21,7 @@ class Device(ShellTest):
def test_mu300_device(self):
cases = [(None, False, 'f50'), (None, True, 'u30air'), ('u30air', False, 'u30air'),
('f50', True, 'f50')] # what init wrote wins over the device tree
('f50', True, 'u30air')] # hardware wins over a stale boot label
for device, dt, want in cases:
r = self.root(device, dt)
for shell in self.each_shell():
@@ -29,12 +30,45 @@ class Device(ShellTest):
(r / 'run' / 'mu300' / 'device').unlink(missing_ok=True)
def test_lan_ip(self):
for device, want in (('f50', '192.168.77.1'), ('u30air', '192.168.78.1'), ('', '192.168.77.1')):
for device, want in (('f50', '192.168.77.1'), ('v50', '192.168.77.1'), ('u30air', '192.168.78.1'), ('', '192.168.77.1')):
r = self.root(device)
for shell in self.each_shell():
out = self.script(shell, BIN / 'mu300-lan-ip', MU300_SYSROOT=r, MU300_BIN=BIN).stdout.strip()
self.assertEqual(out, want, device)
def test_live_tree_overrides_labels_in_both_directions(self):
for tree in ('soc/soc:ap-ahb/i2c@2270000/aw9523b_led@5b',
'soc/ap-ahb/i2c@2270000/aw9523b_led@5b', ''):
r=self.root('v50' if not tree else 'f50')
(r/'proc/device-tree'/tree).mkdir(parents=True)
for shell in self.each_shell():
self.assertEqual(self.script(shell,BIN/'mu300-device',MU300_SYSROOT=r).stdout.strip(),
'v50' if tree else 'f50')
def test_unknown_runtime_label_never_becomes_a_board(self):
r=self.root('other-board')
for shell in self.each_shell():
self.assertEqual(self.script(shell,BIN/'mu300-device',MU300_SYSROOT=r).stdout.strip(),'f50')
def test_initramfs_and_runtime_agree_despite_a_stale_label(self):
source=(TOP/'boot/init').read_text()
fragment=source[source.index('if [ -d /proc/device-tree/charger_policy_service ]; then'):
source.index('# its modules only')]
for tree,want in [('charger_policy_service','u30air'),
('soc/soc:ap-ahb/i2c@2270000/aw9523b_led@5b','v50'),
('soc/ap-ahb/i2c@2270000/aw9523b_led@5b','v50'),('', 'f50')]:
r=self.root('f50' if want!='f50' else 'v50')
(r/'proc/device-tree'/tree).mkdir(parents=True)
(r/'etc').mkdir(exist_ok=True)
(r/'etc/mu300-device').write_text('f50\n' if want!='f50' else 'v50\n')
code=fragment.replace('/proc/device-tree',str(r/'proc/device-tree')).replace('/etc/mu300-device',str(r/'etc/mu300-device'))
for shell in self.each_shell():
init=self.sh(shell,code+'\nprintf "%s\\n" "$DEVICE"')
runtime=self.script(shell,BIN/'mu300-device',MU300_SYSROOT=r)
self.assertEqual(init.returncode,0,init.stderr)
self.assertEqual(init.stdout.strip(),want)
self.assertEqual(runtime.stdout.strip(),want)
class Led(ShellTest):
# the U30 Air's: power is the battery LED's white (the PMIC's green channel), the network LED blue on 4G
@@ -456,7 +490,7 @@ elif op.startswith('w'):
self.stub('i2ctransfer', 'exec python3 "$STUBLOG/eeprom.py" "$@"')
# libgpiod 2: holds the line until killed
self.stub('gpioset', '[ "$1" = --help ] && { echo " -c, --chip"; exit 0; }; '
'[ "$*" = "-c gpiochip4 190=0" ] || exit 1; touch "$STUBLOG/held"; '
'[ "$*" = "-c gpiochip4 ${TEST_NFC_PIN:-190}=0" ] || exit 1; touch "$STUBLOG/held"; '
'trap \'rm -f "$STUBLOG/held"; exit 0\' TERM; while :; do sleep 0.05; done')
self.conf = self.tmp / 'hotspot.conf'
self.conf.write_text('SSID=U30 AIR\nPSK=secret pass!\nBAND=5\n')
@@ -468,7 +502,7 @@ elif op.startswith('w'):
def nfc(self, shell, *args, device='u30air'):
(self.root / 'run/mu300/device').write_text(device + '\n')
return self.script(shell, BIN / 'mu300-nfc', *args, MU300_SYSROOT=self.root, MU300_BIN=BIN,
MU300_HOTSPOT_CONF=self.conf)
MU300_HOTSPOT_CONF=self.conf, TEST_NFC_PIN='189' if device=='v50' else '190')
def writes(self):
w = self.tmp / 'writes'
@@ -562,7 +596,7 @@ elif op.startswith('w'):
self.blank()
r = self.nfc(shell, 'wifi', device='f50')
self.assertEqual(r.returncode, 1)
self.assertIn('only the U30 Air', r.stderr)
self.assertIn('no supported NFC tag', r.stderr)
self.assertEqual(self.nfc(shell, 'blink').returncode, 2)
self.assertEqual(self.nfc(shell, 'url').returncode, 1)
# no capability container: not written
@@ -572,6 +606,30 @@ elif op.startswith('w'):
self.assertIn('capability container', r.stderr)
self.assertEqual(self.writes(), [])
def test_v50_uses_its_stock_reset_pin_and_read_only_discovery(self):
node=self.root/'proc/device-tree/ntag_fm11_gpio';node.mkdir(parents=True)
(node/'ntag-reset-gpio').write_bytes(bytes.fromhex('00000018000000bd00000000'))
for shell in self.each_shell():
self.blank()
r=self.nfc(shell,'supported',device='v50')
self.assertEqual(r.returncode,0,r.stderr)
self.assertFalse((self.tmp/'held').exists());self.assertEqual(self.writes(),[])
r=self.nfc(shell,'wifi',device='v50')
self.assertEqual((r.returncode,r.stdout.strip()),(0,'wifi: U30 AIR (with its password)'),r.stderr)
self.assertFalse((self.tmp/'held').exists())
def test_v50_unknown_reset_binding_is_rejected_without_touching_the_tag(self):
node=self.root/'proc/device-tree/ntag_fm11_gpio';node.mkdir(parents=True)
prop=node/'ntag-reset-gpio'
for value in (None,bytes(8),bytes.fromhex('00000018000000be00000000')):
prop.unlink(missing_ok=True)
if value is not None:prop.write_bytes(value)
for shell in self.each_shell():
self.blank()
r=self.nfc(shell,'wifi',device='v50')
self.assertEqual(r.returncode,1,r.stderr)
self.assertFalse((self.tmp/'held').exists());self.assertEqual(self.writes(),[])
class Ttl(ShellTest):
def setUp(self):
+26 -1
View File
@@ -19,7 +19,7 @@ p=Path(os.environ['STUBLOG']);f=p/'radio.json';s=json.loads(f.read_text());cmd=s
with (p/'commands').open('a') as log:log.write(cmd+'\\n')
slot=int(re.search(r'SPACTCARD=(\\d)',cmd)[1])
if cmd.endswith('+CFUN?'):print('+CFUN: '+str(s['cfun'][slot]))
elif cmd.endswith('+CPIN?'):print('+CPIN: READY')
elif cmd.endswith('+CPIN?'):print('+CPIN: READY' if slot in s.get('present',[0,1]) else '+CME ERROR: 10')
elif cmd.endswith('+SPTESTMODE?'):print('+SPTESTMODE: 134,128,1,20,3,1')
elif cmd.endswith('+SPSWDATA?'):print('+SPSWDATA: '+str(s['data']))
elif cmd.endswith('+SPSWDATA'):s['data']=slot
@@ -64,3 +64,28 @@ f.write_text(json.dumps(s));print('OK')
self.assertNotEqual(r.returncode,0)
self.assertEqual((self.tmp/'commands').read_text(),'')
ready.write_text(str(os.getpid()))
def test_empty_slot_does_not_block_the_inserted_card(self):
for shell in self.each_shell():
self.reset([0,0])
(self.tmp/'radio.json').write_text(json.dumps(dict(cfun=[0,0],data=0,present=[1])))
r=self.script(shell,SCRIPT,**self.extra)
self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(json.loads((self.tmp/'radio.json').read_text())['cfun'],[0,1])
writes=[s for s in (self.tmp/'commands').read_text().splitlines() if not s.endswith('?')]
self.assertEqual(writes,['AT+SPACTCARD=1;+SFUN=2','AT+SPACTCARD=1;+SPTESTMODEM=134,128',
'AT+SPACTCARD=1;+SPSWDATA','AT+SPACTCARD=1;+SFUN=4'])
def test_only_sim0_and_already_active_sim1(self):
for shell in self.each_shell():
self.reset([0,0])
(self.tmp/'radio.json').write_text(json.dumps(dict(cfun=[0,0],data=0,present=[0])))
r=self.script(shell,SCRIPT,**dict(self.extra,MU300_SIM_SLOT='0'))
self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(json.loads((self.tmp/'radio.json').read_text())['cfun'],[1,0])
self.assertNotIn('AT+SPACTCARD=1;+SFUN',(self.tmp/'commands').read_text())
(self.tmp/'radio.json').write_text(json.dumps(dict(cfun=[0,1],data=1,present=[1])))
(self.tmp/'commands').write_text('')
r=self.script(shell,SCRIPT,**self.extra)
self.assertEqual(r.returncode,0,r.stderr)
self.assertNotIn('SFUN=',(self.tmp/'commands').read_text())
+28 -1
View File
@@ -6,6 +6,7 @@ from helpers import TOP, ShellTest
F50 = '324950664950 device usb:1 product:MU300 model:F50 device:MU300 transport_id:1'
U30 = '323960377386 device usb:2 product:U30Air model:U30_Air device:U30Air transport_id:2'
V50 = 'v50-test device usb:4 product:MU3351 model:V50 device:MU3351 transport_id:5'
TABLET = 'd16d93c5 device usb:3 product:nabu_global model:21051182G device:nabu transport_id:3'
OFFLINE = '192.168.31.1:55555 offline product:MU5358 model:MU5358 device:MU5358 transport_id:4'
@@ -23,7 +24,7 @@ class SelectDevice(ShellTest):
def test_one_device_that_is_the_target(self):
for shell in self.each_shell():
for dev, serial in ((F50, '324950664950'), (U30, '323960377386')):
for dev, serial in ((F50, '324950664950'), (U30, '323960377386'), (V50, 'v50-test')):
out = self.run_select(shell, [dev])
self.assertNotIn('ASKED', out)
self.assertIn(f'serial={serial}', out)
@@ -56,6 +57,32 @@ class SelectDevice(ShellTest):
out = self.run_select(shell, [TABLET], mode='quiet')
self.assertNotIn('ASKED', out)
self.assertIn('rc=1 serial=none', out)
out = self.run_select(shell, [TABLET, V50], mode='quiet')
self.assertNotIn('ASKED', out)
self.assertIn('rc=0 serial=v50-test', out)
def test_model_prefix_is_not_a_supported_target(self):
for shell in self.each_shell():
out=self.run_select(shell,[V50.replace('model:V50','model:V500').replace('MU3351','MU33510')],mode='quiet')
self.assertIn('rc=1 serial=none',out)
class AndroidProfile(ShellTest):
def test_f50_v50_and_u30air_match_the_desktop_installer(self):
import runpy
desktop=runpy.run_path(str(TOP/'desktop/installer.py'))
cases=[('F50','MU300','ums9620','f50'),('V50','MU3351','ums9620','v50'),
('V50','MU3351','other',None),('V50','MU300','ums9620',None),
('F50','MU3351','ums9620',None),('U30_Air','U30Air','ums9620','u30air')]
for model,device,platform,want in cases:
if want is None:
with self.assertRaises(ValueError):desktop['android_profile'](model+'\n'+device,platform)
else:self.assertEqual(desktop['android_profile'](model+'\n'+device,platform),want)
for shell in self.each_shell():
result=self.sh(shell,f'. "{TOP}/tools/android-profile.sh"; mu300_android_profile "$MODEL" "$DEVICE" "$PLATFORM"',
MODEL=model,DEVICE=device,PLATFORM=platform)
if want is None:self.assertEqual(result.returncode,2,result.stderr)
else:self.assertEqual((result.returncode,result.stdout.strip()),(0,want),result.stderr)
if __name__ == '__main__':
+32
View File
@@ -15,6 +15,33 @@ DEFAULTS = TOP / 'openwrt/overlay/etc/uci-defaults/90-mu300'
class LedSettings(unittest.TestCase):
def test_v50_without_physical_groups_never_drives_unrelated_lamps(self):
with tempfile.TemporaryDirectory() as tmp:
base=Path(tmp);leds=base/'leds';run=base/'run';run.mkdir()
bindir=base/'bin';bindir.mkdir()
for name, maximum in [('aw_led',120),('red',120),('green',80),('blue',120),
('sc27xx:red',255),('sc27xx:green',255),('sc27xx:blue',255)]:
node=leds/name;node.mkdir(parents=True)
(node/'brightness').write_text('7\n' if name.startswith('sc27xx:') else '0\n')
(node/'max_brightness').write_text(str(maximum)+'\n')
(node/'trigger').write_text('none\n')
for name,body in [('mu300-device','echo v50'),('uci','exit 0')]:
p=bindir/name;p.write_text('#!/bin/sh\n'+body+'\n');p.chmod(0o755)
env=dict(os.environ,PATH=f'{bindir}:{os.environ["PATH"]}',
MU300_LED_SYSFS_ROOT=str(leds),MU300_LED_RUN_DIR=str(run))
def apply(state,expected):
p=subprocess.run(['sh',str(LED),state],env=env,capture_output=True,text=True)
self.assertEqual(p.returncode,0,p.stderr)
actual=tuple((leds/n/'brightness').read_text().strip() for n in ('red','green','blue'))
self.assertEqual(actual,expected)
for n in ('red','green','blue'):
self.assertEqual((leds/('sc27xx:'+n)/'brightness').read_text(),'7\n')
self.assertFalse((leds/'white').exists())
apply('online-4g',('0','0','0'))
apply('online-5g',('0','0','0'))
apply('offline',('0','0','0'))
apply('wifi-on',('0','0','0'))
def test_signal_and_wifi_brightness_are_independent_and_persistent(self):
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
@@ -136,6 +163,11 @@ for (const [locale, title, signal, wifi] of [
const actual = page.render([{ 'keyboard-backlight': { max_brightness: 127, triggers: [] } }, []]);
const realWifi = actual.sections[0].options.find(o => o.key === 'wifi_brightness');
if (realWifi.datatype !== 'range(0,127)' || realWifi.default !== '127') throw Error('hardware maximum');
const v50 = page.render([{ aw_led: {triggers: []}, red: {triggers: []}, green: {triggers: []}, blue: {triggers: []} }, []]);
if (v50.sections[0].options.some(o => o.key === 'wifi' || o.key === 'wifi_brightness')) throw Error('V50 has no verified independent Wi-Fi lamp');
const adapted = page.render([{ 'v50:net1:white': { max_brightness: 80, triggers: [] } }, []]);
if (!adapted.sections[0].options.some(o => o.key === 'signal2') ||
!adapted.sections[0].options.some(o => o.key === 'wifi')) throw Error('V50 physical lamps missing');
}
'''
result = subprocess.run(['node', '-', str(UI)], input=harness, capture_output=True,
+59
View File
@@ -0,0 +1,59 @@
"""Board migration precedes modem ownership, and keeps later user settings."""
from helpers import ShellTest, TOP
SCRIPT = TOP/'rootfs/overlay/opt/mu300/bin/mu300-platform-config'
class PlatformConfig(ShellTest):
def setUp(self):
super().setUp()
self.stub('mu300-device', 'echo "$TEST_DEVICE"')
self.stub('uci', '''
if [ "$2" = get ]; then
case "$3" in
unisoc_modem.main) echo core ;;
*.platform_defaults) echo "${TEST_DEFAULTS:-}" ;;
esac
elif [ "$2" = batch ]; then cat > "$STUBLOG/batch"; fi
''')
def test_initial_defaults_and_same_board_preferences(self):
for shell in self.each_shell():
for device, marker, changes in [('v50','',True),('v50','v50',False),('f50','',True),
('u30air','',True),('f50','f50',False),('u30air','u30air',False)]:
batch=self.tmp/'batch'; batch.unlink(missing_ok=True)
r=self.script(shell,SCRIPT,TEST_DEVICE=device,TEST_DEFAULTS=marker)
self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(batch.exists(),changes)
if changes:
commands=batch.read_text()
self.assertIn("platform_defaults='"+device+"'",commands)
if device=='v50':self.assertIn("sim_slots='2'",commands)
else:self.assertNotIn('sim_slots=',commands)
self.assertNotIn('data_sim=',commands)
def test_cross_board_restore_resets_only_adapter_configuration(self):
for shell in self.each_shell():
for device,marker,slots in [('f50','v50',1),('u30air','v50',1),('v50','f50',2),('f50','u30air',1)]:
batch=self.tmp/'batch';batch.unlink(missing_ok=True)
r=self.script(shell,SCRIPT,TEST_DEVICE=device,TEST_DEFAULTS=marker)
self.assertEqual(r.returncode,0,r.stderr)
commands=batch.read_text()
self.assertIn(f"sim_slots='{slots}'",commands)
self.assertIn("data_sim='0'",commands)
for key in ('data_sim_command','sim0_device','sim1_device'):
self.assertIn(f"{key}=''",commands)
self.assertNotIn('delete ',commands)
self.assertNotIn('network.',commands)
self.assertNotIn('sms',commands)
self.assertNotIn('traffic',commands)
def test_failed_save_is_reported(self):
self.stub('uci','case "$2" in get) [ "$3" != unisoc_modem.main ] || echo core ;; batch) cat >/dev/null; exit 1 ;; esac')
for shell in self.each_shell():
self.assertNotEqual(self.script(shell,SCRIPT,TEST_DEVICE='v50').returncode,0)
def test_at_owners_start_after_platform_defaults(self):
source=(TOP/'openwrt/overlay/etc/init.d/mu300-atd').read_text()
self.assertLess(source.index('/mu300-platform-config'),source.index('procd_open_instance atd'))
for file in ['tools/build-openwrt-tf-magisk.sh','tools/make-release.sh','openwrt/build-rootfs.sh']:
self.assertIn('mu300-platform-config',(TOP/file).read_text())
+23 -2
View File
@@ -8,7 +8,7 @@ import struct
import tarfile
import unittest
from helpers import BIN, ShellTest
from helpers import BIN, TOP, ShellTest
class Update(ShellTest):
@@ -212,8 +212,10 @@ class Update(ShellTest):
new = self.bundle('new.tar.gz', 'f50 u30air\n')
old = self.bundle('old.tar.gz', None)
f50only = self.bundle('f50.tar.gz', 'f50\n')
v50 = self.bundle('v50.tar.gz', 'f50 v50 u30air\n')
cases = [('f50', new, True), ('f50', old, True), ('u30air', new, True), ('u30air', old, False),
('u30air', f50only, False)]
('u30air', f50only, False), ('v50', v50, True), ('v50', old, False),
('v50', new, False), ('v50', f50only, False), ('f50', v50, True)]
for shell in self.each_shell():
for dev, b, ok in cases:
self.device(dev)
@@ -223,6 +225,25 @@ class Update(ShellTest):
self.assertEqual(r.stdout.strip(), 'YES' if ok else 'NO', (dev, b.name, r.stderr))
(d / 'devices').unlink(missing_ok=True)
def test_v50_is_advertised_only_for_an_aw9523b_kernel(self):
source=(TOP/'upstream/make-bundle.sh').read_text()
start=source.index("devices='f50 u30air'")
end=source.index('\ntar -C "$W/b"',start)
code=source[start:end]
build=self.tmp/'build';build.mkdir()
stage=self.tmp/'stage';(stage/'b').mkdir(parents=True)
for shell in self.each_shell():
for config,expected in [('CONFIG_LEDS_AW9523B=y\n',True),
('CONFIG_LEDS_AW9523B=m\n',False),
('# CONFIG_LEDS_AW9523B is not set\n',False)]:
(build/'kernel.config').write_text(config)
result=self.sh(shell,code,UO=build,W=stage)
self.assertEqual(result.returncode,0,result.stderr)
boards=(stage/'b/devices').read_text().split()
self.assertEqual('v50' in boards,expected)
self.assertIn('f50',boards)
self.assertIn('u30air',boards)
if __name__ == '__main__':
unittest.main()
+89
View File
@@ -0,0 +1,89 @@
"""V50's two network banks and hotspot bank do not overwrite one another."""
import os
from helpers import ShellTest, TOP
SCRIPT=TOP/'rootfs/overlay/opt/mu300/bin/v50-led-status'
class V50Leds(ShellTest):
def setUp(self):
super().setUp()
self.leds=self.tmp/'leds'; self.run=self.tmp/'run';self.run.mkdir()
for bank in ('net1','net2','wifi'):
for color,maximum in [('red',120),('white',80),('blue',120)]:
p=self.leds/f'v50:{bank}:{color}';p.mkdir(parents=True)
(p/'brightness').write_text('0\n');(p/'trigger').write_text('none timer\n')
(p/'max_brightness').write_text(str(maximum))
self.stub('uci','''case "$3" in
*.signal) echo "${TEST_SIGNAL:-1}" ;;
*.signal2) echo "${TEST_SIGNAL2:-1}" ;;
*.signal_brightness) echo "${TEST_BRIGHTNESS:-255}" ;;
*.signal2_brightness) echo 128 ;;
*.wifi) echo 1 ;;
*.wifi_brightness) echo 255 ;;
*.data_sim) echo "${TEST_SIM:-0}" ;;
esac''')
self.stub('mu300-at','echo unexpected_at_query >> "$STUBLOG/commands"; exit 1')
self.extra=dict(MU300_LED_SYSFS_ROOT=self.leds,MU300_LED_RUN_DIR=self.run,MU300_LED_WIFI_FREQ='5200')
def values(self,bank):
return tuple(int((self.leds/f'v50:{bank}:{c}'/'brightness').read_text()) for c in ('red','white','blue'))
def call(self,shell,*args,**env):
r=self.script(shell,SCRIPT,*args,**dict(self.extra,**env))
self.assertEqual(r.returncode,0,r.stderr)
def test_registration_and_wifi_are_independent_without_at_queries(self):
for shell in self.each_shell():
self.call(shell,'sim-status','0','+CEREG: 1,"0012","abcd",7')
self.assertEqual(self.values('net1'),(0,0,120))
self.call(shell,'sim-status','1','+CEREG: 2,1,"0012","abcd",11','1')
self.assertEqual(self.values('net2'),(0,40,0))
self.call(shell,'wifi-on')
self.assertEqual(self.values('wifi'),(0,80,0))
self.call(shell,'wifi-on',MU300_LED_WIFI_FREQ='2412')
self.assertEqual(self.values('wifi'),(0,0,120))
self.call(shell,'sim-status','0','+CEREG: 2')
self.assertEqual(self.values('net1'),(120,0,0))
self.assertEqual(self.values('net2'),(0,40,0))
self.assertEqual(self.values('wifi'),(0,0,120))
self.assertFalse((self.tmp/'commands').exists())
def test_settings_refresh_and_data_sim_ownership(self):
for shell in self.each_shell():
self.call(shell,'online-4g',TEST_SIM='1')
self.assertEqual(self.values('net2'),(0,0,60))
self.call(shell,'online-5g',TEST_SIM='0')
self.call(shell,'refresh',TEST_SIGNAL='0',TEST_SIGNAL2='0')
self.assertEqual(self.values('net1'),(0,0,0))
self.assertEqual(self.values('net2'),(0,0,0))
self.call(shell,'refresh',TEST_BRIGHTNESS='64')
self.assertEqual(self.values('net1'),(0,20,0))
self.assertEqual(self.values('net2'),(0,0,60))
alarm=self.run/'mu300/thermal-alarm';alarm.parent.mkdir(exist_ok=True);alarm.touch()
self.call(shell,'refresh')
self.assertEqual(self.values('net1'),(120,0,0))
alarm.unlink();self.call(shell,'refresh')
self.assertEqual(self.values('net1'),(0,80,0))
def test_bad_and_short_responses_preserve_the_last_status(self):
for shell in self.each_shell():
self.call(shell,'sim-status','1','+CEREG: 5,"0012","abcd",11')
self.call(shell,'sim-status','1','+CEREG: 5')
self.assertEqual(self.values('net2'),(0,40,0))
self.call(shell,'sim-status','1','+CME ERROR: 3')
self.assertEqual(self.values('net2'),(0,40,0))
def test_boot_presence_event_clears_empty_lamp_and_emergency_is_offline(self):
for shell in self.each_shell():
self.call(shell,'boot')
self.call(shell,'sim-presence','0','absent')
self.assertEqual(self.values('net1'),(0,0,0))
self.call(shell,'sim-status','0','+CEREG: 0')
self.assertEqual(self.values('net1'),(0,0,0))
self.call(shell,'sim-presence','1','present')
self.call(shell,'sim-status','1','+CEREG: 2,8,"0012","abcd",11','1')
self.assertEqual(self.values('net2'),(60,0,0))
self.call(shell,'sim-status','1','+CEREG: 1,"0012","abcd",11')
self.call(shell,'sim-presence','1','present')
self.assertEqual(self.values('net2'),(0,40,0))
self.assertFalse((self.tmp/'commands').exists())
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Augment a Magisk ZIP without rebuilding/changing its original runtime files."""
import argparse
import copy
import importlib.util
import json
from pathlib import Path, PurePosixPath
import tempfile
import zipfile
TOP=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location('desktop_package',TOP/'desktop/package.py')
pkg=importlib.util.module_from_spec(spec);spec.loader.exec_module(pkg)
def augment(source,out,tools,kernel,exe=None):
if source.resolve()==out.resolve():raise ValueError('input and output must differ')
if out.exists():raise ValueError('output exists; do not overwrite a release')
with tempfile.TemporaryDirectory(prefix='mu300-desktop-') as temp:
stage=Path(temp)
with zipfile.ZipFile(source) as old:
if len(set(old.namelist()))!=len(old.namelist()):raise ValueError('duplicate ZIP entries')
original={}
for info in old.infolist():
name=PurePosixPath(info.filename)
if name.is_absolute() or '..' in name.parts or '\\' in info.filename or ':' in info.filename:
raise ValueError('unsafe ZIP entry: '+info.filename)
if info.is_dir():continue
data=old.read(info);p=stage/info.filename;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(data)
original[info.filename]=info
manifest=pkg.assemble(stage,tools,kernel,exe)
manifest['origin']={'archive':source.name,'sha256':pkg.sha(source),'runtime':'unchanged original archive'}
(stage/'desktop/manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
out.parent.mkdir(parents=True,exist_ok=True)
partial=out.with_suffix('.partial')
with zipfile.ZipFile(partial,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=6) as z:
for p in sorted(stage.rglob('*')):
if p.is_file():
n=p.relative_to(stage).as_posix()
original_name=next((old for old,new in manifest['magisk_layout'].items() if new==n),None)
if original_name in original:
info=copy.copy(original[original_name]);info.filename=n;info.orig_filename=n
z.writestr(info,p.read_bytes())
else:z.write(p,n)
with zipfile.ZipFile(partial) as z:
if z.testzip():raise ValueError('ZIP CRC verification failed')
import hashlib
for n,want in manifest['magisk'].items():
if hashlib.sha256(z.read(n)).hexdigest()!=want:raise ValueError('original Magisk member changed: '+n)
partial.replace(out)
print(out)
print('Original Magisk members verified:',len(manifest['magisk']))
return out
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('source',type=Path);p.add_argument('out',type=Path)
p.add_argument('--tools',type=Path,required=True);p.add_argument('--kernel',choices=('6.18','7.2'),required=True);p.add_argument('--exe',type=Path)
a=p.parse_args();augment(a.source,a.out,a.tools,a.kernel,a.exe)
+3 -1
View File
@@ -52,8 +52,10 @@ bc_setup() {
command -v getprop >/dev/null 2>&1 || { bc_refuse "this is not Android: the boot chain is only ever copied from Android"; return 1; }
_m="$(getprop ro.product.model) / $(getprop ro.product.device)"
case $_m in
'V50 / MU3351')
[ "$(getprop ro.board.platform)" = ums9620 ] || { bc_refuse 'V50 is not the UMS9620 platform'; return 1; } ;;
*U30Air*|*U30_Air*|*"U30 Air"*|*MU300*|*F50*|*mu300*) ;;
*) bc_refuse "this is not a ZTE F50/MU300 or U30 Air ($_m)"; return 1 ;;
*) bc_refuse "this is not a ZTE F50/MU300, V50/MU3351 or U30 Air ($_m)"; return 1 ;;
esac
case $(getprop ro.boot.slot_suffix) in
_a) BC_A=a; BC_L=b ;;
+18
View File
@@ -0,0 +1,18 @@
# Source from the host installer. Return 2 for inconsistent V50 identity,
# so an unsafe platform cannot fall through to the legacy F50 confirmation.
mu300_android_profile() {
local model device platform
model=$(printf '%s' "$1" | LC_ALL=C tr 'a-z' 'A-Z' | tr -d '\r')
device=$(printf '%s' "$2" | LC_ALL=C tr 'a-z' 'A-Z' | tr -d '\r')
platform=$(printf '%s' "$3" | tr -d '\r')
case "$model/$device" in
V50/*|*/V50|MU3351/*|*/MU3351)
case "$model/$device/$platform" in
V50/MU3351/ums9620|MU3351/V50/ums9620) echo v50 ;;
*) return 2 ;;
esac ;;
*U30AIR*|*U30_AIR*|*"U30 AIR"*) echo u30air ;;
*MU300*|*F50*) echo f50 ;;
*) return 1 ;;
esac
}
+31 -1
View File
@@ -25,6 +25,16 @@ VERSION=${MU300_VERSION:-}
[ -n "$VERSION" ] || VERSION=clean-tf-$KERNEL
mkdir -p "$TOP/work"
# Hybrid layout relocates original deployment files behind a thin Magisk entry;
# desktop code is not added to the Magisk boot image.
DESKTOP=${MU300_DESKTOP_INSTALLER:-1}
DESKTOP_TOOLS=${MU300_DESKTOP_TOOLS:-$TOP/work/desktop-tools}
if [ "$DESKTOP" = 1 ]; then
[ -s "$DESKTOP_TOOLS/lib/ld-musl-aarch64.so.1" ] || {
echo "desktop maintenance tools missing: $DESKTOP_TOOLS (set MU300_DESKTOP_TOOLS or MU300_DESKTOP_INSTALLER=0)" >&2; exit 1;
}
fi
for f in dumps/boot_a.img dumps/misc-head.bin busybox tools/logdw/logdw; do
[ -s "$IN/$f" ] || { echo "missing $IN/$f" >&2; exit 1; }
done
@@ -39,11 +49,24 @@ for f in wcn_bsp.ko sprd_wlan_combo.ko sprdbt_tty.ko mali_kbase.ko; do
done
[ -s "$UO/Image" ] || { echo "missing Linux $KERNEL Image in $UO" >&2; exit 1; }
python3 "$TOP/upstream/check-container-support.py" "$UO"
grep -qx 'CONFIG_LEDS_AW9523B=y' "$UO/kernel.config" || {
echo 'Shared F50/V50 firmware requires built-in AW9523B support; rebuild the kernel before packaging' >&2
exit 1
}
rel=$(strings "$UO/Image" | sed -n 's/^Linux version \([^ ]*\) .*/\1/p' | head -n1)
case $rel in "$KERNEL".*) ;; *) echo "$UO is kernel '$rel', expected $KERNEL.x" >&2; exit 1 ;; esac
for m in $(cat "$TOP/upstream/module-order.txt"); do
[ -s "$UO/modules/$m" ] || { echo "missing $KERNEL module $m" >&2; exit 1; }
done
if grep -qx 'CONFIG_ARM_SPRD_CPUFREQ_V2=m' "$UO/kernel.config"; then
cpu_ko=$UO/modules/sprd-cpufreq-v2-driver.ko
[ -s "$cpu_ko" ] || { echo 'CPU voltage module missing; run build-modules.sh' >&2; exit 1; }
for feature in voltage_offset_uv scaling_voltage_table scaling_voltage_offset scaling_voltage_domain; do
strings "$cpu_ko" | grep -F "$feature" >/dev/null || {
echo "CPU module lacks $feature; rebuild modules before packaging" >&2; exit 1;
}
done
fi
for m in "$UO"/modules/*.ko; do
v=$(strings "$m" | sed -n 's/^vermagic=\([^ ]*\) .*/\1/p' | head -n1)
[ "$v" = "$rel" ] || { echo "$m is built for '$v', Image is '$rel'" >&2; exit 1; }
@@ -69,7 +92,7 @@ for f in ./lib/netifd/proto/mu300cell.sh ./lib/netifd/proto/mu300cell-v6.sh \
./opt/mu300/bin/mu300-keys ./opt/mu300/bin/mu300-bt-init ./opt/mu300/bin/mu300-atd ./opt/mu300/bin/mu300-at ./opt/mu300/bin/mobile-data \
./opt/mu300/bin/mu300-user-packages ./etc/init.d/mu300-user-packages ./etc/mu300/image-packages \
./opt/mu300/lib/wifi-channels.sh ./usr/share/ucode/wifi/hostapd.uc \
./opt/mu300/bin/mu300-usb ./opt/mu300/bin/mu300-sim-env ./opt/mu300/bin/mu300-data-sim ./opt/mu300/bin/mu300-dual-radio ./etc/init.d/mu300-post ./etc/init.d/mu300-atd \
./opt/mu300/bin/mu300-usb ./opt/mu300/bin/v50-led-status ./opt/mu300/bin/mu300-platform-config ./opt/mu300/bin/openwrt-board-check ./opt/mu300/bin/mu300-sim-env ./opt/mu300/bin/mu300-data-sim ./opt/mu300/bin/mu300-dual-radio ./etc/init.d/mu300-post ./etc/init.d/mu300-atd \
./etc/init.d/mu300-smsd ./opt/mu300/bin/mu300-smsd ./opt/mu300/bin/mu300-sms ./etc/sysctl.d/99-mu300-console.conf \
./usr/share/luci/menu.d/luci-app-mu300.json \
./www/luci-static/resources/view/mu300/home.js \
@@ -144,6 +167,13 @@ cp "$BOOT" "$STAGE/boot-linux.img"
(cd "$STAGE" && sha256sum boot-linux.img | cut -d' ' -f1 > boot-linux.sha256)
python3 "$TOP/tools/tf-payload-manifest.py" "$STAGE"
chmod 755 "$STAGE"/*.sh "$STAGE/busybox"
if [ "$DESKTOP" = 1 ]; then
if [ -n "${MU300_DESKTOP_EXE:-}" ]; then
python3 "$TOP/desktop/package.py" --stage "$STAGE" --tools "$DESKTOP_TOOLS" --kernel "$KERNEL" --exe "$MU300_DESKTOP_EXE"
else
python3 "$TOP/desktop/package.py" --stage "$STAGE" --tools "$DESKTOP_TOOLS" --kernel "$KERNEL"
fi
fi
rm -f "$OUT"
python3 - "$STAGE" "$OUT" <<'PY'
import os, sys, zipfile
+3 -3
View File
@@ -55,7 +55,7 @@ select_device() { # select_device [quiet]: quiet never asks, it only picks what
[ -n "${ANDROID_SERIAL:-}" ] && return 0
_sd_all=$(adb devices -l 2>/dev/null | awk 'NR > 1 && $2 == "device"')
[ -n "$_sd_all" ] || return 0
_sd_f50=$(printf '%s\n' "$_sd_all" | grep -E 'model:F50|product:MU300|device:MU300|device:U30Air' | awk '{print $1}')
_sd_f50=$(printf '%s\n' "$_sd_all" | grep -E '(model:F50|product:MU300|device:MU300|device:U30Air|model:V50|product:MU3351|device:MU3351)([[:space:]]|$)' | awk '{print $1}')
_sd_one=
[ -n "$_sd_f50" ] && [ "$(printf '%s\n' "$_sd_f50" | wc -l | tr -d ' ')" = 1 ] && _sd_one=$_sd_f50
# the only adb device, and an F50/U30 Air: nothing to ask
@@ -69,7 +69,7 @@ select_device() { # select_device [quiet]: quiet never asks, it only picks what
fi
# Otherwise always ask: a phone or tablet next to the device is what the installer must never write to, and
# picking one by itself is how it got close (the F50 was in Linux, a tablet was the only one in Android)
echo " $(t 'which adb device is the F50 or U30 Air?')"
echo " $(t 'which adb device is the F50, V50 or U30 Air?')"
printf '%s\n' "$_sd_all" | awk '{ m = ""; for (i = 3; i <= NF; i++) if ($i ~ /^model:/) m = substr($i, 7); printf " %d) %s %s\n", NR, $1, m }'
_sd_def=1
[ -n "$_sd_one" ] && _sd_def=$(printf '%s\n' "$_sd_all" | awk -v s="$_sd_one" '$1 == s {print NR}')
@@ -81,7 +81,7 @@ select_device() { # select_device [quiet]: quiet never asks, it only picks what
# call before anything else that needs adb
# is one of the adb devices an F50/U30 Air?
target_attached() { adb devices -l 2>/dev/null | awk 'NR > 1 && $2 == "device"' | grep -q -E 'model:F50|product:MU300|device:MU300|device:U30Air'; }
target_attached() { adb devices -l 2>/dev/null | awk 'NR > 1 && $2 == "device"' | grep -q -E '(model:F50|product:MU300|device:MU300|device:U30Air|model:V50|product:MU3351|device:MU3351)([[:space:]]|$)'; }
require_android() {
# The device in Linux, and only a phone or tablet in Android: that is not the one to install to - offer to
+1 -1
View File
@@ -82,7 +82,7 @@ MU300_INPUTS="$IN" MU300_LUCI_PLUGIN_SRC="$TOP/openwrt/luci-app-mu300" MU300_VER
mv "$TOP/openwrt/mu300-openwrt-release.tar.gz" "$D/mu300-openwrt-rootfs.tar.gz"
for f in ./opt/mu300/bin/mu300-at ./opt/mu300/bin/mobile-data \
./opt/mu300/bin/mu300-user-packages ./etc/init.d/mu300-user-packages ./etc/mu300/image-packages \
./opt/mu300/lib/wifi-channels.sh ./usr/share/ucode/wifi/hostapd.uc ./opt/mu300/bin/mu300-sim-env ./opt/mu300/bin/mu300-data-sim ./opt/mu300/bin/mu300-dual-radio ./usr/share/luci/menu.d/luci-app-mu300.json ./www/luci-static/resources/view/mu300/home.js \
./opt/mu300/lib/wifi-channels.sh ./usr/share/ucode/wifi/hostapd.uc ./opt/mu300/bin/v50-led-status ./opt/mu300/bin/mu300-platform-config ./opt/mu300/bin/mu300-sim-env ./opt/mu300/bin/mu300-data-sim ./opt/mu300/bin/mu300-dual-radio ./usr/share/luci/menu.d/luci-app-mu300.json ./www/luci-static/resources/view/mu300/home.js \
./opt/mu300/bin/mu300-smsd ./opt/mu300/bin/mu300-sms ./etc/init.d/mu300-smsd \
./www/luci-static/resources/mu300/refresh.js ./www/luci-static/resources/view/mu300/sms.css \
./usr/libexec/unisoc-modem/dashboard-rates ./usr/libexec/unisoc-modem/operator.uc \
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""Verify a hybrid ZIP and exercise its desktop boot builder without hardware."""
import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
import subprocess
import sys
import tempfile
import zipfile
def verify(path):
with tempfile.TemporaryDirectory(prefix='mu300 desktop ') as temp:
stage=Path(temp)
with zipfile.ZipFile(path) as archive:
for name in archive.namelist():
p=PurePosixPath(name)
if p.is_absolute() or '..' in p.parts or '\\' in name or ':' in name:raise ValueError('unsafe archive path')
if archive.testzip():raise ValueError('ZIP CRC failure')
manifest=json.loads(archive.read('desktop/manifest.json'))
for group in ('magisk','desktop'):
for name,want in manifest[group].items():
if hashlib.sha256(archive.read(name)).hexdigest()!=want:raise ValueError('checksum failure: '+name)
archive.extractall(stage)
print('ZIP checksums passed:',path,flush=True)
shared=manifest.get('magisk_layout',{}).get('mu300-openwrt.tar.gz','mu300-openwrt.tar.gz')
if shared not in manifest['magisk'] or 'desktop/files/rootfs.tar.gz' in manifest['desktop']:
raise ValueError('expected one shared rootfs archive')
if manifest.get('format')==2:
allowed={'OpenWrt-Installer.exe','OpenWrt-Installer.py','module.prop','customize.sh'}
if {p.name for p in stage.iterdir() if p.is_file()}-allowed:
raise ValueError('unexpected top-level file')
subprocess.run([sys.executable,str(stage/'OpenWrt-Installer.py'),'--check-boot'],check=True)
subprocess.run([sys.executable,str(stage/'OpenWrt-Installer.py'),'--check-rootfs'],check=True)
if sys.platform=='win32' and (stage/'OpenWrt-Installer.exe').exists():
subprocess.run([str(stage/'OpenWrt-Installer.exe'),'--check-boot'],check=True)
subprocess.run([str(stage/'OpenWrt-Installer.exe'),'--check-rootfs'],check=True)
# Exercise a real CMD launcher from a path containing spaces.
launcher=stage/('launchers/start-installer.cmd' if manifest.get('format')==2 else 'start-installer.cmd')
subprocess.run(['cmd.exe','/c',str(launcher),'--check'],cwd=stage,input='\n',text=True,check=True)
return {'archive':path.name,'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),
'original_members':len(manifest['magisk']),'kernel':manifest['kernel'],'device_writes':False}
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);p.add_argument('packages',type=Path,nargs='+');p.add_argument('--report',type=Path)
a=p.parse_args();report=[verify(path) for path in a.packages]
if a.report:a.report.write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2))
+8 -2
View File
@@ -6,7 +6,7 @@
# ./ramdisk-generic.lz4 boot/init, busybox, logdw and the modules of upstream/module-order.txt
# ./modules/*.ko every module, for /lib/modules/<release> on the root filesystem
# ./kernel.release the kernel's release string (uname -r)
# ./devices the devices it runs on (f50 u30air)
# ./devices boards supported by this actual kernel build
# ./modules.builtin* what the kernel has built in, for depmod/modprobe
# busybox and logdw are the static helpers of the 5.4 bundle (default: the newest one under release/).
set -eu
@@ -55,6 +55,12 @@ for f in modules.builtin modules.builtin.modinfo; do [ ! -f "$UO/$f" ] || cp "$U
echo "$krel" > "$W/b/kernel.release"
# the devices this kernel runs on; mu300-update and the installers check it (FINDINGS 33c: mainline kernels from
# before this file do not bring up the U30 Air's USB)
echo "f50 u30air" > "$W/b/devices"
devices='f50 u30air'
# Do not mark an older kernel as V50-compatible just because the packaging
# source is newer. V50's physical lamps require the built-in AW9523B driver.
if grep -qx 'CONFIG_LEDS_AW9523B=y' "$UO/kernel.config"; then
devices="$devices v50"
fi
echo "$devices" > "$W/b/devices"
tar -C "$W/b" -czf "$OUT" .
echo "$OUT: kernel $krel, $(ls "$W/b/modules" | wc -l | tr -d ' ') modules, ramdisk segment $(wc -c < "$W/b/ramdisk-generic.lz4" | tr -d ' ') bytes"
+1
View File
@@ -329,6 +329,7 @@ CONFIG_LEDS_GPIO=y
CONFIG_LEDS_ZTE_LDO=y
# ... and its red network LED, on the PMIC's keypad backlight sink (leds-sc27xx-kpled.c)
CONFIG_LEDS_SC27XX_KPLED=y
CONFIG_LEDS_AW9523B=y
CONFIG_LEDS_TRIGGERS=y
CONFIG_LEDS_TRIGGER_TIMER=y
CONFIG_LEDS_TRIGGER_HEARTBEAT=y
+282
View File
@@ -0,0 +1,282 @@
// SPDX-License-Identifier: GPL-2.0-only
/* V50/MU3351's vendor AW9523B LED binding, not a GPIO expander binding.
* DT idx values are GPIO pin numbers (confirmed against Android's driver).
* No vendor boot-animation thread, interrupt handler or periodic worker.
*/
#include <linux/delay.h>
#include <linux/gpio/consumer.h>
#include <linux/i2c.h>
#include <linux/leds.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/of.h>
#define AW_ID 0x10
#define AW_GCR 0x11
#define AW_MODE0 0x12
#define AW_MODE1 0x13
#define AW_RESET 0x7f
#define AW_CHANNELS 16
struct aw9523b;
struct aw9523b_led {
struct led_classdev cdev;
struct aw9523b *chip;
u16 pins;
};
struct aw9523b {
struct i2c_client *client;
struct mutex lock;
u16 pins;
unsigned int count;
struct aw9523b_led leds[];
};
/* P0_0..7 => DIM4..11, P1_0..3 => DIM0..3, P1_4..7 => DIM12..15. */
static unsigned int aw9523b_dim(unsigned int pin)
{
return pin < 8 ? 0x24 + pin : pin < 12 ? 0x18 + pin : 0x20 + pin;
}
/* Android groupcolor_store: three physical indicators, each with two
* white emitters. Wi-Fi has only one blue and one red emitter.
*/
static const struct {
const char *name;
u16 pins;
unsigned int maximum;
} v50_lamps[] = {
{ "v50:net1:white", BIT(8) | BIT(11), 80 },
{ "v50:net1:blue", BIT(9) | BIT(12), 120 },
{ "v50:net1:red", BIT(10) | BIT(13), 120 },
{ "v50:net2:white", BIT(14) | BIT(1), 80 },
{ "v50:net2:blue", BIT(15) | BIT(2), 120 },
{ "v50:net2:red", BIT(0) | BIT(3), 120 },
{ "v50:wifi:white", BIT(4) | BIT(5), 80 },
{ "v50:wifi:blue", BIT(6), 120 },
{ "v50:wifi:red", BIT(7), 120 },
};
static int aw9523b_brightness(struct led_classdev *cdev,
enum led_brightness brightness)
{
struct aw9523b_led *led = container_of(cdev, struct aw9523b_led, cdev);
struct aw9523b *chip = led->chip;
unsigned int pin;
int ret = 0;
mutex_lock(&chip->lock);
for (pin = 0; pin < AW_CHANNELS; pin++) {
if (!(led->pins & BIT(pin)))
continue;
ret = i2c_smbus_write_byte_data(chip->client, aw9523b_dim(pin), brightness);
if (ret)
break;
}
mutex_unlock(&chip->lock);
return ret;
}
static void aw9523b_off(void *data)
{
struct aw9523b *chip = data;
unsigned int pin;
mutex_lock(&chip->lock);
for (pin = 0; pin < AW_CHANNELS; pin++)
if (chip->pins & BIT(pin))
i2c_smbus_write_byte_data(chip->client, aw9523b_dim(pin), 0);
mutex_unlock(&chip->lock);
}
static int aw9523b_probe(struct i2c_client *client)
{
struct device *dev = &client->dev;
struct device_node *bank;
struct gpio_desc *reset;
struct aw9523b *chip;
u32 enabled, gpio_enabled, imax, pins[AW_CHANNELS];
unsigned int count, index = 0, pin;
int ret;
if (of_property_read_u32(dev->of_node, "aw9523b,led_enable", &enabled) || enabled != 1 ||
of_property_read_u32(dev->of_node, "aw9523b,gpio_enable", &gpio_enabled) || gpio_enabled)
return -ENODEV;
bank = of_get_child_by_name(dev->of_node, "aw9523b,led");
if (!bank)
return -EINVAL;
count = of_get_available_child_count(bank);
if (!count || count > AW_CHANNELS ||
of_property_read_u32(bank, "aw9523b,default_imax", &imax) || imax > 255) {
ret = -EINVAL;
goto out_node;
}
/* Keep the vendor groups and expose each wired channel independently.
* V50 has several front-panel lamps, not one shared RGB indicator.
*/
chip = devm_kzalloc(dev, struct_size(chip, leds, count + AW_CHANNELS + ARRAY_SIZE(v50_lamps)), GFP_KERNEL);
if (!chip) {
ret = -ENOMEM;
goto out_node;
}
mutex_init(&chip->lock);
chip->client = client;
chip->count = count;
for_each_available_child_of_node_scoped(bank, node) {
struct aw9523b_led *led = &chip->leds[index++];
u32 n, maximum, initial;
const char *name;
if (of_property_read_string(node, "aw9523b,name", &name) ||
of_property_read_u32(node, "aw9523b,idx_count", &n) || !n || n > AW_CHANNELS ||
of_property_count_u32_elems(node, "aw9523b,idx") != n ||
of_property_read_u32_array(node, "aw9523b,idx", pins, n) ||
of_property_read_u32(node, "aw9523b,max_brightness", &maximum) || !maximum || maximum > 255 ||
of_property_read_u32(node, "aw9523b,default_brightness", &initial) || initial > maximum) {
ret = -EINVAL;
goto out_node;
}
for (pin = 0; pin < n; pin++) {
if (pins[pin] >= AW_CHANNELS || (led->pins & BIT(pins[pin]))) {
ret = -EINVAL;
goto out_node;
}
led->pins |= BIT(pins[pin]);
}
chip->pins |= led->pins;
led->chip = chip;
led->cdev.name = name;
led->cdev.max_brightness = maximum;
led->cdev.brightness = initial;
led->cdev.brightness_set_blocking = aw9523b_brightness;
}
/* Validate the entire binding before resetting or changing the controller. */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
ret = -EOPNOTSUPP;
goto out_node;
}
reset = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH);
if (IS_ERR(reset)) {
ret = PTR_ERR(reset);
goto out_node;
}
if (reset) {
gpiod_set_value_cansleep(reset, 0);
usleep_range(1000, 2000);
gpiod_set_value_cansleep(reset, 1);
usleep_range(2000, 3000);
}
ret = i2c_smbus_read_byte_data(client, AW_ID);
if (ret != 0x23) {
ret = ret < 0 ? ret : -ENODEV;
goto out_node;
}
ret = i2c_smbus_write_byte_data(client, AW_RESET, 0);
if (ret)
goto out_node;
usleep_range(1000, 2000);
ret = devm_add_action_or_reset(dev, aw9523b_off, chip);
if (ret)
goto out_node;
for (pin = 0; pin < AW_CHANNELS; pin++) {
ret = i2c_smbus_write_byte_data(client, aw9523b_dim(pin), 0);
if (ret)
goto out_node;
}
/* LED-only use: mask GPIO interrupts; leave unused pins in GPIO mode.
* IMAX has only two bits: Android also masks the vendor 0x11 value to 1.
*/
ret = i2c_smbus_write_byte_data(client, 0x06, 0xff);
if (!ret)
ret = i2c_smbus_write_byte_data(client, 0x07, 0xff);
if (!ret)
ret = i2c_smbus_write_byte_data(client, AW_GCR, 0x10 | (imax & 3));
if (!ret)
ret = i2c_smbus_write_byte_data(client, AW_MODE0, ~chip->pins & 0xff);
if (!ret)
ret = i2c_smbus_write_byte_data(client, AW_MODE1, (~chip->pins >> 8) & 0xff);
if (ret)
goto out_node;
for (index = 0; index < count; index++) {
struct aw9523b_led *led = &chip->leds[index];
ret = aw9523b_brightness(&led->cdev, led->cdev.brightness);
if (!ret)
ret = devm_led_classdev_register(dev, &led->cdev);
if (ret)
goto out_node;
}
for (pin = 0; pin < AW_CHANNELS; pin++) {
struct aw9523b_led *led;
unsigned int maximum = 255;
if (!(chip->pins & BIT(pin)))
continue;
for (index = 0; index < count; index++)
if (chip->leds[index].pins & BIT(pin))
maximum = min(maximum, chip->leds[index].cdev.max_brightness);
led = &chip->leds[chip->count++];
led->chip = chip;
led->pins = BIT(pin);
led->cdev.name = devm_kasprintf(dev, GFP_KERNEL, "aw9523b:pin%u", pin);
if (!led->cdev.name) {
ret = -ENOMEM;
goto out_node;
}
led->cdev.max_brightness = maximum;
ret = i2c_smbus_read_byte_data(client, aw9523b_dim(pin));
if (ret < 0)
goto out_node;
led->cdev.brightness = ret;
led->cdev.brightness_set_blocking = aw9523b_brightness;
ret = devm_led_classdev_register(dev, &led->cdev);
if (ret)
goto out_node;
}
/* The layout is verified only for the complete MU3351 vendor binding.
* Other AW9523B boards retain their DT groups and raw channels.
*/
if (count == 4 && chip->pins == 0xffff &&
chip->leds[1].pins == (BIT(8) | BIT(11) | BIT(14) | BIT(1) | BIT(4) | BIT(5)) &&
chip->leds[2].pins == (BIT(9) | BIT(12) | BIT(15) | BIT(2) | BIT(6)) &&
chip->leds[3].pins == (BIT(10) | BIT(13) | BIT(0) | BIT(3) | BIT(7))) {
for (index = 0; index < ARRAY_SIZE(v50_lamps); index++) {
struct aw9523b_led *led = &chip->leds[chip->count++];
led->chip = chip;
led->pins = v50_lamps[index].pins;
led->cdev.name = v50_lamps[index].name;
led->cdev.max_brightness = v50_lamps[index].maximum;
led->cdev.brightness_set_blocking = aw9523b_brightness;
ret = devm_led_classdev_register(dev, &led->cdev);
if (ret)
goto out_node;
}
}
i2c_set_clientdata(client, chip);
dev_info(dev, "%u LED groups, pin mask %#x\n", count, chip->pins);
out_node:
of_node_put(bank);
return ret;
}
static void aw9523b_shutdown(struct i2c_client *client)
{
aw9523b_off(i2c_get_clientdata(client));
}
static const struct of_device_id aw9523b_match[] = {
{ .compatible = "awinic,aw9523b" },
{ }
};
MODULE_DEVICE_TABLE(of, aw9523b_match);
static struct i2c_driver aw9523b_driver = {
.driver = { .name = "aw9523b-led", .of_match_table = aw9523b_match },
.probe = aw9523b_probe,
.shutdown = aw9523b_shutdown,
};
module_i2c_driver(aw9523b_driver);
MODULE_DESCRIPTION("AW9523B vendor LED groups for ZTE V50/MU3351");
MODULE_LICENSE("GPL");
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""Shared MMC durability policy; preserve runtime PM and idle clock gating."""
from pathlib import Path
import re
def apply(kernel):
kernel = Path(kernel)
header = kernel / 'include/linux/mmc/host.h'
text = header.read_text()
if '#define MMC_CAP2_NO_REL_WR' not in text:
if re.search(r'^#define MMC_CAP2_.*(?:<<\s*29|BIT\(29\))', text, re.M):
raise ValueError('MMC capability bit 29 is no longer free')
pos = text.index('\n', text.index('#define MMC_CAP2_ALT_GPT_TEGRA'))
text = text[:pos] + '\n#define MMC_CAP2_NO_REL_WR\t(1 << 29)\t/* Emulate FUA with cache flushes */' + text[pos:]
header.write_text(text)
block = kernel / 'drivers/mmc/core/block.c'
text = block.read_text()
if '!(card->host->caps2 & MMC_CAP2_NO_REL_WR)' not in text:
anchor = '\tif (md->flags & MMC_BLK_CMD23 &&\n'
if text.count(anchor) != 1:
raise ValueError('MMC reliable-write anchor changed')
text = text.replace(anchor, anchor + '\t !(card->host->caps2 & MMC_CAP2_NO_REL_WR) &&\n', 1)
block.write_text(text)
path = kernel / 'drivers/mmc/host/sdhci-sprd.c'
text = path.read_text()
# Clean old shared and V50-only policies from cached build trees as well.
for start in (
'\t/* Shared eMMC policy: keep the non-removable memory controller awake.',
'\tif (!mmc_card_is_removable(host->mmc)) {\n\t\tstruct device_node *aw =',
):
if start in text:
a = text.index(start)
b = text.index('\tsdhci_sprd_phy_param_parse(', a)
text = text[:a] + text[b:]
text = re.sub(
r'\tif \(sprd_host->runtime_keep_awake\) \{\n'
r'\t\tpm_runtime_forbid\(&pdev->dev\);\n.*?\n\t\}\n',
'', text, flags=re.S,
)
text = text.replace('\tif (sprd_host->runtime_keep_awake)\n\t\tpm_runtime_allow(&pdev->dev);\n', '')
text = text.replace('''\t/* Keep eMMC clocks and PHY state across runtime and system idle. */
\tif (sprd_host->runtime_keep_awake)
\t\treturn 0;
''', '')
text = text.replace('''\t/* Shared eMMC policy: no autonomous inner/outer clock gating. */
\tif (clk > 400000 && !sprd_host->runtime_keep_awake) {''', '''\t/* Enable CLK_AUTO when the clock is greater than 400K. */
\tif (clk > 400000) {''')
text = text.replace('\tbool runtime_keep_awake;\n', '')
if 'runtime_keep_awake' in text:
raise ValueError('Unrecognized cached eMMC keep-awake policy')
marker = 'Shared eMMC policy: preserve FUA durability'
if marker not in text:
anchor = '\tsprd_host = TO_SPRD_HOST(host);\n\tsdhci_sprd_phy_param_parse(sprd_host, pdev->dev.of_node);'
if text.count(anchor) != 1:
raise ValueError('eMMC host policy anchor changed')
text = text.replace(anchor, '''\tsprd_host = TO_SPRD_HOST(host);
\t/* Shared eMMC policy: preserve FUA durability through flush emulation.
\t * Runtime PM, aggressive PM and CLK_AUTO retain their normal behavior. */
\tif (!mmc_card_is_removable(host->mmc) &&
\t !(host->mmc->caps2 & MMC_CAP2_NO_MMC) &&
\t of_property_match_string(pdev->dev.of_node, "sprd,name", "sdio_wlan") < 0 &&
\t of_property_match_string(pdev->dev.of_node, "sprd,name", "sdio_sd") < 0)
\t\thost->mmc->caps2 |= MMC_CAP2_NO_REL_WR;
\tsdhci_sprd_phy_param_parse(sprd_host, pdev->dev.of_node);''', 1)
path.write_text(text)
path = kernel / 'drivers/mmc/core/mmc.c'
text = path.read_text()
# _mmc_suspend serves both runtime and system callbacks. The old guard
# would still block aggressive runtime sleep even without pm_forbid.
text = text.replace('''
\t/* Shared eMMC policy: system suspend preserves powered card and state.
\t * The cache flush above remains mandatory; do not mark it suspended. */
\tif (pm_type == MMC_POWEROFF_SUSPEND && !mmc_card_is_removable(host))
\t\tgoto out;
''', '')
marker = 'Shared eMMC policy: system-only power retention'
if marker not in text:
start = text.index('static int mmc_suspend(struct mmc_host *host)')
end = text.index('\n}', start)
body = text[start:end]
anchor = '\terr = _mmc_suspend(host, MMC_POWEROFF_SUSPEND);'
if body.count(anchor) != 1:
raise ValueError('MMC system suspend anchor changed')
body = body.replace(anchor, '''\t/* Shared eMMC policy: system-only power retention. Runtime suspend
\t * still uses _mmc_suspend unchanged; an already suspended card stays
\t * suspended and will be restored by its normal runtime resume. */
\tif (!mmc_card_is_removable(host)) {
\t\tmmc_claim_host(host);
\t\terr = mmc_card_suspended(host->card) ? 0 : _mmc_flush_cache(host);
\t\tmmc_release_host(host);
\t} else {
\t\terr = _mmc_suspend(host, MMC_POWEROFF_SUSPEND);
\t}''', 1)
text = text[:start] + body + text[end:]
path.write_text(text)
if __name__ == '__main__':
import sys
apply(sys.argv[1])
+5
View File
@@ -137,6 +137,9 @@ if 'MU300: CD GPIO deferred' not in t:
# which gives data CRC errors on HS400ES writes while reads work)
t = t.replace('#define SDHCI_SPRD_DLL_PHASE_INTERNAL\t0x3', '#define SDHCI_SPRD_DLL_PHASE_INTERNAL\t0x2 /* MU300 r11p3 */')
open(sp, 'w').write(t)
# Shared durability policy; migrate cached keep-awake trees back to runtime PM.
from emmc import apply as apply_emmc_policy
apply_emmc_policy(tree)
# thermal: UMS9620 on-die sensors (vendor sprd_thermal_r5p0), calibration from eFuse
append_once('drivers/thermal/Makefile', 'sprd_thermal_r5p0.o', 'obj-$(CONFIG_SPRD_THERMAL_R5P0) += sprd_thermal_r5p0.o\n')
append_once('drivers/thermal/Kconfig', 'SPRD_THERMAL_R5P0', '''
@@ -222,6 +225,8 @@ print('port installed')
# LEDs of the ZTE U30 Air: its white ones on PMIC LDOs (leds-zte-ldo.c), and its red on the PMIC's keypad backlight
# sink (leds-sc27xx-kpled.c)
LED_DRIVERS = (
('LEDS_AW9523B', 'leds-aw9523b', 'AW9523B LED groups (ZTE V50)',
'LEDS_CLASS && I2C && OF', 'The V50/MU3351 RGB controller with its original Android DT binding.'),
('LEDS_ZTE_LDO', 'leds-zte-ldo', 'LEDs on PMIC LDOs (ZTE U30 Air)', 'LEDS_CLASS && REGULATOR && OF',
"The ZTE U30 Air's white LEDs, powered by three PMIC LDOs."),
('LEDS_SC27XX_KPLED', 'leds-sc27xx-kpled', 'Spreadtrum/Unisoc PMIC keypad backlight',