openwrt: restore fast F50 boot, modem, Wi-Fi LED and SMS platform

This commit is contained in:
kanoqwq committed 2026-10-01 01:19:35 +08:00
1 parent d7347caa5a
commit cd4fb28ba5
30 files changed
+1701 -127

No files matched your search

+2
View File
@@ -8,3 +8,5 @@
*.tar binary
*.lz4 binary
*.ko binary
# Patch files contain unified-diff context markers followed by source indentation.
kernel/patches/*.patch whitespace=-blank-at-eol,-space-before-tab,-blank-at-eof
@@ -0,0 +1,24 @@
sprd_wlan_combo: restore the PCIe channel table on every power-on
The vendor error path clears sc2355_hif.mchn_ops. A later WCN power-on
can call post_init without rerunning pcie_init, which passes NULL to
mchn_init and leaves Wi-Fi unusable until the next reboot. The table is
static; restore its pointer when registering the channels.
--- a/sc2355/pcie.c
+++ b/sc2355/pcie.c
@@ -2034,6 +2034,14 @@ int pcie_post_init(struct sprd_hif *hif)
int ret = -EINVAL, chn = 0;
sc2355_hif.hif = (void *)hif;
+ /*
+ * A failed/aborted earlier power cycle clears this pointer in the
+ * error path below. The vendor driver only restores it in pcie_init(),
+ * but a later WCN power-on may call post_init directly. Passing
+ * &NULL[0] to mchn_init then makes Wi-Fi permanently fail until reboot.
+ * The channel table is static, so make every post-init self-contained.
+ */
+ sc2355_hif.mchn_ops = sc2355_pcie_hif_ops;
sc2355_hif.max_num =
sizeof(sc2355_pcie_hif_ops) / sizeof(struct mchn_ops_t);
+2 -2
View File
@@ -122,12 +122,12 @@ printf "%s\n" "${MU300_VERSION:-dev}" > $R/etc/mu300/image-version
# enable the services (rc.common "enable" needs ubus, which is not running in the build container)
# accounts still those of the image until an installer or mu300-update puts the device ones in place
: > $R/etc/.mu300-accounts-from-image
for s in mu300-accounts mu300-vendor mu300-hw mu300-post mu300-toolkit mu300-atd mu300-modem-log mu300-wifi-client mu300-buttons; do
for s in mu300-accounts mu300-vendor mu300-hw mu300-post mu300-toolkit mu300-atd mu300-modem-log mu300-wifi-client mu300-buttons mu300-ndp mu300-smsd; do
n=$(sed -n "s/^START=//p" $R/etc/init.d/$s)
ln -sf ../init.d/$s $R/etc/rc.d/S$n$s
done
# busybox PATH is /usr/sbin:/usr/bin:/sbin:/bin, so the commands go into /usr/bin
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; do ln -sf /opt/mu300/bin/$c $R/usr/bin/$c; done
for c in mu300-toolkit mu300-next-boot mu300-os mu300-update mobile-data mu300-at mu300-sms led-status mu300-vpn wifi-client mu300-ttl mu300-wifi-band mu300-led mu300-usb mu300-nfc; do ln -sf /opt/mu300/bin/$c $R/usr/bin/$c; done
# no kernel of its own: OpenWrt kmods (6.12) and grub are unused on this device
rm -rf $R/lib/modules/6.* $R/boot
# out-of-tree modules for the experimental mainline kernel (upstream/)
+11 -19
View File
@@ -1,20 +1,12 @@
# MU300: the ECM gadget was bound in the initramfs; macOS keeps the link inactive after netifd reconfigures usb0
# (at boot and on every network restart). Re-enumerate the gadget whenever the LAN comes up, at most every 20 s,
# so the host starts DHCP on a fresh link.
#!/bin/sh
# Stop the temporary preinit DHCP server only when the real LAN is up.
[ "$ACTION" = ifup ] && [ "$INTERFACE" = lan ] || exit 0
stamp=/tmp/mu300-usb-rebound
now=$(cut -d. -f1 /proc/uptime)
[ -e $stamp ] && [ $((now - $(cat $stamp))) -lt 20 ] && exit 0
echo "$now" > $stamp
C=/sys/kernel/config
grep -q " $C configfs" /proc/mounts || mount -t configfs configfs $C 2>/dev/null
g=$C/usb_gadget/linux
[ -e $g/UDC ] || exit 0
udc=$(cat $g/UDC)
[ -n "$udc" ] || udc=$(ls /sys/class/udc | head -1)
(
sleep 2
echo "" > $g/UDC 2>/dev/null
sleep 1
echo "$udc" > $g/UDC && logger -t mu300 "usb gadget re-enumerated on $udc"
) &
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.
# The final NCM endpoint health check/rebind is a procd one-shot in mu300-post.
# A detached child launched by hotplug can be reaped with the hotplug process;
# keep this hook limited to the deterministic DHCP handoff above.
+61 -4
View File
@@ -1,15 +1,72 @@
#!/bin/sh /etc/rc.common
# keep the modem's AT channel open (closing it wedges the SIPC tty; see /opt/mu300/bin/mu300-atd)
START=91
# Keep the modem's AT channels open (closing a SIPC tty wedges it; see mu300-atd).
#
# The vendor RIL opens three channels per SIM slot (socket_id*3 .. socket_id*3+2):
# nr0/nr1/nr2 = slot 0 group, nr3/nr4/nr5 = slot 1 group, nr31 = engpc.
# Within a group the %3==1 channel (nr1) is the handshake channel (AT+SMMSWAP=0).
# We mirror this: nr1 stays the general-purpose command channel (mu300-at,
# toolkit, diagnostics), and nr2 - the same slot 0 group's third channel - is
# dedicated to mobile-data. During AT+CGDATA's 10-20 s wait on nr2, nr1 stays
# free for signal checks, SMS and everything else.
#
# START=19, not 91. The wan protocol (S20network) dials through mobile-data, and every AT command of
# that dial goes through mu300-at -> one of these daemons. At 91 the daemon did not exist yet while
# netifd ran the first attach, so mu300-at fell back to opening /dev/stty_nr1 directly - and that
# fallback "works once, and then the channel needs a modem restart" (see mu300-at). Then the daemon
# opened the same channel again. Two readers on one SIPC tty is exactly the failure both files warn
# about, so the order was not just slow, it was the wrong side of a documented hazard.
# (V50 开机提速研究实测,见 01-逐文件改动说明.md)
START=19
USE_PROCD=1
export PATH="$PATH:/opt/mu300/busybox-bin"
# wait for a SIPC tty inside the procd command: the nodes appear when the CP is alive, and an init
# script that returns without opening an instance never gets a second chance. Bounded (240 s) so a
# kernel without the modem stack says so instead of spinning silently - procd respawns and retries.
wait_and_exec() {
# $1 = tty node, $2.. = the daemon and its env is set by the caller
local dev=$1; shift
echo "n=0; while [ ! -c $dev ]; do n=\$((n+1)); if [ \"\$n\" -gt 240 ]; then echo 'mu300-atd: $dev never appeared' >&2; exit 1; fi; sleep 1; done; exec $*"
}
start_service() {
[ -c /dev/stty_nr1 ] || return 0
[ -x /opt/mu300/bin/bootmark ] && /opt/mu300/bin/bootmark S19-atd-init
procd_open_instance atd
procd_set_param command /opt/mu300/bin/mu300-atd
procd_set_param command /bin/sh -c "$(wait_and_exec /dev/stty_nr1 /opt/mu300/bin/mu300-atd)"
procd_set_param respawn 3600 10 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
# second instance on nr2 (mobile-data's dedicated channel)
procd_open_instance atd2
procd_set_param command /bin/sh -c "$(wait_and_exec /dev/stty_nr2 /opt/mu300/bin/mu300-atd)"
procd_set_param env MU300_AT_DEV=/dev/stty_nr2 MU300_AT_DIR=/run/mu300-at2 MU300_AT_URC_CHANNELS=
procd_set_param respawn 3600 10 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
# Keep slot 1's nr3/nr4/nr5 open like the vendor RIL does. The optional
# nr6/nr7 channels are the bounded slot-0 dashboard pool; all descriptors
# remain open for the life of the boot so failover never requires a reopen.
for n in 3 4 5 6 7; do
procd_open_instance atd$n
procd_set_param command /bin/sh -c "$(wait_and_exec /dev/stty_nr$n /opt/mu300/bin/mu300-atd)"
procd_set_param env MU300_AT_DEV=/dev/stty_nr$n MU300_AT_DIR=/run/mu300-at$n MU300_AT_URC_CHANNELS=
procd_set_param respawn 3600 10 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
done
# Turn the radio on as soon as nr1's persistent daemon is ready, in a
# separate procd process. This overlaps the remaining rc scripts and leaves
# PDP activation to netifd. The FIFO is the readiness event; mobile-data's
# radio lock excludes a simultaneous dial-up state machine.
procd_open_instance radio-warmup
procd_set_param command /bin/sh -c 'n=0; until [ -p /run/mu300-at/cmd ]; do n=$((n+1)); [ "$n" -gt 90 ] && exit 1; sleep 1; done; exec /opt/mu300/bin/mobile-data radio-on'
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
+12
View File
@@ -13,6 +13,10 @@ boot() {
}
hw_bringup() {
# switch_root terminates initramfs background jobs. Resume the same tracked
# chase immediately and keep it until mu300-post (or an earlier WAN success)
# selects the steady state.
/opt/mu300/bin/led-status boot 2>/dev/null
/opt/mu300/bin/extra-modules >/tmp/mu300-extra-modules.log 2>&1
/opt/mu300/bin/zram-start >/dev/null 2>&1
/opt/mu300/bin/wifi-start >/tmp/mu300-wifi-start.log 2>&1
@@ -27,6 +31,14 @@ hw_bringup() {
iw reg set "$country"
for n in $(seq 1 10); do iw reg get | grep -q "country $country:" && break; sleep 1; done
fi
# netifd may have scanned before the late, external SC2355 driver created
# phy0. Reconcile once immediately when firmware and regulatory data are
# ready; this is readiness-driven and does not leave a polling worker.
# A reload does not restart a hostapd interface that already entered
# AP-DISABLED while the world regulatory domain was still active. One
# down/up transition does, immediately after the requested country is live.
wifi down >>/tmp/mu300-wifi-start.log 2>&1
wifi up >>/tmp/mu300-wifi-start.log 2>&1
}
start() {
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh /etc/rc.common
# Public IPv6 host routes for LAN clients (see /opt/mu300/bin/ndp-learn)
START=99
USE_PROCD=1
start_service() {
procd_open_instance
procd_set_param command /bin/sh /opt/mu300/bin/ndp-learn
procd_set_param respawn 3600 10 0
procd_close_instance
}
+23 -8
View File
@@ -5,12 +5,31 @@ USE_PROCD=1
export PATH="$PATH:/opt/mu300/busybox-bin"
start_service() {
# the host gives up asking for a DHCP lease long before this device finishes booting; if nothing took an
# address, make the gadget re-enumerate once, which looks like a fresh cable to the host
procd_open_instance usb-lease
procd_set_param command /opt/mu300/bin/mu300-usb-reset --if-no-lease 25
# START=99 means the web/LAN services have been started. End the initramfs
# chase now; if WAN is not ready yet the specified steady state is red.
case "$(/opt/mu300/bin/led-status current 2>/dev/null)" in
boot|modem|registering|'') /opt/mu300/bin/led-status offline ;;
esac
procd_open_instance led-events
procd_set_param command /opt/mu300/bin/mu300-led-events
procd_set_param respawn 3600 5 0
procd_close_instance
# The initramfs NCM RX path can work while its TX endpoint is dead: the
# device sees DHCPDISCOVER but Windows never sees DHCPOFFER. Let procd run
# one tracked 100 ms UDC rebind now that br-lan and dnsmasq are ready. This
# is the boot handoff only; PDP/IPv4/IPv6 renewals never touch USB.
procd_open_instance usb-ready
procd_set_param command /opt/mu300/bin/mu300-usb-reset --fast-run
procd_set_param oneshot 1
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
# U30 Air exposes a second function on some kernels. Keep it in the LAN;
# PDP and IPv4/IPv6 lease changes themselves never re-enumerate the gadget.
[ -e /sys/class/net/usb1 ] && ip link set usb1 master br-lan 2>/dev/null && ip link set usb1 up
procd_open_instance cellwatch
procd_set_param command /opt/mu300/bin/mobile-data watch
procd_set_param env MU300_NETIFD=1 PATH="$PATH"
@@ -20,10 +39,6 @@ start_service() {
procd_set_param command /opt/mu300/bin/thermal-guard
procd_set_param env PATH="$PATH"
procd_close_instance
# the SC2355 sometimes refuses the first IFF_UP (EIO); if the AP did not come up, try once more
procd_open_instance wifiretry
procd_set_param command /bin/sh -c "sleep 45; [ -e /sys/class/net/wlan0 ] || exit 0; ubus call hostapd.wlan0 get_status >/dev/null 2>&1 || { logger -t mu300-post 'AP not up, retrying'; wifi up; sleep 15; }; ubus call hostapd.wlan0 get_status >/dev/null 2>&1 && /opt/mu300/bin/mu300-led wifi on"
procd_close_instance
procd_open_instance bootok
procd_set_param command /bin/sh -c "sleep 30; exec /opt/mu300/bin/mu300-next-boot --rearm"
procd_set_param env PATH="$PATH"
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh /etc/rc.common
# keep the local SMS pool in step with the SIM (see /opt/mu300/bin/mu300-smsd)
START=95
USE_PROCD=1
export PATH="$PATH:/opt/mu300/busybox-bin"
start_service() {
[ -c /dev/stty_nr1 ] || return 0
procd_open_instance smsd
procd_set_param command /opt/mu300/bin/mu300-smsd
# /var is tmpfs on OpenWrt; the pool is small and worth keeping across reboots
procd_set_param env MU300_SMS_POOL=/etc/mu300/sms
procd_set_param respawn 3600 10 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
+16 -2
View File
@@ -1,6 +1,17 @@
#!/bin/sh /etc/rc.common
# Android vendor services in a chroot: modem_control (PM watchdog + modem boot), cp_diskserver (modem NV), refnotify
START=11
#
# START=9, not 11. This service has exactly one job on the boot path: release the CP so it can start booting.
# The CP then needs about fifteen seconds before its AT channel answers, so every second this starts earlier
# is a second off "the modem is on the network". Sitting behind S00sysfixtime/S00urngd/S10boot/S10system cost
# 1.4 s (boot-timeline: preinit-end 6.95 -> S11-vendor-init 8.40). At 9 it runs right after urngd.
# Everything it touches is already there once preinit is done (/dev, /proc, /sys, /opt, /run), and it waits
# for /dev/modem or /dev/pmsys for up to 90 s by itself, so running earlier cannot make it wrong.
# (V50 开机提速研究实测,见 01-逐文件改动说明.md)
# Keep the leading zero: rc.common embeds START verbatim in the rc.d link.
# S9 sorts after S19 lexically and delayed CP bring-up by about 31 seconds;
# S09 runs before the AT daemons and network as intended.
START=09
USE_PROCD=1
export PATH="$PATH:/opt/mu300/busybox-bin"
@@ -10,6 +21,7 @@ start_service() {
# wait for it themselves (android-vendor-start waits for /dev/modem, android-run for the chroot).
[ -f /lib/modules/$(uname -r)/sipc-core.ko ] || [ -e /dev/modem ] || [ -e /dev/pmsys ] || {
logger -t mu300-vendor "no modem stack in $(uname -r)"; return 0; }
/opt/mu300/bin/bootmark S09-vendor-init
# the NV server first: the modem asks for its data while it boots, and a modem that does not get it
# stalls with "wait modem alive timeout" (this is what kept the mainline kernel without a modem)
procd_open_instance cp_diskserver
@@ -19,7 +31,9 @@ start_service() {
procd_close_instance
procd_open_instance modem_control
procd_set_param command /bin/sh -c "sleep 5; exec /opt/mu300/bin/android-vendor-start"
# The helper already waits on the actual modem nodes. Start it immediately so
# CP bring-up and registration are not held back by an unconditional delay.
procd_set_param command /opt/mu300/bin/android-vendor-start
procd_set_param env PATH="$PATH"
procd_set_param respawn 3600 10 0
procd_set_param stdout 1
+57 -2
View File
@@ -2,26 +2,81 @@
# First boot: one LAN for USB and Wi-Fi (192.168.77.1/24 on an F50, 192.168.78.1/24 on a U30 Air), cellular WAN through the modem, hostname, USB console.
# lan ip6assign 64: a carrier hands out one /64 (the wan_6 that mu300cell adds), and the default /60 request
# would leave the LAN without IPv6
usb_host_mac=$(tr -d '\000\r\n' < /sys/kernel/config/usb_gadget/linux/functions/ncm.usb0/host_addr 2>/dev/null)
[ -n "$usb_host_mac" ] || usb_host_mac='02:50:00:00:77:03'
lan_ip=$(/opt/mu300/bin/mu300-lan-ip)
usb_host_ip=${lan_ip%.*}.200
uci -q batch <<UCI
set system.@system[0].hostname='mu300'
set system.@system[0].zonename='Europe/Istanbul'
set system.@system[0].timezone='<+03>-3'
set network.lan.ipaddr='$(/opt/mu300/bin/mu300-lan-ip)'
set network.lan.ipaddr='$lan_ip'
set network.lan.netmask='255.255.255.0'
set network.lan.ip6assign='64'
delete network.wan6
set network.wan=interface
set network.wan.proto='mu300cell'
set network.wan.apn=''
set network.wan.pdptype='IPV4V6'
UCI
# IPv6 the way this carrier actually serves it (China Telecom IoT, measured): the context is
# dual-stack but CGCONTRDP only ever shows a placeholder - the real public address arrives by
# SLAAC from the carrier's RA on the bearer, and clients get that same /64 relayed onto the LAN.
# - wan.pdptype IPV4V6 + mu300cell.sh enable accept_ra=2 on the bearer (the RA is solicited)
# - dhcp.wan master: odhcpd relays RS/RA both ways between the LAN and wan, so clients
# SLAAC real public addresses out of the carrier's /64 (no separate wan6 interface is
# needed - the relay master just needs to point at the interface that owns sipa_eth0)
# - firewall masq6: egress NAT66 through the device's own public address (the carrier routes
# one address per bearer; Android's tethering does the same)
# - lan ip6assign + a ULA: a local range for the LAN itself
# - ndp-learn (init.d/mu300-ndp) pins host routes for each client public address: without
# them NAT66 replies follow sipa_eth0's connected /64 and never reach the client
uci -q batch <<UCI
set network.lan.ip6assign='60'
set network.globals.ula_prefix='fd66:1126:7956::/48'
set dhcp.wan=dhcp
set dhcp.wan.interface='wan'
set dhcp.wan.master='1'
set dhcp.wan.ra='relay'
set dhcp.wan.dhcpv6='relay'
set dhcp.wan.ndp='relay'
set dhcp.lan.ra='relay'
set dhcp.lan.dhcpv6='relay'
set dhcp.lan.ndp='relay'
# Windows can keep requesting the initramfs lease while it has already removed
# that IPv4 address. A unicast DHCPOFFER to the removed address then disappears
# in the NCM host stack. Pin the USB host and tag its OFFER/ACK for broadcast.
set dhcp.mu300_usb=host
set dhcp.mu300_usb.name='mu300-usb-host'
set dhcp.mu300_usb.mac='$usb_host_mac'
set dhcp.mu300_usb.ip='$usb_host_ip'
set dhcp.mu300_usb.broadcast='1'
UCI
zone=$(uci -q show firewall | sed -n "s/^\(firewall\.@zone\[[0-9]*\]\)\.name='wan'$/\1/p")
[ -n "$zone" ] && uci -q set $zone.masq6='1'
# Before netifd creates br-lan, the early management address lives directly on
# usb0. Give that local-only path the same input policy as LAN; forwarding stays
# blocked, and once bridged packets enter through br-lan as usual.
early=$(uci -q show firewall | sed -n "s/^\(firewall\.@zone\[[0-9]*\]\)\.name='earlyusb'$/\1/p")
if [ -z "$early" ]; then
early=$(uci add firewall zone)
uci set firewall.$early.name='earlyusb'
uci add_list firewall.$early.device='usb0'
uci set firewall.$early.input='ACCEPT'
uci set firewall.$early.output='ACCEPT'
uci set firewall.$early.forward='REJECT'
fi
# the armsr default bridges eth0; the MU300 LAN bridge carries the USB gadget (Wi-Fi joins via wireless config)
dev=$(uci -q show network | sed -n "s/^network\.\(@device\[[0-9]*\]\)\.name='br-lan'$/\1/p" | head -1)
if [ -n "$dev" ]; then
uci -q delete network.$dev.ports
uci add_list network.$dev.ports='usb0'
uci add_list network.$dev.ports='rndis0' # the gadget's RNDIS configuration (Windows)
# Do not wait for the wireless bridge member before creating the wired LAN.
uci set network.$dev.bridge_empty='1'
fi
uci commit system
uci commit network
uci commit dhcp
uci commit firewall
grep -q '^ttyGS0:' /etc/inittab || echo 'ttyGS0::askfirst:/usr/libexec/login.sh' >> /etc/inittab
exit 0
+70 -29
View File
@@ -2,6 +2,15 @@
# netifd protocol for the MU300 modem: attach with AT commands (mobile-data) and configure sipa_eth0.
# /etc/config/network: config interface 'wan' / option proto 'mu300cell' / option apn 'internet'
# LuCI edits the same options through www/luci-static/resources/protocol/mu300cell.js.
#
# The bearer's kernel state is owned here, not by netifd: every update is sent
# address-external, so netifd tracks addresses, routes and DNS for display and
# firewall purposes but never installs or removes them. A mixed mode (netifd
# installing the v4 during setup, the monitor later reporting external) makes
# netifd delete the address it installed the moment the first external report
# arrives - the mobile-data watchdog then saw an address-less WAN and redialled
# every 60 s. mobile-data's netifd path leaves the interface alone; this script
# and mu300cell-v6.sh are the only writers.
[ -n "$INCLUDE_ONLY" ] || {
. /lib/functions.sh
. ../netifd-proto.sh
@@ -11,6 +20,7 @@
proto_mu300cell_init_config() {
available=1
no_device=1
renew_handler=1
proto_config_add_string "apn"
proto_config_add_string "pdptype"
proto_config_add_boolean "peerdns"
@@ -33,7 +43,6 @@ proto_mu300cell_setup() {
if [ -z "$ip" ]; then
logger -t mu300cell "attach failed: $(cat /tmp/mu300cell.err)"
proto_notify_error "$config" ATTACH_FAILED
sleep 20
proto_setup_failed "$config"
return 1
fi
@@ -44,7 +53,42 @@ proto_mu300cell_setup() {
iid=$(echo "$out" | sed -n 's/^IID6=//p')
ip link set "$ifname" up
proto_init_update "$ifname" 1
# This carrier's RAs give INFINITE address lifetimes: after a redial on a
# new prefix the old SLAAC address never expires and prefixes stack up
# (same for the default route a previous dial left behind). Clear the last
# dial's v6 state; RS/RA re-establishes it within ~1 s. Also fine for
# v4-only bearers - there is nothing to keep either way.
ip -6 addr flush dev "$ifname" scope global 2>/dev/null
ip -6 route flush dev "$ifname" 2>/dev/null
# netifd treats this as a v4 protocol, so forwarding leaves accept_ra at 0. Enable
# IPv6 and accept RAs before waiting for the carrier address. The monitor below
# reports the initial RA and all later address/route lifetime refreshes.
if [ "${pdptype:-IP}" != IP ]; then
# The 1->0 cycle restarts addrconf entirely: the link-local on-link
# route is rebuilt (a bare route flush leaves it missing and stops RA
# processing) and a fresh router solicitation goes out, so the global
# address returns about a second after the flush above.
[ -w "/proc/sys/net/ipv6/conf/$ifname/disable_ipv6" ] && {
echo 1 > "/proc/sys/net/ipv6/conf/$ifname/disable_ipv6"
echo 0 > "/proc/sys/net/ipv6/conf/$ifname/disable_ipv6"
}
[ -w "/proc/sys/net/ipv6/conf/$ifname/accept_ra" ] && {
echo 0 > "/proc/sys/net/ipv6/conf/$ifname/accept_ra"
echo 2 > "/proc/sys/net/ipv6/conf/$ifname/accept_ra"
}
fi
# Install the bearer address ourselves (external updates are never applied by
# netifd). Replace-first keeps an unchanged address continuous across
# re-setups; anything else the carrier left behind is removed after it.
ip -4 addr replace "$ip/${prefix:-32}" dev "$ifname" 2>/dev/null ||
ip -4 addr add "$ip/${prefix:-32}" dev "$ifname"
local a
for a in $(ip -4 -o addr show dev "$ifname" scope global | awk '{print $4}'); do
[ "$a" = "$ip/${prefix:-32}" ] || ip -4 addr del "$a" dev "$ifname" 2>/dev/null
done
ip -4 route replace default dev "$ifname"
proto_init_update "$ifname" 1 1
proto_add_ipv4_address "$ip" "${prefix:-32}"
proto_add_ipv4_route "0.0.0.0" 0
if [ "${peerdns:-1}" != 0 ]; then
@@ -52,39 +96,36 @@ proto_mu300cell_setup() {
[ -n "$dns2" ] && proto_add_dns_server "$dns2"
fi
proto_send_update "$config"
if [ -n "$iid" ]; then
# The network assigned IPv6. Link-local from its interface identifier, as 3GPP has the UE do, then
# odhcp6c learns the /64 from the router advertisement; extendprefix hands that single /64 to the LAN,
# where odhcpd advertises it (lan ip6assign 64) - the same as uqmi does for QMI modems.
ip -6 addr add "fe80::$iid/64" dev "$ifname" 2>/dev/null
zone=$(fw4 -q network "$config" 2>/dev/null)
json_init
json_add_string name "${config}_6"
json_add_string ifname "@$config"
json_add_string proto dhcpv6
json_add_string reqaddress none
json_add_string reqprefix no
json_add_boolean extendprefix 1
[ -n "$zone" ] && json_add_string zone "$zone"
proto_add_dynamic_defaults
json_close_object
ubus call network add_dynamic "$(json_dump)"
else
# After proto_send_update, not before: netifd turns IPv6 back on as it configures the interface,
# so mobile-data setting this itself has no effect on OpenWrt. The bearer is IPv4-only, and an
# interface left with a link-local address sends router solicitations and multicast into it for
# nothing. See docs/FINDINGS.md 13f.
[ -w "/proc/sys/net/ipv6/conf/$ifname/disable_ipv6" ] &&
echo 1 > "/proc/sys/net/ipv6/conf/$ifname/disable_ipv6"
fi
/opt/mu300/bin/mu300-led data on
# The event-driven child is the protocol task netifd owns. It reports IPv6
# netlink changes and CGEV-triggered IPv4/DNS changes without holding setup.
[ "${pdptype:-IP}" != IP ] && proto_run_command "$config" \
/lib/netifd/proto/mu300cell-v6.sh "$config" "$ifname" "$ip" \
"${prefix:-32}" "$dns1" "$dns2" "${peerdns:-1}"
[ "${pdptype:-IP}" = IP ] && [ -w "/proc/sys/net/ipv6/conf/$ifname/disable_ipv6" ] &&
echo 1 > "/proc/sys/net/ipv6/conf/$ifname/disable_ipv6"
logger -t mu300cell "connected: $ip/${prefix:-32} on $ifname"
}
proto_mu300cell_renew() {
# Standard netifd renew: ask the existing event monitor to re-read the
# bearer. It updates in place; it does not cycle CGACT or restart the link.
local sigusr1="$(kill -l SIGUSR1)"
[ -n "$sigusr1" ] && proto_kill_command "$1" "$sigusr1"
}
proto_mu300cell_teardown() {
local config="$1"
/opt/mu300/bin/mobile-data down >/dev/null 2>&1
proto_kill_command "$config"
/opt/mu300/bin/mobile-data down >/dev/null 2>&1
# External state is not removed by netifd on ifdown, so clean the bearer
# ourselves - both families. v6 must go too: this carrier's RAs carry
# INFINITE lifetimes, so an unflushed SLAAC address (and the default route
# an earlier report installed) would survive every redial and stack up.
# sipa_eth0 is the one bearer this hardware has (mobile-data assumes it too).
ip -4 addr flush dev sipa_eth0 scope global 2>/dev/null
ip -4 route del default dev sipa_eth0 2>/dev/null
ip -6 addr flush dev sipa_eth0 scope global 2>/dev/null
ip -6 route flush dev sipa_eth0 2>/dev/null
}
[ -n "$INCLUDE_ONLY" ] || add_protocol mu300cell
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
# Keep the USB host usable across switch_root. The initramfs DHCP server only
# lives for ~0.6 s after NCM binds, which is shorter than Windows needs to load
# its driver and ask for a lease. Restart it immediately in the real rootfs;
# the LAN ifup hook stops it when dnsmasq/netifd take ownership.
#
# The lease is one hour, not the initramfs's ten minutes. The host keeps the
# early lease until dnsmasq answers a fresh request. The final dnsmasq host
# entry broadcasts its OFFER/ACK, so Windows can complete that handoff even if
# it has already removed the old address; no USB re-enumeration is involved.
# The config is written here rather than reused from the initramfs so this file
# alone decides the pool and lease time.
mu300_early_usb() {
[ -e /sys/class/net/usb0 ] || return 0
/opt/mu300/bin/led-status boot 2>/dev/null
/opt/mu300/bin/busybox ifconfig usb0 192.168.77.1 netmask 255.255.255.0 up
cat > /run/udhcpd-usb0.conf <<'EOF'
start 192.168.77.200
end 192.168.77.200
interface usb0
option subnet 255.255.255.0
option router 192.168.77.1
option lease 3600
lease_file /run/udhcpd-usb0.leases
EOF
/opt/mu300/bin/busybox udhcpd -f /run/udhcpd-usb0.conf >/dev/null 2>&1 &
echo $! > /run/mu300-early-udhcpd.pid
}
boot_hook_add preinit_essential mu300_early_usb
+37
View File
@@ -0,0 +1,37 @@
#!/bin/sh
# Event-driven reconciliation for state changes that are not owned by
# mobile-data. No fixed startup sleeps: hostapd/netifd readiness drives it.
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
wifi_state() {
if ubus call hostapd.wlan0 get_status 2>/dev/null | grep -q '"status": "ENABLED"'; then
led-status wifi-on
else
led-status wifi-off
fi
}
network_state() {
if ubus call network.interface.wan status 2>/dev/null | grep -q '"up": true'; then
case "$(led-status current 2>/dev/null)" in
online-4g) led-status online-4g; return ;;
online-5g) led-status online-5g; return ;;
esac
act=$(mu300-at -t 3 'AT+CEREG?' 2>/dev/null | grep '+CEREG:' | head -1 | awk -F, '{print $NF}' | tr -d '" ')
case "$act" in
11|12|13|15) led-status online-5g ;;
*) led-status online-4g ;;
esac
else
led-status offline
fi
}
network_state
wifi_state
ubus listen 2>/dev/null | while IFS= read -r event; do
case "$event" in
*network.interface*) network_state ;;
*network.wireless*|*hostapd*) wifi_state ;;
esac
done
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
# Watch the LAN for public SLAAC addresses (odhcpd relay hands the carrier's /64 to
# clients) and pin a host route for each one. Without it, a reply coming back through
# NAT66 follows sipa_eth0's connected /64 route and dies on the wrong interface -
# measured: ICMP 100% loss, TCP connect timeouts, until the /128 exists.
while :; do
for a in $(ip -6 neigh show dev br-lan 2>/dev/null | cut -d' ' -f1 |
grep -E '^[23][0-9a-f]*:'); do
ip -6 route show "$a/128" 2>/dev/null | grep -q 'dev br-lan' ||
ip -6 route add "$a/128" dev br-lan 2>/dev/null
done
# self-heal the bearer's own public address: the carrier's RA can be missed while the
# bearer settles after boot, and nothing else ever re-solicits - flip accept_ra to send
# a fresh router solicitation whenever the bearer has no global address
if ! ip -6 addr show sipa_eth0 2>/dev/null | grep -q 'scope global'; then
echo 0 > /proc/sys/net/ipv6/conf/sipa_eth0/accept_ra 2>/dev/null
sleep 1
echo 2 > /proc/sys/net/ipv6/conf/sipa_eth0/accept_ra 2>/dev/null
fi
sleep 10
done
@@ -3,14 +3,24 @@
# PM co-processor watchdog cuts power ~290 s after boot. See linux-boot/STATUS.md (v9).
set -e
A=/opt/mu300/android
mark() { [ -x /opt/mu300/bin/bootmark ] && /opt/mu300/bin/bootmark "$@" || true; }
mark vendor-start
# wait for the modem stack: on the mainline kernel the modules are loaded by userspace (see extra-modules), so
# this service can start before /dev/modem exists
for n in $(seq 1 90); do
[ -e /dev/modem ] || [ -e /dev/pmsys ] || { sleep 1; continue; }
break
done
mark vendor-stack-present
mkdir -p /dev/socket /dev/block/by-name
[ -S /dev/socket/logdw ] || { /opt/mu300/bin/logdw /dev/socket/logdw >> /var/log/android-logcat.txt 2>&1 & sleep 1; }
# No need to wait for logdw's socket. modem_control is still more than a second away (the chroot mounts, the
# node ownership and the cmdline bind all come first), and /dev is rbind-mounted into the chroot, so a socket
# that appears late shows up in $A/dev just the same. The old flat "sleep 1" was a second of the boot waiting
# for nothing - it actually did wait it out on two of three measured boots (boot-timeline: vendor-start 8.31
# -> vendor-props 9.33).
if [ ! -S /dev/socket/logdw ]; then
/opt/mu300/bin/logdw /dev/socket/logdw >> /var/log/android-logcat.txt 2>&1 &
fi
# bind the read-only Android property area instead of copying it: it is ~85 MiB (RAM on tmpfs) and OpenWrt's /dev
# is a 512 KiB tmpfs, where the copy silently ends up as empty files and modem_control never boots the modem
if ! [ -s /dev/__properties__/property_info ]; then
@@ -18,13 +28,20 @@ if ! [ -s /dev/__properties__/property_info ]; then
mkdir -p /dev/__properties__
mount --bind $A/dev-properties /dev/__properties__
fi
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
d=$(basename "$(dirname "$u")")
n=$(sed -n 's/^PARTNAME=//p' "$u")
[ -e "$u" ] || continue
d=${u%/uevent}; d=${d##*/}
n=
while IFS='=' read -r k v; do [ "$k" = PARTNAME ] && n=$v; done < "$u"
ln -sfn /dev/$d /dev/block/$d
[ -n "$n" ] && ln -sfn /dev/$d /dev/block/by-name/$n
done
sh /opt/mu300/bin/ueventd-perms.sh
mark vendor-perms
for m in dev proc sys; do mkdir -p $A/$m; done
mkdir -p $A/data/vendor $A/mnt $A/tmp
mountpoint -q $A/dev || mount --rbind /dev $A/dev
@@ -41,4 +58,5 @@ mount --bind /run/mu300-cmdline.android $A/proc/cmdline
# OpenWrt's procd preloads /lib/libsetlbf.so into services; the bionic linker in the chroot cannot load it
unset LD_PRELOAD
export LD_LIBRARY_PATH=/apex/com.android.runtime/lib64/bionic:/system/lib64:/vendor/lib64
mark vendor-chroot-ready
exec chroot $A /vendor/bin/modem_control
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# 开机里程碑记录。服务侧的里程碑(谁在几秒启动、射频什么时候开、什么时候注册上)由各服务自己用
# /opt/mu300/bin/bootmark 写进 /etc/mu300/boot-timeline.txt;这个脚本只补「结果侧」的三条,
# 然后立刻退出。
#
# 它**一个 AT 命令都不发**:mu300-at 的锁是全局的($DIR/lock),开机时任何 AT 轮询都会把拨号
# 自己的命令挤到后面(第一版探针就是这样凭空造出 43 s 的假延迟,见 docs/FINDINGS.md §43)。
# OpenWrt 由 /etc/rc.local 拉起,Ubuntu 由 mu300-boot-milestones.service 拉起,只活到 DNS 通为止。
f=/etc/mu300/boot-timeline.txt
mark() { printf 't=%-9s %s\n' "$(cut -d' ' -f1 /proc/uptime)" "$*" >>"$f" 2>/dev/null; }
i=0
while [ "$i" -lt 180 ]; do
ip -4 addr show sipa_eth0 2>/dev/null | grep -q 'inet ' && { mark "milestone-iface-ip"; break; }
sleep 1; i=$((i + 1))
done
i=0
while [ "$i" -lt 30 ]; do
ip route | grep -q '^default dev sipa_eth0' && { mark "milestone-route"; break; }
sleep 1; i=$((i + 1))
done
i=0
while [ "$i" -lt 60 ]; do
nslookup www.qq.com >/dev/null 2>&1 && { mark "milestone-dns-ok 真正可上网"; break; }
sleep 1; i=$((i + 1))
done
exit 0
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# 开机时间线打点。只做一件事:把 /proc/uptime 记到 /etc/mu300/boot-timeline.txt。
# 故意不依赖 procd/netifd/systemd,preinit 钩子里也能用;每条都是一个进程一次短写,
# 多进程并发追加不会互相撕行。
# (来自 V50 开机提速研究的现役实现,测量方法见 01-逐文件改动说明.md)
f=/etc/mu300/boot-timeline.txt
[ "${1:-}" = "-r" ] && { : >"$f"; shift; }
printf 't=%-9s %s\n' "$(cut -d' ' -f1 /proc/uptime)" "$*" >>"$f" 2>/dev/null
exit 0
+8 -1
View File
@@ -27,7 +27,14 @@ fi
# Both places: OpenWrt keeps the modules flat in $M, the Ubuntu image under $M/extra. Looking only in $M meant
# the delegate was never started on Ubuntu, and Ubuntu had no mobile data downlink at all.
if { [ -f "$M/sipa-dele.ko" ] || [ -f "$M/extra/sipa-dele.ko" ]; } && ! grep -q '^sipa_dele ' /proc/modules; then
/opt/mu300/bin/sipa-dele-start >/tmp/mu300-sipa-dele.log 2>&1 &
if [ -f /etc/openwrt_release ]; then
# mobile-data inserts it synchronously after registration and before
# CGACT. A background loader can race PDP activation and panic inside
# the delegate probe when SIPA resources are already active.
:
else
/opt/mu300/bin/sipa-dele-start >/tmp/mu300-sipa-dele.log 2>&1 &
fi
fi
# The PM co-processor keeps its own watchdog, and it power-cuts the device a few minutes after boot unless this
+162
View File
@@ -0,0 +1,162 @@
#!/bin/sh
# MU300/V50 status LED controller.
#
# The F50 has three LED channels under sc27xx:*, where "green" is physically WHITE
# (verified: the vendor's own userspace treats it as white). The V50 has separate
# /sys/class/leds/{red,white,blue}/ paths. This script auto-detects both.
#
# States (one multi-color LED, priority order):
# boot red/white/blue chase - Linux is booting
# online-4g solid blue - data connected, LTE
# online-5g solid white - data connected, 5G NR
# offline solid red - booted, no data
# thermal red blink - SoC above 85C (overrides network color)
# wifi-on WiFi lamp on - independent from the exact network colour
#
# Usage: led-status <state> set a state
# led-status wifi-on/off remember the hotspot state
# led-status current print the last set state
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
# --- detect LED paths (F50 sc27xx vs V50 plain)
if [ -d /sys/class/leds/sc27xx:blue ]; then
LED_R=/sys/class/leds/sc27xx:red/brightness
LED_W=/sys/class/leds/sc27xx:green/brightness # physically white on the F50
LED_B=/sys/class/leds/sc27xx:blue/brightness
elif [ -d /sys/class/leds/blue ]; then
LED_R=/sys/class/leds/red/brightness
LED_W=/sys/class/leds/white/brightness
LED_B=/sys/class/leds/blue/brightness
else
exit 0
fi
[ -w "$LED_B" ] || exit 0
# On the F50 the keyboard-backlight class is the separate hotspot indicator.
# Do not use it on the U30 Air: that model assigns the same class to another
# front-panel function. Keeping this separate also guarantees that LTE stays
# pure blue (B=255, R=W=0), 5G pure white and offline pure red.
WIFI_LED=
if [ "$(mu300-device 2>/dev/null)" = f50 ] && [ -w /sys/class/leds/keyboard-backlight/brightness ]; then
WIFI_LED=/sys/class/leds/keyboard-backlight/brightness
fi
STATE_FILE=/run/led-status.state
WIFI_FILE=/run/led-status.wifi
BLINK_PID=/run/led-status.blink.pid
# Status reads must be side-effect free. In particular, dashboards and event
# handlers may query this during boot and must not stop the chase animation.
if [ "${1:-}" = current ]; then
cat "$STATE_FILE" 2>/dev/null || echo boot
exit 0
fi
# WiFi changes must not cancel the boot chase, thermal alarm, or modem/network
# animation. They only drive the F50's independent hotspot lamp.
case "${1:-}" in
wifi-on|wifi-off)
[ "${1:-}" = wifi-on ] && wifi_state=on || wifi_state=off
echo "$wifi_state" > "$WIFI_FILE"
if [ -n "$WIFI_LED" ]; then
echo none > "$(dirname "$WIFI_LED")/trigger" 2>/dev/null
[ "$wifi_state" = on ] && echo 127 > "$WIFI_LED" || echo 0 > "$WIFI_LED"
fi
exit 0 ;;
esac
# stop any previous user-space blinker
[ -f "$BLINK_PID" ] && kill "$(cat "$BLINK_PID")" 2>/dev/null
rm -f "$BLINK_PID"
# clear hardware triggers (a trigger left on would fight our brightness writes)
for f in $(dirname "$LED_R")/trigger $(dirname "$LED_W")/trigger $(dirname "$LED_B")/trigger; do
echo none > "$f" 2>/dev/null
done
set_rgb() { # R W B (0-255)
echo "${1:-0}" > "$LED_R" 2>/dev/null
echo "${2:-0}" > "$LED_W" 2>/dev/null
echo "${3:-0}" > "$LED_B" 2>/dev/null
}
pause_us() {
# The rootfs intentionally does not install every BusyBox applet symlink.
# Invoke the bundled binary directly so missing `usleep` cannot turn an LED
# animation into a CPU-burning tight loop.
/opt/mu300/bin/busybox usleep "$1" 2>/dev/null && return 0
command -v usleep >/dev/null 2>&1 && usleep "$1" 2>/dev/null && return 0
sleep 1
}
start_blink() { # R W B ON_MS OFF_MS
_r=$1; _w=$2; _b=$3; _on=$4; _off=$5
(
while :; do
echo "$_r" > "$LED_R" 2>/dev/null
echo "$_w" > "$LED_W" 2>/dev/null
echo "$_b" > "$LED_B" 2>/dev/null
pause_us "$_on"
echo 0 > "$LED_R" 2>/dev/null
echo 0 > "$LED_W" 2>/dev/null
echo 0 > "$LED_B" 2>/dev/null
pause_us "$_off"
done
) &
echo $! > "$BLINK_PID"
}
start_chase() {
(
while :; do
echo 255 > "$LED_R" 2>/dev/null; echo 0 > "$LED_W" 2>/dev/null; echo 0 > "$LED_B" 2>/dev/null; pause_us 120000
echo 0 > "$LED_R" 2>/dev/null; echo 255 > "$LED_W" 2>/dev/null; echo 0 > "$LED_B" 2>/dev/null; pause_us 120000
echo 0 > "$LED_R" 2>/dev/null; echo 0 > "$LED_W" 2>/dev/null; echo 255 > "$LED_B" 2>/dev/null; pause_us 120000
done
) &
echo $! > "$BLINK_PID"
}
# Restore the exact steady-state network colour. The F50 exposes one RGB lamp,
# so mixing a WiFi tint here makes LTE look cyan and offline look orange.
restore_steady() {
state=$(cat "$STATE_FILE" 2>/dev/null || echo offline)
case "$state" in
online-4g) set_rgb 0 0 255 ;;
online-5g) set_rgb 0 255 0 ;;
offline) set_rgb 255 0 0 ;;
*) set_rgb 0 0 255 ;;
esac
}
case "${1:-}" in
boot) # visible chase throughout boot
echo boot > "$STATE_FILE"
set_rgb 0 0 0
start_chase ;;
modem) # slow blue blink: CP initializing
echo modem > "$STATE_FILE"
set_rgb 0 0 0
start_blink 0 0 255 500000 500000 ;;
registering) # white blink: registering on the network
echo registering > "$STATE_FILE"
set_rgb 0 0 0
start_blink 0 255 0 300000 300000 ;;
online-4g) # solid blue: LTE data
echo online-4g > "$STATE_FILE"
restore_steady ;;
online-5g) # solid white: 5G NR data
echo online-5g > "$STATE_FILE"
restore_steady ;;
offline) # solid red: no data
echo offline > "$STATE_FILE"
restore_steady ;;
thermal) # red blink: SoC too hot (called by thermal-guard)
start_blink 255 0 0 200000 200000 ;;
current)
cat "$STATE_FILE" 2>/dev/null || echo boot ;;
*)
echo "usage: $0 boot|modem|registering|online-4g|online-5g|offline|thermal|wifi-on|wifi-off|current" >&2
exit 1 ;;
esac
+253 -27
View File
@@ -1,6 +1,6 @@
#!/bin/bash
# Mobile data on the MU300 modem without Android RIL: AT commands on /dev/stty_nr1, data over sipa_eth<cid-1>.
# usage: mobile-data up [APN] | down | status | signal | at "CMD" | sim-reset | watch
# usage: mobile-data up [APN] | radio-on | down | status | signal | at "CMD" | sim-reset | watch
# MU300_NETIFD=1 mobile-data up [APN]: only attach and print IFACE/IP/PREFIX/DNS1/DNS2 (OpenWrt netifd protocol)
# OpenWrt: od/timeout come from the static busybox in /opt/mu300/busybox-bin
export PATH="$PATH:/opt/mu300/busybox-bin"
@@ -8,6 +8,7 @@ set -euo pipefail
DEV=${MU300_AT_DEV:-/dev/stty_nr1}
CID=1
IFACE=sipa_eth$((CID - 1))
DEVICE=$(/opt/mu300/bin/mu300-device 2>/dev/null || echo f50)
# The blue LED only reports whether data is up. The PMIC rejects a brightness write now and then (seen as
# "write error: Invalid argument"), and under `set -e` that killed up() one line before it could report the
@@ -18,12 +19,28 @@ led() { /opt/mu300/bin/mu300-led data "$1" 2>/dev/null || true; }
# data is up: the LED tells 4G from 5G as ZTE's firmware does (the U30 Air: blue on 4G, white on 5G). The access
# technology changes under a live connection, so the watchdog asks again on every round.
led_up() {
case $(at 'AT+COPS?' 4 | sed -n 's/^+COPS: [0-9],[0-9],"[^"]*",\([0-9]*\).*/\1/p') in
11|12|13) led 5g ;;
*) led on ;;
# CEREG is a short local-status read; COPS can take about two seconds on
# weak service and used to hold an AT channel on every watchdog round.
# F50's legacy mu300-led maps both 4G and 5G to blue, so only led-status
# may drive its RGB lamp. U30 Air keeps its separate legacy network LEDs.
act=$(at 'AT+CEREG?' 4 2>/dev/null | grep '+CEREG:' | head -1 | awk -F, '{print $NF}' | tr -d '" ')
case "$act" in
11|12|13|15)
led-status online-5g 2>/dev/null || true
[ "$DEVICE" = u30air ] && led 5g
;;
*)
led-status online-4g 2>/dev/null || true
[ "$DEVICE" = u30air ] && led on
;;
esac
}
# radio.log:radio_on 的每一步决策都留一行,重启后可以逐行对账(V50 开机提速研究,docs/FINDINGS.md §43)。
radio_say() { printf 't=%-9s %s\n' "$(cut -d' ' -f1 /proc/uptime)" "$*" >>/etc/mu300/radio.log 2>/dev/null || true; }
# 开机时间线打点:bootmark 把 /proc/uptime 追加到 /etc/mu300/boot-timeline.txt
mark() { [ -x /opt/mu300/bin/bootmark ] && /opt/mu300/bin/bootmark "$@" || true; }
ATLOCK=/run/mu300-at/owner
# Is that pid a live process that holds the AT channel? mu300-atd and the direct path below both write their
@@ -35,8 +52,15 @@ at_owner_alive() {
at() { # at CMD [timeout] -> response lines up to the final result code
local cmd=$1 t=${2:-5} line owner
# mu300-atd owns the AT channel when it runs: closing the SIPC tty wedges it until the modem restarts, so
# ask the daemon instead of opening the device here
# mobile-data gets its own AT channel (nr2, same slot-0 group as nr1): AT+CGDATA
# blocks its channel for 10-20 s, and having it on the shared nr1 made every other
# AT user (toolkit signal checks, SMS) wait behind it. The nr2 daemon serves only
# this script, so the dial-up sequence never contends with anything.
if [ -p /run/mu300-at2/cmd ]; then
MU300_AT_DIR=/run/mu300-at2 /opt/mu300/bin/mu300-at -t "$t" "$cmd"
return
fi
# fall through to the shared nr1 daemon when the nr2 one is not running yet
if [ -p /run/mu300-at/cmd ]; then
/opt/mu300/bin/mu300-at -t "$t" "$cmd"
return
@@ -207,15 +231,156 @@ v6_off() {
# Make sure the radio is on (CFUN=1). SFUN=4 alone is enough from any state; the off/on cycle is the last resort,
# because an interrupted cycle used to leave the radio switched off with nothing to turn it back on.
radio_on() {
at 'AT+CFUN?' 4 | grep -q '+CFUN: 1' && return 0
at 'AT+SFUN=4' 15 >/dev/null || true
at 'AT+CFUN?' 4 | grep -q '+CFUN: 1' && return 0
# 开机这一段踩过两个坑(V50 开机提速研究的实测,docs/FINDINGS.md §43),顺序是按实测重排的:
# 1) modem_control 把 CP 放出来之后,SIPC 的 AT 口要十几秒才通,实测第一次回话是
# "+CFUN: 0" —— 射频关着。所以在拿到回话之前一个小命令都不要发:发出去没人接,
# 只会把自己和后面排队的命令一起拖住(mu300-at 的全局锁)。
# 2) 旧代码是「AT+SFUN=4 之后立刻问一次 CFUN?,问不到就跳到 SFUN=2 + SFUN=4 的断电重启」。
# 实测那一步会把刚起来的 CP 又清一次,白等一整轮 CP 启动(12 s 起)。SFUN=4 之后要等
# 射频真正上来,而不是问一次就走。
radio_on_locked() {
local i=0 out silent=0 answered=0 urclog=/run/mu300-at/urc/stty_nr0.log
local ready_deadline=$((SECONDS + ${MU300_CFUN_WAIT:-30}))
mark radio-on-enter
# CP readiness is announced on nr0. Wait on that event source before taking
# the command-channel lock; repeatedly sending CFUN? while CP is still
# booting only queues timeouts and starves the other AT clients.
while [ "$SECONDS" -lt "$ready_deadline" ]; do
[ -s "$urclog" ] && break
sleep 0.2 2>/dev/null || sleep 1
done
# Android's slot-0 RIL opens nr0/nr1/nr2 and makes SMMSWAP=0 the first
# command on nr1. Do the same once per boot, before CFUN or any dial-up
# command. Reuse the existing readiness budget: failure ends this round
# immediately instead of adding another wait or sending recovery commands
# into a channel that has not completed its RIL handshake.
if [ ! -e /run/mu300-ril-handshake ]; then
# A dashboard/watch probe can own the client mutex for a fraction of a
# second as nr1 becomes ready. Give that collision one second instead
# of abandoning this boot attempt and waiting for netifd's next retry.
out=$(MU300_AT_LOCK_WAIT=1 MU300_AT_DIR=/run/mu300-at \
/opt/mu300/bin/mu300-at -t 4 'AT+SMMSWAP=0' 2>&1 || true)
case "$out" in
*OK*)
: > /run/mu300-ril-handshake
radio_say "slot0 RIL 握手完成(AT+SMMSWAP=0)"
mark ril-handshake-done
;;
*)
radio_say "slot0 RIL 握手无有效回应,本轮立即结束:$(echo "${out:-无回答}" | tr -s '\n' ' ')"
return 1
;;
esac
fi
out=$(at 'AT+CFUN?' 4 2>&1 || true)
case "$out" in
*"+CFUN: 1"*) return 0 ;;
*"+CFUN: 0"*) ;;
*)
radio_say "AT 通道没有回应,停止本轮,不向死通道发送 SFUN:$(echo "${out:-无回答}" | tr -s '\n' ' ')"
return 1 ;;
esac
radio_say "AT 通道已就绪,射频为 0;发送 SFUN=4"
at 'AT+SFUN=4' "${MU300_SFUN_TIMEOUT:-20}" >/dev/null || true
i=0
while [ "$i" -lt "${MU300_CFUN_UP_WAIT:-30}" ]; do
out=$(at 'AT+CFUN?' 4 2>&1 || true)
case "$out" in
*"+CFUN: 1"*) radio_say "AT+SFUN=4 之后 ${i}s 射频到 1"; return 0 ;;
*"+CFUN:"*) answered=1; silent=0 ;;
*) silent=$((silent + 1)) ;;
esac
# A vanished command channel cannot execute the recovery commands. Stop
# promptly and let the outer watcher retry instead of burning minutes.
[ "$silent" -ge 2 ] && { radio_say "SFUN=4 后 AT 通道沉默,快速结束本轮"; return 1; }
sleep 2; i=$((i + 2))
done
[ "$answered" = 1 ] || return 1
radio_say "AT+SFUN=4 之后 ${i}s 射频仍然不是 1,走最后的断电重启(SFUN=2 -> SFUN=4)"
at 'AT+SFUN=2' 5 >/dev/null || true
at 'AT+SFUN=4' 20 >/dev/null || true
at 'AT+CFUN?' 4 | grep -q '+CFUN: 1'
}
# The early radio warm-up and netifd may meet at the boundary. Serialize that
# small window so they never run two CFUN/SFUN state machines in parallel.
# The collision wait is capped at eight seconds; netifd can retry later.
radio_on() {
local lock=/run/mu300-radio-on.lock owner= n=0 rc
while ! mkdir "$lock" 2>/dev/null; do
owner=$(cat "$lock/pid" 2>/dev/null || true)
if [ -z "$owner" ] || [ ! -d "/proc/$owner" ] ||
! tr '\0' ' ' < "/proc/$owner/cmdline" 2>/dev/null | grep -q mobile-data; then
rm -rf "$lock"
continue
fi
n=$((n + 1))
[ "$n" -gt 80 ] && return 1
/opt/mu300/bin/busybox sleep 0.1 2>/dev/null || sleep 1
done
echo $$ > "$lock/pid"
radio_on_locked
rc=$?
[ "$(cat "$lock/pid" 2>/dev/null)" = $$ ] && rm -rf "$lock"
return $rc
}
# 取 PDP 地址。AT+CGACT? 回答 1,1 并不等于地址已经下发:实测在 NR 上有过「CGACT 通了之后
# 40 s 还不给地址」的情况(开机那次第一次拨号就是这么失败的)。所以这里可以反复问,失败时由
# 调用方决定怎么办。
# 成功时把 +CGCONTRDP 那一行留在全局 rdp 里(后面的解析继续用它)。
# 预算是真实秒。按轮数算的话「8」会变成 4 轮 —— 每轮是一条 AT 往返(实测约 2 s)加 sleep 2,
# 也就是 17 s 才放弃。这里的每一秒都算在开机时间里,所以到点就走。
fetch_addr() { # $1 = 预算秒(真实秒,不是轮数)
local lim=${1:-8} end line am
rdp=
end=$((SECONDS + lim))
while [ "$SECONDS" -lt "$end" ]; do
line=$(at "AT+CGCONTRDP=$CID" 4 2>&1 | grep '^+CGCONTRDP:' | head -1 || true)
am=$(echo "$line" | cut -d, -f4 | tr -d '"')
case "$am" in
''|0.0.0.0*) : ;;
*.*.*.*) rdp=$line; return 0 ;;
esac
sleep 2
done
return 1
}
is_registered() {
# Query form: +CEREG: <n>,<stat>,...; unsolicited form: +CEREG: <stat>,...
grep -qE '^\+CEREG: (1|5)(,|$)|^\+CEREG: [0-9]+,(1|5)(,|$)'
}
wait_registered() {
local urclog=/run/mu300-at/urc/stty_nr0.log out start size
local deadline=$((SECONDS + ${MU300_REGISTER_WAIT:-60}))
local next_query=$SECONDS
# nr0 reports registration changes immediately. Watch only bytes appended
# after this point so an old registered URC cannot be mistaken for the
# current state. A low-rate query is the fallback for a carrier that emits
# no URC; this replaces the old 0.3 s AT+CEREG? flood.
size=$(wc -c < "$urclog" 2>/dev/null || echo 0)
start=$((size + 1))
while [ "$SECONDS" -lt "$deadline" ]; do
size=$(wc -c < "$urclog" 2>/dev/null || echo 0)
[ "$size" -lt "$start" ] && start=1
if [ -f "$urclog" ] && tail -c +"$start" "$urclog" 2>/dev/null | is_registered; then
return 0
fi
if [ "$SECONDS" -ge "$next_query" ]; then
out=$(at 'AT+CEREG?' 3 2>&1 || true)
echo "$out" | is_registered && return 0
next_query=$((SECONDS + 5))
fi
sleep 0.2 2>/dev/null || sleep 1
done
return 1
}
# The modem needs the vendor modem loader/SIPC drivers (5.4 kernel); a kernel without them (mainline) has no modem.
modem_stack() { [ -e /dev/modem ] || [ -e /dev/pmsys ] || [ -c "$DEV" ]; }
@@ -258,13 +423,30 @@ up_locked() {
rm -f /run/mu300-mobile-data-down
tty_setup
radio_on
for n in $(seq 1 60); do
at 'AT+CEREG?' | grep -qE '\+CEREG: [0-9],(1|5)' && break
# the radio can be switched off again meanwhile (modem reset), so re-check it every 10 s
[ $((n % 5)) -eq 0 ] && radio_on
sleep 2
done
at 'AT+CEREG?' | grep -qE '\+CEREG: [0-9],(1|5)' || { led error; echo "not registered on the network" >&2; exit 1; }
mark dial-radio-on-done
# Android's RIL enables the IMS bearer used by SMS. This is idempotent;
# keep it on the normal radio bring-up path and do not wait for IMS here.
at 'AT+CAVIMS=1' 5 >/dev/null || true
wait_registered || { echo "not registered on the network" >&2; exit 1; }
mark dial-registered
radio_say "注册完成"
# sipa_dele must probe after the CP packet domain exists but before the PDP
# resource graph becomes active. Loading it later raced CGACT and produced
# a reproducible CFI panic in sipa_delegate. extra-modules deliberately
# leaves this step to us on OpenWrt so the order is deterministic.
_m=/lib/modules/$(uname -r)
if { [ -f "$_m/sipa-dele.ko" ] || [ -f "$_m/extra/sipa-dele.ko" ]; } &&
! grep -q '^sipa_dele ' /proc/modules; then
MU300_DELE_WAIT=20 /opt/mu300/bin/sipa-dele-start >/tmp/mu300-sipa-dele.log 2>&1 || {
echo "sipa delegate did not become ready; refusing unsafe PDP activation" >&2
exit 1
}
grep -q '^sipa_dele ' /proc/modules || {
echo "sipa delegate load returned without a module" >&2
exit 1
}
fi
# systemd has no way to pass an argument from a config file, so the APN can come from the environment too:
# /etc/mu300/mobile-data.conf is an EnvironmentFile for the service. The argument still wins, which is what
# the OpenWrt protocol handler uses.
@@ -277,8 +459,22 @@ up_locked() {
# MU300_PDP_TYPE=IPV4V6 asks for both again, for a carrier that needs it.
at "AT+CGDCONT=$CID,\"${MU300_PDP_TYPE:-IP}\",\"$1\"" >/dev/null
fi
at "AT+CGACT?" | grep -q "+CGACT:$CID,1" || at "AT+CGACT=1,$CID" 20 >/dev/null
rdp=$(at "AT+CGCONTRDP=$CID" 4 | grep '^+CGCONTRDP:' | head -1)
# 不再先问一次 AT+CGACT?:开机时上下文一定是关的,问那一趟是一条整 AT 往返(实测约 2 s),
# 而 CGACT=1 对已经激活的上下文是幂等的(重拨、watch 重连就是这种情况),所以问不问结果一样。
at "AT+CGACT=1,$CID" 20 >/dev/null
mark dial-pdp-active
# 激活成功不等于地址已经下发。Do not cycle CGACT=0/1 here: two measured
# boots showed that tearing down the just-created context made the AT
# channel silent and held WAN pending for minutes. Reasserting CGACT=1 is
# idempotent and nudges the existing context without resetting the CP. Keep
# both phases bounded; this path is at most 16 s instead of the old 57 s.
if ! fetch_addr "${MU300_ADDR_WAIT_FIRST:-8}"; then
radio_say "CGACT 已激活但暂未下发地址;幂等重发一次,不切断 PDP"
at "AT+CGACT=1,$CID" 8 >/dev/null || true
fetch_addr "${MU300_ADDR_WAIT_RETRY:-8}" || {
echo "no IPv4 address from AT+CGCONTRDP after bounded CGACT reassert" >&2; exit 1; }
fi
mark dial-addr-ok
# +CGCONTRDP: cid,bearer,apn,"a.b.c.d.m.m.m.m",gw,dns1,dns2,...
addrmask=$(echo "$rdp" | cut -d, -f4 | tr -d '"')
ip4=$(echo "$addrmask" | cut -d. -f1-4)
@@ -296,8 +492,28 @@ up_locked() {
# carries a link-local address and sends router solicitations and multicast into a bearer that is IPv4 only
# (FINDINGS 13f). With one, v6_up below (systemd) or the proto handler (OpenWrt) sets it up.
# On OpenWrt this is undone a moment later - netifd turns IPv6 back on while it configures the interface -
# so the proto handler repeats it after proto_send_update.
[ -n "$iid" ] || v6_off
# so the proto handler repeats it after proto_send_update. Here it is for the systemd path, which configures
# the interface itself and where it sticks.
if [ "${MU300_PDP_TYPE:-IP}" = IP ] && [ -w "/proc/sys/net/ipv6/conf/$IFACE/disable_ipv6" ]; then
echo 1 > "/proc/sys/net/ipv6/conf/$IFACE/disable_ipv6"
fi
# IPV4V6: the carrier's RA is the only way this bearer ever gets its IPv6 address - measured on
# China Telecom IoT (ctiot): CGCONTRDP/CGPADDR keep a ::1-style placeholder forever even with the
# context active AND CGDATA connected, but with accept_ra enabled the kernel solicits and the
# GGSN answers with a real 240e::/20 prefix (SLAAC, default route included). 2, not 1: this is a
# router (forwarding on), and netifd leaves the knob at 0 for a v4-only proto.
if [ "${MU300_PDP_TYPE:-IP}" != IP ]; then
[ -w "/proc/sys/net/ipv6/conf/$IFACE/disable_ipv6" ] && echo 0 > "/proc/sys/net/ipv6/conf/$IFACE/disable_ipv6"
[ -w "/proc/sys/net/ipv6/conf/$IFACE/accept_ra" ] && echo 2 > "/proc/sys/net/ipv6/conf/$IFACE/accept_ra"
fi
# Select the steady network colour before returning to netifd. Previously
# this lived after the return, so every OpenWrt connection stayed forever
# in the earlier "modem" blink state.
act=$(at 'AT+CEREG?' 2>/dev/null | grep '+CEREG:' | head -1 | awk -F',' '{print $NF}' | tr -d '" ')
case "$act" in
11|12|13|15) led-status online-5g 2>/dev/null || true ;;
*) led-status online-4g 2>/dev/null || true ;;
esac
if [ "${MU300_NETIFD:-0}" = 1 ]; then
# OpenWrt: netifd (proto mu300cell) configures the address, routes, DNS and firewall itself
printf 'IFACE=%s\nIP=%s\nPREFIX=%s\nDNS1=%s\nDNS2=%s\nIID6=%s\n' "$IFACE" "$ip4" "$prefix" "$dns1" "$dns2" "$iid"
@@ -329,14 +545,15 @@ table ip mu300_nat {
}
}
NFT
[ -n "$iid" ] && v6_up "$iid"
led_up
echo "mobile data up on $IFACE ($(at 'AT+COPS?' | sed -n 's/^+COPS: [0-9],[0-9],"\([^"]*\)".*/\1/p'))"
# 运营商名字是一条 AT 往返(实测约 2 s),不影响能不能上网:成功回话在关键路径上打印,
# 运营商那半句挪到后台的 radio.log(V50 开机提速研究的「收尾 AT 后台化」)。
echo "mobile data up on $IFACE ($ip4/$prefix)"
( radio_say "运营商 $(at 'AT+COPS?' 4 2>&1 | tr -s '\n' ' ' || true)" ) >/dev/null 2>&1 &
}
down() {
touch /run/mu300-mobile-data-down # tells watch not to reconnect
led off
led-status offline 2>/dev/null
nft delete table ip mu300_nat 2>/dev/null || true
v6_off
ip route del default dev "$IFACE" 2>/dev/null || true
@@ -410,7 +627,8 @@ watch() {
fails=$((fails + 1))
[ "$fails" -lt 2 ] && continue
echo "mobile data lost (modem reset or detached), reconnecting" >&2
led off
led-status offline 2>/dev/null || true
[ "$DEVICE" = u30air ] && led off
if [ "${MU300_NETIFD:-0}" = 1 ]; then
ifup "${MU300_WAN:-wan}" # OpenWrt: let netifd run the mu300cell protocol again
else
@@ -471,6 +689,14 @@ status() {
case "${1:-status}" in
up) up "${2:-}" ;;
radio-on)
modem_stack || exit 3
tty_setup
mark radio-warmup-enter
radio_on
at 'AT+CAVIMS=1' 5 >/dev/null || true
mark radio-warmup-done
;;
signal) signal ;;
at) [ -n "${2:-}" ] || { echo "usage: $0 at \"AT+COMMAND\"" >&2; exit 2; }
tty_setup; at "$2" "${3:-6}" ;;
@@ -478,5 +704,5 @@ case "${1:-status}" in
status) status ;;
sim-reset) sim_reset ;;
watch) watch ;;
*) echo "usage: $0 up [APN] | down | status | signal | at \"CMD\" | sim-reset | watch" >&2; exit 2 ;;
*) echo "usage: $0 up [APN] | radio-on | down | status | signal | at \"CMD\" | sim-reset | watch" >&2; exit 2 ;;
esac
+36 -9
View File
@@ -42,7 +42,7 @@ if [ -p "$DIR/cmd" ]; then
rm -rf "$lock"; continue
fi
n=$((n + 1)); [ "$n" -gt $((wait * 10)) ] && { echo "mu300-at: busy" >&2; exit 1; }
sleep 0.1 2>/dev/null || sleep 1
sleep 0.1 2>/dev/null || /opt/mu300/bin/busybox sleep 0.1 2>/dev/null || sleep 1
done
echo $$ > "$lock/pid" 2>/dev/null || true
trap 'rm -rf "$lock" 2>/dev/null' EXIT INT TERM
@@ -51,18 +51,45 @@ if [ -p "$DIR/cmd" ]; then
answer=$DIR/answer.$$
rm -f "$answer" "$answer.part"
trap 'rm -rf "$lock" "$answer" "$answer.part" 2>/dev/null' EXIT INT TERM
if command -v timeout >/dev/null 2>&1; then
timeout $((T + 6)) sh -c 'printf "%s %s %s\n" "$1" "$2" "$3" > "$4"' _ "$T" "$answer" "$cmd" "$DIR/cmd" || {
echo "mu300-at: the daemon is not reading commands" >&2; exit 1; }
else
printf '%s %s %s\n' "$T" "$answer" "$cmd" > "$DIR/cmd"
fi
# write to the daemon's command fifo. The old `timeout N sh -c 'printf ...'` wrapper
# cost 200+ ms per command (two forks + timer setup on this SoC, visible only when
# the whole thing ran inside a CGI where every fork's pipe-close is waited for by
# uhttpd). The daemon is always reading this fifo, so the write completes in
# microseconds; if the daemon is dead the client hits its own answer-file timeout
# below, which is the same outcome the timeout wrapper was trying to avoid.
# Open the FIFO read-write. A write-only open blocks until a reader opens
# the *same inode*. If procd replaces the daemon between the path lookup and
# that open, the client and the new daemon wait forever on two different,
# unlinked FIFOs while this client keeps the global command lock. O_RDWR
# never blocks; with no daemon the answer timeout below releases the lock.
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; }
exec 9>&-
n=0
# fast poll: the daemon typically writes the answer in ~20 ms, so a 1 s sleep
# here adds a full second to every AT round trip. The system /bin/sleep (busybox
# applet) rejects fractional arguments on this image ("invalid number"), which
# quietly sank the chain below into `sleep 1` - every command cost a flat
# second (measured: 30 commands in 30.6 s). The static busybox next to us
# accepts fractions; use it when present.
zz=$([ -x /opt/mu300/bin/busybox ] && echo /opt/mu300/bin/busybox || echo sleep)
while [ ! -e "$answer" ]; do
n=$((n + 1))
[ "$n" -gt $(( (T + 8) * 10 )) ] && { echo "mu300-at: no answer from the daemon" >&2; exit 1; }
sleep 0.1 2>/dev/null || sleep 1
[ "$n" -gt $(( (T + 1) * 100 )) ] && { echo "mu300-at: no answer from the daemon" >&2; exit 1; }
"$zz" sleep 0.01 2>/dev/null || "$zz" sleep 0.1 2>/dev/null || sleep 1
done
# atd always creates the answer file, including for a timeout. An empty
# file is therefore not success: callers such as atwatch use the exit code
# to distinguish a responding channel from a silent one.
# A timed-out daemon can leave CR/LF or an echoed fragment in the answer
# file. Success requires a real final result code; otherwise callers must
# be able to fail over instead of accepting a blank/partial frame.
grep -aEq '^(OK|ERROR|\+CME ERROR|\+CMS ERROR|CONNECT|NO CARRIER)' "$answer" 2>/dev/null || {
echo "mu300-at: modem returned no final response" >&2
exit 1
}
cat "$answer"
exit 0
fi
+14 -1
View File
@@ -98,7 +98,10 @@ open_tty || { echo "mu300-atd: cannot open $DEV" >&2; exit 1; }
URCDIR=$DIR/urc
URCMAX=${MU300_AT_URC_MAX:-65536}
mkdir -p "$URCDIR"
for n in ${MU300_AT_URC_CHANNELS:-0}; do
# Use '-' rather than ':-': an explicitly empty value means this secondary
# daemon must not open any URC channel. With ':-', atd2 and atd3 both fell back
# to nr0 and three readers split/lost the unsolicited stream.
for n in ${MU300_AT_URC_CHANNELS-0}; do
other=${DEV%[0-9]}$n
[ "$other" = "$DEV" ] && continue
[ -c "$other" ] || continue
@@ -137,6 +140,12 @@ drain() { # throw away whatever the modem sent while nobody was asking (URCs),
# written the next command we would read it as that command's reply and stay one answer behind for ever.
# This modem makes that easy to hit - AT+CGACT and AT+CGDATA answer "^ORIG: <cid>,<n>" first and OK or
# CONNECT ten to twenty seconds later (docs/FINDINGS.md 13f).
#
# FAST PATH: when the previous reply ended in a clean final result code (OK/ERROR/
# CONNECT), the channel is known-quiet - there is nothing to drain, and the 1 s wait
# below was pure tax on every single AT round trip. The slow path stays for the
# after-timeout case, where a late reply really can be on its way.
[ "${PREV_CLEAN:-0}" = 1 ] && { PREV_CLEAN=0; return 0; }
end=$(( $(now) + ${DRAIN_MAX:-3} ))
while [ "$(now)" -lt "$end" ]; do
junk=
@@ -186,6 +195,10 @@ while :; do
drain
printf '%s\r' "$cmd" >&3
reply=$(collect "$t")
# did this command end with a clean final result code? If so, the channel is quiet
# and the next drain can skip its 1 s wait (see drain's fast path)
PREV_CLEAN=0
echo "$reply" | grep -qE '^(OK|ERROR|\+CME ERROR|\+CMS ERROR|CONNECT|NO CARRIER)' && PREV_CLEAN=1
# When the modem restarts (AT+SFUN=4 during a bring-up, or a CP crash) this descriptor is left attached to a
# channel that no longer exists: it reads nothing for ever, and because it still holds the channel, nobody
# else can talk to the modem either. Reopening is the only cure for that case - but it is also the way to
+642
View File
@@ -0,0 +1,642 @@
#!/bin/sh
# Local SMS pool for the MU300 modem: everything the SIM holds (or arrives later) is mirrored into
# $POOL, one file per message, and everything the pool can do it does without touching the SIM
# except through an explicit --sim.
# mu300-sms list [PAGE] newest first, MU300_SMS_PAGE per page (default 10)
# mu300-sms show ID whole message (marks a received one read)
# mu300-sms send NUM TEXT... UCS-2 PDU submit, so non-ASCII travels correctly
# mu300-sms delete ID|all pool entry only; --sim also CMGDs the matching SIM slot
# mu300-sms mark ID read|unread
# mu300-sms sync pull everything AT+CMGL lists into the pool
# All AT traffic goes through mu300-atd (via mu300-at); the AT channel is never opened here.
set -u
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
POOL=${MU300_SMS_POOL:-/var/lib/mu300/sms}
MSGDIR=$POOL/msg
ATDIR=${MU300_AT_DIR:-/run/mu300-at}
PAGE=${MU300_SMS_PAGE:-10}
die() { echo "mu300-sms: $*" >&2; exit 1; }
at() { # at CMD [timeout] -> reply lines
mu300-at -t "${2:-6}" "$1"
}
# ------------------------------------------------------------------ the pool
# One file per message: "field: value" headers, a blank line, then the body verbatim to EOF
# (bodies span lines). Everything the pool writes goes through name.part + mv so a reader never
# sees a half-written message; the pool lock keeps two writers from sharing an id.
pool_init() {
mkdir -p "$MSGDIR" || die "cannot create $MSGDIR"
[ -f "$POOL/next_id" ] || echo 0 > "$POOL/next_id"
}
# mkdir lock with pid-liveness takeover, the house pattern: a writer killed with SIGKILL leaves
# the directory behind, and the next writer must be able to tell a live holder from a stale one.
pool_lock() {
local lock=$POOL/.lock pid=
local n=0
while ! mkdir "$lock" 2>/dev/null; do
pid=$(cat "$lock/pid" 2>/dev/null || true)
if [ -n "$pid" ] && [ -d "/proc/$pid" ] &&
tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | grep -q mu300-sms; then
n=$((n + 1)); [ "$n" -gt 120 ] && die "another mu300-sms writer has held the pool for two minutes"
sleep 1
continue
fi
rm -rf "$lock"
done
echo $$ > "$lock/pid"
}
pool_unlock() { rm -rf "$POOL/.lock" 2>/dev/null || true; }
hdr() { # hdr FILE field (headers only: the body may legitimately repeat any "field: " line)
sed -n "1,/^$/s/^$2: //p" "$1" 2>/dev/null | head -1
}
set_hdr() { # set_hdr FILE field value
sed -i "1,/^$/s/^$2: .*/$2: $3/" "$1"
}
body_of() { sed -n '1,/^$/!p' "$1" 2>/dev/null; }
# md5 of from|scts|body, the identity of a message across pool and SIM listings. Two identical
# messages from one sender inside the same SCTS minute dedupe into one - acceptable next to the
# alternative (index-based keys, which go stale the moment anything deletes from the SIM).
fingerprint() {
printf '%s|%s|%s' "$1" "$2" "$3" | md5sum 2>/dev/null | cut -d' ' -f1
}
next_id() {
local id
id=$(($(cat "$POOL/next_id" 2>/dev/null || echo 0) + 1))
echo "$id" > "$POOL/next_id"
printf '%06d' "$id"
}
store_msg() { # store_msg dir status peer scts sim_index coding body -> id on stdout
local dir=$1 status=$2 peer=$3 scts=$4 simidx=$5 coding=$6 text=$7 id f part
id=$(next_id)
f=$MSGDIR/$id
part=$f.part
{
printf 'id: %s\n' "$id"
printf 'dir: %s\n' "$dir"
printf 'status: %s\n' "$status"
if [ "$dir" = mt ]; then printf 'from: %s\n' "$peer"; else printf 'to: %s\n' "$peer"; fi
printf 'scts: %s\n' "$scts"
printf 'received: %s\n' "$(date +%s)"
printf 'sim_index: %s\n' "$simidx"
printf 'coding: %s\n' "$coding"
printf 'fingerprint: %s\n' "$(fingerprint "$peer" "$scts" "$text")"
printf 'length: %s\n' "$(printf '%s' "$text" | wc -c | tr -d ' ')"
printf '\n'
printf '%s\n' "$text"
} > "$part"
mv "$part" "$f"
echo "$id"
}
ids_newest_first() { ls -1 "$MSGDIR" 2>/dev/null | grep -E '^[0-9]+$' | sort -rn; }
# With CSCS left at UCS2 (the send path sets it), text-mode CMGL encodes the
# originating address as ASCII-hex: 17674544422 arrives as "313736373435...3232".
# Decode byte pairs back, but only when every pair is printable and the result
# is digit-major - a plain numeric address must never be mangled.
peer_decode() {
printf '%s' "$1" | LC_ALL=C awk '
BEGIN { split("0123456789abcdef", H, ""); for (i = 1; i <= 16; i++) v[H[i]] = i - 1 }
{
orig = $0; s = tolower($0)
if (s !~ /^[0-9a-f]+$/ || length(s) % 2 != 0 || length(s) < 4) { print orig; exit }
out = ""; digits = 0; n = 0
for (i = 1; i <= length(s); i += 2) {
hi = v[substr(s, i, 1)]; lo = v[substr(s, i + 1, 1)]
b = hi * 16 + lo
if (b < 32 || b > 126) { print orig; exit }
c = sprintf("%c", b); out = out c; n++
if (c ~ /[0-9]/) digits++
}
if (digits * 2 >= n) print out; else print orig
}'
}
# ------------------------------------------------------------------ codecs
# UCS-2 hex -> "\ooo" escapes (printf %b turns them into bytes). Backslash itself is doubled.
# Surrogate pairs join; an unpaired one decodes to '?'. All string ops are byte-wise (LC_ALL=C).
ucs2_to_esc() {
LC_ALL=C awk '
BEGIN {
split("0123456789abcdef", H, "")
for (i = 1; i <= 16; i++) hv[H[i]] = i - 1
}
function h4(s, i) { return hv[substr(s, i, 1)] * 4096 + hv[substr(s, i + 1, 1)] * 256 + hv[substr(s, i + 2, 1)] * 16 + hv[substr(s, i + 3, 1)] }
function e(b) { return (b == 92) ? "\\\\" : sprintf("\\%03o", b) }
function u8(cp) {
if (cp < 128) return e(cp)
if (cp < 2048) return e(192 + int(cp / 64)) e(128 + cp % 64)
if (cp < 65536) return e(224 + int(cp / 4096)) e(128 + int(cp / 64) % 64) e(128 + cp % 64)
cp -= 65536
return e(240 + int(cp / 262144)) e(128 + int(cp / 4096) % 64) \
e(128 + int(cp / 64) % 64) e(128 + cp % 64)
}
{
s = tolower($0); gsub(/[^0-9a-f]/, "", s); n = length(s); out = ""; i = 1
while (i + 3 <= n) {
cp = h4(s, i)
if (cp >= 55296 && cp <= 56319 && i + 7 <= n) {
lo = h4(s, i + 4)
if (lo >= 56320 && lo <= 57343) { cp = 65536 + (cp - 55296) * 1024 + (lo - 56320); i += 4 }
}
out = out u8(cp)
i += 4
}
print out
}'
}
# UTF-8 -> UCS-2 hex (surrogate pair above 0xFFFF). Malformed bytes become "?" rather than
# aborting the message.
utf8_to_ucs2() {
LC_ALL=C awk '
BEGIN { for (i = 1; i < 256; i++) ord[sprintf("%c", i)] = i }
{
s = $0; n = length(s); i = 1; out = ""
while (i <= n) {
b1 = ord[substr(s, i, 1)]
if (b1 < 128) { cp = b1; w = 1 }
else if (b1 < 224) { cp = b1 % 32; w = 2 }
else if (b1 < 240) { cp = b1 % 16; w = 3 }
else if (b1 < 245) { cp = b1 % 8; w = 4 }
else { cp = 63; w = 1 }
for (j = 2; j <= w; j++) {
b = ord[substr(s, i + j - 1, 1)]
if (b < 128 || b > 191) { cp = 63; w = 1; break }
cp = cp * 64 + (b % 64)
}
i += w
if (cp > 65535) {
cp -= 65536
out = out sprintf("%04x%04x", 55296 + int(cp / 1024), 56320 + cp % 1024)
} else {
out = out sprintf("%04x", cp)
}
}
print out
}'
}
# BCD digits -> semioctets ("10086" -> "0180F6"): low nibble carries the first digit, an odd
# count pads the high nibble of the last octet with F.
pack_semi() {
LC_ALL=C awk '{
s = $0; gsub(/[^0-9]/, "", s); n = length(s); out = ""
for (i = 1; i <= n; i += 2) {
d2 = (i < n) ? substr(s, i + 1, 1) : "F"
out = out d2 substr(s, i, 1)
}
print out
}'
}
# ------------------------------------------------------------------ AT+CMGL
# Text-mode listing: one "+CMGL: idx,\"stat\",\"oa\",[\"alpha\"],\"scts\"" header, body lines after
# it, until the next header or the final code. mu300-atd does not demux URCs out of a reply
# (that is this chain's known weakness), so the parser drops the URC lines this modem is known
# to emit mid-reply. Bodies are newline-escaped with \001 for the TSV trip.
parse_cmgl() {
LC_ALL=C awk '
function flush() { if (idx != "") { sub(/\001$/, "", body); printf "%s\t%s\t%s\t%s\t%s\n", idx, stat, oa, scts, body } }
/^\+CMGL:/ {
flush()
inbody = 1; body = ""; stat = ""; oa = ""; scts = ""
line = $0; sub(/^\+CMGL: */, "", line)
idx = line; sub(/,.*/, "", idx)
k = 0
while (match(line, /"[^"]*"/)) {
k++
t = substr(line, RSTART + 1, RLENGTH - 2)
if (k == 1) stat = t
else if (k == 2) oa = t
else if (t ~ /\//) scts = t
line = substr(line, RSTART + RLENGTH)
}
next
}
/^(OK|ERROR|\+CMS ERROR|\+CME ERROR)/ { flush(); inbody = 0; idx = ""; next }
inbody && /^\+(CSQ|CESQ|SPPCI|ECIND|SIND|CREG|CGREG|CEREG|C5GREG|CTZV|CGEV|CMTI|SPNRINDICATE|SPERRLOG)/ { next }
# a blank line right after the header (this modem emits one on some UCS2
# records) must not become a leading newline inside the body
inbody { if (body == "" && $0 == "") next; body = body (body == "" ? "" : "\001") $0 }
END { flush() }
'
}
# AT+CMGR answers one record shaped like a +CMGL header, with the index supplied by us (the
# firmware does not repeat it). Same TSV, same URC-skipping, as parse_cmgl.
parse_cmgr() { # parse_cmgr INDEX
LC_ALL=C awk -v want="$1" '
function flush() { if (idx != "") { sub(/\001$/, "", body); printf "%s\t%s\t%s\t%s\t%s\n", idx, stat, oa, scts, body } }
BEGIN { idx = "" }
/^\+CMGR:/ {
flush()
inbody = 1; body = ""; stat = ""; oa = ""; scts = ""
line = $0; sub(/^\+CMGR: */, "", line)
k = 0
while (match(line, /"[^"]*"/)) {
k++
t = substr(line, RSTART + 1, RLENGTH - 2)
if (k == 1) stat = t
else if (k == 2) oa = t
else if (t ~ /\//) scts = t
line = substr(line, RSTART + RLENGTH)
}
idx = want
next
}
/^(OK|ERROR|\+CMS ERROR|\+CME ERROR)/ { flush(); inbody = 0; idx = ""; next }
inbody && /^\+(CSQ|CESQ|SPPCI|ECIND|SIND|CREG|CGREG|CEREG|C5GREG|CTZV|CGEV|CMTI|SPNRINDICATE|SPERRLOG)/ { next }
# a blank line right after the header (this modem emits one on some UCS2
# records) must not become a leading newline inside the body
inbody { if (body == "" && $0 == "") next; body = body (body == "" ? "" : "\001") $0 }
END { flush() }
'
}
select_storage() {
local s reply line used total best= cache=${MU300_SMS_STORE_CACHE:-/run/mu300-sms-store}
if [ -s "$cache" ]; then
s=$(cat "$cache" 2>/dev/null)
case $s in SM|MT|ME)
at "AT+CPMS=\"$s\"" 6 >/dev/null 2>&1 && { echo "$s"; return 0; }
;;
esac
rm -f "$cache"
fi
# This modem rejects the usual three-argument CPMS form. Probe with the
# supported single-argument form, prefer a store containing messages, then
# any store with real capacity (ME is commonly 0/0 on this hardware).
for s in SM MT ME; do
reply=$(at "AT+CPMS=\"$s\"" 6 2>/dev/null || true)
line=$(printf '%s\n' "$reply" | grep '^+CPMS:' | head -1)
used=$(printf '%s\n' "$line" | awk -F'[,:]' '{gsub(/ /,"",$2); print $2}')
total=$(printf '%s\n' "$line" | awk -F'[,:]' '{gsub(/ /,"",$3); print $3}')
case "$used:$total" in *[!0-9:]*|:*) continue ;; esac
if [ "$used" -gt 0 ]; then
echo "$s" > "$cache"
echo "$s"
return 0
fi
[ "$total" -gt 0 ] && [ -z "$best" ] && best=$s
done
[ -n "$best" ] || best=ME
at "AT+CPMS=\"$best\"" 6 >/dev/null || return 1
echo "$best" > "$cache"
echo "$best"
}
# List the SIM as TSV records, by whichever door this firmware opens. The measured cases:
# * CMGF=1 refused -> report; nothing to list with
# * AT+CMGL="ALL" refused -> some firmwares only take the numeric stat (CMGL=4) in text mode
# * both refused -> this firmware offers no listing at all (the E5 of this family
# is read by CMGR after each +CMTI - see unisoc-cpd FINDINGS), so scan slots instead;
# the fingerprint dedupe in sync absorbs the overlap
sim_list() {
local reply store
store=$(select_storage) || {
echo "mu300-sms: no usable SMS storage" >&2
return 1
}
reply=$(at 'AT+CMGF=1' 6)
case $reply in *OK*) ;; *)
echo "mu300-sms: AT+CMGF=1 refused: $(printf '%s\n' "$reply" | head -1)" >&2
return 1 ;;
esac
sleep 1 # this CP asserts on unpaced command bursts; every sync is rare, so be generous
reply=$(at 'AT+CMGL="ALL"' 15)
case $reply in *'+CMS ERROR'*|*'+CME ERROR'*)
reply=$(at 'AT+CMGL=4' 15) ;;
esac
case $reply in *'+CMS ERROR'*|*'+CME ERROR'*)
local i misses=0 scan
scan=$(mktemp "${TMPDIR:-/tmp}/mu300-sms.XXXXXX")
for i in $(seq 1 ${MU300_SMS_SCAN:-30}); do
reply=$(at "AT+CMGR=$i" 6)
case $reply in
*'+CMS ERROR'*|*'+CME ERROR'*|"") misses=$((misses + 1)); [ "$misses" -ge 3 ] && break; continue ;;
esac
printf '%s\n' "$reply" | parse_cmgr "$i" >> "$scan"
misses=0
done
cat "$scan"
rm -f "$scan"
return 0 ;;
esac
printf '%s\n' "$reply" | parse_cmgl
}
# ------------------------------------------------------------------ commands
cmd_sync() {
pool_init
local reply tmp new=0 total=0
tmp=$(mktemp "${TMPDIR:-/tmp}/mu300-sms.XXXXXX") || die mktemp
sim_list > "$tmp" || { rm -f "$tmp"; die "cannot list the SIM storage"; }
# Concatenated SMS arrive as one SIM record per part; text mode hides the UDH,
# but every part of one message carries the same sender and the same SCTS.
# Fold parts (CMGL lists them in index order) into one record per (oa,scts).
# The odd genuinely-separate same-second pair from one sender folds too - the
# same tradeoff the fingerprint dedupe below already makes.
local merged
merged=$(mktemp "${TMPDIR:-/tmp}/mu300-sms.XXXXXX")
LC_ALL=C awk -F'\t' '
NF >= 5 {
key = $3 "|" $4
b = $5; for (i = 6; i <= NF; i++) b = b "\t" $i # keep tabs inside the body
# parts join seamlessly: for UCS2 that is plain hex concatenation (a
# separator would break the all-hex test downstream), for GSM text
# it is the correct continuation of the message
if (key in body) { body[key] = body[key] b; next }
body[key] = b; stat[key] = $2; idx[key] = $1; order[++n] = key
}
END { for (i = 1; i <= n; i++) { k = order[i]; split(k, a, "|"); print idx[k] "\t" stat[k] "\t" a[1] "\t" a[2] "\t" body[k] } }
' "$tmp" > "$merged" && mv "$merged" "$tmp"
pool_lock
trap pool_unlock EXIT INT TERM
# fingerprints of what the pool already holds, so a sync is idempotent and the SIM index of
# a still-present message stays current (indexes shift whenever anything deletes from the SIM)
local fpfile idx stat oa scts body f fpid
fpfile=$(mktemp "${TMPDIR:-/tmp}/mu300-sms.XXXXXX")
for f in "$MSGDIR"/[0-9]*; do
[ -f "$f" ] || continue
printf '%s %s\n' "$(hdr "$f" fingerprint)" "$f" >> "$fpfile"
done
while IFS="$(printf '\t')" read -r idx stat oa scts body; do
[ -n "${idx:-}" ] || continue
case $stat in REC*|ALL) ;; *) continue ;; esac # STO UNSENT/SENT are mobile-originated
total=$((total + 1))
oa=$(peer_decode "$oa")
body=$(printf '%s' "$body" | tr '\001' '\n')
local coding=gsm
case $body in
*[!0-9A-Fa-f]*|"") ;;
*) if [ $(( ${#body} % 4 )) -eq 0 ] && [ -n "$body" ]; then
body=$(printf '%b' "$(printf '%s\n' "$body" | ucs2_to_esc)")
coding=ucs2
fi ;;
esac
fpid=$(fingerprint "$oa" "$scts" "$body")
local known=""
while read -r kf kfile; do
[ "$kf" = "$fpid" ] && { known=$kfile; break; }
done < "$fpfile"
# locally-deleted messages stay deleted: their fingerprints are on the
# tombstone list, otherwise the next sync would just re-import them
grep -qxF "$fpid" "$POOL/deleted" 2>/dev/null && continue
if [ -n "$known" ]; then
[ "$(hdr "$known" sim_index)" != "$idx" ] && set_hdr "$known" sim_index "$idx"
else
local newid st=unread
# the SIM's own read state carries over: a message already read (on the phone,
# before this pool ever saw it) does not arrive here pretending to be new
case $stat in *UNREAD*) st=unread ;; *) st=read ;; esac
newid=$(store_msg mt "$st" "$oa" "$scts" "$idx" "$coding" "$body")
printf '%s %s\n' "$fpid" "$MSGDIR/$newid" >> "$fpfile"
new=$((new + 1))
echo "new: $newid from ${oa:-?} ${scts:-}"
fi
done < "$tmp"
rm -f "$tmp" "$fpfile"
echo "sync: $new new, $total on the SIM, $(ids_newest_first | wc -l | tr -d ' ') in the pool"
pool_unlock
trap - EXIT INT TERM
}
cmd_list() {
pool_init
local page=${1:-1} total pages skip n=0 shown=0 id f dir status peer scts text unread=0
case $page in ''|*[!0-9]*) page=1 ;; esac
[ "$page" -ge 1 ] || page=1
total=$(ids_newest_first | wc -l | tr -d ' ')
for f in "$MSGDIR"/[0-9]*; do
[ -f "$f" ] || continue
[ "$(hdr "$f" status)" = unread ] && unread=$((unread + 1))
done
pages=$(( (total + PAGE - 1) / PAGE ))
[ "$pages" -ge 1 ] || pages=1
echo "pool: $total message(s), $unread unread - page $page/$pages ($PAGE per page)"
[ "$total" -eq 0 ] && return 0
skip=$(( (page - 1) * PAGE ))
for id in $(ids_newest_first); do
n=$((n + 1))
[ "$n" -le "$skip" ] && continue
[ "$shown" -ge "$PAGE" ] && break
shown=$((shown + 1))
f=$MSGDIR/$id
dir=$(hdr "$f" dir); status=$(hdr "$f" status)
peer=$(hdr "$f" from); [ -n "$peer" ] || peer=$(hdr "$f" to)
scts=$(hdr "$f" scts)
# preview: first line, at most 44 BYTES, backed off to a UTF-8 character
# boundary (cut -c1-44 chopped multi-byte characters in half and the
# replacement square ended up in the UI). The backoff runs ONLY after a
# real cut: an all-multibyte line that is already short must not be
# nibbled to nothing from its tail.
text=$(body_of "$f" | head -1 | LC_ALL=C awk '
BEGIN { for (i = 0; i < 256; i++) o[sprintf("%c", i)] = i }
{
s = $0
if (length(s) > 44) {
s = substr(s, 1, 44)
while (length(s) > 0) {
b = o[substr(s, length(s), 1)]
if (b < 128) break # ASCII tail: complete char
if (b >= 192) { s = substr(s, 1, length(s) - 1); break } # lead byte: drop once, done
s = substr(s, 1, length(s) - 1) # continuation: keep backing up
}
}
print s
}')
printf '%-7s %-7s %-3s %-18s %-21s %s\n' \
"$id" "$status" "$dir" "${peer:-?}" "${scts:-?}" "$text"
done
}
cmd_show() {
local id=${1:-} f dir status peer scts idx coding recv text n
case $id in ''|*[!0-9]*) die "show needs a numeric id (see: mu300-sms list)" ;; esac
n=$(printf '%s' "$id" | sed 's/^0*//'); [ -n "$n" ] || n=0
f=$MSGDIR/$(printf '%06d' "$n")
[ -f "$f" ] || die "no message $id"
dir=$(hdr "$f" dir); status=$(hdr "$f" status)
peer=$(hdr "$f" from); [ -n "$peer" ] || peer=$(hdr "$f" to)
scts=$(hdr "$f" scts); idx=$(hdr "$f" sim_index); coding=$(hdr "$f" coding)
recv=$(hdr "$f" received)
echo "id: $id"
echo "direction: $([ "$dir" = mt ] && echo 'received (MT)' || echo 'sent (MO)')"
echo "status: $status"
echo "$([ "$dir" = mt ] && echo from || echo to): $peer"
echo "time: ${scts:-?}"
echo "sim index: ${idx:-not on the SIM}"
[ -n "$recv" ] && echo "pooled: $(date -u -d "@$recv" 2>/dev/null || date -u -r "$recv" 2>/dev/null || echo "$recv") UTC"
[ "$coding" = ucs2 ] && echo "coding: UCS-2 (decoded)"
echo "---"
body_of "$f"
# mark-read on first view. The && chain returns 1 for an already-read
# message, and as the last command that became cmd_show's exit status -
# every rpcd sms_show of a read message answered ok:0 with the full text
# hidden in the error field (bubbles never updated past the preview).
[ "$dir" = mt ] && [ "$status" = unread ] && set_hdr "$f" status read
return 0
}
cmd_mark() {
local id=${1:-} what=${2:-} f n
case $id in ''|*[!0-9]*) die "mark needs a numeric id" ;; esac
case $what in read|unread) ;; *) die "mark ID read|unread" ;; esac
n=$(printf '%s' "$id" | sed 's/^0*//'); [ -n "$n" ] || n=0
f=$MSGDIR/$(printf '%06d' "$n")
[ -f "$f" ] || die "no message $id"
set_hdr "$f" status "$what"
}
# This CP's prompt has no newline, so a two-stage AT+CMGS conversation loses the
# ">" in atd's line reader. Send command, literal CR, PDU and Ctrl-Z as one
# atomic atd request; the modem accepts this form and replies with +CMGS/OK.
cmd_send() {
local num=${1:-} text idigits toa ud udl pdu len
shift $(($# > 0 ? 1 : 0))
text=$*
case $num in
'+'*[0-9][0-9][0-9]*) toa=91; idigits=${num#+} ;;
[0-9][0-9][0-9]*) toa=81; idigits=$num ;;
*) die "send needs a phone number and a text (mu300-sms send 10086 你好)" ;;
esac
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} / 4 )) -gt 70 ] &&
die "text is $(( ${#ud} / 4 )) UCS-2 units; one SMS part carries 70 (concatenation not implemented)"
udl=$(( ${#ud} / 2 ))
# 00: empty SMSC (the modem's default service centre - the vendor's own submit carries it
# empty too); 01: submit, no VP octet follows (a 0x11 here - promising a validity period
# the PDU never carries - is a measured +CMS ERROR: 302 on this CP family); 00: message
# reference. CMGS's length counts the octets after the SMSC field.
pdu="000100$(printf '%02X' "${#idigits}")${toa}$(printf '%s' "$idigits" | pack_semi)0008$(printf '%02X' "$udl")$ud"
pdu=$(printf '%s' "$pdu" | tr 'a-f' 'A-F')
len=$(( (${#pdu} - 2) / 2 ))
echo "submitting to $num ($len octets, $((udl / 2)) UCS-2 units)"
local r0 r2 submit
r0=$(at 'AT+CAVIMS=1' 6)
case $r0 in *OK*) ;; *) die "modem refused AT+CAVIMS=1: $r0" ;; esac
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)
# back to text mode whatever happened: this firmware boots in PDU mode, where a manual
# AT+CMGL="ALL" answers +CMS ERROR: 302, and leaving PDU behind after every submit is how
# the next reader gets confused
at 'AT+CMGF=1' 6 >/dev/null || true
if ! printf '%s\n' "$r2" | grep -q '^+CMGS:'; then
die "submit failed: $(printf '%s\n' "$r2" | grep -E 'CMS|ERROR' | head -1)"
fi
pool_init
pool_lock
# bytes above 0x7F mean the text is not plain GSM-7 ASCII and travelled as UCS-2
local coding=gsm
[ -n "$(printf '%s' "$text" | LC_ALL=C tr -d '\000-\177')" ] && coding=ucs2
store_msg mo sent "$num" "$(date '+%y/%m/%d,%H:%M:%S')" "" "$coding" "$text" >/dev/null
pool_unlock
echo "sent ($(printf '%s\n' "$r2" | sed -n 's/^+CMGS: //p' | head -1))"
}
# Lock order, everywhere: the AT *client* lock ($ATDIR/lock) is only ever taken by a path
# that holds no pool lock, and the pool lock is only ever taken by a path that makes no AT
# calls while holding it. The two AT-talking commands (sync, delete --sim) finish their AT
# conversation before touching the pool; send takes the client lock first and the pool lock
# only around the pool append. Getting this backwards deadlocks send against sync.
cmd_delete() {
local what=${1:-} wantsim=false id n f
for a in "$@"; do [ "$a" = --sim ] && wantsim=true; done
[ "$what" = --sim ] && { shift; what=${1:-}; }
pool_init
# tombstone every removed message so a later sync does not re-import it
# from the SIM (a local-only delete must actually delete something)
tombstone() { [ -n "$(hdr "$1" fingerprint)" ] &&
printf '%s\n' "$(hdr "$1" fingerprint)" >> "$POOL/deleted" 2>/dev/null; }
if [ "$what" = all ]; then
for id in $(ids_newest_first); do
tombstone "$MSGDIR/$id"
[ "$wantsim" = true ] && sim_delete "$id"
done
pool_lock
trap pool_unlock EXIT INT TERM
rm -f "$MSGDIR"/[0-9]* 2>/dev/null
pool_unlock
trap - EXIT INT TERM
echo "pool emptied"
return 0
fi
case "$what" in ''|*[!0-9]*) die "delete needs an id or \"all\" (optionally --sim)" ;; esac
n=$(printf '%s' "$what" | sed 's/^0*//'); [ -n "$n" ] || n=0
id=$(printf '%06d' "$n")
f=$MSGDIR/$id
[ -f "$f" ] || die "no message $what"
tombstone "$f"
[ "$wantsim" = true ] && sim_delete "$id"
rm -f "$f"
echo "deleted $what"
}
# CMGD by index alone is dangerous (indexes shift with every deletion), so the SIM is re-listed
# and the slot whose fingerprint matches the pool entry is the one deleted. No match: nothing
# happens to the SIM, which is also the answer for a message the SIM never held.
sim_delete() {
local id=$1 f=$MSGDIR/$id want simidx reply idx stat oa scts body fpid
[ -f "$f" ] || return 0
want=$(hdr "$f" fingerprint)
reply=$(sim_list) || return 0
simidx=""
while IFS="$(printf '\t')" read -r idx stat oa scts body; do
[ "$idx" = "" ] && continue
body=$(printf '%s' "$body" | tr '\001' '\n')
case $body in
*[!0-9A-Fa-f]*|"") ;;
*) [ $(( ${#body} % 4 )) -eq 0 ] && body=$(printf '%b' "$(printf '%s\n' "$body" | ucs2_to_esc)") ;;
esac
[ "$(fingerprint "$oa" "$scts" "$body")" = "$want" ] && { simidx=$idx; break; }
done <<EOF
$(printf '%s\n' "$reply" | tr -d '\r')
EOF
if [ -z "$simidx" ]; then
echo "message $id is not on the SIM (already gone, or never stored there)" >&2
return 0
fi
at "AT+CMGD=$simidx" 6 | grep -q '^OK' && echo "deleted SIM slot $simidx for message $id"
}
usage() {
cat <<EOF
usage: mu300-sms list [PAGE] paged inbox, newest first (MU300_SMS_PAGE per page, default 10)
mu300-sms show ID the whole message; marks a received one read
mu300-sms send NUM TEXT UCS-2 submit (non-ASCII travels correctly)
mu300-sms delete ID|all pool only; --sim also deletes the matching SIM slot
mu300-sms mark ID read|unread
mu300-sms sync pull everything AT+CMGL lists into the pool
pool: $POOL (MU300_SMS_POOL to move it)
EOF
}
case ${1:-list} in
list) shift $(($# > 0 ? 1 : 0)); cmd_list "${1:-}" ;;
show) shift; cmd_show "$@" ;;
send) shift; cmd_send "$@" ;;
delete) shift; cmd_delete "$@" ;;
del) shift; cmd_delete "$@" ;;
mark) shift; cmd_mark "$@" ;;
sync) cmd_sync ;;
-h|--help|help) usage ;;
*) usage; exit 2 ;;
esac
+81
View File
@@ -0,0 +1,81 @@
#!/bin/sh
# Keep the local SMS pool in step with the SIM (see mu300-sms).
#
# Receiving is +CMTI-driven where it can be: mu300-atd logs every unsolicited line of every
# channel into /run/mu300-at/urc/*.log, so a new "+CMTI:" anywhere changes the md5 of the
# +CMTI lines and that is the trigger. The logs are capped and truncated, not rotated - a
# truncation changes the signature too, and a sync is idempotent, so a spurious trigger costs
# one paced AT+CMGL. A full sync also runs once per MU300_SMS_SYNC_INTERVAL regardless, as the
# safety net for an announcement missed while nobody watched.
#
# Nothing here ever deletes from the SIM; deletion is the operator's explicit "delete --sim".
set -u
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
POOL=${MU300_SMS_POOL:-/var/lib/mu300/sms}
ATDIR=${MU300_AT_DIR:-/run/mu300-at}
URCDIR=$ATDIR/urc
POLL=${MU300_SMS_POLL:-5}
SYNC_INTERVAL=${MU300_SMS_SYNC_INTERVAL:-30}
SMS=${MU300_SMS_BIN:-$(command -v mu300-sms 2>/dev/null || echo /opt/mu300/bin/mu300-sms)}
# one daemon, the house pattern: a second instance (procd respawning, a service started twice)
# waits for the lock only as long as the holder is alive, then takes over
LOCK=${MU300_SMS_LOCK:-/run/mu300-smsd.lock}
while ! mkdir "$LOCK" 2>/dev/null; do
owner=$(cat "$LOCK/pid" 2>/dev/null || true)
if [ -n "$owner" ] && [ -d "/proc/$owner" ] &&
tr '\0' ' ' < "/proc/$owner/cmdline" 2>/dev/null | grep -q mu300-smsd; then
echo "mu300-smsd: pid $owner is already pooling into $POOL" >&2
exit 0
fi
rm -rf "$LOCK"
done
echo $$ > "$LOCK/pid"
trap '[ "$(cat "$LOCK/pid" 2>/dev/null)" = $$ ] && rm -rf "$LOCK"; exit 0' INT TERM
# mu300-atd owns the AT channel; until its command fifo exists nothing can be asked at all
n=0
until [ -p "$ATDIR/cmd" ]; do
n=$((n + 1))
[ "$n" -gt 120 ] && { echo "mu300-smsd: no command fifo from mu300-atd, exiting" >&2; exit 1; }
sleep 5
done
# the SIM needs its time after a boot (mobile-data waits 15 s for it); poll for READY, but a
# modem that never answers still gets its periodic sync attempts in the main loop below
n=0
until mu300-at -t 4 'AT+CPIN?' 2>/dev/null | grep -q READY; do
n=$((n + 1))
[ "$n" -gt 60 ] && { echo "mu300-smsd: SIM never became ready, syncing anyway" >&2; break; }
sleep 10
done
# Without CNMI the modem files incoming messages silently (measured 0,0,0,1,0),
# the +CMTI trigger below never fires and arrival waits for the 30 s net. Ask
# for storage indications; a refusal still leaves the periodic sync working.
mu300-at -t 4 'AT+CNMI=2,1,0,0,0' >/dev/null 2>&1 || true
"$SMS" sync
signature() {
cat "$URCDIR"/*nr*.log 2>/dev/null | grep -aF '+CMTI' | md5sum 2>/dev/null | cut -d' ' -f1
}
last=$(signature)
elapsed=0
echo "mu300-smsd: pooling into $POOL (poll ${POLL}s, full sync every ${SYNC_INTERVAL}s)" >&2
while :; do
sleep "$POLL"
s=$(signature)
if [ "$s" != "$last" ]; then
last=$s
sleep 2 # let the message land in the SIM storage before listing it
"$SMS" sync || echo "mu300-smsd: sync failed, will retry on the next trigger" >&2
elapsed=0
continue
fi
elapsed=$((elapsed + POLL))
if [ "$elapsed" -ge "$SYNC_INTERVAL" ]; then
elapsed=0
"$SMS" sync || true
fi
done
+35 -16
View File
@@ -1,35 +1,54 @@
#!/bin/sh
# Make the host re-enumerate the USB gadget, so it asks for a DHCP lease again.
#
# Why this exists: the host starts its DHCP the moment the gadget appears and gives up after a few seconds. A
# device that is still booting (modules, modem, services) answers too late, the host falls back to a
# self-assigned 169.254 address and, on macOS at least, stops asking. Re-enumerating looks like a fresh cable to
# the host and it tries again.
# Manual disaster recovery for a wedged USB gadget. Normal boot, PDP setup and
# IPv6 updates never call this: the early DHCP handoff and broadcast replies
# keep the existing NCM function usable without a fake cable event.
#
# It detaches itself on purpose: unbinding the gadget kills the ACM console (and the SSH session over ECM) that
# this was most likely started from, and a rebind that never runs leaves the device with no USB at all.
set -u
export PATH="$PATH:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
G=${MU300_GADGET:-/sys/kernel/config/usb_gadget/linux}
[ -d "$G" ] || { echo "mu300-usb-reset: no gadget at $G" >&2; exit 1; }
# "--if-no-lease": used at the end of the boot. If the host took an address, leave it alone; if it is still
# waiting (it gave up while the device was booting), re-enumerate once.
if [ "${1:-}" = --if-no-lease ]; then
sleep "${2:-20}"
for f in /tmp/dhcp.leases /var/lib/misc/dnsmasq.leases /var/lib/dnsmasq/dnsmasq.leases; do
[ -s "$f" ] && exit 0
done
set -- --detach
if [ "${1:-}" = --ready ]; then
setsid "$0" --fast-run </dev/null >/dev/null 2>&1 &
exit 0
fi
if [ "${1:-}" != --run ]; then
if [ "${1:-}" != --run ] && [ "${1:-}" != --fast-run ]; then
setsid "$0" --run </dev/null >/dev/null 2>&1 &
echo "re-enumerating: the console and any SSH session drop for a few seconds"
exit 0
fi
# initramfs used /config and unmounted it before switch_root. Mount configfs at
# the normal rootfs location so the same gadget can be rebound from OpenWrt.
if [ ! -d "$G" ]; then
mkdir -p /sys/kernel/config
mount -t configfs configfs /sys/kernel/config 2>/dev/null || true
fi
[ -d "$G" ] || { echo "mu300-usb-reset: no gadget at $G" >&2; exit 1; }
udc=$(cat "$G/UDC" 2>/dev/null)
[ -n "$udc" ] || udc=$(ls /sys/class/udc 2>/dev/null | head -n1)
if [ "${1:-}" = --fast-run ]; then
echo "" > "$G/UDC" 2>/dev/null
n=0
while [ -n "$(cat "$G/UDC" 2>/dev/null)" ] && [ "$n" -lt 100 ]; do
n=$((n + 1)); /opt/mu300/bin/busybox usleep 20000 2>/dev/null || sleep 1
done
# USB 2.0 requires a visible disconnect interval; 100 ms is enough for the
# Windows NCM stack to observe removal while remaining far below the old 5 s.
/opt/mu300/bin/busybox usleep 100000 2>/dev/null || sleep 1
n=0
while [ "$n" -lt 100 ]; do
echo "$udc" > "$G/UDC" 2>/dev/null && [ "$(cat "$G/UDC" 2>/dev/null)" = "$udc" ] && break
n=$((n + 1)); /opt/mu300/bin/busybox usleep 20000 2>/dev/null || sleep 1
done
ip link set usb0 master br-lan 2>/dev/null || true
ip link set usb0 up 2>/dev/null || ifconfig usb0 up 2>/dev/null
logger -t mu300-usb "fast gadget rebind completed on $udc"
exit 0
fi
sleep 2
echo "" > "$G/UDC" 2>/dev/null
sleep 3
@@ -22,7 +22,8 @@ uci -q batch <<UCI
set wireless.$radio.band='$band'
set wireless.$radio.channel='$CHANNEL'
set wireless.$radio.htmode='$htmode'
set wireless.$radio.country='${COUNTRY:-TR}'
set wireless.$radio.country='${COUNTRY:-CN}'
set wireless.$radio.noscan='1'
set wireless.$radio.disabled='0'
delete wireless.default_$radio
delete wireless.$radio.disabled
+2 -2
View File
@@ -67,5 +67,5 @@ while [ "$n" -lt "$WAIT" ]; do
sleep 2
done
log "modem still silent after ${WAIT}s, loading anyway so the resources exist"
insmod "$KO" 2>/dev/null && log "loaded sipa-dele" || log "FAILED sipa-dele"
log "packet domain not ready after ${WAIT}s; refusing unsafe delegate load"
exit 1
+8 -1
View File
@@ -9,8 +9,15 @@ command -v depmod >/dev/null && depmod -a
for m in pcie-sprd-misc pcie-sprd; do
modprobe "$m" 2>/dev/null || [ -d /sys/bus/platform/drivers/sprd-pcie ]
done
# modprobe needs modules.dep/modules.bb, which this rootfs does not ship; the modules sit
# flat in /lib/modules/<release> (and under extra/ on Ubuntu), so insmod them directly
K=/lib/modules/$(uname -r)
for m in wcn_bsp sprd_wlan_combo; do
grep -q "^$m " /proc/modules || modprobe "$m"
grep -q "^$m " /proc/modules && continue
f=$K/$m.ko
[ -f "$f" ] || f=$K/extra/$m.ko
[ -f "$f" ] || { echo "missing $m.ko" >&2; exit 1; }
insmod "$f"
done
for n in $(seq 1 30); do [ -e /sys/class/net/wlan0 ] && break; sleep 1; done
# wcn_bsp turns the Marlin3 firmware (ARM) log on at boot; every firmware log packet is printed to the kernel log
@@ -2034,6 +2034,14 @@ int pcie_post_init(struct sprd_hif *hif)
int ret = -EINVAL, chn = 0;
sc2355_hif.hif = (void *)hif;
/*
* A failed/aborted earlier power cycle clears this pointer in the
* error path below. The vendor driver only restores it in pcie_init(),
* but a later WCN power-on may call post_init directly. Passing
* &NULL[0] to mchn_init then makes Wi-Fi permanently fail until reboot.
* The channel table is static, so make every post-init self-contained.
*/
sc2355_hif.mchn_ops = sc2355_pcie_hif_ops;
sc2355_hif.max_num =
sizeof(sc2355_pcie_hif_ops) / sizeof(struct mchn_ops_t);