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

{view === 'advanced' ? t.advanced : t.install}

{(view === 'advanced' ? ['reinstall','image','uninstall'] : ['tf','part','reinstall']).map(m => )}
{method === 'uninstall' &&

{t.uninstallHelp}

} {method === 'image' &&
{t.experimental}
} + {method === 'part' && } {['part','image'].includes(method) && } {['part','reinstall'].includes(method) && }
} @@ -351,7 +358,9 @@ function App() { } {view === 'plan' && tx && <>
{tx.choices.method === 'uninstall' ? t.reviewUninstall : t.review}

{tx.device.model}

{tx.package.name} · ••••{tx.device.serial.slice(-4)}

{tx.choices.method === 'uninstall' && impactNotice}
{tx.choices.method === 'uninstall' && tx.plan.layout_source === 'device' &&

{t.uninstallDeviceBounds}

}
{tx.choices.method === 'uninstall' ? t.operationMethod : t.installMethod}
{tx.choices.method === 'boot' ? t.boot : tx.choices.method === 'update' ? t.update : (t as unknown as Record)[tx.choices.method]}
{tx.choices.method === 'uninstall' ? t.uninstallTarget : t.target}
{tx.plan.target}
{tx.choices.method === 'uninstall' ? t.androidAllocation : t.android}
{tx.choices.method === 'uninstall' && <>{gib(tx.plan.previous_android_bytes)} → }{gib(tx.plan.android_bytes)}
{tx.choices.method === 'uninstall' ? t.release : t.allocation}
{tx.choices.method === 'boot' ? '—' : gib(tx.plan.openwrt_bytes)}
{tx.choices.method === 'uninstall' ? <>
{t.reclaim}
{gib(tx.plan.reclaimed_bytes)}
{!!tx.plan.released_unallocated_bytes &&
{t.unallocatedRelease}
{gib(tx.plan.released_unallocated_bytes)}
} :
{t.grow}
{tx.plan.grow ? : '—'}
}
{tx.choices.method !== 'uninstall' && impactNotice} - {(tx.plan.offline || tx.plan.two_stage) &&

{tx.choices.method === 'uninstall' ? t.uninstallFirstBoot : t.firstBoot}

} + {tx.plan.shrink_strategy === 'online-f2fs' &&
{t.onlineTitle}

{t.onlineDesc}

} + {tx.plan.online_unavailable &&

{t.onlineUnavailable} {tx.plan.online_unavailable}

} + {tx.plan.shrink_strategy !== 'online-f2fs' && (tx.plan.offline || tx.plan.two_stage) &&

{tx.choices.method === 'uninstall' ? t.uninstallFirstBoot : t.firstBoot}

}
} @@ -373,7 +382,8 @@ function App() { {tx.error &&

{tx.error.message}

} }} {waitingForOpenwrt &&
{tx.choices.method !== 'uninstall' &&

{['update','boot'].includes(tx.choices.method) ? t.existingLogin : t.defaultLogin}

}{tx.details?.verification_error &&

{tx.details.verification_error}

}
} - {tx.status !== 'completed' &&
{waitingForOpenwrt && }{active ? : }
+ {waitingOnline && } + {tx.status !== 'completed' && !waitingOnline &&
{waitingForOpenwrt && }{active ? : }
}
} @@ -384,6 +394,16 @@ function App() {
OpenWrt Installer · v1.0USB / SSH · {pkg?.profile || '—'}
{t.running}}>{helpOpen && } {guideOpen && } + {waitingOnline && !onlineDismissed && {if (!open) {setOnlineDismissed(true);setOnlineInput('');}}}> + +
{t.onlineFallbackTitle}{t.onlineFallbackDesc}
+

{tx?.online_fallback?.reason}

+
+
+
} {resetPrompt && {if (!open && !busy) setResetPrompt(undefined);}}>
{t.uninstallResetQuestion}{resetPrompt.model} · ••••{resetPrompt.serial_hint}
diff --git a/installer/ui/src/protocol.ts b/installer/ui/src/protocol.ts index b43610b1..463f4467 100644 --- a/installer/ui/src/protocol.ts +++ b/installer/ui/src/protocol.ts @@ -6,7 +6,8 @@ export interface Package {path: string; name: string; adapter: string; profile: export interface ResetPrompt {confirmation_required: 'format_android'; reason: string; reset_token: string; model: string; serial_hint: string} export interface Transaction { id: string; status: string; stage: string; device: Device; package: Package; - choices: {method: string; host?: string}; plan: {wipe: boolean; data_action?: string; preservation_error?: string; layout_source?: 'original_record' | 'device'; released_unallocated_bytes?: number; two_stage: boolean; offline?: boolean; openwrt_bytes: number; android_bytes?: number; previous_android_bytes?: number; reclaimed_bytes?: number; target: string; grow?: boolean; experimental?: boolean; gap_start?: number}; + choices: {method: string; host?: string}; plan: {wipe: boolean; data_action?: string; preservation_error?: string; layout_source?: 'original_record' | 'device'; released_unallocated_bytes?: number; shrink_strategy?: string; online_unavailable?: string; two_stage: boolean; offline?: boolean; openwrt_bytes: number; android_bytes?: number; previous_android_bytes?: number; reclaimed_bytes?: number; target: string; grow?: boolean; experimental?: boolean; gap_start?: number}; + online_fallback?: {state:'awaiting'|'confirmed'; nonce:string; reason:string}; uninstall_armed?: boolean; completed: string[]; unsafe: boolean; updated: number; revision?: number; stage_started_at?: number; stage_finished_at?: number; details?: {host?: string; tool?: string; reboot_manually?: boolean; boot_confirmed?: boolean; verification_error?: string; connection_state?: string}; error?: {message: string; retryable: boolean; code: string}; @@ -20,7 +21,7 @@ export const native = (command: string, args?: Record (bytes / 1073741824).toFixed(2) + ' GiB'; export function stateGroup(stage: string): number { if (['plan', 'package', 'device', 'environment'].includes(stage)) return 0; - if (['backup', 'prepare','uninstall_prepare','firmware_extract','firmware_convert'].includes(stage)) return 1; + if (['online_shrink', 'online_fallback', 'backup', 'prepare','uninstall_prepare','firmware_extract','firmware_convert'].includes(stage)) return 1; if (['uninstall_offline','android_boot', 'android_setup', 'usb_debugging', 'debug_authorization', 'magisk', 'root_permission', 'root_ready', 'recheck'].includes(stage)) return 2; if (['transfer_install', 'verify_capacity', 'verify_android', 'uninstall_restore_boot', 'openwrt_boot'].includes(stage)) return 3; return 4; diff --git a/installer/verification/online-shrink.json b/installer/verification/online-shrink.json new file mode 100644 index 00000000..f48bcbd3 --- /dev/null +++ b/installer/verification/online-shrink.json @@ -0,0 +1,25 @@ +{ + "date": "2026-10-29", + "scope": "source, native helper and browser; no additional device shrink", + "native_helper_sha256": "357f4907cc35b2b67f14410a3cfbbad04d62dc3f59c08f711f09f8514993496d", + "covered": [ + "eMMC 512 and UFS 4096 GPT", + "A/B free-space resume", + "kernel reject and explicit wipe fallback", + "ADB loss after fork", + "known mixed GPT recovery", + "cancel deferred until sealed GPT", + "commit in a later Android boot", + "zh/en fallback dialog and fresh confirmation" + ], + "hardware": "Changxing60 64GiB preserve-data shrink was previously validated. This implementation only ran read-only inspect; detached worker install/power-loss acceptance not performed.", + "release": "EXE/App and full firmware packages have not been rebuilt for this change.", + "unit_regression": { + "run": 368, + "skipped": 74, + "failed": 0 + }, + "focused_online_tests": 16, + "slot_resume_tests": "E5-specific", + "browser": "zh/en online strategy and explicit erase fallback passed; MU300 complete 12-suite browser regression passed; E5 existing 11 suites and new suite passed" +} diff --git a/installer/verification/ui-regression.json b/installer/verification/ui-regression.json index 7de39c75..8371195f 100644 --- a/installer/verification/ui-regression.json +++ b/installer/verification/ui-regression.json @@ -52,5 +52,23 @@ "exit": 0, "output": "Wireless ADB smoke passed: retry, Enter connect without package, explicit multi-device target, exact disconnect, USB protection, authorization/offline, bound Android resume and unsafe-stage exclusion, bilingual 800x650 layout; no real device access\r\n", "error": "" + }, + { + "test": "uninstall_smoke", + "exit": 0, + "output": "PASS: reset consent/cancel, original-record and device-evidence plans, preservation/release/reset impacts, bilingual UI, Android completion, bounded layout; simulated backend only\r\n", + "error": "" + }, + { + "test": "mtp_smoke", + "exit": 0, + "output": "MTP toast: Chinese/English success/warning, one notification, no confirmation dialog\r\n", + "error": "" + }, + { + "test": "online_shrink_smoke", + "exit": 0, + "output": "PASS: zh/en, small viewport, default online, explicit format, cancel, nonce/yes and new-plan confirmation\r\n", + "error": "" } ] diff --git a/openwrt/build-rootfs.sh b/openwrt/build-rootfs.sh index b567d231..d6d62e17 100755 --- a/openwrt/build-rootfs.sh +++ b/openwrt/build-rootfs.sh @@ -160,7 +160,7 @@ apk_retry() { done } apk_retry update >/dev/null -# openssl-util: mu300-vpn fetches the VPN server certificate with it to pin, for links that ask for allowInsecure; +# openssl-util: general TLS certificate inspection and maintenance tools; # i2c-tools, gpiod-tools: mu300-usb (the charger of the U30 Air) and mu300-nfc (its NFC tag) apk_retry add --allow-untrusted /in/wifi-sae/*.apk >/dev/null # The cipher capability helper needs the section omitted by reduced iw builds. diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js index b8421e04..b27855dc 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js @@ -857,6 +857,7 @@ var DASH_I18N = { '锁定': ['Lock', 'Kilitle'], '已运行': ['Uptime', 'Çalışma süresi'], '无线电已关': ['Radio off', 'Radyo kapalı'], + '未插卡': ['No SIM card', 'SIM kart takılı değil'], '未驻留小区': ['No serving cell', 'Bağlı olunan hücre yok'], '无应答': ['No response', 'Yanıt yok'], '信号': ['Signal', 'Sinyal'], diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js index 781ef521..bbfe95ec 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js @@ -446,10 +446,21 @@ return view.extend({ /* A newer successful read supersedes the slow tier's old failure. */ delete c.error; } + var viewedSlot = Number(c && c.card != null ? c.card : M.selectedSlot()); + var sim = i.modem && i.modem.sims && i.modem.sims[viewedSlot]; + var absent = !!(sim && sim.state === 'absent' && Number(sim.slot) === viewedSlot); + // SIM removal clears subscription/network data, while equipment identity + // and the real RF readback remain meaningful without a card. + if (absent) { + var equipment = c && c.ident; + c = { card: sim.slot, cfun: c && c.cfun, ident: equipment ? { + imei: equipment.imei, mfg: equipment.mfg, model: equipment.model, fw: equipment.fw + } : null }; + } this.lastCell = c; /* 慢档数据(邻区/运营商/身份)只在整份缓存的时间戳变化时重绘 */ var fullTs = [c && c.card, st.cell && st.cell.ts, st.cell && st.cell.partial || 0, - st.cell && st.cell.neigh_pending || 0, c && c.error || ''].join(':'); + st.cell && st.cell.neigh_pending || 0, c && c.error || '', absent ? 'absent' : ''].join(':'); var slowChanged = fullTs !== this.lastFullTs; this.lastFullTs = fullTs; @@ -465,8 +476,8 @@ return view.extend({ var label = M.qLabel(rsrp, rsrq, sinr), score = M.qScore({ rsrp: rsrp, rsrq: rsrq, sinr: sinr }); var col = M.qCol(label); - var rat = '--'; - if (c && !c.error) { + var rat = absent ? '未插卡' : '--'; + if (!absent && c && !c.error) { var nr = c.nr && c.nr.band ? true : false; var lte = c.lte && c.lte.band ? true : false; if (nr && lte) rat = '5G NSA'; @@ -530,7 +541,7 @@ return view.extend({ M.set('apn', w.apn || '--'); M.set('sess', w.uptime ? M.fmtUptime(w.uptime) : '--'); var regmap = { 0: '未注册', 1: '已注册', 2: '搜索中', 3: '注册被拒', 4: '未知', 5: '已注册(漫游)', 7: '仅紧急', 8: '仅紧急', 10: '已注册' }; - var reg = '--'; + var reg = absent ? '未插卡' : '--'; if (c && c.reg) { reg = regmap[c.reg.stat] || ('状态 ' + c.reg.stat); if (c.reg.tac) reg += ' · TAC ' + c.reg.tac; diff --git a/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash b/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash index 68c339af..23f1ab10 100644 --- a/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash +++ b/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash @@ -100,7 +100,7 @@ m_act() { case "$arg" in on) enabled=1;; off) enabled=0;; *) printf '{"ok":0,"error":"Invalid radio request"}\n'; return;; esac "$DASH/data-sim" start "radio-${MU300_SIM_SLOT:-0}-$enabled" ;; - modem-reset|reboot|poweroff|vpn) + modem-reset|reboot|poweroff) setsid "$DASH/action" "$op" "$arg" >/dev/null 2>&1 & printf '{"ok":1,"started":1,"op":"%s"}\n' "$op$arg" ;; diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/action b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/action index cd19ad5c..bf0b5a8a 100644 --- a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/action +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/action @@ -4,7 +4,6 @@ # mu300-dash-act data up|down netifd wan interface up/down (no AT in-band) # mu300-dash-act wifi on|off uci wireless disabled flag + wifi up/down # mu300-dash-act modem-reset the SFUN 5/3/2/4 sequence mobile-data uses for sim-reset -# mu300-dash-act vpn start|stop /etc/init.d/mu300-vpn # mu300-dash-act reboot|poweroff orderly restart/shutdown, after a 3 s grace for the HTTP reply # # Every op prints one JSON line on stdout. The rpcd backend (/usr/libexec/rpcd/mu300dash) @@ -53,14 +52,6 @@ case "${1:-}:${2:-}" in fi ok "modem-reset" ;; - vpn:start|vpn:stop) - if [ -x /etc/init.d/mu300-vpn ]; then - /etc/init.d/mu300-vpn "$2" >/dev/null 2>&1 - ok "vpn $2" - else - fail "vpn $2" "VPN integration is not provided by this platform" - fi - ;; reboot:|poweroff:) sleep 3 # the reply has to make it out first "$1" # procd stops services and unmounts normally; never force @@ -95,7 +86,7 @@ case "${1:-}:${2:-}" in fi ;; *) - echo "usage: $0 radio on|off | data up|down | wifi on|off | modem-reset | vpn start|stop | reboot | poweroff | os android" >&2 + echo "usage: $0 radio on|off | data up|down | wifi on|off | modem-reset | reboot | poweroff | os android" >&2 printf '{"ok":0,"error":"unknown op"}\n' exit 2 ;; diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward index 0d901f4c..208d3ce5 100644 --- a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward @@ -608,7 +608,8 @@ device_info_sms() { printf '%s%s' "$_model" "${nickname:+ ($nickname)}" } sms_units() { - printf '%s' "$1" | LC_ALL=C awk ' + # The added terminator lets NR>1 count every original LF, including tails. + printf '%s\n' "$1" | LC_ALL=C awk ' BEGIN { for (i=1; i<256; i++) ord[sprintf("%c",i)]=i; count=0 } NR>1 { count++ } { @@ -817,7 +818,11 @@ process_sms() { _scts=$(msg_field "$_file" scts) _source=$(msg_field "$_file" source) _coding=$(msg_field "$_file" coding) - _body=$(msg_body "$_file") + # Command substitution strips all trailing LF. Protect them with a + # sentinel, then remove only store_msg's single file terminator. + _body=$(msg_body "$_file"; printf '.') + _body=${_body%.} + _body=${_body%"$NL"} last_id=$_id save_state || { write_result storage_failed "$power_last_result"; return 1; } _processed=$((_processed + 1)) diff --git a/openwrt/luci-app-mu300/root/usr/share/ucode/mu300/dash.uc b/openwrt/luci-app-mu300/root/usr/share/ucode/mu300/dash.uc index f94c869c..2540e004 100644 --- a/openwrt/luci-app-mu300/root/usr/share/ucode/mu300/dash.uc +++ b/openwrt/luci-app-mu300/root/usr/share/ucode/mu300/dash.uc @@ -18,6 +18,15 @@ function text(v) { return v == null || v === '' ? null : replace(''+v,/[\r\n]/g, function device(v) { return type(v)=='string' && v!='.' && v!='..' && match(v,/^[A-Za-z0-9_.:-]{1,15}$/) ? v : null; } function exists(p) { return fs.stat(ROOT+p)!=null; } function executable(p) { return fs.access(ROOT+p,'x')==true; } +export function sim_state(slot) { + if(!(slot in ['0','1']))return 'unknown'; + let row=obj('/run/mu300-registration/sim'+slot+'.json'); + // The AT owner records absence only after the SIM was known to be powered. + // An empty ICCID or CFUN=0 alone is never proof of removal. + if(type(row)!='object' || row.slot!==int(slot) || !exists('/run/mu300-registration/sim-power'+slot) || + !(row.state in ['ready','locked','absent']))return 'unknown'; + return row.state; +}; function call(bus,o,m) { return bus?.call(o,m,{}) || {}; } function net(dev) { dev=device(dev); @@ -182,11 +191,6 @@ export function info(slot) { if(match(pid,/^[1-9][0-9]*$/) && exists('/proc/'+pid) && fs.stat(ROOT+p+'/cmd')?.type=='fifo')atd=true; } let urc=fs.stat(ROOT+'/run/mu300-at/urc/stty_nr0.log'); - let vpn=rd('/etc/mu300/vpn.conf'), engine=null, enabled=false; - for(let line in split(vpn,'\n')) { - if(line=='ENABLE=1')enabled=true; - if(substr(line,0,7)=='ENGINE=')engine=text(substr(line,7)); - } let ht=replace(wifi.htmode || '',/[^0-9]/g,''); return {ts:now,uptime:int(rd('/proc/uptime')),host:text(c.get('system','@system[0]','hostname') || rd('/proc/sys/kernel/hostname')), model:text(rd('/tmp/sysinfo/model') || replace(rd('/proc/device-tree/model'),/\x00/g,'')),fw,kernel, @@ -201,10 +205,10 @@ export function info(slot) { country:text(wifi.country),enc:wifi.enc || 'none',hidden:wifi.hidden ?? null,hostapd:hapd.status=='ENABLED'?1:0, clients:stations.rows,clients_n:stations.count}, lan:{leases:length(leases),ip:address(rows4,lan,false),list:leases}, - modem:{alive:atd || (urc && now-urc.mtime<240)?1:0,atd:atd?1:0,data_paused:exists('/run/mu300-mobile-data-down')?1:0}, - boot:boot(),capabilities:{vpn:executable('/etc/init.d/mu300-vpn')?1:0,dualboot:executable('/opt/mu300/bin/mu300-next-boot')?1:0}, - conns:conntrack(),traffic:obj('/run/unisoc-modem-traffic/view.json'), - vpn:{enabled:enabled?1:0,engine,up:exists('/sys/class/net/xtun') || exists('/sys/class/net/sbtun')?1:0}}; + modem:{alive:atd || (urc && now-urc.mtime<240)?1:0,atd:atd?1:0,data_paused:exists('/run/mu300-mobile-data-down')?1:0, + sims:map(['0','1'],n=>({slot:int(n),state:atd?sim_state(n):'unknown'}))}, + boot:boot(),capabilities:{dualboot:executable('/opt/mu300/bin/mu300-next-boot')?1:0}, + conns:conntrack(),traffic:obj('/run/unisoc-modem-traffic/view.json')}; }; function age(path) { let s=fs.stat(ROOT+path); return s?.size>0?time()-s.mtime:-1; } diff --git a/openwrt/luci-app-unisoc-ota/README.i18n.md b/openwrt/luci-app-unisoc-ota/README.i18n.md new file mode 100644 index 00000000..4bd6647e --- /dev/null +++ b/openwrt/luci-app-unisoc-ota/README.i18n.md @@ -0,0 +1,14 @@ +# Menu translations + +The menu uses LuCI's native `System patches` message key. English is the source +language; Simplified Chinese and Turkish catalogs are bundled in `root/`, so +both package installation and copying the overlay install the translations. +Page content keeps its existing language selection. + +Regenerate the committed LMO files after changing PO sources, using LuCI's +`po2lmo` (from this directory): + +```sh +po2lmo po/zh_Hans/unisoc-ota.po root/usr/lib/lua/luci/i18n/unisoc-ota.zh-cn.lmo +po2lmo po/tr/unisoc-ota.po root/usr/lib/lua/luci/i18n/unisoc-ota.tr.lmo +``` diff --git a/openwrt/luci-app-unisoc-ota/po/tr/unisoc-ota.po b/openwrt/luci-app-unisoc-ota/po/tr/unisoc-ota.po new file mode 100644 index 00000000..01e0cf53 --- /dev/null +++ b/openwrt/luci-app-unisoc-ota/po/tr/unisoc-ota.po @@ -0,0 +1,7 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: tr\n" + +msgid "System patches" +msgstr "Sistem yamaları" diff --git a/openwrt/luci-app-unisoc-ota/po/zh_Hans/unisoc-ota.po b/openwrt/luci-app-unisoc-ota/po/zh_Hans/unisoc-ota.po new file mode 100644 index 00000000..165f255c --- /dev/null +++ b/openwrt/luci-app-unisoc-ota/po/zh_Hans/unisoc-ota.po @@ -0,0 +1,7 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: zh_Hans\n" + +msgid "System patches" +msgstr "系统补丁" diff --git a/openwrt/luci-app-unisoc-ota/root/usr/lib/lua/luci/i18n/unisoc-ota.tr.lmo b/openwrt/luci-app-unisoc-ota/root/usr/lib/lua/luci/i18n/unisoc-ota.tr.lmo new file mode 100644 index 00000000..61e4421c Binary files /dev/null and b/openwrt/luci-app-unisoc-ota/root/usr/lib/lua/luci/i18n/unisoc-ota.tr.lmo differ diff --git a/openwrt/luci-app-unisoc-ota/root/usr/lib/lua/luci/i18n/unisoc-ota.zh-cn.lmo b/openwrt/luci-app-unisoc-ota/root/usr/lib/lua/luci/i18n/unisoc-ota.zh-cn.lmo new file mode 100644 index 00000000..ad9a5c6f Binary files /dev/null and b/openwrt/luci-app-unisoc-ota/root/usr/lib/lua/luci/i18n/unisoc-ota.zh-cn.lmo differ diff --git a/openwrt/luci-app-unisoc-ota/root/usr/share/luci/menu.d/unisoc-ota.json b/openwrt/luci-app-unisoc-ota/root/usr/share/luci/menu.d/unisoc-ota.json index 96db55eb..1cb4424f 100644 --- a/openwrt/luci-app-unisoc-ota/root/usr/share/luci/menu.d/unisoc-ota.json +++ b/openwrt/luci-app-unisoc-ota/root/usr/share/luci/menu.d/unisoc-ota.json @@ -1,6 +1,6 @@ { "admin/system/unisoc-ota": { - "title": "系统补丁 / System patches", + "title": "System patches", "order": 65, "action": {"type": "view", "path": "system/unisoc-ota"}, "depends": {"acl": ["luci-app-unisoc-ota"]} diff --git a/openwrt/no-vpn-payload.py b/openwrt/no-vpn-payload.py index 2c11f315..03b3c65f 100644 --- a/openwrt/no-vpn-payload.py +++ b/openwrt/no-vpn-payload.py @@ -4,6 +4,7 @@ import argparse import io import os import re +import runpy from pathlib import Path, PurePosixPath import tarfile import tempfile @@ -12,6 +13,7 @@ APPS = {'xray', 'sing-box', 'singbox', 'hev-socks5-tunnel', 'openvpn', 'openconn 'ocserv', 'tailscale', 'tailscaled', 'zerotier', 'zerotier-one', 'zerotier-cli', 'zerotier-idtool', 'wireguard-go', 'wg', 'wg-quick', 'ipsec', 'charon', 'strongswan', 'xl2tpd', 'pptpd', 'sstpc', 'softethervpn', 'mu300-vpn'} +UI = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'tools/release-ui-policy.py')) def forbidden(name): parts=PurePosixPath(name).parts @@ -39,16 +41,29 @@ def strip(archive): fd,tmp=tempfile.mkstemp(prefix=archive.name+'.no-vpn.',dir=archive.parent) os.close(fd) try: + # Plan small UI/database edits first, then stream the archive. Never + # unpack another complete rootfs or leave stale APK ownership records. + files = {} + with tarfile.open(archive, 'r|gz') as src: + for member in src: + name = member.name.removeprefix('./') + if member.isfile() and UI['candidate'](name): + if member.size > 16 * 1024 * 1024: + raise ValueError('Unexpected UI resource size: ' + name) + files[name] = src.extractfile(member).read() + obsolete, changed = UI['plan'](files) with tarfile.open(archive,'r|gz') as src,tarfile.open(tmp,'w:gz',compresslevel=6) as dst: for member in src: name=member.name.removeprefix('./') - if forbidden(name): + if forbidden(name) or name in obsolete: removed.append(name);continue if name.startswith('lib/apk/packages/') and any(PurePosixPath(name).name.startswith(app+'-') for app in APPS): raise ValueError('VPN APK installed in base; remove it from package selection: '+name) data=src.extractfile(member) if member.isfile() else None if name=='opt/mu300/bin/mu300-toolkit': content=toolkit(data.read());member.size=len(content);data=io.BytesIO(content) + if name in changed: + content=changed[name];member.size=len(content);data=io.BytesIO(content) dst.addfile(member,data) os.chmod(tmp,archive.stat().st_mode & 0o777) os.replace(tmp,archive) diff --git a/openwrt/overlay/etc/hotplug.d/iface/10-mu300-usb b/openwrt/overlay/etc/hotplug.d/iface/10-mu300-usb index e47af82c..7c677fba 100755 --- a/openwrt/overlay/etc/hotplug.d/iface/10-mu300-usb +++ b/openwrt/overlay/etc/hotplug.d/iface/10-mu300-usb @@ -1,6 +1,7 @@ #!/bin/sh # Stop the temporary preinit DHCP server only when the real LAN is up. -[ "$ACTION" = ifup ] && [ "$INTERFACE" = lan ] || exit 0 +[ "$INTERFACE" = lan ] || exit 0 +case "$ACTION" in ifup|ifupdate) ;; *) exit 0 ;; esac # RNDIS must be a bridge port before removing its inherited preinit address. # Installed bridge configurations can predate the user's switch to RNDIS. if [ -e /sys/class/net/rndis0 ]; then @@ -10,24 +11,22 @@ fi pid=$(cat /run/mu300-early-udhcpd.pid 2>/dev/null) [ -n "$pid" ] && kill "$pid" 2>/dev/null rm -f /run/mu300-early-udhcpd.pid -# netifd has transferred usb0 to br-lan without changing the management IP or -# DHCP lease. - # With the RNDIS-only gadget, initramfs gives rndis0 the LAN address to serve # early DHCP. netifd can retain that address after enslaving rndis0, creating # two equal 192.168.77.0/24 routes; replies then leave through the wrong # device and the Windows host cannot even ping br-lan. Keep the IP on br-lan -# only, after netifd has installed it. This also handles an NCM handoff if -# that driver ever retains its early address. -bridge_ip=$(ip -4 -o addr show dev br-lan 2>/dev/null | awk 'NR == 1 { print $4 }') +# only, after netifd has installed it. The early address can differ from the +# configured LAN after the user changes subnet: matching only br-lan's IP +# leaves 192.168.77.1 reachable forever. Bridged gadget ports have no IPv4 +# ownership; all configured LAN addresses belong to br-lan. Leave unbridged +# interfaces and IPv6 alone, without bringing a link down or rebinding USB. +bridge_ip=$(ip -4 -o addr show dev br-lan scope global 2>/dev/null | awk 'NR == 1 { print $4 }') if [ -n "$bridge_ip" ]; then for nic in usb0 rndis0; do ip -o link show dev "$nic" 2>/dev/null | grep -q 'master br-lan' || continue - # Match the address even when preinit and netifd used different prefixes. - nic_ip=$(ip -4 -o addr show dev "$nic" 2>/dev/null | - awk -v a="${bridge_ip%/*}" '{ split($4, p, "/"); if (p[1] == a) { print $4; exit } }') - [ -n "$nic_ip" ] || continue - ip addr del "$nic_ip" dev "$nic" 2>/dev/null || true + for nic_ip in $(ip -4 -o addr show dev "$nic" scope global 2>/dev/null | awk '{ print $4 }'); do + ip -4 addr del "$nic_ip" dev "$nic" 2>/dev/null || true + done done fi diff --git a/openwrt/overlay/etc/init.d/mu300-vpn b/openwrt/overlay/etc/init.d/mu300-vpn deleted file mode 100755 index ab09f6af..00000000 --- a/openwrt/overlay/etc/init.d/mu300-vpn +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh /etc/rc.common -# VLESS via Xray (default) or sing-box, on a TUN; settings in /etc/mu300/vpn.conf, see /opt/mu300/bin/mu300-vpn -START=95 -USE_PROCD=1 -export PATH="$PATH:/opt/mu300/busybox-bin" - -start_service() { - [ -r /etc/mu300/vpn.conf ] || return 0 - procd_open_instance vpn - procd_set_param command /opt/mu300/bin/mu300-vpn run - procd_set_param env PATH="$PATH" - procd_set_param respawn 3600 5 0 - procd_set_param stdout 1 - procd_set_param stderr 1 - procd_close_instance -} diff --git a/rootfs/assemble.sh b/rootfs/assemble.sh index e680c75f..4913e040 100755 --- a/rootfs/assemble.sh +++ b/rootfs/assemble.sh @@ -23,7 +23,7 @@ if [ -n "$miss" ]; then fi # Optional inputs decide whether the image can use the modem, Wi-Fi and the GPU at all. Missing ones used to # pass silently and produce an image that boots and does nothing useful, so say what went in. -for o in /firmware /android-subset /android-gpu-subset /bt-init /keys /atd-io /cltest /sing-box /xray /hev-socks5-tunnel; do +for o in /firmware /android-subset /android-gpu-subset /bt-init /keys /atd-io /cltest; do [ -e "$o" ] && echo "assemble.sh: + $o" || echo "assemble.sh: - $o (not mounted; the image will be built without it)" done @@ -64,10 +64,6 @@ if [ -e /bt-init ]; then cp /bt-init $R/opt/mu300/bin/mu300-bt-init; fi # tools/keys build (static arm64): the buttons (mu300-buttons) if [ -e /keys ]; then install -m755 /keys $R/opt/mu300/bin/mu300-keys; fi if [ -e /atd-io ]; then install -m755 /atd-io $R/opt/mu300/bin/mu300-atd-io; fi -# VLESS clients for mu300-vpn: the xray engine (tools/fetch-xray.sh) and sing-box (tools/fetch-sing-box.sh) -if [ -f /sing-box ]; then install -m755 /sing-box $R/opt/mu300/bin/sing-box; fi -if [ -f /xray ]; then install -m755 /xray $R/opt/mu300/bin/xray; fi -if [ -f /hev-socks5-tunnel ]; then install -m755 /hev-socks5-tunnel $R/opt/mu300/bin/hev-socks5-tunnel; fi # accounts still the image's (ubuntu/ubuntu) until an installer or mu300-update puts the device's own in place : > $R/etc/.mu300-accounts-from-image for u in mu300-accounts.service:sysinit.target mu300-early-recorder.service:sysinit.target mu300-vendor.service:sysinit.target mu300-lan.service:multi-user.target mu300-ssh-hostkeys.service:sysinit.target mu300-telnetd.service:multi-user.target serial-getty@ttyGS0.service:getty.target ssh.socket:sockets.target mu300-wifi.service:multi-user.target mu300-wifi-client.service:multi-user.target mu300-mobile-data.service:multi-user.target mu300-mobile-data-watch.service:multi-user.target mu300-fixups.service:sysinit.target mu300-zram.service:swap.target mu300-boot-ok.service:multi-user.target mu300-cp_diskserver.service:multi-user.target mu300-refnotify.service:multi-user.target mu300-extra-modules.service:multi-user.target mu300-hotspot.service:multi-user.target mu300-bluetooth.service:multi-user.target mu300-thermal-guard.service:multi-user.target mu300-audio.service:multi-user.target mu300-firewall.service:sysinit.target mu300-kmsg.service:sysinit.target mu300-toolkit.service:multi-user.target mu300-atd.service:multi-user.target mu300-modem-log.service:multi-user.target mu300-buttons.service:multi-user.target systemd-networkd.service:multi-user.target mu300-user-packages.service:multi-user.target; do @@ -79,7 +75,7 @@ for u in mu300-accounts.service:sysinit.target mu300-early-recorder.service:sysi done # the commands people are told to run must be on PATH, including sudo's secure_path, which does not contain # /opt/mu300/bin - without these links every "sudo mu300-os ..." in the README is a "command not found" -for c in mu300-toolkit mu300-next-boot mu300-os mu300-update mobile-data mu300-at mu300-vpn wifi-client mu300-ttl mu300-wifi-band mu300-led mu300-usb mu300-nfc mu300-user-packages; do ln -sfn /opt/mu300/bin/$c $R/usr/local/bin/$c; done +for c in mu300-toolkit mu300-next-boot mu300-os mu300-update mobile-data mu300-at wifi-client mu300-ttl mu300-wifi-band mu300-led mu300-usb mu300-nfc mu300-user-packages; do ln -sfn /opt/mu300/bin/$c $R/usr/local/bin/$c; done # no graphical/serial login noise on a headless dongle; keep ttyS1 console for debugging ln -sfn /dev/null $R/etc/systemd/system/getty@tty1.service cd $R && tar --numeric-owner -czf /w/mu300-ubuntu-$UBUNTU-rootfs.tar.gz . diff --git a/rootfs/overlay/etc/mu300/vpn.conf.example b/rootfs/overlay/etc/mu300/vpn.conf.example deleted file mode 100644 index 90bf3b3f..00000000 --- a/rootfs/overlay/etc/mu300/vpn.conf.example +++ /dev/null @@ -1,25 +0,0 @@ -# MU300 VPN (VLESS). Copy to /etc/mu300/vpn.conf, edit, then: mu300-vpn gen && restart the service -# Ubuntu: sudo systemctl restart mu300-vpn OpenWrt: /etc/init.d/mu300-vpn restart -ENABLE=1 -# the share link from your server/panel (vless://uuid@host:port?type=...&security=...#name) -VLESS_URI="" -# xray: Xray-core behind hev-socks5-tunnel on a kernel TUN -# sing-box: sing-box's own TUN (FINDINGS 26b) -# unset: xray, or sing-box when KILL_SWITCH=1 -ENGINE=xray -# 1: nothing leaves through the cellular interface except the tunnel itself (also while the tunnel is down). -# Only works with ENGINE=sing-box for now; with xray it is ignored, with a warning. -KILL_SWITCH=0 -# DNS for the device and its clients, resolved through the tunnel -REMOTE_DNS=1.1.1.1 -# sing-box only: used to look up the VPN server's own name (sent directly, outside the tunnel) -BOOTSTRAP_DNS=1.1.1.1 -# more networks that stay local, comma-separated (the device's own USB/Wi-Fi LAN always does) -#LAN_CIDRS=192.168.1.0/24 -# 1: also carry IPv6 (sing-box only, and only if the server has IPv6 connectivity) -IPV6=0 -# sing-box only, optional: reach the VPN server through an HTTP proxy (host:port) -UPSTREAM_HTTP_PROXY= -# xray only. Xray 26 no longer has allowInsecure; for a link that asks for it, the certificate the server presents -# is fetched once (needs openssl), pinned here, and fetched again by itself if the server renews it. Leave empty. -TLS_PIN_SHA256= diff --git a/rootfs/overlay/etc/systemd/system/mu300-vpn.service b/rootfs/overlay/etc/systemd/system/mu300-vpn.service deleted file mode 100644 index e802d656..00000000 --- a/rootfs/overlay/etc/systemd/system/mu300-vpn.service +++ /dev/null @@ -1,17 +0,0 @@ -[Unit] -Description=MU300 VPN (VLESS via Xray or sing-box, TUN) -After=mu300-firewall.service mu300-mobile-data.service -Wants=mu300-mobile-data.service -ConditionPathExists=/etc/mu300/vpn.conf -StartLimitIntervalSec=0 - -[Service] -ExecStart=/opt/mu300/bin/mu300-vpn run -# the engine exits when it starts before the modem has a route to the server (sing-box: "missing default -# interface"; xray: the server name does not resolve yet), and on a renewed server certificate; keep retrying -# instead of hitting the start limit and giving up -Restart=always -RestartSec=10 - -[Install] -WantedBy=multi-user.target diff --git a/rootfs/overlay/opt/mu300/bin/android-vendor-start b/rootfs/overlay/opt/mu300/bin/android-vendor-start index f6be1347..95c161bb 100755 --- a/rootfs/overlay/opt/mu300/bin/android-vendor-start +++ b/rootfs/overlay/opt/mu300/bin/android-vendor-start @@ -34,9 +34,12 @@ mark vendor-props # Two ln calls per partition plus basename/sed/dirname is about 365 fork()s over the 73 partitions (measured: # 0.64 s, all of it on the boot path between the CP being released and the modem being asked to start). # Take the path and PARTNAME in the shell itself and keep only the ln calls. -for u in /sys/class/block/mmcblk0p*/uevent; do +. /opt/mu300/lib/storage.sh +internal_disk=$(mu300_storage_disk) || exit 4 +for u in /sys/class/block/${internal_disk}*/uevent; do [ -e "$u" ] || continue d=${u%/uevent}; d=${d##*/} + case "$d" in "${internal_disk}"p[0-9]*|"${internal_disk}"[0-9]*) ;; *) continue ;; esac n= while IFS='=' read -r k v; do [ "$k" = PARTNAME ] && n=$v; done < "$u" ln -sfn /dev/$d /dev/block/$d diff --git a/rootfs/overlay/opt/mu300/bin/cpu-voltage-platform b/rootfs/overlay/opt/mu300/bin/cpu-voltage-platform index 9a993d6b..9e1f3e7f 100755 --- a/rootfs/overlay/opt/mu300/bin/cpu-voltage-platform +++ b/rootfs/overlay/opt/mu300/bin/cpu-voltage-platform @@ -31,7 +31,8 @@ supported() { case ${hash%% *} in ff4782690fd805ff54fe34853ef8ee5c7e51c3259e20077c55373b50a4b259c2|\ 5b3183f17af9b416e71dea61e578c61824e4e1df43737a1179032f4b20466b2b|\ - f27ac16f44e6cdc87a8ee00a9b53c499c8dde0c3b92c771388e256e84ef12e70) ;; + f27ac16f44e6cdc87a8ee00a9b53c499c8dde0c3b92c771388e256e84ef12e70|\ + 6e3b9234525ace117a503925c8f8db0ed05e1679bd773d4731b56334140f5a2f) ;; *) return 1 ;; esac done diff --git a/rootfs/overlay/opt/mu300/bin/early-recorder b/rootfs/overlay/opt/mu300/bin/early-recorder index a773090e..2ab94c8b 100755 --- a/rootfs/overlay/opt/mu300/bin/early-recorder +++ b/rootfs/overlay/opt/mu300/bin/early-recorder @@ -7,8 +7,10 @@ export PATH="$PATH:/opt/mu300/busybox-bin" slot=$(cat /run/mu300/linux-slot 2>/dev/null || echo b) case $slot in a|b) ;; *) exit 0 ;; esac bootpart=boot_$slot -BOOTDEV=$(readlink -f "/dev/block/by-name/$bootpart" 2>/dev/null) -[ -b "$BOOTDEV" ] || for u in /sys/class/block/mmcblk0p*/uevent; do grep -qx "PARTNAME=$bootpart" "$u" && BOOTDEV=/dev/$(basename "$(dirname "$u")"); done +. /opt/mu300/lib/storage.sh +disk=$(mu300_storage_disk) || exit 0 +node=$(mu300_storage_part "$bootpart" "$disk") || exit 0 +BOOTDEV=/dev/$node [ -b "$BOOTDEV" ] || exit 0 # --- cpus begin # The little cluster (FINDINGS 208): a round reads the kernel's whole log, which is work that woke an A76 every few diff --git a/rootfs/overlay/opt/mu300/bin/mu300-at b/rootfs/overlay/opt/mu300/bin/mu300-at index 1a8e8094..af0aedb4 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-at +++ b/rootfs/overlay/opt/mu300/bin/mu300-at @@ -130,7 +130,10 @@ if [ -p "$DIR/cmd" ]; then # unlinked FIFOs while this client keeps the global command lock. O_RDWR # never blocks; with no daemon the answer timeout below releases the lock. native_gate || exit 1 - exec 9<> "$DIR/cmd" 2>/dev/null || { + # Keep stderr attached to the caller. A bare exec with 2>/dev/null also + # silenced every later timeout/final-response diagnostic in this client. + # `command` makes a failed special-builtin redirection return to this guard. + { command exec 9<> "$DIR/cmd"; } 2>/dev/null || { echo "mu300-at: the daemon is not reading commands" >&2; exit 1; } printf '%s %s %s\n' "$T" "$answer" "$cmd" >&9 || { exec 9>&-; echo "mu300-at: the daemon is not reading commands" >&2; exit 1; } diff --git a/rootfs/overlay/opt/mu300/bin/mu300-ipa-dump b/rootfs/overlay/opt/mu300/bin/mu300-ipa-dump index 4486e60d..dc30ee97 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-ipa-dump +++ b/rootfs/overlay/opt/mu300/bin/mu300-ipa-dump @@ -84,10 +84,10 @@ echo echo "=== pushing traffic at $TARGET through $IFACE" # TCP, not ping. On this network ICMP does not come back even over a working link: measured on stock Android, # where data demonstrably works, "ping -I sipa_eth0 8.8.8.8" reports 100% loss - and that form binds to the -# device, so it is the cellular path and not a VPN eating the echo. A ping-based test here reads "nothing +# device, so it is the cellular path and not a tunnel intercepting the echo. A ping-based test here reads "nothing # arrives" on a link that is fine, which is how this investigation lost time more than once. # -# What answers the question is not whether the connect succeeds - it may well be carried by a VPN, and on +# What answers the question is not whether the connect succeeds - it may well be carried by a tunnel, and on # Android it was - but whether rx_packets on this interface moves at all. Downlink is downlink whoever the # bytes belong to, and ours has never moved. src=$(ip -4 -br addr show "$IFACE" | awk '{print $3}' | cut -d/ -f1) diff --git a/rootfs/overlay/opt/mu300/bin/mu300-modemd b/rootfs/overlay/opt/mu300/bin/mu300-modemd index 53669917..999bbaf9 100644 --- a/rootfs/overlay/opt/mu300/bin/mu300-modemd +++ b/rootfs/overlay/opt/mu300/bin/mu300-modemd @@ -258,7 +258,9 @@ io_connect = function() { // ------------------------------------------------------------------ requests (mu300-at's protocol) const LF = '\n', CR = '\r', SUB = '\x1a'; -// one_request CMD: exactly one modem command - no line feed, and a CR only in "AT+CMGS=" +// one_request CMD: no line feed; an embedded CR is only a PDU submission, +// optionally prefixed by the sender's atomic SIM selection. Keep the prefix +// on the wire: stripping it would submit on whichever SIM last owned the port. function one_request(cmd) { if (index(cmd, LF) >= 0) return false; @@ -266,7 +268,7 @@ function one_request(cmd) { if (c < 0) return true; let head = substr(cmd, 0, c), body = substr(cmd, c + 1); - if (!match(head, /^AT\+CMG[SW]=[0-9]{1,3}$/)) + if (!match(head, /^AT(\+SPACTCARD=[01];)?\+CMG[SW]=[0-9]{1,3}$/)) return false; if (substr(body, -1) != SUB) return false; diff --git a/rootfs/overlay/opt/mu300/bin/mu300-sms b/rootfs/overlay/opt/mu300/bin/mu300-sms index 4443c009..b2b33f34 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-sms +++ b/rootfs/overlay/opt/mu300/bin/mu300-sms @@ -267,8 +267,11 @@ ucs2_to_esc() { # UTF-8 -> UCS-2 hex (surrogate pair above 0xFFFF). Malformed bytes become "?" rather than # aborting the message. utf8_to_ucs2() { - LC_ALL=C awk ' + # The extra terminator preserves even trailing LF as records. Emit their + # encoded 000a between records, never a literal LF inside the PDU string. + printf '%s\n' "$1" | LC_ALL=C awk ' BEGIN { for (i = 1; i < 256; i++) ord[sprintf("%c", i)] = i } + NR > 1 { printf "000a" } { s = $0; n = length(s); i = 1; out = "" while (i <= n) { @@ -291,8 +294,9 @@ utf8_to_ucs2() { out = out sprintf("%04x", cp) } } - print out - }' + printf "%s", out + } + END { printf "\n" }' } # BCD digits -> semioctets ("10086" -> "0180F6"): low nibble carries the first digit, an odd @@ -838,7 +842,7 @@ cmd_send() { case $idigits in ''|*[!0-9]*) die "$num is not a phone number" ;; esac [ -n "$text" ] || die "send needs a text" [ -p "$ATDIR/cmd" ] || die "mu300-atd is not running - a submit needs its two-phase path" - ud=$(printf '%s' "$text" | utf8_to_ucs2) + ud=$(utf8_to_ucs2 "$text") [ $(( ${#ud} / 4 )) -gt 70 ] && die "text is $(( ${#ud} / 4 )) UCS-2 units; one SMS part carries 70 (concatenation not implemented)" udl=$(( ${#ud} / 2 )) @@ -852,7 +856,7 @@ cmd_send() { echo "submitting to $num ($len octets, $((udl / 2)) UCS-2 units)" sms_op_lock - local r0 r2 submit + local r0 r2 submit submit_rc reason at_lock smsc_refresh r0=$(at 'AT+CAVIMS=1' 6) @@ -860,11 +864,14 @@ cmd_send() { r0=$(at 'AT+CMGF=0' 6) # PDU mode for the submit case $r0 in *OK*) ;; *) die "modem refused AT+CMGF=0: $r0" ;; esac submit=$(printf 'AT+CMGS=%s\r%s\032' "$len" "$pdu") - r2=$(at "$submit" 25) + r2=$(at "$submit" 25 2>&1); submit_rc=$? # Stay in PDU mode. Switching back to text here corrupts direct +CMT # delivery; the legacy SIM reader selects text explicitly when needed. if ! printf '%s\n' "$r2" | grep -q '^+CMGS:'; then - die "submit failed: $(printf '%s\n' "$r2" | grep -E 'CMS|ERROR' | head -1)" + reason=$(printf '%s\n' "$r2" | grep -E 'CMS|ERROR|mu300-at:|unisoc-at:' | head -1) + [ -n "$reason" ] || reason="no submission acknowledgement (AT exit $submit_rc); delivery status unknown" + # A timeout after Ctrl-Z is ambiguous. Do not send the PDU again. + die "submit failed: $reason" fi # Never wait for the local pool while owning the AT channel. at_unlock diff --git a/rootfs/overlay/opt/mu300/bin/mu300-toolkit b/rootfs/overlay/opt/mu300/bin/mu300-toolkit index bcd00eb7..31195703 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-toolkit +++ b/rootfs/overlay/opt/mu300/bin/mu300-toolkit @@ -8,7 +8,6 @@ # mu300-toolkit apply apply the saved settings: performance profile, TTL (boot service) export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin" CONF=/etc/mu300/toolkit.conf -VPN_CONF=/etc/mu300/vpn.conf CPUFREQ=/sys/devices/system/cpu/cpufreq GPU=$(ls -d /sys/class/devfreq/*.gpu 2>/dev/null | head -n1) # The U30 Air's battery: "battery" under 5.4 (the vendor charger manager), "sc27xx-fgu" under mainline. The F50 has @@ -174,7 +173,7 @@ sec == "net" && /:/ { cur["rx_" ifc] = f[1]; cur["tx_" ifc] = f[9] } sec == "load" { if (NF == 5) load = $1 " " $2 " " $3; else up = int($1) } -sec == "disk" && $3 ~ /^mmcblk[0-9]+$/ { cur["dw"] += $10; cur["dr"] += $6 } +sec == "disk" && $3 ~ /^(mmcblk[0-9]+|sd[a-z]+)$/ { cur["dw"] += $10; cur["dr"] += $6 } sec == "sys" { i = index($0, ":"); path = substr($0, 1, i - 1); val = substr($0, i + 1) n = split(path, pp, "/"); leaf = pp[n]; node = pp[n - 1] @@ -587,36 +586,6 @@ menu_wifi() { done } -vpn_enabled() { [ -r "$VPN_CONF" ] && grep -q '^ENABLE=1' "$VPN_CONF"; } -menu_vpn() { - while :; do - title "VPN (VLESS)" - printf ' service: %s config: %s\n\n' "$(state_color "$(svc status mu300-vpn)")" \ - "$( [ -r "$VPN_CONF" ] && (vpn_enabled && echo "enabled" || echo "disabled") || echo "missing")" - /opt/mu300/bin/mu300-vpn status 2>/dev/null | sed 's/^/ /' - menu_items="Turn on (ENABLE=1, start at boot)|Turn off (stop, remove kill switch)|Edit config ($VPN_CONF)|Restart" - printf '\n' - i=1; IFS='|'; for l in $menu_items; do printf ' %s%d%s %s\n' "$C" "$i" "$N" "$l"; i=$((i + 1)); done; unset IFS - printf '\n %s0%s Back\n\n > ' "$C" "$N" - read -r c || return - case $c in - 1) [ -r "$VPN_CONF" ] || cp /etc/mu300/vpn.conf.example "$VPN_CONF" 2>/dev/null - chmod 600 "$VPN_CONF" - if grep -q '^VLESS_URI=""' "$VPN_CONF" || ! grep -q '^VLESS_URI=' "$VPN_CONF"; then - echo " set VLESS_URI first (Edit config)"; pause; continue - fi - sed -i 's/^ENABLE=.*/ENABLE=1/' "$VPN_CONF"; svc enable mu300-vpn; sleep 3 ;; - 2) [ -r "$VPN_CONF" ] && sed -i 's/^ENABLE=.*/ENABLE=0/' "$VPN_CONF" - svc disable mu300-vpn; /opt/mu300/bin/mu300-vpn off ;; - 3) [ -r "$VPN_CONF" ] || { cp /etc/mu300/vpn.conf.example "$VPN_CONF" 2>/dev/null; chmod 600 "$VPN_CONF"; } - ${EDITOR:-$(command -v nano || echo vi)} "$VPN_CONF" - vpn_enabled && svc restart mu300-vpn ;; - 4) svc restart mu300-vpn; sleep 3 ;; - *) return ;; - esac - done -} - # Live radio quality: move the device around and watch RSRP. The watchdog is paused while this runs, because only # one reader can have the modem's AT channel at a time. menu_signal() { @@ -668,7 +637,7 @@ menu_network() { while :; do menu "Network" "Live traffic (monitor)" "Interfaces and addresses" "Mobile data: status" \ "Mobile signal (live, for finding a better spot)" "Mobile data: reconnect" "Mobile data: disconnect" \ - "Wi-Fi (hotspot, or join a network)" "VPN" "TTL of mobile data (hide hotspot use)" + "Wi-Fi (hotspot, or join a network)" "TTL of mobile data (hide hotspot use)" case $CHOICE in 1) monitor ;; 2) title "Interfaces"; { ip -br addr 2>/dev/null || ip addr; } | grep -vE '^(dummy|tunl|gre|erspan|ip_vti|ip6_vti|sit|ip6tnl|ip6gre|sipa_eth[1-9])' | sed 's/^/ /' @@ -679,14 +648,13 @@ menu_network() { echo " reconnect started"; pause ;; 6) if is_openwrt; then ifdown wan; else svc stop mu300-mobile-data; fi; pause ;; 7) menu_wifi ;; - 8) menu_vpn ;; - 9) menu_ttl ;; + 8) menu_ttl ;; *) return ;; esac done } -MU300_SERVICES="mu300-vendor mu300-wifi mu300-hotspot mu300-lan mu300-mobile-data mu300-mobile-data-watch mu300-bluetooth mu300-vpn mu300-firewall mu300-thermal-guard mu300-zram mu300-toolkit" +MU300_SERVICES="mu300-vendor mu300-wifi mu300-hotspot mu300-lan mu300-mobile-data mu300-mobile-data-watch mu300-bluetooth mu300-firewall mu300-thermal-guard mu300-zram mu300-toolkit" menu_services() { while :; do title "Services" @@ -773,7 +741,7 @@ menu_system() { main_menu() { while :; do menu "Main menu" "Monitor (task manager)" "Performance profile (CPU/GPU)" "Stress test (CPU/GPU/network)" \ - "Network, mobile data, VPN" "Services" "System (password, hostname, timezone, reboot)" "Summary" + "Network, mobile data" "Services" "System (password, hostname, timezone, reboot)" "Summary" case $CHOICE in 1) monitor ;; 2) menu_performance ;; diff --git a/rootfs/overlay/opt/mu300/bin/mu300-update b/rootfs/overlay/opt/mu300/bin/mu300-update index 2adabe5c..4a7aa3e4 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-update +++ b/rootfs/overlay/opt/mu300/bin/mu300-update @@ -28,10 +28,7 @@ VERSION_FILE=$CONF/image-version say() { printf '\n==> %s\n' "$*"; } die() { printf '\nERROR: %s\n' "$*" >&2; exit 1; } have() { command -v "$1" >/dev/null 2>&1; } -vpn_conf_value() { - [ -r "$1" ] || return 0 - sed -n "s/^$2=//p" "$1" 2>/dev/null | tail -n1 | sed "s/[[:space:]]#.*//; s/[\"' ]//g" -} + # A transfer that stalls is cut off and retried rather than waited for: with older boot images the IPA's downlink # can die in the middle of one (docs/FINDINGS.md 32), and without a timeout the update hung for good. @@ -121,7 +118,7 @@ root_layout() { _back=$(cat "$_sys/sys/class/block/$_rn/loop/backing_file" 2>/dev/null) case $_back in /dev/mmcblk[0-9]*) echo region ;; ?*) echo image ;; *) echo unknown ;; esac return ;; - mmcblk[0-9]*) + mmcblk[0-9]*|sd[a-z]*[0-9]) if grep -qx PARTNAME=mu300root "$_sys/sys/class/block/$_rn/uevent" 2>/dev/null; then echo part; return; fi _disk=${_rn%p*} if [ "$(cat "$_sys/sys/class/block/$_disk/device/type" 2>/dev/null)" = SD ]; then echo sd; return; fi ;; @@ -281,7 +278,7 @@ accounts() { # --- user-packages begin # Packages installed on the device are not in the release's image, and an update puts the image in place while it -# keeps /etc/config (OpenWrt) and /etc/mu300: their programs were gone and their settings stayed - OpenClash's left +# keeps /etc/config (OpenWrt) and /etc/mu300: their programs were gone and their settings stayed - an absent DNS extension left # the device without DNS (#116). So before the switch the update writes down what was added - the packages asked for # by hand (OpenWrt: /etc/apk/world; Ubuntu: dpkg's packages that apt did not pull in by itself) less the image's # own set (etc/mu300/image-packages, written when the image is built) - into etc/mu300/user-packages/ of the new diff --git a/rootfs/overlay/opt/mu300/bin/mu300-user-packages b/rootfs/overlay/opt/mu300/bin/mu300-user-packages index a0ebd4d4..b8bcecc4 100644 --- a/rootfs/overlay/opt/mu300/bin/mu300-user-packages +++ b/rootfs/overlay/opt/mu300/bin/mu300-user-packages @@ -16,7 +16,7 @@ # tries again at the next boot, five boots at most (then: retry). A package the feeds do not have (installed from a # file) fails for good: its settings stay in /etc/mu300/orphaned-config, and status says how to put them back. # -# After the reinstall step OpenWrt's DNS is checked: a proxy (OpenClash and the like) points dnsmasq at a port of its +# After the reinstall step OpenWrt's DNS is checked: a local DNS forwarding service points dnsmasq at a port of its # own on 127.0.0.1 while it runs, and an update took that over with /etc/config/dhcp - without the proxy there was no # DNS at all (#116). It never weakens DNS privacy by itself (see dns_check): a forwarder of a package that is gone for # good is removed only when another server stays; an only one is reported, and repair-dns removes it on request. @@ -69,13 +69,12 @@ port_bound() { cat "$PROC/net/udp" "$PROC/net/udp6" 2>/dev/null | awk -v h="$_h" '{ n = split($2, a, ":"); if (n > 1 && toupper(a[n]) == h) f = 1 } END { exit !f }' } -# What a proxy (OpenClash and the like) left in dnsmasq: while it runs it points dnsmasq at a port of its own on the +# What a local DNS forwarding service left in dnsmasq: while it runs it points dnsmasq at a port of its own on the # loopback, and an update took that over with /etc/config/dhcp (#116). DNS privacy comes first: nothing here ever # sends DNS to the connection's resolvers by itself, and it acts only on a forwarder that is provably orphaned: # - its port is a value in the set-aside settings of a package the update wrote down (attributable), and nothing in -# the project's own settings (/etc/mu300, the VPN's included) names that port; +# the project's own settings (/etc/mu300) names that port; # - nothing is bound to it at any of DNS_CHECKS looks, DNS_INTERVAL seconds apart; -# - the VPN is off (vpn.conf ENABLE, read with vpn_conf_value, never printed); # - for a change at boot: the package is definitively absent (failed in the feeds, given up, or skipped) - checked # after the reinstall step, never before - and another server stays in that dnsmasq section. A forwarder that is # the only one is reported (status, the note at login) and left as it is: no DNS until the user decides, with @@ -99,12 +98,11 @@ port_owner() { done < "$D/files" return 1 } -# project_names PORT: the project's own settings (the VPN's too) mention the port +# project_names PORT: the project's own settings mention the port project_names() { [ -n "$(find "$R/etc/mu300" -type f ! -path '*/orphaned-config/*' ! -path '*/user-packages/*' \ -exec grep -lw -- "$1" {} + 2>/dev/null)" ] } -vpn_on() { [ "$(vpn_conf_value "$R/etc/mu300/vpn.conf" ENABLE)" = 1 ]; } # dns_orphans: "SECTION VALUE PKG FINAL OTHERS" for each attributable loopback forwarder nothing listens on now # (FINAL 1: the package is definitively absent; OTHERS 1: the section has another server) dns_orphans() { @@ -129,11 +127,6 @@ dns_check() { [ "$KIND" = openwrt ] && have uci || return 0 _c=$(dns_orphans) [ -n "$_c" ] || return 0 - if vpn_on; then - log "DNS: dnsmasq forwards to a port of a package that is not installed, and the VPN is on: nothing is changed (uci show dhcp)" - echo "dnsmasq forwards to a port of a package that is not installed; the VPN is on, so nothing was changed: uci show dhcp" > "$DNS_NOTE" - return 0 - fi # seen again over the window: one that comes up meanwhile was starting, not gone _i=1 while [ "$_i" -lt "$DNS_CHECKS" ] && [ -n "$_c" ]; do diff --git a/rootfs/overlay/opt/mu300/bin/mu300-vpn b/rootfs/overlay/opt/mu300/bin/mu300-vpn deleted file mode 100755 index 3aa838ec..00000000 --- a/rootfs/overlay/opt/mu300/bin/mu300-vpn +++ /dev/null @@ -1,444 +0,0 @@ -#!/bin/sh -# VLESS client for the MU300 (Ubuntu and OpenWrt): a TUN device and policy routing, so the device's own traffic -# and USB/Wi-Fi clients all leave through the tunnel. Settings: /etc/mu300/vpn.conf -# ENGINE=xray Xray-core (the VLESS reference client) behind hev-socks5-tunnel, a small C program on a -# plain kernel TUN - the default -# ENGINE=sing-box sing-box with its own TUN inbound (gvisor stack, see FINDINGS 26b) -# mu300-vpn gen build the engine's config under /run/mu300-vpn from vpn.conf and check it -# mu300-vpn run gen + kill switch + run the engine in the foreground (used by the service) -# mu300-vpn off remove the kill switch (the service stop does not, so a crash never leaks), -# and any routing an engine left behind if it is no longer running -# mu300-vpn status service, tunnel, exit IP -set -e -CONF=${MU300_VPN_CONF:-/etc/mu300/vpn.conf} -RUN=${MU300_VPN_RUN:-/run/mu300-vpn} # (MU300_VPN_RUN, MU300_LAN_CONF, MU300_BIN, MU300_LIB: for tests/) -MARK=0x2d0 # routing mark on the engine's own connections: they bypass the tunnel and the kill switch -[ -r "$CONF" ] && . "$CONF" -ENABLE=${ENABLE:-0}; KILL_SWITCH=${KILL_SWITCH:-1}; REMOTE_DNS=${REMOTE_DNS:-1.1.1.1} -BOOTSTRAP_DNS=${BOOTSTRAP_DNS:-1.1.1.1}; IPV6=${IPV6:-0} -# The device's own LAN always stays local, whatever LAN_CIDRS says: a vpn.conf copied from another device, or one -# written before the LAN address changed (the U30 Air is on 192.168.78.0/24), would send the replies to its USB -# and Wi-Fi clients into the tunnel. The address br-lan has is the truth (lan.conf or UCI); before it is up, the -# configured one. -own=$(ip -4 -o addr show br-lan 2>/dev/null | awk '{print $4; exit}') -# (only a readable lan.conf is sourced: dash leaves the whole subshell when "." cannot open its file) -own=${own%/*}; [ -n "$own" ] || own=$(f=${MU300_LAN_CONF:-/etc/mu300/lan.conf}; [ -r "$f" ] && . "$f" - echo "${LAN_IP:-$(${MU300_BIN:-/opt/mu300/bin}/mu300-lan-ip)}") -own=${own%.*}.0/24 -case ",${LAN_CIDRS:-}," in *",$own,"*) ;; *) LAN_CIDRS=${LAN_CIDRS:+$LAN_CIDRS,}$own ;; esac -# Xray is the default, except with the kill switch on. The kill switch drops everything unmarked on the cellular -# interface, and before the tunnel exists the server's name is looked up through dnsmasq and its certificate -# fetched with openssl - both unmarked. sing-box does its bootstrap lookup on its own marked socket, so it works -# there. An update keeps vpn.conf, and older ones say KILL_SWITCH=1: they stay on sing-box, which is what they ran. -if [ -z "${ENGINE:-}" ]; then [ "$KILL_SWITCH" = 1 ] && ENGINE=sing-box || ENGINE=xray; fi -XRAY=${XRAY:-/opt/mu300/bin/xray}; HEV=${HEV:-/opt/mu300/bin/hev-socks5-tunnel} -BIN=${SING_BOX:-/opt/mu300/bin/sing-box} -SOCKS_PORT=10808 -# an image built before the xray engine existed has only sing-box: keep working with what is there -if [ "$ENGINE" = xray ] && { [ ! -x "$XRAY" ] || [ ! -x "$HEV" ]; }; then - [ -x "$BIN" ] && { echo "xray engine not installed, using sing-box" >&2; ENGINE=sing-box; } -fi -case "$ENGINE" in xray) TUN=xtun ;; *) TUN=sbtun ;; esac - -# json_str VALUE : JSON string literal -json_str() { printf '"%s"' "$(printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g')"; } -# json_list "a,b,c" : JSON array of strings -json_list() { printf '%s' "$1" | awk -F, '{printf "["; for (i = 1; i <= NF; i++) { gsub(/"/, "\\\"", $i); printf "%s\"%s\"", (i > 1 ? "," : ""), $i } printf "]"}'; } -hex2dec() { printf '%d' "0x$1"; } -# busybox awk has no hex string conversion: decode %XX with printf instead -urldecode() { - rest=$1; out= - while :; do - case "$rest" in - *%[0-9A-Fa-f][0-9A-Fa-f]*) - pre=${rest%%%*}; tail=${rest#*%}; hh=$(printf '%s' "$tail" | cut -c1-2); rest=$(printf '%s' "$tail" | cut -c3-) - out="$out$pre$(printf "\\$(printf '%03o' "$(hex2dec "$hh")")")" ;; - *) out="$out$rest"; break ;; - esac - done - printf '%s' "$out" -} -param() { printf '%s' "$QUERY" | tr '&' '\n' | sed -n "s/^$1=//p" | head -n1; } - -parse_uri() { - u=$VLESS_URI - case "$u" in vless://*) ;; *) echo "VLESS_URI must start with vless://" >&2; exit 1 ;; esac - u=${u#vless://}; u=${u%%#*} - case "$u" in *\?*) QUERY=${u#*\?}; u=${u%%\?*} ;; *) QUERY= ;; esac - UUID=$(urldecode "${u%%@*}"); hp=${u#*@}; hp=${hp%/} - case "$hp" in - \[*\]:*) HOST=${hp#\[}; HOST=${HOST%%\]*}; PORT=${hp##*:} ;; - *:*) HOST=${hp%:*}; PORT=${hp##*:} ;; - *) HOST=$hp; PORT=443 ;; - esac - TYPE=$(param type); TYPE=${TYPE:-tcp} - SECURITY=$(param security); SECURITY=${SECURITY:-none} - SNI=$(urldecode "$(param sni)"); [ -n "$SNI" ] || SNI=$(urldecode "$(param peer)") - FP=$(param fp); ALPN=$(urldecode "$(param alpn)"); FLOW=$(param flow) - INSECURE=$(param allowInsecure); PBK=$(param pbk); SID=$(param sid) - WSPATH=$(urldecode "$(param path)"); WSHOST=$(urldecode "$(param host)"); SVC=$(urldecode "$(param serviceName)") - [ -n "$UUID" ] && [ -n "$HOST" ] || { echo "cannot parse VLESS_URI" >&2; exit 1; } -} - -outbound_json() { - printf '{"type":"vless","tag":"proxy","server":%s,"server_port":%s,"uuid":%s' "$(json_str "$HOST")" "$PORT" "$(json_str "$UUID")" - [ -n "$FLOW" ] && printf ',"flow":%s' "$(json_str "$FLOW")" - printf ',"packet_encoding":"xudp","domain_resolver":"bootstrap"' - [ -n "$UPSTREAM_HTTP_PROXY" ] && printf ',"detour":"upstream"' - case "$SECURITY" in - tls|reality) - printf ',"tls":{"enabled":true,"server_name":%s' "$(json_str "${SNI:-$HOST}")" - case "$INSECURE" in 1|true) printf ',"insecure":true' ;; esac - # h3 (QUIC) does not apply to VLESS over TCP - ALPN=$(printf '%s' "$ALPN" | awk -F, '{n = 0; for (i = 1; i <= NF; i++) if ($i != "h3") printf "%s%s", (n++ ? "," : ""), $i}') - [ -n "$ALPN" ] && printf ',"alpn":%s' "$(json_list "$ALPN")" - [ -n "$FP" ] && printf ',"utls":{"enabled":true,"fingerprint":%s}' "$(json_str "$FP")" - [ "$SECURITY" = reality ] && printf ',"reality":{"enabled":true,"public_key":%s,"short_id":%s}' "$(json_str "$PBK")" "$(json_str "$SID")" - printf '}' ;; - esac - case "$TYPE" in - ws) printf ',"transport":{"type":"ws","path":%s' "$(json_str "${WSPATH:-/}")"; [ -n "$WSHOST" ] && printf ',"headers":{"Host":%s}' "$(json_str "$WSHOST")"; printf '}' ;; - grpc) printf ',"transport":{"type":"grpc","service_name":%s}' "$(json_str "$SVC")" ;; - httpupgrade) printf ',"transport":{"type":"httpupgrade","path":%s' "$(json_str "${WSPATH:-/}")"; [ -n "$WSHOST" ] && printf ',"host":%s' "$(json_str "$WSHOST")"; printf '}' ;; - tcp|raw) ;; - *) echo "transport type '$TYPE' is not supported by this helper" >&2; exit 1 ;; - esac - printf '}' -} - -gen_singbox() { - [ -n "$VLESS_URI" ] || { echo "VLESS_URI is not set in $CONF" >&2; exit 1; } - parse_uri - mkdir -p "$RUN"; chmod 700 "$RUN" - excl=$(json_list "$LAN_CIDRS") - { - printf '{"log":{"level":"warn","timestamp":false},\n' - printf '"dns":{"servers":[{"type":"tcp","tag":"remote","server":%s,"detour":"proxy"},' "$(json_str "$REMOTE_DNS")" - # the VPN server name is looked up via BOOTSTRAP_DNS (directly, or over TCP through UPSTREAM_HTTP_PROXY) - if [ -n "$UPSTREAM_HTTP_PROXY" ]; then - printf '{"type":"tcp","tag":"bootstrap","server":%s,"detour":"upstream"}],' "$(json_str "$BOOTSTRAP_DNS")" - else - printf '{"type":"udp","tag":"bootstrap","server":%s}],' "$(json_str "$BOOTSTRAP_DNS")" - fi - # IPv6 through the tunnel only when the server side has it: otherwise programs prefer the (dead) IPv6 route and - # every connection to a dual-stack host fails first, so DNS answers only A records and the TUN gets no IPv6 address - if [ "$IPV6" = 1 ]; then strategy=prefer_ipv4; addrs='"172.19.0.1/30","fdfe:dcba:9876::1/126"' - else strategy=ipv4_only; addrs='"172.19.0.1/30"'; fi - printf '"final":"remote","strategy":"%s"},\n' "$strategy" - # "stack":"gvisor", not the default system stack. On this device's 5.4 vendor kernel the system stack - # takes the connection off the tun and then drops it: sing-box logs one "router: pre-match => sniff" and - # nothing more, the client gets an RST ("Connection refused", or uclient-fetch's "Operation not permitted") - # and not a single packet reaches an outbound. DNS still worked, which is what made it look like a routing - # or firewall problem for so long. The warning it prints on startup is the same story from the other end: - # "inbound/tun[tun-in]: enable offload: set udp offload: TUNSETOFFLOAD: invalid argument" - the kernel does - # not have what that stack expects. gvisor carries its own TCP/IP and does not care. - printf '"inbounds":[{"type":"tun","tag":"tun-in","stack":"gvisor","interface_name":"%s","address":[%s],"mtu":1400,' "$TUN" "$addrs" - printf '"auto_route":true,"strict_route":true,"route_exclude_address":%s}],\n' "$excl" - printf '"outbounds":['; outbound_json - [ -n "$UPSTREAM_HTTP_PROXY" ] && printf ',{"type":"http","tag":"upstream","server":%s,"server_port":%s}' "$(json_str "${UPSTREAM_HTTP_PROXY%:*}")" "${UPSTREAM_HTTP_PROXY##*:}" - printf ',{"type":"direct","tag":"direct"}],\n' - printf '"route":{"rules":[{"action":"sniff"},{"protocol":"dns","action":"hijack-dns"},{"ip_is_private":true,"outbound":"direct"}],' - printf '"final":"proxy","auto_detect_interface":true,"default_mark":%d,"default_domain_resolver":"bootstrap"}}\n' "$MARK" - } > "$RUN/config.json" - chmod 600 "$RUN/config.json" - "$BIN" check -c "$RUN/config.json" -} - -# ---- xray engine ---------------------------------------------------------------------------------------------- -# Xray does VLESS and nothing else here; hev-socks5-tunnel owns the TUN and hands every TCP/UDP flow to Xray's -# SOCKS port on loopback. Neither installs routes, so this script does, with the same rule prefs and table as -# sing-box's auto_route - which is what lets routing_cleanup and the kill switch serve both engines. - -# first IPv4 address for a name, from the system resolver. Runs before any rule points into the tunnel, so the -# answer comes over the plain bearer. -resolve4() { - case "$1" in *[!0-9.]*) ;; *) printf '%s' "$1"; return 0 ;; esac - # glibc's getent on Ubuntu; OpenWrt has no getent but its busybox has nslookup (Ubuntu's image does not) - if command -v getent >/dev/null 2>&1; then - getent ahostsv4 "$1" 2>/dev/null | awk '{print $1; exit}' - else - nslookup "$1" 2>/dev/null | awk '/^Name:/ {n = 1} n && /^Address/ {sub(/^Address( [0-9]+)?: */, ""); if ($0 ~ /^[0-9.]+$/) {print; exit}}' - fi -} -listening() { { ss -ltn 2>/dev/null || netstat -ltn 2>/dev/null; } | grep -q "127.0.0.1:$1 "; } - -xray_stream_json() { - case "$TYPE" in tcp|raw) net=raw ;; ws|grpc|httpupgrade|xhttp) net=$TYPE ;; - *) echo "transport type '$TYPE' is not supported by this helper" >&2; exit 1 ;; esac - printf '"streamSettings":{"network":"%s"' "$net" - case "$TYPE" in - ws) printf ',"wsSettings":{"path":%s' "$(json_str "${WSPATH:-/}")"; [ -n "$WSHOST" ] && printf ',"host":%s' "$(json_str "$WSHOST")"; printf '}' ;; - grpc) printf ',"grpcSettings":{"serviceName":%s}' "$(json_str "$SVC")" ;; - httpupgrade) printf ',"httpupgradeSettings":{"path":%s' "$(json_str "${WSPATH:-/}")"; [ -n "$WSHOST" ] && printf ',"host":%s' "$(json_str "$WSHOST")"; printf '}' ;; - xhttp) printf ',"xhttpSettings":{"path":%s' "$(json_str "${WSPATH:-/}")"; [ -n "$WSHOST" ] && printf ',"host":%s' "$(json_str "$WSHOST")" - [ -n "$XMODE" ] && printf ',"mode":%s' "$(json_str "$XMODE")"; printf '}' ;; - esac - case "$SECURITY" in - tls) - printf ',"security":"tls","tlsSettings":{"serverName":%s' "$(json_str "${SNI:-$HOST}")" - # Xray 26 removed allowInsecure. Its replacement pins the one certificate the server presents, - # which is stricter: anything else is refused, including a correctly signed certificate for a - # different host. It also skips the expiry check, so an expired certificate keeps working until - # the server renews it - and then the pin has to change with it. - [ -n "$PIN" ] && printf ',"pinnedPeerCertSha256":%s' "$(json_str "$PIN")" - [ -n "$VCN" ] && printf ',"verifyPeerCertByName":%s' "$(json_str "$VCN")" - [ -n "$ALPN" ] && printf ',"alpn":%s' "$(json_list "$ALPN")" - [ -n "$FP" ] && printf ',"fingerprint":%s' "$(json_str "$FP")" - printf '}' ;; - reality) - printf ',"security":"reality","realitySettings":{"serverName":%s,"fingerprint":%s,"publicKey":%s,"shortId":%s' \ - "$(json_str "${SNI:-$HOST}")" "$(json_str "${FP:-chrome}")" "$(json_str "$PBK")" "$(json_str "$SID")" - [ -n "$SPX" ] && printf ',"spiderX":%s' "$(json_str "$SPX")" - printf '}' ;; - esac - printf ',"sockopt":{"mark":%d}}' "$((MARK))" -} - -# Xray 26 has no allowInsecure; pinnedPeerCertSha256 is its replacement. For a link that asks for allowInsecure the -# pin is managed here: fetched once when there is none, kept in vpn.conf, and fetched again only when Xray reports -# that the server's certificate no longer matches (a renewal). A pin that came from the link (pcs) or was written -# by hand without allowInsecure is left alone. -pin_managed() { [ "$SECURITY" = tls ] && case "$INSECURE" in 1|true) true ;; *) false ;; esac; } - -# SHA-256 of the leaf certificate the server presents, in the form Xray expects. Goes out directly: at start the -# tunnel's rules are not in place yet, and while it runs rule 9002 keeps the server's address off the tunnel. -fetch_pin() { - command -v openssl >/dev/null 2>&1 || { echo "fetching the server certificate needs openssl (OpenWrt: apk add openssl-util)" >&2; return 1; } - t=; command -v timeout >/dev/null 2>&1 && t="timeout 20" - h=$($t openssl s_client -connect "$SERVER_IP:$PORT" -servername "${SNI:-$HOST}" /dev/null | - openssl x509 -outform DER 2>/dev/null | sha256sum | cut -d' ' -f1) - # the hash of nothing is what an empty pipe produces when the handshake failed - case "$h" in ""|e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855) return 1 ;; esac - printf '%s' "$h" -} - -save_pin() { - if grep -q '^TLS_PIN_SHA256=' "$CONF"; then sed -i "s/^TLS_PIN_SHA256=.*/TLS_PIN_SHA256=$1/" "$CONF" - else printf '# fetched by mu300-vpn: the VPN server certificate, standing in for allowInsecure (Xray 26)\nTLS_PIN_SHA256=%s\n' "$1" >> "$CONF"; fi -} - -gen_xray() { - [ -n "$VLESS_URI" ] || { echo "VLESS_URI is not set in $CONF" >&2; exit 1; } - parse_uri - XMODE=$(param mode); SPX=$(urldecode "$(param spx)"); ENC=$(urldecode "$(param encryption)") - # pcs/vcn are the share-link spellings of pinnedPeerCertSha256/verifyPeerCertByName; TLS_PIN_SHA256 in - # vpn.conf is for links written before those existed - PIN=${TLS_PIN_SHA256:-$(urldecode "$(param pcs)")}; VCN=$(urldecode "$(param vcn)") - # the name is looked up now and Xray is given the address, so it never has to resolve anything itself - the - # resolver it would use sits behind the tunnel it is trying to build. The name stays as the SNI. - SERVER_IP=$(resolve4 "$HOST") - [ -n "$SERVER_IP" ] || { echo "cannot resolve the VPN server $HOST" >&2; exit 1; } - # allowInsecure with nothing pinned yet: take whatever certificate the server presents now and keep it - if pin_managed && [ -z "$PIN" ]; then - PIN=$(fetch_pin) || { echo "the link asks for allowInsecure, which Xray no longer has, and the server's" \ - "certificate could not be fetched to pin instead. Set TLS_PIN_SHA256 in $CONF, or ENGINE=sing-box." >&2; exit 1; } - save_pin "$PIN" - echo "pinned the server's current certificate ($PIN)" - fi - mkdir -p "$RUN"; chmod 700 "$RUN" - { - # info, not warning: a failed outbound - including a pin mismatch - is only reported at info. run_xray's - # reader scans every line and passes on only warnings and worse, so the system log does not fill up. - printf '{"log":{"loglevel":"info","access":"none"},\n' - printf '"inbounds":[{"tag":"socks-in","listen":"127.0.0.1","port":%d,"protocol":"socks","settings":{"auth":"noauth","udp":true,"ip":"127.0.0.1"}}],\n' "$SOCKS_PORT" - printf '"outbounds":[{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":%s,"port":%s,"users":[{"id":%s,"encryption":%s' \ - "$(json_str "$SERVER_IP")" "$PORT" "$(json_str "$UUID")" "$(json_str "${ENC:-none}")" - [ -n "$FLOW" ] && printf ',"flow":%s' "$(json_str "$FLOW")" - printf '}]}]},'; xray_stream_json; printf '},\n' - printf '{"tag":"direct","protocol":"freedom","streamSettings":{"sockopt":{"mark":%d}}}]}\n' "$((MARK))" - } > "$RUN/xray.json" - chmod 600 "$RUN/xray.json" - cat > "$RUN/hev.yml" < "$RUN/server-ip" - "$XRAY" run -test -c "$RUN/xray.json" >/dev/null || { "$XRAY" run -test -c "$RUN/xray.json" >&2; exit 1; } - echo "xray config OK ($RUN/xray.json), server $HOST -> $SERVER_IP" -} - -xray_routes_up() { - ip rule add pref 9000 fwmark "$MARK" lookup main - for c in $(printf '%s' "$LAN_CIDRS" | tr ',' ' '); do ip rule add pref 9001 to "$c" lookup main; done - ip rule add pref 9002 to "$(cat "$RUN/server-ip")" lookup main - ip route replace default dev "$TUN" table 2022 - ip rule add pref 9010 lookup 2022 - # the device's own lookups: dnsmasq forwards to whatever the bearer handed out, and the carrier's resolver - # does not answer from the far end of the tunnel. Send them to REMOTE_DNS instead, which the routing above - # then carries through the tunnel. Clients that use their own DNS are already going through it. - nft -f - </dev/null || true - for pref in 9000 9001 9002 9003 9010; do - while ip rule del pref "$pref" 2>/dev/null; do :; done - done - ip route flush table 2022 2>/dev/null || true -} - -# Two processes and the routing between them, torn down together: if either dies the service exits, the routes -# go with it and procd starts the whole thing again. Leaving rules behind with nothing at the other end is what -# made sing-box's crashes look like a dead modem (routing_cleanup), so every way out of here goes through down(). -run_xray() { - xray_routes_down - gen_xray - # Xray's output goes through a reader that passes it on and notes a pin mismatch, so a renewed server - # certificate is noticed without polling the server - rm -f "$RUN/pin-mismatch" "$RUN/xray.out"; mkfifo "$RUN/xray.out" - while IFS= read -r l; do - case "$l" in *"peer cert is unrecognized (against pinnedPeerCertSha256)"*) : > "$RUN/pin-mismatch" ;; esac - case "$l" in *"[Info]"*|*"[Debug]"*) ;; *) printf '%s\n' "$l" ;; esac - done < "$RUN/xray.out" & - "$XRAY" run -c "$RUN/xray.json" > "$RUN/xray.out" 2>&1 & xpid=$! - hpid= - down() { - trap - EXIT INT TERM - [ -n "$hpid" ] && kill "$hpid" 2>/dev/null - kill "$xpid" 2>/dev/null - wait 2>/dev/null - xray_routes_down - } - trap 'down; exit 0' INT TERM - trap down EXIT - n=0 - until listening "$SOCKS_PORT"; do - kill -0 "$xpid" 2>/dev/null || { echo "xray exited during start" >&2; exit 1; } - n=$((n + 1)); [ "$n" -lt 15 ] || { echo "xray did not open its SOCKS port" >&2; exit 1; } - sleep 1 - done - "$HEV" "$RUN/hev.yml" & hpid=$! - n=0 - until ip link show "$TUN" >/dev/null 2>&1; do - kill -0 "$hpid" 2>/dev/null || { echo "hev-socks5-tunnel exited during start" >&2; exit 1; } - n=$((n + 1)); [ "$n" -lt 15 ] || { echo "$TUN did not appear" >&2; exit 1; } - sleep 1 - done - ip link set "$TUN" up - xray_routes_up - echo "tunnel up on $TUN (xray $xpid, hev $hpid)" - # whichever exits first ends the service - while kill -0 "$xpid" 2>/dev/null && kill -0 "$hpid" 2>/dev/null; do - sleep 2 - [ -e "$RUN/pin-mismatch" ] && pin_managed || continue - rm -f "$RUN/pin-mismatch" - new=$(fetch_pin) || { sleep 30; continue; } - [ "$new" = "$PIN" ] && { sleep 30; continue; } - save_pin "$new" - echo "the server's certificate changed; pinned the new one and restarting" >&2 - exit 1 - done - echo "$( kill -0 "$xpid" 2>/dev/null && echo hev-socks5-tunnel || echo xray ) exited, tearing the tunnel down" >&2 - exit 1 -} - -gen() { case "$ENGINE" in xray) gen_xray ;; *) gen_singbox ;; esac; } - -killswitch_on() { - nft -f - </dev/null || true; } - -# The kill switch only stops traffic; nothing here lets any through, and on OpenWrt nothing else does either -# unless the tunnel is in a firewall zone. fw4's forward chain is policy drop and sends lan traffic to -# forward_lan, which accepts towards the wan zone's devices and towards lan - and $TUN is in neither, so a -# client's packet is policy-routed into the tunnel and then rejected with a TCP reset on the way out. -# -# None of that is visible from the device, whose own traffic takes the output hook instead and works: the VPN -# reports an exit IP and looks healthy while every client behind it gets nothing. -# -# Adding $TUN to the wan zone is what makes accept_to_wan cover it. Harmless while the VPN is off, because fw4 -# never matches a device that is not there, so this is done once and left in place. -ensure_firewall_zone() { - command -v uci >/dev/null 2>&1 || return 0 - zone=$(uci show firewall 2>/dev/null | sed -n "s/^firewall\.@zone\[\([0-9]*\)\]\.name='wan'$/\1/p" | head -1) - [ -n "$zone" ] || return 0 - uci -q get "firewall.@zone[$zone].device" 2>/dev/null | tr ' ' '\n' | grep -qx "$TUN" && return 0 - uci add_list "firewall.@zone[$zone].device=$TUN" 2>/dev/null || return 0 - uci commit firewall 2>/dev/null || return 0 - /etc/init.d/firewall reload >/dev/null 2>&1 - echo "added $TUN to the wan firewall zone, so clients can be forwarded into it" >&2 -} - -# sing-box installs the policy routing for its tun itself (auto_route: rule prefs 9000-9010 and table 2022) and -# removes it when it exits cleanly. It cannot when it is killed or crashes, and what it leaves behind is worse -# than no VPN at all: every packet the device sends is still directed into a tunnel with nothing at the other -# end, so the whole system reports "Operation not permitted" and looks like it has lost the modem. That cost an -# evening once - the data path was fine and every test was being answered by a routing rule. -# -# Only when nothing is running, so this never takes the rules away from a live tunnel. -routing_cleanup() { - pgrep -f '[s]ing-box run|[x]ray run|[h]ev-socks5-tunnel' >/dev/null 2>&1 && return 0 - ip link show "$TUN" >/dev/null 2>&1 && return 0 - n=0 - for pref in 9000 9001 9002 9003 9010; do - while ip rule del pref "$pref" 2>/dev/null; do n=$((n + 1)); done - done - ip route flush table 2022 2>/dev/null || true - nft delete table ip mu300_vpn_dns 2>/dev/null || true - [ "$n" -gt 0 ] && echo "removed $n stale routing rule(s) left by a VPN engine" - return 0 -} - -# tests/ source this file for its functions only -[ -z "${MU300_LIB:-}" ] || return 0 - -case "${1:-status}" in - gen) gen ;; - run) - [ "$ENABLE" = 1 ] || { echo "VPN disabled (ENABLE=0 in $CONF)"; killswitch_off; exit 0; } - [ "$ENGINE" = xray ] || gen >/dev/null - ensure_firewall_zone - if [ "$ENGINE" = xray ] && [ "$KILL_SWITCH" = 1 ]; then - # see ENGINE above: with the kill switch on, this engine could never come up, and the device would be - # left with no connection at all - echo "the kill switch is not supported with ENGINE=xray yet: running without it (ENGINE=sing-box has it)" >&2 - killswitch_off - elif [ "$KILL_SWITCH" = 1 ]; then killswitch_on; else killswitch_off; fi - [ "$ENGINE" = xray ] && run_xray - exec "$BIN" run -c "$RUN/config.json" ;; - off) killswitch_off; echo "kill switch removed"; routing_cleanup ;; - status) - echo "engine: $ENGINE enabled: $ENABLE kill switch: $KILL_SWITCH ($(nft list table inet mu300_vpn >/dev/null 2>&1 && echo active || echo inactive))" - ip -br addr show "$TUN" 2>/dev/null || echo "$TUN: down" - if ip link show "$TUN" >/dev/null 2>&1; then - printf 'exit IP: '; (wget -qO- -T 8 http://api.ipify.org 2>/dev/null || curl -s -m 8 http://api.ipify.org 2>/dev/null || echo unreachable); echo - fi ;; - *) echo "usage: $0 gen|run|off|status" >&2; exit 2 ;; -esac diff --git a/rootfs/overlay/opt/mu300/bin/rootfs-fixups b/rootfs/overlay/opt/mu300/bin/rootfs-fixups index 90e157b7..4be9cd1a 100755 --- a/rootfs/overlay/opt/mu300/bin/rootfs-fixups +++ b/rootfs/overlay/opt/mu300/bin/rootfs-fixups @@ -9,7 +9,7 @@ done # /opt/mu300/bin is on nobody's PATH, and sudo's secure_path cannot see it at all, so the commands the # documentation tells people to run need links from a directory that is. Systems installed before these links # existed get them here instead of only after an update. -for c in mu300-toolkit mu300-next-boot mu300-os mu300-update mobile-data mu300-at mu300-vpn wifi-client mu300-ttl; do +for c in mu300-toolkit mu300-next-boot mu300-os mu300-update mobile-data mu300-at wifi-client mu300-ttl; do [ -x "/opt/mu300/bin/$c" ] || continue [ -e "/usr/local/bin/$c" ] || ln -sfn "/opt/mu300/bin/$c" "/usr/local/bin/$c" 2>/dev/null || true done diff --git a/rootfs/overlay/opt/mu300/lib/storage.sh b/rootfs/overlay/opt/mu300/lib/storage.sh new file mode 100644 index 00000000..c3adc97f --- /dev/null +++ b/rootfs/overlay/opt/mu300/lib/storage.sh @@ -0,0 +1,99 @@ +# Shared eMMC/UFS topology. Geometry in sysfs and public callers is always +# 512-byte sectors; only GPT encoders use the device's logical block size. +# No disk selection by enumeration order and no removable/USB disk fallback. +mu300_storage_parent() { + local node=${1##*/} path + [ -f "${MU300_STORAGE_SYS:-/sys/class/block}/$node/partition" ] || return 1 + path=$(readlink -f "${MU300_STORAGE_SYS:-/sys/class/block}/$node") || return 1 + path=${path%/*} + case ${path##*/} in mmcblk[0-9]*|sd[a-z]*) printf '%s\n' "${path##*/}" ;; *) return 1 ;; esac +} + +mu300_storage_controller() { + local path + path=$(readlink -f "${MU300_STORAGE_SYS:-/sys/class/block}/${1##*/}/device") || return 1 + while [ "$path" != / ] && [ -n "$path" ]; do + case ${path##*/} in *.ufs) printf '%s\n' "$path"; return 0 ;; esac + path=${path%/*} + done + return 1 +} + +mu300_storage_kind() { + local disk=${1##*/} + case "$disk" in + mmcblk[0-9]*) [ "$(cat "${MU300_STORAGE_SYS:-/sys/class/block}/$disk/device/type" 2>/dev/null)" = MMC ] && echo emmc ;; + sd[a-z]*) mu300_storage_controller "$disk" >/dev/null && echo ufs ;; + *) return 1 ;; + esac +} + +mu300_storage_identity() { + local disk=${1##*/} kind value controller manufacturer lun + kind=$(mu300_storage_kind "$disk") || return 1 + case "$kind" in + emmc) + value=$(cat "${MU300_STORAGE_SYS:-/sys/class/block}/$disk/device/cid") || return 1 + [ "${#value}" = 32 ] || return 1 + case "$value" in *[!0-9a-f]*) return 1 ;; esac + printf '%s\n' "$value" ;; + ufs) + controller=$(mu300_storage_controller "$disk") || return 1 + value=$(cat "$controller/string_descriptors/serial_number") || return 1 + manufacturer=$(cat "$controller/string_descriptors/manufacturer_name") || return 1 + [ -n "$value" ] && [ -n "$manufacturer" ] || return 1 + lun=$(readlink -f "${MU300_STORAGE_SYS:-/sys/class/block}/$disk/device") || return 1 + lun=${lun##*:} + case "$lun" in ''|*[!0-9]*) return 1 ;; esac + # Keep legacy transaction field width, but domain-separate UFS IDs. + # Never use the generic SAMSUNG WWID as a unique device identity. + printf 'ufs:%s:%s:%s' "$manufacturer" "$value" "$lun" | sha256sum | cut -c1-32 ;; + *) return 1 ;; + esac +} + +mu300_storage_partnode() { + case "$2" in ''|0*|*[!0-9]*) return 1 ;; esac + case "$1:$2" in + mmcblk[0-9]*:[1-9]*) printf '%sp%s\n' "$1" "$2" ;; + sd[a-z]*:[1-9]*) printf '%s%s\n' "$1" "$2" ;; + *) return 1 ;; + esac +} + +mu300_storage_part() { + local label=$1 disk=${2:-} u node name key value parent found= + for u in "${MU300_STORAGE_SYS:-/sys/class/block}"/*/uevent; do + [ -r "$u" ] || continue + node=${u%/uevent}; node=${node##*/} + if [ -n "$disk" ]; then + case "$node" in "${disk}"p[0-9]*|"${disk}"[0-9]*) ;; *) continue ;; esac + fi + name= + while IFS='=' read -r key value; do [ "$key" != PARTNAME ] || name=$value; done < "$u" + [ "$name" = "$label" ] || continue + parent=$(mu300_storage_parent "$node") || continue + if [ -n "$disk" ]; then + [ "$parent" = "$disk" ] || continue + else + mu300_storage_kind "$parent" >/dev/null || continue + fi + [ -z "$found" ] || return 1 + found=$node + done + [ -n "$found" ] && printf '%s\n' "$found" +} + +mu300_storage_disk() { + local node disk + node=$(mu300_storage_part userdata) || return 1 + disk=$(mu300_storage_parent "$node") || return 1 + mu300_storage_kind "$disk" >/dev/null || return 1 + printf '%s\n' "$disk" +} + +mu300_storage_sector_size() { + local value + value=$(cat "${MU300_STORAGE_SYS:-/sys/class/block}/${1##*/}/queue/logical_block_size") || return 1 + case "$value" in 512|4096) printf '%s\n' "$value" ;; *) return 1 ;; esac +} diff --git a/tests/dashboard_cache_browser.py b/tests/dashboard_cache_browser.py index 80932b4d..26717932 100644 --- a/tests/dashboard_cache_browser.py +++ b/tests/dashboard_cache_browser.py @@ -64,7 +64,8 @@ with sync_playwright() as pw: check(app.lastCell.error==='new failure','older good signal must not erase newer failure'); check(document.querySelector('#mud-rat').firstChild.nodeValue==='无应答','newer failure must remain visible'); - const full=freeze({...signal,ts:200,ident:{imei:'fixture-zero',model:'fixture'}, + const full=freeze({...signal,ts:200,ident:{imei:'fixture-zero',model:'fixture',fw:'fixture-fw', + imsi:'fixture-imsi',iccid:'fixture-iccid',msisdn:'fixture-number'}, operator:{name:'fixture carrier',act:7},qos:{qci:9},neigh:[{pci:456}], sig_src:'nr',sig:{rsrp:-80},lte:null,nr:{band:41,pci:321,arfcn:500000}}); show({cell:full,sig:null}); @@ -86,6 +87,30 @@ with sync_playwright() as pw: show({cell:freeze({ts:204,error:'both failed'}),sig:freeze({ts:205,error:'both failed'})}); check(document.querySelector('#mud-rat').firstChild.nodeValue==='无应答','continued failure must not reuse last successful signal'); + + const simInfo=state=>({modem:{alive:1,atd:1,sims:[{slot:0,state},{slot:1,state:'ready'}]}}); + const off=freeze({...signal,ts:220,cfun:0,lte:null,nr:null}); + show({info:simInfo('absent'),cell:{...full,ts:220,cfun:0},sig:null}); + check(document.querySelector('#mud-rat').firstChild.nodeValue==='未插卡','confirmed absence must override RF-off and stale RAT'); + check(text('reg')==='未插卡' && text('rsrp')==='--','absence must clear stale network and signal'); + check(text('imei')==='fixture-zero' && text('fwmodel')==='fixture' && text('fw')==='fixture-fw','equipment identity must remain available without a SIM'); + check(text('imsi')==='--' && text('iccid')==='--' && text('msisdn')==='--','removed SIM identifiers must not remain visible'); + check(!app.lastCell.ident.imsi && !app.lastCell.ident.iccid && !app.lastCell.ident.msisdn,'reveal must not restore identifiers from a removed SIM'); + check(full.ident.imsi==='fixture-imsi','absence filtering must not mutate the source cache'); + show({info:simInfo('unknown'),cell:off,sig:null}); + check(document.querySelector('#mud-rat').firstChild.nodeValue==='无线电已关','unknown SIM must not be guessed absent'); + show({info:simInfo('ready'),cell:off,sig:null}); + check(document.querySelector('#mud-rat').firstChild.nodeValue==='无线电已关','inserted SIM with RF off keeps its real status'); + show({info:simInfo('absent'),cell:{...off,card:1},sig:null}); + check(document.querySelector('#mud-rat').firstChild.nodeValue==='无线电已关','other SIM absence must not cross slots'); + show({info:simInfo('absent'),cell:{ts:221,card:0,error:'AT unavailable'},sig:null}); + check(document.querySelector('#mud-rat').firstChild.nodeValue==='未插卡','known absence must not become an engineering read error'); + show({info:simInfo('ready'),cell:{...full,ts:222},sig:null}); + check(document.querySelector('#mud-rat').firstChild.nodeValue==='5G SA','fresh insertion/registration must restore RAT'); + app._slowCell=null; app.lastCell=null; app.lastFullTs=null; + show({info:simInfo('absent'),cell:{...full,ts:223,cfun:0,ident:{imei:'cold-imei',model:'cold-model',fw:'cold-fw'}},sig:null}); + check(text('imei')==='cold-imei' && text('fw')==='cold-fw','a fresh no-SIM page must render newly read equipment identity'); + check(document.querySelector('#mud-rat').firstChild.nodeValue==='未插卡','equipment identity must not fabricate registration'); return {recovery:true,partial_recovery:true,older_signal_rejected:true, same_sim_details_preserved:true,sim_isolation:true,real_failures_visible:true,input_immutable:true}; }''') diff --git a/tests/forward_profiles_fixture.sh b/tests/forward_profiles_fixture.sh index e6d3f2ed..71748767 100644 --- a/tests/forward_profiles_fixture.sh +++ b/tests/forward_profiles_fixture.sh @@ -3,6 +3,7 @@ set -e source=$1 base=$(mktemp -d /tmp/mu300-forward-profiles.XXXXXX) +trap 'rm -rf "$base"' EXIT export MU300_FORWARD_DIR=$base/config MU300_SMS_POOL=$base/pool MU300_FORWARD_RESULT=$base/result export MU300_FORWARD_BATTERY=$base/battery MU300_SMS_BIN=/bin/false export MU300_FORWARD_RUNTIME=$base @@ -125,7 +126,9 @@ curl() { msmtp() { cat > "$base/smtp.body"; } # Minimal base images may omit openssl; exercise argument/encoding plumbing # there. On the device the installed openssl performs the actual HMAC/MIME. +real_openssl=1 if ! command -v openssl >/dev/null 2>&1; then + real_openssl=0 openssl() { case "$1" in dgst) cat ;; base64) cat >/dev/null; printf 'VEVTVCs/=' ;; *) return 1 ;; esac; } fi load_config @@ -153,13 +156,41 @@ TEST_HTTP_CODE=200 webhook_method=POST webhook_body= deliver sms 10010 legacy now [ "$(jsonfilter -i "$base/curl.body" -e '@.text')" = legacy ] [ "$(jsonfilter -i "$base/curl.body" -e '@.date')" = now ] +# Literal newlines must be JSON-escaped, not split into records or stripped. +TEST_MULTILINE=$(printf '\nfirst\r\n中文\n\nlast\n\n.') +TEST_MULTILINE=${TEST_MULTILINE%.} +export TEST_MULTILINE +deliver sms 10010 "$TEST_MULTILINE" now +ucode -e 'import {readfile} from "fs"; if (json(readfile(ARGV[0])).text != getenv("TEST_MULTILINE")) exit(1);' "$base/curl.body" +webhook_body='{"text":"{text}","sim":"{sim}"}' +deliver sms 10010 "$TEST_MULTILINE" now +ucode -e 'import {readfile} from "fs"; if (json(readfile(ARGV[0])).text != getenv("TEST_MULTILINE")) exit(1);' "$base/curl.body" +webhook_content_type=text/plain webhook_body='{text}' +deliver sms 10010 "$TEST_MULTILINE" now +ucode -e 'import {readfile} from "fs"; if (readfile(ARGV[0]) != getenv("TEST_MULTILINE")) exit(1);' "$base/curl.body" +webhook_content_type=application/json webhook_body= method=dingtalk dingtalk_webhook='https://oapi.dingtalk.com/robot/send?access_token=TEST_ONLY' dingtalk_secret=TEST_SIGN_KEY -deliver sms 10010 body now +deliver sms 10010 "$TEST_MULTILINE" now grep -q 'timestamp=.*sign=' "$base/curl.args" [ "$(jsonfilter -i "$base/curl.body" -e '@.msgtype')" = text ] +ucode -e 'import {readfile} from "fs"; let text=json(readfile(ARGV[0])).text.content; if (substr(text,-length(getenv("TEST_MULTILINE"))) != getenv("TEST_MULTILINE")) exit(1);' "$base/curl.body" method=smtp smtp_host=smtp.example.com smtp_port=465 smtp_username=from@example.com smtp_to=to@example.com smtp_password=TEST_ONLY -deliver sms 10010 body now +deliver sms 10010 "$TEST_MULTILINE" now grep -q 'Subject: =?UTF-8?B?' "$base/smtp.body" +if [ "$real_openssl" = 1 ]; then + ucode -e 'import {readfile} from "fs"; let msg=readfile(ARGV[0]), body=b64dec(replace(split(msg,"\r\n\r\n")[1],/[\r\n]/g,"")); if (substr(body,-length(getenv("TEST_MULTILINE"))) != getenv("TEST_MULTILINE")) exit(1);' "$base/smtp.body" +fi +# Exercise the SMS forwarding branch too, replacing only the final sender. +cat > "$base/sms-capture" <<'EOF_SMS_CAPTURE' +#!/bin/sh +[ "$1" = send ] || exit 1 +printf '%s' "$3" > "$MU300_FORWARD_RUNTIME/sms.body" +EOF_SMS_CAPTURE +chmod 700 "$base/sms-capture" +method=sms SMS=$base/sms-capture sms_to_phone=10086 sms_forward_device_info=0 +deliver sms 10010 "$TEST_MULTILINE" now +[ "$DELIVER_RESULT" = sent ] +ucode -e 'import {readfile} from "fs"; let body=readfile(ARGV[0]); if (substr(body,-length(getenv("TEST_MULTILINE"))) != getenv("TEST_MULTILINE")) exit(1);' "$base/sms.body" echo 'PASS isolated real delivery: POST/GET/headers/timeout/HTTP errors/legacy JSON/DingTalk signing/SMTP' # Saving a disabled profile before its inbox exists cannot create a zero/zero # cursor that would subsequently turn a SIM history import into live mail. diff --git a/tests/test_at_client_boundary.py b/tests/test_at_client_boundary.py index 5a6b200a..9cde30ed 100644 --- a/tests/test_at_client_boundary.py +++ b/tests/test_at_client_boundary.py @@ -109,6 +109,12 @@ class ATClientBoundary(unittest.TestCase): self.assertNotEqual(result.returncode, 0) self.assertLess(time.monotonic() - started, 3.5) self.assertFalse((self.root / 'lock').exists()) + self.assertIn(b'no answer from the daemon', result.stderr) + + def test_incomplete_daemon_answer_has_a_diagnostic(self): + result = self.exchange('AT', b'') + self.assertNotEqual(result.returncode, 0) + self.assertIn(b'modem returned no final response', result.stderr) def test_zero_lock_wait_never_steals_a_live_owner(self): lock = self.root / 'lock'; lock.mkdir() diff --git a/tests/test_boot_partition_wait.py b/tests/test_boot_partition_wait.py index 7c711020..422a383b 100644 --- a/tests/test_boot_partition_wait.py +++ b/tests/test_boot_partition_wait.py @@ -8,7 +8,7 @@ class PartitionWait(ShellTest): source=(TOP/'boot/init').read_text() loop=source.split('find_partitions() {',1)[1].split(' detect_linux_slot',1)[0] # Isolate the real readiness loop before slot detection and writes. - self.loop='poll() {'+loop.replace('/sys/class/block',str(self.tmp/'block')).replace('/dev/',str(self.tmp/'dev')+'/').replace('-b "$misc"','-f "$misc"')+'\n}\npoll\n' + self.loop='mu300_storage_disk() { echo mmcblk0; }\nmu300_storage_part() { echo mmcblk0p1; }\npoll() {'+loop.replace('/sys/class/block',str(self.tmp/'block')).replace('/dev/',str(self.tmp/'dev')+'/').replace('-b "$misc"','-f "$misc"')+'\n}\npoll\n' block=self.tmp/'block/mmcblk0p1';block.mkdir(parents=True) (block/'uevent').write_text('PARTNAME=misc\n') (self.tmp/'dev').mkdir() diff --git a/tests/test_build_release.py b/tests/test_build_release.py index 7ad661dc..8664c606 100644 --- a/tests/test_build_release.py +++ b/tests/test_build_release.py @@ -100,6 +100,36 @@ class Ownership(unittest.TestCase): class Archives(unittest.TestCase): + def test_entry_repair_keeps_firmware_and_native_files_identical(self): + spec=importlib.util.spec_from_file_location('entry_repack',TOP/'tools/repack-with-diff.py') + module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + with tempfile.TemporaryDirectory() as folder: + root=Path(folder);studio=root/'studio';(studio/'docs').mkdir(parents=True) + files={'payload/boot-linux.img':b'boot','payload/mu300-openwrt.tar.gz':b'rootfs', + 'OpenWrt-Installer.py':b'old entry','desktop/installer.py':b'old entry', + 'tools/backend/openwrt-backend.exe':b'native runtime','START-HERE.md':b'guide', + 'docs/DIFF-STUDIO.md':b'diff guide'} + tool={'files':{'tools/backend/openwrt-backend.exe':hashlib.sha256(b'native runtime').hexdigest()}} + files['diff-tool.json']=json.dumps(tool).encode() + (studio/'diff-tool.json').write_bytes(files['diff-tool.json']) + (studio/'docs/DIFF-STUDIO.md').write_bytes(b'diff guide') + manifest={'magisk_layout':{'boot-linux.img':'payload/boot-linux.img','mu300-openwrt.tar.gz':'payload/mu300-openwrt.tar.gz'}, + 'magisk':{k:hashlib.sha256(v).hexdigest() for k,v in files.items() if k.startswith('payload/')}, + 'desktop':{k:hashlib.sha256(v).hexdigest() for k,v in files.items() if not k.startswith('payload/')}, + 'source':{'installer.py':'old'}} + source=root/'old.zip';target=root/'fixed.zip' + with zipfile.ZipFile(source,'w') as z: + for k,v in files.items():z.writestr(k,v) + z.writestr('desktop/manifest.json',json.dumps(manifest)) + module.repack(source,target,studio,dict(source_commit='abc',source_fingerprint='def'),repair_installer=True) + with zipfile.ZipFile(target) as z: + revised=json.loads(z.read('desktop/manifest.json')) + for k,v in files.items(): + self.assertEqual(z.read(k),(TOP/'desktop/installer.py').read_bytes() if k in ('OpenWrt-Installer.py','desktop/installer.py') else v) + for k,h in {**revised['magisk'],**revised['desktop']}.items(): + self.assertEqual(hashlib.sha256(z.read(k)).hexdigest(),h) + self.assertEqual(json.loads(z.read('desktop/TOOLS-REVISION.json'))['kind'],'installer-entry-repair') + def fixture(self, path, *, corrupt=False, extra=None): files = {'payload/boot-linux.img': b'boot', 'payload/mu300-openwrt.tar.gz': b'root', 'OpenWrt-Installer.py': b'cli'} runtime={'OpenWrt-Diff-Studio.exe':b'diff GUI','OpenWrt-Diff-Studio.py':b'diff CLI', diff --git a/tests/test_dashboard_info.py b/tests/test_dashboard_info.py index 09749bd8..2b9f5a8b 100644 --- a/tests/test_dashboard_info.py +++ b/tests/test_dashboard_info.py @@ -1,5 +1,6 @@ """Native snapshot regressions retain the original dashboard wire contract.""" import json +import os import tempfile import unittest from pathlib import Path @@ -10,6 +11,34 @@ class DashboardInfo(unittest.TestCase): self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup) self.root=Path(self.tmp.name);self.snap=Snapshot(self.root) + def test_sim_presence_uses_only_the_scoped_powered_owner_cache(self): + s=self.snap + self.assertEqual(s.run('sim_state','0'),'unknown') + s.write('run/mu300-registration/sim0.json','{"slot":0,"state":"absent"}') + self.assertEqual(s.run('sim_state','0'),'unknown') + s.write('run/mu300-registration/sim-power0','') + self.assertEqual(s.run('sim_state','0'),'absent') + self.assertEqual(s.run('sim_state','1'),'unknown') + for value in ('{"slot":1,"state":"absent"}','{"slot":0,"state":"invalid"}','broken json','null'): + s.write('run/mu300-registration/sim0.json',value) + self.assertEqual(s.run('sim_state','0'),'unknown') + for value in ('ready','locked'): + s.write('run/mu300-registration/sim0.json',json.dumps(dict(slot=0,state=value))) + self.assertEqual(s.run('sim_state','0'),value) + self.assertEqual(s.run('sim_state','invalid'),'unknown') + + def test_info_reports_the_requested_slot_and_clears_on_owner_loss(self): + s=self.snap + s.write('run/mu300-at/owner/pid','123') + s.write('proc/123/cmdline','owner') + fifo=s.root/'run/mu300-at/cmd';os.mkfifo(fifo) + s.write('run/mu300-registration/sim-power0','') + s.write('run/mu300-registration/sim0.json','{"slot":0,"state":"absent"}') + self.assertEqual(s.run(slot='0')['modem']['sims'][0],dict(slot=0,state='absent')) + self.assertEqual(s.run(slot='1')['modem']['sims'][1],dict(slot=1,state='unknown')) + (s.root/'run/mu300-at/owner/pid').unlink() + self.assertEqual(s.run(slot='0')['modem']['sims'][0],dict(slot=0,state='unknown')) + def test_dns_reuses_both_status_snapshots(self): data=self.snap.run() self.assertEqual(data['wan']['dns'],'1.1.1.1, 2001:4860:4860::8888') diff --git a/tests/test_desktop_free_loop.py b/tests/test_desktop_free_loop.py index ccbd7367..63d29f64 100644 --- a/tests/test_desktop_free_loop.py +++ b/tests/test_desktop_free_loop.py @@ -53,12 +53,14 @@ class RealLoop(unittest.TestCase): for tool in ('e2fsck','resize2fs'):(repair/'usr/sbin'/tool).symlink_to(shutil.which(tool)) shutil.copyfile(TOP/'desktop/android-loop.sh',payload/'android-loop.sh') shutil.copyfile(TOP/'desktop/boot/ext4-geometry.sh',payload/'ext4-geometry.sh') + # This fixture substitutes identity only; production uses real sysfs. + (payload/'storage-lib.sh').write_text('mu300_storage_identity() { echo '+('a'*32)+'; }\n') 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('/dev/block/mmcblk[0-9]*|/dev/block/sd[a-z]*',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'") diff --git a/tests/test_desktop_installer.py b/tests/test_desktop_installer.py index 9a041611..6aac848a 100644 --- a/tests/test_desktop_installer.py +++ b/tests/test_desktop_installer.py @@ -59,6 +59,33 @@ def cpio_files(stream): return found class Desktop(unittest.TestCase): + def test_external_entries_resolve_dependencies_under_a_frozen_host(self): + with tempfile.TemporaryDirectory(prefix='installer package ') as temp: + root=Path(temp)/'desktop';root.mkdir();support=root/'desktop';support.mkdir() + (root/'tools/backend').mkdir(parents=True) + for name in ('gpt.py','storage.py'): + (support/name).write_bytes((TOP/'installer/backend'/name).read_bytes()) + (support/'storage-lib.sh').write_bytes((TOP/'rootfs/overlay/opt/mu300/lib/storage.sh').read_bytes()) + for entry in (root/'OpenWrt-Installer.py',support/'installer.py'): + entry.write_bytes((TOP/'desktop/installer.py').read_bytes()) + script='''import importlib.util,sys +from pathlib import Path +sys.frozen=True +sys.executable=sys.argv[2] +spec=importlib.util.spec_from_file_location('external_entry',sys.argv[1]) +m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) +assert Path(m._gpt.__file__).resolve()==Path(sys.argv[3]).resolve() +assert m._storage.part_node('sda',75)=='sda75' +if Path(sys.argv[1]).name=='OpenWrt-Installer.py': + assert m.package_root()==Path(sys.argv[1]).parent +print('external entry loaded') +''' + result=subprocess.run([sys.executable,'-c',script,str(entry), + str(root/'tools/backend/openwrt-backend.exe'),str(support/'gpt.py')], + cwd=temp,capture_output=True,text=True,timeout=15) + self.assertEqual(result.returncode,0,result.stderr) + self.assertIn('external entry loaded',result.stdout) + @unittest.skipUnless(importlib.util.find_spec('paramiko'), 'SSH tests need Paramiko') def test_update_ignores_old_host_key_cache_and_never_saves_keys(self): import paramiko @@ -424,6 +451,7 @@ desktop_free_loop def test_boot_append_leaves_kernel_original_frame_and_log_tail_intact(self): with tempfile.TemporaryDirectory() as t: assets=Path(t);(assets/'repair').mkdir() + (assets/'storage-lib.sh').write_bytes((TOP/'rootfs/overlay/opt/mu300/lib/storage.sh').read_bytes()) for n in ('storage.sh','install-part.sh','part-prepare.sh','part-progress.sh','ext4-geometry.sh','mu300-gpt'): (assets/n).write_bytes((TOP/'desktop/boot'/n).read_bytes()) for n,source in (('original-init',TOP/'boot/init'),('build-boot-image.py',TOP/'boot/build-boot-image.py')):(assets/n).write_bytes(source.read_bytes()) diff --git a/tests/test_mu300_i18n.py b/tests/test_mu300_i18n.py index 04f9e3b8..9125ec4e 100644 --- a/tests/test_mu300_i18n.py +++ b/tests/test_mu300_i18n.py @@ -69,6 +69,15 @@ const M = new Function('rpc', 'baseclass', 'L', 'document', 'navigator', 'getCom result = subprocess.run(['node', '-', str(COMMON)], input=harness, capture_output=True, text=True, encoding='utf-8') self.assertEqual(result.returncode, 0, result.stderr) + def test_sim_presence_translations(self): + self.run_js(""" +for (const [locale, expected] of [['en','No SIM card'],['tr','SIM kart takılı değil']]) { + lang=locale; + if (M.translate('未插卡')!==expected) throw Error('SIM translation: '+locale); + if (M.translate('无线电已关')==='无线电已关') throw Error('RF translation: '+locale); +} +""") + def test_battery_current_preserves_real_sign_zero_and_unavailable_values(self): self.run_js(""" for (const [raw, expected] of [[260000,'+260mA'],[-570000,'-570mA'],[0,'0mA'], diff --git a/tests/test_no_vpn_payload.py b/tests/test_no_vpn_payload.py index 4a7ba90b..3580edd1 100644 --- a/tests/test_no_vpn_payload.py +++ b/tests/test_no_vpn_payload.py @@ -1,6 +1,7 @@ """A default image must not inherit optional VPN engines or stale menu entries.""" import hashlib import io +import json from pathlib import Path import runpy import subprocess @@ -49,3 +50,22 @@ class NoVpn(unittest.TestCase): self.assertNotIn('$(opt '+name+' ',text) self.assertNotIn('cp /in/'+name,text) self.assertIn('python3 "$TOP/openwrt/no-vpn-payload.py"',text) + + def test_streaming_cleanup_preserves_upstream_theme_and_removes_empty_menu(self): + with tempfile.TemporaryDirectory() as directory: + p=Path(directory)/'rootfs.tar.gz' + theme='www/luci-static/aurora/patches/admin-services-openclash-config.css' + menu='usr/share/luci/menu.d/luci-base.json' + self.archive(p,{theme:b'upstream theme bytes',menu:b'{"admin/vpn":{"title":"VPN"},"admin/network":{"title":"Network"}}'}) + policy['strip'](p) + with tarfile.open(p) as tar: + self.assertEqual(tar.extractfile(theme).read(),b'upstream theme bytes') + self.assertEqual(json.loads(tar.extractfile(menu).read()),{'admin/network':{'title':'Network'}}) + + def test_project_actions_and_default_toolkit_do_not_offer_removed_service(self): + app=ROOT/'openwrt/luci-app-mu300/root' + for name in ('usr/libexec/unisoc-modem/action','usr/libexec/rpcd/mu300dash','usr/share/ucode/mu300/dash.uc'): + text=(app/name).read_text() + self.assertNotIn('mu300-vpn',text) + self.assertNotIn('vpn:',text) + self.assertFalse((ROOT/'openwrt/overlay/etc/init.d/mu300-vpn').exists()) diff --git a/tests/test_release_ui_policy.py b/tests/test_release_ui_policy.py new file mode 100644 index 00000000..37099e68 --- /dev/null +++ b/tests/test_release_ui_policy.py @@ -0,0 +1,77 @@ +"""Exercise resource pruning, package records and user-installed menu ownership.""" +import base64 +import hashlib +import json +from pathlib import Path +import runpy +import tempfile +import unittest + +TOP = Path(__file__).resolve().parents[1] +policy = runpy.run_path(str(TOP/'tools/release-ui-policy.py')) +ASSET = 'www/luci-static/aurora/patches/admin-services-openclash-config.css' +CSS = 'www/luci-static/aurora/main.css' +MENU = 'usr/share/luci/menu.d/luci-base.json' +LIST = 'lib/apk/packages/luci-theme-aurora.list' +DB = 'lib/apk/db/installed' + + +class Resources(unittest.TestCase): + def root(self): + tmp = tempfile.TemporaryDirectory(); self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + values = {ASSET:b'old integration', CSS:b'.card{color:red}:is(.nav)[data-section=vpn]{--icon:shield}.other{color:blue}', + MENU:json.dumps({'admin/vpn':{'title':'VPN'},'admin/network':{'title':'Network'}}).encode(), + LIST:('/'+ASSET+'\n/'+CSS+'\n').encode(), + DB:('P:luci-theme-aurora\nF:www/luci-static/aurora/patches\nR:'+Path(ASSET).name+'\nZ:Q1old\n' + 'F:www/luci-static/aurora\nR:main.css\nZ:Q1old\n\nP:luci-base\nF:usr/share/luci/menu.d\nR:luci-base.json\nZ:Q1old\n\n').encode()} + for name,data in values.items(): + p=root/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(data) + return root + + def test_empty_menu_removed_but_upstream_theme_unchanged(self): + root=self.root();keep=root/'www/luci-static/aurora/patches/admin-network-wireless.css' + keep.write_text('.wifi{display:flex}') + policy['cleanup'](root) + self.assertEqual((root/ASSET).read_bytes(),b'old integration') + self.assertEqual(keep.read_text(),'.wifi{display:flex}') + self.assertEqual((root/CSS).read_text(),'.card{color:red}:is(.nav)[data-section=vpn]{--icon:shield}.other{color:blue}') + self.assertEqual(json.loads((root/MENU).read_text()),{'admin/network':{'title':'Network'}}) + self.assertIn('openclash',(root/LIST).read_text()) + db=(root/DB).read_text();self.assertIn('openclash',db) + for name in (MENU,): + self.assertIn('Z:Q1'+base64.b64encode(hashlib.sha1((root/name).read_bytes()).digest()).decode(),db) + snapshot={p.relative_to(root):p.read_bytes() for p in root.rglob('*') if p.is_file()} + self.assertEqual(policy['cleanup'](root),([],[])) + self.assertEqual(snapshot,{p.relative_to(root):p.read_bytes() for p in root.rglob('*') if p.is_file()}) + + def test_custom_child_menu_retains_its_parent_and_user_configuration(self): + root=self.root();custom=root/'usr/share/luci/menu.d/custom.json' + custom.write_text('{"admin/vpn/custom":{"title":"User service"}}') + config=root/'etc/config/user-service';config.parent.mkdir(parents=True);config.write_text('credentials-stay') + policy['cleanup'](root) + self.assertIn('admin/vpn',json.loads((root/MENU).read_text())) + self.assertEqual(config.read_text(),'credentials-stay') + + def test_invalid_menu_fails_before_removing_any_resource(self): + root=self.root();(root/MENU).write_text('invalid json') + with self.assertRaises(ValueError):policy['cleanup'](root) + self.assertTrue((root/ASSET).is_file()) + + def test_non_menu_files_are_never_rewritten(self): + files={CSS:b'[data-section=vpn]{color:red}',ASSET:b'original theme', + 'etc/config/openclash':b'user data'} + self.assertEqual(policy['plan'](files),(set(),{})) + + @unittest.skipUnless(hasattr(Path,'symlink_to'), 'Requires filesystem symlink support') + def test_symlink_escape_is_rejected(self): + root=self.root();(root/MENU).unlink() + outside=root.parent/(root.name+'-outside') + outside.write_text('leave alone');self.addCleanup(lambda:outside.unlink(missing_ok=True)) + try:(root/MENU).symlink_to(outside) + except OSError:self.skipTest('Symlink creation unavailable') + with self.assertRaisesRegex(ValueError,'escapes staging'):policy['cleanup'](root) + self.assertEqual(outside.read_text(),'leave alone') + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_sipa_worker_lifecycle.py b/tests/test_sipa_worker_lifecycle.py new file mode 100644 index 00000000..0b6bcea5 --- /dev/null +++ b/tests/test_sipa_worker_lifecycle.py @@ -0,0 +1,133 @@ +"""Run the real SIPA worker bodies with host pthread wait queues (no MMIO).""" +import pathlib +import shutil +import subprocess +import tempfile +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[1] +SIPA = ROOT / 'upstream/modules/sprd_modem/sipa_v3' + + +def function(source, name): + start = source.index('static int ' + name + '(') + pos = source.index('{', start) + depth = 1 + end = pos + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +class Workers(unittest.TestCase): + def test_probe_resume_interrupt_and_stop(self): + cc = shutil.which('cc') + if not cc: + self.skipTest('host C compiler required') + send = (SIPA / 'sipa_skb_send.c').read_text() + recv = (SIPA / 'sipa_skb_recv.c').read_text() + harness = r''' +#include +#include +#include +#include +#include +#include +#include +struct queue { pthread_mutex_t mutex; pthread_cond_t cond; }; +struct sipa_skb_sender { bool init_flag; struct queue free_waitq; + bool free_notify_net; }; +struct sipa_skb_receiver { bool init_flag; struct queue fill_recv_waitq; }; +static struct queue *q; +static atomic_bool stopping, pending, interrupt_wait; +static atomic_int mmio_reads, work, waits; +#define READ_ONCE(x) __atomic_load_n(&(x), __ATOMIC_ACQUIRE) +#define WRITE_ONCE(x,v) __atomic_store_n(&(x),(v),__ATOMIC_RELEASE) +#define current 0 +#define sched_setscheduler(a,b,c) ((void)0) +#define kthread_should_stop() atomic_load(&stopping) +#define wait_event_interruptible(queue,condition) ({ \ + int rc = 0; pthread_mutex_lock(&(queue).mutex); \ + while (!(condition)) { atomic_fetch_add(&waits,1); \ + pthread_cond_wait(&(queue).cond, &(queue).mutex); \ + if (atomic_exchange(&interrupt_wait,false)) { rc = -1; break; } \ + } pthread_mutex_unlock(&(queue).mutex); rc; }) +static bool sipa_sender_ck_unfree(void *unused) { + atomic_fetch_add(&mmio_reads,1); return !atomic_load(&pending); +} +static bool sipa_check_need_fill_cnt(void) { + atomic_fetch_add(&mmio_reads,1); return atomic_load(&pending); +} +static void sipa_free_sent_items(void) { + atomic_store(&pending,false); atomic_fetch_add(&work,1); +} +static int sipa_fill_all_free_fifo(void) { sipa_free_sent_items(); return 0; } +#define usleep_range(a,b) usleep(a) +''' + harness += function(send, 'sipa_free_thread') + '\n' + harness += function(recv, 'sipa_fill_recv_thread') + '\n' + harness += r''' +static int (*worker)(void *); +static void *entry(void *arg) { worker(arg); return NULL; } +static void wake(void) { + pthread_mutex_lock(&q->mutex); pthread_cond_broadcast(&q->cond); + pthread_mutex_unlock(&q->mutex); +} +static void settle(void) { usleep(30000); } +static void run_case(bool receive, bool resume) { + struct sipa_skb_sender s = { .init_flag = true }; + struct sipa_skb_receiver r = { .init_flag = true }; + pthread_t thread; + q = receive ? &r.fill_recv_waitq : &s.free_waitq; + pthread_mutex_init(&q->mutex,NULL); pthread_cond_init(&q->cond,NULL); + atomic_store(&stopping,false); atomic_store(&pending,true); + atomic_store(&interrupt_wait,false); atomic_store(&mmio_reads,0); + atomic_store(&work,0); atomic_store(&waits,0); + worker = receive ? sipa_fill_recv_thread : sipa_free_thread; + assert(!pthread_create(&thread,NULL,entry,receive ? (void*)&r : (void*)&s)); + settle(); assert(atomic_load(&waits)>0); + wake(); settle(); + atomic_store(&interrupt_wait,true); wake(); settle(); + /* Queued work, spurious wake, and signal cannot touch MMIO before resume. */ + assert(atomic_load(&mmio_reads)==0 && atomic_load(&work)==0); + if (resume) { + if (receive) WRITE_ONCE(r.init_flag,false); + else WRITE_ONCE(s.init_flag,false); + wake(); settle(); assert(atomic_load(&work)==1); + assert(atomic_load(&mmio_reads)>0); + wake(); settle(); assert(atomic_load(&work)==1); + atomic_store(&pending,true); wake(); settle(); + assert(atomic_load(&work)==2); + } + int before = atomic_load(&work); + atomic_store(&stopping,true); wake(); + assert(!pthread_join(thread,NULL)); assert(atomic_load(&work)==before); + pthread_cond_destroy(&q->cond); pthread_mutex_destroy(&q->mutex); +} +int main(void) { + alarm(5); + run_case(false,false); run_case(true,false); + run_case(false,true); run_case(true,true); + return 0; +} +''' + with tempfile.TemporaryDirectory(prefix='sipa-workers-') as tmp: + src = pathlib.Path(tmp) / 'test.c' + exe = pathlib.Path(tmp) / 'test' + src.write_text(harness) + subprocess.run([cc, '-std=gnu11', '-pthread', '-O2', str(src), + '-o', str(exe)], check=True, capture_output=True) + subprocess.run([str(exe)], check=True, timeout=8) + + def test_managed_threads_and_initialization(self): + for name in ('sipa_skb_send.c', 'sipa_skb_recv.c'): + source = (SIPA / name).read_text() + self.assertIn('= kthread_run(', source) + self.assertIn('devm_add_action_or_reset(', source) + self.assertIn('kthread_stop(data)', source) + self.assertNotIn('= kthread_create(', source) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_sms_broker.py b/tests/test_sms_broker.py new file mode 100644 index 00000000..1b99d1d7 --- /dev/null +++ b/tests/test_sms_broker.py @@ -0,0 +1,133 @@ +"""Production SMS -> FIFO -> ucode broker -> simulated modem; never sends SMS.""" +import os +import re +import select +import shlex +import subprocess +import threading +import unittest + +from helpers import TOP, ucode +from test_modemd import Base, MODEMD, has_modules + + +@unittest.skipUnless(ucode(), 'ucode required') +class PduBoundary(unittest.TestCase): + def accepted(self, commands): + # Execute the actual validator in ucode, not a Python translation. + import json + source = MODEMD.read_text() + source = source[source.index("const LF ="):source.index('\nfunction answer_file')] + code = source + '\nfor (let c in ' + json.dumps(commands) + ') print(one_request(c) ? "1\\n" : "0\\n");' + result = subprocess.run(ucode() + ['-e', code], capture_output=True, text=True, timeout=8) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.splitlines() + + def test_bare_and_sim_scoped_atomic_pdu_requests(self): + requests = [f'AT{scope}+CMG{op}=12\r001122Aa\x1a' + for scope in ('', '+SPACTCARD=0;', '+SPACTCARD=1;') for op in ('S', 'W')] + self.assertEqual(self.accepted(requests), ['1'] * len(requests)) + + def test_pdu_does_not_allow_other_commands_or_malformed_scopes(self): + heads = ['AT+SPACTCARD=2;+CMGS=12', 'AT+SPACTCARD=-1;+CMGS=12', + 'AT+SPACTCARD=01;+CMGS=12', 'AT+SPACTCARD=1;+CFUN=0;+CMGS=12', + 'AT+CFUN=0;+CMGS=12', 'AT+SPACTCARD=0;+SPACTCARD=1;+CMGS=12', + 'AT+SPACTCARD=1;AT+CMGS=12', 'AT+SPACTCARD=1;+CMGS=1000'] + requests = [h + '\r001122\x1a' for h in heads] + [ + 'AT+SPACTCARD=1;+CMGS=12\r001122', + 'AT+SPACTCARD=1;+CMGS=12\r00112Z\x1a', + 'AT+SPACTCARD=1;+CMGS=12\r\x1a', + 'AT+SPACTCARD=1;+CMGS=12\r001122\x1a\rAT+CFUN=0', + 'AT+SPACTCARD=1;+CMGS=12\r001122\x1a\nAT+CFUN=0'] + self.assertEqual(self.accepted(requests), ['0'] * len(requests)) + + +@unittest.skipUnless(ucode() and has_modules(ucode()), 'ucode socket/uloop/ubus required') +class SmsBroker(Base): + def setUp(self): + super().setUp() + # Never publish on the device's live bus, even when tested on hardware. + self.env['MU300_UBUS_SOCKET'] = str(self.tmp / 'isolated-unavailable.sock') + + def start_dual(self): + self.start(f'name=sim0,dev=/dev/stty_nr1,dir={self.run_root}/mu300-at,urc=0', + f'name=sim1,dev=/dev/stty_nr4,dir={self.run_root}/mu300-at4,urc=3') + self.ready('stty_nr1') + self.ready('stty_nr4') + + def test_both_scoped_submits_reach_only_their_channel_in_one_write(self): + self.start_dual() + for slot, name, directory in ((0, 'stty_nr1', 'mu300-at'), (1, 'stty_nr4', 'mu300-at4')): + cmd = f'AT+SPACTCARD={slot};+CMGS=12\r0011000B811234\x1a' + self.table[cmd] = ['+CMGS: 42', 'OK'] + answer = self.run_root / directory / f'answer.{10 + slot}' + self.ask(f'2 {answer} {cmd}', name) + self.assertEqual(self.answer(answer), '+CMGS: 42\nOK\n') + self.assertEqual([tx for tx in self.bridge.tx if cmd in tx[1]], [(name, cmd + '\r')]) + + def test_real_sender_and_client_through_broker_on_both_sims(self): + self.table['AT+CSCA?'] = ['+CSCA: "+8613800100500",145', 'OK'] + original_modem = self.bridge.modem + self.bridge.modem = lambda name, cmd: ( + ['+CMGS: 42', 'OK'] if re.fullmatch(r'AT\+SPACTCARD=[01];\+CMGS=\d+\r[0-9A-F]+\x1a', cmd) + else original_modem(name, cmd)) + self.start_dual() + bindir = self.tmp / 'bin' + bindir.mkdir() + client = bindir / 'mu300-at' + client.write_text('#!/bin/sh\nexec /bin/sh ' + shlex.quote(str(TOP / 'rootfs/overlay/opt/mu300/bin/mu300-at')) + ' "$@"\n') + client.chmod(0o755) + for slot, name, directory in ((0, 'stty_nr1', 'mu300-at'), (1, 'stty_nr4', 'mu300-at4')): + with self.subTest(slot=slot): + atdir = self.run_root / directory + fifo = atdir / 'cmd' + os.mkfifo(fifo, 0o600) + fd = os.open(fifo, os.O_RDWR | os.O_NONBLOCK) + stop = threading.Event() + errors = [] + def forward_requests(): + pending = b'' + try: + while not stop.is_set(): + if not select.select([fd], [], [], .02)[0]: + continue + pending += os.read(fd, 8192) + while b'\n' in pending: + line, pending = pending.split(b'\n', 1) + self.bridge.req(name, line.decode('ascii')) + except Exception as error: + errors.append(error) + thread = threading.Thread(target=forward_requests, daemon=True) + thread.start() + before = len(self.bridge.tx) + try: + env = dict(self.env, PATH=str(bindir) + ':' + os.environ['PATH'], + MU300_AT_DIR=str(atdir), MU300_SIM_SLOT=str(slot), + MU300_SMS_POOL=str(self.tmp / f'pool{slot}'), + MU300_SMS_OP_LOCK=str(self.tmp / f'operation{slot}.lock'), + MU300_SMS_PDU_AWK=str(TOP / 'rootfs/overlay/opt/mu300/lib/sms-pdu.awk')) + body = 'first\n第二行\r\n\nlast\n' + result = subprocess.run(['/bin/sh', str(TOP / 'rootfs/overlay/opt/mu300/bin/mu300-sms'), + 'send', '10010', body], env=env, capture_output=True, + text=True, stdin=subprocess.DEVNULL, start_new_session=True, timeout=12) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('sent (42)', result.stdout) + tx = self.bridge.tx[before:] + self.assertEqual(len(tx), 5, tx) + self.assertTrue(all(channel == name and cmd.startswith(f'AT+SPACTCARD={slot};') for channel, cmd in tx), tx) + self.assertEqual(sum('+CMGS=' in cmd for _, cmd in tx), 1) + submit = next(cmd for _, cmd in tx if '+CMGS=' in cmd) + pdu = bytes.fromhex(submit.split('\r', 1)[1].removesuffix('\x1a\r')) + payload = pdu[8 + (pdu[3] + 1) // 2:] + self.assertEqual(payload, body.encode('utf-16-be')) + self.assertFalse((atdir / 'lock').exists()) + self.assertFalse((self.tmp / f'operation{slot}.lock').exists()) + self.assertEqual(errors, []) + finally: + stop.set() + thread.join(2) + os.close(fd) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_sms_forward_history.py b/tests/test_sms_forward_history.py index e122b6e0..940d2e5f 100644 --- a/tests/test_sms_forward_history.py +++ b/tests/test_sms_forward_history.py @@ -18,7 +18,7 @@ class ForwardHistory(ShellTest): def setUp(self): super().setUp() text = FORWARD.read_text() - self.code = '\n'.join([ + self.code = "NL='\n'\n" + '\n'.join([ text[text.index('number() {'):text.index('bool() {')], text[text.index('load_state() {'):text.index('save_config() {')], text[text.index('write_result() {'):text.index('read_result() {')], @@ -28,6 +28,27 @@ class ForwardHistory(ShellTest): ]) self.barrier = epoch('2026-10-07T12:00:00+08:00') + def test_spooled_multiline_body_reaches_forwarder_without_losing_blank_lines(self): + for index, shell in enumerate(self.each_shell()): + for n, body in enumerate(('first\nsecond', '\nfirst\n\nlast\n\n', + 'a\r\nb\r\n', '\n', 'trailing dot.\n')): + base = self.tmp / f'body-{index}-{n}' + pool = base / 'pool' + (pool / 'msg').mkdir(parents=True) + (pool / 'msg/000001').write_bytes(( + 'dir: mt\nfrom: 10010\nsource: direct\ncoding: pdu\n' + f'received: {self.barrier + 500}\nscts: old\n\n{body}\n').encode()) + (pool / 'next_id').write_text('1\n') + state = base / 'state' + state.write_text(f'0|{self.barrier}|-1|none\n') + env = dict(BASE=base, POOL=pool, STATE=state, RESULT=base / 'result', + DELIVERIES=base / 'sent', enabled=1, power_last_result='idle', + blacklist_phone='', blacklist_keywords='') + run = self.code + '\ndeliver() { printf "%s" "$3" > "$DELIVERIES"; DELIVER_RESULT=sent; }\nload_state\nprocess_sms' + result = self.sh(shell, run, **env) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((base / 'sent').read_bytes(), body.encode()) + def test_timestamp_offsets_and_calendar_independent_of_host_timezone(self): cases = [ ('26/10/07,12:34:56+32', '2026-10-07T12:34:56+08:00'), diff --git a/tests/test_sms_forward_templates.py b/tests/test_sms_forward_templates.py index 05971261..78ea5d4a 100644 --- a/tests/test_sms_forward_templates.py +++ b/tests/test_sms_forward_templates.py @@ -13,6 +13,14 @@ class ForwardTemplates(ShellTest): super().setUp() source = FORWARD.read_text(encoding='utf-8') self.code = "NL='\n'\n" + source[source.index('template_strings() {'):source.index('sms_units() {')] + self.units = source[source.index('sms_units() {'):source.index('deliver() {')] + + def test_sms_units_include_every_newline_and_surrogate_pair(self): + for shell in self.each_shell(): + for body in ('', 'a', '\n', 'a\n', 'a\n\n', '\r\n', '😀\n', 'a' * 69 + '\n\n', '\\n'): + result = self.sh(shell, self.units + '\nsms_units "$BODY"', BODY=body) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(int(result.stdout), len(body.encode('utf-16-be')) // 2, repr(body)) def test_sms_body_and_sender_are_preserved_in_every_language(self): body = '验证码 123456\nİstanbul şifre: 654321\n$(reboot); "quoted" \\path' diff --git a/tests/test_sms_pool_rpc.py b/tests/test_sms_pool_rpc.py index 32bcef51..bd764eae 100644 --- a/tests/test_sms_pool_rpc.py +++ b/tests/test_sms_pool_rpc.py @@ -99,7 +99,7 @@ esac''') def test_init_pool_environment_matches_for_both_sms_receivers_and_at_owners(self): for shell in self.shells: for configured,expected in [(self.legacy,self.current),(self.tmp/'custom dir',self.tmp/'custom dir')]: - for init,entry in [('mu300-atd','start_single_sim'),('mu300-smsd','start_service')]: + for init,entry in [('mu300-atd','start_service'),('mu300-smsd','start_service')]: source=(TOP/'openwrt/overlay/etc/init.d'/init).read_text() source=source.replace('/dev/stty_nr1','/dev/null') if init=='mu300-atd': @@ -107,6 +107,8 @@ esac''') service=service[service.index('MODEMD_BROKERS='):].replace('/opt/mu300/bin/mu300-device','mu300-device') fixture=self.tmp/'modemd-layout.sh';fixture.write_text('modemd_require() { :; }\n'+service) source=source.replace('. "${MU300_MODEMD_SERVICE_LIB:-/opt/mu300/lib/modemd-service.sh}"',f'. "{fixture}"') + source=source.replace('/opt/mu300/bin/mu300-device','mu300-device') + source=source.replace('/opt/mu300/bin/mu300-platform-config','true') self.stub('mu300-device','echo f50') code=source+'''\nprocd_open_instance() { instance=$1; } procd_close_instance() { :; } diff --git a/tests/test_sms_send_transaction.py b/tests/test_sms_send_transaction.py index 846bd2bc..f79fb01e 100644 --- a/tests/test_sms_send_transaction.py +++ b/tests/test_sms_send_transaction.py @@ -2,7 +2,11 @@ import json import os from pathlib import Path +import re import select +import shlex +import shutil +import signal import subprocess import tempfile import threading @@ -69,8 +73,8 @@ class SmsTransaction(unittest.TestCase): part.write_text(reply) part.rename(answer) - def send(self, shell='bash', **extra): - return subprocess.run([shell, str(SMS), 'send', '10010', 'test'], + def send(self, shell='bash', text='test', **extra): + return subprocess.run([shell, str(SMS), 'send', '10010', text], env=dict(self.env, **extra), capture_output=True, text=True, timeout=8) @@ -92,6 +96,32 @@ class SmsTransaction(unittest.TestCase): self.assertEqual(self.commands[1][0], 'AT+SPACTCARD=1;+CSCA="+8613800100500",145') self.assertTrue(all(c.startswith('AT+SPACTCARD=1;') for c, _ in self.commands)) + def test_multiline_text_is_encoded_inside_pdu_not_fifo_protocol(self): + for text in ('first\nsecond', '\nfirst\n\nlast\n', 'a\r\nb\r\n', + 'literal\\ntext', '中文\nİstanbul 😀\n', '\n', 'a' * 68 + '\nZ'): + with self.subTest(text=repr(text)): + self.commands.clear() + result = self.send(text=text, MU300_SIM_SLOT='1') + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + commands = [cmd for cmd, _ in self.commands if '+CMGS=' in cmd] + self.assertEqual(len(commands), 1) + command = commands[0] + self.assertNotIn('\n', command) + header, pdu = command.split('\r', 1) + data = bytes.fromhex(pdu.removesuffix('\x1a')) + address_bytes = (data[3] + 1) // 2 + udl_position = 7 + address_bytes + payload = data[udl_position + 1:] + self.assertEqual(payload, text.encode('utf-16-be')) + self.assertEqual(data[udl_position], len(payload)) + self.assertEqual(int(re.search(r'CMGS=(\d+)', header)[1]), len(data) - 1) + + def test_trailing_newlines_count_towards_sms_limit_before_any_at(self): + result = self.send(text='a' * 69 + '\n\n') + self.assertNotEqual(result.returncode, 0) + self.assertIn('71 UCS-2 units', result.stderr) + self.assertEqual(self.commands, []) + def test_malformed_or_failed_query_still_submits(self): for query in ['ERROR\n', '+CSCA: "evil;AT",145\nOK\n', 'OK\n']: self.query = query @@ -113,6 +143,52 @@ class SmsTransaction(unittest.TestCase): self.assertNotEqual(result.returncode, 0) self.assertFalse((self.channel / 'lock').exists()) self.assertFalse((self.root / 'oplock').exists()) + self.assertIn('+CMS ERROR: 500', result.stderr) + + @unittest.skipUnless(shutil.which('busybox'), 'BusyBox ash required') + def test_background_signal_state_preserves_slot_and_transaction(self): + # Run both sender and FIFO client in ash, as on OpenWrt; the host's + # /bin/sh might be dash and otherwise re-exec the client in bash. + client = self.bin / 'mu300-at' + client.unlink() + client.write_text('#!/bin/sh\nexec busybox ash '+shlex.quote(str(AT))+' "$@"\n') + client.chmod(0o755) + for ignored, blocked in (([signal.SIGCHLD, signal.SIGPIPE], []), + ([], [signal.SIGCHLD, signal.SIGALRM]), + ([signal.SIGINT, signal.SIGQUIT, signal.SIGHUP], [])): + def setup(): + for sig in ignored: + signal.signal(sig, signal.SIG_IGN) + signal.pthread_sigmask(signal.SIG_BLOCK, blocked) + self.commands.clear() + # Forwarding keeps descriptor 8/9 locks open in its parent. The + # child may use fd9 for its FIFO, without closing the parent's lock. + launch = 'exec 8>'+shlex.quote(str(self.root/'fd8'))+' 9>'+shlex.quote(str(self.root/'fd9'))+'; exec "$@"' + result = subprocess.run(['busybox', 'ash', '-c', launch, 'fixture', + 'busybox', 'ash', str(SMS), 'send', '10010', 'fixture'], + env=dict(self.env, MU300_SIM_SLOT='1'), + stdin=subprocess.DEVNULL, capture_output=True, + preexec_fn=setup, start_new_session=True, text=True, timeout=8) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(self.commands), 5) + self.assertEqual(len({holder for _, holder in self.commands}), 1) + self.assertTrue(all(c.startswith('AT+SPACTCARD=1;') for c, _ in self.commands)) + self.assertEqual(sum('CMGS=' in c for c, _ in self.commands), 1) + + def test_empty_at_submission_is_reported_without_resending(self): + # Interpose a transport failure after the real client has carried all + # setup requests; this must not create a sent entry or repeat Ctrl-Z. + client = self.bin / 'mu300-at' + client.unlink() + client.write_text('#!/bin/sh\ncase "$*" in *CMGS=*) exit 7 ;; esac\n' + 'exec bash '+shlex.quote(str(AT))+' "$@"\n') + client.chmod(0o755) + result = self.send() + self.assertNotEqual(result.returncode, 0) + self.assertIn('no submission acknowledgement (AT exit 7)', result.stderr) + self.assertFalse(any('CMGS=' in c for c, _ in self.commands)) + self.assertFalse((self.channel / 'lock').exists()) + self.assertFalse((self.root / 'oplock').exists()) def test_live_holder_busy_without_commands(self): lock = self.channel / 'lock' diff --git a/tests/test_ufs_storage.py b/tests/test_ufs_storage.py new file mode 100644 index 00000000..961176b4 --- /dev/null +++ b/tests/test_ufs_storage.py @@ -0,0 +1,159 @@ +"""UFS geometry uses real logical blocks while public offsets remain 512B.""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +import uuid +import zlib + +from helpers import TOP, ShellTest +sys.path.insert(0,str(TOP)) +from installer.backend import gpt, storage, uninstall + + +def snapshot(block, sectors=64*2097152): + factor=block//512;total=sectors//factor;count=128;rows=(count*128+block-1)//block + table=bytearray(count*128) + for number,name,start,end in ((1,'misc',2048,4095),(2,'userdata',4096,16*2097152-1)): + e=bytearray(128);e[:16]=uuid.UUID('0fc63daf-8483-4772-8e79-3d69d8477de4').bytes_le + e[16:32]=uuid.UUID(int=number).bytes_le + struct.pack_into('> "$STUBLOG/ip-calls" case "$*" in 'link set rndis0 master br-lan') touch "$STUBLOG/bridged" ;; - '-4 -o addr show dev br-lan') echo '2: br-lan inet 192.168.77.1/24 scope global br-lan' ;; + '-4 -o addr show dev br-lan scope global') [ "$LAN_READY" = 1 ] && echo '2: br-lan inet 192.168.88.1/24 scope global br-lan' ;; '-o link show dev rndis0') [ -f "$STUBLOG/bridged" ] && echo '3: rndis0 master br-lan' ;; '-o link show dev usb0') echo '4: usb0' ;; - '-4 -o addr show dev rndis0') echo "3: rndis0 inet $PORT_ADDR scope global rndis0" ;; + '-4 -o addr show dev rndis0 scope global') echo "3: rndis0 inet $PORT_ADDR scope global rndis0" ;; esac exit 0 ''') @@ -107,18 +107,29 @@ exit 0 # function must win so this fixture can never call the host's ip. source='ip() { "$STUBLOG/stubs/ip" "$@"; }\n'+source for shell in self.each_shell(): - for address in ('192.168.77.1/24', '192.168.77.1/16', '192.168.88.1/24'): + for address, action, ready in ( + ('192.168.77.1/24', 'ifup', '1'), + ('192.168.77.1/16', 'ifup', '1'), + ('192.168.88.1/24', 'ifup', '1'), + ('192.168.77.1/24', 'ifupdate', '1'), + ('192.168.77.1/24', 'ifup', '0'), + ('192.168.77.1/24', 'ifdown', '1')): for name in ('bridged', 'ip-calls'): (self.tmp / name).unlink(missing_ok=True) - r = self.sh(shell, source, ACTION='ifup', INTERFACE='lan', PORT_ADDR=address) + r = self.sh(shell, source, ACTION=action, INTERFACE='lan', PORT_ADDR=address, LAN_READY=ready) self.assertEqual(r.returncode, 0, r.stderr) - calls = (self.tmp / 'ip-calls').read_text() + calls = (self.tmp / 'ip-calls').read_text() if (self.tmp / 'ip-calls').exists() else '' + if action == 'ifdown': + self.assertEqual(calls, '') + continue self.assertLess(calls.index('link set rndis0 master br-lan'), calls.index('-4 -o addr show dev br-lan')) - if address.startswith('192.168.77.1/'): + if ready == '1': self.assertIn(f'addr del {address} dev rndis0', calls) else: self.assertNotIn('addr del ', calls) self.assertNotIn('addr del 192.168.77.1/24 dev usb0', calls) + self.assertNotIn(' down', calls) + self.assertNotIn('-6', calls) if __name__ == '__main__': diff --git a/tests/test_user_packages.py b/tests/test_user_packages.py index 9c3075b6..9b761643 100644 --- a/tests/test_user_packages.py +++ b/tests/test_user_packages.py @@ -632,16 +632,15 @@ class Service(ShellTest): self.assertEqual(self.rec('state'), 'offline\n') self.assertEqual(self.dhcp(), before) - def test_dns_untouched_with_the_vpn_on(self): + def test_dns_untouched_when_custom_resolver_owns_the_port(self): for shell in self.each_shell(): self.setup_openwrt(server='127.0.0.1#7874 8.8.8.8') - write(self.R, {'etc/mu300/vpn.conf': 'ENABLE=1\nSECRET=do-not-print\n'}) + write(self.R, {'etc/mu300/local-resolver.conf': 'ENABLE=1\nDNS_PORT=7874\nSECRET=do-not-print\n'}) (self.tmp / 'online').write_text('') (self.tmp / 'missing').write_text('luci-app-openclash\n') before = self.dhcp() r = self.run_upk(shell, 'run') self.assertEqual(self.dhcp(), before) - self.assertIn('the VPN is on', self.rec('note')) self.assertNotIn('do-not-print', r.stdout + r.stderr + self.rec('log') + self.run_upk(shell, 'status').stdout) self.run_upk(shell, 'repair-dns') self.assertEqual(self.dhcp(), before) diff --git a/tests/test_vpn.py b/tests/test_vpn.py deleted file mode 100644 index 0f6d6227..00000000 --- a/tests/test_vpn.py +++ /dev/null @@ -1,115 +0,0 @@ -"""mu300-vpn, sourced for its functions (MU300_LIB=1): the VLESS URI parser, JSON helpers, which networks stay out of -the tunnel, and the sing-box config it writes. Ubuntu and OpenWrt both run it (dash, bash, busybox ash).""" -import json -import unittest - -from helpers import BIN, ShellTest - - -class Vpn(ShellTest): - def setUp(self): - super().setUp() - self.conf = self.tmp / 'vpn.conf' - self.conf.write_text('') - self.root = self.tmp / 'root' - (self.root / 'run/mu300').mkdir(parents=True) - self.brlan = None - self.stub('ip', 'if [ "$*" = "-4 -o addr show br-lan" ] && [ -s "$STUBLOG/br-lan" ]; then ' - 'echo "5: br-lan inet $(cat "$STUBLOG/br-lan") brd x scope global br-lan"; fi') - - def vpn(self, shell, code, conf='', device='f50', brlan=None): - self.conf.write_text(conf) - (self.root / 'run/mu300/device').write_text(device + '\n') - (self.tmp / 'br-lan').write_text(brlan or '') - return self.sh(shell, f'. "{BIN}/mu300-vpn"; {code}', MU300_LIB=1, MU300_VPN_CONF=self.conf, - MU300_VPN_RUN=self.tmp / 'run-vpn', MU300_LAN_CONF=self.tmp / 'no-lan.conf', - MU300_BIN=BIN, MU300_SYSROOT=self.root) - - def test_own_lan_always_local(self): - cases = [ - # (vpn.conf, device, br-lan address, LAN_CIDRS wanted) - ('', 'f50', '192.168.77.1/24', '192.168.77.0/24'), - ('', 'u30air', '192.168.78.1/24', '192.168.78.0/24'), - # a vpn.conf copied from an F50 onto a U30 Air: its own network is added, not replaced - ('LAN_CIDRS=192.168.77.0/24\n', 'u30air', '192.168.78.1/24', '192.168.77.0/24,192.168.78.0/24'), - ('LAN_CIDRS=192.168.78.0/24\n', 'u30air', '192.168.78.1/24', '192.168.78.0/24'), - # br-lan not up yet: the device's default address - ('', 'u30air', None, '192.168.77.0/24'), - ('', 'f50', None, '192.168.77.0/24'), - # an address set in lan.conf / UCI, as br-lan has it - ('LAN_CIDRS=10.0.0.0/8\n', 'f50', '192.168.5.1/24', '10.0.0.0/8,192.168.5.0/24'), - ] - for shell in self.each_shell(): - for conf, device, brlan, want in cases: - r = self.vpn(shell, 'echo "$LAN_CIDRS"', conf, device, brlan) - self.assertEqual(r.stdout.strip(), want, (conf, device, brlan, r.stderr)) - - def test_urldecode(self): - for shell in self.each_shell(): - r = self.vpn(shell, "urldecode 'a%20b%2Fc'; echo; urldecode 'k%C3%BCt%C3%BCk'; echo; urldecode plain; echo") - self.assertEqual(r.stdout.split('\n')[:3], ['a b/c', 'kütük', 'plain']) - - def test_json_helpers(self): - for shell in self.each_shell(): - r = self.vpn(shell, """json_str 'a"b\\c'; echo; json_list 'x,y"z,w'; echo""") - a, b = r.stdout.split('\n')[:2] - self.assertEqual(json.loads(a), 'a"b\\c') - self.assertEqual(json.loads(b), ['x', 'y"z', 'w']) - - URIS = [ - ('vless://11111111-2222-3333-4444-555555555555@vpn.example.com:8443?type=ws&security=tls&sni=cdn.example.com' - '&path=%2Fws%3Fed%3D2048&host=h.example.com#name', - dict(UUID='11111111-2222-3333-4444-555555555555', HOST='vpn.example.com', PORT='8443', TYPE='ws', - SECURITY='tls', SNI='cdn.example.com', WSPATH='/ws?ed=2048', WSHOST='h.example.com')), - ('vless://uuid@[2001:db8::1]:443?security=reality&pbk=KEY&sid=ab&fp=chrome&type=grpc&serviceName=svc', - dict(UUID='uuid', HOST='2001:db8::1', PORT='443', TYPE='grpc', SECURITY='reality', PBK='KEY', SID='ab', - FP='chrome', SVC='svc')), - ('vless://uuid@host.example', dict(HOST='host.example', PORT='443', TYPE='tcp', SECURITY='none')), - ('vless://uuid@1.2.3.4:80/?type=tcp&peer=p.example', dict(HOST='1.2.3.4', PORT='80', SNI='p.example')), - ] - - def test_parse_uri(self): - for shell in self.each_shell(): - for uri, want in self.URIS: - code = f"VLESS_URI='{uri}'; parse_uri; " + '; '.join(f'echo "{k}=${k}"' for k in want) - r = self.vpn(shell, code) - self.assertEqual(r.returncode, 0, r.stderr) - got = dict(line.split('=', 1) for line in r.stdout.splitlines()) - self.assertEqual(got, want, uri) - - def test_parse_uri_rejects(self): - for shell in self.each_shell(): - for uri in ('vmess://abc@h:1', 'vless://@host:443', 'https://x'): - r = self.vpn(shell, f"VLESS_URI='{uri}'; parse_uri; echo PARSED") - self.assertNotEqual(r.returncode, 0, uri) - self.assertNotIn('PARSED', r.stdout) - - def test_outbound_json(self): - for shell in self.each_shell(): - for uri, _ in self.URIS: - r = self.vpn(shell, f"VLESS_URI='{uri}'; UPSTREAM_HTTP_PROXY=; parse_uri; outbound_json") - o = json.loads(r.stdout) - self.assertEqual(o['type'], 'vless') - self.assertIsInstance(o['server_port'], int) - r = self.vpn(shell, f"VLESS_URI='{self.URIS[1][0]}'; UPSTREAM_HTTP_PROXY=; parse_uri; outbound_json") - o = json.loads(r.stdout) - self.assertEqual(o['tls']['reality'], {'enabled': True, 'public_key': 'KEY', 'short_id': 'ab'}) - self.assertEqual(o['transport'], {'type': 'grpc', 'service_name': 'svc'}) - - def test_singbox_config(self): - self.stub('sing-box', 'echo "$*" >> "$STUBLOG/sb.args"') - conf = f"VLESS_URI='{self.URIS[0][0]}'\nLAN_CIDRS=192.168.77.0/24\nENGINE=sing-box\n" - for shell in self.each_shell(): - code = f'BIN="{self.stubs}/sing-box"; UPSTREAM_HTTP_PROXY=; gen_singbox' - r = self.vpn(shell, code, conf, 'u30air', '192.168.78.1/24') - self.assertEqual(r.returncode, 0, r.stderr) - cfg = json.loads((self.tmp / 'run-vpn' / 'config.json').read_text()) - tun = cfg['inbounds'][0] - self.assertEqual(tun['type'], 'tun') - self.assertEqual(tun['route_exclude_address'], ['192.168.77.0/24', '192.168.78.0/24']) - self.assertEqual(cfg['outbounds'][0]['server'], 'vpn.example.com') - self.assertIn('check -c', (self.tmp / 'sb.args').read_text()) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/ufs_gpt_runtime.py b/tests/ufs_gpt_runtime.py new file mode 100644 index 00000000..92ace0fd --- /dev/null +++ b/tests/ufs_gpt_runtime.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Run the shipped ucode GPT tool on sparse files, never physical disks. + +Uses the existing local OpenWrt base image and removes its own temp fixtures. +Run in WSL: python3 tests/ufs_gpt_runtime.py +""" +from pathlib import Path +import subprocess +import tempfile + +from test_ufs_storage import snapshot, TOP, gpt + + +def run(): + for block in (512,4096): + with tempfile.TemporaryDirectory(prefix='mu300-ufs-gpt-') as tmp: + folder=Path(tmp);disk=folder/'disk' + first,last,total=snapshot(block) + with disk.open('wb') as stream: + stream.write(first);stream.seek(total*512-len(last));stream.write(last) + def command(*args, ok=True): + cmd=['docker','run','--rm','--platform','linux/arm64', + '-v',str(folder)+':/fixtures', + '-v',str(TOP/'desktop/boot/mu300-gpt')+':/tool:ro', + '--entrypoint','/usr/bin/ucode','mu300-openwrt-base:25.12.5', + '/tool',args[0],'/fixtures/disk',*map(str,args[1:])] + r=subprocess.run(cmd,capture_output=True,text=True,timeout=45) + assert (r.returncode==0)==ok,r.stdout+r.stderr + return r.stdout + listing=command('list') + assert '2 4096 33554431 userdata' in listing,listing + prior=16*2097152-4096;target=4*2097152;need=4*2097152 + command('plan','resize:userdata:'+str(target),'mu300root:'+str(need)) + with disk.open('rb') as stream: + assert stream.read(len(first))==first + command('carve-userdata',target,need,prior) + # Geometry and CRC are independently verified by the Python codec. + with disk.open('rb') as stream: + a=stream.read(len(first));stream.seek(total*512-len(last));b=stream.read() + info=gpt.gpt_space(a,b,total) + root=next(p for p in info['parts'] if p['name']=='mu300root') + assert root['start']==4096+target and root['end']+1-root['start']==need + command('uuid',root['n']) + command('resize','mu300root',need//2) + command('add','testroot',need//2) + with disk.open('rb') as stream: + a=stream.read(len(first));stream.seek(total*512-len(last));b=stream.read() + gpt.gpt_space(a,b,total) + before=(a,b) + command('carve-userdata',target,need,prior,ok=False) + if block == 4096: + command('resize','mu300root',2049,ok=False) + command('add','unaligned',2049,ok=False) + with disk.open('rb') as stream: + a=stream.read(len(first));stream.seek(total*512-len(last));b=stream.read() + assert (a,b)==before + print(f'{block}-byte GPT: list/plan/carve/uuid/resize/add and rejected retry verified',flush=True) + + +if __name__=='__main__':run() diff --git a/tools/android-install.sh b/tools/android-install.sh index cf2eb73a..f2ef96ef 100755 --- a/tools/android-install.sh +++ b/tools/android-install.sh @@ -167,7 +167,7 @@ fi # --- user-packages begin # Packages installed on the device are not in the release's image, and an update puts the image in place while it -# keeps /etc/config (OpenWrt) and /etc/mu300: their programs were gone and their settings stayed - OpenClash's left +# keeps /etc/config (OpenWrt) and /etc/mu300: their programs were gone and their settings stayed - an absent DNS extension left # the device without DNS (#116). So before the switch the update writes down what was added - the packages asked for # by hand (OpenWrt: /etc/apk/world; Ubuntu: dpkg's packages that apt did not pull in by itself) less the image's # own set (etc/mu300/image-packages, written when the image is built) - into etc/mu300/user-packages/ of the new diff --git a/tools/build-release.py b/tools/build-release.py index f9d02de3..db0a16d2 100644 --- a/tools/build-release.py +++ b/tools/build-release.py @@ -287,7 +287,7 @@ def package(task, common, rows): print('Verified release: ' + str(destination)) -def add_diff(task,rows,source): +def add_diff(task,rows,source,repair_installer=False): if source is None:raise ValueError('Supply --source-release') source=source.resolve() if source.parent!=(TOP/'release').resolve() or source.name.startswith('.'): @@ -304,15 +304,16 @@ def add_diff(task,rows,source): if stage_path(task.workspace,profile).exists():raise ValueError('Prior staging retained: '+profile) identify=runpy.run_path(str(TOP/'tools/release-identity.py'))['identify'] before=identify(TOP,'mu300','7.2.8');parent=TOP/'release';pending=parent/('.building-'+task.id);pending.mkdir() - task.save(pending_output=str(pending),build_type='diff-tools-only',base_release=str(source)) + task.save(pending_output=str(pending),build_type='installer-entry-repair' if repair_installer else 'diff-tools-only',base_release=str(source)) repack=runpy.run_path(str(TOP/'tools/repack-with-diff.py'))['repack'];assets=[] for profile,path in selected.items(): stage=stage_path(task.workspace,profile);stage.mkdir(parents=True) write_json(stage/'.build-owner.json',{'owner':OWNER,'profile':profile}) studio=stage/'assembly' task.run(profile+'-diff',[sys.executable,TOP/'tools/package-diff-studio.py','--prepare','--package',studio]) - target=pending/(path.stem+'-tools-g'+before['source_commit'][:8]+'.zip') - repack(path,target,studio,before);verify_archive(target,require_diff=True) + tag='-installer-fix-g' if repair_installer else '-tools-g' + target=pending/(path.stem+tag+before['source_commit'][:8]+'.zip') + repack(path,target,studio,before,repair_installer=repair_installer);verify_archive(target,require_diff=True) checksum=digest(target);(pending/(target.name+'.sha256')).write_text(checksum+' '+target.name+'\n') assets.append({'profile':profile,'file':target.name,'bytes':target.stat().st_size,'sha256':checksum}) clean_stage(task.workspace,profile);task.save(assets=assets) @@ -325,7 +326,7 @@ def add_diff(task,rows,source): def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('action', choices=('plan', 'check', 'package', 'add-diff', 'run', 'status', 'clean-staging')) + parser.add_argument('action', choices=('plan', 'check', 'package', 'add-diff', 'repair-installer', 'run', 'status', 'clean-staging')) parser.add_argument('--profiles', nargs='+', choices=('all', *PROFILES), default=['all']) parser.add_argument('--workspace', type=Path, default=Path.home() / 'openwrt-build') parser.add_argument('--config', type=Path, default=TOP / 'tools/build-layout.json') @@ -356,8 +357,8 @@ def main(): if args.action == 'run': if not command: raise ValueError('Supply a real compiler/build command after --') task.run('command', command); task.save(state='complete') - elif args.action=='add-diff': - add_diff(task,rows,args.source_release) + elif args.action in ('add-diff','repair-installer'): + add_diff(task,rows,args.source_release,repair_installer=args.action=='repair-installer') else: package(task, common, rows) except BaseException as error: diff --git a/tools/fetch-sing-box.sh b/tools/fetch-sing-box.sh deleted file mode 100755 index 3383410a..00000000 --- a/tools/fetch-sing-box.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -# Download the pinned sing-box release (static musl arm64) used by mu300-vpn and verify it. -# tools/fetch-sing-box.sh [OUT] (default: ./sing-box, picked up by the rootfs builds) -set -eu -VER=1.14.1 -SHA256=d94fc9704372ca2fa2854e54c20b406e4b8779b5ccdd0c557da90ea9344e9631 -NAME=sing-box-$VER-linux-arm64-musl -OUT=${1:-sing-box} -tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT -curl -fsSL -o "$tmp/$NAME.tar.gz" "https://github.com/SagerNet/sing-box/releases/download/v$VER/$NAME.tar.gz" -have=$(shasum -a 256 "$tmp/$NAME.tar.gz" 2>/dev/null || sha256sum "$tmp/$NAME.tar.gz") -[ "${have%% *}" = "$SHA256" ] || { echo "checksum mismatch for $NAME.tar.gz" >&2; exit 1; } -tar -xzf "$tmp/$NAME.tar.gz" -C "$tmp" -install -m 755 "$tmp/$NAME/sing-box" "$OUT" -echo "sing-box $VER -> $OUT" diff --git a/tools/fetch-xray.sh b/tools/fetch-xray.sh deleted file mode 100755 index 1ee009f7..00000000 --- a/tools/fetch-xray.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/sh -# Download the pinned Xray-core and hev-socks5-tunnel releases (static arm64) used by mu300-vpn's xray engine and -# verify them. Xray speaks VLESS (it is the reference implementation); hev-socks5-tunnel turns a kernel TUN -# device into connections on Xray's local SOCKS port. -# tools/fetch-xray.sh [OUTDIR] (default: .; writes OUTDIR/xray and OUTDIR/hev-socks5-tunnel) -set -eu -XRAY_VER=26.3.27 -XRAY_SHA256=4d30283ae614e3057f730f67cd088a42be6fdf91f8639d82cb69e48cde80413c -HEV_VER=2.17.1 -HEV_SHA256=958206dcebcdc390cdc4d5b88c8504ec81483e2a04b46d37c835a179830c86ba -OUT=${1:-.} -tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT -sha() { s=$(shasum -a 256 "$1" 2>/dev/null || sha256sum "$1"); printf '%s' "${s%% *}"; } - -curl -fsSL -o "$tmp/xray.zip" "https://github.com/XTLS/Xray-core/releases/download/v$XRAY_VER/Xray-linux-arm64-v8a.zip" -[ "$(sha "$tmp/xray.zip")" = "$XRAY_SHA256" ] || { echo "checksum mismatch for Xray $XRAY_VER" >&2; exit 1; } -unzip -q -o "$tmp/xray.zip" xray -d "$tmp" -install -m 755 "$tmp/xray" "$OUT/xray" - -curl -fsSL -o "$tmp/hev" "https://github.com/heiher/hev-socks5-tunnel/releases/download/$HEV_VER/hev-socks5-tunnel-linux-arm64" -[ "$(sha "$tmp/hev")" = "$HEV_SHA256" ] || { echo "checksum mismatch for hev-socks5-tunnel $HEV_VER" >&2; exit 1; } -install -m 755 "$tmp/hev" "$OUT/hev-socks5-tunnel" - -echo "xray $XRAY_VER, hev-socks5-tunnel $HEV_VER -> $OUT" diff --git a/tools/make-release.sh b/tools/make-release.sh index e6020f45..73fb89c4 100755 --- a/tools/make-release.sh +++ b/tools/make-release.sh @@ -32,8 +32,6 @@ sh "$TOP/tools/keys/build.sh" "$IN/tools/keys" sh "$TOP/tools/atd-io/build.sh" "$IN/tools/atd-io" # cltest links against Android's libraries at build time only; use a local build when there is one [ -f "$TOP/tools/gpu/cltest" ] && cp "$TOP/tools/gpu/cltest" "$IN/tools/gpu/cltest" -sh "$TOP/tools/fetch-sing-box.sh" "$IN/sing-box" -sh "$TOP/tools/fetch-xray.sh" "$IN" echo "==> kernel bundle" K=$D/kernel && mkdir -p "$K" @@ -71,7 +69,7 @@ for u in 24.04 26.04; do cltest=""; [ -f "$IN/tools/gpu/cltest" ] && cltest="-v $IN/tools/gpu/cltest:/cltest:ro" # shellcheck disable=SC2086 docker run --rm -v "$B":/w -v "$IN/out/modules":/kmods:ro -v "$IN/out":/kout:ro -v "$IN/tools/logdw/logdw":/logdw:ro \ - -v "$IN/tools/bt-init/mu300-bt-init":/bt-init:ro -v "$IN/tools/keys/mu300-keys":/keys:ro -v "$IN/tools/atd-io/mu300-atd-io":/atd-io:ro -v "$IN/sing-box":/sing-box:ro -v "$IN/xray":/xray:ro -v "$IN/hev-socks5-tunnel":/hev-socks5-tunnel:ro $cltest \ + -v "$IN/tools/bt-init/mu300-bt-init":/bt-init:ro -v "$IN/tools/keys/mu300-keys":/keys:ro -v "$IN/tools/atd-io/mu300-atd-io":/atd-io:ro $cltest \ -e MU300_VERSION="$TAG" mu300-ubuntu:$u bash /w/assemble.sh >/dev/null out=mu300-ubuntu-rootfs.tar.gz; [ $u = 24.04 ] || out=mu300-ubuntu-$u-rootfs.tar.gz mv "$B/mu300-ubuntu-$u-rootfs.tar.gz" "$D/$out"; rm -rf "$B" @@ -134,7 +132,7 @@ for a in mu300-kernel mu300-kernel-6.18 mu300-kernel-7.2 mu300-ubuntu-rootfs mu3 -e '(^|/)lib/firmware/(wcnmodem|gnssmodem|wifi_board_config|bt_configure)' \ -e '^opt/mu300/android/.+' -e '__properties__|dev-properties' \ -e '(^|/)(libmali|libOpenCL|libGLES|libEGL|libvulkan)[^/]*\.so' \ - -e '^etc/uhttpd\.key$' -e '^etc/ssh/ssh_host_' -e '^etc/mu300/(hotspot|vpn|toolkit)\.conf$' -e '^etc/dropbear/dropbear_.*_host_key' \ + -e '^etc/uhttpd\.key$' -e '^etc/ssh/ssh_host_' -e '^etc/mu300/(hotspot|toolkit)\.conf$' -e '^etc/dropbear/dropbear_.*_host_key' \ | grep -vE '^opt/mu300/android/system/?$|^opt/mu300/android/system/bin/?$|^opt/mu300/android/system/bin/cltest$' || true) if [ -n "$bad" ]; then echo "$a contains files that must not be published:"; echo "$bad" | head -20; fail=1; fi mid=$(tar -xzOf "$D/$a.tar.gz" ./etc/machine-id 2>/dev/null || true) @@ -172,9 +170,7 @@ modem/GPU userspace from your own device and adds them during installation. Built from $REPO@$commit with \`kernel/build-all.sh\` and \`tools/make-release.sh\`. Corresponding source (GPL): kernel https://github.com/Enceka/android_kernel_zte_ums9620_mifi_u30air/tree/$kernel_rev , Wi-Fi/Bluetooth/Mali modules https://github.com/realme-kernel-opensource/realme_C51_C53_Narzo-N53-AndroidT-kernel-source/tree/$modules_rev , -patches in \`kernel/patches\`. Ubuntu, OpenWrt and busybox packages come from their distributions' archives; -sing-box from https://github.com/SagerNet/sing-box/releases, Xray from https://github.com/XTLS/Xray-core/releases, -hev-socks5-tunnel from https://github.com/heiher/hev-socks5-tunnel/releases. +patches in \`kernel/patches\`. Ubuntu, OpenWrt and busybox packages come from their distributions' archives. EOF if gh release view "$TAG" -R "$REPO" >/dev/null 2>&1; then gh release upload "$TAG" -R "$REPO" --clobber "$D"/*.tar.gz "$D/mu300-update" "$D/SHA256SUMS" diff --git a/tools/release-ui-policy.py b/tools/release-ui-policy.py new file mode 100644 index 00000000..00365b72 --- /dev/null +++ b/tools/release-ui-policy.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Remove an unused menu parent without altering themes or user plugins.""" +import argparse +import base64 +import hashlib +import json +from pathlib import Path + + +def candidate(name): + name = name.removeprefix('./') + return (name.startswith('usr/share/luci/menu.d/') and name.endswith('.json') + or name == 'lib/apk/db/installed') + + +def apk_database(data, changed): + """Update checksums for the modified menu files, retaining package ownership.""" + lines = data.decode().splitlines(keepends=True) + output, folder, i = [], '', 0 + while i < len(lines): + line = lines[i] + if line.startswith('F:'): + folder = line[2:].strip() + if not line.strip(): + folder = '' + if not line.startswith('R:'): + output.append(line); i += 1; continue + end = i + 1 + while end < len(lines) and lines[end].strip() and not lines[end].startswith(('R:', 'F:')): + end += 1 + name = (folder + '/' + line[2:].strip()).lstrip('/') + record = lines[i:end] + if name in changed: + digest = 'Q1' + base64.b64encode(hashlib.sha1(changed[name]).digest()).decode() + record = [f'Z:{digest}\n' if x.startswith('Z:') else x for x in record] + output.extend(record) + i = end + return ''.join(output).encode() + + +def plan(files): + """Pure transform shared by offline directory and streaming tar builders.""" + removed = set() + changed = {} + menus = {name: json.loads(data) for name, data in files.items() + if name.startswith('usr/share/luci/menu.d/') and name.endswith('.json')} + # Preserve the parent if a user-installed plugin actually needs it. + used = any(key.startswith('admin/vpn/') for menu in menus.values() for key in menu) + for name, menu in menus.items(): + if not used and 'admin/vpn' in menu: + del menu['admin/vpn'] + changed[name] = (json.dumps(menu, ensure_ascii=False, indent=2) + '\n').encode() + database = 'lib/apk/db/installed' + if database in files: + new = apk_database(files[database], changed) + if new != files[database]: + changed[database] = new + return removed, changed + + +def cleanup(root): + root = Path(root).resolve() + files = {} + for directory in ('usr/share/luci/menu.d',): + base = root / directory + if base.exists(): + for path in base.rglob('*'): + name = path.relative_to(root).as_posix() + if candidate(name) and path.is_file(): + if path.is_symlink() or not path.resolve().is_relative_to(root): + raise ValueError('UI resource escapes staging: ' + name) + files[name] = path.read_bytes() + database = root / 'lib/apk/db/installed' + if database.exists(): + if database.is_symlink() or not database.resolve().is_relative_to(root): + raise ValueError('APK database escapes staging') + files['lib/apk/db/installed'] = database.read_bytes() + removed, changed = plan(files) + for name in sorted(removed): + (root / name).unlink() + for name, data in changed.items(): + (root / name).write_bytes(data) + return sorted(removed), sorted(changed) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--root', required=True, type=Path) + args = parser.parse_args() + print(json.dumps(dict(zip(('removed', 'changed'), cleanup(args.root))))) diff --git a/tools/repack-with-diff.py b/tools/repack-with-diff.py index 36055ab2..f3546e98 100644 --- a/tools/repack-with-diff.py +++ b/tools/repack-with-diff.py @@ -10,7 +10,7 @@ import zipfile TOP=Path(__file__).resolve().parents[1] -def repack(source,target,studio,revision): +def repack(source,target,studio,revision,repair_installer=False): if target.exists():raise ValueError('Target release already exists') tool=json.loads((studio/'diff-tool.json').read_text()) patches={} @@ -27,8 +27,18 @@ def repack(source,target,studio,revision): 'Windows: **OpenWrt-Diff-Studio.exe**. Apple Silicon: **OpenWrt-Diff-Studio.app**.\n\n' '完整解压后打开;与安装器共用 tools 目录,请勿单独移动程序。' '使用说明见 [DIFF-STUDIO.md](docs/DIFF-STUDIO.md)。\n').encode() + if repair_installer: + # The external Python entry is loaded by both native hosts. This + # repair changes no firmware or native runtime; do not rebuild them. + patches['START-HERE.md']=old.read('START-HERE.md') + entry=(TOP/'desktop/installer.py').read_bytes() + for name in ('OpenWrt-Installer.py','desktop/installer.py'): + if name not in manifest['desktop']: + raise ValueError('Missing installer entry: '+name) + patches[name]=entry + manifest['source']['installer.py']=hashlib.sha256(entry).hexdigest() payload={n:checks[n] for n in manifest['magisk_layout'].values()} - patches['desktop/TOOLS-REVISION.json']=(json.dumps({'format':1,'kind':'tools-only', + patches['desktop/TOOLS-REVISION.json']=(json.dumps({'format':1,'kind':'installer-entry-repair' if repair_installer else 'tools-only', 'source_commit':revision['source_commit'],'source_fingerprint':revision['source_fingerprint'], 'firmware_unchanged':payload,'base_archive':source.name},indent=2)+'\n').encode() manifest['desktop'].update({n:hashlib.sha256(v).hexdigest() for n,v in patches.items()}) diff --git a/upstream/modules/sprd_modem/sipa_v3/sipa_skb_recv.c b/upstream/modules/sprd_modem/sipa_v3/sipa_skb_recv.c index 6a5ffa9c..9b1608a0 100644 --- a/upstream/modules/sprd_modem/sipa_v3/sipa_skb_recv.c +++ b/upstream/modules/sprd_modem/sipa_v3/sipa_skb_recv.c @@ -790,8 +790,13 @@ static int sipa_fill_recv_thread(void *data) sched_setscheduler(current, SCHED_RR, ¶m); while (!kthread_should_stop()) { - wait_event_interruptible(receiver->fill_recv_waitq, - sipa_check_need_fill_cnt()); + if (wait_event_interruptible(receiver->fill_recv_waitq, + kthread_should_stop() || + (!READ_ONCE(receiver->init_flag) && + sipa_check_need_fill_cnt()))) + continue; + if (kthread_should_stop()) + break; if (sipa_fill_all_free_fifo()) usleep_range(1000, 2000); @@ -800,6 +805,11 @@ static int sipa_fill_recv_thread(void *data) return 0; } +static void sipa_stop_receiver_thread(void *data) +{ + kthread_stop(data); +} + int sipa_receiver_prepare_suspend(struct sipa_skb_receiver *receiver) { int i; @@ -844,7 +854,8 @@ int sipa_receiver_prepare_resume(struct sipa_skb_receiver *receiver) { atomic_set(&receiver->check_suspend, 0); - wake_up_process(receiver->fill_recv_thread); + WRITE_ONCE(receiver->init_flag, false); + wake_up(&receiver->fill_recv_waitq); return sipa_hal_cmn_fifo_stop_recv(receiver->dev, receiver->ep->recv_fifo.idx, @@ -899,6 +910,7 @@ int sipa_create_skb_receiver(struct sipa_plat_drv_cfg *ipa, struct sipa_skb_receiver **receiver_pp) { struct sipa_skb_receiver *receiver = NULL; + int ret; dev_info(ipa->dev, "ep->id = %d start\n", ep->id); receiver = devm_kzalloc(ipa->dev, @@ -910,15 +922,17 @@ int sipa_create_skb_receiver(struct sipa_plat_drv_cfg *ipa, receiver->ep = ep; receiver->rsvd = SIPA_RECV_RSVD_LEN; - sipa_init_recv_array(receiver, - receiver->ep->recv_fifo.rx_fifo.fifo_depth); + ret = sipa_init_recv_array(receiver, + receiver->ep->recv_fifo.rx_fifo.fifo_depth); + if (ret) + return ret; spin_lock_init(&receiver->lock); init_waitqueue_head(&receiver->fill_recv_waitq); sipa_receiver_init(receiver, SIPA_RECV_RSVD_LEN); - receiver->fill_recv_thread = kthread_create(sipa_fill_recv_thread, + receiver->fill_recv_thread = kthread_run(sipa_fill_recv_thread, receiver, "sipa-fill-recv-%d", ep->id); @@ -928,6 +942,10 @@ int sipa_create_skb_receiver(struct sipa_plat_drv_cfg *ipa, ep->id); return PTR_ERR(receiver->fill_recv_thread); } + ret = devm_add_action_or_reset(ipa->dev, sipa_stop_receiver_thread, + receiver->fill_recv_thread); + if (ret) + return ret; *receiver_pp = receiver; return 0; diff --git a/upstream/modules/sprd_modem/sipa_v3/sipa_skb_send.c b/upstream/modules/sprd_modem/sipa_v3/sipa_skb_send.c index 85cd05e8..6fce3920 100644 --- a/upstream/modules/sprd_modem/sipa_v3/sipa_skb_send.c +++ b/upstream/modules/sprd_modem/sipa_v3/sipa_skb_send.c @@ -273,14 +273,29 @@ static int sipa_free_thread(void *data) sched_setscheduler(current, SCHED_RR, ¶m); while (!kthread_should_stop()) { - wait_event_interruptible(sender->free_waitq, - !sipa_sender_ck_unfree(sender) || - sender->free_notify_net); + /* Start the task at probe, but leave the hardware untouched until + * the original resource-resume path enables it. An unwoken + * kthread_create() task otherwise remains in D state indefinitely + * when no SIM registers (and pollutes load/hung-task accounting). + */ + if (wait_event_interruptible(sender->free_waitq, + kthread_should_stop() || + (!READ_ONCE(sender->init_flag) && + (!sipa_sender_ck_unfree(sender) || + sender->free_notify_net)))) + continue; + if (kthread_should_stop()) + break; sipa_free_sent_items(); } return 0; } +static void sipa_stop_sender_thread(void *data) +{ + kthread_stop(data); +} + static int sipa_skb_sender_init(struct sipa_skb_sender *sender) { struct sipa_comm_fifo_params attr; @@ -338,9 +353,9 @@ int sipa_sender_prepare_suspend(struct sipa_skb_sender *sender) int sipa_sender_prepare_resume(struct sipa_skb_sender *sender) { atomic_set(&sender->check_suspend, 0); - if (unlikely(sender->init_flag)) { - wake_up_process(sender->free_thread); - sender->init_flag = false; + if (unlikely(READ_ONCE(sender->init_flag))) { + WRITE_ONCE(sender->init_flag, false); + wake_up(&sender->free_waitq); } return 0; @@ -369,7 +384,6 @@ int sipa_create_skb_sender(struct sipa_plat_drv_cfg *ipa, dev_err(ipa->dev, "alloc sender pair_cache err rx depth = 0x%x\n", ep->send_fifo.rx_fifo.fifo_depth); - kfree(sender); return -ENOMEM; } @@ -388,21 +402,23 @@ int sipa_create_skb_sender(struct sipa_plat_drv_cfg *ipa, atomic_set(&sender->left_cnt, ep->send_fifo.rx_fifo.fifo_depth); - /* reigster sender ipa event callback */ - sipa_skb_sender_init(sender); - init_waitqueue_head(&sender->free_waitq); - sender->free_thread = kthread_create(sipa_free_thread, sender, + /* Register callbacks only after their wait queue is initialized. */ + sipa_skb_sender_init(sender); + + sender->free_thread = kthread_run(sipa_free_thread, sender, "sipa-free-%d", ep->id); if (IS_ERR(sender->free_thread)) { dev_err(sender->dev, "Failed to create kthread: sipa-free-%d\n", ep->id); ret = PTR_ERR(sender->free_thread); - kfree(sender->pair_cache); - kfree(sender); return ret; } + ret = devm_add_action_or_reset(ipa->dev, sipa_stop_sender_thread, + sender->free_thread); + if (ret) + return ret; *sender_pp = sender; @@ -411,8 +427,10 @@ int sipa_create_skb_sender(struct sipa_plat_drv_cfg *ipa, void destroy_sipa_skb_sender(struct sipa_skb_sender *sender) { - kfree(sender->pair_cache); - kfree(sender); + devm_release_action(sender->dev, sipa_stop_sender_thread, + sender->free_thread); + devm_kfree(sender->dev, sender->pair_cache); + devm_kfree(sender->dev, sender); } void sipa_skb_sender_add_nic(struct sipa_skb_sender *sender, diff --git a/upstream/mu300-mainline.config b/upstream/mu300-mainline.config index 06cd06fc..9edb6188 100644 --- a/upstream/mu300-mainline.config +++ b/upstream/mu300-mainline.config @@ -78,6 +78,9 @@ CONFIG_USB_XHCI_HCD=y CONFIG_USB_XHCI_PLATFORM=y CONFIG_SCSI=y CONFIG_BLK_DEV_SD=y +CONFIG_SCSI_UFSHCD=y +CONFIG_SCSI_UFSHCD_PLATFORM=y +CONFIG_SCSI_UFS_SPRD_QOGIRN6PRO=y CONFIG_USB_STORAGE=y CONFIG_USB_UAS=y CONFIG_HID_SUPPORT=y diff --git a/upstream/port/drivers/ufs/host/ufs-sprd-qogirn6pro.c b/upstream/port/drivers/ufs/host/ufs-sprd-qogirn6pro.c new file mode 100644 index 00000000..6fac72c3 --- /dev/null +++ b/upstream/port/drivers/ufs/host/ufs-sprd-qogirn6pro.c @@ -0,0 +1,879 @@ +/* + * Copyright (C) 2018 Spreadtrum Communications Inc. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* UMS9620/QogirN6Pro port from ZTE U30 Air vendor driver. + * Preserve PHY calibration and Hibern8 clock/refclk sequencing. + * RPMB and optional inline crypto belong to the mainline UFS core, not the + * vendor 5.4 private callbacks. OpenWrt root does not use Android FBE keys. + */ +#include +#include +#include +#include +#include "ufshcd-pltfrm.h" +#include +#include "ufs-sprd-qogirn6pro.h" +#include +#include + +/** + * ufs_sprd_rmwl - read modify write into a register + * @base - base address + * @mask - mask to apply on read value + * @val - actual value to write + * @reg - register address + */ +static inline void ufs_sprd_rmwl(void __iomem *base, u32 mask, u32 val, u32 reg) +{ + u32 tmp; + + tmp = readl((base) + (reg)); + tmp &= ~mask; + tmp |= (val & mask); + writel(tmp, (base) + (reg)); +} + +static int ufs_efuse_calib_data(struct platform_device *pdev, + const char *cell_name, u32 *calib_data) +{ + struct nvmem_cell *cell; + void *buf; + size_t len; + + if (!pdev) + return -EINVAL; + + cell = nvmem_cell_get(&pdev->dev, cell_name); + if (IS_ERR_OR_NULL(cell)) + return PTR_ERR(cell); + + buf = nvmem_cell_read(cell, &len); + if (IS_ERR_OR_NULL(buf)) { + nvmem_cell_put(cell); + return PTR_ERR(buf); + } + + if (len != sizeof(*calib_data)) { + kfree(buf); + nvmem_cell_put(cell); + return -EINVAL; + } + *calib_data = get_unaligned_le32(buf); + + kfree(buf); + nvmem_cell_put(cell); + return 0; +} + +static int ufs_sprd_reset(struct ufs_sprd_host *host) +{ + int ret; + dev_info(host->hba->dev, "ufs hardware reset!\n"); + + regmap_update_bits(host->phy_sram_ext_ld_done.regmap, + host->phy_sram_ext_ld_done.reg, + host->phy_sram_ext_ld_done.mask, + host->phy_sram_ext_ld_done.mask); + + regmap_update_bits(host->phy_sram_bypass.regmap, + host->phy_sram_bypass.reg, + host->phy_sram_bypass.mask, + host->phy_sram_bypass.mask); + + ret = reset_control_assert(host->aon_apb_ufs_rst); + if (ret) { + dev_err(host->hba->dev, "%s assert ufsdev_soft_rst failed, ret = %d!\n", + __func__, ret); + goto out; + } + + ret = reset_control_assert(host->ap_ahb_ufs_rst); + if (ret) { + dev_err(host->hba->dev, "%s assert ufs_soft_rst failed, ret = %d!\n", + __func__, ret); + goto out; + } + + usleep_range(1000, 1100); + + ret = reset_control_deassert(host->aon_apb_ufs_rst); + if (ret) { + dev_err(host->hba->dev, "%s deassert ufsdev_soft_rst failed, ret = %d!\n", + __func__, ret); + goto out; + } + + ret = reset_control_deassert(host->ap_ahb_ufs_rst); + if (ret) { + dev_err(host->hba->dev, "%s deassert ufs_soft_rst failed, ret = %d!\n", + __func__, ret); + goto out; + } + +out: + return ret; +} + +static int ufs_sprd_get_syscon_reg(struct device_node *np, + struct syscon_ufs *reg, const char *name) +{ + struct regmap *regmap; + u32 syscon_args[2]; + + regmap = syscon_regmap_lookup_by_phandle_args(np, name, 2, syscon_args); + if (IS_ERR(regmap)) { + pr_err("read ufs syscon %s regmap fail\n", name); + reg->regmap = NULL; + reg->reg = 0x0; + reg->mask = 0x0; + return -EINVAL; + } + reg->regmap = regmap; + reg->reg = syscon_args[0]; + reg->mask = syscon_args[1]; + + return 0; +} + +static void read_ufs_debug_bus(struct ufs_hba *hba) +{ + u32 sigsel, debugbus_data; + struct ufs_sprd_host *host = ufshcd_get_variant(hba); + + if (!host->syssel_reg) { + dev_warn(hba->dev, "can't get ufs debug bus base.\n"); + return; + } + + /* read aon ufs mphy debugbus */ + writel(0x6, host->syssel_reg); + writel(0xD, host->syssel_reg + 0xc); + dev_err(hba->dev, "aon ufs mphy debugbus_data as follow(syssel:0x6, mod_reg:0xD):\n"); + for (sigsel = 0x1; sigsel <= 0x8; sigsel++) { + writel(sigsel, host->syssel_reg + 0x10); + debugbus_data = readl(host->syssel_reg + 0x208); + dev_err(hba->dev, "sig_sel: 0x%x. debugbus_data: 0x%x\n", sigsel, debugbus_data); + } + dev_err(hba->dev, "aon ufs mphy debugbus_data end.\n"); + + /* read ap ufshcd debugbus */ + writel(0x0, host->syssel_reg); + writel(0x0, host->syssel_reg + 0xc); + dev_err(hba->dev, "ap ufshcd debugbus_data as follow(syssel:0x0, mod_reg:0x0):\n"); + for (sigsel = 0x10; sigsel <= 0x12; sigsel++) { + writel(sigsel, host->syssel_reg + 0x10); + debugbus_data = readl(host->syssel_reg + 0x208); + dev_err(hba->dev, "sig_sel: 0x%x. debugbus_data: 0x%x\n", sigsel, debugbus_data); + } + for (sigsel = 0x16; sigsel <= 0x18; sigsel++) { + writel(sigsel, host->syssel_reg + 0x10); + debugbus_data = readl(host->syssel_reg + 0x208); + dev_err(hba->dev, "sig_sel: 0x%x. debugbus_data: 0x%x\n", sigsel, debugbus_data); + } + dev_err(hba->dev, "ap ufshcd debugbus_data end.\n"); +} + +/** + * ufs_sprd_init - find other essential mmio bases + * @hba: host controller instance + * Returns 0 on success, non-zero value on failure + */ +static int ufs_sprd_init(struct ufs_hba *hba) +{ + struct device *dev = hba->dev; + struct platform_device *pdev = to_platform_device(dev); + struct ufs_sprd_host *host; + int ret = 0; + + + host = devm_kzalloc(dev, sizeof(*host), GFP_KERNEL); + if (!host) + return -ENOMEM; + + host->hba = hba; + ufshcd_set_variant(hba, host); + + ret = ufs_efuse_calib_data(pdev, "ufs_cali_lane1", &host->ufs_lane_calib_data1); + if (ret) { + dev_err(&pdev->dev, + "%s:get ufs_lane_calib_data1 failed!\n", __func__); + goto out_variant_clear; + } + + dev_err(&pdev->dev, "%s: ufs_lane_calib_data1: %x\n", + __func__, host->ufs_lane_calib_data1); + + ret = ufs_efuse_calib_data(pdev, "ufs_cali_lane0", &host->ufs_lane_calib_data0); + if (ret) { + dev_err(&pdev->dev, + "%s:get ufs_lane_calib_data1 failed!\n", __func__); + goto out_variant_clear; + } + + dev_err(&pdev->dev, "%s: ufs_lane_calib_data0: %x\n", + __func__, host->ufs_lane_calib_data0); + + host->vdd_mphy = devm_regulator_get(dev, "vdd-mphy"); + if (IS_ERR(host->vdd_mphy)) + return PTR_ERR(host->vdd_mphy); + ret = regulator_enable(host->vdd_mphy); + if (ret) + return -ENODEV; + + ret = ufs_sprd_get_syscon_reg(dev->of_node, &host->phy_sram_ext_ld_done, + "phy_sram_ext_ld_done"); + if (ret < 0) + return -ENODEV; + + ret = ufs_sprd_get_syscon_reg(dev->of_node, &host->phy_sram_bypass, + "phy_sram_bypass"); + if (ret < 0) + return -ENODEV; + + ret = ufs_sprd_get_syscon_reg(dev->of_node, &host->phy_sram_init_done, + "phy_sram_init_done"); + if (ret < 0) + return -ENODEV; + + ret = ufs_sprd_get_syscon_reg(dev->of_node, &host->aon_apb_ufs_clk_en, + "aon_apb_ufs_clk_en"); + if (ret < 0) + return -ENODEV; + + ret = ufs_sprd_get_syscon_reg(dev->of_node, &host->ufsdev_refclk_en, + "ufsdev_refclk_en"); + if (ret < 0) + return -ENODEV; + + ret = ufs_sprd_get_syscon_reg(dev->of_node, + &host->usb31pllv_ref2mphy_en, + "usb31pllv_ref2mphy_en"); + if (ret < 0) + return -ENODEV; + + host->hclk = devm_clk_get(&pdev->dev, "ufs_hclk"); + if (IS_ERR(host->hclk)) { + dev_warn(&pdev->dev, + "can't get the clock dts config: ufs_pclk\n"); + host->hclk = NULL; + } + + host->hclk_source = devm_clk_get(&pdev->dev, "ufs_hclk_source"); + if (IS_ERR(host->hclk_source)) { + dev_warn(&pdev->dev, + "can't get the clock dts config: ufs_hclk_source\n"); + host->hclk_source = NULL; + } + + clk_set_parent(host->hclk, host->hclk_source); + + host->rco_100M = devm_clk_get(&pdev->dev, "ufs_rco_100M"); + if (IS_ERR(host->rco_100M)) { + dev_warn(&pdev->dev, + "can't get the clock dts config: rco_100M\n"); + host->rco_100M = NULL; + } + + host->aon_apb_ufs_rst = devm_reset_control_get(dev, "ufsdev_soft_rst"); + if (IS_ERR(host->aon_apb_ufs_rst)) { + dev_err(dev, "%s get ufsdev_soft_rst failed, err%ld\n", + __func__, PTR_ERR(host->aon_apb_ufs_rst)); + host->aon_apb_ufs_rst = NULL; + return -ENODEV; + } + + host->ap_ahb_ufs_rst = devm_reset_control_get(dev, "ufs_soft_rst"); + if (IS_ERR(host->ap_ahb_ufs_rst)) { + dev_err(dev, "%s get ufs_soft_rst failed, err%ld\n", + __func__, PTR_ERR(host->ap_ahb_ufs_rst)); + host->ap_ahb_ufs_rst = NULL; + return -ENODEV; + } + + + hba->quirks |= UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION | + UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS; + + hba->caps |= UFSHCD_CAP_CLK_GATING | + UFSHCD_CAP_HIBERN8_WITH_CLK_GATING | + UFSHCD_CAP_WB_EN; + + host->syssel_reg = devm_ioremap(dev, REG_DEBUG_BUS_SYSSEL, 0x210); + if (!host->syssel_reg) { + pr_err("error to ioremap ufs debug bus base.\n"); + host->syssel_reg = NULL; + } + + return 0; + +out_variant_clear: + return ret; +} + +/** + * ufs_sprd_hw_init - controller enable and reset + * @hba: host controller instance + */ +static int ufs_sprd_hw_init(struct ufs_hba *hba) +{ + struct ufs_sprd_host *host = ufshcd_get_variant(hba); + + return ufs_sprd_reset(host); +} + +static void ufs_sprd_exit(struct ufs_hba *hba) +{ + struct device *dev = hba->dev; + struct ufs_sprd_host *host = ufshcd_get_variant(hba); + int ret = 0; + + regmap_update_bits(host->aon_apb_ufs_clk_en.regmap, + host->aon_apb_ufs_clk_en.reg, + host->aon_apb_ufs_clk_en.mask, + 0); + + ret = regulator_disable(host->vdd_mphy); + if (ret) + pr_err("disable vdd_mphy failed ret =0x%x!\n", ret); + + devm_kfree(dev, host); + hba->priv = NULL; +} + +static u32 ufs_sprd_get_ufs_hci_version(struct ufs_hba *hba) +{ + return UFSHCI_VERSION_30; +} + +static int ufs_sprd_phy_sram_init_done(struct ufs_hba *hba) +{ + int ret = 0; + uint32_t val = 0; + uint32_t retry = 10; + struct ufs_sprd_host *host = ufshcd_get_variant(hba); + + do { + ret = regmap_read(host->phy_sram_init_done.regmap, + host->phy_sram_init_done.reg, &val); + if (ret < 0) + return ret; + + if ((val&0x1) == 0x1) { + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCREGADDRLSB), 0x1c); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCREGADDRMSB), 0x40); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCREGWRLSB), 0x04); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCREGWRMSB), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCREGRDWRSEL), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(VS_MPHYCFGUPDT), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCREGADDRLSB), 0x1c); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCREGADDRMSB), 0x41); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCREGWRLSB), 0x04); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCREGWRMSB), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCREGRDWRSEL), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(VS_MPHYCFGUPDT), 0x01); + + return 0; + } else { + udelay(1000); + retry--; + } + } while (retry > 0); + return -1; +} + +static int ufs_sprd_phy_init(struct ufs_hba *hba) +{ + int ret = 0; + struct ufs_sprd_host *host = ufshcd_get_variant(hba); + + ufshcd_dme_set(hba, UIC_ARG_MIB(CBREFCLKCTRL2), 0x90); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBCRCTRL), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(RXSQCONTROL, + UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(RXSQCONTROL, + UIC_ARG_MPHY_RX_GEN_SEL_INDEX(1)), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(VS_MPHYCFGUPDT), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(CBRATESEL), 0x01); + + ret = ufs_sprd_phy_sram_init_done(hba); + if (ret) + return ret; + + regmap_update_bits(host->phy_sram_ext_ld_done.regmap, + host->phy_sram_ext_ld_done.reg, + host->phy_sram_ext_ld_done.mask, + 0); + + ufshcd_dme_set(hba, UIC_ARG_MIB(VS_MPHYCFGUPDT), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb0); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x10); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xaf); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x10); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), + (host->ufs_lane_calib_data0 >> 24) & 0xff); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb1); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x10); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb8); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x10); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb0); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x10); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x40); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), + (host->ufs_lane_calib_data0 >> 24) & 0xff); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb0); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x11); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xaf); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x11); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), + (host->ufs_lane_calib_data1 >> 24) & 0xff); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb1); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x11); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb8); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x11); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb0); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x11); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x41); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), + (host->ufs_lane_calib_data1 >> 24) & 0xff); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb0); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x10); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xaf); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x10); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), + (host->ufs_lane_calib_data0 >> 16) & 0xff); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb1); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x10); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x02); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb8); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x10); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb0); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x10); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x40); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), + (host->ufs_lane_calib_data0 >> 16) & 0xff); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb0); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x11); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xaf); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x11); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), + (host->ufs_lane_calib_data1 >> 16) & 0xff); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb1); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x11); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x02); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb8); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x11); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0xb0); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x11); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8116), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8117), 0x41); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8118), + (host->ufs_lane_calib_data1 >> 16) & 0xff); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x8119), 0x00); + ufshcd_dme_set(hba, UIC_ARG_MIB(0x811c), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(0xd085), 0x01); + ufshcd_dme_set(hba, UIC_ARG_MIB(VS_MPHYDISABLE), 0x0); + + return ret; +} + +static int ufs_sprd_hce_enable_notify(struct ufs_hba *hba, + enum ufs_notify_change_status status) +{ + int err = 0; + + switch (status) { + case PRE_CHANGE: + /* Do hardware reset before host controller enable. */ + err = ufs_sprd_hw_init(hba); + if (err) { + dev_err(hba->dev, "%s: ufs hardware init failed!\n", __func__); + return err; + } + hba->capabilities &= ~MASK_AUTO_HIBERN8_SUPPORT; + hba->ahit = 0; + hba->clk_gating.delay_ms = 10; + + break; + case POST_CHANGE: + { + err = ufs_sprd_phy_init(hba); + if (err) { + dev_err(hba->dev, "Phy setup failed (%d)\n", + err); + } + } + break; + default: + dev_err(hba->dev, "%s: invalid status %d\n", __func__, status); + err = -EINVAL; + break; + } + + return err; +} + +static int ufs_sprd_pwr_change_notify(struct ufs_hba *hba, + enum ufs_notify_change_status status, +#if LINUX_VERSION_CODE < KERNEL_VERSION(7, 0, 0) + const struct ufs_pa_layer_attr *dev_max_params, +#endif + struct ufs_pa_layer_attr *dev_req_params) +{ + int err = 0; + + if (!dev_req_params) { + pr_err("%s: incoming dev_req_params is NULL\n", __func__); + err = -EINVAL; + goto out; + } + + switch (status) { + case PRE_CHANGE: +#if LINUX_VERSION_CODE < KERNEL_VERSION(7, 0, 0) + memcpy(dev_req_params, dev_max_params, + sizeof(struct ufs_pa_layer_attr)); +#endif + if (dev_req_params->gear_rx == UFS_HS_G4) + ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXHSADAPTTYPE), 0x0); + break; + case POST_CHANGE: + /* Set auto h8 ilde time to 10ms */ + if (ufshcd_is_auto_hibern8_supported(hba)) { + hba->ahit = AUTO_H8_IDLE_TIME_10MS; + } + break; + default: + err = -EINVAL; + break; + } + +out: + return err; +} + +static void ufs_sprd_hibern8_notify(struct ufs_hba *hba, + enum uic_cmd_dme cmd, + enum ufs_notify_change_status status) +{ + u32 set; + unsigned long flags; + struct ufs_sprd_host *host = ufshcd_get_variant(hba); + + switch (status) { + case PRE_CHANGE: + if (cmd == UIC_CMD_DME_HIBER_ENTER) { + spin_lock_irqsave(hba->host->host_lock, flags); + set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE); + set &= ~UIC_COMMAND_COMPL; + ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE); + spin_unlock_irqrestore(hba->host->host_lock, flags); + + clk_set_parent(host->hclk, host->rco_100M); + ufshcd_writel(hba, 0x64, REG_HCLKDIV); + } + + if (cmd == UIC_CMD_DME_HIBER_EXIT) { + regmap_update_bits(host->ufsdev_refclk_en.regmap, + host->ufsdev_refclk_en.reg, + host->ufsdev_refclk_en.mask, + host->ufsdev_refclk_en.mask); + + regmap_update_bits(host->usb31pllv_ref2mphy_en.regmap, + host->usb31pllv_ref2mphy_en.reg, + host->usb31pllv_ref2mphy_en.mask, + host->usb31pllv_ref2mphy_en.mask); + clk_set_parent(host->hclk, host->hclk_source); + ufshcd_writel(hba, 0x100, REG_HCLKDIV); + } + break; + case POST_CHANGE: + if (cmd == UIC_CMD_DME_HIBER_EXIT) { + spin_lock_irqsave(hba->host->host_lock, flags); + set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE); + set |= UIC_COMMAND_COMPL; + ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE); + spin_unlock_irqrestore(hba->host->host_lock, flags); + } + + if (cmd == UIC_CMD_DME_HIBER_ENTER) { + regmap_update_bits(host->ufsdev_refclk_en.regmap, + host->ufsdev_refclk_en.reg, + host->ufsdev_refclk_en.mask, + 0); + + regmap_update_bits(host->usb31pllv_ref2mphy_en.regmap, + host->usb31pllv_ref2mphy_en.reg, + host->usb31pllv_ref2mphy_en.mask, + 0); + mdelay(2); + } + break; + default: + break; + } +} + +static int ufs_sprd_device_reset(struct ufs_hba *hba) +{ + return 0; +} + +static void ufs_sprd_dbg_register_dump(struct ufs_hba *hba) +{ + read_ufs_debug_bus(hba); +} + +static int ufs_sprd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op, + enum ufs_notify_change_status status) +{ + if (status == PRE_CHANGE) + mdelay(30); + return 0; +} + +static int ufs_sprd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op) +{ + udelay(100); + return 0; +} + +/* + * struct ufs_hba_sprd_vops - UFS sprd specific variant operations + * + * The variant operations configure the necessary controller and PHY + * handshake during initialization. + */ +static struct ufs_hba_variant_ops ufs_hba_sprd_vops = { + .name = "sprd", + .init = ufs_sprd_init, + .exit = ufs_sprd_exit, + .get_ufs_hci_version = ufs_sprd_get_ufs_hci_version, + .hce_enable_notify = ufs_sprd_hce_enable_notify, + .pwr_change_notify = ufs_sprd_pwr_change_notify, + .hibern8_notify = ufs_sprd_hibern8_notify, + .dbg_register_dump = ufs_sprd_dbg_register_dump, + .device_reset = ufs_sprd_device_reset, + .suspend = ufs_sprd_suspend, + .resume = ufs_sprd_resume, +}; + +/** + * ufs_sprd_probe - probe routine of the driver + * @pdev: pointer to Platform device handle + * + * Return zero for success and non-zero for failure + */ +static int ufs_sprd_probe(struct platform_device *pdev) +{ + return ufshcd_pltfrm_init(pdev, &ufs_hba_sprd_vops); +} + +#ifdef CONFIG_PM_SLEEP +static int ufs_pltfrm_sprd_suspend(struct device *dev) +{ + struct ufs_hba *hba = dev_get_drvdata(dev); + struct ufs_sprd_host *host = ufshcd_get_variant(hba); + u32 ufs_pwr_gate = -1; + u32 monitor = -1; + int ret; + + ret = ufshcd_system_suspend(dev); + if (ret) + goto out; + + if (!host->syssel_reg) { + dev_warn(hba->dev, "can't get ufs debug bus base.\n"); + goto out; + } + + writel(0x6, host->syssel_reg); + writel(0x9, host->syssel_reg + 0xc); + writel(0xd1, host->syssel_reg + 0x10); + ufs_pwr_gate = readl(host->syssel_reg + 0x208); + if (unlikely((ufs_pwr_gate & 0x10000000) != 0x0)) + goto check_monitor; + else + goto out; + +check_monitor: + writel(0x0, host->syssel_reg); + writel(0x0, host->syssel_reg + 0xc); + writel(0x18, host->syssel_reg + 0x10); + monitor = readl(host->syssel_reg + 0x208); + if (monitor == 0) { + dev_err(hba->dev, "ufs_pwr_gate:0x%x,monitor:0x%x\n", ufs_pwr_gate, monitor); + ufshcd_system_resume(dev); + ret = -EAGAIN; + } + +out: + return ret; +} +#endif + +/** + * ufs_sprd_remove - set driver_data of the device to NULL + * @pdev: pointer to platform device handle + * + * Always returns 0 + */ +static void ufs_sprd_remove(struct platform_device *pdev) +{ + ufshcd_pltfrm_remove(pdev); +} +static const struct of_device_id ufs_sprd_of_match[] = { + { .compatible = "sprd,ufshc"}, + {}, +}; + +static const struct dev_pm_ops ufs_sprd_pm_ops = { + SET_SYSTEM_SLEEP_PM_OPS(ufs_pltfrm_sprd_suspend, ufshcd_system_resume) + SET_RUNTIME_PM_OPS(ufshcd_runtime_suspend, ufshcd_runtime_resume, NULL) + .prepare = ufshcd_suspend_prepare, + .complete = ufshcd_resume_complete, +}; + +static struct platform_driver ufs_sprd_pltform = { + .probe = ufs_sprd_probe, + .remove = ufs_sprd_remove, + .driver = { + .name = "ufshcd-sprd", + .pm = &ufs_sprd_pm_ops, + .of_match_table = of_match_ptr(ufs_sprd_of_match), + }, +}; +module_platform_driver(ufs_sprd_pltform); + +MODULE_DESCRIPTION("SPRD Specific UFSHCI driver"); +MODULE_LICENSE("GPL v2"); diff --git a/upstream/port/drivers/ufs/host/ufs-sprd-qogirn6pro.h b/upstream/port/drivers/ufs/host/ufs-sprd-qogirn6pro.h new file mode 100644 index 00000000..5c52b61b --- /dev/null +++ b/upstream/port/drivers/ufs/host/ufs-sprd-qogirn6pro.h @@ -0,0 +1,127 @@ + /* + * Copyright (C) 2015-2022 Unisoc Communications Inc. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#ifndef _UFS_SPRD_H_ +#define _UFS_SPRD_H_ + +struct syscon_ufs { + struct regmap *regmap; + u32 reg; + u32 mask; +}; + +struct ufs_sprd_host { + struct ufs_hba *hba; + void __iomem *ufshci_reg; + void __iomem *ufsutp_reg; + void __iomem *unipro_reg; + void __iomem *ufs_ao_reg; + void __iomem *mphy_reg; + void __iomem *rus; + struct regulator *vdd_mphy; + struct syscon_ufs phy_sram_ext_ld_done; + struct syscon_ufs phy_sram_bypass; + struct syscon_ufs phy_sram_init_done; + struct syscon_ufs aon_apb_ufs_clk_en; + struct syscon_ufs ufsdev_refclk_en; + struct syscon_ufs usb31pllv_ref2mphy_en; + + struct clk *hclk_source; + struct clk *rco_100M; + struct clk *hclk; + struct reset_control *ap_ahb_ufs_rst; + struct reset_control *aon_apb_ufs_rst; + uint32_t ufs_lane_calib_data0; + uint32_t ufs_lane_calib_data1; + void __iomem *syssel_reg; +}; + +/*ufs hclk register*/ +#define REG_HCLKDIV 0xFC + +/* Set auto h8 ilde time to 10ms */ +#define AUTO_H8_IDLE_TIME_10MS 0x1001 + +/* UFS host controller vendor specific registers */ +#define REG_SW_RST 0xb0 +#define HCI_RST (1 << 12) +#define HCI_CLOD_RST (1 << 28) + +/* UFS unipro registers */ +#define REG_PA_7 0x1c +#define REDESKEW_MASK (1 << 21) + +#define REG_PA_15 0x3c +#define RMMI_TX_L0_RST (1 << 24) +#define RMMI_TX_L1_RST (1 << 25) +#define RMMI_RX_L0_RST (1 << 26) +#define RMMI_RX_L1_RST (1 << 27) +#define RMMI_CB_RST (1 << 28) +#define RMMI_RST (1 << 29) + +#define REG_PA_27 0x148 +#define RMMI_TX_DIRDY_SEL (1 << 0) + +#define REG_DL_0 0x40 +#define DL_RST (1 << 0) + +#define REG_N_1 0x84 +#define N_RST (1 << 1) + +#define REG_T_9 0xc0 +#define T_RST (1 << 4) + +#define REG_DME_0 0xd0 +#define DME_RST (1 << 2) + +/* UFS utp registers */ +#define REG_UTP_MISC 0x100 +#define TX_RSTZ (1 << 0) +#define RX_RSTZ (1 << 1) + +/* UFS ao registers */ +#define REG_AO_SW_RST 0x1c +#define XTAL_RST (1 << 1) + +/* UFS mphy registers */ +#define REG_DIG_CFG7 0x1c +#define CDR_MONITOR_BYPASS (1 << 24) + +#define REG_DIG_CFG35 0x8c +#define TX_FIFOMODE (1 << 15) + +/* + * Synopsys common M-PHY Attributes + */ +#define CBRATESEL 0x8114 +#define CBCREGADDRLSB 0x8116 +#define CBCREGADDRMSB 0x8117 +#define CBCREGWRLSB 0x8118 +#define CBCREGWRMSB 0x8119 +#define CBCREGRDWRSEL 0x811C +#define CBCRCTRL 0x811F +#define CBREFCLKCTRL2 0x8132 + +/* + *Synopsys RX implementation specific M-PHY Attributes + */ +#define RXSQCONTROL 0x8009 + +#define VS_MPHYDISABLE 0xD0C1 + +#define UFSHCI_VERSION_30 0x00000300 /* 3.0 */ + +/* Define debug bus register */ +#define REG_DEBUG_BUS_SYSSEL 0x7800A100 + +#endif/* _UFS_SPRD_H_ */ diff --git a/upstream/port/install.py b/upstream/port/install.py index dcd0caec..caa9318f 100644 --- a/upstream/port/install.py +++ b/upstream/port/install.py @@ -20,6 +20,16 @@ def append_once(path, marker, text): if marker not in s: open(p, 'w').write(s.rstrip('\n') + '\n' + text) +append_once('drivers/ufs/host/Makefile', 'ufs-sprd-qogirn6pro.o', + 'obj-$(CONFIG_SCSI_UFS_SPRD_QOGIRN6PRO) += ufs-sprd-qogirn6pro.o\n') +append_once('drivers/ufs/host/Kconfig', 'config SCSI_UFS_SPRD_QOGIRN6PRO', + '\nconfig SCSI_UFS_SPRD_QOGIRN6PRO\n' + '\ttristate "Unisoc UMS9620/QogirN6Pro UFS controller"\n' + '\tdepends on SCSI_UFSHCD_PLATFORM && OF && ARCH_SPRD\n' + '\tdepends on COMMON_CLK && RESET_CONTROLLER && REGULATOR && NVMEM\n' + '\tselect MFD_SYSCON\n' + '\thelp\n\t Original U30 Air UFS PHY and power sequence on mainline.\n') + append_once('drivers/misc/Makefile', 'zte-v50-sim.o', 'obj-$(CONFIG_ZTE_V50_SIM) += zte-v50-sim.o\n') append_once('drivers/misc/Kconfig', 'config ZTE_V50_SIM',