Commit graph zephyr/subsys/bluetooth
Author SHA1 Message Date
Zhijie Zhong
8915744d62 Bluetooth: ATT: Stop Execute Write on the first error
When an attribute write failed during an Execute Write the server sent
an Error Response but kept walking the prepare queue. The next handle
was still written, and because the loop reassigns err, a later success
also produced an Execute Write Response, leaving two responses for one
request. Clear the queue and stop at the first failing handle, as Core
v6.3 Vol 3 Part F 3.4.6.3 requires.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Zhijie Zhong <zhongzhijie1@xiaomi.com>
2026-10-16 15:50:40 -05:00
Zhijie Zhong
bab6a4f586 Bluetooth: ATT: Discard the prepare queue on cancel
An Execute Write Request with the flags parameter set to 0x00 asks the
server to drop everything the client has queued. The server instead ran
the same reassembly as a real execute, so a queue whose offsets are not
contiguous, or whose reassembled value is too long, answered the cancel
with an Error Response. Core v6.3 Vol 3 Part F 3.4.6.3 requires the
values to be discarded and an Execute Write Response to be sent.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Zhijie Zhong <zhongzhijie1@xiaomi.com>
2026-10-16 15:50:40 -05:00
Johan Hedberg
86b6deaa4f Bluetooth: Host: Fix connections surviving an identity delete or reset
bt_id_delete() and bt_id_reset() are documented to disconnect any
connection created using the identity, but they only call bt_unpair(),
which disconnects the peers that have keys. A connection that never
paired stayed up with a handle that no longer refers to its identity.
Disconnect the established LE connections that use the handle after the
unpair step. As a bug fix of a stable API, this increments the bt_gap
API version to 1.1.2.

Two cases remain as before: a connection whose Connection Complete
event has been received but not processed yet is not found, and a
pairing in progress may still complete, and store keys for the handle,
before the link is down.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-16 15:13:43 -05:00
Lyle Zhu
8ee3f9a3d5 bluetooth: host: prevent blocking on bt work queue thread
The `bt_conn_create_pdu_timeout()` function already prevents blocking
when called from `k_sys_work_q` thread by forcing the timeout to
`K_NO_WAIT`. However, it did not account for calls from `bt_workq`
thread, which will lead to a deadlock in the `bt_workq` thread if
the timeout is `K_FOREVER`, preventing the Bluetooth host stack from
functioning correctly. Consider a deadlock scenario:
In the function `l2cap_br_disconn_req()` runs on `bt_workq` and calls
`bt_l2cap_br_chan_del()`, which synchronously invokes
`ops->disconnected()`; if a profile initiates a l2cap channel connect
within this callback, `bt_l2cap_br_chan_connect()` is entered again
within the same `bt_workq` stack frame. At this point, if `br_sig_pool`
is exhausted, `bt_workq` becomes indefinitely blocked, causing all RX
processing to stall. In the worst-case scenario, it remains blocked
forever if there is only one net buffer in `br_sig_pool`.

Add `bt_is_work_thread()` helper function to check whether it is
executing in the `bt_workq` thread context.

Add the check to detect when running on `bt_workq` thread by
calling the helper `bt_is_work_thread()` while the timeout is set to
`K_FOREVER` in the function `bt_conn_create_pdu_timeout()` and force
`K_NO_WAIT` in that case as well.

Assisted-by: Claude:claude-sonnet-5
Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-10-16 15:13:19 -05:00
Arkadiusz Grzelka
0e71a62dde Bluetooth: PACS: retry a notification that failed with -ENOMEM
pac_notify() returned 0 whatever pacs_gatt_notify() returned, so
notify_cb() cleared the changed flag after a failed notification. When
no ATT TX buffer is free, bt_gatt_notify_cb() fails with -ENOMEM and the
client never receives the changed PAC.

Return the error and retry on -ENOMEM, as HAS and VCP do, and on
-EAGAIN, which a change-unaware client gets, as MCS does. Retry a PAC
notification on -EBUSY too: pac_notify() returns it when a PAC read
holds the read buffer. Log any other error without a retry. Truncate a
value longer than the ATT MTU allows. Add a BabbleSim test.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Arkadiusz Grzelka <devitwise@gmail.com>
2026-10-16 13:15:18 +02:00
Johan Hedberg
42b48e4787 Bluetooth: Controller: Initialize the advertising random delay
ticker_update_rand() asks for four random bytes in interrupt context
and ignores how many it got. The pool for that context can have fewer:
the first request after advertising has started got one byte on
nrf52_bsim. The other three bytes of the delay were whatever the stack
had, so the time of the second advertising event depended on the image
and on nothing else, and a simulation gave other results after an
unrelated change.

Start from zero, which leaves a delay of fewer random bits in that
case.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-15 16:47:54 +02:00
Johan Hedberg
927dcaaf53 Bluetooth: Controller: Do not start a CONNECT_IND past the scan window
An initiator checks that the CONNECT_IND for an ADV_IND will be over
before its time slot ends. The scan window is closed by a ticker
EVENT_OVERHEAD_START_US before that, and the radio is disabled there:
a CONNECT_IND that the check let through could be cut off in the
middle. The connection has been given to the ULL by then, so the Host
got an LE Connection Complete event for a connection that the peer
never saw and that was lost six connection events later.

Check against the time at which the window is closed as well. An
ADV_IND that comes too late for that is left unanswered, as one that
comes too late for the time slot is.

It took a scan window that is shorter than the scan interval, and an
ADV_IND in the last few hundred microseconds of what was answered.

Tested with tests/bsim/bluetooth/host/central on nrf52_bsim, with the
advertising delay forced to values that put the ADV_IND around that
time: the CONNECT_IND is sent in full or not at all, where it was cut
off at the end of the window before. Not run on hardware.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-15 16:47:54 +02:00
Aleksandr Khromykh
84d24de3c1 bluetooth: mesh: dfd_srv: record self-target apply outcome
The self-target applies its image after the Confirm Update On Target
Nodes procedure, which therefore never sets its Retrieved Update Phase
to Apply Success or Apply Failed (MshDFUv1.0 Section 7.1.2.9). After an
in-place apply its receiver entry kept reporting Applying Update in
Firmware Distribution Receivers Status, also once the distribution had
completed or failed.

Set the entry to Apply Success when the local apply completes, and to
Apply Failed when the deferred apply cannot start.

Assisted-by: Claude:claude-opus-5.5
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
2026-10-15 16:39:40 +02:00
Aleksandr Khromykh
5a29ead7fc bluetooth: mesh: blob_cli: exclude skipped targets from broadcasts
A skipped target is never sent to, but it was still counted in
tx.pending, so an acknowledged broadcast that included one only completed
when the retry timer found nothing left to send, one retry interval
later. The Distributor skips its own target during the Transfer step of
a self-update, so every acknowledged BLOB broadcast in the transfer paid
this delay.

Count only the targets that take part in the broadcast. targets_reset()
still counts all active targets, since the transfer-start paths use it to
check that a valid target remains.

A skipped target can still receive a group-addressed message, for example
when the Distributor's own BLOB Transfer Server is subscribed to the
group, and it answers with an error since it expects no transfer. Ignore
such responses when looking the target up, before they can drop it or
change the transfer state, and keep them out of the pending count.

Assisted-by: Claude:claude-opus-5.5
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
2026-10-15 16:38:38 +02:00
Aleksandr Khromykh
fa0af885ef bluetooth: mesh: dfu_cli: send Firmware Update Cancel to skipped targets
The Transfer step skips targets that do not need the transfer, such as a
Firmware Update Server on the client's own node, which verifies the
image without one. Cancelling during the transfer left the skip flags
set, so the Cancel broadcast never reached those targets and they stayed
in Verification Succeeded.

Clear the skip flags before broadcasting Firmware Update Cancel.

Assisted-by: Claude:claude-opus-5.5
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
2026-10-15 16:38:06 +02:00
Johan Hedberg
aa0d4a21a5 Bluetooth: Host: Fix PSA keys leaking when ECC operations fail
The work handlers that generate the public key and the DH key put a
volatile key into the PSA key store and destroy it once they are done
with it. When exporting the generated key failed, or the key agreement,
they left without destroying it, and the key kept its slot until
reboot. The small builds have five slots, so a few such failures were
enough to make every later key operation fail.

Destroy the key on those paths as well.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-15 14:18:07 +02:00
Johan Hedberg
1dcd0f23b5 Bluetooth: Host: Fix writing a long command response past the buffer
The response to a command is copied from the event into the command's
own buffer, which is as large as the events that the Host is configured
to receive (CONFIG_BT_BUF_EVT_RX_SIZE, 68 bytes by default). The event
itself arrives in a buffer that takes any Command Complete, up to 255
bytes of parameters, and the copy did not look at the length. A longer
response, to a vendor command for instance, was caught by an assertion
at best and written past the command buffer otherwise.

Fail the command when its response does not fit.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-15 14:17:50 +02:00
Johan Hedberg
c14bdb32b1 Bluetooth: Host: Clear buffer pointers at queue handover
A buffer put into a FIFO or list belongs to the queue from then on, and
the thread or work item on the other side may process and free it
before the call returns. Passing net_buf_take(&buf) clears the caller's
pointer in the same expression, so code added after the handover
cannot use the buffer by mistake.

Convert the insertions in ATT, L2CAP, HCI core, HCI raw and the L2CAP
shell where the put is the last use of the pointer. bt_hci_cmd_send()
still uses its pointer after queueing, to take a command back from a
closed transport, so it stays as it is.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-15 14:17:17 +02:00
Johan Hedberg
2ae5593b9f bluetooth: classic: rfcomm: Fix reading the buffer after queueing it
bt_rfcomm_dlc_send() returns buf->len after it has put the buffer on
the DLC TX queue and scheduled the TX work. That work runs on the
Bluetooth workqueue, on another CPU or as soon as an interrupt preempts
the caller, and hands the buffer to L2CAP, which modifies and later
frees it. The returned byte count is then read from a buffer RFCOMM no
longer owns.

Read the length before queueing the buffer, and clear the pointer at
the handover with net_buf_take().

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-14 13:44:42 +02:00
Johan Hedberg
36b83f07e3 Bluetooth: Controller: Fix the CIS burst counter for burst number 15
The LLL marks the payloads of a burst as done by moving the current
burst number past the burst number, which the 4 bit field can not hold
for the largest burst number of 15. The counter wraps to 0 instead,
and the LLL goes on with the payload numbers of the previous burst.
Widen the field to 5 bits.

Tested for regressions with tests/bsim/bluetooth/ll/cis on nrf52_bsim.
No test with a burst number of 15 is added.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-14 08:44:59 +02:00
Johan Hedberg
c05b3a9b8e Bluetooth: Controller: Fix conn is_abort assert without event deferral
When neither 2M nor Coded PHY is enabled, EVENT_DEFER_MAX is 0 and the
TRX busy iteration maximum is 0 too. The debug assert in the central and
peripheral is_abort callbacks then fails every time a connection event
is cancelled by an overlapping event, e.g. when a connection event with
more data runs into the next connection interval.

Only check the iteration count when deferral is supported.

Tested for regressions with tests/bsim/bluetooth/ll/conn on nrf52_bsim.
No test of a build without the 2M and Coded PHYs is added.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-14 08:44:49 +02:00
Arkadiusz Grzelka
2856edf906 Bluetooth: Controller: Calculate BIG control subevent channel ahead
When a BIG control PDU is pending, isr_rx() calls lll_chan_iso_event()
before starting the radio for the control subevent. The extra work
before radio_tmr_start_us() can make the start late and trip its
LL_ASSERT_ERR().

Calculate the control subevent channel in next_chan_calc_seq() and
next_chan_calc_int(), after the radio start of the last data subevent
is set up. When isr_rx() skips the remaining data subevents, or the last
BIS is not synchronized, isr_rx() still calculates the channel before
the start, as before.

Tested on two nRF5340 Audio DKs with zephyrproject-rtos/zephyr#120919
applied: without this change, a sink following a source that re-creates
its BIG hit the assert within six terminations in both runs.

Assisted-by: Claude:claude-opus-5.5
Signed-off-by: Arkadiusz Grzelka <devitwise@gmail.com>
2026-10-14 08:41:13 +02:00
Arkadiusz Grzelka
3ae8217cf7 Bluetooth: PACS: Fix notify property of Sink and Source PAC
The Sink and Source PAC characteristics set the notify property under
CONFIG_BT_PAC_SNK_LOC_NOTIFIABLE and CONFIG_BT_PAC_SRC_LOC_NOTIFIABLE,
but their CCCD follows CONFIG_BT_PAC_SNK_NOTIFIABLE and
CONFIG_BT_PAC_SRC_NOTIFIABLE.

With only the PAC option set, a client's CCCD write is rejected with
CCC Improper Configuration. With only the location option set, the
property has no CCCD behind it.

Gate the property on the PAC option.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Arkadiusz Grzelka <devitwise@gmail.com>
2026-10-14 08:40:58 +02:00
Aleksandr Khromykh
d86ca41a93 bluetooth: mesh: sequence store rate configuration fix
Commit fixes configuration of the sequence store rate.
KConfig picks up the first met default option.

Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
2026-10-13 17:13:19 +02:00
Johan Hedberg
81be40fd71 Bluetooth: L2CAP: Fix TX stall after 0 initial credits
An LE credit-based connection request or response may carry 0 initial
credits. l2cap_chan_tx_give_credits() still set BT_L2CAP_STATUS_OUT for
such a grant, reporting the channel as sendable. An SDU queued before the
peer granted credits then never went out: l2cap_data_pull() dropped the
channel from the ready list for lack of credits, and the first real grant
found the bit already set and did not add the channel back.

Ignore grants of 0 credits, so that the first real grant sets the bit and
resumes TX.

Fixes #121544

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-13 17:08:02 +02:00
Johan Hedberg
9f4f79b3aa Bluetooth: Host: Fix command left waiting when bt_disable() closes HCI
bt_disable() completes the commands that are still queued when it
closes the HCI transport, but not the one that has been handed to the
driver. A command that another thread sends while bt_disable() waits
for the controller to be reset is transmitted once the controller has
responded to the reset. The transport is then closed before the
response to the command arrives, and its sender waits for the command
timeout, which ends in an assertion.

Complete the command in flight with an error once the transport has
been closed, since nothing can respond to it any more.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-12 23:26:05 +02:00
Johan Hedberg
12881504fd Bluetooth: Host: Fix deadlock when the driver fails to send data
When send_buf() fails, typically because the HCI driver failed to send
the packet, the TX processor gives the connection up and disconnects
it. bt_conn_disconnect() waits for its HCI command, and the TX
processor is what transmits commands: with
CONFIG_BT_TX_PROCESSOR_THREAD, the default, it waits for a command
that it cannot send, holding the host lock, until the command times
out and the Host asserts.

Leave the disconnecting to the Bluetooth workqueue, which can wait for
the command. The connection is flagged for it, and the TX processor
passes a flagged connection over for as long as it is connected, so
that nothing more is sent on it while it is being disconnected. A
connection that is still connected after that, because the command
failed, loses the flag and goes on sending. A disconnected one loses
it too, as a central CIS keeps its object for its next connection.

A BIS is left alone: it cannot be disconnected on its own, and
terminating its BIG would take the other BISes down too. What failed
to go out on it is lost, and sending goes on.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-12 23:26:05 +02:00
Johan Hedberg
861b8a6bcc Bluetooth: Host: Fix deadlock when data is sent during bt_disable()
bt_disable() clears BT_DEV_READY and then waits for the controller to
be reset, with the connections still in place since
commit 78ea662dfe ("Bluetooth: Host: Reset controller before conn
teardown in bt_disable()"). Data sent meanwhile is dropped by
send_buf(), the Host being no longer ready, which the TX processor
takes for a fatal error and answers by disconnecting the connection.
That is a synchronous HCI command issued from the thread that
transmits commands, so it waits for a command that it cannot send, and
does so holding the host lock. With CONFIG_BT_SMP bt_disable() takes
that lock once the controller has been reset and never gets to purge
the command queue, which would have ended the wait: both threads stay
blocked until the command times out and the Host asserts.

Seen with auto-pts, which powers the tester off while a broadcast
source is streaming.

Have the TX processor pass over the connections while the Host is not
ready, before it takes anything from them. What is queued stays where
it is until bt_disable() tears the connections down, as for any
connection that goes away with data queued, or until the Host is ready
again after a failed reset, which now restarts the TX processor.

That replaces the check in send_buf(), which came too late: the upper
layer had by then accounted for the data as handed over, and the
failure was reported to a callback running in the TX processor.
bt_disable() now clears BT_DEV_READY under the host lock, which the TX
processor holds for a whole pass, so that the flag does not change
under a pass that another thread is in the middle of.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-12 23:26:05 +02:00
Zhijie Zhong
840bde98df Bluetooth: SMP: clear LinkKey distribution bits after legacy pairing
bt_smp_encrypt_change() clears BT_SMP_DIST_LINK_KEY inside its Secure
Connections branch, and the comment there already says these bits double
as the pairing-finished indicator. On the legacy path the bit is never
cleared, so with CONFIG_BT_CLASSIC=y and CONFIG_BT_SMP_SC_PAIR_ONLY=n,
against a peer that sets LinkKey while Secure Connections is not
selected, local_dist keeps BT_SMP_DIST_LINK_KEY after key distribution
has finished. The `if (!smp->local_dist && !smp->remote_dist)` checks
never become true, smp_pairing_complete() is never called, and the SMP
timeout eventually reports the pairing as failed even though the link is
encrypted and the keys were exchanged.

Move the clearing out of the Secure Connections branch, leaving only
SMP_FLAG_DERIVE_LK inside it. A link key can only be derived from a
Secure Connections LTK, so the bit has nothing to signal on the legacy
path. Nothing on air changes.

Signed-off-by: Zhijie Zhong <zhongzhijie1@xiaomi.com>
Assisted-by: Kiro:claude-opus-5
2026-10-10 12:59:46 +02:00
Johan Hedberg
83d85095c4 Bluetooth: Classic: L2CAP: Fix PSM left on connless buffer on failure
bt_l2cap_br_connless_send() adds the PSM to the buffer before sending,
and returned the buffer to the caller with the PSM still added when
sending failed, although the caller keeps the buffer on error.

Remove the PSM again when sending fails, and document that the caller
gets the buffer back unchanged.

Tested with tests/bluetooth/host_l2cap_br_send on native_sim.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-10 06:52:47 +02:00
Johan Hedberg
4218544d7e Bluetooth: Classic: L2CAP: Fix header left on buffer after failed send
In basic mode, bt_l2cap_br_send_cb() added the L2CAP header before
checking that the buffer's user data has room for the send callback.
When that check failed, the caller, who keeps the buffer on error, got
it back with the header added, for example from bt_l2cap_chan_send().

Check the user data before adding the header.

Tested with tests/bluetooth/host_l2cap_br_send on native_sim.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-10 06:52:47 +02:00
Ludvig Jordet
3f878df514 Bluetooth: Mesh: Decouple RPL store timeout from storage mode
Solve two issues:

  * Other storage modes than CONFIG_BT_MESH_RPL_STORAGE_MODE_SETTINGS
    could not reuse the pending store scheduler used by the settings
    backend.
  * The store timing of SRPL, which is always stored through the
    Settings subsystem, would use CONFIG_BT_MESH_RPL_STORE_TIMEOUT if
    RPL was also stored in settings via
    CONFIG_BT_MESH_RPL_STORAGE_MODE_SETTINGS, but not if another storage
    mode was used for RPL.

Decouple the store scheduler from the Settings subsystem and the
chosen RPL storage mode, so the scheduler code and the separate
CONFIG_BT_MESH_RPL_STORE_TIMEOUT option are

a) Available regardless of storage mode, and always used for SRPL when
set and
b) Available without CONFIG_BT_SETTINGS, in case an RPL storage mode
does not need Settings but would like the scheduling.

Also change the BT_MESH_SETTINGS_RPL_RESET_PENDING to always store
immediately. This was in practice already the case whenever settings was
used, since this was only ever scheduled right before a second NO_WAIT
configuration was scheduled (like net key, IV, etc.). Now this behavior
is consistent both with and without BT_SETTINGS enabled.

Assisted-by: Copilot:claude-sonnet-5.5
Signed-off-by: Ludvig Jordet <ludvig.jordet@nordicsemi.no>
2026-10-09 16:58:06 +02:00
Vandra-Meyer Akos
132586a433 Bluetooth: Host: Fail bt_enable() when the Controller never responds
When the Controller is missing, unpowered or does not run HCI, the first
command that bt_enable() sends times out, and the Host asserts:

  ASSERTION FAIL [err == 0] @ .../bluetooth/host/hci_core.c:572
  	Controller unresponsive, command opcode 0x0c03 timeout with err -11

An application cannot handle this, so Bluetooth cannot be optional at run
time, for example on a board with the Controller on a plug-in module.

The Host now records whether the Controller has sent a packet while
bt_enable() runs. When bt_hci_cmd_send_sync() times out waiting for a
response during bt_enable(), and the Controller has not sent anything,
the Host closes the transport, as bt_disable() does, and bt_enable() fails
with -ETIMEDOUT. The close stops a late response from completing a
command whose sender has returned. Because the transport is closed,
bt_enable() can be called again. This also applies to a command that the
TX processor thread never sends, such as HCI Reset with CONFIG_BT_WAIT_NOP
when no NOP arrives: the close completes it.

The Host still asserts when a command times out after the Controller has
responded. Such a Controller is present but faulty, and once packets have
come in, a clean failure needs the RX teardown that bt_disable() does. The
record is kept across HCI Reset, so a Controller that answers HCI Reset
and then stops also causes the assert. The Host also asserts when the
driver cannot close the transport, and, without
CONFIG_BT_TX_PROCESSOR_THREAD, when a command sent from the system work
queue cannot be sent.

The transport must not be closed while the driver is in send(), and a
send() can outlast the command timeout. The TX processor holds the host
lock during send(), so the Host takes the lock without waiting before it
closes the transport. When the lock is not free, the Host asserts.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Vandra-Meyer Akos <akos@lvgl.io>
2026-10-09 16:55:07 +02:00
Ryan Erickson
1783873470 Bluetooth: fix format specifiers for size_t/ssize_t
Several LOG_ and __ASSERT format strings use %u or %d for arguments
that are size_t or ssize_t, which produces -Wformat= warnings on
LP64 targets (e.g. AArch64). Switch to %zu / %zd.

* subsys/bluetooth/host/classic/sdp.c: three format strings that
  compare against sizeof() or use ssize_t counters.

* drivers/bluetooth/hci/hci_nxp_setup.c: matching V1 and V3
  "Out of sending buffer range" messages (both LOG_ERR and the
  neighbouring __ASSERT that uses the same string).

No functional change; eliminates 5 build warnings on
nitrogen93_smarc/mimx9352/a55/nx611.

Assisted-by: Claude:claude-opus-4.7
Signed-off-by: Ryan Erickson <ryan.erickson@ezurio.com>
2026-10-09 16:49:48 +02:00
Axel Le Bourhis
6b1dd1d959 bluetooth: mesh: fix BLOB flash double-program on ECC flash
The explicit-erase path in wr_chunk() programs a shared write block
twice when a chunk boundary is not write-block aligned, which corrupts
the ECC syndrome on flash that allows only one program per erase (e.g.
some NXP MCXW SoCs) and faults on the next read. Commit a9ad258c84
fixed only the non-erase path.

Add opt-in CONFIG_BT_MESH_BLOB_IO_FLASH_BLOCK_CACHE (default n) that
buffers a block in RAM and, on the chunk that completes the block,
programs it write-block-aligned once, so no write block is programmed
twice. The flush runs in wr() rather than block_end so a failed
flash_area_write is returned to the server (the chunk stays missing and
the client retries) and a sticky error prevents any later re-program;
an unaligned init offset is rejected up front. Default builds are
unchanged.

Signed-off-by: Axel Le Bourhis <axel.lebourhis@nxp.com>
2026-10-08 15:07:35 +02:00
Szymon Janc
478f9bfbf4 Bluetooth: Host: Fix advertising with NRPA with privacy enabled
With privacy enabled random address is set via
bt_id_set_adv_private_addr() which has a shortcut for NRPA
when BT_LE_ADV_OPT_USE_NRPA flag is set. Previously advertising
instance options were set at the very beginning of configuration
and this was working correctly. But now new options are set only
after configuration was successful and this resulted in RPA being
set by bt_id_set_adv_private_addr() since options were not yet
updated.

Pass new options to bt_id_set_adv_private_addr() directly allowing
it to take proper actions. This is also consistent with current design
of bt_id_set_adv_own_addr().

This is a regression after
commit 2548b7b100 ("Bluetooth: Host: Set adv->options only on success")

This is affecting GAP/BROB/BCST/BV-04-C qualification test case.

Signed-off-by: Szymon Janc <szymon.janc@codecoup.pl>
2026-10-08 10:45:37 +02:00
Hugo Zamith
2a30fddadb Bluetooth: Controller: wrap long PHY_LEGACY call sites
Break radio_switch_complete_and_tx lines that exceed the 100-column
checkpatch limit after expanding tabs.

Signed-off-by: Hugo Zamith <hhzamith@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-07 09:36:57 +02:00
Hugo Zamith
94e79e65a4 Bluetooth: Controller: use PHY_LEGACY and PHY_FLAGS macros
Replace remaining magic 0/0U phy and flag arguments in Nordic and
OpenISA LLL radio setup/timing helpers with PHY_LEGACY and
PHY_FLAGS_UNUSED.

Coded PHY S2/S8 call sites already use PHY_FLAGS_S2/S8; this finishes
the cleanup for legacy paths so radio_phy_set,
radio_switch_complete_and_tx, and delay helpers consistently use the
named macros from pdu.h.

Fixes #37458

Signed-off-by: Hugo Zamith <hhzamith@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-07 09:36:57 +02:00
Pisit Sawangvonganan
29ec38a2e8 Bluetooth: MPL: fix typo
Utilize a code spell-checking tool to scan for and correct spelling errors
in all files within:
- `subsys/bluetooth/audio`

Assisted-by: Claude:claude-sonnet-5-5 codespell
Signed-off-by: Pisit Sawangvonganan <pisit@ndrsolution.com>
2026-10-06 22:40:51 +02:00
Sylvio Alves
4b97fc46f3 bluetooth: host: fix lost deferred resolving list removals
When the resolving list cannot be changed, bt_id_del() defers the
removal by flagging the keys, but bt_keys_clear() wipes the keys
right after, so the removal is lost. The stale entry keeps
counting in rl_entries and can force the switch to host-side
resolution, after which no bonded peer using an RPA passes the
filter accept list. The removal has been lost this way since
commit e25d925242 ("Bluetooth: Defer RL update if there's an
ongoing connection").

Queue the peer identity address instead, so the removal survives
the keys being cleared or reused. bt_id_add() carries out the
queued removals before adding, so a peer added again after the
deferring condition ended is not removed afterwards, and
rebuilding the list after host-side resolution drops the queued
removals it no longer holds. The limited scan flag is dropped as
the removal is carried out right away in that case.

Assisted-by: Claude:opus-5
Signed-off-by: Sylvio Alves <sylvio.alves@espressif.com>
2026-10-06 10:04:59 +02:00
Johan Hedberg
13f3fc65aa Bluetooth: Host: Fix the help text of BT_RX_STACK_SIZE
The help text calls the option the stack size of the receiving thread
and says that all callbacks to the application come from that thread.
Neither holds. Since commit 9ef7acd7d7 ("Bluetooth: Host: Add a
general purpose Bluetooth workqueue") the stack is that of the Bluetooth
workqueue, which also runs the deferred work of the Host, and the
documented callback contract promises no thread: some callbacks run in
the thread that calls the API which triggers them.

Say what the option sizes.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-10-06 10:03:39 +02:00
Aleksandr Khromykh
272d92d21d bluetooth: mesh: handle out-of-range First Index in Receivers Get
Clamp the entry count in handle_receivers_get() so a First Index past
the end of the receivers list yields a Receivers List with the list
field omitted, instead of a count computed from a negative difference,
as required by the Mesh DFU Model specification, section 6.2.3.5.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
2026-10-06 07:29:33 +02:00
Arkadiusz Grzelka
a709b6a5c6 Bluetooth: Host: keys: Fix re-adding IRKs on a repeated settings_load()
keys_commit() marks every bond with an IRK BT_KEYS_ID_PENDING_ADD on
each settings_load(), including one whose IRK is already in the
resolving list. The next advertising or scan start then calls
bt_id_add() for it again.

A Controller that rejects duplicates fails LE Add Device To Resolving
List with 0x12. With host address resolution, rl_entries counts the bond
twice.

Skip bonds that already have BT_KEYS_ID_ADDED set.

Fixes #120829

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Arkadiusz Grzelka <devitwise@gmail.com>
2026-10-06 07:25:11 +02:00
Sylvio Alves
e8cf062c59 bluetooth: host: shell: fix build with iso sync receiver only
With BT_ISO_SYNC_RECEIVER enabled but no unicast role, the shell
failed to build: the big-sync command took its RX QoS from the
unicast iso_rx_qos, and connection_info compared against the
unicast iso_chan. Give the sync receiver its own RX QoS, since
the host only requires it to be non-NULL, compare against
iso_chan only when unicast is enabled, and declare iso_chan
under the same guard as its definition.

Assisted-by: Claude:opus-5
Signed-off-by: Sylvio Alves <sylvio.alves@espressif.com>
2026-10-06 07:22:49 +02:00
Emil Gydesen
a4e5cbf41b Bluetooth: Audio: Use bt_att_get_max_ntf_size
Use the public bt_att_get_max_ntf_size function to get the
current notification size, rather than using the
LE Audio specific one.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-30 12:42:59 +02:00
Emil Gydesen
4ef942f53c Bluetooth: GATT: Shell: Add checks for notification lenghts
Add checks for notification lenghts in the GATT shell, and
truncate long notifications.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-30 12:42:59 +02:00
Emil Gydesen
e247dd1359 Bluetooth: Host: ATT: add public max notification size API
Applications that send notifications larger than the ATT_MTU have to
truncate them to ATT_MTU - 3, but the 3-octet ATT_HANDLE_VALUE_NTF
header size was only available in the internal ATT header, so every
user had to define it again.

Add bt_att_get_max_notify_size() and bt_att_get_max_indicate_size()
to the public ATT API.

Assisted-by: Copilot:claude-sonnet-4.5
Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-09-30 12:42:59 +02:00
Aleksandr Khromykh
389797aeb2 bluetooth: mesh: fix rpl store timeout being overridden
CONFIG_BT_MESH_RPL_STORE_TIMEOUT was only honored while no other
storage flag was pending. As soon as a generic flag such as model
data, keys or config was scheduled alongside a replay protection
list flag, the shared work item was rescheduled to the shorter
CONFIG_BT_MESH_STORE_TIMEOUT deadline, and the replay lists got
stored on that shorter deadline too, causing extra flash wear.

Give the replay protection list and solicitation replay list
their own work item so they are always stored on
CONFIG_BT_MESH_RPL_STORE_TIMEOUT regardless of what else is
pending. The replay list invalidated by an IV Index update or
cleared keeps using CONFIG_BT_MESH_STORE_TIMEOUT, as intended.
bt_mesh_rpl_reset() also no longer schedules that store when an
IV Index update leaves the replay list empty.

Assisted-by: Copilot:claude-opus-5
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
2026-09-29 10:41:11 +02:00
Yuheng Li
7e2cead6b7 Bluetooth: Classic: AVDTP: skip unknown capabilities when parsing caps
bt_avdtp_parse_capability_codec() left an unrecognised category's LOSC and
content in the buffer, so the next iteration misparsed those bytes and
bailed with -EINVAL, stopping the discover walk.

Skip unknown category content instead, as AVDTP requires receivers to
ignore capabilities they do not recognise.

Found during PTS AVDTP/SRC/INT/SIG/SMG/BI-30-C and BI-36-C (ignore
reserved capabilities) qualification runs.

Assisted-by: DeepSeek:deepseek-flash
Signed-off-by: Yuheng Li <liyuheng@xiaomi.com>
2026-09-29 10:40:47 +02:00
Benjamin Cabé
3484454ac8 scripts: kconfig: hardenconfig: switch to YAML hardening database
Replace scripts/kconfig/hardened.csv with a distributed YAML database.
The CSV format could not carry any explanation for its recommendations,
had no validation (a malformed line was silently dropped), no notion of
profiles, no ownership story, and no way to extend it out of tree.

The database now lives where the code lives: the central
scripts/kconfig/hardening.yaml defines the hardening profiles (plus
rules for top-level Kconfig symbols), and per-subsystem hardening.yaml
fragments next to the relevant Kconfig files carry the rules, so each
rule is reviewed by the maintainers of the code it hardens. Every rule
has a required rationale and optional references, supports exact-value
and integer min/max recommendations (STACK_POINTER_RANDOM is now
'>=100' instead of '==100'), and belongs to a profile: 'base' (memory
protection and inherently insecure features) or 'strict' (extends base
with debug/observability feature removal). The default profile is
'strict', matching the rule set the CSV checked.

hardenconfig is restructured around a serializable HardeningReport
model so results can be consumed programmatically, and gains:

- a Rationale column in the report
- profile selection:
  west build -t hardenconfig -- -DHARDENCONFIG_PROFILE=base
- HARDENCONFIG_SHOW_ALL to also list PASS/NA results
- HARDENCONFIG_STRICT to exit non-zero on failures, for CI use
- HARDENCONFIG_JSON to write machine-readable results, including which
  database file each rule came from
- HARDENCONFIG_EXTRA_SOURCES to layer out-of-tree database files that
  may add profiles/rules and override in-tree ones

The EXPERIMENTAL/DEPRECATED/NOT_SECURE marker symbol detection is
preserved unchanged.

Three CSV entries are intentionally not carried over because they were
redundant: BT_CONN_DISABLE_SECURITY and BT_OOB_DATA_FIXED can only be
enabled together with BT_TESTING, and TIMER_RANDOM_GENERATOR together
with TEST_RANDOM_GENERATOR, all of which the database already
recommends disabling for the same profiles.

Behavioral fix: the CSV's DEBUG_COREDUMP line used '=' instead of ','
and was silently ignored, so CONFIG_DEBUG_COREDUMP was never actually
checked; it now is.

Also add tabulate to requirements-base.txt: hardenconfig has always
imported it, but it was only pulled in via other requirements files.

Assisted-by: Claude:fable-5
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
2026-09-29 10:40:32 +02:00
Johan Hedberg
8aa1eb1abb Bluetooth: GATT: Ignore Reserved CCC bits in the value cfg_changed gets
The value passed to a CCC's cfg_changed callback is the highest value
any connected peer wrote, Reserved bits included. A peer that sets one
next to the notify bit (0x0005) is then reported as not subscribed by
every callback that compares the value with BT_GATT_CCC_NOTIFY, such as
the Current Time Service's, although a receiver shall ignore Reserved
bits (Core 6.3, Vol 1, Part E, Section 2.4.1). Mask them before taking
the highest value, which leaves the value unchanged for peers that set
none.

The Reserved bit scenario added to the GATT notify bsim test in the
next commit fails without this change.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-26 01:06:31 +02:00
Johan Hedberg
eceb34cd47 Bluetooth: GATT: Track Service Changed when the indicate bit is set
The Service Changed CCC keeps the per-peer entry that records database
changes made while a bonded peer is disconnected only when the peer
wrote exactly 0x0002. A peer that also sets a Reserved bit, which a
receiver shall ignore (Core 6.3, Vol 1, Part E, Section 2.4.1), gets no
entry, so a change made while it is disconnected is never indicated
when it reconnects. Test the indicate bit instead.

The Reserved bit scenario added to the sc_indicate bsim test in the
next commit fails without this change.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-26 01:06:31 +02:00
Johan Hedberg
ed22337558 Bluetooth: GATT: Match the CCC bit when broadcasting
A notification or indication sent to all peers skips every peer whose
stored CCC value is not exactly that procedure's bit. The value is a bit
field: a client may enable both procedures (Core 6.3, Vol 3, Part G,
Section 3.3.3.3), and a Reserved bit that a client sets anyway is to be
ignored (Vol 1, Part E, Section 2.4.1). Such a peer gets no broadcast at
all, while a notification addressed to its connection reaches it, as the
subscription check on that path, bt_gatt_is_subscribed(), tests the bit.
Test the bit here too.

The broadcast scenario added to the GATT notify bsim test in the next
commit fails without this change.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-09-26 01:06:31 +02:00
Szymon Janc
fc09be87de Bluetooth: Host: Call bond_delete callback only if bond was deleted
bond_delete callback should only be called if actual bond was present
and deleted. Currently it is being called unconditionally when
bt_unpair is called. Bond present is check by validating if any
key was present, this matches bt_foreach_bond() and also handles
paired, but not bonded connected peers.

Signed-off-by: Szymon Janc <szymon.janc@codecoup.pl>
2026-09-26 00:49:01 +02:00
Måns Ansgariusson
e6161ef3ad debug: add granular per-file assertions (ZASSERT)
Introduce ZASSERT, a self-contained assertion facility configured per
source file through a named module rather than the single global
CONFIG_ASSERT switch.

A file selects its module with ZASSERT_MODULE(); the level is resolved
from CONFIG_ASSERT_MODULE_<MODULE>_LEVEL and may be overridden per file.
Modules are defined with the Kconfig.template.assert template, which takes
module/module-str inputs following the logging template convention.
The four levels are:
- Off (compiled out)
- Terse (check only)
- On (check + location only)
- Verbose (Check, location, condition and message)

Since the level is known at compile time, disabled assertions are folded
away by the compiler, and below Verbose the optional message and its
arguments are as well.

zassert provides a set of __weak overridable hooks:
- zassert_fail() - called when an assertion fails
- zassert_vprint() - called to print the assertion failure message
- zassert_post_action() - the terminal action after an assertion failure

CONFIG_ASSERT remains the master switch. The assert Kconfig moves from
subsys/debug to lib/os/zassert, the legacy CONFIG_ASSERT_* symbols are kept
but deprecated (mapped onto the DEFAULT module), and lib/os/assert.c is
removed. The __ASSERT() family is preserved as a thin compatibility shim
over the DEFAULT module, so existing call sites keep working unchanged.

Signed-off-by: Måns Ansgariusson <mansgariusson@gmail.com>
2026-09-25 10:01:43 +02:00