Skip to content

PAN/BNEP over BR/EDR: bring-up, TX pool sizing and boot auto-connect - #591

Open
Sen70s wants to merge 38 commits into
open-vela:dev-ai-contest-2026from
Sen70s:bletest
Open

Sen70s wants to merge 38 commits into
open-vela:dev-ai-contest-2026from
Sen70s:bletest

Conversation

@Sen70s

@Sen70s Sen70s commented Aug 21, 2026

Copy link
Copy Markdown

本 PR 来自 2026 首届 openvela AI 硬件开发者大赛参赛队 181
(contest2026_181_womenshayebuhuidui),是手表通过手机蓝牙网络共享(BNEP/PAN)
上网这条线上的平台侧修复。

本 PR 内容

  • caa4e857 pan: BNEP SAL over zblue BREDR L2CAP + enable PAN profile build
  • 3263937f pan: reuse existing BREDR ACL in pan_connect - avoid HCI CREATE_CONN timeout assert
  • 2bdcc718 pan: 5s reconnect cooldown after ACL teardown - LCPU controller stale state causes CREATE_CONN timeout assert
  • 37e80939 pan: request link encryption before L2CAP connect (Android NAP rejects unencrypted PAN connections)
  • 40db0c4e pan: fix use-after-free on ACL teardown - let chan disconnected callback own the conn
  • e5a94751 pan: defer set_security to sys workqueue - sync HCI cmd from stack-thread callback deadlocks
  • 4c24d41d pan: add syslog traces at ACL/security/L2CAP/BNEP stages for field debugging
  • 3db0bb48 pan: unify ACL reuse path through encryption gate (was skipping set_security on lookup hit)
  • 151680fb pan: full syslog diagnostics on connect/create_br failure paths
  • e6872f9d pan: passive encryption wait + 2s L2CAP fallback - never call set_security from callbacks/workqueue
  • f99451da pan: request encryption from connect caller context (service thread, safe for send_sync)
  • 94d90ee2 pan: dedicated worker thread for sync HCI (create_br/set_security)
  • 5288ad42 pan: worker waits for ACL-up callback before set_security (ENOTCONN fix)
  • faec4d2c pan: log L2CAP connect result
  • af54c8db pan: worker skips acl_ready wait when reused ACL already CONNECTED
  • 7d7ae176 pan: fix L2CAP BR chan type - pan_conn_t.chan must be bt_l2cap_br_chan (BR_CHAN walks past struct bt_l2cap_chan, garbage psm -> EEXIST)
  • 0c6d033e pan: worker polls ACL up up to 10s (remote page can exceed 3s)
  • 317d80cb pan: init br_chan rx.mtu=672 + sec level L2 (calloc zero sent MTU=0 CONFIG_REQ, phone disconnects)
  • 079e9587 pan: rx.mtu=1691 (BNEP std) - Android NAP rejects MTU<1691 with UNACCEPTABLE_PARAMS
  • 9c9589cb pan: allocate TX from zblue ACL pool via bt_l2cap_create_pdu_timeout (raw pool+reserve overflowed tailroom -> HardFault)
  • 670e546a pan: dedicated TX pool via create_pdu_timeout; keep ACL TX pool small (BSS shift corrupted flash driver)
  • 5f42a764 pan: release pending conn on ACL up timeout (retry was rejected as already exists)
  • 6fbdd601 adv: unconditional syslog diagnostics in start/stop adv (BT_LOGE empty without BLUETOOTH_LOG which needs KVDB property)
  • 777104ff panu: drop stale conn for same addr in pan_new_conn (blocks reconnect after failed BR attempt)
  • 1cdb4644 feat(bnep): add zero-dependency BNEP codec with control frames
  • 749166e9 feat(bnep): encode Ethernet frames, never compressing broadcast
  • a489b141 feat(bnep): decode all four data frame types and skip extensions
  • 971944db fix(bnep): carry whole Ethernet frames and derive every limit from tx.mtu
  • bbeb4c70 fix(bt): read the COD symbol under the name kconfig actually emits
  • 24d23bcd fix(pan): make the DHCP worker exit cleanly and the lifecycle observable
  • 021919aa fix(storage): run the unqlite path synchronously instead of on the uv pool
  • 545b2e5e feat(bt): come up enabled, discoverable and reconnecting without a console
  • bcdff9ba fix(bt): survive a signal, and answer SSP the way HyperOS asks
  • ec9ad5c5 fix(pan): size the BNEP TX pool for real and auto-connect from the bond list

验证

SF32LB52 手表板 + Android(HyperOS) 手机,正式(非调试)镜像:

  • 冷启动无人干预即联网:BNEP setup OK (tx_mtu=1691) → DHCP 拿到地址 → netmgr 切到 bt-pan
  • 网关 / 公网 IP / DNS 域名 / 1472 字节大包 ping 均 0% 丢包
  • 手机侧断链后自动重连并重新 DHCP
  • 60 分钟长稳 60 轮:0 assert、0 断链,堆用量首尾持平(无泄漏)

技术背景

根因分析与完整证据链见参赛仓文档:
https://github.com/Sen70s/contest2026_181_womenshayebuhuidui/blob/feat/ai-agent-contest/docs_ble/21_pan_breakthrough_authoritative.md

可复用规则(含本 PR 涉及的平台约束):
https://github.com/Sen70s/contest2026_181_womenshayebuhuidui/blob/feat/ai-agent-contest/docs_ble/22_pan_engineering_guide.md

Sen70s added 30 commits August 15, 2026 01:26
- service/stacks/include/sal_pan_interface.h: bt_sal_pan_* interface
- service/stacks/zephyr/sal_pan_interface.c: minimal PANU BNEP stack
  (PSM 0x000F, setup handshake, FRAME_ETH data path, PANU->NAP roles)
- CMakeLists: compile sal_pan_interface.c with CONFIG_BLUETOOTH_PAN
- carries pre-existing local fixes (service_loop/ipc/btservice/sal_adapter)
…timeout assert

Repeated pan connect while the controller still holds the previous
connection made bt_hci_cmd_send_sync time out (zblue asserts). Look
up the BR address first with bt_conn_lookup_addr_br and go straight
to L2CAP when the ACL already exists.
…s unencrypted PAN connections)

ACL up -> bt_conn_set_security(L2) -> security_changed -> l2cap_chan_connect
…ack own the conn

Freeing the conn from pan_br_disconnected while the L2CAP chan is
still owned by the stack corrupted memory and hung the system after
the phone dropped the ACL.
…read callback deadlocks

bt_ssp_start_security -> bt_hci_cmd_send_sync(AUTH_REQUESTED) called
from the zblue connection callback (HCI event thread) blocks the very
thread that must process the Command Status -> HCI_CMD_TIMEOUT assert
after 30s, then bluetoothd dies and the board hangs.
…urity from callbacks/workqueue

The LCPU controller stops answering AUTH_REQUESTED after the peer
drops the ACL; send_sync then wedges the sys workqueue for
HCI_CMD_TIMEOUT and asserts, killing bluetoothd and blocking all
subsequent HCI commands. Rely on the peer re-encrypting bonded links
(security_changed drives L2CAP connect) with a 2s delayable fallback
that only performs the async l2cap_chan_connect.
…safe for send_sync)

Android NAP waits for the initiator to authenticate; the passive wait
made the phone drop the ACL. bt_sal_pan_connect runs on the IPC
service thread - bt_conn_set_security is safe there (same context as
create_br): send_sync blocks only this thread, HCI RX still processes
the Command Status.
Root cause found via addr2line: send_sync asserts at hci_core.c:507
(k_sem_take timeout). The bluetoothd service-loop thread both runs the
IPC handler AND polls /dev/ttyHCI0 for HCI events, so a synchronous
command from the IPC path blocks the very thread that must deliver the
Command Status - 10s self-deadlock assert. All sync HCI for PAN now
runs on a dedicated worker thread.
…n (BR_CHAN walks past struct bt_l2cap_chan, garbage psm -> EEXIST)
…(raw pool+reserve overflowed tailroom -> HardFault)
…y without BLUETOOTH_LOG which needs KVDB property)
….mtu

The SAL/profile boundary used to pass (protocol, dst_addr, src_addr,
payload) as four separate arguments, and bt_sal_pan_write() then threw
the two addresses away with `(void)dst_addr; (void)src_addr;`. Every
outbound frame was therefore encoded as Compressed Ethernet with the
peer's unicast MAC implied as the destination, so ARP requests and DHCP
DISCOVER - which must go to ff:ff:ff:ff:ff:ff - were delivered to the
phone as unicast and silently dropped. Whole 14-byte-header frames now
cross the boundary intact and bnep_codec decides the frame type, which
is the only way broadcast can be represented at all.

The size limits were the other half of the problem. There is no
compile-time TX ceiling: zblue's BR/EDR send path compares buf->len
against the negotiated br_chan->tx.mtu (classic/l2cap_br.c:1906) and
never reads CONFIG_BT_L2CAP_TX_MTU, so the 253-byte config value was a
false ceiling. bt_sal_pan_get_tx_mtu() exposes the negotiated value and
panu_service sets the TAP interface MTU from it via SIOCSIFMTU before
bringing the link up, which is what keeps the IP stack from generating
frames BNEP cannot carry (SIOCSIFMTU sets d_pktsize, and TCP_MSS /
UDP_MSS derive from it).

Also on the RX side: tun_read() returns -EINVAL *without dequeuing* when
the supplied buffer is shorter than the queued frame, wedging the uplink
permanently, so the TAP read buffer is now CONFIG_NET_ETH_PKTSIZE rather
than a negotiated-MTU-sized allocation. The reassembly buffer lives in
pan_conn_t, not on the stack, because CONFIG_BT_RX_STACK_SIZE is 1200
bytes and a 1514-byte local would overflow the zblue RX thread only for
large frames - every small-packet test would still have passed.

Handshake correctness: the Setup Request was being built by hand as a
20-byte 128-bit-UUID message with a 2-byte UUID Size field. The field is
one byte, so peers answered 0x0003 Invalid Service UUID Size. It is now
bnep_encode_setup_req(NAP, PANU), 7 bytes. Peer-initiated setup is
answered with the standard 4-byte response, filter requests are refused
with 0x0001 Unsupported, and unrecognised control types get Command Not
Understood instead of being ignored.

Details:
- CMakeLists.txt: build bnep_codec.c and put service/stacks/zephyr on
  INCDIR. A quoted include inside sal_pan_interface.h resolves relative
  to service/stacks/include, so without this the codec header is not
  found from panu_service.c either.
- sal_pan_interface.h: delete the local constant table. Its response
  codes were wrong from 0x0003 up and 0x02 had two conflicting
  meanings; bnep_codec.h is now the single source.
- bt_uuid.h: add BT_UUID_PANU / BT_UUID_NAP.
- panu_service.c: register the SDP record with
  BT_UUID_DECLARE_16(BT_UUID_PANU) instead of an all-zero 128-bit UUID,
  drop ifup from the TAP-open path so the MTU is set first, and ifdown
  on disconnect rather than leaving a configured interface behind a
  dead link.
- pan_local_mac() is lazy: bt_sal_get_address() asserts the address
  type is public, which does not hold before the adapter is up.

Builds clean for contest_board:ai_agent (sram 474356 B / 90.48%,
flash 6252632 B / 37.27%). Not yet exercised on hardware.
The Kconfig entry is `config CONFIG_BLUETOOTH_DEFAULT_COD` (Kconfig:278),
so kconfig writes CONFIG_CONFIG_BLUETOOTH_DEFAULT_COD into .config. The
header tested the single-prefix spelling, which is never defined, so it
always fell through to the hardcoded fallback and any board that set the
value in its defconfig with one prefix had that line silently discarded.

Both spellings are now accepted, and the fallback gains the Networking
service-class bit (0x002A0704 instead of 0x00280704). Phones read that
bit to decide whether to offer network tethering, so a PAN-capable build
must not depend on a defconfig override to get it.
Three defects in the DHCP worker, all of which present as "PAN connects
but there is no IP, and nothing in the log says why".

1. g_dhcp_running leaked true. Both early returns (netlib_getmacaddr and
   dhcpc_open failures) and the success path returned without clearing
   it, and pan_start_dhcp() refuses to start while it is set. A single
   dhcpc_open failure therefore disabled DHCP for the rest of the boot -
   the link would reconnect happily and never request an address again.
   The thread now has one exit through `out`.

2. The thread was joinable and nothing ever joined it, so every PAN
   reconnect leaked a TCB and a 4K stack. Now PTHREAD_CREATE_DETACHED,
   and the pthread_t is a local since nobody needs to reference it.

3. Retry exhaustion just logged and died, leaving a live BNEP link with
   no address - the worst state to sit in, because every status check
   reports "connected". It now calls pan_dhcp_give_up_and_reconnect(),
   which posts to the service loop and drops the link so the existing
   PROFILE_STATE_DISCONNECTED handler drives ifdown and the three-class
   backoff. That keeps one reconnect path rather than two.

A bool alone could not express (3) safely. A link drop clears the flag to
ask the worker to stop, but the worker is asleep between retries and may
not see it for two seconds; a reconnect inside that window starts a new
worker, and the old one waking up would clear the flag under it and let
a later reconnect run two workers at once. g_dhcp_epoch fixes that: a
worker captures the epoch at startup and only clears the flag or triggers
a give-up if its epoch is still current. All three external stop sites go
through pan_stop_dhcp(), which bumps it.

The lifecycle trace is raw syslog, not BT_LOGI. CONFIG_BLUETOOTH_LOG is
off in the product config, so CONFIG_BLUETOOTH_SERVICE_LOG_LEVEL is
undefined and utils/log.h expands every BT_LOG* macro to nothing - all
51 BT_LOG* calls in this file emit nothing on the board, which is why
the PAN layer has been failing silently. PAN_STATE_LOG() gives one fixed
prefix so the whole lifecycle is `grep '[pan] state='`:

  state=connecting|connected|disconnected|disconnecting addr=... roles
  state=ifup dev=bt-pan tx_mtu=1691 if_mtu=1500
  state=dhcp_start|dhcp_retry|dhcp_ok|dhcp_dns|dhcp_giveup|dhcp_failed
  state=ifup_abort|dhcp_abort|dhcp_skip reason=...

Verified present in the linked image with arm-none-eabi-strings, since a
log that compiles away is exactly the failure being fixed here. Build is
clean; SRAM unchanged at 463428 B / 88.39%.
Sen70s added 4 commits August 20, 2026 21:30
… pool

Pairing died in unqliteOsLock with pfd->pMethods = 0x00011906: the 48-byte
file handle unqlite allocates at boot sits at the very top of the SRAM heap
and had its first word replaced. The mm node header below it was intact and
DEBUG_MM never fired, so the block was reused after a free rather than
overrun.

unqlite itself is not the gap - it installs recursive pthread mutexes and
every kv entry point takes pDb->pMutex. The asynchronous uv_db path is: its
request queue has no lock yet is entered from whichever thread calls in, a
failed uv_queue_work leaves a freed request linked (uv__queue_remove then
writes into it), and uv_queue_work off the loop thread touches
loop->active_reqs unlocked. The bond save comes in on the zblue stack
thread, unlike the boot-time AdapterInfo save that always worked.

So serialise every set/get on one mutex and run it on the calling thread
with the commit inline. Buffer ownership becomes "the caller always frees",
a missing key returns negative without invoking the load callback (all three
callers already handle that), and the load callbacks run outside the lock
because they re-enter the adapter state machine. Two syslog lines because
BT_LOG* is compiled out in this config.

Also gate the per-frame HCI trace behind BLUETOOTH_HCI_FRAME_TRACE: one
console write per ACL packet is not something the BNEP data path can carry.
The two frame-drop logs stay unconditional.

And bt_list: six non-void functions were returning garbage from a bare
"return;" on the NULL-list guard.
…nsole

Three gaps that all had the same shape - the headless product had nobody to
type the command:

- Nothing in this tree calls bt_adapter_enable(). bluetoothd only built the
  stack and waited, so the radio stayed off until "bttool enable".
  BLUETOOTH_AUTO_ENABLE arms a one-shot service-loop timer in
  bt_service_init(), because the whole turn-on path is the loop's work and
  the loop is not running yet at init time.

- A device with no saved properties comes up connectable-only, and there is
  no pairing UI to change that. BLUETOOTH_BOOT_SCAN_MODE overrides
  scan_mode in adapter_on_adapter_info_load() rather than in the turn-on
  path, so the value travels with the properties (the SAL gets it from
  adapter_on_br_enabled(), adapter_save_properties() persists it) and stays
  overridable at runtime.

- The bond and last_nap both survive a reset, so on a normal boot nothing
  bonds again and pan_on_bond_state() never fires: the watch came up paired
  with no network. pan_on_adapter_state_changed() now kicks
  pan_start_auto_connect() when a NAP is remembered and the auto state
  machine is idle.

Verified on hardware: t=15.4s auto-enable=0, t=19.6s BNEP+SDP registered,
scanmode 2 held across a reboot that had 1 in the database, phone finds the
watch.
sal_adapter_interface: register pairing_confirm/passkey_display/
passkey_confirm so get_io_capa() reports DisplayYesNo instead of
NoInputNoOutput. With only pincode_entry set, HyperOS 3.0 fell back to
legacy PIN entry and the phone showed a PIN-mismatch error - there is no PIN handler on
a headless board. passkey_confirm auto-accepts for the same reason.

main: nsh "kill <pid>" left the daemon wedged forever in
service_loop_join() (the loop thread does not exit on signals), and every
later IPC call hung with it until a USB power cycle. A daemon killed by
signal should just die.
…nd list

The BNEP TX path never worked: net_buf_tailroom() was 249 bytes whatever
CONFIG_BT_L2CAP_TX_MTU said, because pan_tx_pool was missing from zblue's
_net_buf_pool_list[] and pool_id() silently resolved it to index 0, handing
the buffer discardable_pool's size and storage.  With the pool registered
(external_zblue), drop the diagnostic scaffolding here: one allocation with a
100 ms wait is enough, and a tx_nobuf counter is all we need to tell an
exhausted pool from a broken one.

Shrink the pool from 4 buffers to 2.  Each is BT_L2CAP_BUF_SIZE(1691), about
1.7 KB of .bss, and the SRAM heap has to stay clear of the HCPU/LCPU mailbox
at 0x2007FB00, so the room has to come from somewhere.  The TAP reader sends
one frame at a time and the buffer is released on ACL completion, so depth
only buys pipelining.

Auto-connect had two gaps that left a paired watch offline until someone
typed "pan connect":

- last_nap was only written from the BOND_STATE_BONDED callback, so a watch
  paired by an older firmware had a bond but no last_nap, and
  pan_on_adapter_state_changed() skipped the auto-connect.  Fall back to the
  most recently bonded BR/EDR device, the same way bt_cm_device_connect()
  picks one.
- Write last_nap back on PROFILE_STATE_CONNECTED, so a console connect or a
  bond-list fallback also makes the next boot auto-connect.

RX logging is now limited to ARP, DHCP and failed TAP writes; everything else
on a tethered link is mDNS/ND chatter that drowns the console.
@Sen70s
Sen70s requested review from a team as code owners August 21, 2026 14:13
The guards added in 021919a were written as one-liners, which the project's
clang-format (WebKit) rejects: it wants the braced body on its own line.  Same
code, 11 sites, no behaviour change.
Three comments had Chinese text in them, which the checkpatch workflow
rejects in source files.  Comments only, no behaviour change.

void bt_list_clear(bt_list_t* list)
{
assert(list);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please do not change the assert check.
Fix the caller if there is a mistake.

Comment thread framework/common/bt_list.c Outdated
{
assert(list);
if (!list) {
syslog(LOG_ERR, "bt_list: NULL list\n");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use BT_LOGE instead.

Comment thread service/common/bluetooth_define.h Outdated
#define DEFAULT_DEVICE_OF_CLASS CONFIG_BLUETOOTH_DEFAULT_COD
#else
#define DEFAULT_DEVICE_OF_CLASS 0x00280704
#define DEFAULT_DEVICE_OF_CLASS 0x002A0704

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can set class of device via defconfig.

Comment thread service/common/bluetooth_define.h Outdated
#endif

#define DEFAULT_IO_CAPABILITY BT_IO_CAPABILITY_NOINPUTNOOUTPUT
#define DEFAULT_IO_CAPABILITY BT_IO_CAPABILITY_DISPLAYYESNO

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same, do not change the default value.

…match

bt_sal_pan_get_tx_mtu() looked the connection up by address only.  The two
establishment paths do not agree on how that address is produced (outbound
bt_sal_pan_connect() copies the caller's bytes, inbound pan_server_accept()
builds it from the stack's own representation), so the lookup could miss a
link that had just finished the BNEP handshake.  The profile layer then read
tx_mtu=0, logged ifup_abort reason=no_negotiated_mtu and dropped the link -
observed on hardware as an endless connect/drop/reconnect cycle.

PAN_MAX_CONNECTIONS is 1, so fall back to the only connected entry instead of
failing; log a warning when the fallback is what saved the call.
…aller

Addresses the review on open-vela#591:

- bt_list.c and bluetooth_define.h are back to their upstream form: the
  asserts are the library's contract, and the class-of-device default stays
  as it was.  The class of device is set from the board defconfig instead
  (board/contest_board/configs/ai_agent/defconfig).
- The Kconfig symbol was literally named CONFIG_BLUETOOTH_DEFAULT_COD, so
  kconfig emitted CONFIG_CONFIG_BLUETOOTH_DEFAULT_COD and the header's
  #ifdef CONFIG_BLUETOOTH_DEFAULT_COD never matched - the value was
  unreachable from a defconfig.  Renamed to BLUETOOTH_DEFAULT_COD so the
  defconfig route works as intended (no other board references the old name).
- sal_pan_interface.c now makes sure g_pan.conn_list exists at init instead
  of relying on bt_list_*() to tolerate NULL: a soft reset keeps RAM, so the
  list pointer can survive from the previous incarnation.

@zhongzhijie1 zhongzhijie1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

感谢提交 PAN/BNEP 这条链路的平台侧修复。整体方向可以,但按本仓库的采纳边界需要拆开看:

  • SAL / stack(service/stacks/zephyr/、bnep_codec.*):功能可以要,但下面几处实现问题需要先修。
  • service 层(service/profiles/、service/common/、service/src/):原则上不接受改动,尤其是产品定制、调试残留和跨模块夹带,请拆出或删掉。

以下 9 条 inline comment,SAL 5 条 / service 4 条。

if (!conn) {
return;
}
if (conn->state == PAN_CONN_CONNECTED) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SAL] 建议修复:连接建立前失败静默释放,且 5s 握手超时未实现

pan_chan_disconnected() 只在 state == PAN_CONN_CONNECTED 时上报 PROFILE_STATE_DISCONNECTED,其余状态直接 pan_conn_free(conn),上层收不到任何事件。

叠加 auto-connect 状态机:panu_service.c 里 g_auto_state = PAN_AUTO_CONNECTING 只有收到 DISCONNECTED 才会被复位,而 case PROFILE_STATE_CONNECTING: 是空的 break。于是手机侧拒绝 BNEP setup / 中途掉 ACL / 不回 setup 时,g_auto_state 会永久停在 PAN_AUTO_CONNECTING,auto-reconnect 不再触发,直到 bluetoothd 重启。

另外 setup_sent_ms(本文件 106 行注释写着 "for the 5s handshake timeout")只在 261 行写入、全文件无任何读取——握手超时实际没有实现,对端不应答 BNEP setup 时连接会永远卡在 PAN_CONN_BNEP_PENDING。

建议:

  1. 连接态之前失败也要上报 DISCONNECTED(带失败原因),让上层状态机能复位;
  2. 把 5s 握手超时真正接上 setup_sent_ms。

uint8_t out[16];
int n;

if (bnep_parse_control(ctrl, ctrl_len, &info) != BNEP_OK) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SAL] bnep_encode_cmd_not_understood() 是死代码,规范要求的 Command Not Understood 实际从未发出

bnep_parse_control() 对未知控制类型返回 BNEP_ERR_BADTYPE(bnep_codec.c:112-113 的 default: return BNEP_ERR_BADTYPE;)。而这里对任何非 BNEP_OK 都 early-return 并打 "malformed control frame"。

结果是下面 switch 的 default: 分支(约 388-394 行)不可达——未知但帧合法的控制类型被当成 malformed 丢弃,对端(例如较新的 Android NAP)收不到 BNEP 规范要求的 Command Not Understood,会一直等、握手互操作就断在这里。这与 commit message 的自述也不符。

建议:区分「帧本身 malformed」(TRUNCATED/BADUUID)和「未知消息类型」(BADTYPE),后者走 default: 回 Command Not Understood。

bt_addr_set(&addr, info.br.dst->val);

if (pan_find_conn(&addr)) {
syslog(LOG_WARNING, "[pan] incoming conn for known addr, replacing\n");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SAL] 日志说 replacing,实际并没有 replace

注释写着 "drop the stale one; the phone re-dials the PSM after ACL up",但下一行直接 return -ENOMEM,既没从 conn_list 移除旧 pan_conn_t,也没有复用它。

后果:ACL 回弹后手机重拨 BNEP PSM 0x000F,只要旧 entry 还挂在链表里,入向连接会被反复 -ENOMEM 拒掉,对端无法重建 PAN。

建议:要么真正 pan_conn_free(pan_find_conn(&addr)) 之后走新建流程,要么复用已有 conn;同时把返回码从 -ENOMEM 改成能反映「已有连接」的语义。

pan_conn_t* pconn;

if (err != BT_SECURITY_ERR_SUCCESS) {
syslog(LOG_WARNING, "[pan] security err %d\n", err);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SAL] security 失败只打日志就返回,worker 超时后仍会「L2CAP anyway」

err != BT_SECURITY_ERR_SUCCESS 时这里只记日志就 return,conn 留在 PAN_CONN_ACL_PENDING,上层收不到任何失败通知。

随后 worker 的 30s 等待超时(约 789 行 "worker: timeout, L2CAP anyway")会照发 L2CAP(pan_l2cap_connect(acl))。但本 PR 的 commit message 明确说 "Android NAP rejects unencrypted PAN connections"、这里还专门做了 request link encryption before L2CAP connect——加密失败后继续建连,要么在要求加密的对端上建不起来并卡死,要么在 required_sec_level = BT_SECURITY_L2 的配置下明文起 BNEP。

建议:加密失败时直接走失败上报 + pan_conn_free,让 worker 的超时兜底只处理「security 回调没来」的情况,不要覆盖「security 已经明确失败」的情况。


g_pan.max_connections = max_connections;
g_pan.role = role;
g_pan.conn_list = bt_list_new(NULL);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SAL] g_pan.conn_list 分配两次,每次 init 泄漏一个 bt_list_t

845-851 的 NULL 守卫块会 bt_list_new(NULL),紧接着这里又无条件 g_pan.conn_list = bt_list_new(NULL) 覆盖掉指针——守卫块等于每次白分配一个 list。

bt_sal_pan_cleanup() 会 bt_list_free 后把 g_pan.conn_list 置 NULL,所以下一次 init 一定走守卫分支,于是每次 PAN enable/disable 都累积一次堆泄漏;如果第二次 bt_list_new 失败,还会返回 BT_STATUS_NOMEM 而第一个 list 的指针已经悬空。

在目标机上这是常驻泄漏。建议删掉 854 行这次重复分配,只保留守卫分支;或者反过来删守卫块、保留无条件分配(但那样 cleanup 后的语义要重新确认)。

if (g_dhcp_handle) {
/* struct dhcpc_state_s starts with: interface, sockfd, ...
* The sockfd field is at offset sizeof(const char*) = 4 on ARM. */
typedef struct { const char *iface; int sockfd; } *dhcp_min_t;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[service] 采纳边界外 + 实现有问题,建议拆出/重做

先说边界:本仓库原则上不接受 service 层改动,这条属于 service profile,请移到产品仓或单独议题讨论。

实现层面两个问题:

  1. type-pun 强关 fd + 复用竞态:手工 typedef struct { const char *iface; int sockfd; } *dhcp_min_t 硬猜 struct dhcpc_state_s 的布局(注释还写死了 "= 4 on ARM"),这既不是可移植 ABI,也和并发的 DHCP worker 抢同一个 fd——worker 可能正阻塞在 recv(),此时 close(fd) 后系统复用该 fd 给新打开的文件,dying worker 会去读/关别人的 fd。
  2. epoch 守卫导致 dhcpc_state_s 泄漏:注释声称 "the thread wakes up ... and calls dhcpc_close() itself",但 worker 的 out: 路径是 if (handle && g_dhcp_epoch == my_epoch) { dhcpc_close(handle); }(435 行)——恰好是 stop 把 epoch 顶掉了,这个条件为假,dhcpc_close 被跳过。438 行还无条件 g_dhcp_handle = NULL,之后也没人能再关它。所以每次 DHCP 进行中断连都会泄漏一份 dhcpc_state_s,与注释描述相反。

建议:把 stop 协议改成 worker 自己收尾(例如 shutdown() 而非 close(),让 worker 走正常 dhcpc_close),不要跨线程拆别人的结构体。

* xiaozhi-sf32 does this at BT_APP_READY: bt_interface_set_local_name
* with "xiaozhi-XX:XX:XX:XX:XX:XX". We do "Agent-Watch-XX:XX:XX:XX:XX:XX". */

static void pan_set_local_name_with_mac(void)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[service] 范围蔓延 + 产品定制,不应进 open-vela 公共树

这条改动和 PAN/BNEP 功能无关,属于赛题产品逻辑:

  1. pan_set_local_name_with_mac() 在每次 adapter ON 时把蓝牙名强制改成 BT_NAME_PREFIX "Agent-Watch" + MAC(覆盖用户名)——任何复用本 service 的产品开蓝牙名字都会被改掉。
  2. 文件里夹带了 xiaozhi 的身份工具 pan_get_device_id() / pan_get_bt_mac_address(),并在文件中部 #include <mbedtls/sha256.h>(606 行)——PAN profile 依赖 mbedtls 做身份派生,层级不对。
  3. 193 行注释含 Unicode 制表符框线(── PAN auto-connect helpers ... ──),违反本项目「英文代码注释、无非 ASCII 源码」约定。

建议:把改名、设备身份相关代码整体拆到产品仓;PANU service 只保留通用 PAN 逻辑。

Comment thread service/common/storage.c
/* Outside the lock: the load callbacks re-enter the adapter state machine,
* which stores keys again. */
key_get_callback(0, key, buf, cookie);
free(buf.base);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[service] 采纳边界外;且这里把内部指针交给回调后立刻 free,边界不安全

边界问题同上:service/common/storage.c 属于 service 基础设施,原则上不接受改动。

实现上两点:

  1. key_get_callback(0, key, buf, cookie) 传给 load 回调的 header->key_value 是 buf.base 的内部指针,紧接着 free(buf.base)。当前 adapter 回调是 memcpy 走的,暂时没事;但任何 load 回调(bond / whitelist / gatt cache 等)只要留存该指针就是 use-after-free。建议把「所有权」写进 load_storage_callback_t 的契约,或者让回调拿拷贝。
  2. 72 行 assert(value.len == (sizeof(key_header_t) + header->key_length)) 在断电/半写导致的损坏记录上会直接 abort bluetoothd。存储层遇到脏数据应该走 callback(NULL, 0, 0) 优雅失败并丢弃该 key,而不是崩进程。

Comment thread service/src/btservice.c
#include <syslog.h>
#include <unistd.h>

/* TEMP-DIAG: probe inode tree health by opening /dev/urandom (the exact

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[service] TEMP-DIAG 调试脚手架请勿提交

probe_inode() 在 6 个启动阶段(btsvc-entry / folder / storage / profile / adapter-mgr / stackmgr)无条件 open("/dev/urandom") 并打 syslog——注释自己写了 TEMP-DIAG,是临时排查 inode 树健康的调试代码。

请整体删除,或至少包在明确的 debug Kconfig 后面(默认关闭)。正式版本每次 bluetoothd 启动多 6 次无关 open + 6 行日志噪声,且 /dev/urandom 不可用时还会额外报错。

@Sen70s

Sen70s commented Oct 24, 2026

Copy link
Copy Markdown
Author

按官方 review 的 service 层边界,已将 stack/SAL 部分拆到 #594:

#594

#591 暂不关闭,保留作原始完整 PR 的对照。

#594 范围

  • SAL setup timeout / failed release
  • BNEP BADTYPE / Bad UUID
  • stale / duplicate accept
  • security fast path
  • bt_list_new 修复
  • 旧 profile API 兼容层

#594 不包含 service 层改动。

#3 companion

#3 的 ACL 不拆行为依赖 external_zblue:

open-vela/external_zblue#234

该 PR 只改 l2cap_br_conn_req() 的 accept 失败路径,不拆共享 ACL。

service 层

service 层 #6/#7/#8/#9 已按 review 意见移到产品仓归档:

https://github.com/Sen70s/contest2026_181_womenshayebuhuidui/blob/feat/ai-agent-contest/docs_ble/patches/pr591_service/README.md

不会进入 open-vela/frameworks_bluetooth 公共树。

当前状态

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants