When an HCI ACL packet carries more than one L2CAP PDU, the bytes after
a PDU may be fewer than an L2CAP header. bt_br_acl_recv() still read
the length field from them, which can reach past the end of the
received data before the remainder is rejected as a short packet.
Check that a whole header is present before reading it.
Tested with a new tests/bluetooth/host_br_acl_recv case on native_sim,
which covers dropping such a remainder; the read itself is not
observable there.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
A malformed L2CAP length in received ACL data is a fault on the remote
side, and bt_br_acl_recv() recovers by dropping the rest of the packet,
so these are warnings rather than local errors.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
A receiver may keep the buffer of an L2CAP PDU after bt_l2cap_recv()
returns, as an RFCOMM recv() callback returning -EINPROGRESS does.
bt_br_acl_recv() then restored and pulled that same buffer to reach the
next PDU, so the kept buffer had len 0 when the application read it, or
showed the following PDU when the HCI ACL packet carried several.
Hand the last PDU over in the ACL buffer itself and each earlier one in
a view that references the ACL buffer, from a pool of
CONFIG_BT_BR_ACL_RX_VIEW_COUNT views. Views rather than clones because
a clone from the ACL RX pool would be reported to the Controller as
another completed packet. When no view is left, a PDU shares the ACL
buffer's cursor as before rather than being dropped, since the peer has
spent flow control credits on it.
Tested with tests/bluetooth/host_br_acl_recv on native_sim, with and
without CONFIG_BT_HCI_ACL_FLOW_CONTROL.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
These functions are used in many places, and inlining them
instead of compiling them caused unnecessary memory overhead.
For CONFIG_ASSERT=y the FLASH difference is 644 bytes
when building the BT_SHELL for nrf52840dk/nrf52840
For CONFIG_ASSERT=n the FLASH difference is 144 bytes
when building the BT_SHELL nrf52840dk/nrf52840
The macro, BT_DEV_LOCK_ASSERT, was kept as is, as implementing
that as a function only increased the FLASH.
RAM is unaffected by this change.
Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
A scanner that sets BT_LE_SCAN_OPT_EXT_FILTER_POLICY receives directed
advertisements whose target is a resolvable private address that the
Controller could not resolve, reported as BT_ADDR_LE_UNRESOLVED. To act
on one, the application has to check whether the address was generated
from an IRK it holds, such as its own IRK after a peer lost the bond or
an old IRK after bt_id_reset_irk(). The Host and the Controller already
share this check as bt_rpa_irk_matches() in the private common/rpa.h.
Declare it in addr.h as bt_addr_matches_irk(), next to
bt_addr_le_rpa_resolve(), taking the address first like the other
bt_addr_ functions, and update the Host, Controller and test callers.
BT_IRK_SIZE moves from bluetooth.h to addr.h for the prototype;
bluetooth.h includes addr.h, so its users still see it. The bt_addr API
version goes to 1.1.0. The direct_addr documentation of struct
bt_le_scan_recv_info points to the new function.
It now returns false for an address that is not an RPA, without running
AES. The Host callers already check for an RPA, so they behave as
before. The Controller's resolving list lookup keeps its address type
check and leaves the RPA bit check to the function. The Controller's
PAST receiver with CONFIG_BT_CTLR_SW_DEFERRED_PRIVACY does not check: it
passes any random AdvA to the deferred resolution, static and
non-resolvable ones included. Such an address used to match on a 24-bit
hash collision and no longer does.
Fixes#120887
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Aric Radzin <aric.radzin@gmail.com>
rpa.c is built only when CONFIG_BT_SMP, CONFIG_BT_PRIVACY or
CONFIG_BT_CTLR_PRIVACY selects CONFIG_BT_RPA, and bt_rpa_irk_matches()
had its own guard on the same three options. An observer could only get
the function by enabling privacy, although it can hold the IRKs of peers
that use resolvable private addresses, for example provisioned out of
band, and recognise their advertising without using an RPA itself.
The helpers only need AES, from CONFIG_BT_HOST_CRYPTO or
CONFIG_BT_CTLR_CRYPTO, which CONFIG_BT_RPA already depends on. Enable
CONFIG_BT_RPA by default and drop the guard in rpa.c, so that the
helpers are built whenever AES is available. The linker drops them
when nothing calls them; with CONFIG_LOG=y the bt_rpa log source adds
24 bytes of flash.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Aric Radzin <aric.radzin@gmail.com>
struct bt_att_tx_meta_data puts its uint8_t opcode between an int and
a uint16_t, and struct bt_smp has passkey_round alone between passkey
and two pointers. The resulting holes cost RAM in every ATT TX buffer
and every SMP context.
Move attr_count and opcode after the pointers in the ATT TX metadata,
next to chan_opt: 24 to 20 bytes where an enum takes one byte, as with
the Zephyr SDK's GCC on Cortex-M, where short enums are the default.
With int-sized enums, as on native_sim and 64-bit targets, the size
does not change.
Move passkey and passkey_round below the OOB data pointers in the SMP
context, so that passkey_round joins local_dist and remote_dist: 368 to
360 bytes on bbc_microbit. smp_init() still clears the same members,
everything from method up to the L2CAP channel.
The bbc_microbit peripheral_hr and central_hr builds have three ATT TX
buffers and one SMP context, 20 bytes less in total.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
An LE-only build stores only a struct closure, two pointers, in the
user data of the buffers it sends, but CONFIG_BT_CONN_TX_USER_DATA_SIZE
reserves 16 bytes per buffer on 32-bit and 32 bytes on 64-bit targets.
The larger sizes are for Classic, whose per-buffer state is bigger:
struct l2cap_br_closure (11 bytes on 32-bit, 19 bytes on 64-bit),
struct avctp_buf_user_data (12 and 16 bytes) and struct
bt_avrcp_tg_vd_rsp_tx (16 and 24 bytes).
Keep 16 and 32 bytes when Classic is enabled, and otherwise default to
the size of struct closure: 8 bytes on 32-bit and 16 bytes on 64-bit
targets. ISO stores nothing there; conn_iso_send() only checks that the
user data is as large as the option. Pools that applications size with
the option shrink in the same way.
The ATT and ACL TX pools shrink by 8 bytes per buffer, 40 bytes in the
bbc_microbit peripheral_hr and central_hr builds.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
struct bt_dev stores the whole 64-octet Read Local Supported Commands
response, but the host only checks nine bits of it. Keep those as bits
of an atomic bitmap instead, which grows with the list of commands the
host checks. They are set from the response with the existing
BT_CMD_TEST()-style macros and cleared in bt_disable() as before.
Threads other than the one that sets and clears them read them, for
example when an API call checks for LE Set Host Channel Classification,
hence the atomic accesses.
struct bt_dev shrinks by 64 bytes in the bbc_microbit peripheral_hr and
central_hr minimal builds (280 to 216 and 256 to 192 bytes) and by 56
bytes in the extended observer and mesh_demo builds (224 to 168 and 328
to 272 bytes).
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
The MCC reads the object metadata of the included OTS instance with
BT_OTS_METADATA_REQ_ALL, which makes the OTS client read the Object
First-Created and Object Last-Modified characteristics. The MCC
discovery never stored their handles, so those reads were sent to
handle 0. Store the First-Created and Last-Modified handles in the
existing bt_ots_client fields. Also store the Object Changed handle.
The OTS client does not use it, it is kept so that the BTP tester can
report it to PTS, which expects the handle of every supported OTS
characteristic to be returned during discovery.
Signed-off-by: Alex Ciascai <alexandru.ciascai@nordicsemi.no>
k_mutex_unlock() reports an unlock by a thread that does not hold the
mutex with -EPERM (or -EINVAL when nobody holds it), and
bt_dev_unlock() asserts on that. With CONFIG_NO_RUNTIME_CHECKS the
kernel skips both checks: the unlock goes through, corrupts the lock
count and owner of the host lock and returns 0, so the misuse goes
unnoticed.
Assert with BT_DEV_LOCK_ASSERT() before the unlock. This catches the
misuse in every build with CONFIG_ASSERT and names the offending thread
instead of only the error code. The macro moves above the lock helpers
so that bt_dev_unlock() can use it.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
IAR may incorrectly handle direct assignment of a const
bt_sdp_discover_params structure, resulting in corrupted function
and data pointers after the copy.
Use memcpy() to perform a byte-wise copy and avoid the issue.
Signed-off-by: Make Shi <make.shi@nxp.com>
An extended advertising report without AD data, and a periodic
advertising report with zero-length AD data, call memcpy() with a NULL
source and a length of 0. That is undefined behavior, and UBSAN reports
it.
Copy only when there is data.
Seen on nrf52_bsim with CONFIG_UBSAN=y: tests/bsim/bluetooth/ll/bis hits
the first; the second needs that test to send zero-length periodic
advertising data. Not tested on hardware.
Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Arkadiusz Grzelka <arkadiusz.grzelka@arivemb.com>
With BT_TICKER_EXT_EXPIRE_INFO, periodic advertising and remainder
support, the aux ticker callback computes the SyncInfo offset by
converting its own remainder with hal_ticker_add_jitter(), which
rewrites the remainder in place from the ticker's unit to microseconds.
The same variable is then passed to the aux prepare as p.remainder,
where the LLL reads it in the ticker's unit (radio_tmr_start() on
Nordic converts it with hal_ticker_remove_jitter()). The aux event
therefore starts without its sub-tick part: up to one ticker tick late
against the AuxPtr the primary channel PDUs announce, as a sawtooth
that follows the aux ticker's remainder.
Convert a copy for the SyncInfo offset and pass the remainder unchanged.
With the AuxPtr timing check added to the advx ticker expire info test
on nrf52_bsim/native: without this fix 105 of 480 auxiliary packets of
a set with periodic advertising start outside the window the AuxPtr
allows; with it, none.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Kent Hauser <kent@khauser.net>
Use defines for the ticker node state values, i.e. the difference of
the node's req and ack counts, instead of numeric literals.
No functional change.
Assisted-by: Cursor:Claude Opus 5.5
Signed-off-by: Vinayak Kariappa Chettimada <vich@nordicsemi.no>
Defer ticker yield_abs operation on an expired ticker node until
the ticker job bottom half has processed the expiry.
The bottom half assigns the expired node's slot reservation, hence
a yield applied before it is lost and the full slot remains
reserved. Auxiliary PDU reception tickers started in the yielded
time space are then skipped as collisions, and the scan aux context
is flushed without receiving the auxiliary PDUs.
This happens when ULL_LOW has lower priority than ULL_HIGH and the
ticker job is delayed beyond the ULL_HIGH processing of the PDU
received in the expired ticker's radio event.
Assisted-by: Cursor:Claude Opus 5.5
Signed-off-by: Vinayak Kariappa Chettimada <vich@nordicsemi.no>
Fix ticker_job_list_inquire() to traverse the user operation queue
only up to the operations that ticker_job_list_manage() and
ticker_job_list_insert() have processed, i.e. up to user->middle.
When ticker job executes in a lower priority than a ticker user,
the user can preempt the ticker job and enqueue new operations after
the list manage step. The inquire step traversing up to user->last
then consumed these operations without processing them. A ticker
start was hence never inserted nor its operation callback invoked,
as observed for the scan auxiliary PDU reception ticker started in
ULL_HIGH while ticker job in a lower priority ULL_LOW was preempted,
leaking the scan aux context.
Assisted-by: Cursor:Claude Opus 5.5
Signed-off-by: Vinayak Kariappa Chettimada <vich@nordicsemi.no>
prov_link_close() set link.tx.timeout to CLOSING_TIMEOUT (3 s). On the
device side reset_adv_link() does not reset this field, and
provisionee.c does not re-accept the PB-ADV bearer after a PB-ADV link
closes, so prov_link_accept() never restores TRANSACTION_TIMEOUT. After
one device-initiated close (transaction or protocol timeout), every
transaction on later PB-ADV links was abandoned after 3 s instead of
the 30 s acknowledgment timer required by MshPRT v1.1, section 5.3.3,
until reboot.
Since commit 534177b2ca ("Bluetooth: Mesh: Fix regression in PB-ADV")
Link Close is sent as an unacked PDU repeated
CONFIG_BT_MESH_PB_ADV_LINK_CLOSE_RETRANSMIT_COUNT times, so the closing
timeout is no longer read while closing. Remove the assignment and the
unused CLOSING_TIMEOUT define.
Assisted-by: Claude:claude-opus-5.5
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
With CONFIG_NO_OPTIMIZATIONS=y on 32-bit Arm, the TX processor
overflows its 1024-byte default stack in bt_enable(), and the Bluetooth
workqueue its 1200 bytes once a connection is established. The long
workqueue already has a NO_OPTIMIZATIONS default; these two do not.
Unoptimized peaks, optimized in parentheses: TX processor 1168 (404) in
tests/bluetooth/host_disable on qemu_cortex_m3 and 1320 (392) in
samples/bluetooth/peripheral_hr on nrf52dk/nrf52832; Bluetooth
workqueue 2192 (856) in peripheral_hr with pairing and notifications.
Default to 2048 and 4096 bytes, the latter as for the long workqueue.
ARM64 keeps its values and BT_HCI_RAW its 768.
Tested with stack overflow detection only: host_disable on
qemu_cortex_m3 and mps2/an385 and peripheral_hr on nrf52dk overflow
without this change and run with it, with the main, system workqueue
and test helper stacks raised, and on nrf52dk the Controller's RX
thread stacks as well. Optimized .config files are unchanged.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
randomize_bt_addr() was an empty stub whose TODO stated that the AdvA
could not be refreshed. Remove it and its call in enc_id_adv().
Private Network Identity and Private Node Identity advertising
regenerates the Random field before every advertising start, and
starts the advertiser with BT_LE_ADV_OPT_USE_NRPA, for which the host
generates a new NRPA on every start with both legacy and extended
advertising. This already meets MshPRTv1.1 sections 7.2.2.2.4 and
7.2.2.2.5, which require the AdvA to be regenerated whenever the
Random field is regenerated.
The comment in enc_id_adv() now documents where the AdvA comes from.
Assisted-by: Copilot:claude-opus-4.7
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
The recv() callback of a periodic advertising sync is documented to get
a NULL buffer when the Controller failed to receive a subevent of
Periodic Advertising with Responses. The Host did this only with
CONFIG_BT_PER_ADV_SYNC_BUF_SIZE > 0, so with the default size of 0 the
application never learned about a failed subevent.
Handle the failed subevent before reassembly, as it carries no data.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
The ATT code reads and writes the fields of the embedded LE L2CAP
channel directly in about 50 places: the RX/TX MTU, the TX CID, the
connection and the generic channel object. Several of these go
through BT_L2CAP_LE_CHAN() only to print the CID or fetch the
connection.
Add small static accessors for the channel, connection, TX CID and
RX/TX MTU, and use them everywhere except the fixed channel send in
chan_send(), which is LE specific. This keeps knowledge of the bearer
channel type in one place so a bearer that is not an LE channel can
be added without touching the protocol handlers.
No functional change. Built for native_sim (tests/bluetooth/shell,
tests/bluetooth/init) and ran the ATT, GATT and L2CAP ECRED bsim
tests on nrf52_bsim.
Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
rpa_timeout() stops the RPA timer when no advertiser, initiator or
active scanner uses the RPA, but only with CONFIG_BT_CENTRAL. In other
builds the timer runs, and the Host regenerates the RPA, for as long as
Bluetooth is enabled, so that advertising sets keep getting the
rpa_expired callback while inactive (see #118322).
An Observer-only build has no advertising sets, and a passive scanner
does not send its address, so it gains nothing from the timer. Stop it
there too. The next active scan creates a new RPA, which restarts the
timer.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Aric Radzin <aric.radzin@gmail.com>
CONFIG_BT_PRIVACY was defined inside the BT_SMP block, which is inside
the BT_CONN block, so Broadcaster- and Observer-only builds could not
enable it. Setting it there only gave a Kconfig warning, and such builds
by default advertised and actively scanned with an NRPA that the Host
did not rotate. GAP defines the privacy feature for these roles without
bonding (Core v6.3, Vol 3, Part C, Table 10.3), and generating RPAs
does not need SMP.
Move CONFIG_BT_PRIVACY and its sub-options out of both blocks. It
depends on BT_BROADCASTER or BT_OBSERVER, and still on BT_SMP when
BT_CONN is enabled, since Table 10.3 makes bonding mandatory for a
Peripheral or Central that supports privacy. It selects BT_RPA for
bt_rpa_create(), which so far only BT_SMP selected.
Without SMP there are no peer keys, so bt_id_reset_irk() skips the bond
check, and bt_addr_le_rpa_resolve(), which looks them up, is only built
with SMP. bt_rpa_irk_matches() is also built with privacy, as the
host_id tests check the generated RPAs with it.
The bluetooth.host_id.privacy.no_smp test now builds with privacy and
runs the IRK tests.
Fixes#122737
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Aric Radzin <aric.radzin@gmail.com>
bt_setup_public_id_addr() and bt_setup_random_id_addr() derive the
identity IRK from the IR with bt_smp_irk_get(). It is defined in smp.c,
which is only built with CONFIG_BT_SMP, and nothing else uses it.
The derivation only needs AES, which privacy already needs to generate
RPAs. Move it to id.c as irk_from_ir() so that it builds without SMP.
No functional change.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Aric Radzin <aric.radzin@gmail.com>
The echo API is used for qualification testing, through the tester and
the shell, and has no other known user. Make it available only with
CONFIG_BT_TESTING, like the other APIs needed only for testing. Echo
Requests are still answered in other builds, by the stack.
Update the shell, whose echo commands now need CONFIG_BT_TESTING and are
built by a new scenario, the tests and the documentation, and describe
the change in the migration guide.
Assisted-by: Kiro:claude-opus-5.5
Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
Since the echo API was added, a received Echo Request has only been
answered by a registered req callback calling bt_l2cap_br_echo_rsp().
Without such a callback, which is the case for most applications, the
request was left unanswered, while an L2CAP entity shall respond to a
valid Echo Request with an Echo Response (Core 6.3, Vol 3, Part A,
4.8).
Answer the Echo Request with an Echo Response without data when no req
callback is registered, which the response may carry (Core 6.3, Vol 3,
Part A, 4.9). As for the other responses the stack sends, reserve the
buffer for it before the request is processed, so that a request
received while no buffer is available is kept and processed again
later instead of being dropped.
Assisted-by: Kiro:claude-opus-5.5
Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
The Echo Request used the signaling channel identifier and RTX timer,
which also track the Information Request. This had several effects:
- bt_l2cap_br_echo_req() returned -EBUSY while an Information Request
was outstanding, such as right after the ACL connection is made.
- An Information Response arriving after its request timed out, while
an Echo Request was outstanding, cleared the Echo Request identifier,
so the Echo Response was dropped.
- An Echo Response with a mismatching identifier ended the outstanding
Echo Request, so the matching response was dropped.
- A Command Reject for the Echo Request was taken as one for a dynamic
channel and disconnected the signaling channel.
- The echo RTX timer was not canceled on disconnection.
Keep the Echo Request identifier and RTX timer in the signaling context.
Ignore Echo Responses that do not match the outstanding request, end
the request on a matching Command Reject, and cancel the timer when the
signaling channel is disconnected. The identifier is cleared before the
response callbacks run, so they can send the next request, and the RTX
timer is started before the request is sent, so that a response that
comes before the send returns cancels it.
Update the test that set the signaling channel identifier to stand for
an outstanding Echo Request, so that it sends an Echo Request instead.
Assisted-by: Kiro:claude-opus-5.5
Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
The MCS server has to handle a Track Title that does not fit in a
single ATT operation: a notification of the value is truncated to
ATT_MTU-3 bytes, and a Read Long that continues at an offset after the
value has changed is rejected with the Value Changed During Read Long
error. The MCS qualification test cases GMCS/SR/SPN/BV-02-C verify
this behavior. They need a Track Title that does not fit in a single
ATT operation both before and after the update.
The titles of the tracks in the first group were 9 bytes long. With the
default ATT MTU of 23, at most 20 bytes fit in a single read or
notification, so the Track Title always fit and the server behavior
above could not be exercised. The test cases could not pass.
Change the titles of the tracks in the first group to
"Track 1.x with a very long name" (31 characters), which still fits in
the default CONFIG_BT_MPL_TRACK_TITLE_MAX of 40. The media player
starts on the first track, so with the default ATT MTU of 23 the
initial Track Title is 31 bytes, which does not fit in a single read.
Moving to the next track changes the Track Title to a different 31 byte
value, which triggers the notification. The test case can then check
that the notification is truncated to 20 bytes, that a Read Long at that
offset returns Value Changed During Read Long, and that a new Read Long
from offset 0 returns the full updated title.
This only works with the default ATT MTU of 23. If a different ATT MTU
is exchanged, for example the 65 bytes that BAP requires to be
supported, a 31 byte Track Title fits in a single read or notification
and the test case does not exercise this behavior.
Signed-off-by: Alex Ciascai <alexandru.ciascai@nordicsemi.no>
The NUS TX CCC and RX characteristic accept writes on an unencrypted
link, and a bonded peer's stored subscription lets notifications go out
before encryption.
Add the BT_ZEPHYR_NUS_SECURITY choice to require encryption, or
encryption and authentication, for those writes and for notifications.
Encryption alone still admits a peer paired with Just Works. The
default is no requirements, and the secured options depend on BT_SMP.
Add tests/bluetooth/nus to check the attribute permissions.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Arkadiusz Grzelka <devitwise@gmail.com>
struct bt_dev carried the list of connections with something to send in
builds that have neither connections nor ISO, and the legacy advertiser,
or the pointer to the reserved advertising set, in builds without the
broadcaster role. Nothing refers to either there: the code that does is
only built with those features. Leave the members out as well.
Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
The buffers of the HCI RX pool reserve user data for the connection
metadata of received ACL and ISO data. Received ISO data has buffers of
its own whenever the Host can receive it, see bt_iso_get_rx(), and any
other ISO data is dropped before its metadata is written, so only ACL
data needs the metadata here. Builds without connections, an observer
or an ISO broadcaster for instance, only ever receive events in these
buffers, which have no metadata. Give those builds buffers without user
data, which saves four bytes per buffer.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
A build without CONFIG_BT_ISO_RX sets up nothing to receive ISO data,
but a controller can still send it. Such a packet gets a buffer of the
general RX pool from bt_buf_get_rx(), and hci_iso() writes its metadata
into the user data of that buffer right after parsing the header. Drop
the packet instead.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
The table of L2CAP channel callbacks that every ATT channel points to
is never written, and the channel refers to it through a pointer to
const, but it was a writable static and so took 40 bytes of RAM.
Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
Every advertising set carries a 48-byte delayable work item whose only
use is to stop advertising that bt_le_adv_start() was given with the
BT_LE_AD_LIMITED flag. Applications that never advertise in limited
discoverable mode pay for it all the same.
Add CONFIG_BT_LIM_ADV, enabled by default, and build the timer only
with it. Without it bt_le_adv_start() refuses advertising data that has
the flag, as nothing would end the mode in time.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
No caller uses the result of cancelling the limited advertising timeout,
so the function no longer returns it and the callers drop their casts.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
The host never writes Connection_Accept_Timeout, so an incoming BR/EDR
connection request that the host does not answer in time is rejected by
the controller after whatever its default happens to be. Program it from
Kconfig in common_init(), once the supported commands have been read.
HCI_Write_Connection_Accept_Timeout is reported by Supported_Commands
octet 7 bit 3, so only write it when the controller claims it and leave
the controller default in place otherwise. A failure of a command the
controller does advertise is treated as fatal, like the other writes in
common_init().
The controller applies the same parameter to LE CIS requests (Core
Specification 6.3, Vol 4, Part E, Section 6.7), but if the application's
accept callback in hci_le_cis_req() has not returned by the time it
expires, the controller rejects the request on its own and the host then
sends its accept for a request that is already gone, so the option is
not offered when BT_ISO_PERIPHERAL is enabled.
The range is the mandatory one from that same section rather than the
full 0x0001-0xb540: a controller need not accept anything below 0x00a0.
Assisted-by: Claude:claude-opus-5
Signed-off-by: Zhijie Zhong <zhongzhijie1@xiaomi.com>
Add validation checks to ensure that L2CAP LE operations are only
performed on LE connections. The changes prevents potential
out-of-bounds access to the `le_cid_index_next` array when using the
ACL connection index in cases where the caller fails to verify that the
ACL connection type is LE.
The validation is added to following two functions, including
`bt_l2cap_ecred_chan_connect()`, and `bt_l2cap_chan_connect()`. Each
check logs a message and returns `-EINVAL` when an invalid conn type
is detected.
Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
Optimize the L2CAP LE dynamic CID allocation by using a per-connection
counter to track the next CID to allocate instead of always starting
from the beginning of the range.
The change introduces a `le_cid_index_next` array that maintains the
position of the next CID index to allocate for each connection. The
allocation now searches from the last allocated position through the
range, wrapping around if needed. This reduces the search time for
available CIDs in scenarios with multiple active channels by avoiding
repeated scans of already-allocated CIDs at the start of the range.
Additionally, this modification has the advantage of delaying the
reassignment of a recently disconnected CID to a new channel. This makes
it less likely that data from the channel disconnection process is sent
to the newly assigned channel. Note that it is not a guarantee: if the
cursor happens to point at the index of a CID whose channel has just
been freed, the next allocation still returns that CID immediately.
The allocation still validates that CIDs are not in use by checking
against `l2cap_le_lookup_rx_cid()` before assignment, maintaining the
same correctness guarantees as the previous implementation.
Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
Add a server side implementation of the HID Service (HIDS), the GATT
service that the HID Device role of the HID over GATT Profile is built
on.
The GATT attribute table is static: the number of Report characteristics
of each type is build time configuration, and the application supplies
one Report ID per characteristic when it registers the service. Provided
are a configurable Report Map, Input, Output and Feature Reports, HID
Information and the HID Control Point, which are the characteristics
the HID Service makes mandatory for a Device that supports Report
Protocol Mode only.
Properties:
- The HID Service sets no security requirements of its own, so the
security the characteristics require is a build time choice:
CONFIG_BT_HIDS_SECURITY_NONE, _ENCRYPT or _AUTHEN. ENCRYPT, what the
HID over GATT Profile requires, is the default when SMP is enabled.
- The service keeps no per-connection state. A HID Control Point
command is passed to the application with the connection it came
from; an unknown command is rejected.
- The CCC descriptors are left to the GATT core, which refuses the
indication bit for these notify only characteristics. An application
learns whether a Host is subscribed from the return value of
bt_hids_send_report().
- Notifications through bt_gatt_notify_cb() with an optional completion
callback. The API documents every error value it returns.
- The Report Map and the callback structure are referenced, not copied.
- The API is thread safe: a mutex serializes it with the GATT handlers,
and is released before an application callback runs and before a
notification is sent. A rejected registration leaves no state behind.
A GATT handler that waited for the mutex while the service was
unregistered answers Invalid Handle instead of using the cleared
state.
- The service holds the value of every Report and answers a Host read
from it, the way the other GATT services in the tree do, so every
fragment of a read comes from that one value rather than from a
per-read copy that could go stale. The application sets the value
with bt_hids_report_set() and reads it back with bt_hids_report_get(),
and a Host write to a writable Report replaces it as well.
- A Host write longer than CONFIG_BT_HIDS_MAX_REPORT_LEN is rejected,
which makes that option an upper bound in both directions.
- Register time validation of the Report Map length, of the HID
Information flags, of bcdHID being binary coded decimal, and of the
Report IDs: no duplicates within a Report Type, and no Report ID of 0
when the Report Type has more than one Report characteristic. A flag
the service cannot back, such as the one that announces the HID SCI
feature, is rejected rather than exposed to the Host.
Not supported yet: Boot Protocol Mode, that is the Protocol Mode
characteristic and the Boot Keyboard and Boot Mouse Report
characteristics, which the HID Service makes mandatory for a keyboard
and for a mouse, and several HID Service instances for composite
devices.
Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
Since commit eeef8ad2b1 ("Bluetooth: Host: rotate NRPA"), an
advertiser started with BT_LE_ADV_OPT_USE_NRPA gets a new NRPA at every
RPA timeout when CONFIG_BT_PRIVACY is enabled. This only works with the
extended advertising commands, where adv_enable_rpa() refreshes each set
with its own options. le_update_private_addr() refreshes the legacy
advertiser with bt_id_set_private_addr(), which always creates an RPA,
so from the first timeout on the legacy advertiser used an RPA.
Refresh an enabled legacy advertiser that uses an NRPA with
bt_id_set_adv_private_addr(), as adv_enable_rpa() does. A scanner
running at the same time shares the legacy random address, so it gets
the new NRPA too.
Tested on native_sim with a test HCI driver that logs LE Set Random
Address: the legacy advertiser now gets a new NRPA at each timeout,
and RPA advertising and scanning still rotate RPAs.
Fixes#122891
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Aric Radzin <aric.radzin@gmail.com>
With the legacy advertising commands, the advertiser, the scanner and
the initiator share the random address. With CONFIG_BT_PRIVACY, the
scanner and initiator paths call bt_id_set_private_addr() to set an
RPA there. While an advertiser started with BT_LE_ADV_OPT_USE_NRPA is
enabled, the RPA is not valid, and the controller rejects LE Set Random
Address while legacy advertising is enabled (Core v6.3, Vol 4, Part E,
7.8.4). bt_le_scan_start() and bt_conn_le_create() then fail with
-EACCES.
Store the options in adv_start_legacy() so that this case can be told
apart. A scanner then uses the advertiser's NRPA, which Vol 3, Part C,
10.7.4 allows for active scanning. Connection creation fails with
-EINVAL, since a privacy-enabled Central shall use an RPA as the
initiator's address (10.7.2). The new bt_id_conn_random_addr_check()
rejects it before bt_conn_le_create() can start resolving the peer's
address in the Host, so the error is not reported later from the scan.
bt_le_oob_get_local() also fails with -EINVAL, as it cannot refresh
the RPA in that case.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Aric Radzin <aric.radzin@gmail.com>
The Host drops a periodic advertising report that it cannot reassemble,
one in fragments without CONFIG_BT_PER_ADV_SYNC_BUF_SIZE or one that
does not fit the reassembly buffer, and marks the report truncated until
its last fragment. Only a fragment with the Complete data status ended
the dropped report, but the Controller ends a report with the Incomplete
data status when it fails to receive the rest of it. The Host then took
the next report for the end of the dropped one and dropped it as well.
Without a reassembly buffer, a report with the Incomplete data status on
its own started a dropped report.
End a dropped report on the Incomplete data status as on the Complete
one, and without a reassembly buffer, start one only on the Partial
data status.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
With Controller to Host flow control, an ACL buffer that is freed before
hci_acl() has looked up its connection, as when the driver drops the
packet or it is too short for its header, keeps the zeroed user data of
its allocation. Its completion is then reported for handle 0x0000 while
the first connection is up: to a handle the Controller may not have, or
to another connection. Mark the buffer as having no connection from its
allocation on.
The host_disable test added here fails without the fix.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
A central keeps the object of a CIS for its next connection, and unlike
that of an ACL connection it is not zeroed in between. Two fields
survived a disconnection. next_is_frag, set while an SDU is sent in
part, made the first SDU of the next connection go out as the
continuation of one that the controller never got the start of. in_ll
kept counting the packets that the controller had not acknowledged,
which the TX scheduler takes for packets the controller still holds.
Reset both where the unacknowledged packets are returned.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
bt_iso_reset() disconnected the CISes of a central by hand, without
touching the TX side of their connections. An SDU that the controller
had not acknowledged was never reported. With SDUs still queued in the
Host the connection outlived its CIG, and the connection cleanup then
disconnected the channel a second time, through a pointer that the CIG
cleanup had set to NULL.
Use bt_iso_chan_disconnected(), as for the BISes. It was avoided
because it removed the ISO data path, with an HCI command, which it no
longer does since
commit 065dca7e92 ("Bluetooth: ISO: Make setting ISO data explicit").
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
bt_iso_chan_ops.send_failed is to be called for an SDU that
bt_iso_chan_send() accepted but that did not get sent because the
channel disconnected. The SDUs still queued in the Host at that point
were freed without it, and only those the controller had not
acknowledged were reported. An application that counts its SDUs in
flight never got the queued ones back.
Report them too, after those the controller had not acknowledged, and
only once the channel is disconnected, so that the callback cannot
queue them again. The callback's documentation no longer says that
nothing of such an SDU reached the controller: one that was not
acknowledged did, and a queued one may have in part.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
A bearer takes the first queued request that its channel option allows,
bt_att_chan_req_send() refuses it if it exceeds the ATT_MTU of the
bearer, and the request goes back to the head of the queue.
bt_att_create_pdu() accepts a request that fits any bearer, so one
restricted to EATT that fits only the UATT bearer, or one restricted to
UATT that fits only an EATT bearer, stalls every later request with the
same restriction without reporting an error.
Have a bearer skip the requests it cannot carry, and let the scan skip
a bearer only if its ATT_MTU is no larger than that of the previous one
of its kind. bt_att_sent() and bt_att_status(), which retry a request
on a bearer that was busy, now use the same selection instead of
taking the head of the queue.
The indication scenarios added to the eatt_notif bsim test in the next
commit fail without this change.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
A bearer takes the first queued PDU that its channel option allows. An
EATT bearer whose peer MTU is smaller than that PDU then fails to send
it, as L2CAP refuses the SDU with an error log, and puts it back at the
head of the queue, which keeps the bearer from sending anything else.
A PDU restricted to EATT that fits no EATT bearer, which
bt_att_create_pdu() accepts when the UATT bearer is large enough
(#119817), thereby stalls every later PDU restricted to EATT until an
EATT bearer's MTU grows.
Have an EATT bearer skip the PDUs that L2CAP would refuse, so that later
ones can use it meanwhile; a later PDU that may use either bearer kind
can then be sent before an earlier one waiting for the UATT bearer. A
bearer with nothing to send no longer implies the same for a following
bearer of its kind with a larger MTU, so the scan only skips those that
are not larger. The UATT bearer is unchanged.
The MTU scenario added to the eatt_notif 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>