Skip to content

Contest/pr 20261103 - #596

Open
Sen70s wants to merge 49 commits into
open-vela:dev-ai-contest-2026from
Sen70s:contest/pr-20261103
Open

Sen70s wants to merge 49 commits into
open-vela:dev-ai-contest-2026from
Sen70s:contest/pr-20261103

Conversation

@Sen70s

@Sen70s Sen70s commented Nov 3, 2026 •

Copy link
Copy Markdown

Summary

Implement the PAN/BNEP service layer on the Zephyr stack adapter, and fix the
connection lifecycle races that made PAN hang and silently drop links on
SF32LB52 hardware.

Features

  • Add BNEP codec (header encode/decode, filter handling) and the SAL PAN interface
  • Wire panu_service to SAL: connect/disconnect, TX path, tx_mtu resolution by the
    single connected entry instead of address matching
  • Cancel the setup timer synchronously during cleanup; close connect/cleanup races
    and the publication windows
  • Own the connection lifetime in SAL and harden failure paths; transfer the worker
    slot reference and report setup send errors
  • Synchronize init with worker teardown; decide disconnect by the mounted channel
  • Stop reading the adapter device list from HCI/uv threads (fixes a hard hang)
  • H4 read path: normalize encryption-change status, chunked ACL tracing behind a
    debug switch

Files

文件 说明
service/stacks/zephyr/bnep_codec.c/.h BNEP 头编解码与过滤规则
service/stacks/zephyr/sal_pan_interface.c SAL PAN 实现:连接生命周期、TX、断开判定
service/stacks/include/sal_pan_interface.h SAL PAN 接口定义
service/profiles/pan/panu_service.c PANU profile 接通 SAL
service/profiles/include/pan_service.h profile 接口调整
service/stacks/zephyr/sal_adapter_interface.c 适配器列表访问移出 HCI/uv 线程
service/stacks/zephyr/hci_h4.c H4 读路径与加密状态归一化
service/common/service_loop.c/.h 服务循环清理时序
service/src/adapter_service.c、btservice.c、main.c 初始化与拆解时序
CMakeLists.txt、Kconfig 新增源文件与配置项

Testing

  • 编译:openvela SF32LB52 目标全量编译通过
  • 真机:BLE/BR-EDR 下 PAN 建链 → DHCP → ping / 吞吐测试
  • 反复 connect/disconnect 50 轮无挂死、无残留 worker 引用
  • 长时间(>1h)空闲后重新建链正常

Build host

  • Ubuntu Linux x86_64, gcc 12, openvela dev-ai-contest-2026

Target

  • arch: arm, board: sf32lb52_devkit_lcd (SF32LB52-DevKit-LCD)

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 18 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.
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.
…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.
…uv threads

The link key bridge added earlier today hung the whole device on hardware
(serial silent, BT dropped, screen frozen). Root cause: the B1 producer called
adapter_get_link_key() from HCI event context just to make the bridge
idempotent, and that helper walks g_adapter_service.devices without
adapter_lock while the service thread mutates the same list under that lock
(bt_list_add_tail / bt_list_remove_node + free) -> dangling pointer -> data
abort.

- F1 (producer): drop the adapter_get_link_key() readback + memcmp. Deduplicate
  with a SAL-local static cache (addr + key) instead; every caller runs in the
  HCI event pump on the one sysworkq thread (CONFIG_BT_RECV_WORKQ_SYS=y;
  bt_conn_set_security() does not notify inline), so it has a single writer and
  needs no lock. The cache is only a dedup hint, hence not invalidated on
  unpair: re-pairing derives a fresh key and the compare just misses.
- F2 (producer): drop the bt_keys_link_key_load_file() fallback - no file I/O
  in the HCI event pump; the host already lazy-loads the key in ssp.c:598/619.
- F3 (consumer): B2 no longer calls adapter_get_link_key()/_type(). The 17-byte
  framework snapshot now travels inside the SAL request
  (sal_adapter_req_t.adpt.link_key, filled by bt_sal_set_bonded_devices from the
  props the service thread already holds), and the host key pool is written from
  host context: the payload is handed to k_sys_work_q through a small queue and
  drained by a static work item - the same workqueue that runs the HCI event
  pump (rx_queue_put) and therefore ssp.c/smp.c pool access. The work item is
  static because the workqueue writes work->flags after the handler returns
  (kernel/work.c:697): a per-request item freed from its own handler would be a
  use-after-free.
- Correct the thread attribution comments (:578, :1897): the store callbacks run
  on k_sys_work_q (sysworkq, prio 110); the restore request runs on the libuv
  thread-pool worker (prio 100, 8KB stack), not on a "zblue host thread" (this
  port has none - zblue_main() is only declared).
- The matching hdev->keys NULL guard lives in the zblue repo (bt_dev_get() is
  already non-NULL before bt_keys_init()).

Verified: ninja nuttx.bin clean (flash 73.33%, sram 88.77%). Not flashed, no
serial touched.
@Sen70s
Sen70s requested review from a team as code owners November 3, 2026 15:13
- panu_service: 修正断开/清理路径与服务状态同步
- power_manager: 调整蓝牙电源状态与 PAN 唤醒时序

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.

1 participant