diff --git a/docs/CELLULAR-MOBILITY-20261013.zh-CN.md b/docs/CELLULAR-MOBILITY-20261013.zh-CN.md new file mode 100644 index 00000000..87a77399 --- /dev/null +++ b/docs/CELLULAR-MOBILITY-20261013.zh-CN.md @@ -0,0 +1,46 @@ +# MU300 蜂窝移动续租修复 + +本次只修改仓库代码、完成离线验证,没有部署或测试 MU300 实机。 + +## 发现的问题 + +MU300 已有 CGEV 驱动的原地 IP/DNS 更新,架构与 E5/T551M 的 ModemManager +不同;没有相同的 15 秒注册丢失保护,因此没有移植 45 秒超时修改。 + +但 OpenWrt 的纯 IPv4 分支没有启动该监视器。现有 30 秒看门狗发现基带 +IP 与网口 IP 不同时,也直接进入重拨路径;查询失败还可能被当成上下文 +失活或射频关闭。这些是相近的实现缺口,不代表已实测 MU300 有相同的 +户外掉线表现。 + +## 修复 + +- IPv4 和双栈都启动一个 netifd 管理的事件监视器。 +- 补齐 ACT、DETACH、SPPCODATA 触发;合并事件突发,冷却期间的新提示 + 保留到下一轮。校时回退不会产生长时间等待。 +- 移动换 IP、DNS 或内核丢失地址时先增加新地址,更新路由和 netifd 快照, + 最后删除旧地址。失败保留旧快照,后续可以重试。 +- CGACT 明确失活时先等待三轮、每轮两秒,再交回 netifd 恢复;AT 失败、 + 空值或无法识别的返回保留现有连接,不相信旧 CGCONTRDP 地址。 +- 看门狗发现仍激活的上下文地址不一致时调用 WAN renew,避免重拨。 + 查询失败不增加掉线计数;CFUN 必须明确返回 0 才重新开启射频。 +- 校验 IPv4、连续掩码和 DNS,兼容零 DNS、带引号及双行 IPv4/IPv6 返回。 +- 保留 external 报告方式、SLAAC/RA 有限生命周期、双卡寻址、原有 30 秒 + 看门狗周期及显式关机/切卡门控,没有新增定期 AT 轮询。 + +## 验证 + +新增 `tests/test_cellular_mobility.py`,覆盖原地更新顺序、更新失败后重试、 +AT 失败隔离、明确失活、缺失内核地址、两张 SIM、IPv4/双栈启动监视器、 +事件合并、IPv6 生命周期、看门狗 renew/重连及明确射频关闭修复。 + +```sh +PYTHONPATH=tests python3 -m unittest test_cellular_mobility test_registration_scope \ + test_static.Rules.test_tf_bundle_keeps_usb_and_cellular_handoffs +``` + +20 项通过,新续租行为在 dash、bash、BusyBox ash 下均执行。 +再用 dash/bash 执行相邻 IPv6 前缀撤回、路由修复回归,共 35 项通过。 +现有 IPv6 测试在本机 BusyBox 下会由内置 ip 绕过 PATH 中的测试桩;新增 +测试使用显式函数桩隔离这一差异,没有把这些环境性失败当作设备故障。 + +真实 URC 上报、跨基站/跨 RAT、运营商地址变化和恢复耗时仍待实机验证。 diff --git a/docs/FINDINGS.md b/docs/FINDINGS.md index 71cf8bea..4f28711d 100644 --- a/docs/FINDINGS.md +++ b/docs/FINDINGS.md @@ -1873,3 +1873,37 @@ experiment, and `mu300-update` keeps that segment. 33e made init honour a guard from Android with mu300-linux is exactly that. The generic ramdisk segment, which every update appends behind the device segment, now carries an empty `etc/mu300-trial-guard` (a later file replaces an earlier one), and an experiment's guard goes into a segment of its own behind the generic one. + +## 2026-10-13: Mobility renewal gaps in the OpenWrt protocol + +The existing event monitor was only started for dual-stack contexts. IPv4-only +connections therefore missed in-place address/DNS renewal, while the watchdog +redialled when CGPADDR differed from the kernel address. Both families now use +the same event owner; the watchdog requests renew for an active context and +does not confuse failed AT reads with detach or radio-off. ACT/DETACH/PCO hints +are coalesced without dropping hints during cooldown. Persistent explicit +inactivity still requests netifd recovery after bounded confirmation. + +Replacement addresses are installed before old ones are withdrawn; failed +updates retain the previous snapshot for retry. External IPv6 reporting and +finite RA lifetimes remain intact. There is no ModemManager registration +timeout here, so the E5/T551M 45-second change was not copied. + +20 focused checks passed, including dash/bash/BusyBox renewal tests; adjacent +IPv6 regressions passed with dash/bash (35 combined checks). No MU300 device +was deployed or tested for this change. See +[implementation and validation](CELLULAR-MOBILITY-20261013.zh-CN.md). + +## 2026-10-13:对齐 T551M 发现的 Wi-Fi 接入缺陷 + +MU300 的 AP/GO RX 同样把网络字节序 h_proto 与主机字节序协议常量直接 +比较,导致 IP 组播进入额外复制转发分支。已修正主线共用源码,并补齐 +5.4 构建补丁;保留单播 W2W、非 IP、桥接与 IPv6。 + +PCIe/SDIO 的过期客户端丢弃和组播 LUT 查找日志收敛,上层 TX 错误限速, +队列、credit 和 skb/message 释放路径不变。现有 WCN 事件恢复保留,补上 +down 后复查 disabled,避免恢复期间用户关闭 Wi-Fi 仍被重新打开。 + +34 项 RX/TX/WCN/蜂窝相关测试通过,全部 5.4 Wi-Fi 补丁从原始厂商源码 +实际应用成功。未部署 MU300 实机,不能把 T551M 的现场结果当作 MU300 +验证。详见 [Wi-Fi 对齐记录](WIFI-FORWARDING-20261013.zh-CN.md)。 diff --git a/docs/WIFI-FORWARDING-20261013.zh-CN.md b/docs/WIFI-FORWARDING-20261013.zh-CN.md new file mode 100644 index 00000000..11edaa32 --- /dev/null +++ b/docs/WIFI-FORWARDING-20261013.zh-CN.md @@ -0,0 +1,68 @@ +# MU300:对齐 T551M 接入诊断中的 Wi-Fi 修复 + +只修改 MU300 仓库并离线验证,没有部署 MU300 实机。T551M 上运行的诊断 +继续抓取,不修改它的联网配置或重开热点。 + +## 对比结果 + +MU300 主线 Wi-Fi 的 `sc2355/rx.c` 存在完全相同的字节序错误: +`eth->h_proto` 是网络字节序,AP/GO 广播组播分支却直接比较 `ETH_P_IP` 和 +`ETH_P_IPV6`。小端 CPU 上 IPv4/IPv6 会误入原本只用于非 IP 的额外复制 +转发分支,随后原包仍交给网络栈。固件 W2W 标志与桥接 hairpin 允许转发时, +会多发一份组播;是否在 MU300 实机触发,不能用 T551M 的抓取代替验证。 + +PCIe 和 SDIO 的过期单播 LUT 丢弃仍逐包 `pr_err`,成功查到组播 LUT 也 +逐包 `pr_info`,上层 TX 失败再输出 `netdev_err`。这些输出可能在大流量 +客户端离线时放大处理负担,不据此声称 MU300 已发生相同的固件卡死。 + +MU300 已有 `FW_ERROR` 事件和 `wcn-reopen`,也有互斥、按驱动/PHY/路径 +选择无线设备、忽略禁用 radio 的逻辑。无需再移植 E5 的另一套恢复通知。 +但原脚本只在恢复前检查 disabled,用户在 down 期间关闭无线时仍会被 up。 + +蜂窝实现使用 `mobile-data`,已有 CGEV 原地更新机制,架构不等同于 E5 +的 ModemManager。前一轮已补齐 IPv4 监视器、SPPCODATA/ACT/DETACH 触发、 +原地换地址、AT 失败隔离和 watchdog renew;没有搬入不适用的 MM 注册 +保护时间。[对应记录](CELLULAR-MOBILITY-20261013.zh-CN.md)。 + +## 修改 + +- 主线 RX 比较使用 `htons(ETH_P_IP)` / `htons(ETH_P_IPV6)`,IP 组播交给 + 网络栈,保留非 IP、固件单播 W2W、AP/GO、STA 和复制失败处理。 +- PCIe/SDIO 的过期客户端丢弃及正常组播 LUT 查找改为 + `pr_debug_ratelimited`;上层 TX 错误通过 `net_ratelimit()` 限速,错误级别 + 和释放 skb/message 的路径保留。不改队列、credit、返回值或协议分类。 +- 5.4 原厂驱动补齐 `wlan_combo-rx-ip-multicast-endian.patch` 和 + `wlan_combo-stale-tx-ratelimit.patch`;现有 `wlan_combo-*.patch` 构建入口 + 自动应用它们。6.18/7.2 使用同一份修改后的主线模块源码。 +- `wcn-reopen` 在 down 后重新加载配置、复查 disabled,尊重用户在恢复 + 期间关闭 Wi-Fi;保留 down 失败仍尝试 up 的既有策略。 + +没有新增常驻轮询、复位等待时间或系统重启策略;不关闭 IPv6、hairpin、 +mDNS 或客户端互通。 + +## 离线验证 + +34 项相关测试通过,覆盖 RX、PCIe/SDIO 丢弃、TX 释放/限速、WCN 恢复与 +此前蜂窝续租;shell 行为在测试环境可用的 dash/bash/BusyBox ash 下运行。 + +RX 测试执行生产转发分支,启用 ASan/UBSan:旧比较重现额外复制,修正版 +验证 AP/GO IPv4/IPv6 只交给栈,单播、ARP、复制失败和 STA 行为保留。 +实际旧版 patch 应用结果也与主线转发分支一致。 +TX 测试在 50,000 次模拟失败中确认每次都释放 skb/message,日志被抑制 +不会跳过清理;PCIe/SDIO 的 LUT 拒绝结果保持原样。 + +从缓存的 realme `4381465ccaf87fcf3215b9cd42f4a685df40e5e0` 原始厂商 +源码开始,实际顺序应用全部 5.4 Wi-Fi 补丁成功,不依赖已改过的驱动树。 +实机首次接入体验、多客户端和持续下载仍待 MU300 硬件验证。 + +6.18.54 与 7.2.8 分别在已有内核构建树中重新编译 WCN 依赖和 Wi-Fi +模块成功,使用独立 scratch 目录,未替换现有发布包或实机模块。 +vermagic 分别为 `6.18.54`、`7.2.8`,剥离调试符号后 BTF/BTF.base 仍在。 +产物保存在忽略目录 `work/wifi-forward-20261013//`: + +| 内核 | Wi-Fi 模块 SHA256 | +| --- | --- | +| 6.18.54 | `07c920ef9ce24bb2fd0b810e339b9b401b5efec17a9b1a43c429ecae70035a93` | +| 7.2.8 | `992f65a333c8264fca79a1d7fc3fb2d40eb67d9f82e464c763884f022e95bbd9` | + +5.4 本轮验证的是原始厂商源码的整套补丁应用,未执行完整内核/模块构建。 diff --git a/kernel/patches/wlan_combo-rx-ip-multicast-endian.patch b/kernel/patches/wlan_combo-rx-ip-multicast-endian.patch new file mode 100644 index 00000000..29a32663 --- /dev/null +++ b/kernel/patches/wlan_combo-rx-ip-multicast-endian.patch @@ -0,0 +1,16 @@ +Fix AP/GO IP multicast forwarding: h_proto is network endian. + +--- a/sc2355/rx.c ++++ b/sc2355/rx.c +@@ -284,8 +284,9 @@ + msdu_desc->bc_mc_w2w_flag) { + struct ethhdr *eth = (struct ethhdr *)skb->data; + +- if (eth->h_proto != ETH_P_IP && +- eth->h_proto != ETH_P_IPV6) { ++ /* IP multicast is forwarded by the host network stack. */ ++ if (eth->h_proto != htons(ETH_P_IP) && ++ eth->h_proto != htons(ETH_P_IPV6)) { + tx_skb = pskb_copy(skb, GFP_ATOMIC); + if (likely(tx_skb)) { + tx_skb->dev = ndev; diff --git a/kernel/patches/wlan_combo-stale-tx-ratelimit.patch b/kernel/patches/wlan_combo-stale-tx-ratelimit.patch new file mode 100644 index 00000000..5e358579 --- /dev/null +++ b/kernel/patches/wlan_combo-stale-tx-ratelimit.patch @@ -0,0 +1,54 @@ +Bound stale-client TX diagnostics without changing ownership or error returns. + +--- a/sc2355/pcie.c ++++ b/sc2355/pcie.c +@@ -1077,7 +1077,7 @@ + for (i = 0; i < MAX_LUT_NUM; i++) { + if ((sc2355_is_group(hif->peer_entry[i].tx.da)) && + hif->peer_entry[i].ctx_id == vif->ctx_id) { +- pr_info("%s, %d, group lut_index=%d\n", ++ pr_debug_ratelimited("%s, %d, group lut_index=%d\n", + __func__, __LINE__, + hif->peer_entry[i].lut_index); + return hif->peer_entry[i].lut_index; +@@ -1187,7 +1187,7 @@ + + lut_index = sc2355_pcie_find_lut_index(hif, vif); + if (lut_index < 6 && (!sc2355_is_group(hif->skb_da))) { +- pr_err("%s, %d, sta disconn, no data tx!", __func__, __LINE__); ++ pr_debug_ratelimited("%s, %d, sta disconn, no data tx!", __func__, __LINE__); + return -EPERM; + } + //skb_push(skb, sizeof(struct tx_msdu_dscr) + offset + dscr_rsvd); +--- a/sc2355/sdio.c ++++ b/sc2355/sdio.c +@@ -708,7 +708,7 @@ + for (i = 0; i < MAX_LUT_NUM; i++) { + if ((sc2355_is_group(hif->peer_entry[i].tx.da)) && + hif->peer_entry[i].ctx_id == vif->ctx_id) { +- pr_info("%s, %d, group lut_index=%d\n", ++ pr_debug_ratelimited("%s, %d, group lut_index=%d\n", + __func__, __LINE__, + hif->peer_entry[i].lut_index); + return hif->peer_entry[i].lut_index; +@@ -820,7 +820,7 @@ + + lut_index = sc2355_find_lut_index(hif, vif); + if (lut_index < 6 && (!sc2355_is_group(hif->skb_da))) { +- pr_err("%s, %d, sta disconn, no data tx!", __func__, __LINE__); ++ pr_debug_ratelimited("%s, %d, sta disconn, no data tx!", __func__, __LINE__); + return -EPERM; + } + skb_push(skb, sizeof(struct tx_msdu_dscr) + offset + dscr_rsvd); +--- a/common/iface.c ++++ b/common/iface.c +@@ -742,7 +742,8 @@ + ret = sprd_send_data(vif->priv, vif, msg, skb, SPRD_DATA_TYPE_NORMAL, + offset, true); + if (ret) { +- netdev_err(ndev, "%s drop msg due to TX Err\n", __func__); ++ if (net_ratelimit()) ++ netdev_err(ndev, "%s drop msg due to TX Err\n", __func__); + /* FIXME + * as debug sdiom later, just drop the msg here + * wapi temp drop diff --git a/mu300-linux-openwrt-tf-6.18-20261008-r4.zip.sha256 b/mu300-linux-openwrt-tf-6.18-20261008-r4.zip.sha256 deleted file mode 100644 index ebff5a61..00000000 --- a/mu300-linux-openwrt-tf-6.18-20261008-r4.zip.sha256 +++ /dev/null @@ -1 +0,0 @@ -d23ccad4bb20dd36cfefebd8e162d97ee5c720f03ce75b14b2e6c6f0e2718106 mu300-linux-openwrt-tf-6.18-20261008-r4.zip diff --git a/mu300-linux-openwrt-tf-7.2-20261008-r4.zip.sha256 b/mu300-linux-openwrt-tf-7.2-20261008-r4.zip.sha256 deleted file mode 100644 index 08581fb0..00000000 --- a/mu300-linux-openwrt-tf-7.2-20261008-r4.zip.sha256 +++ /dev/null @@ -1 +0,0 @@ -d3fab024e7cb19b93593c899472010241a789b30f3683967f94ded8fa7ec0d9c mu300-linux-openwrt-tf-7.2-20261008-r4.zip diff --git a/openwrt/overlay/lib/netifd/proto/mu300cell-v6.sh b/openwrt/overlay/lib/netifd/proto/mu300cell-v6.sh index 9d1c8c7d..370a5a3d 100755 --- a/openwrt/overlay/lib/netifd/proto/mu300cell-v6.sh +++ b/openwrt/overlay/lib/netifd/proto/mu300cell-v6.sh @@ -4,7 +4,7 @@ # IPv6 is supplied by RA, so address and route netlink notifications are the # authoritative source (including lifetime refreshes). IPv4 and peer DNS are # supplied by CGCONTRDP; nr0 announces PDP changes with +CGEV, at which point a -# single read refreshes them. This process is owned by netifd via +# state/address check refreshes them. This process is owned by netifd via # proto_run_command and also implements the standard WAN renew signal (USR1). # # Every update is sent address-external (matching the setup in mu300cell.sh): @@ -41,19 +41,37 @@ case "$sim_slot" in 0|1) ;; *) exit 1 ;; esac logtag=mu300cell-renew mask2prefix() { - local m=$1 bits=0 o IFS=. + local m=$1 bits=0 o partial=0 IFS=. for o in $m; do + [ "$partial" = 0 ] || [ "$o" = 0 ] || return 1 case $o in - 255) bits=$((bits + 8)) ;; 254) bits=$((bits + 7)) ;; - 252) bits=$((bits + 6)) ;; 248) bits=$((bits + 5)) ;; - 240) bits=$((bits + 4)) ;; 224) bits=$((bits + 3)) ;; - 192) bits=$((bits + 2)) ;; 128) bits=$((bits + 1)) ;; - 0) ;; *) echo 32; return ;; + 255) bits=$((bits + 8)) ;; + 254) bits=$((bits + 7)); partial=1 ;; + 252) bits=$((bits + 6)); partial=1 ;; + 248) bits=$((bits + 5)); partial=1 ;; + 240) bits=$((bits + 4)); partial=1 ;; + 224) bits=$((bits + 3)); partial=1 ;; + 192) bits=$((bits + 2)); partial=1 ;; + 128) bits=$((bits + 1)); partial=1 ;; + 0) partial=1 ;; *) return 1 ;; esac done echo "$bits" } +valid_ipv4() { + local value=$1 a b c d rest + IFS=. read -r a b c d rest <<-EOF + $value + EOF + [ -z "$rest" ] && [ -n "$d" ] || return 1 + for value in "$a" "$b" "$c" "$d"; do + case "$value" in ''|*[!0-9]*) return 1 ;; esac + [ "$value" -le 255 ] || return 1 + done + [ "$a.$b.$c.$d" != 0.0.0.0 ] +} + # One record per address: CIDR|preferred seconds|valid seconds. Including the # lifetimes in the snapshot means an RA refresh of an unchanged address is # still forwarded to netifd instead of being mistaken for a duplicate event. @@ -101,6 +119,9 @@ report() { # Mark the report external so netifd records it without replacing a finite # SLAAC lifetime with a permanent static address or route. proto_init_update "$ifname" 1 1 + # A complete external snapshot replaces old IP/DNS but leaves finite + # SLAAC lifetimes and the kernel routes under their existing owners. + proto_set_keep 0 [ -n "$ip4" ] && { proto_add_ipv4_address "$ip4" "${prefix4:-32}" proto_add_ipv4_route "0.0.0.0" 0 @@ -139,40 +160,83 @@ read_bearer() { [ -n "$line" ] && break done [ -n "$line" ] || return 1 - addrmask=$(printf '%s\n' "$line" | cut -d, -f4 | tr -d '"') + addrmask=$(printf '%s\n' "$line" | cut -d, -f4 | tr -d '"\r ') new_ip4=$(printf '%s\n' "$addrmask" | cut -d. -f1-4) mask=$(printf '%s\n' "$addrmask" | cut -d. -f5-8) - new_prefix=$(mask2prefix "$mask") - new_dns1=$(printf '%s\n' "$line" | cut -d, -f6 | tr -d '"') - new_dns2=$(printf '%s\n' "$line" | cut -d, -f7 | tr -d '"') - [ -n "$new_ip4" ] || return 1 + new_prefix=$(mask2prefix "$mask") || return 1 + new_dns1=$(printf '%s\n' "$line" | cut -d, -f6 | tr -d '"\r ') + new_dns2=$(printf '%s\n' "$line" | cut -d, -f7 | tr -d '"\r ') + [ "$new_dns1" != 0.0.0.0 ] || new_dns1= + [ "$new_dns2" != 0.0.0.0 ] || new_dns2= + valid_ipv4 "$new_ip4" || return 1 + [ -z "$new_dns1" ] || valid_ipv4 "$new_dns1" || return 1 + [ -z "$new_dns2" ] || valid_ipv4 "$new_dns2" || return 1 BEARER_IP4=$new_ip4 BEARER_PREFIX4=$new_prefix BEARER_DNS1=$new_dns1 BEARER_DNS2=$new_dns2 } +# Only explicit inactivity is evidence to reconnect. AT owners can be busy +# while moving between cells; a timeout/empty response must keep WAN intact. +context_active() { + local d out + local channels='/run/mu300-at6 /run/mu300-at7 /run/mu300-at' + [ "$sim_slot" != 1 ] || channels=/run/mu300-at4 + for d in $channels; do + [ -p "$d/cmd" ] || continue + out=$(MU300_AT_LOCK_WAIT=0 MU300_AT_DIR="$d" mu300-at -t 3 "AT+SPACTCARD=$sim_slot;+CGACT?" 2>/dev/null) || continue + printf '%s\n' "$out" | tr -d '\r' | + grep -Eq '\+CGACT:[[:space:]]*1,1([^0-9]|$)' && return 0 + printf '%s\n' "$out" | tr -d '\r' | + grep -Eq '\+CGACT:[[:space:]]*1,0([^0-9]|$)' && return 1 + done + return 2 +} + refresh_bearer() { - local reason=$1 old old_ip4 old_prefix4 + local reason=$1 old old_ip4 old_prefix4 old_dns1 old_dns2 state try kernel_addresses old="$ip4/$prefix4 $dns1 $dns2" old_ip4=$ip4; old_prefix4=$prefix4 - if ! read_bearer; then + old_dns1=$dns1; old_dns2=$dns2 + context_active + state=$? + try=0 + while [ "$state" = 1 ] && [ "$try" -lt 3 ]; do + sleep 2 + try=$((try + 1)) + context_active + state=$? + done + if [ "$state" = 1 ]; then + logger -t "$logtag" "$reason: PDP context 1 remains inactive; requesting netifd recovery" + return 2 + fi + # A failed state read or an active context with no fresh address does not + # justify disrupting the connection, including stale CGCONTRDP replies. + if [ "$state" != 0 ] || ! read_bearer; then logger -t "$logtag" "$reason: PDP active address is not available; keeping the last netifd state" return 1 fi ip4=$BEARER_IP4; prefix4=$BEARER_PREFIX4 dns1=$BEARER_DNS1; dns2=$BEARER_DNS2 - if [ "$old" != "$ip4/$prefix4 $dns1 $dns2" ]; then + kernel_addresses=$(ip -4 -o addr show dev "$ifname" scope global 2>/dev/null | awk '{print $4}') + if [ "$old" != "$ip4/$prefix4 $dns1 $dns2" ] || + ! printf '%s\n' "$kernel_addresses" | grep -Fxq "$ip4/$prefix4"; then # Add the replacement before deleting the old address. There is no # ifdown, CGACT cycle or USB event, so an address handover only loses # packets during the carrier's own transition. + if ! { ip -4 addr add "$ip4/$prefix4" dev "$ifname" 2>/dev/null || + ip -4 addr replace "$ip4/$prefix4" dev "$ifname"; } || + ! ip -4 route replace default dev "$ifname" || ! report; then + ip4=$old_ip4; prefix4=$old_prefix4 + dns1=$old_dns1; dns2=$old_dns2 + logger -t "$logtag" "$reason: update failed; keeping previous snapshot for retry" + return 1 + fi if [ "$old_ip4/$old_prefix4" != "$ip4/$prefix4" ]; then - ip -4 addr add "$ip4/$prefix4" dev "$ifname" 2>/dev/null || - ip -4 addr replace "$ip4/$prefix4" dev "$ifname" - [ -n "$old_ip4" ] && ip -4 addr del "$old_ip4/${old_prefix4:-32}" dev "$ifname" 2>/dev/null || true - ip -4 route replace default dev "$ifname" + [ -z "$old_ip4" ] || ip -4 addr del "$old_ip4/${old_prefix4:-32}" dev "$ifname" 2>/dev/null || true fi - report logger -t "$logtag" "$reason: bearer updated to $ip4/$prefix4" else logger -t "$logtag" "$reason: bearer unchanged" @@ -204,7 +268,8 @@ reap "ip -6 monitor route dev $ifname" reap "tail -n 0 -F $urclog" events=/run/mu300cell-${config}.events -rm -f "$events" +pdp_pending=$events.pdp +rm -f "$events" "$pdp_pending" mkfifo -m 600 "$events" || exit 1 exec 3<>"$events" @@ -217,12 +282,20 @@ exec 3<>"$events" tail -n 0 -F "$urclog" 2>/dev/null | while IFS= read -r line; do case $line in - *+CGEV:*PDN*|*+CGEV:*MODIFY*) printf 'pdp\n' ;; + # Besides standard PDN/MODIFY reports, Unisoc emits abbreviated + # "NW ACT ," and +SPPCODATA (PCO updates). + # All are hints to perform one coalesced CGCONTRDP refresh. + *+CGEV:*PDN*|*+CGEV:*ACT*|*+CGEV:*DETACH*|*+CGEV:*MODIFY*|*+SPPCODATA:*) + # One queued hint covers the entire burst. A hint arriving during + # an AT read queues another refresh, so cooldown never loses it. + [ -e "$pdp_pending" ] || { : >"$pdp_pending"; printf 'pdp\n'; } + ;; esac done > "$events" ) & urcmon=$! renew_pending=0 cleanup() { + local rc=$1 trap - INT TERM EXIT USR1 kill "$addrmon" "$routemon" "$urcmon" 2>/dev/null # Killing a subshell does not kill the pipeline it feeds; reap the @@ -231,17 +304,19 @@ cleanup() { reap "ip -6 monitor route dev $ifname" reap "tail -n 0 -F $urclog" exec 3>&- - rm -f "$events" - exit 0 + rm -f "$events" "$pdp_pending" + exit "$rc" } -trap cleanup INT TERM EXIT +trap 'cleanup 0' INT TERM +trap 'cleanup $?' EXIT trap 'renew_pending=1' USR1 last_pdp=0 while :; do if [ "$renew_pending" = 1 ]; then renew_pending=0 - refresh_bearer manual-renew || true + refresh_bearer manual-renew + [ "$?" != 2 ] || exit 2 last_pdp=$(date +%s) fi event= @@ -254,17 +329,22 @@ while :; do v6) now=$(v6_snapshot) [ "$now" = "$last_v6" ] && continue + report || continue last_v6=$now - report logger -t "$logtag" "IPv6 RA address/route state refreshed" ;; pdp) now=$(date +%s) - [ $((now - last_pdp)) -lt 2 ] && continue + gap=$((now - last_pdp)) + # A backward NTP correction must not turn cooldown into a long stall. + [ "$gap" -ge 0 ] || gap=0 + [ "$gap" -ge 2 ] || sleep "$((2 - gap))" # Networks commonly emit DEACT plus several ACT notifications as one # transition. Let the burst settle, then perform exactly one AT read. sleep 1 - refresh_bearer cgev || true + rm -f "$pdp_pending" + refresh_bearer cgev + [ "$?" != 2 ] || exit 2 last_pdp=$(date +%s) ;; esac diff --git a/openwrt/overlay/lib/netifd/proto/mu300cell.sh b/openwrt/overlay/lib/netifd/proto/mu300cell.sh index 734b7d0b..eccb0075 100755 --- a/openwrt/overlay/lib/netifd/proto/mu300cell.sh +++ b/openwrt/overlay/lib/netifd/proto/mu300cell.sh @@ -126,7 +126,9 @@ proto_mu300cell_setup() { printf '{"phase":"connected"}\n' > "/run/unisoc-apn-dial-$slot.json" # 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" \ + # IPv4-only contexts change address/DNS during mobility too. Keep the + # same event owner for both PDP families; IPv6 monitoring blocks while idle. + proto_run_command "$config" \ /lib/netifd/proto/mu300cell-v6.sh "$config" "$ifname" "$ip" \ "${prefix:-32}" "$dns1" "$dns2" "${peerdns:-1}" "" "$slot" [ "${pdptype:-IP}" = IP ] && [ -w "/proc/sys/net/ipv6/conf/$ifname/disable_ipv6" ] && diff --git a/openwrt/overlay/opt/mu300/bin/wcn-reopen b/openwrt/overlay/opt/mu300/bin/wcn-reopen index bec636e7..e739c092 100755 --- a/openwrt/overlay/opt/mu300/bin/wcn-reopen +++ b/openwrt/overlay/opt/mu300/bin/wcn-reopen @@ -31,6 +31,10 @@ wcn_radio() { logger -t mu300-wcn "reopening $section after WCN reset" # Always attempt up, even if down reports that the crashed firmware is gone. wifi down "$section" + # Respect a user disabling this radio while the reset/down was running. + config_load wireless + config_get_bool disabled "$section" disabled 0 + [ "$disabled" = 0 ] || return 0 wifi up "$section" || logger -t mu300-wcn "reopen failed: $section; no automatic reboot" return 0 done diff --git a/rootfs/overlay/opt/mu300/bin/mobile-data b/rootfs/overlay/opt/mu300/bin/mobile-data index 5ff19791..5a364d87 100755 --- a/rootfs/overlay/opt/mu300/bin/mobile-data +++ b/rootfs/overlay/opt/mu300/bin/mobile-data @@ -787,8 +787,27 @@ sim_reset() { # The modem firmware occasionally resets itself (modem_control reloads it); it comes back with the radio off and # no PDP context, which Android's RIL repairs silently. Check the context every 30 s and reconnect when it is gone. +watch_context_state() { + local response + response=$(at 'AT+CGACT?' 4) || return 3 + printf '%s\n' "$response" | tr -d '\r' | + grep -Eq "\\+CGACT:[[:space:]]*$CID,1([^0-9]|$)" && return 0 + printf '%s\n' "$response" | tr -d '\r' | + grep -Eq "\\+CGACT:[[:space:]]*$CID,0([^0-9]|$)" && return 1 + return 2 +} + +watch_radio_if_off() { + local response + response=$(at 'AT+CFUN?' 4 2>/dev/null || true) + if printf '%s\n' "$response" | grep -Eq '\+CFUN:[[:space:]]*0([^0-9]|$)'; then + echo "radio was off, switching it on" >&2 + radio_on || true + fi +} + watch() { - local fails=0 + local fails=0 context_state want have # one watchdog is enough: procd and systemd have both been seen starting a second one local wlock=/run/mu300-mobile-data-watch.lock wp= while ! mkdir "$wlock" 2>/dev/null; do @@ -819,24 +838,47 @@ watch() { fi [ -c "$DEV" ] || continue tty_setup - if at "AT+CGACT?" | grep -q "+CGACT:$CID,1" && ip -4 addr show "$IFACE" 2>/dev/null | grep -q inet; then + context_state=0 + watch_context_state || context_state=$? + # Busy AT ownership, no response or an unrecognised response does not + # prove a detach. Keep the established interface and its retry budget. + if [ "$context_state" = 3 ]; then + fails=0 + continue + fi + if [ "$context_state" = 2 ]; then + # A firmware reset can erase all contexts and leave CFUN=0. + # Preserve that repair only when CFUN explicitly confirms it; + # an empty or failed query must never switch the radio. + watch_radio_if_off + fails=0 + continue + fi + if [ "$context_state" = 0 ]; then # An active context is not enough: after the radio or the network dropped the bearer, an LTE modem # attaches again by itself and the context comes back with a new address, while the interface keeps # the old one - it sends with it and nothing ever comes back (measured: rx 0, the modem on - # 10.160.167.97, sipa_eth0 on 10.200.191.225). Reconnect as soon as the two differ. + # 10.160.167.97, sipa_eth0 on 10.200.191.225). In netifd mode ask + # its existing event owner to refresh this address without redial. # the context's IPv4 address: the first field after the cid when it has four parts (an IPv6 one has 16) want=$(at "AT+CGPADDR=$CID" 4 | awk -F'[ ,"]+' '/^\+CGPADDR:/ { if (split($3, o, ".") == 4 && $3 != "0.0.0.0") print $3; exit }' || true) have=$(ip -4 -o addr show "$IFACE" 2>/dev/null | awk '{ split($4, a, "/"); print a[1]; exit }' || true) - if [ -z "$want" ] || [ "$want" = "$have" ]; then + if [ -n "$have" ] && { [ -z "$want" ] || [ "$want" = "$have" ]; }; then fails=0 led_up continue fi + if [ "${MU300_NETIFD:-0}" = 1 ]; then + echo "active PDP address differs ($want; $IFACE has $have), requesting in-place renewal" >&2 + ubus call "network.interface.${MU300_WAN:-wan}" renew >/dev/null 2>&1 || true + fails=0 + continue + fi echo "the network gave the context a new address ($want; $IFACE still has $have), reconnecting" >&2 fails=1 # no second look needed: the next step reconnects fi # a switched-off radio never comes back on its own - at 'AT+CFUN?' 4 | grep -q '+CFUN: 1' || { echo "radio was off, switching it on" >&2; radio_on || true; } + watch_radio_if_off fails=$((fails + 1)) [ "$fails" -lt 2 ] && continue echo "mobile data lost (modem reset or detached), reconnecting" >&2 diff --git a/tests/test_cellular_mobility.py b/tests/test_cellular_mobility.py new file mode 100644 index 00000000..ab51059a --- /dev/null +++ b/tests/test_cellular_mobility.py @@ -0,0 +1,254 @@ +"""Mobility address renewal and watchdog decisions, with isolated AT/IP/netifd.""" +from helpers import ShellTest, TOP, BIN + + +MONITOR = TOP / 'openwrt/overlay/lib/netifd/proto/mu300cell-v6.sh' +SOURCE = MONITOR.read_text() +MOBILE = (BIN / 'mobile-data').read_text() + + +class Mobility(ShellTest): + def setUp(self): + super().setUp() + self.functions = SOURCE[SOURCE.index('mask2prefix() {'):SOURCE.index('\nlast_v6=$(v6_snapshot)')] + self.functions = self.functions.replace('/run/mu300-at', str(self.tmp / 'at')) + for name in ('at', 'at4', 'at6', 'at7'): + directory = self.tmp / name + directory.mkdir() + import os + os.mkfifo(directory / 'cmd') + self.calls = self.tmp / 'calls' + self.stub('logger', 'echo "log $*" >>"$STUBLOG/calls"') + self.stub('sleep', ':') # exercise grace decisions without waiting six seconds + self.stub('mu300-at', ''' +echo "at $MU300_AT_DIR $*" >>"$STUBLOG/calls" +[ "${AT_FAIL:-0}" = 0 ] || exit 1 +case "$*" in + *CGACT*) printf '%s\n' "${CGACT_REPLY:-+CGACT:1,1}" ;; + *CGCONTRDP*) cat "$STUBLOG/reply" ;; +esac +''') + self.stub('ip', ''' +echo "ip $*" >>"$STUBLOG/calls" +case "$*" in + '-4 -o addr show'*) [ "${KERNEL_MISSING:-0}" = 1 ] || echo '1: sipa_eth0 inet 10.0.0.1/8 scope global sipa_eth0' ;; + '-6 addr show'*) printf '%s\n' 'inet6 2408:1::2/64 scope global' 'valid_lft 60sec preferred_lft 30sec' ;; + '-6 route show'*) echo 'default via fe80::1 dev sipa_eth0 proto ra expires 100sec' ;; + '-4 addr add'*|'-4 addr replace'*) [ "${ADD_FAIL:-0}" = 0 ] || exit 1 ;; +esac +''') + self.reply = self.tmp / 'reply' + self.reply.write_text('+CGCONTRDP: 1,6,internet,10.0.0.2.255.0.0.0,,1.1.1.1,8.8.8.8\n') + self.proto = ''' +ip() { "$STUBLOG/stubs/ip" "$@"; } +logger() { "$STUBLOG/stubs/logger" "$@"; } +sleep() { "$STUBLOG/stubs/sleep" "$@"; } +proto_init_update() { echo "proto init $*" >>"$STUBLOG/calls"; } +proto_set_keep() { echo "proto keep $*" >>"$STUBLOG/calls"; } +proto_add_ipv4_address() { echo "proto address $*" >>"$STUBLOG/calls"; } +proto_add_ipv4_route() { echo "proto route $*" >>"$STUBLOG/calls"; } +proto_add_ipv6_address() { echo "proto v6address $*" >>"$STUBLOG/calls"; } +proto_add_ipv6_route() { echo "proto v6route $*" >>"$STUBLOG/calls"; } +proto_add_dns_server() { echo "proto dns $*" >>"$STUBLOG/calls"; } +proto_send_update() { echo "proto update $*" >>"$STUBLOG/calls"; [ "${REPORT_FAIL:-0}" = 0 ]; } +config=wan; ifname=sipa_eth0; sim_slot=0; logtag=test +ip4=10.0.0.1; prefix4=8; dns1=9.9.9.9; dns2=149.112.112.112; peerdns=1 +''' + + def refresh(self, shell, extra='', **env): + self.calls.unlink(missing_ok=True) + r = self.sh(shell, self.functions + self.proto + extra + ''' +rc=0; refresh_bearer cgev || rc=$? +printf 'rc=%s ip=%s/%s dns=%s,%s\n' "$rc" "$ip4" "$prefix4" "$dns1" "$dns2" +''', **env) + self.assertEqual(r.returncode, 0, r.stderr) + return r.stdout, self.calls.read_text() + + def test_replace_first_preserves_ipv6_lifetimes(self): + for shell in self.each_shell(): + output, calls = self.refresh(shell) + self.assertIn('rc=0 ip=10.0.0.2/8 dns=1.1.1.1,8.8.8.8', output) + self.assertLess(calls.index('ip -4 addr add 10.0.0.2/8'), calls.index('proto update wan')) + self.assertLess(calls.index('proto update wan'), calls.index('ip -4 addr del 10.0.0.1/8')) + self.assertIn('proto init sipa_eth0 1 1', calls) + self.assertIn('proto keep 0', calls) + self.assertIn('proto v6address 2408:1::2 64 30 60', calls) + self.assertIn('proto v6route :: 0 fe80::1 4096 100', calls) + self.assertNotIn('CGACT=0', calls) + + def test_empty_or_failed_at_keeps_old_snapshot(self): + for shell in self.each_shell(): + for env in ({'AT_FAIL': '1'}, {'CGACT_REPLY': 'OK'}, {'CGACT_REPLY': '+CGACT:11,1'}): + output, calls = self.refresh(shell, **env) + self.assertIn('rc=1 ip=10.0.0.1/8 dns=9.9.9.9,149.112.112.112', output) + self.assertNotIn('proto update', calls) + self.assertNotIn('ip -4 addr del', calls) + + def test_inactive_context_does_not_trust_stale_address(self): + for shell in self.each_shell(): + output, calls = self.refresh(shell, CGACT_REPLY='+CGACT: 1,0') + self.assertIn('rc=2 ip=10.0.0.1/8', output) + self.assertEqual(calls.count(';+CGACT?'), 4) + self.assertNotIn('proto update', calls) + + def test_failed_update_can_be_retried(self): + for shell in self.each_shell(): + for failure in ('ADD_FAIL', 'REPORT_FAIL'): + output, calls = self.refresh(shell, **{failure: '1'}) + self.assertIn('rc=1 ip=10.0.0.1/8', output) + self.assertNotIn('ip -4 addr del', calls) + self.calls.unlink(missing_ok=True) + code = self.functions + self.proto + ''' +REPORT_FAIL=1 +refresh_bearer cgev || true +REPORT_FAIL=0 +refresh_bearer cgev +echo "$ip4/$prefix4" +''' + r = self.sh(shell, code) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('10.0.0.2/8', r.stdout) + self.assertIn('ip -4 addr del 10.0.0.1/8', self.calls.read_text()) + + def test_invalid_address_and_noncontiguous_mask_rejected(self): + for address in ('999.0.0.2.255.0.0.0', '10.0.0.2.255.0.255.0'): + self.reply.write_text(f'+CGCONTRDP: 1,6,internet,{address},,1.1.1.1,8.8.8.8\n') + for shell in self.each_shell(): + output, calls = self.refresh(shell) + self.assertIn('rc=1 ip=10.0.0.1/8', output) + self.assertNotIn('proto update', calls) + + def test_same_ip_missing_from_kernel_is_restored(self): + self.reply.write_text('+CGCONTRDP: 1,6,internet,10.0.0.1.255.0.0.0,,9.9.9.9,149.112.112.112\n') + for shell in self.each_shell(): + _, calls = self.refresh(shell, KERNEL_MISSING='1') + self.assertIn('ip -4 addr add 10.0.0.1/8', calls) + self.assertIn('proto update wan', calls) + self.assertNotIn('ip -4 addr del', calls) + + def test_sim_two_only_uses_its_owner(self): + for shell in self.each_shell(): + _, calls = self.refresh(shell, extra='sim_slot=1\n') + self.assertIn(f'at {self.tmp}/at4', calls) + self.assertIn('AT+SPACTCARD=1;+CGCONTRDP=1', calls) + self.assertNotIn(f'at {self.tmp}/at6', calls) + + def test_zero_dns_is_absent_and_ipv6_reply_does_not_hide_ipv4(self): + self.reply.write_text('+CGCONTRDP: 1,6,internet,' + '.'.join(['0'] * 32) + ',,,\n' + '+CGCONTRDP: 1,6,internet,"10.0.0.2.255.0.0.0",,"1.1.1.1","0.0.0.0"\r\n') + for shell in self.each_shell(): + output, calls = self.refresh(shell) + self.assertIn('dns=1.1.1.1,', output) + self.assertNotIn('proto dns 0.0.0.0', calls) + + def test_cgev_burst_coalesces_but_hint_during_refresh_is_retained(self): + start = SOURCE.index('\t\tcase $line in') + case = SOURCE[start:SOURCE.index('\n\t\tesac', start) + len('\n\t\tesac')] + for shell in self.each_shell(): + code = f'pdp_pending="{self.tmp}/pending"\n' + for line in ('+CGEV: NW ACT 11,17', '+CGEV: NW MODIFY 1,8', '+SPPCODATA: 1'): + code += f"line='{line}'\n" + case + '\n' + code += 'rm -f "$pdp_pending"\n' # consumer begins its fresh AT read + code += "line='+CGEV: NW DETACH'\n" + case + '\nrm -f "$pdp_pending"\n' + r = self.sh(shell, code) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout.splitlines(), ['pdp', 'pdp']) + + def test_setup_starts_one_monitor_for_each_pdp_family(self): + proto = (MONITOR.parent / 'mu300cell.sh').read_text() + setup = proto[proto.index('proto_mu300cell_setup() {'):proto.index('\nproto_mu300cell_renew()')] + setup = setup.replace('/run/', str(self.tmp) + '/') + setup = setup.replace('/proc/sys/', str(self.tmp / 'sys') + '/') + setup = setup.replace('/tmp/mu300cell.err', str(self.tmp / 'error')) + setup = setup.replace('/opt/mu300/bin/mobile-data', str(self.stubs / 'mobile-data')) + setup = setup.replace('/opt/mu300/bin/mu300-sim-env', str(self.tmp / 'sim-env')) + (self.tmp / 'sim-env').write_text('mu300_sim_env() { MU300_SIM_SLOT=0; MU300_SIM_DEVICE=mob_sipa; }\n') + self.stub('mobile-data', "printf '%s\\n' 'IP=10.0.0.2' 'IFACE=mob_sipa' 'PREFIX=8' 'DNS1=1.1.1.1' 'DNS2=8.8.8.8'") + for shell in self.each_shell(): + for family in ('IP', 'IPV4V6'): + self.calls.unlink(missing_ok=True) + code = self.proto + setup + ''' +json_get_vars() { apn=internet; pdptype=$TEST_PDP_TYPE; peerdns=1; } +proto_run_command() { echo "run $*" >>"$STUBLOG/calls"; } +proto_mu300cell_setup wan +''' + r = self.sh(shell, code, TEST_PDP_TYPE=family) + self.assertEqual(r.returncode, 0, r.stderr) + commands = [line for line in self.calls.read_text().splitlines() if line.startswith('run ')] + self.assertEqual(len(commands), 1) + self.assertIn('mu300cell-v6.sh wan mob_sipa 10.0.0.2 8 1.1.1.1 8.8.8.8 1 0', commands[0]) + + +class Watchdog(ShellTest): + def setUp(self): + super().setUp() + self.context = MOBILE[MOBILE.index('watch_context_state() {'):MOBILE.index('\nwatch() {')] + self.watch = MOBILE[MOBILE.index('watch() {'):MOBILE.index('\n# Radio quality')] + self.watch = self.watch.replace('/run/', str(self.tmp) + '/') + self.stub('sleep', ''' +n=$(cat "$STUBLOG/round" 2>/dev/null || echo 0); n=$((n+1)); echo "$n" >"$STUBLOG/round" +[ "$n" -le "${ROUNDS:-1}" ] || exit 99 +''') + self.stub('ip', "echo '1: sipa_eth0 inet 10.0.0.1/8 scope global sipa_eth0'") + self.stub('jsonfilter', 'echo false') + self.stub('ubus', 'echo "ubus $*" >>"$STUBLOG/calls"') + self.stub('ifup', 'echo "ifup $*" >>"$STUBLOG/calls"') + self.stub('led-status', ':') + + def test_context_forms_and_timeouts_are_distinct(self): + for shell in self.each_shell(): + for reply, expected in [('+CGACT: 1,1\r\n+CGACT:11,1', 0), + ('+CGACT:1,0', 1), ('+CGACT:11,1', 2), ('OK', 2)]: + code = self.context + '\nCID=1\nat() { printf "%s\\n" "$REPLY"; }\nwatch_context_state' + r = self.sh(shell, code, REPLY=reply) + self.assertEqual(r.returncode, expected, r.stderr) + + def run_watch(self, **env): + for name in ('calls', 'round'): + (self.tmp / name).unlink(missing_ok=True) + code = 'set -euo pipefail\n' + self.context + self.watch + ''' +CID=1; DEV=/dev/null; IFACE=sipa_eth0; DEVICE=f50 +MU300_NETIFD=1 +modem_stack() { return 0; } +at_owner_alive() { return 1; } +mu300_sim_env() { MU300_SIM_DEVICE=sipa_eth0; } +tty_setup() { :; } +led_up() { :; } +radio_on() { echo radio_on >>"$STUBLOG/calls"; } +at() { + echo "at $*" >>"$STUBLOG/calls" + case "$1" in + *CGACT*) [ "${AT_FAIL:-0}" = 0 ] || return 1; echo "${CGACT_REPLY:-+CGACT:1,1}" ;; + *CGPADDR*) echo '+CGPADDR: 1,10.0.0.2' ;; + *CFUN*) [ "${CFUN_FAIL:-0}" = 0 ] || return 1; echo "${CFUN_REPLY:-+CFUN: 1}" ;; + esac +} +watch +''' + r = self.sh(['bash'], code, **env) + self.assertEqual(r.returncode, 99, r.stderr) + return (self.tmp / 'calls').read_text() + + def test_address_change_requests_renew_not_redial(self): + calls = self.run_watch() + self.assertIn('ubus call network.interface.wan renew', calls) + self.assertNotIn('ifup', calls) + self.assertNotIn('CFUN', calls) + self.assertNotIn('radio_on', calls) + + def test_at_failure_does_not_reconnect_or_turn_on_radio(self): + calls = self.run_watch(AT_FAIL='1', ROUNDS='2') + self.assertNotIn('CFUN', calls) + self.assertNotIn('ifup', calls) + self.assertNotIn('radio_on', calls) + + def test_confirmed_loss_recovers_but_failed_cfun_is_not_radio_off(self): + calls = self.run_watch(CGACT_REPLY='+CGACT:1,0', CFUN_FAIL='1', ROUNDS='2') + self.assertIn('ifup wan', calls) + self.assertNotIn('radio_on', calls) + + def test_erased_contexts_still_repair_explicit_radio_off(self): + calls = self.run_watch(CGACT_REPLY='OK', CFUN_REPLY='+CFUN: 0') + self.assertIn('radio_on', calls) + calls = self.run_watch(CGACT_REPLY='OK', CFUN_FAIL='1') + self.assertNotIn('radio_on', calls) diff --git a/tests/test_static.py b/tests/test_static.py index bf4c9bcd..4968ba3a 100644 --- a/tests/test_static.py +++ b/tests/test_static.py @@ -138,7 +138,12 @@ class Rules(unittest.TestCase): self.assertIn('cat /run/mu300-usb-host-mac', defaults) self.assertIn('mu300cell-v6.sh', builder) self.assertIn('tools/keys/mu300-keys', builder) - self.assertTrue((TOP / 'openwrt' / 'overlay' / 'lib' / 'netifd' / 'proto' / 'mu300cell-v6.sh').is_file()) + renew = TOP / 'openwrt' / 'overlay' / 'lib' / 'netifd' / 'proto' / 'mu300cell-v6.sh' + self.assertTrue(renew.is_file()) + renew_text = renew.read_text() + self.assertIn('*+CGEV:*ACT*', renew_text) + self.assertIn('*+CGEV:*DETACH*', renew_text) + self.assertIn('*+SPPCODATA:*', renew_text) def test_aurora_is_baked_into_openwrt_and_default(self): rootfs = (TOP / 'openwrt' / 'build-rootfs.sh').read_text() diff --git a/tests/test_wcn_recovery.py b/tests/test_wcn_recovery.py index 4e94c12a..20e1fcd8 100644 --- a/tests/test_wcn_recovery.py +++ b/tests/test_wcn_recovery.py @@ -169,14 +169,19 @@ class ReopenScript(ShellTest): dev = root / phy / 'device' / 'driver' dev.mkdir(parents=True) (dev / 'module').symlink_to(driver) - self.stub('wifi', 'echo "$*" >> "$STUBLOG/wifi"\n[ "$1" != down ]') # still attempt up after failed down + self.stub('wifi', 'echo "$*" >> "$STUBLOG/wifi"\n' + '[ "$1" != down ] || { [ "$DISABLE_DURING_DOWN" != 1 ] || ' + 'touch "$STUBLOG/disabled"; exit 1; }') # still attempt up after failed down self.stub('logger', ':') script = (TOP / 'openwrt/overlay/opt/mu300/bin/wcn-reopen').read_text() # Minimal config API fixture; the production selection/lock/reopen code runs unchanged. fixture = r''' config_load() { :; } config_foreach() { "$1" radio0; "$1" radio1; } -config_get_bool() { eval "$1=\"${DISABLED:-0}\""; } +config_get_bool() { + if [ -f "$STUBLOG/disabled" ]; then eval "$1=1"; + else eval "$1=\"${DISABLED:-0}\""; fi +} config_get() { case "${BINDING:-phy}:$2:$3" in phy:radio0:phy) eval "$1=phy0" ;; @@ -200,6 +205,13 @@ config_get() { else: self.assertFalse((self.tmp / 'wifi').exists()) self.assertFalse((self.tmp / 'lock').exists()) + (self.tmp / 'wifi').unlink(missing_ok=True) + r = self.sh(shell, script, DISABLE_DURING_DOWN='1') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual((self.tmp / 'wifi').read_text().splitlines(), ['down radio0']) + self.assertFalse((self.tmp / 'lock').exists()) + (self.tmp / 'disabled').unlink() + (self.tmp / 'wifi').unlink() (self.tmp / 'lock').mkdir() r = self.sh(shell, script) self.assertEqual(r.returncode, 0, r.stderr) diff --git a/tests/test_wifi_rx_forward.py b/tests/test_wifi_rx_forward.py new file mode 100644 index 00000000..32390da1 --- /dev/null +++ b/tests/test_wifi_rx_forward.py @@ -0,0 +1,116 @@ +"""Run the production AP RX forwarding branch with mocked kernel primitives.""" +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from helpers import TOP + +RX = TOP / 'upstream/modules/sprd_wlan_combo/sc2355/rx.c' + + +def forwarding_branch(text): + start = text.index('\tif ((vif->mode == SPRD_MODE_AP ||\n' + '\t vif->mode == SPRD_MODE_P2P_GO) && msdu_desc->uc_w2w_flag)') + return text[start:text.index('\n\t\t/* skb->data MUST point to ETH HDR */', start)] + + +class RxForwarding(unittest.TestCase): + def run_branch(self, branch, old=False): + if not shutil.which('cc'): + self.skipTest('requires a host C compiler') + code = r''' +#include +#include +#include +#define SPRD_MODE_AP 2 +#define SPRD_MODE_P2P_GO 3 +#define SPRD_MODE_STATION 1 +#define ETH_P_IP 0x0800 +#define ETH_P_IPV6 0x86dd +#define ETH_P_ARP 0x0806 +#define GFP_ATOMIC 0 +#define likely(x) (x) +struct ethhdr { unsigned short h_proto; }; +struct sk_buff { void *dev, *data; }; +struct vif { int mode; }; +struct desc { int uc_w2w_flag, bc_mc_w2w_flag; }; +static struct sk_buff copied; +static int forwarded, delivered, copies, fail_copy; +static struct sk_buff *pskb_copy(struct sk_buff *s, int flags) { + copies++; + if (fail_copy) return 0; + copied = *s; return &copied; +} +static void dev_queue_xmit(struct sk_buff *s) { assert(s->dev); forwarded++; } +static void run(int mode, int uc, int bc, unsigned short proto) { + struct vif v = {mode}, *vif = &v; + struct desc d = {uc, bc}, *msdu_desc = &d; + struct ethhdr h = {htons(proto)}; + struct sk_buff s = {.data=&h}, *skb = &s, *tx_skb; + void *ndev = &h; + forwarded = delivered = copies = 0; +''' + branch + r''' + delivered++; + } +} +int main(int argc, char **argv) { + if (argc > 1) { + if (htons(ETH_P_IP) == ETH_P_IP) return 0; + run(SPRD_MODE_AP, 0, 1, ETH_P_IP); + assert(forwarded == 1 && delivered == 1 && copies == 1); + return 0; + } + for (int mode = SPRD_MODE_AP; mode <= SPRD_MODE_P2P_GO; mode++) { + for (int ip = 0; ip < 2; ip++) { + run(mode, 0, 1, ip ? ETH_P_IPV6 : ETH_P_IP); + assert(forwarded == 0 && delivered == 1 && copies == 0); + } + run(mode, 0, 1, ETH_P_ARP); + assert(forwarded == 1 && delivered == 1 && copies == 1); + fail_copy = 1; run(mode, 0, 1, ETH_P_ARP); + assert(forwarded == 0 && delivered == 1 && copies == 1); fail_copy = 0; + run(mode, 1, 0, ETH_P_IP); + assert(forwarded == 1 && delivered == 0 && copies == 0); + run(mode, 0, 0, ETH_P_IP); + assert(forwarded == 0 && delivered == 1 && copies == 0); + } + run(SPRD_MODE_STATION, 0, 1, ETH_P_IPV6); + assert(forwarded == 0 && delivered == 1 && copies == 0); + return 0; +} +''' + with tempfile.TemporaryDirectory(prefix='mu300-rx-forward-') as temp: + src, exe = Path(temp) / 'check.c', Path(temp) / 'check' + src.write_text(code) + subprocess.run(['cc', '-std=c11', '-fsanitize=address,undefined', + str(src), '-o', str(exe)], check=True, capture_output=True) + subprocess.run([str(exe)] + (['old'] if old else []), check=True, timeout=5) + + def test_ap_go_ip_multicast_is_stack_only_and_other_forwarding_survives(self): + self.run_branch(forwarding_branch(RX.read_text())) + + def test_original_vendor_branch_reproduces_the_extra_copy(self): + branch = forwarding_branch(RX.read_text()) + branch = branch.replace('htons(ETH_P_IP)', 'ETH_P_IP') + branch = branch.replace('htons(ETH_P_IPV6)', 'ETH_P_IPV6') + self.run_branch(branch, old=True) + + def test_legacy_patch_applies_and_matches_the_production_branch(self): + if not shutil.which('patch'): + self.skipTest('requires patch') + text = RX.read_text() + fixed = forwarding_branch(text) + old = fixed.replace('\t\t\t/* IP multicast is forwarded by the host network stack. */\n', '') + old = old.replace('eth->h_proto != htons(ETH_P_IP)', 'eth->h_proto != ETH_P_IP') + old = old.replace('eth->h_proto != htons(ETH_P_IPV6)', 'eth->h_proto != ETH_P_IPV6') + original = text.replace(fixed, old, 1) + with tempfile.TemporaryDirectory(prefix='mu300-legacy-forward-') as temp: + source = Path(temp) / 'sc2355/rx.c' + source.parent.mkdir(); source.write_text(original) + patch = (TOP / 'kernel/patches/wlan_combo-rx-ip-multicast-endian.patch').read_bytes() + subprocess.run(['patch', '-p1', '--batch'], input=patch, cwd=temp, + check=True, capture_output=True) + self.assertEqual(source.read_text(), text) + self.run_branch(forwarding_branch(source.read_text())) diff --git a/tests/test_wifi_tx_logging.py b/tests/test_wifi_tx_logging.py index 0444ced4..f3dcf32d 100644 --- a/tests/test_wifi_tx_logging.py +++ b/tests/test_wifi_tx_logging.py @@ -18,6 +18,62 @@ def function(text, name): class TxPressureLogging(unittest.TestCase): + def test_stale_peer_logging_keeps_pcie_and_sdio_rejection(self): + for backend in ('pcie', 'sdio'): + text = (WLAN / (backend + '.c')).read_text() + start = text.index('\tif (lut_index < 6 && (!sc2355_is_group(hif->skb_da))) {') + branch = text[start:text.index('\n\t}', start) + 3] + self.assertIn('pr_debug_ratelimited(', branch) + self.assertNotIn('pr_err(', branch) + self.run_c(r''' +#include +#include +#define pr_debug_ratelimited(...) ((void)0) +struct sprd_hif { unsigned char skb_da[6]; }; +static int sc2355_is_group(unsigned char *addr) { return addr[0] & 1; } +static int check(int lut_index, struct sprd_hif *hif) { +''' + branch + r''' + return 0; +} +int main(void) { + struct sprd_hif h = {0}; + for (int group = 0; group < 2; group++) { + h.skb_da[0] = group; + for (int lut = 0; lut < 8; lut++) + assert(check(lut, &h) == ((lut < 6 && !group) ? -EPERM : 0)); + } + return 0; +} +''') + + def test_tx_failure_frees_each_packet_even_when_logging_is_limited(self): + text = (WLAN.parent / 'common/iface.c').read_text() + start = text.index('\tif (ret) {', text.index('\tret = sprd_send_data(vif->priv, vif, msg, skb,')) + branch = text[start:text.index('\n\t}', start) + 3] + self.run_c(r''' +#include +#define NETDEV_TX_OK 0 +static int logs, checks, freed, messages; +static int net_ratelimit(void) { return checks++ < 10; } +#define netdev_err(...) (++logs) +static void dev_kfree_skb(void *p) { ++freed; } +static void sprd_chip_free_msg(void *p, void *msg) { ++messages; } +struct priv { int chip; }; +struct vif { struct priv *priv; }; +static int check(int ret, struct vif *vif) { + void *skb = vif, *msg = vif; +''' + branch + r''' + return 99; +} +int main(void) { + struct priv p = {0}; struct vif v = {&p}; + assert(check(0, &v) == 99 && !freed && !messages && !checks); + for (int i = 0; i < 50000; i++) assert(check(-1, &v) == NETDEV_TX_OK); + assert(freed == 50000 && messages == 50000 && logs == 10 && checks == 50000); + return 0; +} +''') + def run_c(self, code): cc = shutil.which('cc') if not cc: diff --git a/upstream/modules/sprd_wlan_combo/common/iface.c b/upstream/modules/sprd_wlan_combo/common/iface.c index d7c98194..974b5efe 100644 --- a/upstream/modules/sprd_wlan_combo/common/iface.c +++ b/upstream/modules/sprd_wlan_combo/common/iface.c @@ -742,7 +742,8 @@ static netdev_tx_t iface_start_xmit(struct sk_buff *skb, struct net_device *ndev ret = sprd_send_data(vif->priv, vif, msg, skb, SPRD_DATA_TYPE_NORMAL, offset, true); if (ret) { - netdev_err(ndev, "%s drop msg due to TX Err\n", __func__); + if (net_ratelimit()) + netdev_err(ndev, "%s drop msg due to TX Err\n", __func__); /* FIXME * as debug sdiom later, just drop the msg here * wapi temp drop diff --git a/upstream/modules/sprd_wlan_combo/sc2355/pcie.c b/upstream/modules/sprd_wlan_combo/sc2355/pcie.c index 40fdd0e2..923f0ddf 100644 --- a/upstream/modules/sprd_wlan_combo/sc2355/pcie.c +++ b/upstream/modules/sprd_wlan_combo/sc2355/pcie.c @@ -1077,7 +1077,7 @@ unsigned char sc2355_pcie_find_lut_index(struct sprd_hif *hif, struct sprd_vif * for (i = 0; i < MAX_LUT_NUM; i++) { if ((sc2355_is_group(hif->peer_entry[i].tx.da)) && hif->peer_entry[i].ctx_id == vif->ctx_id) { - pr_info("%s, %d, group lut_index=%d\n", + pr_debug_ratelimited("%s, %d, group lut_index=%d\n", __func__, __LINE__, hif->peer_entry[i].lut_index); return hif->peer_entry[i].lut_index; @@ -1187,7 +1187,7 @@ int sc2355_pcie_hif_fill_msdu_dscr(struct sprd_vif *vif, lut_index = sc2355_pcie_find_lut_index(hif, vif); if (lut_index < 6 && (!sc2355_is_group(hif->skb_da))) { - pr_err("%s, %d, sta disconn, no data tx!", __func__, __LINE__); + pr_debug_ratelimited("%s, %d, sta disconn, no data tx!", __func__, __LINE__); return -EPERM; } //skb_push(skb, sizeof(struct tx_msdu_dscr) + offset + dscr_rsvd); diff --git a/upstream/modules/sprd_wlan_combo/sc2355/rx.c b/upstream/modules/sprd_wlan_combo/sc2355/rx.c index d0d94b08..753cc33e 100644 --- a/upstream/modules/sprd_wlan_combo/sc2355/rx.c +++ b/upstream/modules/sprd_wlan_combo/sc2355/rx.c @@ -284,8 +284,9 @@ static void rx_skb_process(struct sprd_priv *priv, struct sk_buff *skb) msdu_desc->bc_mc_w2w_flag) { struct ethhdr *eth = (struct ethhdr *)skb->data; - if (eth->h_proto != ETH_P_IP && - eth->h_proto != ETH_P_IPV6) { + /* IP multicast is forwarded by the host network stack. */ + if (eth->h_proto != htons(ETH_P_IP) && + eth->h_proto != htons(ETH_P_IPV6)) { tx_skb = pskb_copy(skb, GFP_ATOMIC); if (likely(tx_skb)) { tx_skb->dev = ndev; diff --git a/upstream/modules/sprd_wlan_combo/sc2355/sdio.c b/upstream/modules/sprd_wlan_combo/sc2355/sdio.c index 115f46fa..33afffa7 100755 --- a/upstream/modules/sprd_wlan_combo/sc2355/sdio.c +++ b/upstream/modules/sprd_wlan_combo/sc2355/sdio.c @@ -708,7 +708,7 @@ unsigned char sc2355_find_lut_index(struct sprd_hif *hif, struct sprd_vif *vif) for (i = 0; i < MAX_LUT_NUM; i++) { if ((sc2355_is_group(hif->peer_entry[i].tx.da)) && hif->peer_entry[i].ctx_id == vif->ctx_id) { - pr_info("%s, %d, group lut_index=%d\n", + pr_debug_ratelimited("%s, %d, group lut_index=%d\n", __func__, __LINE__, hif->peer_entry[i].lut_index); return hif->peer_entry[i].lut_index; @@ -820,7 +820,7 @@ int sc2355_hif_fill_msdu_dscr(struct sprd_vif *vif, lut_index = sc2355_find_lut_index(hif, vif); if (lut_index < 6 && (!sc2355_is_group(hif->skb_da))) { - pr_err("%s, %d, sta disconn, no data tx!", __func__, __LINE__); + pr_debug_ratelimited("%s, %d, sta disconn, no data tx!", __func__, __LINE__); return -EPERM; } skb_push(skb, sizeof(struct tx_msdu_dscr) + offset + dscr_rsvd);