feat(mu300): add verified lock reset and backport network recovery fixes

Backport bounded WCN recovery, RX refill backoff and IPv6 prefix deprecation to the shared 6.18/7.2 paths without automatic system reboots.

Add a confirmed, per-SIM cellular lock reset with fresh readback, interrupted-cleanup protection and English/Turkish/Chinese messages. Document shared F50 NR masks and invalidate the other SIM view without deleting its saved settings.

Validation: 305 regression tests (301 passed, 4 skipped), both kernel module builds and isolated native OpenWrt RA capture. Lock reset hot-deployed and verified through LuCI on both SIMs; new drivers not deployed and cold-boot validation not performed.
This commit is contained in:
kanoqwq committed 2026-10-11 03:34:02 +08:00
1 parent 5c8c2f9582
commit 23361cea51
27 files changed
+1363 -60

No files matched your search

+114
View File
@@ -0,0 +1,114 @@
# 2026-10-11:Wi-Fi 故障恢复与 IPv6 前缀更新
比较范围:上次审查的 `5582413` → 上游 main `18cfac1`,共 14 个非合并提交。
本次是选择性移植,不整合上游整棵驱动目录,也不改变既有启动流程。
## 纳入的修复
| 上游提交 | 本分支落地方式 |
| --- | --- |
| `4a74df2` | RX 补充缓冲失败且没有进展时,20 ms 起指数退避、上限 1 秒;有进展立即恢复。RX 事件不能绕过退避,错误日志限流,工作队列适当让出 CPU。 |
| `b96ea84` | 修正 WCN 电源关闭期间 assert 分支漏解锁;恢复、手工 dump/reset 的锁等待有截止时间,不无限堵住调用者。 |
| `5bb2b26`、`e8759a2` | 接入一次受控 WCN 芯片复位及恢复通知;复位与 dump 串行,通知从可睡眠工作上下文发送,不在原子通知链直接发送 uevent。忽略不安全的固件 RX flush 请求。 |
| `a2b6d35` | 运营商换了 /64 后,通过 RA 将旧前缀首选寿命设为 0;保留非零网关寿命,最多发送三轮。补入 `ucode-mod-socket` 构建依赖。 |
### 与上游的差异
- `recovery_reboot` **默认关闭**。持续故障约 10 秒后只尝试一次芯片复位;
约 70 秒仍失败或再次故障时记录错误并停止自动恢复。不会默认重启整机,
不让 Wi-Fi 单点故障打断 USB、蜂窝服务。这是故障路径,不给正常启动增加等待。
- 加入 RX teardown 的 stopping 标记,阻止清理期间重新排定 retry;
watchdog 停止和再次 probe 的状态也有明确处理。
- misc 设备、网络通知注册成功后才发布 reset notifier;失败逐项撤销注册。
卸载时先取消 notifier 和待执行通知,再释放 misc 设备。
- OpenWrt `wcn-reopen` 用单实例锁,只对 sysfs 确认属于 `sprd_wlan_combo`
且未在配置中禁用的 radio 执行 down/up。外接无线网卡、USB、WAN 不动,
不写 UCI、不新增开机 sleep、不常驻轮询。firmware 事件才触发。
- IPv6 适配现有 `openwrt/overlay` 路径,不替换路由实现。保留 LAN /64、
/128 邻居路由和错误 WAN /128 清理;仅 relay 模式发送弃用通知。
WAN 短暂消失后取得相同前缀不弃用,重新出现的前缀取消后续弃用;
helper 失败也只尝试三轮,不高频重试,不进行 USB 重枚举。
- 保留 20 ms BA 重排超时、软件 RX 校验和、TX/EDMA 压力计数、已有 USB
二次枚举与基带启动优化。
## 不包含
- 5.4 专属 fw4 flowtable 修复、Ubuntu Wi-Fi 客户端恢复。
- 已有的 WAN IPv6 重启处理、TF 双槽安装、邻区频段判定不重复覆盖。
- 本次驱动改动只在共享的 **6.18 / 7.2** 源码验证,没有宣称移植到 5.4。
- 不新增 Docker 用户态,不变更内核配置,不重新打包 rootfs/Magisk ZIP。
## 验证与产物
- 新增 host C 测试:执行实际 RX refill/watchdog 函数,覆盖连续失败、
有进展立即恢复、退出保护、一次复位、复发停止以及默认不整机重启。
- shell 测试覆盖前缀变化/同前缀恢复/NAT6 跳过/三轮限制/网关寿命,
以及只重开匹配且启用的 WCN radio、down 失败仍尝试 up、并发事件互斥。
- 全量 Python 回归:295 项,291 通过、4 跳过,使用 `MU300_TEST_SHELLS=dash,bash`。
- 两套驱动(WCN、WLAN 及依赖 WCN 的 Bluetooth)分别重新编译,使用已验证的
相同 Image/config;产物单独放入 `upstream/out-stability-6.18` 和
`upstream/out-stability-7.2`,不覆盖此前已部署的 `out-features-*`。
模块清单、BTF、vermagic 及内核能力检查通过。
- `tests/runtime_ra_deprecate.sh` 用隔离容器内 veth 验证实际 RA,不使用设备或
电脑物理网卡。ARM QEMU 用户态不支持所需的部分 socket/ethtool 操作,
应使用原生 OpenWrt 容器执行此项。
原生 OpenWrt 25.12.5 已抓包通过:源地址为 LAN link-local、目的地址
`ff02::1`、Hop Limit 255、ICMPv6 checksum 正确、router lifetime 1234 秒,
旧 /64 valid 7200 秒 / preferred 0 秒。非法前缀和网关寿命输入均被拒绝。
后续打包须显式选择对应的 `MU300_UPSTREAM_OUT`(TF / bundle)或
`MU300_MAINLINE_OUT`(rootfs)。新 WLAN 引用了新的 WCN 导出符号,
不能只替换 WLAN 而保留旧 WCN;应更新同一次构建的模块集合。
以上驱动检查不是实机故障恢复验收。没有部署这些新驱动、制造 firmware assert
或重启整机;运行中热卸载 Wi-Fi 驱动也不在本轮操作范围内。
后续仅热部署了下述看板清除功能,并做了真实蜂窝协议栈测试。
## 后续补入:清除当前 SIM 全部蜂窝锁定
借鉴上游 `766dfaff` 的清除范围,重新接入本插件的双卡、任务结果和持久化逻辑,
没有直接移植上游的先删文件、后执行写入流程。
- 入口在「蜂窝 → 网络锁定」底部。当前查看 SIM 就是指令及保存文件的操作对象;
确认框显示卡号,确认期间查看卡槽改变则要求重新确认。
- 模式恢复自动(5G/4G)、开启 EN-DC、LTE/NR 频段恢复自动、解除两种小区锁定。
保留另一个 SIM 的模式、主数据卡字段、保存配置,以及各卡开机自动应用开关。
- **实机发现硬件共享项**:F50 通过 `SPACTCARD=1` 写 NR 掩码后,
`SPACTCARD=0;SPLBAND=3` 同样读到新值。EN-DC 则可以独立回读为主卡 1、副卡 0。
因此不能承诺所有运行时锁定均能双卡隔离。页面与确认框三语均明确提示共享项
会影响另一张卡,另一张卡保留的开机配置也可能再次改变共享项。
清除前后会使另一卡锁定缓存失效,避免继续显示旧掩码;不删除另一卡保存文件。
- 复用全局设置互斥锁和后台任务。先写入并逐项新鲜回读,再只执行一次协议栈
重启,确认射频恢复并再次逐项回读。状态轮询不额外发送 AT。
- 全部核对成功后才删除当前 SIM 的五个保存项。删除前原子发布 `reset_pending`
标记;若进程在多文件清理间中断,下次 early/late 回放先完成清理,禁止回放旧项。
存储错误会报告失败,不冒充清除成功。整个 SIM 目录和身份信息目录不会删除。
- 模组拒绝、无响应、回读不一致、重启失败时保留原有保存项;提示部分运行状态
可能已经改变,要求刷新核对。不是多条 AT 命令的原子回滚。
- 复用主题化确认框、toast 和按钮 loading,补齐中文、英文、土耳其语;
不新增常驻进程、正常开机等待或页面周期查询。
测试使用隔离的模拟 AT,覆盖双卡保存隔离、模式字段保留、逐项回读、重启后漂移、
缺失 OK、明确拒绝、清理中断恢复、存储错误、异步完成和前端确认/loading/翻译。
锁定专项最终 36 项通过(新增双卡缓存失效但保存文件不变的用例)。
更新后的全量回归 305 项:301 通过、4 项环境相关跳过。
Shell/JavaScript 语法及 `git diff --check` 通过。
### 实机热部署验证
- 设备:MU300 / OpenWrt 25.12.5 / Linux 7.2.8;原五个文件均与仓库 HEAD 基线一致。
原文件及双卡保存配置备份在 `/etc/unisoc-modem/backup/lock-reset.hpBPAP/before.tgz`。
只部署插件五个文件,上传与安装后 SHA-256 核对,没有更新内核、Wi-Fi、USB 配置。
- 在真实 LuCI 页面点击,先取消确认验证不下发,再确认执行。SIM1 用时 7.644 秒,
SIM2 用时 7.784 秒,任务均为 done/ok=1,loading 正常结束。每次一个 SFUN 5→4。
- 将副卡 EN-DC 临时设为关闭后清除主卡:副卡仍回读 0,保存项仍为 off,主卡
auto_apply=on 保留,副卡显示缓存已失效。随后清除副卡:EN-DC 回读 1,副卡
临时保存项删除,主卡开机开关不变。所有测试状态都已恢复为自动模式、EN-DC 开启。
- 结束时两卡模式字段 134/134、主数据卡 0、NR 原始掩码 0,0,0,LTE 为全支持集,
LTE/NR 小区锁定为空,CFUN=1,WAN up=true,任务互斥锁已释放。
- 实机使用独立临时完成标记验证空配置 early/late 回放;即使将 AT 执行器设为
`/bin/false` 也成功,证明清除后的保存配置不需要再次下发旧锁定。
这不是整机断电重启测试;没有重启整机或重打安装包。
- 登录跳转阶段捕获到 LuCI `String.format` 初始化异常(luci.js:161);
登录后重新加载的锁定页以及两次实际清除均没有 JavaScript 异常。
本次没有修改 LuCI 框架文件。
+2 -1
View File
@@ -129,7 +129,7 @@ mkdir -p /var/lock /var/run /tmp
apk update >/dev/null
# openssl-util: mu300-vpn fetches the VPN server certificate with it to pin, for links that ask for allowInsecure;
# i2c-tools, gpiod-tools: mu300-usb (the charger of the U30 Air) and mu300-nfc (its NFC tag)
apk add wpad-basic-mbedtls wifi-scripts iwinfo wireless-regdb iw bash ip-full coreutils-stty openssl-util curl ca-bundle msmtp ucode ucode-mod-fs ucode-mod-ubus ucode-mod-uci ucode-mod-uloop \
apk add wpad-basic-mbedtls wifi-scripts iwinfo wireless-regdb iw bash ip-full coreutils-stty openssl-util curl ca-bundle msmtp ucode ucode-mod-fs ucode-mod-ubus ucode-mod-uci ucode-mod-uloop ucode-mod-socket \
i2c-tools gpiod-tools >/dev/null
apk add --allow-untrusted /in/luci-theme-aurora.apk >/dev/null
apk add --allow-untrusted /in/luci-app-aurora-config.apk /in/aurora-config-zh-cn.apk /in/aurora-config-tr.apk >/dev/null
@@ -154,6 +154,7 @@ printf "mu300\n" > $R/etc/hostname # the real one comes from uci (etc/uci-defa
cp -a /in/opt-mu300 $R/opt/mu300
cp -a /in/overlay/. $R/
chmod 0755 $R/opt/mu300/bin/cpu-voltage-platform $R/etc/init.d/mu300-cpu-driver
chmod 0755 $R/opt/mu300/bin/ra-deprecate $R/opt/mu300/bin/wcn-reopen
[ -s $R/www/luci-static/aurora/main.css ] || { echo "Aurora theme assets missing" >&2; exit 1; }
for f in www/luci-static/resources/view/aurora/studio.js \
www/luci-static/resources/view/aurora/marketplace.js \
+1 -1
View File
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-mu300
PKG_VERSION:=1.2.0
PKG_RELEASE:=10
PKG_RELEASE:=11
PKG_LICENSE:=MIT
PKG_MAINTAINER:=MU300 Linux contributors
PKGARCH:=all
@@ -110,6 +110,20 @@ var callUsbNetAdd = rpc.declare({ object: 'mu300dash', method: 'usb_net_add', pa
* standalone package works in any OpenWrt buildroot without po2lmo or extra
* language packages. Chinese remains the source/fallback language. */
var DASH_I18N = {
'清除全部蜂窝锁定': ['Clear all cellular locks', 'Tüm hücresel kilitleri temizle'],
'清除当前 SIM 全部锁定': ['Clear all locks for the selected SIM', 'Seçili SIM için tüm kilitleri temizle'],
'清除 SIM %s 的全部锁定?': ['Clear all locks for SIM %s?', 'SIM %s için tüm kilitler temizlensin mi?'],
'确认清除': ['Confirm clearing', 'Temizlemeyi onayla'],
'按当前查看 SIM 恢复自动模式和频段、解除小区锁定并开启 EN-DC;只删除当前卡的已保存锁定,保留两张卡的开机自动应用开关。': ['Restore automatic mode and bands, remove cell locks and enable EN-DC through the viewed SIM. Only its saved locks are deleted; both SIMs retain their apply-at-startup preferences.', 'Görüntülenen SIM üzerinden otomatik mod ve bantları geri yükle, hücre kilitlerini kaldır ve EN-DC’yi aç. Yalnızca bu SIM’in kayıtlı kilitleri silinir; her iki SIM’in açılışta uygulama tercihleri korunur.'],
'注意:部分模组的频段或小区锁定由双卡共享(F50 的 NR 频段已确认共享),清除也会影响另一张卡。另一张卡的保存配置不会删除,其开机回放可能再次改变共享设置。清除会短暂中断蜂窝连接;全部回读通过后才删除当前卡的保存项。': ['Note: some modems share band or cell locks between SIMs (NR bands are confirmed shared on F50), so clearing also affects the other SIM. Its saved settings remain and may change shared settings again at boot. Cellular service briefly disconnects; only the selected SIM’s saved locks are deleted after all readbacks pass.', 'Not: bazı modemlerde bant veya hücre kilitleri SIM’ler arasında ortaktır (F50’de NR bantlarının ortak olduğu doğrulandı); temizleme diğer SIM’i de etkiler. Diğer SIM’in kayıtlı ayarları korunur ve açılışta ortak ayarları yeniden değiştirebilir. Hücresel bağlantı kısa süre kesilir; yalnızca seçili SIM’in kayıtlı kilitleri tüm geri okumalar doğrulanınca silinir.'],
'恢复自动模式和频段、解除 LTE/NR 小区锁定并开启 EN-DC。双卡共享的模组设置也会影响另一张卡(F50 的 NR 频段共享)。只清除当前卡的保存项,保留另一张卡配置和开机自动应用开关;另一张卡的回放可能重新改变共享设置。蜂窝会短暂断开;全部回读通过才算成功。': ['Restore automatic mode and bands, remove LTE/NR cell locks and enable EN-DC. Shared modem settings also affect the other SIM (F50 shares NR bands). Delete only the selected SIM’s saved locks; keep the other SIM’s settings and startup preferences. Its replay may change shared settings again. Cellular service briefly disconnects; success requires all readbacks to pass.', 'Otomatik mod ve bantları geri yükle, LTE/NR hücre kilitlerini kaldır ve EN-DC’yi aç. Ortak modem ayarları diğer SIM’i de etkiler (F50’de NR bantları ortaktır). Yalnızca seçili SIM’in kayıtlı kilitlerini sil; diğer SIM’in ayarlarını ve açılış tercihlerini koru. Diğer SIM’in ayarları yeniden uygulanınca ortak ayarlar değişebilir. Hücresel bağlantı kısa süre kesilir; başarı için tüm geri okumalar doğrulanmalıdır.'],
'查看卡槽已改变,请重新确认操作': ['The viewed SIM slot changed; confirm the operation again', 'Görüntülenen SIM yuvası değişti; işlemi yeniden onaylayın'],
'当前 SIM 的全部锁定已清除,已核对并清理保存配置': ['All locks for the selected SIM were cleared, verified, and removed from saved settings', 'Seçili SIM’in tüm kilitleri temizlendi, doğrulandı ve kayıtlı ayarlardan kaldırıldı'],
'清除未完成,部分设置可能已生效;已保存锁定未删除,请刷新后重试': ['Clearing was incomplete; some settings may have changed. Saved locks were not deleted. Refresh and retry.', 'Temizleme tamamlanmadı; bazı ayarlar değişmiş olabilir. Kayıtlı kilitler silinmedi. Yenileyip tekrar deneyin.'],
'清除回读不一致,部分设置可能已生效;已保存锁定未删除,请刷新后重试': ['Reset readback did not match; some settings may have changed. Saved locks were not deleted. Refresh and retry.', 'Sıfırlama geri okuması eşleşmedi; bazı ayarlar değişmiş olabilir. Kayıtlı kilitler silinmedi. Yenileyip tekrar deneyin.'],
'模组已恢复自动,但清除结果保存失败;旧锁定仍可能在开机回放,请重试': ['The modem is automatic, but saving the reset failed. Old locks may still be reapplied at boot; retry.', 'Modem otomatik moda döndü ancak sıfırlama kaydedilemedi. Eski kilitler açılışta yeniden uygulanabilir; tekrar deneyin.'],
'模组已恢复自动,旧锁定回放已阻止,但保存文件清理失败,请重试': ['The modem is automatic and replay of old locks is blocked, but saved-file cleanup failed. Retry.', 'Modem otomatik moda döndü ve eski kilitlerin uygulanması engellendi ancak kayıtlı dosyalar temizlenemedi. Tekrar deneyin.'],
'上次清除的保存文件尚未清理完成,请检查存储后重试': ['The previous reset still needs saved-file cleanup. Check storage and retry.', 'Önceki sıfırlamanın kayıtlı dosyaları henüz temizlenmedi. Depolamayı kontrol edip tekrar deneyin.'],
'开机角色策略': ['Boot role policy', 'Açılış rolü ilkesi'],
'当前共享协议': ['Current tethering protocol', 'Geçerli paylaşım protokolü'],
'下次启动协议': ['Protocol on next boot', 'Sonraki açılış protokolü'],
@@ -89,6 +89,15 @@ return view.extend({
<tbody id="mud-neigh"><tr><td colspan="7" style="color:var(--text-muted,var(--text-light,#777))">--</td></tr></tbody></table>
</div>
<div class="mud-note">应用后协议栈重启(SFUN),蜂窝会短暂断开;设置会持久保存,并在启用“开机自动应用”时由插件于 AT 就绪后回放。接入平台的射频前钩子时可无重启回放。频段全不选再点应用 = 恢复自动。</div>
</div>
<div class="mud-sec">
<h3>清除全部蜂窝锁定</h3>
<div class="mud-note">按当前查看 SIM 恢复自动模式和频段、解除小区锁定并开启 EN-DC;只删除当前卡的已保存锁定,保留两张卡的开机自动应用开关。</div>
<div class="mud-ctl" style="margin-top:10px;max-width:400px">
<button class="mud-btn warn" id="mud-lock-reset">清除当前 SIM 全部锁定</button>
</div>
<div class="mud-note">注意:部分模组的频段或小区锁定由双卡共享(F50 的 NR 频段已确认共享),清除也会影响另一张卡。另一张卡的保存配置不会删除,其开机回放可能再次改变共享设置。清除会短暂中断蜂窝连接;全部回读通过后才删除当前卡的保存项。</div>
</div>`;
M.localize(root);
this.wire(root);
@@ -105,11 +114,14 @@ return view.extend({
/* 主题化确认框替代浏览器 confirm;确认后再进入实际执行 */
var apply = function(kind, val, what, opts) {
opts = opts || {};
M.confirmBox('应用「' + what + '」?',
opts.noSfun ? '' : '协议栈会重启(SFUN),蜂窝断开约半分钟。',
{ danger: !opts.noSfun, okText: '应用' })
var slot = M.selectedSlot();
M.confirmBox(opts.title || ('应用「' + what + '」?'),
opts.message || (opts.noSfun ? '' : '协议栈会重启(SFUN),蜂窝断开约半分钟。'),
{ danger: !opts.noSfun, okText: opts.okText || '应用' })
.then(function(go) {
if (self._disposed) return; if (go) applyNow(kind, val, what, opts); });
if (self._disposed || !go) return;
if (M.selectedSlot() !== slot) { self.note('查看卡槽已改变,请重新确认操作', 'info'); return; }
applyNow(kind, val, what, opts); });
};
var applyNow = function(kind, val, what, opts) {
if (self._applying) { self.note('另一项网络设置仍在执行,请稍后重试', 'info'); return; }
@@ -222,6 +234,13 @@ return view.extend({
};
this.Q('lock-cell').onclick = function() { apply('cell', 'auto', '锁定当前服务小区', { btn: this }); };
this.Q('lock-cell-off').onclick = function() { apply('cell', 'off', '解除小区锁定', { btn: this }); };
this.Q('lock-reset').onclick = function() {
apply('reset', 'auto', '清除当前 SIM 全部锁定', {
btn: this, okText: '确认清除',
title: M.translate('清除 SIM %s 的全部锁定?').replace('%s', Number(M.selectedSlot()) + 1),
message: '恢复自动模式和频段、解除 LTE/NR 小区锁定并开启 EN-DC。双卡共享的模组设置也会影响另一张卡(F50 的 NR 频段共享)。只清除当前卡的保存项,保留另一张卡配置和开机自动应用开关;另一张卡的回放可能重新改变共享设置。蜂窝会短暂断开;全部回读通过才算成功。'
});
};
/* 已锁定小区表的解锁按钮(委托) */
this.Q('lockedcells').addEventListener('click', function(ev) {
@@ -395,7 +414,8 @@ return view.extend({
M.busy(btn, false);
}).then(function() {
if (self._disposed) return;
self.note(operation.kind === 'auto_apply' ? '开机自动应用设置已保存' : '已应用并核对模组状态', 'success');
self.note(operation.kind === 'auto_apply' ? '开机自动应用设置已保存' :
operation.kind === 'reset' ? '当前 SIM 的全部锁定已清除,已核对并清理保存配置' : '已应用并核对模组状态', 'success');
return self.refresh();
}).catch(function(error) {
if (self._disposed) return;
@@ -236,7 +236,7 @@ m_lock_set() {
kind=$(inp '@.kind')
val=$(inp '@.val')
case "$kind" in
mode|endc|lte|nr|cell|auto_apply) ;;
mode|endc|lte|nr|cell|auto_apply|reset) ;;
*) printf '{"ok":0,"error":"unknown lock kind"}\n'; return ;;
esac
"$DASH/lock" start "$kind" "$val"
@@ -11,6 +11,7 @@
# nr "78,41" or "" NR band lock (SPLBAND); empty = automatic
# cell auto | off | "nr:627264,393" | "lte:1650,211" serving-cell lock (SPFORCEFRQ)
# auto_apply on | off enable/disable boot replay without deleting settings
# reset auto clear this SIM's locks, verify, then remove saved lock keys
#
# All encodings are the ones the ufi_tools standalone mode uses against this modem
# family, cross-checked against this device's own read-backs (see the header of
@@ -406,6 +407,16 @@ verify_replay() {
do_replay() {
local phase=${1:-late} marker=$REPLAY_MARKER replay_m1= replay_primary= INTERACTIVE_APPLY=1
case $phase in early|late) ;; *) return 2 ;; esac
# An interrupted, already-verified reset must never replay old files.
# Only finish storage cleanup: no AT/SFUN is needed for this recovery.
if [ -e "$STATE_DIR/reset_pending" ]; then
apply_lock || return 1
trap 'rm -f "$APPLY_DIR/pid"; rmdir "$APPLY_DIR" 2>/dev/null' EXIT
trap 'exit 1' INT TERM
finish_reset_state || { say 'reset cleanup failed; refusing old lock replay'; return 1; }
: > "$marker"
return $?
fi
[ -e "$marker" ] && return 0
if ! auto_apply_enabled; then
say "boot replay disabled"
@@ -416,6 +427,7 @@ do_replay() {
trap 'rm -f "$APPLY_DIR/pid"; rmdir "$APPLY_DIR" 2>/dev/null' EXIT
trap 'exit 1' INT TERM
# Another caller may have completed replay while this one waited for the lock.
finish_reset_state || { say 'reset cleanup failed; refusing old lock replay'; return 1; }
[ -e "$marker" ] && return 0
auto_apply_enabled || return 0
# boot hook: the AT settings do not all survive a modem power cycle, so re-send
@@ -5,7 +5,7 @@ fail_apply() { printf '%s\n' "$1" >&2; return 1; }
validate_apply() {
local kind=$1 val=$2 cap encoded pair fr pc
case "$kind:$val" in
mode:auto|mode:4g|mode:sa|mode:nsa|endc:on|endc:off|auto_apply:on|auto_apply:off) return 0 ;;
mode:auto|mode:4g|mode:sa|mode:nsa|endc:on|endc:off|auto_apply:on|auto_apply:off|reset:auto) return 0 ;;
cell:auto|cell:off|cell:off-nr|cell:off-lte) return 0 ;;
esac
case "$kind" in
@@ -93,6 +93,80 @@ verify_apply() {
esac
}
# A committed reset is a tombstone for the old five keys. Never swap/remove
# STATE_DIR itself: SIM 0's directory may contain SIM 1 and identity data.
# Replay/apply finish interrupted cleanup before consuming another saved lock.
finish_reset_state() {
[ -e "$STATE_DIR/reset_pending" ] || return 0
local key
for key in mode endc lte nr cell; do
[ ! -d "$STATE_DIR/$key" ] || return 1
done
rm -f "$STATE_DIR/mode" "$STATE_DIR/endc" "$STATE_DIR/lte" \
"$STATE_DIR/nr" "$STATE_DIR/cell" || return 1
rm -f "$STATE_DIR/reset_pending"
}
verify_reset() {
local kind val
for kind in mode endc lte nr cell; do
case "$kind" in mode) val=auto ;; endc) val=on ;; *) val= ;; esac
verify_apply || return 1
done
}
reset_modem_settings() {
write_setting 'AT+SP5GRAN=1' &&
write_setting "AT+SPTESTMODE=134,$m1,$prim" &&
write_setting 'AT+SPENDC=1' &&
write_setting 'AT+SPLBAND=1,0,0,0,0,0' &&
write_setting 'AT+SPLBAND=2,0,0,0,0' &&
write_setting 'AT+SPFORCEFRQ=12,4' &&
write_setting 'AT+SPFORCEFRQ=16,4'
}
# F50 NR band masks are modem-wide even with atomic SPACTCARD addressing.
# Do not leave the other view showing stale shared fields for ten minutes.
# Saved settings remain per-SIM; never delete the other SIM's intent here.
invalidate_reset_cache() {
rm -f "$LOCKCACHE"
[ "$(cfg sim_slots)" = 2 ] || return 0
case ${MU300_SIM_SLOT:-0}:$RUNDIR in
0:*) rm -f "$RUNDIR/sim1/lock.json" ;;
1:*/sim1) rm -f "${RUNDIR%/sim1}/lock.json" ;;
esac
}
do_reset_apply() {
local tm m0=134 gran=1 m1 prim want_lte= want_nr=
tm=$(read_field 'AT+SPTESTMODE?' SPTESTMODE)
printf '%s\n' "$tm" | grep -Eq '^[0-9]+,[0-9]+,[01](,[0-9]+)*$' ||
{ fail_apply '无法读取当前 SIM 模式,未发送设置'; return 1; }
m1=$(printf '%s' "$tm" | cut -d, -f2)
prim=$(printf '%s' "$tm" | cut -d, -f3)
# A partial modem write cannot be rolled back atomically. Invalidate the
# old display, preserve saved intent on failure, and tell the caller.
invalidate_reset_cache
reset_modem_settings ||
{ fail_apply '清除未完成,部分设置可能已生效;已保存锁定未删除,请刷新后重试'; return 1; }
verify_reset ||
{ fail_apply '清除回读不一致,部分设置可能已生效;已保存锁定未删除,请刷新后重试'; return 1; }
sfun_restart || { fail_apply '协议栈重启被拒绝,请检查模组状态'; return 1; }
at 'AT+CFUN?' 4 | grep -q '+CFUN: 1' ||
{ fail_apply '设置已写入,但射频未恢复,请检查模组状态'; return 1; }
verify_reset || { fail_apply '协议栈重启后设置不一致,未保存'; return 1; }
# Publish the replay barrier before deleting any file, so an interrupted
# worker cannot leave a mixture of old locks for the next replay.
save_state reset_pending 1 ||
{ fail_apply '模组已恢复自动,但清除结果保存失败;旧锁定仍可能在开机回放,请重试'; return 1; }
finish_reset_state ||
{ fail_apply '模组已恢复自动,旧锁定回放已阻止,但保存文件清理失败,请重试'; return 1; }
say "verified reset to automatic for SIM ${MU300_SIM_SLOT:-0}"
invalidate_reset_cache
"$0" get fresh >/dev/null 2>&1
return 0
}
do_apply() {
local kind=$1 val=$2 m0 m1 prim gran tm v rat p fr pc pair want_lte want_nr c INTERACTIVE_APPLY=1
validate_apply "$kind" "$val" || return 1
@@ -106,6 +180,11 @@ do_apply() {
trap 'rm -f "$APPLY_DIR/pid"; rmdir "$APPLY_DIR" 2>/dev/null' EXIT
trap 'exit 1' INT TERM
[ ! -d /run/unisoc-data-sim-switch ] || { fail_apply '另一项网络设置仍在执行,请稍后重试'; return 1; }
finish_reset_state || { fail_apply '上次清除的保存文件尚未清理完成,请检查存储后重试'; return 1; }
if [ "$kind" = reset ]; then
do_reset_apply
return $?
fi
case "$kind" in
mode)
set -- $(mode_pair "$val"); m0=$1; gran=$2
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
# WCN has completed a chip reset. Reconcile only its configured Wi-Fi radios;
# never restart network/USB, redial cellular, or change saved wireless settings.
[ "$ACTION" = change ] && [ "$SOURCE" = unisocwl ] && [ "$EVENT" = FW_ERROR ] || exit 0
/opt/mu300/bin/wcn-reopen </dev/null >>/tmp/mu300-wcn-recovery.log 2>&1 &
+58 -1
View File
@@ -31,11 +31,67 @@ drop_old_prefix() {
done
}
has_prefix() {
local p
for p in $2; do [ "$p" != "$1" ] || return 0; done
return 1
}
router_lifetime() {
ip -6 route show default dev sipa_eth0 2>/dev/null | awk '{
for (i=1; i<NF; i++) if ($i=="expires") { v=$(i+1); sub(/sec$/, "", v) }
} END {
if (v !~ /^[0-9]+$/ || v+0<1) v=1800; else if (v+0>9000) v=9000
print v+0
}'
}
# Based on upstream a2b6d35: do not deprecate on a transient WAN disappearance.
# Only a different live /64 confirms renumbering. No USB reset is needed.
RA_DEPRECATE=${MU300_RA_DEPRECATE:-/opt/mu300/bin/ra-deprecate}
gone=
withdraw=
withdraw_rounds=0
withdraw_old() {
local p g= w=
# Server/NAT6 mode owns its own LAN prefix. Never inject relay RAs there.
if [ "$(uci -q get dhcp.lan.ra)" != relay ]; then
gone=; withdraw=; withdraw_rounds=0
return 0
fi
[ -z "$last_prefix" ] || [ "$last_prefix" = "$prefix" ] || gone="$gone $last_prefix"
for p in $gone; do
[ "$p" = "$prefix" ] || has_prefix "$p" "$g" || g="$g $p"
done
for p in $withdraw; do
[ "$p" = "$prefix" ] || w="$w $p"
done
gone=$g; withdraw=$w
[ -n "$prefix" ] || return 0
if [ -n "$gone" ]; then
for p in $gone; do
has_prefix "$p" "$withdraw" || withdraw="$withdraw $p"
done
withdraw_rounds=3; gone=
logger -t ndp-learn "withdrawing from the LAN:$withdraw"
fi
[ -n "$withdraw" ] && [ "$withdraw_rounds" -gt 0 ] || return 0
withdraw_rounds=$((withdraw_rounds - 1))
# Fixed /64s from /proc, intentionally passed as separate arguments.
# shellcheck disable=SC2086
"$RA_DEPRECATE" br-lan "$(router_lifetime)" $withdraw ||
logger -t ndp-learn "could not withdraw:$withdraw (ra-deprecate)"
# Bound memory and packet size during repeated reconnects. Each batch has
# exactly three attempts, successful or not; no busy retry on socket errors.
[ "$withdraw_rounds" -gt 0 ] || withdraw=
return 0
}
last_prefix=
while :; do
# /proc/net/if_inet6 uses fixed-width hex, so this also handles prefixes
# whose first four hextets are compressed by `ip -6 addr`.
prefix=$(awk '$6=="sipa_eth0" && $4=="00" {
prefix=$(awk '$6=="sipa_eth0" && $4=="00" && $1 ~ /^[23]/ {
for (i=1; i<=4; i++) {
h=substr($1,(i-1)*4+1,4); sub(/^0+/,"",h);
if (h=="") h="0";
@@ -43,6 +99,7 @@ while :; do
}
print "::/64"; exit
}' /proc/net/if_inet6 2>/dev/null)
withdraw_old
if [ -z "$prefix" ] && [ -n "$last_prefix" ]; then
drop_old_prefix "$last_prefix"
last_prefix=
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/ucode
// ra-deprecate IFACE ROUTER_LIFETIME PREFIX/64...
// One router advertisement on IFACE (to all nodes) whose prefix options give each PREFIX a preferred lifetime of 0 and
// a valid lifetime of two hours: hosts that SLAACed an address in it stop choosing it for new connections at once,
// and drop it when the two hours are up (RFC 4862 5.5.3 e: a host never shortens a valid lifetime below two hours
// from an unauthenticated RA). ndp-learn sends it for a /64 the carrier took away (#87): odhcpd's relay forwards the
// carrier's RAs as they are and keeps no prefix state, and the carrier says nothing about a prefix it stopped using.
//
// Every RA also refreshes the sender as the hosts' default router, so ROUTER_LIFETIME is the remaining lifetime of
// the carrier's router (what the relayed RAs say), never 0: that would take the LAN's IPv6 default route away. The
// hop limit, reachable time and retransmit timer are left unspecified (0) and the M and O flags clear; the next
// relayed RA sets the flags again. The source address is IFACE's link-local, the same one odhcpd relays from.
// Needs ucode-mod-socket. Exit status 0 when the advertisement went out.
import * as socket from 'socket';
import { readfile } from 'fs';
const VALID = 7200;
const IPPROTO_ICMPV6 = 58;
const ND_ROUTER_ADVERT = 134;
function fail(msg) {
warn(`ra-deprecate: ${msg}\n`);
exit(1);
}
let iface = ARGV[0], rlt = +ARGV[1];
if (length(ARGV) < 3 || !match(iface ?? '', /^[A-Za-z0-9_.-]{1,15}$/) || !match(ARGV[1], /^[0-9]+$/) ||
rlt < 1 || rlt > 9000)
fail('usage: ra-deprecate IFACE ROUTER_LIFETIME(1-9000) PREFIX/64...');
let ifindex = +trim(readfile(`/sys/class/net/${iface}/ifindex`) ?? '');
if (!ifindex)
fail(`no interface ${iface}`);
function u8(n) { return chr(n & 255); }
function u16(n) { return u8(n >> 8) + u8(n); }
function u32(n) { return u16(n >> 16) + u16(n & 65535); }
// RA: type, code, checksum (the kernel computes it for ICMPv6 raw sockets), hop limit, flags, router lifetime,
// reachable time, retransmit timer
let pkt = u8(ND_ROUTER_ADVERT) + u8(0) + u16(0) + u8(0) + u8(0) + u16(rlt) + u32(0) + u32(0);
for (let i = 2; i < length(ARGV); i++) {
let m = match(ARGV[i], /^([0-9a-f:]+)\/64$/);
let a = m ? iptoarr(m[1]) : null;
// global unicast only (2000::/3), and only the /64 itself
if (length(a) != 16 || (a[0] & 0xe0) != 0x20 || a[8] || a[9] || a[10] || a[11] || a[12] || a[13] || a[14] || a[15])
fail(`not a global /64: ${ARGV[i]}`);
// prefix information: type 3, length 4 (x 8 bytes), prefix length, flags L and A, valid, preferred, reserved
pkt += u8(3) + u8(4) + u8(64) + u8(0xc0) + u32(VALID) + u32(0) + u32(0);
for (let b in a)
pkt += u8(b);
}
let s = socket.create(socket.AF_INET6, socket.SOCK_RAW, IPPROTO_ICMPV6);
if (!s)
fail(`socket: ${socket.error()}`);
// RAs are only valid with hop limit 255 (RFC 4861 6.1.2)
if (!s.setopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, 255) ||
!s.setopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, ifindex))
fail(`setsockopt: ${socket.error()}`);
let n = s.send(pkt, 0, { family: socket.AF_INET6, address: 'ff02::1', port: 0, scope_id: ifindex });
s.close();
if (n != length(pkt))
fail(`send: ${socket.error()}`);
+38
View File
@@ -0,0 +1,38 @@
#!/bin/sh
# One recovery owner even when multiple firmware-reset notifications arrive.
# No boot service, polling loop, artificial delay, or persistent configuration writes.
lock=/run/mu300-wcn-reopen.lock
mkdir "$lock" 2>/dev/null || exit 0
trap 'rmdir "$lock" 2>/dev/null' EXIT
trap 'exit 1' HUP INT TERM
. /lib/functions.sh
config_load wireless
wcn_radio() {
local section=$1 phy path p module syspath disabled
config_get_bool disabled "$section" disabled 0
[ "$disabled" = 0 ] || return 0
config_get phy "$section" phy
config_get path "$section" path
for p in /sys/class/ieee80211/*; do
[ -e "$p" ] || continue
module=$(readlink -f "$p/device/driver/module")
[ "${module##*/}" = sprd_wlan_combo ] || continue
syspath=$(readlink -f "$p/device")
if [ -n "$phy" ]; then
[ "$phy" = "${p##*/}" ] || continue
elif [ -n "$path" ]; then
case "$syspath" in */"$path") ;; *) continue ;; esac
else
# Do not guess which adapter an unbound radio belongs to.
continue
fi
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"
wifi up "$section" || logger -t mu300-wcn "reopen failed: $section; no automatic reboot"
return 0
done
}
config_foreach wcn_radio wifi-device
+47
View File
@@ -54,8 +54,55 @@ async function main() {
messages.push(...[...src.matchAll(/'([^'\n]*[\u3400-\u9fff][^'\n]*)'/g)]
.map(m=>m[1]).filter(s=>!s.includes('{')));
}
const locks = fs.readFileSync(path.join(root, 'htdocs/luci-static/resources/view/mu300/locks.js'), 'utf8');
messages.push('清除全部蜂窝锁定', '清除当前 SIM 全部锁定', '清除 SIM %s 的全部锁定?', '确认清除',
'查看卡槽已改变,请重新确认操作', '当前 SIM 的全部锁定已清除,已核对并清理保存配置',
'正在后台应用 清除当前 SIM 全部锁定 …(SFUN 重启 + 重新驻网,约半分钟)');
messages.push(...[...locks.matchAll(/(?:<div class="mud-note">|message: ')([^<'\n]*清除[^<'\n]*)/g)].map(m=>m[1]));
for (lang of ['en','tr']) for (const text of messages)
assert(!/[\u3400-\u9fff]/.test(M.translate(text)),lang+': '+text);
// Execute the actual page handlers with a minimal DOM: don't clear a
// modem in a browser test, but do check confirmation, SIM scope and busy.
let selected=1, confirm, modal, requests=[], finishJob, failJob, notes=[];
const elements=new Map();
const pageRoot={isConnected:true, querySelectorAll:()=>[], querySelector:selector=>{
if(!elements.has(selector)) elements.set(selector, {
classList:{toggle:()=>{}}, addEventListener:()=>{}, querySelectorAll:()=>[], children:[]
});
return elements.get(selector);
}};
const fakeM={selectedSlot:()=>selected, translate:M.translate, esc:s=>s,
confirmBox:(title,message,options)=>{
modal={title,message,options}; return new Promise(r=>{confirm=r;});
}, busy:(button,on)=>{button.busy=on;},
callLockSet:(kind,val)=>{requests.push({kind,val,slot:selected}); return Promise.resolve({...start,kind});},
waitLockJob:()=>new Promise((resolve,reject)=>{finishJob=resolve;failJob=reject;})};
const page = new Function('view','R','M','L',locks)(
{extend:x=>x},{poll:()=>()=>{}},fakeM,{resolveDefault:x=>Promise.resolve(x)});
page.refresh=()=>Promise.resolve();
page.note=(text,type)=>notes.push({text,type});
page.wire(pageRoot);
const reset=elements.get('#mud-lock-reset');
lang='en'; reset.onclick();
assert.equal(modal.title,'Clear all locks for SIM 2?');
assert.equal(modal.options.danger,true);
assert.equal(modal.options.okText,'确认清除');
confirm(false); await flush(); assert.equal(requests.length,0);
reset.onclick(); selected=0; confirm(true); await flush();
assert.equal(requests.length,0); assert.match(notes.at(-1).text,/查看卡槽已改变/);
selected=1; reset.onclick(); confirm(true); await flush();
assert.deepEqual(requests,[{kind:'reset',val:'auto',slot:1}]);
assert.equal(reset.busy,true); assert.equal(page._applying,true);
reset.onclick(); confirm(true); await flush(); assert.equal(requests.length,1);
finishJob({...start,kind:'reset'}); await flush();
assert.equal(reset.busy,false); assert.equal(page._applying,false);
assert.equal(notes.at(-1).type,'success'); assert.match(notes.at(-1).text,/全部锁定已清除/);
reset.onclick(); confirm(true); await flush();
failJob(Error('readback mismatch')); await flush();
assert.equal(reset.busy,false); assert.equal(page._applying,false);
assert.equal(notes.at(-1).type,'error'); assert.match(notes.at(-1).text,/readback mismatch/);
reset.onclick(); page._disposed=true; confirm(true); await flush();
assert.equal(requests.length,2);
console.log('Lock jobs: verified completion, failures, clock skew, single-flight, timeout, dispose and i18n OK');
}
main().catch(e=>{console.error(e);process.exitCode=1;});
+46
View File
@@ -0,0 +1,46 @@
#!/bin/sh
# Run ONLY in a disposable OpenWrt container with its own network namespace,
# NET_ADMIN/NET_RAW, ucode-mod-socket, ip-full, tcpdump and coreutils-timeout.
# Use native OpenWrt: QEMU user-mode may reject IPV6_MULTICAST_IF/ethtool ioctls.
# No physical interface.
# /repo is this repository, mounted read-only.
set -eu
[ "${MU300_RA_TEST:-}" = isolated-container ] || exit 2
helper=/repo/openwrt/overlay/opt/mu300/bin/ra-deprecate
ip link add ra-test type veth peer name ra-peer
trap 'ip link del ra-test 2>/dev/null || :' EXIT
ip link set ra-test addrgenmode none
ip link set ra-peer addrgenmode none
ip link set ra-test up
ip link set ra-peer up
ip -6 addr add fe80::1234/64 dev ra-test nodad
ip -6 addr add fe80::5678/64 dev ra-peer nodad
timeout 8 tcpdump -i ra-peer -n -vv -c 1 'icmp6 && ip6[40] == 134' >/tmp/ra-capture 2>/tmp/ra-capture.err &
capture=$!
# Readiness of this test's capture, not a production delay.
for n in $(seq 1 5); do
grep -q 'listening on' /tmp/ra-capture.err 2>/dev/null && break
sleep 1
done
ucode "$helper" ra-test 1234 2001:db8:1234:5678::/64
wait "$capture"
cat /tmp/ra-capture
grep -q 'hlim 255' /tmp/ra-capture
grep -q 'fe80::1234 > ff02::1' /tmp/ra-capture
grep -q 'router lifetime 1234s' /tmp/ra-capture
grep -q '2001:db8:1234:5678::/64' /tmp/ra-capture
grep -q 'valid time 7200s, pref. time 0s' /tmp/ra-capture
! grep -q 'bad icmp6 cksum' /tmp/ra-capture
for bad in '2001:db8::1/64' 'fd00::/64' '2001:db8::/48' 'garbage'; do
if ucode "$helper" ra-test 1234 "$bad" >/dev/null 2>&1; then
echo "invalid prefix accepted: $bad" >&2
exit 1
fi
done
for bad in 0 9001 -1 nope; do
if ucode "$helper" ra-test "$bad" 2001:db8::/64 >/dev/null 2>&1; then
echo "invalid lifetime accepted: $bad" >&2
exit 1
fi
done
echo 'RA runtime checks passed (isolated veth only)'
+69
View File
@@ -0,0 +1,69 @@
"""Exercise the deployed ndp-learn withdrawal state machine without sending an RA."""
import unittest
from helpers import TOP, ShellTest
NDP = TOP / 'openwrt/overlay/opt/mu300/bin/ndp-learn'
class PrefixWithdrawal(ShellTest):
def setUp(self):
super().setUp()
self.lib = NDP.read_text().split('\nlast_prefix=\nwhile :;', 1)[0]
self.stub('logger', ':')
self.stub('uci', 'printf "%s\\n" "${RA_MODE:-relay}"')
self.stub('ip', 'printf "%s\\n" "${DEFAULT_ROUTE:-default via fe80::1 dev sipa_eth0 expires 1234sec}"')
self.stub('ra-deprecate', 'echo "$*" >> "$STUBLOG/ras"\nexit "${RA_FAIL:-0}"')
def run_sequence(self, shell, prefixes, **env):
(self.tmp / 'ras').unlink(missing_ok=True)
code = self.lib + '\nlast_prefix=\n'
for p in prefixes:
code += f"prefix='{p}'; withdraw_old; last_prefix=$prefix\n"
r = self.sh(shell, code, MU300_RA_DEPRECATE=self.stubs / 'ra-deprecate', **env)
self.assertEqual(r.returncode, 0, r.stderr)
return (self.tmp / 'ras').read_text().splitlines() if (self.tmp / 'ras').exists() else []
def test_same_prefix_after_disappearance_is_not_deprecated(self):
for shell in self.each_shell():
self.assertEqual(self.run_sequence(shell, ['2408:1:2:3::/64', '', '', '2408:1:2:3::/64']), [])
def test_new_prefix_withdraws_old_three_times_and_retains_gateway(self):
a, b = '2408:1:2:3::/64', '2408:1:2:4::/64'
for shell in self.each_shell():
for gap in ([], ['', '']):
got = self.run_sequence(shell, [a] + gap + [b] * 6)
self.assertEqual(got, [f'br-lan 1234 {a}'] * 3)
def test_returning_prefix_cancels_its_withdrawal(self):
a, b = '2408:1:2:3::/64', '2408:1:2:4::/64'
for shell in self.each_shell():
got = self.run_sequence(shell, [a, b, a, a, a, a])
self.assertEqual(got, [f'br-lan 1234 {a}'] + [f'br-lan 1234 {b}'] * 3)
def test_no_ra_in_server_mode_and_failed_sends_are_bounded(self):
a, b = '2408:1:2:3::/64', '2408:1:2:4::/64'
for shell in self.each_shell():
self.assertEqual(self.run_sequence(shell, [a, b, b, b], RA_MODE='server'), [])
self.assertEqual(len(self.run_sequence(shell, [a] + [b]*100, RA_FAIL='1')), 3)
def test_router_lifetime_fallback_and_clamp(self):
for shell in self.each_shell():
for expiry, expected in [('0', '1800'), ('1', '1'), ('2147483647', '9000'), ('forever', '1800')]:
r = self.sh(shell, self.lib + '\nrouter_lifetime', DEFAULT_ROUTE=f'default expires {expiry}sec')
self.assertEqual(r.stdout.strip(), expected)
def test_our_routing_and_build_dependency_remain(self):
text = NDP.read_text()
for keep in ('metric 1024', 'route del "$r/128" dev sipa_eth0', 'route add "$a/128" dev br-lan', 'accept_ra'):
self.assertIn(keep, text)
build = (TOP / 'openwrt/build-rootfs.sh').read_text()
self.assertIn('ucode-mod-socket', build)
self.assertIn('chmod 0755 $R/opt/mu300/bin/ra-deprecate', build)
helper = (TOP / 'openwrt/overlay/opt/mu300/bin/ra-deprecate').read_text()
for keep in ('IPV6_MULTICAST_HOPS, 255', 'u32(VALID) + u32(0)', 'rlt < 1', 'rlt > 9000'):
self.assertIn(keep, helper)
if __name__ == '__main__':
unittest.main()
+185 -5
View File
@@ -25,7 +25,7 @@ class LockWrites(ShellTest):
shutil.copyfile(LIB / name, self.lock.parent / name)
(self.lock.parent / name).chmod(0o755)
self.modem = self.tmp / 'modem.json'
self.stub('uci', f'case "$3" in unisoc_modem.main.state_dir) echo "{self.state}";; esac')
self.stub('uci', f'case "$3" in unisoc_modem.main.state_dir) echo "{self.state}";; *.sim_slots) echo "${{TEST_SIM_SLOTS:-1}}";; esac')
self.stub('logger', ':')
self.stub('ifup', 'echo ifup >> "$STUBLOG/commands"')
self.stub('sleep', ':')
@@ -48,7 +48,7 @@ if cmd in reads:
if cmd=='AT+SP5GCMDS="get nr support_band"':
print('+SP5GCMDS: get nr support_band,6,41,78,1,8,28,5'); print('OK'); sys.exit(0)
if cmd in ('AT+SPFORCEFRQ=12,3','AT+SPFORCEFRQ=16,3'):
tag=cmd.split('=')[1].split(',')[0]; cells=s['cells'+tag]
tag=cmd.split('=')[1].split(',')[0]; cells=s.get('cell_read_override',{}).get(tag,s['cells'+tag])
print('+SPFORCEFRQ: '+tag+',3'+(''.join(','+x for x in cells))); print('OK'); sys.exit(0)
if s.get('reject'): print('+CME ERROR: 3'); sys.exit(0)
if s.get('reject_restart') and cmd.startswith('AT+SFUN='): print('ERROR'); sys.exit(0)
@@ -61,6 +61,7 @@ if cmd.startswith('AT+SPFORCEFRQ='):
if args[1]=='4': s[key]=[]
elif args[1]=='6': s[key]=sorted(set(s[key]+[','.join(args[2:])]))
if cmd=='AT+SFUN=4' and s.get('drift'): s['lte']='0,0,0,0,0'
if cmd=='AT+SFUN=4' and s.get('reset_drift'): s['lte']='0,0,0,5,0'
f.write_text(json.dumps(s))
if s.get('omit_ok'): sys.exit(1)
print('OK')
@@ -71,13 +72,191 @@ print('OK')
self.reset()
def reset(self, **extra):
self.modem.write_text(json.dumps(dict(tm='134,128,1,0,0,0', gran='1', endc='1',
lte='0,0,0,0,0', nr='0,0,0,0', cfun='1', cells12=['1650,10'], cells16=[], **extra)))
state = dict(tm='134,128,1,0,0,0', gran='1', endc='1',
lte='0,0,0,0,0', nr='0,0,0,0', cfun='1', cells12=['1650,10'], cells16=[])
state.update(extra)
self.modem.write_text(json.dumps(state))
(self.tmp / 'commands').write_text('')
def apply(self, shell, kind, val):
return self.script(shell, self.lock, 'apply', kind, val, **self.extra)
def seed_locks(self, directory=None):
directory = directory or self.state
directory.mkdir(parents=True, exist_ok=True)
saved = dict(mode='nsa', endc='off', lte='1,3', nr='41,78',
cell='lte:1650,10\nnr:627264,393', auto_apply='off')
for key, value in saved.items():
(directory / key).write_text(value)
return saved
def test_reset_clears_all_types_once_preserving_other_sim_and_identity(self):
for shell in self.each_shell():
for omit_ok in (False, True):
self.reset(tm='131,128,1', gran='0', endc='0', lte='0,0,0,5,0',
nr='0,0,272,0', cells16=['627264,393'], omit_ok=omit_ok)
self.seed_locks()
other = self.seed_locks(self.state / 'sim1')
(self.state / 'identity').mkdir(exist_ok=True)
(self.state / 'identity/iccid').write_text('keep')
r = self.apply(shell, 'reset', 'auto')
self.assertEqual(r.returncode, 0, r.stderr)
modem = json.loads(self.modem.read_text())
for key, value in dict(tm='134,128,1', gran='1', endc='1',
lte='0,0,0,0,0', nr='0,0,0,0', cells12=[], cells16=[]).items():
self.assertEqual(modem[key], value, key)
for key in ('mode', 'endc', 'lte', 'nr', 'cell', 'reset_pending'):
self.assertFalse((self.state / key).exists(), key)
self.assertEqual((self.state / 'auto_apply').read_text(), 'off')
self.assertEqual((self.state / 'identity/iccid').read_text(), 'keep')
for key, value in other.items():
self.assertEqual((self.state / 'sim1' / key).read_text(), value)
commands = (self.tmp / 'commands').read_text()
self.assertEqual(commands.count('AT+SFUN=5\n'), 1)
self.assertEqual(commands.count('AT+SFUN=4\n'), 1)
self.assertEqual(json.loads((self.run / 'lock.json').read_text())['cells'], [])
def test_reset_slot1_keeps_slot0_state_and_mode_and_does_not_redial_it(self):
for shell in self.each_shell():
self.reset(tm='128,131,0', gran='0')
original = self.seed_locks()
self.seed_locks(self.state / 'sim1')
env = dict(self.extra, MU300_SIM_SLOT='1', MU300_STATE_DIR=self.state / 'sim1',
MU300_DASH_DIR=self.run / 'sim1')
r = self.script(shell, self.lock, 'apply', 'reset', 'auto', **env)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(json.loads(self.modem.read_text())['tm'], '128,134,0')
for key, value in original.items():
self.assertEqual((self.state / key).read_text(), value)
self.assertEqual(list(p.name for p in (self.state / 'sim1').iterdir()), ['auto_apply'])
self.assertNotIn('ifup\n', (self.tmp / 'commands').read_text())
def test_reset_invalidates_other_sim_cache_but_not_its_saved_settings(self):
for shell in self.each_shell():
for slot in ('0', '1'):
self.reset()
self.seed_locks()
self.seed_locks(self.state / 'sim1')
(self.run / 'sim1').mkdir(exist_ok=True)
(self.run / 'lock.json').write_text('{}')
(self.run / 'sim1/lock.json').write_text('{}')
state = self.state if slot == '0' else self.state / 'sim1'
cache = self.run if slot == '0' else self.run / 'sim1'
other_state = self.state / 'sim1' if slot == '0' else self.state
other_cache = self.run / 'sim1' if slot == '0' else self.run
env = dict(self.extra, TEST_SIM_SLOTS='2', MU300_SIM_SLOT=slot,
MU300_STATE_DIR=state, MU300_DASH_DIR=cache)
r = self.script(shell, self.lock, 'apply', 'reset', 'auto', **env)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertFalse((other_cache / 'lock.json').exists())
self.assertTrue((cache / 'lock.json').exists())
self.assertEqual((other_state / 'mode').read_text(), 'nsa')
self.assertEqual((other_state / 'nr').read_text(), '41,78')
def test_reset_failure_never_discards_saved_intent(self):
for shell in self.each_shell():
for failure in ('reject', 'ignore', 'silent', 'reject_restart', 'reset_drift', 'corrupt_mode_fields'):
self.reset(tm='131,128,1', **{failure: True})
original = self.seed_locks()
r = self.apply(shell, 'reset', 'auto')
self.assertNotEqual(r.returncode, 0, failure)
for key, value in original.items():
self.assertEqual((self.state / key).read_text(), value, (failure, key))
self.assertFalse((self.state / 'reset_pending').exists())
if failure in ('reject', 'ignore', 'silent', 'corrupt_mode_fields'):
self.assertNotIn('SFUN', (self.tmp / 'commands').read_text())
def test_reset_checks_each_readback_not_just_mode(self):
for shell in self.each_shell():
for key, value in [('endc', '0'), ('lte', '0,0,0,1,0'), ('nr', '0,0,256,0'),
('gran', '0'), ('lte', 'ERROR'), ('nr', '0,0')]:
self.reset(read_override={key: value})
original = self.seed_locks()
r = self.apply(shell, 'reset', 'auto')
self.assertNotEqual(r.returncode, 0, (key, value))
self.assertEqual((self.state / 'mode').read_text(), original['mode'])
self.assertNotIn('SFUN', (self.tmp / 'commands').read_text())
def test_interrupted_reset_cleanup_prevents_replay_even_with_marker_and_auto_off(self):
for shell in self.each_shell():
for phase in ('early', 'late'):
self.reset()
self.seed_locks()
other = self.seed_locks(self.state / 'sim1')
(self.state / 'reset_pending').write_text('1')
(self.tmp / 'marker').write_text('')
r = self.script(shell, self.lock, 'replay', phase, **self.extra)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual((self.tmp / 'commands').read_text(), '')
self.assertFalse((self.state / 'mode').exists())
self.assertFalse((self.state / 'reset_pending').exists())
self.assertEqual((self.state / 'auto_apply').read_text(), 'off')
for key, value in other.items():
self.assertEqual((self.state / 'sim1' / key).read_text(), value)
def test_reset_rejects_remaining_cells_on_either_rat(self):
for shell in self.each_shell():
for rat in ('12', '16'):
self.reset(cell_read_override={rat: ['1650,10']})
self.seed_locks()
r = self.apply(shell, 'reset', 'auto')
self.assertNotEqual(r.returncode, 0, rat)
self.assertIn('清除回读不一致', r.stderr)
self.assertTrue((self.state / 'cell').exists())
self.assertNotIn('SFUN', (self.tmp / 'commands').read_text())
def test_reset_barrier_publication_failure_keeps_all_old_files(self):
self.stub('mv', 'case "$2" in */reset_pending) exit 1;; esac; exec /bin/mv "$@"')
for shell in self.each_shell():
self.reset()
original = self.seed_locks()
r = self.apply(shell, 'reset', 'auto')
self.assertNotEqual(r.returncode, 0)
self.assertIn('旧锁定仍可能在开机回放', r.stderr)
self.assertFalse((self.state / 'reset_pending').exists())
for key, value in original.items():
self.assertEqual((self.state / key).read_text(), value)
def test_reset_persistence_failures_are_explicit_and_block_old_replay(self):
for shell in self.each_shell():
self.reset()
self.seed_locks()
(self.state / 'mode').unlink()
(self.state / 'mode').mkdir()
r = self.apply(shell, 'reset', 'auto')
self.assertNotEqual(r.returncode, 0)
self.assertIn('旧锁定回放已阻止', r.stderr)
self.assertTrue((self.state / 'reset_pending').exists())
self.reset()
for phase in ('early', 'late'):
self.assertNotEqual(self.replay(shell, phase).returncode, 0)
self.assertNotEqual(self.apply(shell, 'endc', 'on').returncode, 0)
self.assertEqual((self.tmp / 'commands').read_text(), '')
(self.state / 'mode').rmdir()
# Once storage is repaired, replay finishes cleanup without AT.
self.assertEqual(self.replay(shell, 'early').returncode, 0)
self.assertFalse((self.state / 'reset_pending').exists())
self.assertEqual((self.tmp / 'commands').read_text(), '')
def test_reset_job_done_only_after_verified_cleanup(self):
for shell in self.each_shell():
self.reset()
self.seed_locks()
job = json.loads(self.script(shell, self.lock, 'start', 'reset', 'auto', **self.extra).stdout)
self.assertEqual(job['ok'], 1, job)
self.assertEqual(job['kind'], 'reset')
for _ in range(150):
result = json.loads(self.script(shell, self.lock, 'status', job['id'], **self.extra).stdout)
if result.get('state') in ('done', 'error'):
break
time.sleep(.02)
self.assertEqual(result['state'], 'done', result)
self.assertEqual(result['ok'], 1)
self.assertFalse((self.state / 'mode').exists())
commands = (self.tmp / 'commands').read_text()
self.script(shell, self.lock, 'status', job['id'], **self.extra)
self.assertEqual((self.tmp / 'commands').read_text(), commands)
def test_verified_mode_preserves_slot1_and_primary(self):
for shell in self.each_shell():
self.reset()
@@ -287,7 +466,8 @@ print('OK')
for shell in self.each_shell():
for kind, val in [('lte', '1,79'), ('nr', '6'), ('nr','78;reboot'), ('nr','1,,2'),
('mode','bogus'), ('endc','2'), ('cell','nr:123,1008'),
('cell','lte:123,504'), ('cell','other:1,2'), ('auto_apply','yes')]:
('cell','lte:123,504'), ('cell','other:1,2'), ('auto_apply','yes'),
('reset',''), ('reset','all'), ('reset','auto;reboot')]:
self.reset()
r = self.apply(shell, kind, val)
self.assertNotEqual(r.returncode, 0, (kind,val))
+211
View File
@@ -0,0 +1,211 @@
"""Run the actual refill/recovery state machines with stub kernel primitives.
No fault injection on a device, no real wireless changes.
"""
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
from helpers import TOP, ShellTest
from test_wifi_tx_logging import function
MOD = TOP / 'upstream/modules'
WLAN = MOD / 'sprd_wlan_combo'
class DriverRecovery(unittest.TestCase):
def run_c(self, code):
if not shutil.which('cc'):
self.skipTest('requires a host C compiler')
with tempfile.TemporaryDirectory(prefix='mu300-rx-recovery-') as tmp:
src, exe = Path(tmp) / 'check.c', Path(tmp) / 'check'
src.write_text(code)
p = subprocess.run(['cc', '-std=gnu11', '-Wall', '-Werror', str(src), '-o', str(exe)],
capture_output=True, text=True)
self.assertEqual(p.returncode, 0, p.stderr)
subprocess.run([str(exe)], check=True, timeout=5)
def test_refill_no_progress_backs_off_and_progress_resumes_immediately(self):
text = (WLAN / 'sc2355/rx.c').read_text()
body = function(text, 'sc2355_mm_fill_buffer')
constants = '\n'.join(l for l in text.splitlines() if l.startswith('#define SPRD_REFILL_BACKOFF_'))
self.run_c(r'''
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#define READ_ONCE(x) (x)
#define SPRD_MAX_ADD_MH_BUF_ONCE 32
#define SPRD_PCIE_RX_ALLOC_BUF 1
#define clamp(x,a,b) ((x)<(a)?(a):((x)>(b)?(b):(x)))
#define msecs_to_jiffies(x) (x)
#define atomic_read(p) (*(p))
#define atomic_add_return(n,p) (*(p)+=(n))
static unsigned int atomic_xchg(unsigned int *p, unsigned int v) { unsigned int n=*p; *p=v; return n; }
struct mem_mgmt { unsigned int alloc_num; };
struct rx_mgmt { struct mem_mgmt mm_entry; void *addr_trans_head; bool stopping; int refill_retry; unsigned int refill_backoff_ms; struct sprd_hif *hif; };
struct ops { void (*tx_addr_trans)(struct sprd_hif *, void *, int, bool); };
struct sprd_hif { struct rx_mgmt *rx_mgmt; struct ops *ops; void *priv; };
static unsigned int allocated, immediate, delayed, delay_ms, attempts;
static bool sent;
static void *system_wq;
static int delayed_work_pending(int *p) { return *p; }
static void queue_delayed_work(void *q, int *p, unsigned int ms) { ++delayed; *p=1; delay_ms=ms; }
static void sc2355_queue_rx_buff_work(void *p, int id) { ++immediate; }
static unsigned int sc2355_mm_buffer_alloc(struct mem_mgmt *m, unsigned int n) { ++attempts; return n-allocated; }
static void transmit(struct sprd_hif *h, void *data, int len, bool flush) { if (sent) h->rx_mgmt->addr_trans_head=NULL; }
''' + constants + '\n' + body + r'''
int main(void) {
struct rx_mgmt rx={ .mm_entry={100} }; struct ops ops={transmit}; struct sprd_hif h={&rx,&ops,NULL}; rx.hif=&h;
unsigned int expected[]={20,40,80,160,320,640,1000,1000};
for (unsigned int i=0; i<8; ++i) {
rx.refill_retry=0;
assert(sc2355_mm_fill_buffer(&h)==100);
assert(delay_ms==expected[i] && immediate==0 && attempts==i+1);
for (int j=0; j<1000; ++j) assert(sc2355_mm_fill_buffer(&h)==100);
assert(attempts==i+1); /* RX events cannot bypass a timed retry */
}
rx.refill_retry=0; allocated=10;
assert(sc2355_mm_fill_buffer(&h)==90 && immediate==1 && delayed==8 && rx.refill_backoff_ms==0);
/* Sending pending addresses is progress even when no buffer was allocated. */
allocated=0; rx.addr_trans_head=&h; sent=true;
assert(sc2355_mm_fill_buffer(&h)==90 && immediate==2 && delayed==8);
allocated=90;
assert(sc2355_mm_fill_buffer(&h)==0 && immediate==2 && delayed==8);
rx.stopping=true;
unsigned int before=attempts;
assert(sc2355_mm_fill_buffer(&h)==0 && attempts==before);
return 0;
}
''')
def test_watchdog_resets_once_and_does_not_reboot_by_default(self):
text = (WLAN / 'common/iface.c').read_text()
default = next(l for l in text.splitlines() if l.startswith('static bool recovery_reboot'))
constants = '\n'.join(l for l in text.splitlines() if l.startswith('#define IFACE_WD_'))
funcs = '\n'.join(function(text, n) for n in ('iface_wd_give_up', 'iface_wd_tick'))
self.run_c(r'''
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#define HZ 100
#define READ_ONCE(x) (x)
#define atomic_read(p) (*(p))
#define time_after_eq(a,b) ((long)((a)-(b))>=0)
#define jiffies_to_msecs(x) ((x)*10)
/* Keep log arguments type-checked/used without printing. */
#define pr_err(...) ((void)0)
#define pr_emerg(...) ((void)0)
struct work_struct { int unused; };
struct sprd_hif { bool cp_asserted; int power_cnt; };
static struct { int tick; struct work_struct reset; struct sprd_hif *hif; unsigned long stuck_since; bool stuck,reset_used,reset_this_time,gave_up,stopping; } iface_wd;
static unsigned long jiffies;
static bool dump;
static int resets,reboots,ticks;
static void *system_wq,*system_unbound_wq;
static int sprdwcn_bus_get_carddump_status(void) { return dump; }
static void queue_work(void *w, struct work_struct *x) { ++resets; }
static void queue_delayed_work(void *w, int *x, int d) { ++ticks; }
static void orderly_reboot(void) { ++reboots; }
''' + constants + '\n' + default + '\n' + funcs + r'''
int main(void) {
struct sprd_hif h={false,1}; iface_wd.hif=&h;
iface_wd_tick(NULL); assert(!resets && !reboots);
dump=true; iface_wd_tick(NULL);
jiffies=9*HZ; iface_wd_tick(NULL); assert(!resets);
jiffies=10*HZ; iface_wd_tick(NULL); assert(resets==1);
jiffies=69*HZ; iface_wd_tick(NULL); assert(resets==1 && !reboots);
jiffies=70*HZ; int before=ticks; iface_wd_tick(NULL);
assert(iface_wd.gave_up && !reboots && ticks==before);
/* Fresh state: successful recovery followed by a second failure still must not reset-loop. */
iface_wd.gave_up=false; iface_wd.stuck=false; iface_wd.reset_used=false; iface_wd.reset_this_time=false;
jiffies=100*HZ; dump=true; iface_wd_tick(NULL);
jiffies=110*HZ; iface_wd_tick(NULL); assert(resets==2);
dump=false; h.cp_asserted=false; iface_wd_tick(NULL); assert(!iface_wd.stuck);
jiffies=200*HZ; dump=true; iface_wd_tick(NULL);
jiffies=210*HZ; iface_wd_tick(NULL); assert(iface_wd.gave_up && resets==2 && !reboots);
iface_wd.stopping=true; before=ticks; iface_wd_tick(NULL); assert(ticks==before);
return 0;
}
''')
def test_teardown_lock_and_existing_latency_fixes_survive(self):
text = (MOD / 'wcn_bsp/platform/wcn_procfs.c').read_text()
body = function(text, '__wcn_assert_interface')
powerdown = body.split('if (mdbg_proc->marlin_powerdown_flag)', 1)[1].split('\n\t}', 1)[0]
self.assertIn('goto out;', powerdown)
self.assertNotIn('return;', powerdown)
self.assertIn('mutex_unlock(&mdbg_proc->mutex)', body)
rx = (WLAN / 'sc2355/rx.c').read_text()
deinit = function(rx, 'sc2355_rx_deinit')
seq = ('WRITE_ONCE(rx_mgmt->stopping, true)', 'cancel_delayed_work_sync', 'sprd_clean_work', 'kfree(rx_mgmt)')
self.assertEqual(sorted(deinit.index(x) for x in seq), [deinit.index(x) for x in seq])
self.assertLess(deinit.index('destroy_workqueue(rx_mgmt->rx_queue)'), deinit.index('sprd_clean_work'))
self.assertLess(deinit.index('sprd_clean_work'), deinit.rindex('cancel_delayed_work_sync'))
fill = function(rx, 'sc2355_fill_skb_csum')
self.assertIn('CHECKSUM_NONE', fill)
self.assertNotIn('return -1', fill)
self.assertIn('msecs_to_jiffies(20)', (WLAN / 'sc2355/reorder.h').read_text())
iface = (WLAN / 'common/iface.c').read_text()
init = function(iface, 'iface_notify_init')
self.assertLess(init.index('misc_register'), init.index('atomic_notifier_chain_register'))
self.assertLess(init.index('register_inet6addr_notifier'), init.index('atomic_notifier_chain_register'))
self.assertIn('goto err_misc;', init)
self.assertIn('goto err_inet;', init)
deinit = function(iface, 'iface_notify_deinit')
self.assertLess(deinit.index('atomic_notifier_chain_unregister'), deinit.index('cancel_work_sync'))
self.assertLess(deinit.index('cancel_work_sync'), deinit.index('misc_deregister'))
self.assertNotIn('kobject_get_path', function(iface, 'iface_host_reset'))
class ReopenScript(ShellTest):
def test_only_matching_enabled_wcn_radio_is_reopened(self):
root = self.tmp / 'sys'
module = self.tmp / 'sprd_wlan_combo'
module.mkdir()
for phy, driver in [('phy0', module), ('phy1', self.tmp / 'external_driver')]:
driver.mkdir(exist_ok=True)
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('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() {
case "${BINDING:-phy}:$2:$3" in
phy:radio0:phy) eval "$1=phy0" ;;
phy:radio1:phy) eval "$1=phy1" ;;
path:radio0:path) eval "$1=phy0/device" ;;
path:radio1:path) eval "$1=phy1/device" ;;
*) eval "$1=" ;;
esac
}
'''
script = script.replace('. /lib/functions.sh', fixture).replace('/sys/class/ieee80211', str(root))
script = script.replace('/run/mu300-wcn-reopen.lock', str(self.tmp / 'lock'))
for shell in self.each_shell():
for binding in ('phy', 'path', 'unbound'):
for disabled in ('0', '1'):
(self.tmp / 'wifi').unlink(missing_ok=True)
r = self.sh(shell, script, DISABLED=disabled, BINDING=binding)
self.assertEqual(r.returncode, 0, r.stderr)
if disabled == '0' and binding != 'unbound':
self.assertEqual((self.tmp / 'wifi').read_text().splitlines(), ['down radio0', 'up radio0'])
else:
self.assertFalse((self.tmp / 'wifi').exists())
self.assertFalse((self.tmp / 'lock').exists())
(self.tmp / 'lock').mkdir()
r = self.sh(shell, script)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertFalse((self.tmp / 'wifi').exists())
(self.tmp / 'lock').rmdir()
if __name__ == '__main__':
unittest.main()
@@ -181,6 +181,11 @@ static void cfg80211_do_work(struct work_struct *work)
}
kfree(sprd_work);
/*
* MU300: this loop drains every queued item in one run, and items requeue themselves (the RX
* refill did, back to back, in issue #94). Yield between them so a long run cannot hold the CPU.
*/
cond_resched();
}
}
+168 -15
View File
@@ -11,6 +11,8 @@
#include <linux/ctype.h>
#include <linux/moduleparam.h>
#include <linux/reboot.h>
#include <linux/workqueue.h>
#include <misc/wcn_bus.h>
#include <linux/miscdevice.h>
@@ -114,18 +116,31 @@ static struct miscdevice wlan_misc_device = {
};
#ifndef DRV_RESET_SELF
static int iface_host_reset(struct notifier_block *nb,
unsigned long data, void *ptr)
/*
* MU300: the FW_ERROR uevent from a work item. wcn_reset_notifier_list is an atomic notifier chain (RCU read side),
* and kobject_uevent_env() allocates with GFP_KERNEL and may sleep; the vendor sent it from the notifier, and also
* leaked the path kobject_get_path() allocated for its log line. The uevent is what reopens Wi-Fi after the
* recovery watchdog's reset (see iface_wd_tick).
*/
static void iface_fw_error_uevent(struct work_struct *work)
{
struct sprd_priv *priv = iface_get_priv();
struct sprd_hif *hif;
char *envp[3] = {
[0] = "SOURCE=unisocwl",
[1] = "EVENT=FW_ERROR",
[2] = NULL,
};
kobject_uevent_env(&wlan_misc_device.this_device->kobj, KOBJ_CHANGE, envp);
pr_err("%s: FW_ERROR uevent sent on %s\n", __func__, dev_name(wlan_misc_device.this_device));
}
static DECLARE_WORK(iface_fw_error_work, iface_fw_error_uevent);
static int iface_host_reset(struct notifier_block *nb,
unsigned long data, void *ptr)
{
struct sprd_priv *priv = iface_get_priv();
struct sprd_hif *hif;
if (!priv) {
pr_err("%s sprd_prv is NULL\n", __func__);
return NOTIFY_OK;
@@ -134,9 +149,7 @@ static int iface_host_reset(struct notifier_block *nb,
hif = &priv->hif;
hif->cp_asserted = 1;
kobject_uevent_env(&wlan_misc_device.this_device->kobj, KOBJ_CHANGE, envp);
pr_err("%s() dev_path: %s\n", __func__,
kobject_get_path(&wlan_misc_device.this_device->kobj, GFP_KERNEL));
schedule_work(&iface_fw_error_work);
sprd_chip_force_exit((void *)&priv->chip);
return NOTIFY_OK;
@@ -171,6 +184,127 @@ static struct notifier_block iface_host_reset_cb = {
.notifier_call = iface_host_reset,
};
/*
* MU300: recovery watchdog (issue #94). After a firmware assert our builds leave the WCN in card-dump state for
* good (wcn_bsp's reset_dump defaults to "dump"): every mbuf_link_alloc() fails, Wi-Fi is dead, and until the RX
* refill was given a back-off the printk flood soft-locked a CPU and softlockup_panic rebooted the device - which
* is what brought Wi-Fi back. Without that, something else has to:
*
* - every second, Wi-Fi counts as stuck while the card-dump flag is set, or while the firmware is marked asserted
* (cp_asserted) with an interface open, i.e. the chip was reset but Wi-Fi has not been reopened yet (after our
* reset: until a power-on has succeeded, interface open or not);
* - card dump for 10 s: reset the chip once per boot (wcn_mu300_recover(), what procfs "rebootwcn" does), in a work
* item of its own so that a reset that hangs cannot stall this one. The reset's FW_ERROR uevent (iface_host_reset)
* is userspace's cue to reopen Wi-Fi (OpenWrt: /etc/hotplug.d/misc/10-mu300-wcn), which powers the chip on again;
* - still stuck 70 s after it began (the reset hung, or Wi-Fi was not reopened), or card dump again after the one
* reset of this boot: stop automatic recovery and report it. Whole-device reboot is opt-in: a Wi-Fi fault
* must not take working USB management and cellular service down with it.
* It runs outside every Wi-Fi lock and only reads two flags.
*/
static bool recovery_reboot;
module_param(recovery_reboot, bool, 0644);
MODULE_PARM_DESC(recovery_reboot, "MU300: reboot when Wi-Fi stays stuck after the WCN reset (default off)");
#define IFACE_WD_PERIOD HZ
#define IFACE_WD_RESET_AFTER (10 * HZ)
#define IFACE_WD_REBOOT_AFTER (70 * HZ)
static struct {
struct delayed_work tick;
struct work_struct reset;
struct sprd_hif *hif;
unsigned long stuck_since;
bool stuck;
bool reset_used; /* the one chip reset of this boot */
bool reset_this_time; /* ... and it was for the current stuck spell */
bool gave_up;
bool stopping;
} iface_wd;
static void iface_wd_reset(struct work_struct *work)
{
if (wcn_mu300_recover())
pr_err("MU300 recovery: WCN reset done, Wi-Fi comes back when it is reopened\n");
else
pr_err("MU300 recovery: no WCN reset (see wcn_mu300_recover's line above)\n");
}
static void iface_wd_give_up(const char *why)
{
iface_wd.gave_up = true;
if (recovery_reboot) {
pr_emerg("MU300 recovery: Wi-Fi stuck (%s)%s, rebooting\n", why,
work_busy(&iface_wd.reset) ? ", the WCN reset has not returned" : "");
orderly_reboot();
} else {
pr_emerg("MU300 recovery: Wi-Fi stuck (%s); recovery_reboot=0, so it stays down\n", why);
}
}
static void iface_wd_tick(struct work_struct *work)
{
struct sprd_hif *hif = iface_wd.hif;
bool dump = sprdwcn_bus_get_carddump_status() != 0;
/* after our reset only a successful power-on clears cp_asserted (sc2355_reset): a reopen that fails is stuck too */
bool asserted = READ_ONCE(hif->cp_asserted) &&
(atomic_read(&hif->power_cnt) > 0 || iface_wd.reset_this_time);
const char *why = dump ? "WCN in card dump" : "firmware asserted, Wi-Fi not reopened";
unsigned long now = jiffies;
if (READ_ONCE(iface_wd.stopping))
return;
if (!dump && !asserted) {
if (iface_wd.stuck)
pr_err("MU300 recovery: Wi-Fi is back after %u s\n",
jiffies_to_msecs(now - iface_wd.stuck_since) / 1000);
iface_wd.stuck = false;
iface_wd.reset_this_time = false;
goto again;
}
if (!iface_wd.stuck) {
iface_wd.stuck = true;
iface_wd.stuck_since = now;
pr_err("MU300 recovery: %s, watching\n", why);
}
if (iface_wd.gave_up)
goto again;
if (dump && time_after_eq(now, iface_wd.stuck_since + IFACE_WD_RESET_AFTER)) {
if (!iface_wd.reset_used) {
iface_wd.reset_used = true;
iface_wd.reset_this_time = true;
pr_err("MU300 recovery: %s for %u s, resetting the WCN (once per boot)\n", why,
jiffies_to_msecs(now - iface_wd.stuck_since) / 1000);
queue_work(system_unbound_wq, &iface_wd.reset);
} else if (!iface_wd.reset_this_time) {
iface_wd_give_up("card dump again, this boot's one WCN reset is used");
goto again;
}
}
if (time_after_eq(now, iface_wd.stuck_since + IFACE_WD_REBOOT_AFTER))
iface_wd_give_up(why);
again:
if (!READ_ONCE(iface_wd.stopping) && !iface_wd.gave_up)
queue_delayed_work(system_wq, &iface_wd.tick, IFACE_WD_PERIOD);
}
static void iface_wd_start(struct sprd_priv *priv)
{
memset(&iface_wd, 0, sizeof(iface_wd));
iface_wd.hif = &priv->hif;
INIT_DELAYED_WORK(&iface_wd.tick, iface_wd_tick);
INIT_WORK(&iface_wd.reset, iface_wd_reset);
queue_delayed_work(system_wq, &iface_wd.tick, IFACE_WD_PERIOD);
}
static void iface_wd_stop(void)
{
WRITE_ONCE(iface_wd.stopping, true);
cancel_delayed_work_sync(&iface_wd.tick);
cancel_work_sync(&iface_wd.reset);
}
static void iface_stop_net(struct sprd_vif *vif)
{
struct sprd_vif *real_vif, *tmp_vif;
@@ -1448,18 +1582,19 @@ static int iface_notify_init(struct sprd_priv *priv)
{
int ret = 0;
atomic_notifier_chain_register(&wcn_reset_notifier_list,
&iface_host_reset_cb);
/* The reset notifier can queue a uevent immediately. Publish it only
* after the misc device and all other registrations have succeeded. */
ret = misc_register(&wlan_misc_device);
if (ret)
if (ret) {
pr_err("wlan misc dev register fail\n");
return ret;
}
ret = register_inetaddr_notifier(&iface_inetaddr_cb);
if (ret) {
pr_err("%s failed to register inetaddr notifier(%d)!\n",
__func__, ret);
return ret;
goto err_misc;
}
if (priv->fw_capa & SPRD_CAPA_NS_OFFLOAD) {
@@ -1469,18 +1604,32 @@ static int iface_notify_init(struct sprd_priv *priv)
pr_err
("%s failed to register inet6addr notifier(%d)!\n",
__func__, ret);
return ret;
goto err_inet;
}
}
ret = atomic_notifier_chain_register(&wcn_reset_notifier_list,
&iface_host_reset_cb);
if (!ret)
return 0;
if (priv->fw_capa & SPRD_CAPA_NS_OFFLOAD)
unregister_inet6addr_notifier(&iface_inet6addr_cb);
err_inet:
unregister_inetaddr_notifier(&iface_inetaddr_cb);
err_misc:
misc_deregister(&wlan_misc_device);
return ret;
}
static void iface_notify_deinit(struct sprd_priv *priv)
{
misc_deregister(&wlan_misc_device);
/* MU300: no notifier call after this, then no uevent work left, before the misc device goes */
atomic_notifier_chain_unregister(&wcn_reset_notifier_list,
&iface_host_reset_cb);
#ifndef DRV_RESET_SELF
cancel_work_sync(&iface_fw_error_work);
#endif
misc_deregister(&wlan_misc_device);
unregister_inetaddr_notifier(&iface_inetaddr_cb);
if (priv->fw_capa & SPRD_CAPA_NS_OFFLOAD)
unregister_inet6addr_notifier(&iface_inet6addr_cb);
@@ -1825,6 +1974,9 @@ int sprd_iface_probe(struct platform_device *pdev,
pr_info("Power off WCN (%d time)\n", atomic_read(&hif->power_cnt));
sprd_iface_set_power(hif, false);
/* MU300: the recovery watchdog (see iface_wd_tick) */
iface_wd_start(priv);
return ret;
}
EXPORT_SYMBOL(sprd_iface_probe);
@@ -1836,6 +1988,7 @@ int sprd_iface_remove(struct platform_device *pdev)
int ret;
pr_info("%s\n wlan driver remove.", __func__);
iface_wd_stop(); /* MU300: before hif goes */
pr_info("Power on WCN (%d time)\n", atomic_read(&hif->power_cnt));
ret = sprd_iface_set_power(hif, true);
+28 -13
View File
@@ -138,8 +138,13 @@ static inline int mm_do_addr_buf(struct mem_mgmt *mm_entry)
/* NOTE: addr_buf should be allocating after being sent,
* JUST avoid addr_buf allocating fail after being sent here
*/
/*
* MU300: every message on this path is rate-limited. The RX refill retries it, and when the chip stops
* taking address buffers (issue #94: the WCN in dump status for minutes) each attempt printed four lines
* to the console until a CPU soft-locked in printk. The first ones still show; printk counts the rest.
*/
if (!hif->fw_awake) {
pr_info("%s, fw power save, need to wake up it!\n", __func__);
pr_info_ratelimited("%s, fw power save, need to wake up it!\n", __func__);
spin_lock_bh(&priv->list_lock);
list_for_each_entry(tmp_vif, &priv->vif_list, vif_node) {
if (tmp_vif->state & VIF_STATE_OPEN) {
@@ -155,7 +160,7 @@ static inline int mm_do_addr_buf(struct mem_mgmt *mm_entry)
if (!sc2355_cmd_host_wakeup_fw(vif->priv, vif)) {
hif->fw_power_down = 0;
} else {
pr_err("%s, wake up fw failed!!\n", __func__);
pr_err_ratelimited("%s, wake up fw failed!!\n", __func__);
return -EIO;
}
}
@@ -164,7 +169,7 @@ static inline int mm_do_addr_buf(struct mem_mgmt *mm_entry)
pr_debug("%s: addr buf is NULL, re-alloc here\n", __func__);
mm_alloc_addr_buf(mm_entry);
if (unlikely(!mm_entry->addr_trans)) {
pr_err("%s: alloc addr buf fail!\n", __func__);
pr_err_ratelimited("%s: alloc addr buf fail!\n", __func__);
ret = -ENOMEM;
}
} else if (value->num >= SPRD_MAX_ADD_MH_BUF_ONCE) {
@@ -180,11 +185,11 @@ static inline int mm_do_addr_buf(struct mem_mgmt *mm_entry)
addr_trans_len, false) >= 0)) {
mm_alloc_addr_buf(mm_entry);
if (unlikely(!mm_entry->addr_trans)) {
pr_err("%s: alloc addr buf fail!\n", __func__);
pr_err_ratelimited("%s: alloc addr buf fail!\n", __func__);
ret = -ENOMEM;
}
} else {
pr_err("%s: send addr buf fail!\n", __func__);
pr_err_ratelimited("%s: send addr buf fail!\n", __func__);
ret = -EIO;
}
}
@@ -238,8 +243,8 @@ static int mm_single_buffer_alloc(struct mem_mgmt *mm_entry)
if (likely(pcie_addr)) {
ret = mm_w_addr_buf(mm_entry, pcie_addr);
if (ret) {
pr_err("%s: write addr buf fail: %d\n",
__func__, ret);
pr_err_ratelimited("%s: write addr buf fail: %d\n",
__func__, ret);
dev_kfree_skb(skb);
} else {
/* queue skb */
@@ -247,7 +252,7 @@ static int mm_single_buffer_alloc(struct mem_mgmt *mm_entry)
}
}
} else {
pr_err("%s: alloc skb fail\n", __func__);
pr_err_ratelimited("%s: alloc skb fail\n", __func__);
}
return ret;
@@ -296,7 +301,7 @@ int mm_buffer_relink(struct mem_mgmt *mm_entry,
ret = mm_w_addr_buf(mm_entry, pcie_addr);
if (ret) {
pr_err("%s: write addr buf fail: %d\n", __func__, ret);
pr_err_ratelimited("%s: write addr buf fail: %d\n", __func__, ret);
skb = mm_single_buffer_unlink(mm_entry, pcie_addr);
if (likely(skb))
dev_kfree_skb(skb);
@@ -461,7 +466,7 @@ static void mm_normal_data_process(struct mem_mgmt *mm_entry,
}
if (unlikely(!skb)) {
pr_err("%s: alloc skb fail\n", __func__);
pr_err_ratelimited("%s: alloc skb fail\n", __func__);
free_data = true;
} else {
skb_reserve(skb, mm_entry->hif_offset);
@@ -509,7 +514,16 @@ static int mm_single_event_process(struct mem_mgmt *mm_entry,
/* NOTE: Not need to do anything here */
break;
case SPRD_FLUSH_BUFFER:
sc2355_rx_flush_buffer(mm_entry);
/*
* MU300: ignored. The vendor called sc2355_rx_flush_buffer(mm_entry) here, with mm_entry where it
* takes the hif, so it read a garbage rx_mgmt pointer: this firmware never sends it, or it would have
* crashed. Done right, it is still unsafe: from this RX context it would free buffer_list and the
* address buffer under a running refill (sprd_work), and deferred to sprd_work it would free buffers
* that later RX events in this same batch, and refills after it, still hand to or take from the chip.
* Leaving the buffers alone is safe: the last interface's close flushes them all (sc2355_reset and
* sc2355_handle_tx_status_after_close).
*/
pr_warn_ratelimited("%s: firmware asked for an RX buffer flush, ignored\n", __func__);
break;
default:
pr_err("%s: err type: %d\n", __func__, value->type);
@@ -581,8 +595,9 @@ int sc2355_mm_buffer_alloc(struct mem_mgmt *mm_entry, int need_num)
for (num = 0; num < need_num; num++) {
ret = mm_single_buffer_alloc(mm_entry);
if (ret) {
pr_err("%s: alloc num: %d, need num: %d, ret: %d\n",
__func__, num, need_num, ret);
/* MU300: rate-limited, the refill retries this (see mm_do_addr_buf) */
pr_err_ratelimited("%s: alloc num: %d, need num: %d, ret: %d\n",
__func__, num, need_num, ret);
break;
}
}
+12 -6
View File
@@ -143,8 +143,9 @@ static int pcie_tx_one(struct sprd_hif *hif, unsigned char *data,
ret = sprdwcn_bus_list_alloc(chn, &head, &tail, &num);
//ret = 0;
if (ret || !head || !tail) {
pr_err("%s:%d sprdwcn_bus_list_alloc fail\n",
__func__, __LINE__);
/* MU300: rate-limited, it fails on every command while the WCN is in dump status (issue #94) */
pr_err_ratelimited("%s:%d sprdwcn_bus_list_alloc fail\n",
__func__, __LINE__);
return -1;
}
@@ -397,8 +398,9 @@ static int pcie_rx_common_push(int chn, struct mbuf_t **head,
ret = sprdwcn_bus_list_alloc(chn, head, tail, num);
if (ret || head == NULL || tail == NULL || *head == NULL || *tail == NULL) {
pr_err("%s:%d sprdwcn_bus_list_alloc fail\n", __func__,
__LINE__);
/* MU300: rate-limited, as in pcie_tx_one */
pr_err_ratelimited("%s:%d sprdwcn_bus_list_alloc fail\n", __func__,
__LINE__);
ret = -ENOMEM;
} else {
ret = pcie_rx_fill_mbuf(*head, *tail, *num, len);
@@ -736,8 +738,12 @@ inline int sc2355_tx_addr_trans_pcie(struct sprd_hif *hif,
ret = sprdwcn_bus_list_alloc(hif->tx_data_port,
&head, &tail, &num);
if (ret || !head || !tail) {
pr_err("%s:%d sprdwcn_bus_list_alloc fail, chn: %d\n",
__func__, __LINE__, hif->tx_data_port);
/*
* MU300: rate-limited. The RX refill retries this, and in issue #94 (the WCN in dump status for
* minutes) it and its siblings flooded the console until a CPU soft-locked in printk.
*/
pr_err_ratelimited("%s:%d sprdwcn_bus_list_alloc fail, chn: %d\n",
__func__, __LINE__, hif->tx_data_port);
} else {
mbuf = head;
mbuf->buf = data;
+81 -5
View File
@@ -453,10 +453,14 @@ void sc2355_queue_rx_buff_work(struct sprd_priv *priv, unsigned char id)
{
struct sprd_work *misc_work;
struct sprd_vif *tmp_vif;
struct rx_mgmt *rx_mgmt = priv->hif.rx_mgmt;
if (!rx_mgmt || READ_ONCE(rx_mgmt->stopping))
return;
misc_work = sprd_alloc_work(0);
if (!misc_work) {
pr_err("%s out of memory\n", __func__);
pr_err_ratelimited("%s out of memory\n", __func__);
return;
}
spin_lock_bh(&priv->list_lock);
@@ -467,6 +471,15 @@ void sc2355_queue_rx_buff_work(struct sprd_priv *priv, unsigned char id)
}
}
spin_unlock_bh(&priv->list_lock);
/*
* MU300: sc2355_do_delay_work() dereferences work->vif for both ids, and with no interface open there is no
* RX ring to refill or flush. The vendor queued it anyway; the refill's timed retry can now fire after the
* last interface closed.
*/
if (!misc_work->vif) {
kfree(misc_work);
return;
}
switch (id) {
case SPRD_PCIE_RX_ALLOC_BUF:
case SPRD_PCIE_RX_FLUSH_BUF:
@@ -495,22 +508,70 @@ void sc2355_rx_process(struct rx_mgmt *rx_mgmt, struct sk_buff *pskb)
queue_work(rx_mgmt->rx_net_workq, &rx_mgmt->rx_net_work);
}
/*
* MU300: back-off for an RX refill that got nowhere. The vendor requeued the refill at once whenever buffers were
* still owed, so when the chip stopped taking them (issue #94: channel 10's links refused for minutes while the
* WCN sat in dump status) the shared sprd_work worker retried back to back, printing on every attempt, until a CPU
* soft-locked in printk and softlockup_panic rebooted the device. An attempt that neither allocates a buffer nor
* sends the pending address list now retries from a timer, 20 ms doubling to 1 s; one that makes progress
* resets it and requeues at once, as before.
*/
#define SPRD_REFILL_BACKOFF_MIN_MS 20U
#define SPRD_REFILL_BACKOFF_MAX_MS 1000U
static void rx_refill_retry(struct work_struct *work)
{
struct rx_mgmt *rx_mgmt =
container_of(to_delayed_work(work), struct rx_mgmt, refill_retry);
/* back onto the ordered sprd_work queue: a refill must not run beside another one */
if (!READ_ONCE(rx_mgmt->stopping))
sc2355_queue_rx_buff_work(rx_mgmt->hif->priv, SPRD_PCIE_RX_ALLOC_BUF);
}
int sc2355_mm_fill_buffer(struct sprd_hif *hif)
{
struct rx_mgmt *rx_mgmt =
(struct rx_mgmt *)hif->rx_mgmt;
struct mem_mgmt *mm_entry = &rx_mgmt->mm_entry;
unsigned int num = 0, alloc_num = atomic_xchg(&mm_entry->alloc_num, 0);
unsigned int num = 0, alloc_num;
bool had_trans, progress;
if (READ_ONCE(rx_mgmt->stopping))
return 0;
/* MU300: a retry is already timed; RX events (mm_buffer_unlink) must not bypass the back-off */
if (delayed_work_pending(&rx_mgmt->refill_retry))
return atomic_read(&mm_entry->alloc_num);
alloc_num = atomic_xchg(&mm_entry->alloc_num, 0);
had_trans = rx_mgmt->addr_trans_head != NULL;
num = sc2355_mm_buffer_alloc(&rx_mgmt->mm_entry, alloc_num);
progress = num < alloc_num;
if (hif->ops->tx_addr_trans)
hif->ops->tx_addr_trans(hif, NULL, 0, true);
if (had_trans && !rx_mgmt->addr_trans_head)
progress = true;
if (num)
num = atomic_add_return(num, &mm_entry->alloc_num);
if (num > SPRD_MAX_ADD_MH_BUF_ONCE || rx_mgmt->addr_trans_head)
sc2355_queue_rx_buff_work(rx_mgmt->hif->priv,
SPRD_PCIE_RX_ALLOC_BUF);
if (progress)
rx_mgmt->refill_backoff_ms = 0;
if (num > SPRD_MAX_ADD_MH_BUF_ONCE || rx_mgmt->addr_trans_head) {
if (progress) {
sc2355_queue_rx_buff_work(rx_mgmt->hif->priv,
SPRD_PCIE_RX_ALLOC_BUF);
} else {
rx_mgmt->refill_backoff_ms =
clamp(rx_mgmt->refill_backoff_ms * 2,
SPRD_REFILL_BACKOFF_MIN_MS,
SPRD_REFILL_BACKOFF_MAX_MS);
queue_delayed_work(system_wq, &rx_mgmt->refill_retry,
msecs_to_jiffies(rx_mgmt->refill_backoff_ms));
}
}
return num;
}
@@ -545,6 +606,9 @@ void sc2355_rx_flush_buffer(void *hif)
}
sc2355_mm_flush_buffer(mm_entry);
/* MU300: the ring is gone, and with it any timed refill (not _sync: this can run in RX context) */
cancel_delayed_work(&rx_mgmt->refill_retry);
rx_mgmt->refill_backoff_ms = 0;
}
int sc2355_rx_init(struct sprd_hif *hif)
@@ -608,6 +672,7 @@ int sc2355_rx_init(struct sprd_hif *hif)
}
sc2355_reorder_init(&rx_mgmt->ba_entry);
INIT_DELAYED_WORK(&rx_mgmt->refill_retry, rx_refill_retry);
hif->lp = 0;
hif->rx_mgmt = (void *)rx_mgmt;
@@ -633,11 +698,22 @@ int sc2355_rx_deinit(struct sprd_hif *hif)
{
struct rx_mgmt *rx_mgmt = (struct rx_mgmt *)hif->rx_mgmt;
/* Draining a producer is not enough if another queued work can re-arm its timer. */
WRITE_ONCE(rx_mgmt->stopping, true);
/*
* Stop the timer, drain RX producers, then drain sprd_work. An in-flight
* refill may have passed its stopping check before teardown and re-armed
* the timer after the first cancel, so cancel again after all producers.
*/
cancel_delayed_work_sync(&rx_mgmt->refill_retry);
flush_workqueue(rx_mgmt->rx_queue);
destroy_workqueue(rx_mgmt->rx_queue);
flush_workqueue(rx_mgmt->rx_net_workq);
destroy_workqueue(rx_mgmt->rx_net_workq);
sprd_clean_work(hif->priv);
cancel_delayed_work_sync(&rx_mgmt->refill_retry);
sprd_deinit_msg(&rx_mgmt->rx_list);
@@ -85,6 +85,11 @@ struct rx_mgmt {
u16 rx_snaphdr_seqnum;
u8 rx_snaphdr_lut;
u8 rx_snaphdr_tid;
/* MU300: the RX refill's retry after an attempt that got nowhere (see sc2355_mm_fill_buffer) */
struct delayed_work refill_retry;
unsigned int refill_backoff_ms;
bool stopping;
};
/* NOTE: MUST not modify, defined by HW */
@@ -19,6 +19,10 @@ extern u32 wcn_print_level;
#define WCN_ERR(fmt, args...)\
pr_err(" error: " fmt, ## args)
/* MU300: for errors a caller can hit on every attempt (printk's own "callbacks suppressed" line keeps the count) */
#define WCN_ERR_RATELIMITED(fmt, args...)\
pr_err_ratelimited(" error: " fmt, ## args)
#define WCN_DBG(fmt, args...)\
pr_debug(" dbg: " fmt, ## args)
@@ -335,6 +335,8 @@ extern struct sprdwcn_bus_ops *get_wcn_bus_ops(void);
extern void wcn_assert_interface(enum wcn_source_type, char *str);
extern void wcn_assert_interface_async(enum wcn_source_type type, char *str);
extern bool wcn_is_assert(void);
/* MU300: chip reset for the Wi-Fi recovery watchdog (wcn_procfs.c) */
extern bool wcn_mu300_recover(void);
bool wcn_push_list_condition_check(struct mbuf_t *head, struct mbuf_t *tail, int num);
extern bool wcn_is_power_busy(void);
int sprd_wlan_power_status_sync(int option, int value);
+8 -3
View File
@@ -42,13 +42,18 @@ int mbuf_link_alloc(int chn, struct mbuf_t **head, struct mbuf_t **tail,
struct buffer_pool *pool = &(mchn->chn_public[chn].pool);
WCN_DBG("pool=%p, chn=%d, free=%d\n", pool, chn, pool->free);
/*
* MU300: both failures below are hit once per attempt, and Wi-Fi retries its RX refill and every TX: in
* issue #94 the card sat in dump status for minutes and this line, with Wi-Fi's own, flooded the console
* until a CPU soft-locked in printk. Rate-limited; the first ones still show.
*/
if (sprdwcn_bus_get_carddump_status()) {
WCN_ERR("%s err in dump status,chn=%d\n", __func__, chn);
return -1;
WCN_ERR_RATELIMITED("%s err in dump status,chn=%d\n", __func__, chn);
return -1;
}
spin_lock_irqsave(&(pool->lock), pool->irq_flags);
if ((*num <= 0) || (pool->free <= 0)) {
WCN_ERR("[+]%s err, num %d, free %d)\n",
WCN_ERR_RATELIMITED("[+]%s err, num %d, free %d)\n",
__func__, *num, pool->free);
*num = 0;
*head = *tail = NULL;
+79 -3
View File
@@ -117,6 +117,67 @@ void wcn_reset_process(void)
WCN_INFO("%s reset end\n", __func__);
}
/*
* MU300: the chip reset for sprd_wlan_combo's recovery watchdog (issue #94). Our builds are not
* TARGET_BUILD_VARIANT=user, so a firmware assert takes the "dump" path (reset_dump defaults to dump):
* wcn_dump_process() sets the card-dump flag and nothing ever clears it, and every mbuf_link_alloc() fails from
* then on. This is procfs "rebootwcn" (the non-integrated branch) followed by wcn_reset_process(), which also
* clears dump_cnt and the assert notification so that a later assert is handled again: power the chip off,
* call wcn_reset_notifier_list (Wi-Fi marks itself asserted and sends its FW_ERROR uevent) and clear the flag.
* The chip powers on again at the next start_marlin(), i.e. when Wi-Fi is reopened. Process context; may block.
*/
/*
* MU300: mdbg_proc->mutex with a deadline. A dump holds it for seconds (several MB over PCIe), and a path that
* never lets go must not leave rebootwcn's writer or the recovery work in D state for good.
*/
#define MDBG_LOCK_WAIT_MS 30000U
static bool mdbg_lock_bounded(unsigned int ms)
{
unsigned long end = jiffies + msecs_to_jiffies(ms);
while (!mutex_trylock(&mdbg_proc->mutex)) {
if (time_after(jiffies, end))
return false;
msleep(100);
}
return true;
}
bool wcn_mu300_recover(void)
{
bool done = false;
/*
* mdbg_proc->mutex, as the firmware-assert path (__wcn_assert_interface: dump or wcn_reset_process),
* procfs dumpmem and rebootwcn hold it: one dump or reset at a time. Same order as theirs, this mutex and
* then marlin_dev->power_lock (inside wcn_chip_power_off). The watchdog that calls this from a work item of
* its own never takes it. This deadline is only for fault recovery, not normal boot. The watchdog reports
* failure if recovery does not complete; a whole-device reboot is disabled by default in this fork.
*/
if (!mdbg_lock_bounded(MDBG_LOCK_WAIT_MS)) {
WCN_ERR("%s: a dump or reset has held the WCN for %u s, no reset\n",
__func__, MDBG_LOCK_WAIT_MS / 1000);
return false;
}
/* someone else (an assert's reset, a manual rebootwcn) may have recovered it meanwhile */
if (sprdwcn_bus_get_carddump_status()) {
WCN_INFO("%s begin\n", __func__);
stop_loopcheck();
mdbg_proc->fail_count = 0;
marlin_set_download_status(0);
wcn_reset_process();
WCN_INFO("%s end\n", __func__);
done = true;
} else {
WCN_INFO("%s: not in card dump any more, nothing to do\n", __func__);
}
mutex_unlock(&mdbg_proc->mutex);
return done;
}
EXPORT_SYMBOL_GPL(wcn_mu300_recover);
void wcn_dump_process(enum wcn_source_type type)
{
struct wcn_match_data *g_match_config = get_wcn_match_config();
@@ -186,7 +247,8 @@ void __wcn_assert_interface(enum wcn_source_type type, char *str)
if (!(g_match_config && g_match_config->unisoc_wcn_integrated)) {
if (mdbg_proc->marlin_powerdown_flag) {
WCN_ERR("fw assert hanppend in WCN Powerdown!!\n");
return;
/* MU300: the vendor returned here with mdbg_proc->mutex held, for good */
goto out;
}
}
@@ -948,9 +1010,13 @@ static ssize_t mdbg_proc_write(struct file *filp,
}
} else {
if (strncmp(mdbg_proc->write_buf, "dumpmem", 7) == 0) {
/* MU300: the lock first and with a deadline (see mdbg_lock_bounded), then the dump flag */
if (!mdbg_lock_bounded(MDBG_LOCK_WAIT_MS)) {
WCN_ERR("dumpmem: a dump or reset holds the WCN for %u s, try again\n",
MDBG_LOCK_WAIT_MS / 1000);
return -EBUSY;
}
sprdwcn_bus_set_carddump_status(true);
mutex_lock(&mdbg_proc->mutex);
marlin_set_sleep(MARLIN_MDBG, FALSE);
marlin_set_wakeup(MARLIN_MDBG);
mdbg_dump_mem(WCN_SOURCE_BTWF);
@@ -980,6 +1046,15 @@ static ssize_t mdbg_proc_write(struct file *filp,
return count;
}
if (strncmp(mdbg_proc->write_buf, "rebootwcn", 9) == 0) {
/*
* MU300: under mdbg_proc->mutex, as the assert path and wcn_mu300_recover() reset the chip,
* but never stuck in D state behind it: -EBUSY if a dump or reset holds it for 30 s.
*/
if (!mdbg_lock_bounded(MDBG_LOCK_WAIT_MS)) {
WCN_ERR("rebootwcn: a dump or reset holds the WCN for %u s, try again\n",
MDBG_LOCK_WAIT_MS / 1000);
return -EBUSY;
}
flag_reset = 1;
WCN_INFO("marlin gnss need reset\n");
WCN_INFO("fail_count is value %d\n", mdbg_proc->fail_count);
@@ -990,6 +1065,7 @@ static ssize_t mdbg_proc_write(struct file *filp,
marlin_chip_en(false, true);
wcn_reset_cp2();
flag_reset = 0;
mutex_unlock(&mdbg_proc->mutex);
return count;
}
if (strncmp(mdbg_proc->write_buf, "at+getchipversion", 17) == 0) {