bug: v/22580
The watch now supports power meters. In addition to the existing SVC_DATA_16 filter, new UUID_SOME and UUID_ALL filters must be added.
Signed-off-by: liuxiang18 <liuxiang18@xiaomi.com>
Fix various compilation errors across bluetooth framework, service,
and stack layers including:
- Add missing function declarations and header includes
- Fix type mismatches and implicit function declarations
- Add missing macro definitions in dfx headers
- Add stub implementation for hid device interface
- Fix list utility inline function issues
Signed-off-by: openvela <openvela@xiaomi.com>
bug: v/88938
When acting as A2DP ACP, if the remote side disconnects ACL right after
Set Configuration (before media channel is established), a2dp_info->stream
is freed in a2dp_info_destroy() while zblue's ep->stream still references
the same memory. The subsequent avdtp_release_work() then accesses freed
memory (use-after-free).
Fix by deferring a2dp_info cleanup in zblue_on_disconnected() when stream
is still alive. The cleanup is completed later in zblue_on_stream_released()
after zblue finishes its release work.
Also guard DISCONNECTED_EVT in zblue_on_stream_released() to only fire
when media channel was actually established, avoiding duplicate events
with zblue_on_disconnected().
Add debug logging to a2dp_info_destroy, zblue_on_stream_configured,
zblue_on_stream_released, and zblue_on_disconnected for easier diagnosis.
Signed-off-by: Lu Jia <jialu@xiaomi.com>
bug: v/87935
Rootcause: The global connection list g_sal_hf_conn_list in
sal_hfp_hf_interface.c is accessed by multiple threads (zblue
callback thread, service work thread, upper layer API thread)
without any synchronization, which may cause data race, list
corruption, use-after-free or crash.
Add a pthread recursive mutex (g_sal_hf_conn_lock) with wrapper
functions conn_list_lock()/conn_list_unlock() to protect all
accesses to g_sal_hf_conn_list and calls sub-lists. The mutex
is initialized in bt_sal_hfp_hf_init() and destroyed in
bt_sal_hfp_hf_cleanup(). NULL checks for the list pointer are
moved inside the lock scope to avoid TOCTOU races.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/87935
Rootcause: The global connection list g_sal_ag_conn_list in
sal_hfp_ag_interface.c is accessed by multiple threads (zblue
callback thread, service work thread, upper layer API thread)
without any synchronization, which may cause data race, list
corruption, use-after-free or crash.
Add a pthread recursive mutex (g_sal_ag_conn_lock) with wrapper
functions conn_list_lock()/conn_list_unlock() to protect all
accesses to g_sal_ag_conn_list and calls sub-lists. The mutex
is initialized in bt_sal_hfp_ag_init() and destroyed in
bt_sal_hfp_ag_cleanup(). NULL checks for the list pointer are
moved inside the lock scope to avoid TOCTOU races.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/87673
Rootcause: Multiple bt_sal_hfp_hf_* functions directly call zblue
Z_API() in the caller's context, which can cause concurrent access
issues. Move all remaining HF interfaces (answer_call, reject_call,
hold_call, hangup_call, dial_number, dial_memory, call_control,
get_current_calls, voice_recognition, send_battery_level, send_at_cmd,
send_dtmf, get_subscriber_number) into service_loop_work to serialize
execution in the service loop.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/87673
Rootcause: Multiple bt_sal_hfp_ag_* functions directly call zblue
Z_API() in the caller's context, which can cause concurrent access
issues similar to the set_volume deadlock. Move all remaining AG
interfaces (voice_recognition, cind_response, dial_response,
cops_response, notify_device_status_changed, set_inband_ring_enable,
send_at_cmd, error_response) into service_loop_work to serialize
execution in the service loop.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/87673
Rootcause: bt_sal_hfp_hf_set_volume and bt_sal_hfp_ag_set_volume
directly call zblue API (bt_hfp_hf_vgm/vgs, bt_hfp_ag_vgm/vgs) in
the caller's context. During volume adjustment stress testing on iOS
calls, rapid consecutive invocations can cause deadlock. Move the
actual zblue API calls into service_loop_work to serialize execution
in the service loop, preventing concurrent access issues.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/88196
Rootcause: Concurrent bt_sal_connect calls send multiple HCI Create
Connection commands before the first completes, causing controller to
reject with Command Disallowed. Add a pending queue to serialize ACL
connect requests, dispatching the next via sal_send_req only after
zblue_on_connected callback fires.
Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
bug: v/88680
Rootcause: hfp_hf_voice_volume_change_callback runs in media policy thread
while set_volume_cnt is read/written in hf_stm service loop thread, causing
a race condition. Move set_volume_cnt check and media_volume update from
the callback into a new HF_MEDIA_VOLUME_CHANGED event handler in the
service loop, so all accesses run in the same thread without needing a lock.
Signed-off-by: zhangyuan20 <zhangyuan20@xiaomi.com>
after bt_conn_create_br succeeds (conn enters BT_CONN_INITIATING internally,
which maps to BT_CONN_STATE_CONNECTING publicly), send CONNECTION_STATE_CONNECTING
event to upper layers via adapter_on_connection_state_changed.
Previously only incoming connections (zblue_on_connect_req) notified
CONNECTING state; outgoing connections jumped directly from
DISCONNECTED to CONNECTED, causing upper layers to miss the
intermediate state.
Signed-off-by: zhongzhijie1 <zhongzhijie1@xiaomi.com>
bug: v/87679
When ACL connection fails (e.g., Page Timeout), profile handlers were
not triggered, causing upper layer to wait for timeout instead of
receiving immediate disconnection notification.
This patch:
1. Triggers pending profile handlers when ACL disconnects, allowing
them to detect failure via bt_conn_lookup_addr_br() returning NULL
2. Ensures all profile connect handlers have complete error callbacks
in their failure paths
Affected profiles: HFP HF/AG, A2DP Source/Sink, AVRCP, GATTS BR
Signed-off-by: zhongzhijie1 <zhongzhijie1@xiaomi.com>
bug: v/88179
Restrict BR/LE security_changed bond cleanup to authentication failure
and missing-key cases only. Preserve existing bond information for other
security errors, and move BR bond removal plus ACL disconnect handling
to the service work queue to match the async LE flow.
- rootcause: BR/LE security_changed treated generic security failures as
stale key failures, so delayed teardown or non-key-related errors could
incorrectly delete the stored bond and break the next reconnect.
- include connection state in security_changed logs to improve failure
diagnosis.
- route BR remove_bond and disconnect through the internal async SAL
path instead of operating directly in the callback.
Signed-off-by: zhongzhijie1 <zhongzhijie1@xiaomi.com>
bug: v/88496
When PTS mode is enabled, set the SBC max bitpool to 53 for all
source and sink codec IEs on A2DP connected. This ensures PTS
test compliance with the standard SBC max bitpool value.
Signed-off-by: jialu <jialu@xiaomi.com>
bug: v/88088
bt_att_create_pdu uses BT_ATT_TIMEOUT (K_SECONDS(30)) for ATT_RESPONSE
and ATT_NOTIFICATION ops, which can block the calling thread up to 30s
when the buf pool is exhausted.
Refactor bt_sal_gatt_server_send_notification,
bt_sal_gatt_server_send_indication and bt_sal_gatt_server_send_response
to copy the payload into a heap-allocated request struct and dispatch
via service_loop_work, so the framework thread returns immediately and
the blocking stack call runs in the service worker thread.
- rootcause: bt_gatt_notify_cb/bt_gatt_indicate/bt_gatt_send_read_rsp
all call bt_att_create_pdu which may block K_SECONDS(30) on buf pool
exhaustion, stalling the framework thread
- Add sal_gatts_notify_req_t and sal_gatts_rsp_req_t with flexible array
member to carry the value copy inline
- First four fields of both structs mirror sal_adapter_req_t so
sal_invoke_async can cast and dispatch safely
Signed-off-by: zhongzhijie1 <zhongzhijie1@xiaomi.com>
bug: v/87639
Keep the ACL link in active mode during SCO connection to reduce
control latency for HFP commands such as call termination.
Also fix audio_on_exit to call bt_pm_idle instead of bt_pm_busy,
ensuring consistent idle state when SCO is not established.
Signed-off-by: Zihao Gao <gaozihao@xiaomi.com>
bug: v/5823
CM_RECONNECT_INTERVAL was changed from 8s to 12s for power optimization,
but CM_RECONNECT_TIMES was not updated accordingly, resulting in a 45-minute
reconnect window instead of the designed 30 minutes.
Fix by deriving CM_RECONNECT_TIMES from CM_RECONNECT_INTERVAL directly,
so future interval changes are automatically reflected.
Signed-off-by: liuxiang18 <liuxiang18@xiaomi.com>
bug: v/87902
Refactor the HFP AG SAL connection establishment to align with the
HFP HF implementation:
- Remove global g_conn_params that serialized all connections through
a single slot, preventing parallel outgoing connections.
- Split do_ag_connect into do_ag_sdp_discover (SDP phase) and
do_ag_slc_connect (SLC phase), matching HF's do_hf_sdp_discover
and do_hf_slc_connect.
- Create sal_conn early at SDP discover time so the connection is
tracked from the start, enabling proper cleanup on SDP failure.
- Use service_loop_work to dispatch do_ag_slc_connect from
zblue_on_sdp_done, instead of direct synchronous call.
- Add find_connection_by_context to look up sal_conn by bt_conn*.
- Fix zblue_on_ag_disconnected to use sal_conn->addr directly and
call bt_list_remove after callbacks.
- Fix zblue_on_ag_connected to handle incoming connections and
simultaneous connection collision consistently with HF.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/87902
Use sal_conn->addr directly instead of an intermediate bt_address_t*
pointer variable. The sal_conn object remains valid until bt_list_remove
at the end of the function, so direct access is safe and cleaner.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/87902
Rootcause: When ACL disconnects during SDP discovery, the SDP client
only invokes the disconnected callback, not the func callback. HFP AG
SAL did not register a disconnected callback, so the upper layer never
received a PROFILE_STATE_DISCONNECTED notification and could get stuck.
Add the disconnected callback to notify the upper layer of the
disconnection.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/87902
Rootcause: When ACL disconnects during SDP discovery, the SDP client
only invokes the disconnected callback, not the func callback. HFP HF
SAL did not register a disconnected callback, causing sal_conn to be
orphaned in g_sal_hf_conn_list and the upper layer state machine to
get stuck. Add the disconnected callback to clean up sal_conn and
notify the upper layer of the disconnection.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/85832
Fix defects causing bttool resource leak during BT enable/disable
stress test:
1. Store bttool_t pointer in g_bttool_loop->data so TURNING_OFF callback
can access the async queue (previously always 0, cleanup was skipped)
2. Replace do_in_thread_loop with bttool_uninit() in TURNING_OFF callback
to send _uninit command via uv_async_queue_send, ensuring bt_tool_uninit
runs on g_bttool_loop thread (mirrors bttool_quit pattern). Guard with
CONFIG_LIBUV_EXTENSION only.
3. Add re-entry guard in bt_tool_uninit to prevent double cleanup on
repeated BT disable cycles
Signed-off-by: chejinxian1 <chejinxian1@xiaomi.com>
bug: v/87941
bt_sal_a2dp_source_send_data calls net_buf_add_mem(media_packet_buf, &buf[AVDTP_RTP_HEADER_LEN], nbytes) without validating whether nbytes exceeds the available space in media_packet_buf. The buffer is allocated from bt_a2dp_tx_pool with a data size of CONFIG_ZBLUE_A2DP_SOURCE_BUF_SIZE (default 660 bytes). After bt_a2dp_stream_create_pdu reserves protocol headers (STREAM_DATA_RESERVED, i.e. AVDTP_RTP_HEADER_LEN = 12 bytes), the actual usable payload space is CONFIG_ZBLUE_A2DP_SOURCE_BUF_SIZE - STREAM_DATA_RESERVED (648 bytes). Zephyr's net_buf_add_mem only has an __ASSERT_NO_MSG check which is stripped in release builds. If nbytes exceeds the tailroom, a buffer overflow occurs, corrupting adjacent memory and potentially causing hard faults or data corruption.
Fix: Add a length check before buffer allocation using CONFIG_ZBLUE_A2DP_SOURCE_BUF_SIZE - STREAM_DATA_RESERVED as the maximum payload limit. When nbytes exceeds this limit, log an error and return BT_STATUS_PARM_INVALID, avoiding unnecessary buffer allocation and out-of-bounds writes.
Signed-off-by: jialu <jialu@xiaomi.com>
bug: v/87852
This commit performs an architecture-level refactoring of cs_ras.c and cs_ras.h. The core change replaces the shared global buffer and static arrays used for Real-time and On-demand mode data storage with independent dynamically-allocated linked list queues, resolving memory safety issues and concurrent processing defects in the original architecture.
Signed-off-by: jialu <jialu@xiaomi.com>
bug: v/88151
In zblue_on_connected, when the device acts as ACP (acceptor), it only creates the a2dp_info and waits passively. It never initiates bt_a2dp_discover, so if the remote side also does not initiate the discover/set_config flow, the A2DP connection stalls -- signaling channel is up but no stream is ever configured.
Additionally, in bt_a2dp_discover_endpoint_cb, the a2dp_info->role remains SEP_INVALID for ACP connections because the role was only assigned during the connect initiation path. The SNK set_config branch also had an unnecessary int_acp == A2DP_INT guard, which blocked ACP-initiated discover from completing the configuration.
Fix:
Added a 2-second service_loop_timer in the ACP path of zblue_on_connected. If the remote does not send set_config within 2s, the local side proactively initiates bt_a2dp_discover.
The timer is cancelled in zblue_on_config_req (remote drove the flow first) and in a2dp_info_destroy (cleanup on disconnect).
In bt_a2dp_discover_endpoint_cb, the local role is now derived from the remote's sep_info->tsep: BT_AVDTP_SOURCE -> local SEP_SNK, BT_AVDTP_SINK -> local SEP_SRC.
Removed the int_acp == A2DP_INT restriction on the SEP_SNK set_config branch so ACP-triggered discover can also complete codec negotiation.
Signed-off-by: jialu <jialu@xiaomi.com>
bug: v/84601
rootcause:
1: The old interface forcibly disconnects ACLs, causing profile
connection compatibility issues.
2: The old interface port forcibly releases and cleans up local
resources before disconnecting, especially in sniffing scenarios,
ending before entering active mode, causing a 30-second
timeout on the phone.
in turn, increases the connection disconnection time by 300 milliseconds.
Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
bug: v/-88168
Rootcause: Adjusting the volume in sniff mode is relatively slow; need to exit sniff before adjusting the volume.
Signed-off-by: zhangyuan20 <zhangyuan20@xiaomi.com>
bug: v/87917
Map BT_LE_ADDR_TYPE_UNKNOWN to BT_ADDR_LE_PUBLIC instead of
BT_ADDR_LE_RANDOM to maintain compatibility with legacy stack
behavior where the default address type was public.
Signed-off-by: zhongzhijie1 <zhongzhijie1@xiaomi.com>
bug: v/88096
Fix SPP client connection by implementing bt_sal_spp_connect_with_option.
Previously this function returned BT_STATUS_UNSUPPORTED directly, causing
SPP client connect to fail.
Now for non-insecure mode, it calls bt_sal_spp_connect to establish
connection. Insecure mode is not yet supported and still returns
BT_STATUS_UNSUPPORTED.
Signed-off-by: chejinxian1 <chejinxian1@xiaomi.com>
Bug: v/87379
Refactor gattc_service.c to use the new debug module:
- Include gattc_internal.h and gattc_debug.h
- Remove local struct definitions (moved to gattc_internal.h)
- Replace inline logging with debug module functions
- Remove dump_services() (moved to gattc_debug.c)
Add CONFIG_BLUETOOTH_GATT_CLIENT_DEBUG Kconfig option:
- Default enabled (y) for backward compatibility
- When disabled, debug functions become empty macros
- Reduces code size by removing log strings
Update Makefile and CMakeLists.txt to conditionally compile
gattc_debug.c based on the config option.
Signed-off-by: Zihao Gao <gaozihao@xiaomi.com>
Bug: v/87379
Define BT_UUID_STR_LENGTH macro (40) in bt_uuid.h to replace hardcoded
magic numbers for UUID string buffer size. Use LENGTH suffix to avoid
conflict with Zephyr's BT_UUID_STR_LEN definition.
Update all usages across the codebase to use the new macro.
Signed-off-by: Zihao Gao <gaozihao@xiaomi.com>
bug: v/87572
When bt_sal_spp_write returns BT_STATUS_NOMEM, the complete packet
(size == mfs) is cached via spp_cache_fragement, setting
cache_buf.length = mfs. On recovery, spp_on_outgoing_complete directly
calls euv_pipe_read_start, causing euv_alloc_buffer to compute
len = mfs - mfs = 0. libuv gets a zero-length buffer, pipe read
stalls, and the connection eventually drops.
Fix by incrementing remaining_quota before the recovery check to
prevent uint8_t underflow (0 - 1 = 0xFF), then branching on
cache_buf.length: flush cached data via do_spp_write if present,
otherwise restart pipe read with mfs.
Signed-off-by: chejinxian1 <chejinxian1@xiaomi.com>
bug: v/87852
This change fixes multiple issues in the Bluetooth CS (Channel Sounding) RAS (Ranging Service) data conversion and transmission:
Filter type overflow: Changed ras_filter from uint32_t to uint16_t to match the RAS spec (16-bit filter mask per mode), and updated the initial value from 0xFFFFFFFF to 0xFFFF.
Filter enum start value: All mode filter bit enums (MODE_0/1/2/3) now start at 2 instead of 0, aligning with the actual bit definitions in the RAS specification.
MODE 1 role condition inverted: In CS_RAS_SUBEVENT_STEP_MODE_1, the Initiator and Reflector role branches were swapped (Reflector was incorrectly executing the Initiator path).
Missing antenna_paths semantic conversion: HCI reports num_antenna_paths as a count (1-4), but RAS requires a bitmask. Added count-to-bitmask conversion (e.g., count=4 → 0x0F).
MODE 2/3 Tone data parsing: Changed Tone_PCT and Tone_Quality_Indicator from bulk copy using (num_antenna_paths+1) to per-tone iteration via while(remaining > 0), matching the RAS spec's per-tone filtering semantics.
Real-time data trigger condition: Changed the condition in cs_ras_subevent_result_cb from procedure_done_status to subevent_done_status, since real-time mode should trigger on each subevent completion, not the entire procedure.
Signed-off-by: jialu <jialu@xiaomi.com>
bug: v/87862
Rootcause: zblue_on_security_changed and zblue_on_pairing_failed
callbacks run inside smp_pairing_complete. They called bt_unpair /
bt_conn_disconnect synchronously, which freed bt_conn before
smp_pairing_complete finished. smp_reset then accessed freed memory.
Fix: use async bt_sal_le_remove_bond / bt_sal_le_disconnect instead,
so bt_conn stays alive until the entire callback chain returns.
Signed-off-by: zhongzhijie1 <zhongzhijie1@xiaomi.com>
bug: v/87645
After sending STREAM_SUSPEND_REQ without receiving a response, STREAM_START_REQ is received and enters open state, then DISCONNECTED_EVT is received, causing pending to remain in stop state, which
prevents music from playing normally after reconnection.
Signed-off-by: jialu <jialu@xiaomi.com>
bug: v/83395
Rootcause: Upper-layer app does not unregister callbacks on BT off.
Callbacks list was freed in hf_shutdown, losing registrations across BT on/off cycles. As a compatibility change, move callbacks to init/cleanup so registrations persist across BT enable/disable.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/86209
Add logging in bt_sal_hfp_ag_phone_state_change to trace incoming
call state parameters, new call creation, and existing call state
transitions for easier debugging.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/86209
When only one call remains in the call list and it is terminated,
the AG should send a hangup indication rather than CHLD=1 to the
HF device, so the HF side can correctly update its call state.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/83395
Rootcause: Upper-layer app does not unregister callbacks on BT off.
Callbacks list was freed in ag_shutdown, losing registrations across
BT on/off cycles. As a compatibility change, move callbacks to
init/cleanup so registrations persist across BT enable/disable.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/86209
Rootcause: When zblue triggers call state callbacks (accept/held/retrieve/
reject/terminate), the SAL layer notifies the upper service layer, which
then calls phone_state_change to update the same state. This causes
duplicate Z_API calls back into zblue, leading to stack errors.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/87527
Rootcause: In update_sal_call, when a call entry has unknown state
or direction, find_call_by_context was used to locate the owner
connection. However for call_sync entries the context may be NULL,
causing the lookup to fail and the stale entry to remain in the
list. Also, phone_state_change did not remove call entries on
terminal states.
Use the conn parameter directly instead of find_call_by_context,
and remove call entries when state becomes unknown after
phone_state_change.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>
bug: v/87527
Rootcause: When HFP connection is established during an active call,
AT+BAC sets preferred_codec to mSBC, but bt_hfp_ag_codec_select may
auto-select CVSD. The codec_negotiate callback on success path did
not sync the actual codec back to preferred_codec, so upper layer
used mSBC sample rate (16000Hz) for CVSD data, causing audio
distortion (noise).
Update zblue_on_ag_codec_negotiation to accept the actual codec_id
from the callback. On success, compare with preferred_codec and
notify upper layer via hfp_ag_on_codec_changed if they differ.
Signed-off-by: liyuheng <liyuheng@xiaomi.com>