Commit graph zephyr/subsys/bluetooth
Author SHA1 Message Date
Kai Cheng
8c398ec652 bluetooth: classic: shell: add HID Host commands
Add hid_host shell commands to exercise the HID Host profile:

- register / unregister
- sdp_discover
- connect / disconnect / select <address>
- get_report <type> <id> <buf_size>
- set_report <type> <hex...>
- get_protocol / set_protocol <boot|report>
- send <hex...> (output report on the interrupt channel)
- suspend / exit_suspend
- vcu (virtual cable unplug)

The profile does not read the HID service record, so sdp_discover does it
here: it reads the report descriptor and the device attributes and walks
the descriptor for a Report ID Global item. The Report ID is then split off
incoming reports and added to GET_REPORT requests, which is the work an
application has to do (HID spec v1.1.2 Section 3.1.2.3 and Section 3.3.1).
Only the descriptor is required; the remaining attributes are optional in
the record, so a missing one is reported and the rest is still read.

The profile associates with one HID Device per ACL connection, so the state
the shell keeps for a peer is indexed by connection index as well: the
report descriptor outcome, the protocol mode, the pending unplug and the
SDP discovery parameters. Sharing one set would mix up a keyboard that
declares Report IDs with a mouse that does not, destroy the bonding of the
wrong peer, or put the same SDP request node on two lists. The connected
callback points the selected instance at whatever associated last, so
select reaches the other one while both are up.

A Virtual Cable Unplug destroys the bonding as required by Section
3.1.2.2.3, deferred until the channels have closed so that the ACL is not
dropped from under them.

Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
2026-09-16 05:50:36 +02:00
Kai Cheng
f7858e15e0 bluetooth: HID: add HID Host profile support
Add the HID Host side of the Bluetooth Classic HID profile, letting a
Zephyr device drive HID peripherals such as keyboards, mice and gamepads,
as defined in HID spec v1.1.2.

The profile owns the HIDP framing and the association:

- host-initiated connection, opening the control channel first and the
  interrupt channel once it is up (Section 5.2.2)
- device-initiated connection through L2CAP servers on both PSMs
- GET_REPORT / SET_REPORT and GET_PROTOCOL / SET_PROTOCOL on the control
  channel, with a single outstanding transaction (Section 3.2.1)
- output reports sent and input reports received on the interrupt channel
- SUSPEND / EXIT_SUSPEND and Virtual Cable Unplug in both directions
- connection pool indexed by ACL connection index

Reading the HID service record is left to the application. Both PSMs are
fixed, so the profile needs nothing from the record to open the channels,
and report payloads are handed over as received: whether one starts with a
Report ID follows from the report descriptor and from the protocol mode,
which only the application knows (Section 3.1.2.3 and Section 3.3.1).
This matches the HID Device side, which does not store a descriptor
either, and follows MAP and PBAP, where SDP discovery lives in the
application.

Both channels request an MTU of BT_L2CAP_RX_MTU as required by Section
5.2.3.1, the interrupt channel is closed before the control channel per
Section 5.2.2, and a control transaction that is never answered is bounded
by a timer so the association cannot stay blocked (Section 5.2.6).

Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
2026-09-16 05:50:36 +02:00
Kai Cheng
77c2c27df2 bluetooth: classic: HID: share the protocol values between both roles
Move the HID protocol values an application needs into a new
<zephyr/bluetooth/classic/hid.h> and include it from hid_device.h, so a
second role can reuse them instead of defining its own copy.

Protocol mode, report type and HANDSHAKE result codes are carried by the
same HIDP messages in both directions, so they belong to neither role.
Keeping a copy per role means two public headers cannot be included in the
same translation unit unless every replacement list stays textually
identical, which is not something a compiler warns about until it breaks.

The internal copies go away with it: hid_internal.h loses the HANDSHAKE
result codes it repeated from the public header and BT_HID_PAR_REP_TYPE_*,
which named the same report types a second time. Message types, HID_CONTROL
operations and the header field masks stay internal since they are HIDP
framing that no application has to know about.

This follows the layout other stacks use for the same reason: BTstack keeps
btstack_hid.h next to hid_host.h and hid_device.h, and Fluoride keeps
hiddefs.h next to hidh_api.h and hidd_api.h.

Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
2026-09-16 05:50:36 +02:00
Pisit Sawangvonganan
5febb0aa90 Bluetooth: classic: shell: avoid recomputing strlen() in loops
Optimize HFP command handlers where strlen(action) was unnecessarily
recomputed on every loop iteration even though the string argument
never changed within the loop.

The affected functions:
- cmd_ag_vre_state(): strlen(action) recomputed in action parsing
- cmd_ag_vre_text(): strlen(action) recomputed in action parsing

Store the string length in a local variable before the loop and reuse it
throughout, eliminating redundant strlen() calls.

Assisted-by: Claude:Haiku 4.5
Signed-off-by: Pisit Sawangvonganan <pisit@ndrsolution.com>
2026-09-16 05:43:25 +02:00
Johan Hedberg
36374b133d Bluetooth: Host: Drop the forward declaration of get_pending_per_adv_sync()
The function is defined before its first use, so the declaration
serves no purpose. No functional change.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-15 07:15:07 -04:00
Johan Hedberg
a6ef755158 Bluetooth: Host: CS: Order clear_on_disconnect() before its use
clear_on_disconnect() is only referenced by the connection callback
table: define the table after the function and drop the forward
declaration. No functional change.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-15 07:14:57 -04:00
Johan Hedberg
61e0fc777a Bluetooth: Host: Order the ECC work handlers before their work items
generate_pub_key() and generate_dh_key() are only referenced by the
work items defined with K_WORK_DEFINE(): define the work items after
the handlers and drop the forward declarations. No functional change.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-15 07:14:49 -04:00
Johan Hedberg
dc7d7634af Bluetooth: Host: Drop redundant forward declarations in direction.c
The six declared functions are all defined before their first use, so
the declarations serve no purpose. No functional change.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-15 07:14:37 -04:00
Johan Hedberg
c8c2438f05 Bluetooth: Classic: AVRCP: Do not wait for browsing RX buffers
The buffer callback of the browsing channel allocates with K_FOREVER.
L2CAP calls it from the Bluetooth RX workqueue, both for a new SDU and
for every further fragment appended to it, and releases the buffers on
that same workqueue once the SDU has been delivered. The pool is
shared by all browsing channels and one SDU can take several buffers,
so once it runs dry the wait can never be satisfied and stops all HCI
receive processing instead.

Allocate without waiting. L2CAP handles a failed allocation on this
channel by disconnecting it, which the application can recover from,
unlike a blocked host.

Compile-tested only; there is no AVRCP browsing test coverage in the
tree.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-14 08:42:57 -04:00
Johan Hedberg
8529242080 Bluetooth: AVCTP: Do not block the workqueue on reassembly allocation
The reassembly buffer for a fragmented AVCTP message is allocated with
K_FOREVER from the receive path, which runs in the Bluetooth RX
workqueue. That workqueue is also the only context that releases
reassembly buffers, once the reassembled message has been dispatched,
so a wait there can never be satisfied and would stop all HCI receive
processing instead. The in-tree pool sizing, one buffer per session,
keeps the wait from triggering today, and the failure path behind it
returned -ENOMEM, which makes L2CAP tear down the channel, unlike
every other failure in this function, which drops the fragment and
keeps the channel up.

Allocate without waiting and treat a failed allocation like the other
reassembly failures: drop the fragment and let the peer time out.

Compile-tested only; there is no AVCTP test coverage in the tree.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-14 08:42:57 -04:00
Jasen Liu
d0e3e07de4 bluetooth: audio: guard PA sync FILTER_DUPLICATE with ADI feature
The bap_broadcast_sink sample was previously fixed to only set
BT_LE_PER_ADV_SYNC_OPT_FILTER_DUPLICATE when the controller supports
the Periodic Advertising ADI Support feature. Several other broadcast
sink/assistant code paths still set this option unconditionally.

BT_LE_PER_ADV_SYNC_OPT_FILTER_DUPLICATE requires the controller to
support the Periodic Advertising ADI Support feature. On controllers
that do not support it (e.g. external HCI controllers such as NXP
IW612), bt_le_per_adv_sync_create() rejects the option and returns
-ENOTSUP, so the periodic advertising sync is never created.

Apply the same fix as bap_broadcast_sink to the remaining paths:
check BT_FEAT_LE_PER_ADV_ADI_SUPP via bt_le_get_local_features() and
fall back to BT_LE_PER_ADV_SYNC_OPT_NONE when the feature is not
supported.

Updated PA sync creation paths:
- cap_acceptor: pa_sync_without_past() - PA sync when PAST is not used
- cap_acceptor: scan_check_and_sync_broadcast() - PA sync from scan
- shell/bap: pa_sync_broadcast_sink() - PA sync from scan results
- shell/bap_scan_delegator: pa_sync_no_past() - PA sync without PAST

Signed-off-by: Jasen Liu <jasen.liu@nxp.com>
2026-09-14 08:42:48 -04:00
Emil Gydesen
1254bf165a Bluetooth: CAP: add subprocedure callbacks for unicast start and stop
The CAP unicast audio start and stop procedures consist of several
subprocedures, and applications may need to know when each of these have
completed, e.g. to reconfigure the unicast group after the streams have
been codec configured but before they are QoS configured.

Add new callbacks to bt_cap_initiator_cb for each subprocedure of the
unicast audio start and unicast audio stop procedures. The callbacks are
only called if at least one request was sent to a CAP acceptor as part of
the subprocedure, so that subprocedures that are skipped because all
streams are already in the requested state do not trigger a callback. To
support this a new subproc_initiated field has been added to the common
procedure struct, which is reset whenever a new subprocedure is set.

The unit tests have been extended to verify both that the callbacks are
called when the subprocedures are performed, and that they are not called
when the subprocedures are skipped, and the BSIM CAP initiator unicast
test now waits for the new callbacks as part of the start and stop
procedures.

Assisted-by: Copilot:claude-opus-4.5

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-14 08:42:10 -04:00
Emil Gydesen
b01df6e903 Bluetooth: ASCS: Refactor ASCS to use sys_wq for cp_rsp
Refactor ASCS to use the system workqueue for the control
point notification. This is to ensure that we always send
the notification, even if we may be out of ATT buffers at
any point, but also ensures that the control point notification
is sent before any ASE notifications triggered by that control
point write.

Some refactoring was done to account for the changes when cleaning
up the ASEs.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-12 07:52:56 -04:00
Emil Gydesen
92c6927cb1 Bluetooth: Host: Set BT_GAP_SID_INVALID for legacy adv
The SID is only used for extended advertising sets. For any
legacy advertising sets, we now set the adv->sid to
BT_GAP_SID_INVALID. This is similar to how the SID for
legacy scan reports are handled in scan.c

bt_le_ext_adv_update_param could also have a new SID for the
advertising set that was never stored in adv->sid. This has
also been fixed in this commit.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-11 17:34:52 +02:00
Johan Hedberg
e9c3252c24 Bluetooth: Host: Validate periodic advertising report length
The periodic advertising report handler checks that the event header is
present and that the data fits in the reassembly buffer, but not that
the event actually carries as many data bytes as its length field
claims. With CONFIG_BT_PER_ADV_SYNC_BUF_SIZE > 0, a report with a
length field larger than the remaining event payload makes
net_buf_simple_add_mem() copy up to 255 bytes from beyond the end of
the HCI event buffer into the reassembly buffer, and the result is
passed on to the application.

Drop such reports the same way as reports that do not fit in the
reassembly buffer.

Fixes #117587

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-11 17:26:33 +02:00
Lyle Zhu
35fcd3947f bluetooth: classic: l2cap: Fix data drop waiting for config rsp sent
In commit 15bb270 (bluetooth: classic: l2cap: Fix race condition in
config rsp handling), the channel transitions from the `CONFIG` state
to the `CONNECTED` state of L2CAP channel will be set after the
configuration response frame has been sent via the sent callback
`l2cap_br_config_rsp_sent_cb()`. The sent callback will be called by
`hci_num_completed_packets()` when the HCI event
`NUM_COMPLETED_PACKETS` is notified. However, the time duration
between the completion of the configuration response transmission
and the arrival of the `NUM_COMPLETED_PACKETS` HCI event is
indeterminate; it depends entirely on the controller.

From the peer's perspective, the L2CAP channel is successfully
established once the configuration response is received, whereas the
local side remains in the `CONFIG` state until the
`NUM_COMPLETED_PACKETS` event arrives. Consequently, it is possible
for the peer to transmit data over the established channel before the
`NUM_COMPLETED_PACKETS` event arrives. Since the local side is still
in the `CONFIG` state, this data will be discarded.

Add `L2CAP_FLAG_CONF_RSP_SENDING` flag, set before queuing the
configuration response and cleared in the sent callback. In the
receive path, attempt to complete the configuration state when this
flag is set, so that data arriving before the HCI
`NUM_COMPLETED_PACKETS` event does not get silently discarded.

The change aims to prevent the dropping of received data while waiting
for the HCI event `NUM_COMPLETED_PACKETS`.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-09-11 05:24:55 -04:00
Lyle Zhu
a8707cca92 bluetooth: classic: rfcomm: add retry timeout mechanism
Add a retry timeout mechanism to prevent indefinite retry attempts
when buffer allocation failures persist, ensuring the RFCOMM state
machine eventually fails gracefully instead of retrying forever.

Introduce per-DLC `retry_timeout_work` and per-session
`retry_timeout_work` timers (5 seconds) that run in parallel with
the randomized retry mechanism. When a retry timeout expires, trigger
the RTX timeout handler to tear down the connection.

Add `rfcomm_dlc_retry_timeout()` and `rfcomm_session_retry_timeout()`
handlers that reschedule the RTX work with `K_NO_WAIT` to initiate
immediate disconnect when retry attempts exceed the timeout threshold.

Schedule retry timeout when setting retry flags for:
- DLC operations: PN_REQ, PN_RSP, UA_FOR_SABM, DM, UA_FOR_DISC,
  MSC_FC_CLEAR_REQ
- Session operations: FC_ON_REQ, FC_ON_RSP, FC_OFF_RSP, UA_FOR_DISC

Cancel retry timeout when operations succeed to prevent spurious
disconnects after successful recovery.

Rename `RFCOMM_RETRY_TIMEOUT` to `RFCOMM_RETRY_INTERVAL` and introduce
new `RFCOMM_RETRY_TIMEOUT` constant (5 seconds) to distinguish between
the randomized retry interval (0-100ms) and the overall retry timeout
threshold.

Update all retry scheduling calls to use `RFCOMM_RETRY_INTERVAL` for
the randomized delay and `RFCOMM_RETRY_TIMEOUT` for the timeout timer.

Cancel retry timeout work in cleanup paths:
- `rfcomm_dlc_destroy()` for DLC cleanup
- `rfcomm_disconnected()` for session cleanup

Add early return in `rfcomm_session_retry_timeout()` when the
underlying connection is already gone to handle race conditions
during cleanup.

This change complements the randomized retry mechanism by adding an
upper bound on retry duration, preventing resource exhaustion and
ensuring predictable failure behavior when buffer allocation issues
cannot be resolved within a reasonable timeframe.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-09-11 05:24:36 -04:00
Lyle Zhu
082367e49b bluetooth: classic: rfcomm: add randomized retry mechanism
Refactor RFCOMM retry mechanism to improve robustness and prevent
thundering herd issues when multiple operations fail simultaneously
due to buffer exhaustion.

Add the session-level `retry_work` supports randomized retry delays
for session-scoped operations. Convert DLC `tx_work` from `k_work`
to `k_work_delayable` to support randomized retry delays for
DLC-scoped operations.

Since the FCON and FCOFF apply to all DLCS, they should be handled at
the session-scoped rather the DLC-level. Move their handling to the
session-level `retry_work` instead of handling them per-DLC
`retry_work`. Besides, UA for DISC of DLCI0 also handled by the
session-level `retry_work`.

Introduce randomized retry timeout (0-100ms) using `sys_rand32_get()`
to prevent synchronized retries when multiple DLCs or sessions
experience buffer allocation failures concurrently.

Add session-level retry handler `rfcomm_session_retry_handler()` to
process deferred session operations (FC_ON_REQ, FC_ON_RSP, FC_OFF_RSP,
UA_FOR_SABM, UA_FOR_DISC, DISCONN_REQ) with proper flag-based state
tracking.

Add DLC-level retry handler `rfcomm_dlc_retry()` within the tx_worker
to process deferred DLC operations (PN_REQ, PN_RSP, UA_FOR_SABM, DM)
before entering the connected state. And add DLC-level retry handler
`rfcomm_dlc_reprocess_disc()` within the tx_worker to process
deferred DLC operations (UA_FOR_DISC).

Extract send operations into dedicated functions with comprehensive
error handling:
- `rfcomm_dlc_send_pn_req()` / `rfcomm_dlc_send_pn_rsp()` for PN
- `rfcomm_dlc_send_ua_for_sabm()` for SABM response
- `rfcomm_dlc_send_dm()` for security rejection
- `rfcomm_session_send_fc_on_req()` / `rfcomm_session_send_fc_on_rsp()`
- `rfcomm_session_send_fc_off_rsp()` for flow control
- `rfcomm_session_send_ua_for_disc()` for session disconnect
- `rfcomm_session_send_ua_for_sabm()` for session connect
- `rfcomm_session_disconn_req()` for session L2CAP disconnect

Add `rfcomm_dlc_process_disc()` and `rfcomm_dlc_reprocess_disc()` to
handle DISC processing with retry support for UA response failures.

Extract `rfcomm_session_control_channel_connected()` to centralize
DLC startup logic after session establishment.

Add `BT_RFCOMM_STATE_SECURITY_FAILED` state to properly track security
rejection scenarios and enable deferred DM sending.

Reorder states in the enum to group security-related states together
before CONFIG state.

Cancel session retry_work in `rfcomm_disconnected()` cleanup path.

These changes complement the previous buffer allocation error handling
by distributing retry attempts over time, reducing contention on the
buffer pool and improving overall system stability under load.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-09-11 05:24:36 -04:00
Lyle Zhu
054159d25e bluetooth: classic: rfcomm: improve FCON and credit retry handling
Improve the robustness of RFCOMM flow control recovery by adding
session-level FCON retry logic and retry triggers for failed credit
and MSC operations.

Add `rfcomm_dlc_update_fc_on()` to check the flag and send FCON when
buffers become available, with proper error handling that retries
on failure.

Set `RFCOMM_SESSION_FLAG_FC_ON_REQ` in `rfcomm_dlc_connected()`. And
call `rfcomm_dlc_update_fc_on()` to send FCON.

Call `rfcomm_dlc_update_fc_on()` from `rfcomm_dlc_fc_check_and_on()` so
session-level flow control will be checked and processed in the DLC TX
processing.

Trigger TX processing at the end of `rfcomm_dlc_connected()` to ensure
the deferred FCON send happens promptly if the flag
`RFCOMM_SESSION_FLAG_FC_ON_REQ` is not cleared.

Add retry triggers in `rfcomm_dlc_fc_check_and_on()` and
`rfcomm_dlc_update_credits()` when send failures occur, ensuring the
state machine recovers quickly instead of waiting for the next DLC TX
event.

These changes refine the various handling mechanisms for buffer
allocation errors from the previous submission, ensuring that flow
control operations at both the session-level (FCON) and the DLC level
(MSC, credit-based) can recover when buffer allocation fails.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-09-11 05:24:36 -04:00
Lyle Zhu
ce7527e688 bluetooth: classic: rfcomm: handle MSC send failure in dlc connected cb
When rfcomm_send_msc() fails in rfcomm_dlc_connected(), set the
RFCOMM_FLAG_MSC_FC_CLEAR_REQ flag to ensure the MSC command will be
retried later instead of silently dropping the failure.

This complements the buffer allocation error handling introduced in the
previous commit by ensuring the flow control state machine can recover
when the initial MSC send fails due to buffer exhaustion.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-09-11 05:24:36 -04:00
Lyle Zhu
214530895d bluetooth: classic: rfcomm: remove K_FOREVER from buffer allocation
Previously, the timeout `K_FOREVER` is used to allocate the net buffer
from the TX buffer pool. It causes the BT workqueue to be blocked by
the buffer allocation operations with unpredictable completion times,
preventing subsequent work handlers from executing.

Use `K_NO_WAIT` to replace `K_FOREVER`. It means that when the buffer
allocation function returns, there's no guarantee that a buffer has
been allocated. Therefore, add comprehensive error handling for
buffer allocation failures in the RFCOMM implementation.

- Add `rfcomm_create_pdu()` to wrap `bt_l2cap_create_pdu_timeout()`,
  checking both the allocation result and available tailroom
  before the buffer is used.
- Check the return value of every `rfcomm_send_*()` call and
  propagate allocation failures up the call stack as -ENOBUFS.
- Handle send failures in the SABM, DISC, PN, UA, DM, MSC, RLS,
  RPN, TEST, FCON, FCOFF and NSC paths, logging the error and, on
  the disconnect paths, rescheduling the retransmission timer
  immediately so the state machine still recovers instead of
  waiting on the RTX timeout.
- Extract `rfcomm_dlc_connect()` and `rfcomm_dlc_disconn()` so the
  connect/disconnect error handling lives in one place instead of
  being duplicated at each call site.

The change prevents workqueue stalls and crashes when the L2CAP buffer
pool is exhausted.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-09-11 05:24:36 -04:00
Kai Cheng
5fcb4619b3 Bluetooth: SDP: Add bt_sdp_unregister_service() API
Add a new API to remove a previously registered Service Record from
the SDP database. This complements bt_sdp_register_service() and
follows the same pattern as bt_l2cap_br_server_unregister().

The function checks for active SDP server L2CAP channels and returns
-EBUSY if any exist, preventing unsafe removal during active
transactions. A residual race window remains between the check and
the actual removal; the caller is responsible for ensuring no new
SDP connections are established during this call.

Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
2026-09-11 05:22:43 -04:00
Kai Cheng
d48951897a Bluetooth: SDP: Remove redundant num_services variable
The num_services counter was only used in a single condition
(state.current_svc < num_services) within the SSA response
continuation state logic. Since record indices are assigned
sequentially from 0 and state.current_svc is always set from
record->index (which is always < num_services for any valid
record), this condition is always true — making it dead code.

Remove the variable, its increment in bt_sdp_register_service(),
and the redundant condition wrapper, unconditionally entering
dry_run mode when the packet is full.

Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
2026-09-11 05:22:43 -04:00
Aleksandr Khromykh
92a642f79a bluetooth: mesh: wait for target apply to finish before confirm
Commit 1de08e0b6e ("bluetooth: mesh: dfu_cli, dfu_srv: accept SUCCESS
+ APPLYING as terminal") ended the Apply step as soon as a target
answered Success with phase Applying Update. MshDFUv1.0 Section 6.2.2.4
requires the Confirm step to wait until the targets have applied, and
that retry loop was the only thing implementing the wait. Without it the
client reads the old Current Firmware ID and Table 7.3 in Section
7.1.2.9 marks the target Apply Failed. A PTS test caught this.

Repeat Firmware Update Apply while a target reports Applying Update, as
Section 7.1.2.6 permits. Once the install completes the target answers
Wrong Phase with phase Idle, which the branch above already accepts.

Keep acknowledging the self-target: a Distributor that is also a Target
defers its own apply until the Confirm step completes, so it never
leaves Applying Update on its own.

Revert the accompanying dfu_srv change, which applied the firmware on an
unacknowledged response assuming the client would not retry. Reverting
the phase to Verification Succeeded on any send error is correct now
that it does: the retry is accepted as a fresh apply per Section
6.1.3.6.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
2026-09-10 19:18:01 +02:00
Emil Gydesen
14b440ecad Bluetooth: OTS: Client: call checksum cb on error responses
The oacp_ind_handler only invoked the obj_checksum_calculated
callback when the indication contained a 32-bit checksum. Error
responses to BT_GATT_OTS_OACP_PROC_CHECKSUM_CALC omit the checksum,
so the callback was never called and the application had no way to
learn that the procedure failed.

Only parse the checksum when the result code is success, and always
invoke the callback with the result code, passing a checksum of 0 for
error responses. This matches the documented behavior of the
callback.

Assisted-by: Copilot:GPT-5.6

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-10 19:14:44 +02:00
Lyle Zhu
c623845e4c Bluetooth: host: classic: shell: Fix SDP discovery parameter handling
Previously, a single static `discov` variable was used to hold the
selected discovery parameters, which would be overwritten on each call.
This could lead to issues if multiple discovery operations were queued
or in progress.

The change makes `discov` a local pointer that references the
appropriate pre-defined discovery parameter structure based on the
input shell command parameters.

The change is used to align with the refactored SDP client queue-based
request handling and ensures each discovery request maintains its own
parameter context.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-09-10 12:18:37 +02:00
Lyle Zhu
9cf8cd6513 Bluetooth: host: classic: Refactor SDP client session management
SDP clients use `sem_lock(k_sem_take(K_FOREVER))` to serialize access
to their request list and session state to avoid thread safety issues.
Because SDP client callbacks run on a shared, cooperative `bt_workq`,
blocking the semaphore from the `bt_workq` context could cause all
other items in the same work queue to stall, not just the SDP session
itself.

Replacing the semaphore-protected `sys_slist` pair (`reqs`/`reqs_next`)
with a single `k_queue reqs_pending` allows safe access from any
context without blocking. `bt_sdp_discover()` returns success
immediately after adding a new request to the `queue reqs_pending` and
submitting a new `sdp_client_worker`. Therefore, the original session
creation-related operations are moved to `sdp_client_work_handler()`
and its helper functions, which run only on `bt_workq`.

The `sdp_client_work_handler()` function iterates through all SDP
sessions after each request submission and performs one of the
following workflow:
- If a disconnection is in progress (`SDP_CLIENT_DISCONNECTING`),
  skip the session;
- If the channel is connected but idle (`SDP_CLIENT_CONNECTED`, with
  no active parameter, it means the `session->param` is `NULL`), resume
  iterating through pending requests;
- If the channel is disconnected (`SDP_CLIENT_DISCONNECTED`) and there
  are pending requests, start a new L2CAP session;
- If the backend ACL connection is no longer active, clear
  `reqs_pending` using `UUID_NOT_RESOLVED` and reset the session.

SDP Client session lifecycle changes:
- `SDP_CLIENT_RELEASED` has been removed; `SDP_CLIENT_DISCONNECTED` is
  used to cover the same "not connected" state. The L2CAP `.released`
  channel ops has also been removed because restarting after
  disconnection is now driven by `sdp_client_work_handler()` instead
  of the `.released` callback. Also, since the `sdp_client_discover()`
  function requests an accept buffer, the L2CAP `.alloc_buf` channel
  ops is no longer needed to simplify the process and avoid potential
  `session->param` overwriting issues.
- A `BT_CONN_CB.disconnected` callback has been added to monitor ACL
  disconnection events. When the ACL connection itself is disconnected,
  all pending requests are cleared and the session is reset (previously
  handled indirectly via `reqs_next` and `sdp_client_released()`).
- Take/release ACL conn reference by the function `bt_sdp_discover()`.
  when adding a request to the `queue reqs_pending`, `bt_sdp_discover()`
  takes the reference of the ACL connection and releases the reference
  after the request is dequeued (cleared by processing of pending
  request, `bt_sdp_discover_cancel()`, or when the ACL connection is
  closed).
- Handle receiving buffer allocation failures without disconnecting the
  session. Notify the SDP discovery result with the `NULL` response
  buffer if the receive buffer allocation failed. And go to the next SDP
  discovery procedure instead of disconnecting the session.
- Use the client worker to trigger the next SDP discovery procedure
  to avoid recursive calls in the functions `sdp_client_discover()` and
  `sdp_client_params_iterator()`.

Updated API doxygen comments for `bt_sdp_discover()` and
`bt_sdp_discover_cancel()` to reflect the new return semantics:
`bt_sdp_discover()` always returns 0 after the request is enqueued,
and the actual success/failure of the discovery is reported later via
`params->func()`.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-09-10 12:18:37 +02:00
Zhijie Zhong
06bf600ddd Bluetooth: conn: drop the unused user data on the fragment pool
The ACL fragment pool declares CONFIG_BT_CONN_TX_USER_DATA_SIZE bytes of
user data that nothing reads. The requirement came from bt_buf_set_type()
and went away with 26d97164be, so the TODO next to it is stale.

Size it zero and keep the view metadata in the side table: an HCI driver
may use a sent fragment's user data, so metadata that frag_destroy()
dereferences does not belong there.

Signed-off-by: Zhijie Zhong <zhongzhijie1@xiaomi.com>
Assisted-by: Kiro:claude-opus-5
2026-09-10 12:17:11 +02:00
Sylvio Alves
0d8201a50f bluetooth: host: name the esp32c5 and esp32c61 hw variants
The espressif hardware variant table stopped at the esp32h2,
so the two ids defined after it were printed as "unknown".
Add both names.

Signed-off-by: Sylvio Alves <sylvio.alves@espressif.com>
2026-09-09 18:14:06 -04:00
Zhijie Zhong
7906aaef02 Bluetooth: SMP: make the CTKD directions configurable
Cross-Transport Key Derivation is unconditional today. With
CONFIG_BT_CLASSIC enabled, Secure Connections pairing over LE always
asks for a derived BR/EDR link key, and the Security Manager over
BR/EDR always accepts deriving the LE LTK from the link key. A device
that must not end up with a bond on the other transport as a side
effect of pairing has no way to say so. Both decisions are device
global: the responder negotiates the key distribution before
bt_conn_set_security() is ever reached, and the fixed channel mask is
built during ACL setup, so Kconfig rather than an API.

Add BT_SMP_DERIVE_LTK and BT_SMP_DERIVE_LK, both default y, so
behaviour is unchanged unless a build opts out.

Without BT_SMP_DERIVE_LK, LINK_DIST expands to 0. That keeps the
negotiated key distribution and what goes on air consistent in both
roles without touching the PDU construction sites, and
ltk_derive_link_key_allowed() refuses the derivation as well.

Without BT_SMP_DERIVE_LTK, smp_br_pairing_allowed() refuses the
procedure and the BR/EDR Security Manager fixed channel is left out of
the L2CAP information response, so a peer does not start one that would
then be rejected. The channel stays registered, so a Pairing Request
that arrives anyway still gets the 0x0E failure.

Signed-off-by: Zhijie Zhong <zhongzhijie1@xiaomi.com>
Assisted-by: Kiro:claude-opus-5
2026-09-09 18:13:56 -04:00
Johan Hedberg
7bb94f0fa1 Bluetooth: host: Use the HCI packet helpers for commands
Build the HCI command packet prefix in bt_hci_cmd_send() with
bt_hci_pkt_push_cmd_hdr(), and decode Command Complete and Command
Status events in hci_cmd_complete() and hci_cmd_status() with the
corresponding pull helpers, instead of open-coding the same encoding
and decoding.

Besides removing the duplication, this exercises the helpers with the
Host's own command traffic, and it settles two edge cases. A Command
Complete whose return parameters lack the status they start with had
that status read from past the end of the event; the helper now reports
it with BT_HCI_ERR_UNSPECIFIED as the status, so the command fails and
its sender gets an error instead of the command timeout, while
Num_HCI_Command_Packets is still honoured and the command flow keeps
going. The Command Complete event with opcode 0x0000 (a
Num_HCI_Command_Packets update without return parameters) no longer has
a status byte read from past its parameters either.

bt_hci_cmd_send() now also releases the buffer when the header cannot
be pushed, as it does on its other failure paths; before, a buffer
rejected for insufficient headroom stayed referenced.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-09 10:38:37 -04:00
Johan Hedberg
8148680ac2 Bluetooth: Add HCI packet helpers
Add hci_pkt.h, stateless helpers for framing HCI command packets and
parsing the events that carry command responses, operating on
net_buf_simple buffers and on packet bytes, implemented in
subsys/bluetooth/common and built into every Bluetooth build (the
library is static, so unused helpers cost nothing).

The helpers are independent of the Bluetooth Host and of the HCI driver
interface, and usable in any build type. The intended users are the
Host itself and HCI drivers that need to exchange HCI commands with the
controller over their own transport, typically for vendor-specific
controller initialization. Today such drivers either call Host command
APIs like bt_hci_cmd_send_sync(), which are unavailable in
controller-only builds, or duplicate the command construction with raw
buffers.

The helpers keep the Host's encoding conventions: parameters are built
and decoded with the packed structures of hci_types.h and the
net_buf_simple API, the encoded length is the buffer length, and the
header push derives the parameter length from it. BT_HCI_PKT_CMD_DEFINE()
provides a command buffer with headroom for the packet prefix reserved.
A Command Complete for a command whose return parameters lack the
status they start with is reported as -ENODATA with the rest decoded
and BT_HCI_ERR_UNSPECIFIED as the status, so that callers can fail the
command instead of guessing.

Add a unit test covering framing and parsing, including the Command
Complete event with opcode 0x0000, which carries no return parameters,
the status-less Command Complete and malformed events, building the
implementation file directly so that it stays independent of the
Bluetooth stack, plus the documentation page and release notes entry.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-09 10:38:37 -04:00
Johan Hedberg
7f44a96268 Bluetooth: AVDTP: Do not block the workqueue on buffer allocation
The signalling response PDUs are allocated with K_FOREVER from the
AVDTP buffer pool. The command handlers run in the Bluetooth
workqueue, which is also the context that runs the AVDTP TX processing
that returns the buffers to that same pool, so waiting for a buffer
there cannot make progress. Most of the handlers wait with the
endpoint lock held, which additionally blocks any other user of the
endpoint.

The same applies to the reassembly buffer allocated on the receive
path, which already has an unreachable allocation failure path.

Allocate both without waiting. All the response allocations already
handle the failure by not responding, leaving the remote side to time
out, which is preferable to blocking the whole host.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-09 10:38:10 -04:00
Emil Gydesen
61e50d01a6 Bluetooth: BAP: Shell: Allow 0 for bap stats
Rename the command to `bap stats` instead of `bap bap_stats`
and allow the value 0 to disable reporting.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-08 19:18:05 -04:00
Emil Gydesen
1ff54a9bc1 Bluetooth: BAP: Shell: Change LC3 priority
Change the LC3 priority to be a higher value (lower priority).
The purpose of this is to prioritize the USB thread higher
as that is more sensitive to time than the LC3 thread.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-08 19:17:59 -04:00
Emil Gydesen
2a8d4eabdb Bluetooth: MCS: Clear pending notifications on unsub
If the client removes its subscription to any of the MCS
characteristics at any time, the pending appropriate flags
are now being cleared.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-08 16:06:52 +02:00
Jamie McCrae
f2a1d086ae bluetooth: host: kconfig: Add missing deprecation text
Adds a missing [DEPRECATED] tag to the Kconfig prompt

Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
2026-09-08 16:04:16 +02:00
Emil Gydesen
00e55c5c75 Revert "Bluetooth: Host: Fix RPA expire issues for adv"
This reverts commit e55eaf1312ea55f1ad702f35e15a9935814482d0.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-08 16:04:02 +02:00
Alex Ciascai
5c25ce6230 Bluetooth: MPL: add Media Player Name setter API
Add a proper Media Proxy API for setting the local
Media Player Name and expose it through the media
player callback interface.

Signed-off-by: Alex Ciascai <alexandru.ciascai@nordicsemi.no>
2026-09-08 11:12:35 +02:00
Emil Gydesen
2548b7b100 Bluetooth: Host: Set adv->options only on success
If the parameters failed to be set, we should not modify
the advertising set's options.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-07 21:07:36 -04:00
Emil Gydesen
05d6a3dbb6 Bluetooth: ISO: Make bt_iso_chan_state_str public
Make the existing function to return a string representation
of an ISO state public.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-07 17:54:48 +02:00
Emil Gydesen
60ad721a83 Bluetooth: ISO: Add function to get bt_iso_chan from bt_conn
It is possible to get the ISO bt_conn object from e.g.
bt_conn_foreach but it is pretty useless without
being able to get the `bt_iso_chan` that it is linked to.

Added function to get the bt_iso_chan object from the
bt_conn ISO object.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-07 17:54:48 +02:00
Yuheng Li
bb2dd53f7a Bluetooth: Classic: AVDTP: return NULL from avdtp_get_sep for unknown SEID
SYS_SLIST_FOR_EACH_CONTAINER leaves the loop variable pointing at the
last node when the scan comes up empty, so avdtp_get_sep() returned that
node for a SEID the endpoint never registered. Every command handler
(get caps, set config, open, start, suspend, abort, close, ...) branches
on sep == NULL to answer Reject, so an unknown SEID was instead treated
as targeting the wrong SEP: a Close carrying SEID 62 was answered against
the only registered SEP (id 8, streaming) instead of being rejected with
BAD_ACP_SEID, and PTS AVDTP/SNK/ACP/SIG/SMG/BI-23-C timed out waiting for
the Reject.

Track the match explicitly and return NULL when none is found.

Signed-off-by: Yuheng Li <liyuheng@xiaomi.com>
2026-09-04 13:42:39 -04:00
Emil Gydesen
915d63e193 Bluetooth: ASCS: Add cp_rsp_buf per client
Modify the buffer for control point responses to exist per client.
This is a requirement to later support handling the control point
notifications in the system workqueue, which enables support for
proper handling of notifications in case that we run out of ATT
buffers, as we need to store the response until then, and that we
may have multiple clients connected.

CONFIG_BT_MAX_PAIRED was chosen over CONFIG_BT_MAX_CONN as we only
care about paired (encrypted) connections, and this may scale
better at the cost of doing lookups on address instead of e.g.
bt_conn_index.

The unit tests for ASCS are updated to pass without any
functional changes.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-04 13:41:33 -04:00
Emil Gydesen
ac1141fbc9 Bluetooth: audio: release VOCS and AICS client instances on alloc failure
Fixes issue with VCP and MICP init failures not cleaning
up allocated AICS and VOCS instances.

Assisted-by: copilot-swe-agent
Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-04 13:41:29 -04:00
Alex Ciascai
a8aac60612 bluetooth: MPL: notify track postion when stop playback
Notify Track Position when resetting it to zero while
playback is active. Stop resets the position before
changing the Media State to Paused, which previously
supressed the Track Position notification.

Signed-off-by: Alex Ciascai <alexandru.ciascai@nordicsemi.no>
2026-09-04 06:23:40 -04:00
Cheng Chang
f8eeda1891 bluetooth: host: bip: fix DELETE_IMAGE_FUNC_BIT macro definition
The DELETE_IMAGE_FUNC_BIT macro was incorrectly defined as
BT_BIP_SUPP_FUNC_REMOTE_DISPLAY instead of BT_BIP_SUPP_FUNC_DELETE_IMAGE.
This caused the wrong function bit to be used for the delete image
operation.

Signed-off-by: Cheng Chang <cheng.chang@nxp.com>
2026-09-04 06:23:32 -04:00
Johan Hedberg
3bdda744f9 Bluetooth: Classic: SDP: Bound the client AttributeIDList length
sdp_client_get_attribute_id_list_len() summed the encoded size of the
attribute ID list in a uint16_t while iterating a size_t count. With
enough ranges the sum wrapped, the tailroom check in the SA and SSA
request builders passed on the wrapped value, and
sdp_client_add_attribute_id() then encoded every range into the request
PDU, writing past the end of the net_buf.

Accumulate in size_t, pass the measured length to the encoder instead of
recomputing it there, and reject lists that cannot fit in a request PDU
in bt_sdp_discover() with -EINVAL. The bound is derived from the request
with the largest fixed-size parameters, an SSA request with a 128-bit
UUID and a full-size continuation state, so a list accepted by
bt_sdp_discover() fits every request of the transaction.

Document the limit in the API.

Fixes #117579

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-04 06:21:36 -04:00
Lyle Zhu
8855ac4626 bluetooth: classic: bip: add required app param tag validation
The `required_appl_param_tag_id` bitmask in `struct bip_function` was
unused; both `bip_server_get_req_cb()` and `bip_client_get_req_cb()`
contained a placeholder comment noting that application parameter tag
IDs were not checked.

Add `has_required_ap_tag_id()`, which iterates every set bit in the
bitmask via `__builtin_ctz()` and verifies that the corresponding
application parameter is present in the request buffer using
`bt_obex_has_app_param()`. Invoke this helper in both the server and
client request paths (GET and PUT) so BIP operations that require
specific application parameters are correctly rejected when those
parameters are absent, rather than being silently passed through.

Also rename the struct field from `required_appl_param_tag_id` to
`required_ap_tag_id` to align with the shorter naming convention
used elsewhere in the file.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-09-04 06:19:43 -04:00
Lyle Zhu
b77e8dc200 bluetooth: classic: Refactor OBEX authentication to be reusable
Move OBEX authentication functions from PBAP to the OBEX layer to make
them available for other OBEX-based profiles. The authentication
implementation remains unchanged but is now part of the generic OBEX
API rather than being PBAP-specific.

Move `bt_pbap_calculate_nonce()` to `bt_obex_generate_nonce()`. Move
`bt_pbap_calculate_rsp_digest()` to
`bt_obex_calculate_request_digest()`. Move
`bt_pbap_verify_authentication()` to `bt_obex_verify_auth_response()`.

The refactoring allows other OBEX-based profiles to use the same
authentication mechanism without code duplication.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-09-04 06:18:31 -04:00