1 /******************************************************************************
2 *
3 * Copyright 2008-2014 Broadcom Corporation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19 /******************************************************************************
20 *
21 * This file contains functions for BLE GAP.
22 *
23 ******************************************************************************/
24
25 #define LOG_TAG "bt_btm_ble"
26
27 #include <android_bluetooth_sysprop.h>
28 #include <base/functional/bind.h>
29 #include <base/strings/string_number_conversions.h>
30 #include <bluetooth/log.h>
31 #include <com_android_bluetooth_flags.h>
32
33 #include <bitset>
34 #include <cstdint>
35 #include <list>
36 #include <memory>
37 #include <type_traits>
38 #include <vector>
39
40 #include "bta/include/bta_api.h"
41 #include "common/time_util.h"
42 #include "hci/controller.h"
43 #include "hci/controller_interface.h"
44 #include "main/shim/acl_api.h"
45 #include "main/shim/entry.h"
46 #include "osi/include/allocator.h"
47 #include "osi/include/properties.h"
48 #include "osi/include/stack_power_telemetry.h"
49 #include "stack/btm/btm_ble_int.h"
50 #include "stack/btm/btm_ble_int_types.h"
51 #include "stack/btm/btm_dev.h"
52 #include "stack/btm/btm_int_types.h"
53 #include "stack/btm/btm_sec.h"
54 #include "stack/btm/btm_sec_cb.h"
55 #include "stack/include/acl_api.h"
56 #include "stack/include/advertise_data_parser.h"
57 #include "stack/include/ble_scanner.h"
58 #include "stack/include/bt_dev_class.h"
59 #include "stack/include/bt_types.h"
60 #include "stack/include/bt_uuid16.h"
61 #include "stack/include/btm_api_types.h"
62 #include "stack/include/btm_ble_addr.h"
63 #include "stack/include/btm_ble_privacy.h"
64 #include "stack/include/btm_log_history.h"
65 #include "stack/include/btm_status.h"
66 #include "stack/include/gap_api.h"
67 #include "stack/include/gattdefs.h"
68 #include "stack/include/hci_error_code.h"
69 #include "stack/include/inq_hci_link_interface.h"
70 #include "stack/rnr/remote_name_request.h"
71 #include "types/ble_address_with_type.h"
72 #include "types/raw_address.h"
73
74 // TODO(b/369381361) Enfore -Wmissing-prototypes
75 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
76
77 using namespace bluetooth;
78
79 extern tBTM_CB btm_cb;
80
81 void btm_ble_adv_filter_init(void);
82
83 #define BTM_EXT_BLE_RMT_NAME_TIMEOUT_MS (30 * 1000)
84 #define MIN_ADV_LENGTH 2
85 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN 9
86 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_L_RELEASE BTM_VSC_CHIP_CAPABILITY_RSP_LEN
87 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_M_RELEASE 15
88 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_S_RELEASE 25
89
90 /* Sysprop paths for scan parameters */
91 static const char kPropertyInquiryScanInterval[] = "bluetooth.core.le.inquiry_scan_interval";
92 static const char kPropertyInquiryScanWindow[] = "bluetooth.core.le.inquiry_scan_window";
93
94 #ifndef PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED
95 #define PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED \
96 "bluetooth.core.gap.le.privacy.own_address_type.enabled"
97 #endif
98
99 static void btm_ble_start_scan();
100 static void btm_ble_stop_scan();
101 static tBTM_STATUS btm_ble_stop_adv(void);
102 static tBTM_STATUS btm_ble_start_adv(void);
103
104 using bluetooth::shim::GetController;
105
106 namespace {
107
108 constexpr char kBtmLogTag[] = "SCAN";
109
110 constexpr uint8_t BLE_EVT_CONNECTABLE_BIT = 0;
111 constexpr uint8_t BLE_EVT_SCANNABLE_BIT = 1;
112 constexpr uint8_t BLE_EVT_DIRECTED_BIT = 2;
113 constexpr uint8_t BLE_EVT_SCAN_RESPONSE_BIT = 3;
114 constexpr uint8_t BLE_EVT_LEGACY_BIT = 4;
115
116 class AdvertisingCache {
117 public:
118 /* Set the data to |data| for device |addr_type, addr| */
Set(uint8_t addr_type,const RawAddress & addr,std::vector<uint8_t> data)119 const std::vector<uint8_t>& Set(uint8_t addr_type, const RawAddress& addr,
120 std::vector<uint8_t> data) {
121 auto it = Find(addr_type, addr);
122 if (it != items.end()) {
123 it->data = std::move(data);
124 return it->data;
125 }
126
127 if (items.size() > cache_max) {
128 items.pop_back();
129 }
130
131 items.emplace_front(addr_type, addr, std::move(data));
132 return items.front().data;
133 }
134
Exist(uint8_t addr_type,const RawAddress & addr)135 bool Exist(uint8_t addr_type, const RawAddress& addr) {
136 auto it = Find(addr_type, addr);
137 if (it != items.end()) {
138 return true;
139 }
140 return false;
141 }
142
143 /* Append |data| for device |addr_type, addr| */
Append(uint8_t addr_type,const RawAddress & addr,std::vector<uint8_t> data)144 const std::vector<uint8_t>& Append(uint8_t addr_type, const RawAddress& addr,
145 std::vector<uint8_t> data) {
146 auto it = Find(addr_type, addr);
147 if (it != items.end()) {
148 it->data.insert(it->data.end(), data.begin(), data.end());
149 return it->data;
150 }
151
152 if (items.size() > cache_max) {
153 items.pop_back();
154 }
155
156 items.emplace_front(addr_type, addr, std::move(data));
157 return items.front().data;
158 }
159
160 /* Clear data for device |addr_type, addr| */
Clear(uint8_t addr_type,const RawAddress & addr)161 void Clear(uint8_t addr_type, const RawAddress& addr) {
162 auto it = Find(addr_type, addr);
163 if (it != items.end()) {
164 items.erase(it);
165 }
166 }
167
ClearAll()168 void ClearAll() { items.clear(); }
169
170 private:
171 struct Item {
172 uint8_t addr_type;
173 RawAddress addr;
174 std::vector<uint8_t> data;
175
Item__anon5ed1097b0111::AdvertisingCache::Item176 Item(uint8_t addr_type, const RawAddress& addr, std::vector<uint8_t> data)
177 : addr_type(addr_type), addr(addr), data(data) {}
178 };
179
Find(uint8_t addr_type,const RawAddress & addr)180 std::list<Item>::iterator Find(uint8_t addr_type, const RawAddress& addr) {
181 for (auto it = items.begin(); it != items.end(); it++) {
182 if (it->addr_type == addr_type && it->addr == addr) {
183 return it;
184 }
185 }
186 return items.end();
187 }
188
189 /* we keep maximum 7 devices in the cache */
190 const size_t cache_max = 7;
191 std::list<Item> items;
192 };
193
194 /* Devices in this cache are waiting for either scan response, or chained packets
195 * on secondary channel */
196 AdvertisingCache cache;
197
198 } // namespace
199
ble_vnd_is_included()200 bool ble_vnd_is_included() {
201 // replace build time config BLE_VND_INCLUDED with runtime
202 return android::sysprop::bluetooth::Ble::vnd_included().value_or(true);
203 }
204
205 static tBTM_BLE_CTRL_FEATURES_CBACK* p_ctrl_le_feature_rd_cmpl_cback = NULL;
206 /**********PAST & PS *******************/
207 using StartSyncCb = base::Callback<void(
208 uint8_t /*status*/, uint16_t /*sync_handle*/, uint8_t /*advertising_sid*/,
209 uint8_t /*address_type*/, RawAddress /*address*/, uint8_t /*phy*/, uint16_t /*interval*/)>;
210 using SyncReportCb =
211 base::Callback<void(uint16_t /*sync_handle*/, int8_t /*tx_power*/, int8_t /*rssi*/,
212 uint8_t /*status*/, std::vector<uint8_t> /*data*/)>;
213 using SyncLostCb = base::Callback<void(uint16_t /*sync_handle*/)>;
214 using SyncTransferCb = base::Callback<void(uint8_t /*status*/, RawAddress)>;
215 #define MAX_SYNC_TRANSACTION 16
216 #define SYNC_TIMEOUT (30 * 1000)
217 #define ADV_SYNC_ESTB_EVT_LEN 16
218 #define SYNC_LOST_EVT_LEN 3
219 typedef enum {
220 PERIODIC_SYNC_IDLE = 0,
221 PERIODIC_SYNC_PENDING,
222 PERIODIC_SYNC_ESTABLISHED,
223 PERIODIC_SYNC_LOST,
224 } tBTM_BLE_PERIODIC_SYNC_STATE;
225
226 struct alarm_t* sync_timeout_alarm;
227 typedef struct {
228 uint8_t sid;
229 RawAddress remote_bda;
230 tBTM_BLE_PERIODIC_SYNC_STATE sync_state;
231 uint16_t sync_handle;
232 bool in_use;
233 StartSyncCb sync_start_cb;
234 SyncReportCb sync_report_cb;
235 SyncLostCb sync_lost_cb;
236 BigInfoReportCb biginfo_report_cb;
237 } tBTM_BLE_PERIODIC_SYNC;
238
239 typedef struct {
240 bool in_use;
241 int conn_handle;
242 RawAddress addr;
243 SyncTransferCb cb;
244 } tBTM_BLE_PERIODIC_SYNC_TRANSFER;
245
246 static list_t* sync_queue;
247 static std::mutex sync_queue_mutex_;
248
249 typedef struct {
250 bool busy;
251 uint8_t sid;
252 RawAddress address;
253 uint16_t skip;
254 uint16_t timeout;
255 } sync_node_t;
256 typedef struct {
257 uint8_t sid;
258 RawAddress address;
259 } remove_sync_node_t;
260 typedef enum {
261 BTM_QUEUE_SYNC_REQ_EVT,
262 BTM_QUEUE_SYNC_ADVANCE_EVT,
263 BTM_QUEUE_SYNC_CLEANUP_EVT
264 } btif_queue_event_t;
265
266 typedef struct {
267 tBTM_BLE_PERIODIC_SYNC p_sync[MAX_SYNC_TRANSACTION];
268 tBTM_BLE_PERIODIC_SYNC_TRANSFER sync_transfer[MAX_SYNC_TRANSACTION];
269 } tBTM_BLE_PA_SYNC_TX_CB;
270 tBTM_BLE_PA_SYNC_TX_CB btm_ble_pa_sync_cb;
271 StartSyncCb sync_rcvd_cb;
272 static bool syncRcvdCbRegistered = false;
273 static int btm_ble_get_psync_index(uint8_t adv_sid, RawAddress addr);
274 static void btm_ble_start_sync_timeout(void* data);
275
276 /*****************************/
277 /*******************************************************************************
278 * Local functions
279 ******************************************************************************/
280 static void btm_ble_update_adv_flag(uint8_t flag);
281 void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type,
282 const RawAddress& bda, uint8_t primary_phy, uint8_t secondary_phy,
283 uint8_t advertising_sid, int8_t tx_power, int8_t rssi,
284 uint16_t periodic_adv_int, uint8_t data_len, const uint8_t* data,
285 const RawAddress& original_bda);
286 static uint8_t btm_set_conn_mode_adv_init_addr(RawAddress& p_peer_addr_ptr,
287 tBLE_ADDR_TYPE* p_peer_addr_type,
288 tBLE_ADDR_TYPE* p_own_addr_type);
289 static void btm_ble_stop_observe(void);
290 static void btm_ble_fast_adv_timer_timeout(void* data);
291 static void btm_ble_start_slow_adv(void);
292 static void btm_ble_inquiry_timer_gap_limited_discovery_timeout(void* data);
293 static void btm_ble_inquiry_timer_timeout(void* data);
294 static void btm_ble_observer_timer_timeout(void* data);
295 static DEV_CLASS btm_ble_appearance_to_cod(uint16_t appearance);
296
297 enum : uint8_t {
298 BTM_BLE_NOT_SCANNING = 0x00,
299 BTM_BLE_INQ_RESULT = 0x01,
300 BTM_BLE_OBS_RESULT = 0x02,
301 };
302
ble_evt_type_is_connectable(uint16_t evt_type)303 static bool ble_evt_type_is_connectable(uint16_t evt_type) {
304 return evt_type & (1 << BLE_EVT_CONNECTABLE_BIT);
305 }
306
ble_evt_type_is_scannable(uint16_t evt_type)307 static bool ble_evt_type_is_scannable(uint16_t evt_type) {
308 return evt_type & (1 << BLE_EVT_SCANNABLE_BIT);
309 }
310
ble_evt_type_is_scan_resp(uint16_t evt_type)311 static bool ble_evt_type_is_scan_resp(uint16_t evt_type) {
312 return evt_type & (1 << BLE_EVT_SCAN_RESPONSE_BIT);
313 }
314
ble_evt_type_is_legacy(uint16_t evt_type)315 static bool ble_evt_type_is_legacy(uint16_t evt_type) {
316 return evt_type & (1 << BLE_EVT_LEGACY_BIT);
317 }
318
ble_evt_type_data_status(uint16_t evt_type)319 static uint8_t ble_evt_type_data_status(uint16_t evt_type) { return (evt_type >> 5) & 3; }
320
321 constexpr uint8_t UNSUPPORTED = 255;
322
323 /* LE states combo bit to check */
324 const uint8_t btm_le_state_combo_tbl[BTM_BLE_STATE_MAX][BTM_BLE_STATE_MAX] = {
325 {
326 /* single state support */
327 HCI_LE_STATES_CONN_ADV_BIT, /* conn_adv */
328 HCI_LE_STATES_INIT_BIT, /* init */
329 HCI_LE_STATES_INIT_BIT, /* central */
330 HCI_LE_STATES_PERIPHERAL_BIT, /* peripheral */
331 UNSUPPORTED, /* todo: lo du dir adv, not covered ? */
332 HCI_LE_STATES_HI_DUTY_DIR_ADV_BIT, /* hi duty dir adv */
333 HCI_LE_STATES_NON_CONN_ADV_BIT, /* non connectable adv */
334 HCI_LE_STATES_PASS_SCAN_BIT, /* passive scan */
335 HCI_LE_STATES_ACTIVE_SCAN_BIT, /* active scan */
336 HCI_LE_STATES_SCAN_ADV_BIT /* scanable adv */
337 },
338 {
339 /* conn_adv =0 */
340 UNSUPPORTED, /* conn_adv */
341 HCI_LE_STATES_CONN_ADV_INIT_BIT, /* init: 32 */
342 HCI_LE_STATES_CONN_ADV_CENTRAL_BIT, /* central: 35 */
343 HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT, /* peripheral: 38,*/
344 UNSUPPORTED, /* lo du dir adv */
345 UNSUPPORTED, /* hi duty dir adv */
346 UNSUPPORTED, /* non connectable adv */
347 HCI_LE_STATES_CONN_ADV_PASS_SCAN_BIT, /* passive scan */
348 HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_BIT, /* active scan */
349 UNSUPPORTED /* scanable adv */
350 },
351 {
352 /* init */
353 HCI_LE_STATES_CONN_ADV_INIT_BIT, /* conn_adv: 32 */
354 UNSUPPORTED, /* init */
355 HCI_LE_STATES_INIT_CENTRAL_BIT, /* central 28 */
356 HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT, /* peripheral 41 */
357 HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_BIT, /* lo du dir adv 34 */
358 HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_BIT, /* hi duty dir adv 33 */
359 HCI_LE_STATES_NON_CONN_INIT_BIT, /* non connectable adv */
360 HCI_LE_STATES_PASS_SCAN_INIT_BIT, /* passive scan */
361 HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT, /* active scan */
362 HCI_LE_STATES_SCAN_ADV_INIT_BIT /* scanable adv */
363 },
364 {
365 /* central */
366 HCI_LE_STATES_CONN_ADV_CENTRAL_BIT, /* conn_adv: 35 */
367 HCI_LE_STATES_INIT_CENTRAL_BIT, /* init 28 */
368 HCI_LE_STATES_INIT_CENTRAL_BIT, /* central 28 */
369 HCI_LE_STATES_CONN_ADV_INIT_BIT, /* peripheral: 32 */
370 HCI_LE_STATES_LO_DUTY_DIR_ADV_CENTRAL_BIT, /* lo duty cycle adv 37 */
371 HCI_LE_STATES_HI_DUTY_DIR_ADV_CENTRAL_BIT, /* hi duty cycle adv 36 */
372 HCI_LE_STATES_NON_CONN_ADV_CENTRAL_BIT, /* non connectable adv*/
373 HCI_LE_STATES_PASS_SCAN_CENTRAL_BIT, /* passive scan */
374 HCI_LE_STATES_ACTIVE_SCAN_CENTRAL_BIT, /* active scan */
375 HCI_LE_STATES_SCAN_ADV_CENTRAL_BIT /* scanable adv */
376 },
377 {
378 /* peripheral */
379 HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT, /* conn_adv: 38,*/
380 HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT, /* init 41 */
381 HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT, /* central 41 */
382 HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT, /* peripheral: 38,*/
383 HCI_LE_STATES_LO_DUTY_DIR_ADV_PERIPHERAL_BIT, /* lo duty cycle adv 40 */
384 HCI_LE_STATES_HI_DUTY_DIR_ADV_PERIPHERAL_BIT, /* hi duty cycle adv 39 */
385 HCI_LE_STATES_NON_CONN_ADV_PERIPHERAL_BIT, /* non connectable adv */
386 HCI_LE_STATES_PASS_SCAN_PERIPHERAL_BIT, /* passive scan */
387 HCI_LE_STATES_ACTIVE_SCAN_PERIPHERAL_BIT, /* active scan */
388 HCI_LE_STATES_SCAN_ADV_PERIPHERAL_BIT /* scanable adv */
389 },
390 {
391 /* lo duty cycle adv */
392 UNSUPPORTED, /* conn_adv: 38,*/
393 HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_BIT, /* init 34 */
394 HCI_LE_STATES_LO_DUTY_DIR_ADV_CENTRAL_BIT, /* central 37 */
395 HCI_LE_STATES_LO_DUTY_DIR_ADV_PERIPHERAL_BIT, /* peripheral: 40 */
396 UNSUPPORTED, /* lo duty cycle adv 40 */
397 UNSUPPORTED, /* hi duty cycle adv 39 */
398 UNSUPPORTED, /* non connectable adv */
399 UNSUPPORTED, /* TODO: passive scan, not covered? */
400 UNSUPPORTED, /* TODO: active scan, not covered? */
401 UNSUPPORTED /* scanable adv */
402 },
403 {
404 /* hi duty cycle adv */
405 UNSUPPORTED, /* conn_adv: 38,*/
406 HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_BIT, /* init 33 */
407 HCI_LE_STATES_HI_DUTY_DIR_ADV_CENTRAL_BIT, /* central 36 */
408 HCI_LE_STATES_HI_DUTY_DIR_ADV_PERIPHERAL_BIT, /* peripheral: 39*/
409 UNSUPPORTED, /* lo duty cycle adv 40 */
410 UNSUPPORTED, /* hi duty cycle adv 39 */
411 UNSUPPORTED, /* non connectable adv */
412 HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_BIT, /* passive scan */
413 HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_BIT, /* active scan */
414 UNSUPPORTED /* scanable adv */
415 },
416 {
417 /* non connectable adv */
418 UNSUPPORTED, /* conn_adv: */
419 HCI_LE_STATES_NON_CONN_INIT_BIT, /* init */
420 HCI_LE_STATES_NON_CONN_ADV_CENTRAL_BIT, /* central */
421 HCI_LE_STATES_NON_CONN_ADV_PERIPHERAL_BIT, /* peripheral: */
422 UNSUPPORTED, /* lo duty cycle adv */
423 UNSUPPORTED, /* hi duty cycle adv */
424 UNSUPPORTED, /* non connectable adv */
425 HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_BIT, /* passive scan */
426 HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_BIT, /* active scan */
427 UNSUPPORTED /* scanable adv */
428 },
429 {
430 /* passive scan */
431 HCI_LE_STATES_CONN_ADV_PASS_SCAN_BIT, /* conn_adv: */
432 HCI_LE_STATES_PASS_SCAN_INIT_BIT, /* init */
433 HCI_LE_STATES_PASS_SCAN_CENTRAL_BIT, /* central */
434 HCI_LE_STATES_PASS_SCAN_PERIPHERAL_BIT, /* peripheral: */
435 UNSUPPORTED, /* lo duty cycle adv */
436 HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_BIT, /* hi duty cycle adv */
437 HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_BIT, /* non connectable adv */
438 UNSUPPORTED, /* passive scan */
439 UNSUPPORTED, /* active scan */
440 HCI_LE_STATES_SCAN_ADV_PASS_SCAN_BIT /* scanable adv */
441 },
442 {
443 /* active scan */
444 HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_BIT, /* conn_adv: */
445 HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT, /* init */
446 HCI_LE_STATES_ACTIVE_SCAN_CENTRAL_BIT, /* central */
447 HCI_LE_STATES_ACTIVE_SCAN_PERIPHERAL_BIT, /* peripheral: */
448 UNSUPPORTED, /* lo duty cycle adv */
449 HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_BIT, /* hi duty cycle adv */
450 HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_BIT, /* non connectable adv */
451 UNSUPPORTED, /* TODO: passive scan */
452 UNSUPPORTED, /* TODO: active scan */
453 HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_BIT /* scanable adv */
454 },
455 {
456 /* scanable adv */
457 UNSUPPORTED, /* conn_adv: */
458 HCI_LE_STATES_SCAN_ADV_INIT_BIT, /* init */
459 HCI_LE_STATES_SCAN_ADV_CENTRAL_BIT, /* central */
460 HCI_LE_STATES_SCAN_ADV_PERIPHERAL_BIT, /* peripheral: */
461 UNSUPPORTED, /* lo duty cycle adv */
462 UNSUPPORTED, /* hi duty cycle adv */
463 UNSUPPORTED, /* non connectable adv */
464 HCI_LE_STATES_SCAN_ADV_PASS_SCAN_BIT, /* passive scan */
465 HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_BIT, /* active scan */
466 UNSUPPORTED /* scanable adv */
467 }};
468
469 /* check LE combo state supported */
BTM_LE_STATES_SUPPORTED(const uint64_t x,uint8_t bit_num)470 inline bool BTM_LE_STATES_SUPPORTED(const uint64_t x, uint8_t bit_num) {
471 uint64_t mask = 1 << bit_num;
472 return (x)&mask;
473 }
474
BTM_BleOpportunisticObserve(bool enable,tBTM_INQ_RESULTS_CB * p_results_cb)475 void BTM_BleOpportunisticObserve(bool enable, tBTM_INQ_RESULTS_CB* p_results_cb) {
476 if (enable) {
477 btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb = p_results_cb;
478 } else {
479 btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb = NULL;
480 }
481 }
482
BTM_BleTargetAnnouncementObserve(bool enable,tBTM_INQ_RESULTS_CB * p_results_cb)483 void BTM_BleTargetAnnouncementObserve(bool enable, tBTM_INQ_RESULTS_CB* p_results_cb) {
484 if (enable) {
485 btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb = p_results_cb;
486 } else {
487 btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb = NULL;
488 }
489 }
490
get_low_latency_scan_params()491 std::pair<uint16_t /* interval */, uint16_t /* window */> get_low_latency_scan_params() {
492 uint16_t scan_interval =
493 osi_property_get_int32(kPropertyInquiryScanInterval, BTM_BLE_LOW_LATENCY_SCAN_INT);
494 uint16_t scan_window =
495 osi_property_get_int32(kPropertyInquiryScanWindow, BTM_BLE_LOW_LATENCY_SCAN_WIN);
496
497 return std::make_pair(scan_interval, scan_window);
498 }
499
500 /*******************************************************************************
501 *
502 * Function BTM_BleObserve
503 *
504 * Description This procedure keep the device listening for advertising
505 * events from a broadcast device.
506 *
507 * Parameters start: start or stop observe.
508 * duration: how long the scan should last, in seconds. 0 means
509 * scan without timeout. Starting the scan second time without
510 * timeout will disable the timer.
511 *
512 * Returns void
513 *
514 ******************************************************************************/
BTM_BleObserve(bool start,uint8_t duration,tBTM_INQ_RESULTS_CB * p_results_cb,tBTM_CMPL_CB * p_cmpl_cb)515 tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration, tBTM_INQ_RESULTS_CB* p_results_cb,
516 tBTM_CMPL_CB* p_cmpl_cb) {
517 tBTM_STATUS status = tBTM_STATUS::BTM_WRONG_MODE;
518 uint8_t scan_phy = !btm_cb.ble_ctr_cb.inq_var.scan_phy ? BTM_BLE_DEFAULT_PHYS
519 : btm_cb.ble_ctr_cb.inq_var.scan_phy;
520
521 // use low latency scanning
522 uint16_t ll_scan_interval, ll_scan_window;
523 std::tie(ll_scan_interval, ll_scan_window) = get_low_latency_scan_params();
524
525 log::verbose("scan_type:{}, {}, {}", btm_cb.ble_ctr_cb.inq_var.scan_type, ll_scan_interval,
526 ll_scan_window);
527
528 if (!bluetooth::shim::GetController()->SupportsBle()) {
529 return tBTM_STATUS::BTM_ILLEGAL_VALUE;
530 }
531
532 if (start) {
533 /* shared inquiry database, do not allow observe if any inquiry is active.
534 * except we are doing CSIS active scanning
535 */
536 if (btm_cb.ble_ctr_cb.is_ble_observe_active()) {
537 if (duration == 0) {
538 if (alarm_is_scheduled(btm_cb.ble_ctr_cb.observer_timer)) {
539 alarm_cancel(btm_cb.ble_ctr_cb.observer_timer);
540 } else {
541 log::error("Scan with no duration started twice!");
542 }
543 }
544 /*
545 * we stop current observation request for below scenarios
546 * 1. current ongoing scanning is low latency
547 */
548 bool is_ongoing_low_latency = btm_cb.ble_ctr_cb.inq_var.scan_interval == ll_scan_interval &&
549 btm_cb.ble_ctr_cb.inq_var.scan_window == ll_scan_window;
550 if (is_ongoing_low_latency) {
551 log::warn("Observer was already active, is_low_latency: {}", is_ongoing_low_latency);
552 return tBTM_STATUS::BTM_CMD_STARTED;
553 }
554 // stop any scan without low latency config
555 btm_ble_stop_observe();
556 }
557
558 btm_cb.ble_ctr_cb.p_obs_results_cb = p_results_cb;
559 btm_cb.ble_ctr_cb.p_obs_cmpl_cb = p_cmpl_cb;
560 status = tBTM_STATUS::BTM_CMD_STARTED;
561
562 /* scan is not started */
563 if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) {
564 /* allow config of scan type */
565 cache.ClearAll();
566 btm_cb.ble_ctr_cb.inq_var.scan_type =
567 (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_NONE)
568 ? BTM_BLE_SCAN_MODE_ACTI
569 : btm_cb.ble_ctr_cb.inq_var.scan_type;
570 btm_send_hci_set_scan_params(btm_cb.ble_ctr_cb.inq_var.scan_type, (uint16_t)ll_scan_interval,
571 (uint8_t)ll_scan_window, (uint16_t)scan_phy,
572 btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type,
573 BTM_BLE_DEFAULT_SFP);
574
575 btm_ble_start_scan();
576 }
577
578 btm_cb.neighbor.le_observe = {
579 .start_time_ms = timestamper_in_milliseconds.GetTimestamp(),
580 .results = 0,
581 };
582
583 BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le observe started",
584 "low latency scanning enabled");
585
586 if (status == tBTM_STATUS::BTM_CMD_STARTED) {
587 btm_cb.ble_ctr_cb.set_ble_observe_active();
588 if (duration != 0) {
589 /* start observer timer */
590 uint64_t duration_ms = duration * 1000;
591 alarm_set_on_mloop(btm_cb.ble_ctr_cb.observer_timer, duration_ms,
592 btm_ble_observer_timer_timeout, NULL);
593 }
594 }
595 } else if (btm_cb.ble_ctr_cb.is_ble_observe_active()) {
596 const uint64_t duration_timestamp =
597 timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.le_observe.start_time_ms;
598 BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le observe stopped",
599 base::StringPrintf("duration_s:%6.3f results:%-3lu",
600 (double)duration_timestamp / 1000.0,
601 (unsigned long)btm_cb.neighbor.le_observe.results));
602 status = tBTM_STATUS::BTM_CMD_STARTED;
603 btm_ble_stop_observe();
604 } else {
605 log::error("Observe not active");
606 }
607
608 return status;
609 }
610
611 /*******************************************************************************
612 *
613 * Function BTM_BleGetVendorCapabilities
614 *
615 * Description This function reads local LE features
616 *
617 * Parameters p_cmn_vsc_cb : Locala LE capability structure
618 *
619 * Returns void
620 *
621 ******************************************************************************/
BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB * p_cmn_vsc_cb)622 void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB* p_cmn_vsc_cb) {
623 if (NULL != p_cmn_vsc_cb) {
624 *p_cmn_vsc_cb = btm_cb.cmn_ble_vsc_cb;
625 }
626 }
627
BTM_BleGetDynamicAudioBuffer(tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB p_dynamic_audio_buffer_cb[])628 void BTM_BleGetDynamicAudioBuffer(tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB p_dynamic_audio_buffer_cb[]) {
629 log::verbose("BTM_BleGetDynamicAudioBuffer");
630
631 if (NULL != p_dynamic_audio_buffer_cb) {
632 for (int i = 0; i < 32; i++) {
633 p_dynamic_audio_buffer_cb[i] = btm_cb.dynamic_audio_buffer_cb[i];
634 }
635 }
636 }
637
638 /******************************************************************************
639 *
640 * Function BTM_BleReadControllerFeatures
641 *
642 * Description Reads BLE specific controller features
643 *
644 * Parameters: tBTM_BLE_CTRL_FEATURES_CBACK : Callback to notify when
645 * features are read
646 *
647 * Returns void
648 *
649 ******************************************************************************/
BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK * p_vsc_cback)650 void BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK* p_vsc_cback) {
651 if (!ble_vnd_is_included()) {
652 return;
653 }
654
655 if (btm_cb.cmn_ble_vsc_cb.values_read) {
656 return;
657 }
658
659 log::verbose("BTM_BleReadControllerFeatures");
660
661 btm_cb.cmn_ble_vsc_cb.values_read = true;
662 bluetooth::hci::ControllerInterface::VendorCapabilities vendor_capabilities =
663 GetController()->GetVendorCapabilities();
664
665 btm_cb.cmn_ble_vsc_cb.adv_inst_max = vendor_capabilities.max_advt_instances_;
666 btm_cb.cmn_ble_vsc_cb.rpa_offloading =
667 vendor_capabilities.offloaded_resolution_of_private_address_;
668 btm_cb.cmn_ble_vsc_cb.tot_scan_results_strg = vendor_capabilities.total_scan_results_storage_;
669 btm_cb.cmn_ble_vsc_cb.max_irk_list_sz = vendor_capabilities.max_irk_list_sz_;
670 btm_cb.cmn_ble_vsc_cb.filter_support = vendor_capabilities.filtering_support_;
671 btm_cb.cmn_ble_vsc_cb.max_filter = vendor_capabilities.max_filter_;
672 btm_cb.cmn_ble_vsc_cb.energy_support = vendor_capabilities.activity_energy_info_support_;
673
674 btm_cb.cmn_ble_vsc_cb.version_supported = vendor_capabilities.version_supported_;
675 btm_cb.cmn_ble_vsc_cb.total_trackable_advertisers =
676 vendor_capabilities.total_num_of_advt_tracked_;
677 btm_cb.cmn_ble_vsc_cb.extended_scan_support = vendor_capabilities.extended_scan_support_;
678 btm_cb.cmn_ble_vsc_cb.debug_logging_supported = vendor_capabilities.debug_logging_supported_;
679
680 btm_cb.cmn_ble_vsc_cb.le_address_generation_offloading_support =
681 vendor_capabilities.le_address_generation_offloading_support_;
682 btm_cb.cmn_ble_vsc_cb.a2dp_source_offload_capability_mask =
683 vendor_capabilities.a2dp_source_offload_capability_mask_;
684 btm_cb.cmn_ble_vsc_cb.quality_report_support =
685 vendor_capabilities.bluetooth_quality_report_support_;
686 btm_cb.cmn_ble_vsc_cb.dynamic_audio_buffer_support =
687 vendor_capabilities.dynamic_audio_buffer_support_;
688 btm_cb.cmn_ble_vsc_cb.a2dp_offload_v2_support = vendor_capabilities.a2dp_offload_v2_support_;
689
690 if (vendor_capabilities.dynamic_audio_buffer_support_) {
691 std::array<bluetooth::hci::DynamicAudioBufferCodecCapability, BTM_CODEC_TYPE_MAX_RECORDS>
692 capabilities = GetController()->GetDabCodecCapabilities();
693
694 for (size_t i = 0; i < capabilities.size(); i++) {
695 btm_cb.dynamic_audio_buffer_cb[i].default_buffer_time = capabilities[i].default_time_ms_;
696 btm_cb.dynamic_audio_buffer_cb[i].maximum_buffer_time = capabilities[i].maximum_time_ms_;
697 btm_cb.dynamic_audio_buffer_cb[i].minimum_buffer_time = capabilities[i].minimum_time_ms_;
698 }
699 }
700
701 if (btm_cb.cmn_ble_vsc_cb.filter_support == 1 &&
702 GetController()->GetLocalVersionInformation().manufacturer_name_ == LMP_COMPID_QTI) {
703 // QTI controller, TDS data filter are supported by default.
704 btm_cb.cmn_ble_vsc_cb.adv_filter_extended_features_mask = 0x01;
705 } else {
706 btm_cb.cmn_ble_vsc_cb.adv_filter_extended_features_mask = 0x00;
707 }
708
709 log::verbose("irk={}, ADV ins:{}, rpa={}, ener={}, ext_scan={}",
710 btm_cb.cmn_ble_vsc_cb.max_irk_list_sz, btm_cb.cmn_ble_vsc_cb.adv_inst_max,
711 btm_cb.cmn_ble_vsc_cb.rpa_offloading, btm_cb.cmn_ble_vsc_cb.energy_support,
712 btm_cb.cmn_ble_vsc_cb.extended_scan_support);
713
714 if (btm_cb.cmn_ble_vsc_cb.max_filter > 0) {
715 btm_ble_adv_filter_init();
716 }
717
718 /* VS capability included and non-4.2 device */
719 if (GetController()->SupportsBle() && GetController()->SupportsBlePrivacy() &&
720 btm_cb.cmn_ble_vsc_cb.max_irk_list_sz > 0 && GetController()->GetLeResolvingListSize() == 0) {
721 btm_ble_resolving_list_init(btm_cb.cmn_ble_vsc_cb.max_irk_list_sz);
722 }
723
724 if (p_vsc_cback != NULL) {
725 p_vsc_cback(tHCI_STATUS::HCI_SUCCESS);
726 }
727 }
728
729 /*******************************************************************************
730 *
731 * Function BTM_BleConfigPrivacy
732 *
733 * Description This function is called to enable or disable the privacy in
734 * LE channel of the local device.
735 *
736 * Parameters privacy_mode: privacy mode on or off.
737 *
738 * Returns bool privacy mode set success; otherwise failed.
739 *
740 ******************************************************************************/
BTM_BleConfigPrivacy(bool privacy_mode)741 bool BTM_BleConfigPrivacy(bool privacy_mode) {
742 log::warn("{}", (int)privacy_mode);
743
744 /* if LE is not supported, return error */
745 if (!bluetooth::shim::GetController()->SupportsBle()) {
746 return false;
747 }
748
749 tGAP_BLE_ATTR_VALUE gap_ble_attr_value;
750 gap_ble_attr_value.addr_resolution = 0;
751 if (!privacy_mode) /* if privacy disabled, always use public address */
752 {
753 btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type = BLE_ADDR_PUBLIC;
754 /* This is a Floss only flag. Allow host use random address when privacy
755 * mode is not enabled by setting the sysprop true */
756 if (com::android::bluetooth::flags::floss_separate_host_privacy_and_llprivacy()) {
757 if (osi_property_get_bool(PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED, privacy_mode)) {
758 btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type = BLE_ADDR_RANDOM;
759 }
760 }
761 btm_cb.ble_ctr_cb.privacy_mode = BTM_PRIVACY_NONE;
762 } else /* privacy is turned on*/
763 {
764 /* always set host random address, used when privacy 1.1 or priavcy 1.2 is
765 * disabled */
766 btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type = BLE_ADDR_RANDOM;
767 /* This is a Floss only flag. Allow host use public address when privacy
768 * mode is enabled by setting the sysprop false */
769 if (com::android::bluetooth::flags::floss_separate_host_privacy_and_llprivacy()) {
770 /* use public address if own address privacy is false in sysprop */
771 if (!osi_property_get_bool(PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED, privacy_mode)) {
772 btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type = BLE_ADDR_PUBLIC;
773 }
774 }
775
776 /* 4.2 controller only allow privacy 1.2 or mixed mode, resolvable private
777 * address in controller */
778 if (bluetooth::shim::GetController()->SupportsBlePrivacy()) {
779 gap_ble_attr_value.addr_resolution = 1;
780 btm_cb.ble_ctr_cb.privacy_mode = BTM_PRIVACY_1_2;
781 } else { /* 4.1/4.0 controller */
782 btm_cb.ble_ctr_cb.privacy_mode = BTM_PRIVACY_1_1;
783 }
784 }
785 log::verbose("privacy_mode: {} own_addr_type: {}", btm_cb.ble_ctr_cb.privacy_mode,
786 btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type);
787
788 GAP_BleAttrDBUpdate(GATT_UUID_GAP_CENTRAL_ADDR_RESOL, &gap_ble_attr_value);
789
790 bluetooth::shim::ACL_ConfigureLePrivacy(privacy_mode);
791 return true;
792 }
793
794 /*******************************************************************************
795 *
796 * Function BTM_BleLocalPrivacyEnabled
797 *
798 * Description Checks if local device supports private address
799 *
800 * Returns Return true if local privacy is enabled else false
801 *
802 ******************************************************************************/
BTM_BleLocalPrivacyEnabled(void)803 bool BTM_BleLocalPrivacyEnabled(void) { return btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE; }
804
is_resolving_list_bit_set(void * data,void *)805 static bool is_resolving_list_bit_set(void* data, void* /* context */) {
806 tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
807
808 if ((p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) != 0) {
809 return false;
810 }
811
812 return true;
813 }
814
815 /*******************************************************************************
816 * PAST and Periodic Sync helper functions
817 ******************************************************************************/
818
sync_queue_add(sync_node_t * p_param)819 static void sync_queue_add(sync_node_t* p_param) {
820 std::unique_lock<std::mutex> guard(sync_queue_mutex_);
821 if (!sync_queue) {
822 log::info("allocating sync queue");
823 sync_queue = list_new(osi_free);
824 log::assert_that(sync_queue != NULL, "assert failed: sync_queue != NULL");
825 }
826
827 // Validity check
828 log::assert_that(list_length(sync_queue) < MAX_SYNC_TRANSACTION,
829 "assert failed: list_length(sync_queue) < MAX_SYNC_TRANSACTION");
830 sync_node_t* p_node = (sync_node_t*)osi_malloc(sizeof(sync_node_t));
831 *p_node = *p_param;
832 list_append(sync_queue, p_node);
833 }
834
sync_queue_advance()835 static void sync_queue_advance() {
836 log::debug("");
837 std::unique_lock<std::mutex> guard(sync_queue_mutex_);
838
839 if (sync_queue && !list_is_empty(sync_queue)) {
840 sync_node_t* p_head = (sync_node_t*)list_front(sync_queue);
841 log::info("queue_advance");
842 list_remove(sync_queue, p_head);
843 }
844 }
845
sync_queue_cleanup(remove_sync_node_t * p_param)846 static void sync_queue_cleanup(remove_sync_node_t* p_param) {
847 std::unique_lock<std::mutex> guard(sync_queue_mutex_);
848 if (!sync_queue) {
849 return;
850 }
851
852 sync_node_t* sync_request;
853 const list_node_t* node = list_begin(sync_queue);
854 while (node && node != list_end(sync_queue)) {
855 sync_request = (sync_node_t*)list_node(node);
856 node = list_next(node);
857 if (sync_request->sid == p_param->sid && sync_request->address == p_param->address) {
858 log::info("removing connection request SID={:04X}, bd_addr={}, busy={}", sync_request->sid,
859 sync_request->address, sync_request->busy);
860 list_remove(sync_queue, sync_request);
861 }
862 }
863 }
864
btm_ble_start_sync_request(uint8_t sid,RawAddress addr,uint16_t skip,uint16_t timeout)865 void btm_ble_start_sync_request(uint8_t sid, RawAddress addr, uint16_t skip, uint16_t timeout) {
866 tBLE_ADDR_TYPE address_type = BLE_ADDR_RANDOM;
867 tINQ_DB_ENT* p_i = btm_inq_db_find(addr);
868 if (p_i) {
869 address_type = p_i->inq_info.results.ble_addr_type; // Random
870 }
871 btm_random_pseudo_to_identity_addr(&addr, &address_type);
872 address_type &= ~BLE_ADDR_TYPE_ID_BIT;
873 uint8_t options = 0;
874 uint8_t cte_type = 7;
875 int index = btm_ble_get_psync_index(sid, addr);
876
877 if (index == MAX_SYNC_TRANSACTION) {
878 log::error("Failed to get sync transfer index");
879 return;
880 }
881
882 tBTM_BLE_PERIODIC_SYNC* p = &btm_ble_pa_sync_cb.p_sync[index];
883 p->sync_state = PERIODIC_SYNC_PENDING;
884
885 if (BleScanningManager::IsInitialized()) {
886 BleScanningManager::Get()->PeriodicScanStart(options, sid, address_type, addr, skip, timeout,
887 cte_type);
888 }
889
890 alarm_set(sync_timeout_alarm, SYNC_TIMEOUT, btm_ble_start_sync_timeout, NULL);
891 }
892
btm_queue_sync_next()893 static void btm_queue_sync_next() {
894 if (!sync_queue || list_is_empty(sync_queue)) {
895 log::debug("sync_queue empty");
896 return;
897 }
898
899 sync_node_t* p_head = (sync_node_t*)list_front(sync_queue);
900
901 log::info("executing sync request SID={:04X}, bd_addr={}", p_head->sid, p_head->address);
902 if (p_head->busy) {
903 log::debug("BUSY");
904 return;
905 }
906
907 p_head->busy = true;
908 alarm_cancel(sync_timeout_alarm);
909 btm_ble_start_sync_request(p_head->sid, p_head->address, p_head->skip, p_head->timeout);
910 }
911
btm_ble_sync_queue_handle(uint16_t event,char * param)912 static void btm_ble_sync_queue_handle(uint16_t event, char* param) {
913 switch (event) {
914 case BTM_QUEUE_SYNC_REQ_EVT:
915 log::debug("BTIF_QUEUE_SYNC_REQ_EVT");
916 sync_queue_add((sync_node_t*)param);
917 break;
918 case BTM_QUEUE_SYNC_ADVANCE_EVT:
919 log::debug("BTIF_QUEUE_ADVANCE_EVT");
920 sync_queue_advance();
921 break;
922 case BTM_QUEUE_SYNC_CLEANUP_EVT:
923 sync_queue_cleanup((remove_sync_node_t*)param);
924 return;
925 }
926 btm_queue_sync_next();
927 }
928
btm_sync_queue_advance()929 static void btm_sync_queue_advance() {
930 log::debug("");
931 btm_ble_sync_queue_handle(BTM_QUEUE_SYNC_ADVANCE_EVT, nullptr);
932 }
933
btm_ble_start_sync_timeout(void *)934 static void btm_ble_start_sync_timeout(void* /* data */) {
935 log::debug("");
936 sync_node_t* p_head = (sync_node_t*)list_front(sync_queue);
937 uint8_t adv_sid = p_head->sid;
938 RawAddress address = p_head->address;
939
940 int index = btm_ble_get_psync_index(adv_sid, address);
941
942 if (index == MAX_SYNC_TRANSACTION) {
943 log::error("Failed to get sync transfer index");
944 return;
945 }
946
947 tBTM_BLE_PERIODIC_SYNC* p = &btm_ble_pa_sync_cb.p_sync[index];
948
949 if (BleScanningManager::IsInitialized()) {
950 BleScanningManager::Get()->PeriodicScanCancelStart();
951 }
952 p->sync_start_cb.Run(0x3C, 0, p->sid, 0, p->remote_bda, 0, 0);
953
954 p->sync_state = PERIODIC_SYNC_IDLE;
955 p->in_use = false;
956 p->remote_bda = RawAddress::kEmpty;
957 p->sid = 0;
958 p->sync_handle = 0;
959 p->in_use = false;
960 }
961
btm_ble_get_psync_index_from_handle(uint16_t handle)962 static int btm_ble_get_psync_index_from_handle(uint16_t handle) {
963 int i;
964 for (i = 0; i < MAX_SYNC_TRANSACTION; i++) {
965 if (btm_ble_pa_sync_cb.p_sync[i].sync_handle == handle &&
966 btm_ble_pa_sync_cb.p_sync[i].sync_state == PERIODIC_SYNC_ESTABLISHED) {
967 log::debug("found index at {}", i);
968 return i;
969 }
970 }
971 return i;
972 }
973
btm_ble_get_psync_index(uint8_t adv_sid,RawAddress addr)974 static int btm_ble_get_psync_index(uint8_t adv_sid, RawAddress addr) {
975 int i;
976 for (i = 0; i < MAX_SYNC_TRANSACTION; i++) {
977 if (btm_ble_pa_sync_cb.p_sync[i].sid == adv_sid &&
978 btm_ble_pa_sync_cb.p_sync[i].remote_bda == addr) {
979 log::debug("found index at {}", i);
980 return i;
981 }
982 }
983 return i;
984 }
985
986 /*******************************************************************************
987 *
988 * Function btm_ble_periodic_adv_sync_established
989 *
990 * Description Periodic Adv Sync Established callback from controller when
991 & sync to PA is established
992 *
993 *
994 ******************************************************************************/
btm_ble_periodic_adv_sync_established(uint8_t status,uint16_t sync_handle,uint8_t adv_sid,uint8_t address_type,const RawAddress & addr,uint8_t phy,uint16_t interval,uint8_t adv_clock_accuracy)995 void btm_ble_periodic_adv_sync_established(uint8_t status, uint16_t sync_handle, uint8_t adv_sid,
996 uint8_t address_type, const RawAddress& addr,
997 uint8_t phy, uint16_t interval,
998 uint8_t adv_clock_accuracy) {
999 log::debug(
1000 "[PSync]: status={}, sync_handle={}, s_id={}, addr_type={}, "
1001 "adv_phy={},adv_interval={}, clock_acc={}",
1002 status, sync_handle, adv_sid, address_type, phy, interval, adv_clock_accuracy);
1003
1004 /*if (param_len != ADV_SYNC_ESTB_EVT_LEN) {
1005 log::error("[PSync]Invalid event length");
1006 STREAM_TO_UINT8(status, param);
1007 if (status == tBTM_STATUS::BTM_SUCCESS) {
1008 STREAM_TO_UINT16(sync_handle, param);
1009 //btsnd_hcic_ble_terminate_periodic_sync(sync_handle);
1010 if (BleScanningManager::IsInitialized()) {
1011 BleScanningManager::Get()->PeriodicScanTerminate(sync_handle);
1012 }
1013 return;
1014 }
1015 }*/
1016
1017 RawAddress bda = addr;
1018 alarm_cancel(sync_timeout_alarm);
1019
1020 tBLE_ADDR_TYPE ble_addr_type = to_ble_addr_type(address_type);
1021 if (ble_addr_type & BLE_ADDR_TYPE_ID_BIT) {
1022 btm_identity_addr_to_random_pseudo(&bda, &ble_addr_type, true);
1023 }
1024 int index = btm_ble_get_psync_index(adv_sid, bda);
1025 if (index == MAX_SYNC_TRANSACTION) {
1026 log::warn("[PSync]: Invalid index for sync established");
1027 if (status == 0) {
1028 log::warn("Terminate sync");
1029 if (BleScanningManager::IsInitialized()) {
1030 BleScanningManager::Get()->PeriodicScanTerminate(sync_handle);
1031 }
1032 }
1033 btm_sync_queue_advance();
1034 return;
1035 }
1036 tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index];
1037 ps->sync_handle = sync_handle;
1038 ps->sync_state = PERIODIC_SYNC_ESTABLISHED;
1039 ps->sync_start_cb.Run(status, sync_handle, adv_sid, from_ble_addr_type(ble_addr_type), bda, phy,
1040 interval);
1041 btm_sync_queue_advance();
1042 }
1043
1044 /*******************************************************************************
1045 *
1046 * Function btm_ble_periodic_adv_report
1047 *
1048 * Description This callback is received when controller estalishes sync
1049 * to a PA requested from host
1050 *
1051 ******************************************************************************/
btm_ble_periodic_adv_report(uint16_t sync_handle,uint8_t tx_power,int8_t rssi,uint8_t cte_type,uint8_t data_status,uint8_t data_len,const uint8_t * periodic_data)1052 void btm_ble_periodic_adv_report(uint16_t sync_handle, uint8_t tx_power, int8_t rssi,
1053 uint8_t cte_type, uint8_t data_status, uint8_t data_len,
1054 const uint8_t* periodic_data) {
1055 log::debug(
1056 "[PSync]: sync_handle = {}, tx_power = {}, rssi = {},cte_type = {}, "
1057 "data_status = {}, data_len = {}",
1058 sync_handle, tx_power, rssi, cte_type, data_status, data_len);
1059
1060 std::vector<uint8_t> data;
1061 for (int i = 0; i < data_len; i++) {
1062 data.push_back(periodic_data[i]);
1063 }
1064 int index = btm_ble_get_psync_index_from_handle(sync_handle);
1065 if (index == MAX_SYNC_TRANSACTION) {
1066 log::error("[PSync]: index not found for handle {}", sync_handle);
1067 return;
1068 }
1069 tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index];
1070 log::debug("[PSync]: invoking callback");
1071 ps->sync_report_cb.Run(sync_handle, tx_power, rssi, data_status, data);
1072 }
1073
1074 /*******************************************************************************
1075 *
1076 * Function btm_ble_periodic_adv_sync_lost
1077 *
1078 * Description This callback is received when sync to PA is lost
1079 *
1080 ******************************************************************************/
btm_ble_periodic_adv_sync_lost(uint16_t sync_handle)1081 void btm_ble_periodic_adv_sync_lost(uint16_t sync_handle) {
1082 log::debug("[PSync]: sync_handle = {}", sync_handle);
1083
1084 int index = btm_ble_get_psync_index_from_handle(sync_handle);
1085 if (index == MAX_SYNC_TRANSACTION) {
1086 log::error("[PSync]: index not found for handle {}", sync_handle);
1087 return;
1088 }
1089 tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index];
1090 ps->sync_lost_cb.Run(sync_handle);
1091
1092 ps->in_use = false;
1093 ps->sid = 0;
1094 ps->sync_handle = 0;
1095 ps->sync_state = PERIODIC_SYNC_IDLE;
1096 ps->remote_bda = RawAddress::kEmpty;
1097 }
1098
1099 /*******************************************************************************
1100 *
1101 * Function btm_set_conn_mode_adv_init_addr
1102 *
1103 * Description set initiator address type and local address type based on
1104 * adv mode.
1105 *
1106 *
1107 ******************************************************************************/
btm_set_conn_mode_adv_init_addr(RawAddress & p_peer_addr_ptr,tBLE_ADDR_TYPE * p_peer_addr_type,tBLE_ADDR_TYPE * p_own_addr_type)1108 static uint8_t btm_set_conn_mode_adv_init_addr(RawAddress& p_peer_addr_ptr,
1109 tBLE_ADDR_TYPE* p_peer_addr_type,
1110 tBLE_ADDR_TYPE* p_own_addr_type) {
1111 uint8_t evt_type;
1112 tBTM_SEC_DEV_REC* p_dev_rec;
1113
1114 if (btm_cb.ble_ctr_cb.inq_var.connectable_mode == BTM_BLE_NON_CONNECTABLE) {
1115 if (btm_cb.ble_ctr_cb.inq_var.scan_rsp) {
1116 evt_type = BTM_BLE_DISCOVER_EVT;
1117 } else {
1118 evt_type = BTM_BLE_NON_CONNECT_EVT;
1119 }
1120 } else {
1121 evt_type = BTM_BLE_CONNECT_EVT;
1122 }
1123
1124 if (evt_type == BTM_BLE_CONNECT_EVT) {
1125 log::assert_that(p_peer_addr_type != nullptr, "assert failed: p_peer_addr_type != nullptr");
1126 const tBLE_BD_ADDR ble_bd_addr = {
1127 .type = *p_peer_addr_type,
1128 .bda = p_peer_addr_ptr,
1129 };
1130 log::debug("Received BLE connect event {}", ble_bd_addr);
1131
1132 evt_type = btm_cb.ble_ctr_cb.inq_var.directed_conn;
1133
1134 if (static_cast<std::underlying_type_t<tBTM_BLE_EVT>>(
1135 btm_cb.ble_ctr_cb.inq_var.directed_conn) == BTM_BLE_CONNECT_DIR_EVT ||
1136 static_cast<std::underlying_type_t<tBTM_BLE_EVT>>(
1137 btm_cb.ble_ctr_cb.inq_var.directed_conn) == BTM_BLE_CONNECT_LO_DUTY_DIR_EVT) {
1138 /* for privacy 1.2, convert peer address as static, own address set as ID
1139 * addr */
1140 if (btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_1_2 ||
1141 btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_MIXED) {
1142 /* only do so for bonded device */
1143 if ((p_dev_rec = btm_find_or_alloc_dev(btm_cb.ble_ctr_cb.inq_var.direct_bda.bda)) != NULL &&
1144 p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) {
1145 p_peer_addr_ptr = p_dev_rec->ble.identity_address_with_type.bda;
1146 *p_peer_addr_type = p_dev_rec->ble.identity_address_with_type.type;
1147 *p_own_addr_type = BLE_ADDR_RANDOM_ID;
1148 return evt_type;
1149 }
1150 /* otherwise fall though as normal directed adv */
1151 }
1152 /* direct adv mode does not have privacy, if privacy is not enabled */
1153 *p_peer_addr_type = btm_cb.ble_ctr_cb.inq_var.direct_bda.type;
1154 p_peer_addr_ptr = btm_cb.ble_ctr_cb.inq_var.direct_bda.bda;
1155 return evt_type;
1156 }
1157 }
1158
1159 /* undirect adv mode or non-connectable mode*/
1160 /* when privacy 1.2 privacy only mode is used, or mixed mode */
1161 if ((btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_1_2 &&
1162 btm_cb.ble_ctr_cb.inq_var.afp != AP_SCAN_CONN_ALL) ||
1163 btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_MIXED) {
1164 list_node_t* n = list_foreach(btm_sec_cb.sec_dev_rec, is_resolving_list_bit_set, NULL);
1165 if (n) {
1166 /* if enhanced privacy is required, set Identity address and matching IRK
1167 * peer */
1168 tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(list_node(n));
1169 p_peer_addr_ptr = p_dev_rec->ble.identity_address_with_type.bda;
1170 *p_peer_addr_type = p_dev_rec->ble.identity_address_with_type.type;
1171
1172 *p_own_addr_type = BLE_ADDR_RANDOM_ID;
1173 } else {
1174 /* resolving list is empty, not enabled */
1175 *p_own_addr_type = BLE_ADDR_RANDOM;
1176 }
1177 } else if (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE) {
1178 /* privacy 1.1, or privacy 1.2, general discoverable/connectable mode, disable privacy in */
1179 /* controller fall back to host based privacy */
1180 *p_own_addr_type = BLE_ADDR_RANDOM;
1181 }
1182
1183 /* if no privacy,do not set any peer address,*/
1184 /* local address type go by global privacy setting */
1185 return evt_type;
1186 }
1187
1188 /*******************************************************************************
1189 *
1190 * Function btm_ble_select_adv_interval
1191 *
1192 * Description select adv interval based on device mode
1193 *
1194 * Returns void
1195 *
1196 ******************************************************************************/
btm_ble_select_adv_interval(uint8_t evt_type,uint16_t * p_adv_int_min,uint16_t * p_adv_int_max)1197 static void btm_ble_select_adv_interval(uint8_t evt_type, uint16_t* p_adv_int_min,
1198 uint16_t* p_adv_int_max) {
1199 switch (evt_type) {
1200 case BTM_BLE_CONNECT_EVT:
1201 case BTM_BLE_CONNECT_LO_DUTY_DIR_EVT:
1202 *p_adv_int_min = *p_adv_int_max = BTM_BLE_GAP_ADV_FAST_INT_1;
1203 break;
1204
1205 case BTM_BLE_NON_CONNECT_EVT:
1206 case BTM_BLE_DISCOVER_EVT:
1207 *p_adv_int_min = *p_adv_int_max = BTM_BLE_GAP_ADV_FAST_INT_2;
1208 break;
1209
1210 /* connectable directed event */
1211 case BTM_BLE_CONNECT_DIR_EVT:
1212 *p_adv_int_min = BTM_BLE_GAP_ADV_DIR_MIN_INT;
1213 *p_adv_int_max = BTM_BLE_GAP_ADV_DIR_MAX_INT;
1214 break;
1215
1216 default:
1217 *p_adv_int_min = *p_adv_int_max = BTM_BLE_GAP_ADV_SLOW_INT;
1218 break;
1219 }
1220 }
1221
1222 /*******************************************************************************
1223 *
1224 * Function btm_ble_update_dmt_flag_bits
1225 *
1226 * Description Obtain updated adv flag value based on connect and
1227 * discoverability mode. Also, setup DMT support value in the
1228 * flag based on whether the controller supports both LE and
1229 * BR/EDR.
1230 *
1231 * Parameters: flag_value (Input / Output) - flag value
1232 * connect_mode (Input) - Connect mode value
1233 * disc_mode (Input) - discoverability mode
1234 *
1235 * Returns void
1236 *
1237 ******************************************************************************/
btm_ble_update_dmt_flag_bits(uint8_t * adv_flag_value,const uint16_t connect_mode,const uint16_t disc_mode)1238 void btm_ble_update_dmt_flag_bits(uint8_t* adv_flag_value, const uint16_t connect_mode,
1239 const uint16_t disc_mode) {
1240 /* BR/EDR non-discoverable , non-connectable */
1241 if ((disc_mode & BTM_DISCOVERABLE_MASK) == 0 && (connect_mode & BTM_CONNECTABLE_MASK) == 0) {
1242 *adv_flag_value |= BTM_BLE_BREDR_NOT_SPT;
1243 } else {
1244 *adv_flag_value &= ~BTM_BLE_BREDR_NOT_SPT;
1245 }
1246
1247 /* if local controller support, mark both controller and host support in flag
1248 */
1249 if (bluetooth::shim::GetController()->SupportsSimultaneousLeBrEdr()) {
1250 *adv_flag_value |= (BTM_BLE_DMT_CONTROLLER_SPT | BTM_BLE_DMT_HOST_SPT);
1251 } else {
1252 *adv_flag_value &= ~(BTM_BLE_DMT_CONTROLLER_SPT | BTM_BLE_DMT_HOST_SPT);
1253 }
1254 }
1255
1256 /*******************************************************************************
1257 *
1258 * Function btm_ble_set_adv_flag
1259 *
1260 * Description Set adv flag in adv data.
1261 *
1262 * Parameters: connect_mode (Input)- Connect mode value
1263 * disc_mode (Input) - discoverability mode
1264 *
1265 * Returns void
1266 *
1267 ******************************************************************************/
btm_ble_set_adv_flag(uint16_t connect_mode,uint16_t disc_mode)1268 void btm_ble_set_adv_flag(uint16_t connect_mode, uint16_t disc_mode) {
1269 uint8_t flag = 0, old_flag = 0;
1270 tBTM_BLE_LOCAL_ADV_DATA* p_adv_data = &btm_cb.ble_ctr_cb.inq_var.adv_data;
1271
1272 if (p_adv_data->p_flags != NULL) {
1273 flag = old_flag = *(p_adv_data->p_flags);
1274 }
1275
1276 btm_ble_update_dmt_flag_bits(&flag, connect_mode, disc_mode);
1277
1278 log::info("disc_mode {:04x}", disc_mode);
1279 /* update discoverable flag */
1280 if (disc_mode & BTM_BLE_LIMITED_DISCOVERABLE) {
1281 flag &= ~BTM_BLE_GEN_DISC_FLAG;
1282 flag |= BTM_BLE_LIMIT_DISC_FLAG;
1283 } else if (disc_mode & BTM_BLE_GENERAL_DISCOVERABLE) {
1284 flag |= BTM_BLE_GEN_DISC_FLAG;
1285 flag &= ~BTM_BLE_LIMIT_DISC_FLAG;
1286 } else /* remove all discoverable flags */
1287 {
1288 flag &= ~(BTM_BLE_LIMIT_DISC_FLAG | BTM_BLE_GEN_DISC_FLAG);
1289 }
1290
1291 if (flag != old_flag) {
1292 btm_ble_update_adv_flag(flag);
1293 }
1294 }
1295 /*******************************************************************************
1296 *
1297 * Function btm_ble_set_discoverability
1298 *
1299 * Description This function is called to set BLE discoverable mode.
1300 *
1301 * Parameters: combined_mode: discoverability mode.
1302 *
1303 * Returns tBTM_STATUS::BTM_SUCCESS is status set successfully; otherwise failure.
1304 *
1305 ******************************************************************************/
btm_ble_set_discoverability(uint16_t combined_mode)1306 tBTM_STATUS btm_ble_set_discoverability(uint16_t combined_mode) {
1307 tBTM_LE_RANDOM_CB* p_addr_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
1308 uint16_t mode = (combined_mode & BTM_BLE_DISCOVERABLE_MASK);
1309 uint8_t new_mode = BTM_BLE_ADV_ENABLE;
1310 uint8_t evt_type;
1311 tBTM_STATUS status = tBTM_STATUS::BTM_SUCCESS;
1312 RawAddress address = RawAddress::kEmpty;
1313 tBLE_ADDR_TYPE init_addr_type = BLE_ADDR_PUBLIC, own_addr_type = p_addr_cb->own_addr_type;
1314 uint16_t adv_int_min, adv_int_max;
1315
1316 log::verbose("mode=0x{:0x} combined_mode=0x{:x}", mode, combined_mode);
1317
1318 /*** Check mode parameter ***/
1319 if (mode > BTM_BLE_MAX_DISCOVERABLE) {
1320 return tBTM_STATUS::BTM_ILLEGAL_VALUE;
1321 }
1322
1323 btm_cb.ble_ctr_cb.inq_var.discoverable_mode = mode;
1324
1325 evt_type = btm_set_conn_mode_adv_init_addr(address, &init_addr_type, &own_addr_type);
1326
1327 if (btm_cb.ble_ctr_cb.inq_var.connectable_mode == BTM_BLE_NON_CONNECTABLE &&
1328 mode == BTM_BLE_NON_DISCOVERABLE) {
1329 new_mode = BTM_BLE_ADV_DISABLE;
1330 }
1331
1332 btm_ble_select_adv_interval(evt_type, &adv_int_min, &adv_int_max);
1333
1334 alarm_cancel(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer);
1335
1336 /* update adv params if start advertising */
1337 log::verbose("evt_type=0x{:x} p-cb->evt_type=0x{:x}", evt_type,
1338 btm_cb.ble_ctr_cb.inq_var.evt_type);
1339
1340 if (new_mode == BTM_BLE_ADV_ENABLE) {
1341 btm_ble_set_adv_flag(btm_cb.btm_inq_vars.connectable_mode, combined_mode);
1342
1343 if (evt_type != btm_cb.ble_ctr_cb.inq_var.evt_type ||
1344 btm_cb.ble_ctr_cb.inq_var.adv_addr_type != own_addr_type ||
1345 !btm_cb.ble_ctr_cb.inq_var.fast_adv_on) {
1346 btm_ble_stop_adv();
1347
1348 /* update adv params */
1349 btsnd_hcic_ble_write_adv_params(
1350 adv_int_min, adv_int_max, evt_type, own_addr_type, init_addr_type, address,
1351 btm_cb.ble_ctr_cb.inq_var.adv_chnl_map, btm_cb.ble_ctr_cb.inq_var.afp);
1352 btm_cb.ble_ctr_cb.inq_var.evt_type = evt_type;
1353 btm_cb.ble_ctr_cb.inq_var.adv_addr_type = own_addr_type;
1354 }
1355 }
1356
1357 if (status == tBTM_STATUS::BTM_SUCCESS && btm_cb.ble_ctr_cb.inq_var.adv_mode != new_mode) {
1358 if (new_mode == BTM_BLE_ADV_ENABLE) {
1359 status = btm_ble_start_adv();
1360 } else {
1361 status = btm_ble_stop_adv();
1362 }
1363 }
1364
1365 if (btm_cb.ble_ctr_cb.inq_var.adv_mode == BTM_BLE_ADV_ENABLE) {
1366 btm_cb.ble_ctr_cb.inq_var.fast_adv_on = true;
1367 /* start initial GAP mode adv timer */
1368 alarm_set_on_mloop(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer, BTM_BLE_GAP_FAST_ADV_TIMEOUT_MS,
1369 btm_ble_fast_adv_timer_timeout, NULL);
1370 }
1371
1372 /* set up stop advertising timer */
1373 if (status == tBTM_STATUS::BTM_SUCCESS && mode == BTM_BLE_LIMITED_DISCOVERABLE) {
1374 log::verbose("start timer for limited disc mode duration={} ms", BTM_BLE_GAP_LIM_TIMEOUT_MS);
1375 /* start Tgap(lim_timeout) */
1376 alarm_set_on_mloop(btm_cb.ble_ctr_cb.inq_var.inquiry_timer, BTM_BLE_GAP_LIM_TIMEOUT_MS,
1377 btm_ble_inquiry_timer_gap_limited_discovery_timeout, NULL);
1378 }
1379 return status;
1380 }
1381
1382 /*******************************************************************************
1383 *
1384 * Function btm_ble_set_connectability
1385 *
1386 * Description This function is called to set BLE connectability mode.
1387 *
1388 * Parameters: combined_mode: connectability mode.
1389 *
1390 * Returns tBTM_STATUS::BTM_SUCCESS is status set successfully; otherwise failure.
1391 *
1392 ******************************************************************************/
btm_ble_set_connectability(uint16_t combined_mode)1393 tBTM_STATUS btm_ble_set_connectability(uint16_t combined_mode) {
1394 tBTM_LE_RANDOM_CB* p_addr_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
1395 uint16_t mode = (combined_mode & BTM_BLE_CONNECTABLE_MASK);
1396 uint8_t new_mode = BTM_BLE_ADV_ENABLE;
1397 uint8_t evt_type;
1398 tBTM_STATUS status = tBTM_STATUS::BTM_SUCCESS;
1399 RawAddress address = RawAddress::kEmpty;
1400 tBLE_ADDR_TYPE peer_addr_type = BLE_ADDR_PUBLIC, own_addr_type = p_addr_cb->own_addr_type;
1401 uint16_t adv_int_min, adv_int_max;
1402
1403 log::verbose("mode=0x{:0x} combined_mode=0x{:x}", mode, combined_mode);
1404
1405 /*** Check mode parameter ***/
1406 if (mode > BTM_BLE_MAX_CONNECTABLE) {
1407 return tBTM_STATUS::BTM_ILLEGAL_VALUE;
1408 }
1409
1410 btm_cb.ble_ctr_cb.inq_var.connectable_mode = mode;
1411
1412 evt_type = btm_set_conn_mode_adv_init_addr(address, &peer_addr_type, &own_addr_type);
1413
1414 if (mode == BTM_BLE_NON_CONNECTABLE &&
1415 btm_cb.ble_ctr_cb.inq_var.discoverable_mode == BTM_BLE_NON_DISCOVERABLE) {
1416 new_mode = BTM_BLE_ADV_DISABLE;
1417 }
1418
1419 btm_ble_select_adv_interval(evt_type, &adv_int_min, &adv_int_max);
1420
1421 alarm_cancel(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer);
1422 /* update adv params if needed */
1423 if (new_mode == BTM_BLE_ADV_ENABLE) {
1424 btm_ble_set_adv_flag(combined_mode, btm_cb.btm_inq_vars.discoverable_mode);
1425 if (btm_cb.ble_ctr_cb.inq_var.evt_type != evt_type ||
1426 btm_cb.ble_ctr_cb.inq_var.adv_addr_type != p_addr_cb->own_addr_type ||
1427 !btm_cb.ble_ctr_cb.inq_var.fast_adv_on) {
1428 btm_ble_stop_adv();
1429
1430 btsnd_hcic_ble_write_adv_params(
1431 adv_int_min, adv_int_max, evt_type, own_addr_type, peer_addr_type, address,
1432 btm_cb.ble_ctr_cb.inq_var.adv_chnl_map, btm_cb.ble_ctr_cb.inq_var.afp);
1433 btm_cb.ble_ctr_cb.inq_var.evt_type = evt_type;
1434 btm_cb.ble_ctr_cb.inq_var.adv_addr_type = own_addr_type;
1435 }
1436 }
1437
1438 /* update advertising mode */
1439 if (status == tBTM_STATUS::BTM_SUCCESS && new_mode != btm_cb.ble_ctr_cb.inq_var.adv_mode) {
1440 if (new_mode == BTM_BLE_ADV_ENABLE) {
1441 status = btm_ble_start_adv();
1442 } else {
1443 status = btm_ble_stop_adv();
1444 }
1445 }
1446
1447 if (btm_cb.ble_ctr_cb.inq_var.adv_mode == BTM_BLE_ADV_ENABLE) {
1448 btm_cb.ble_ctr_cb.inq_var.fast_adv_on = true;
1449 /* start initial GAP mode adv timer */
1450 alarm_set_on_mloop(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer, BTM_BLE_GAP_FAST_ADV_TIMEOUT_MS,
1451 btm_ble_fast_adv_timer_timeout, NULL);
1452 }
1453 return status;
1454 }
1455
btm_send_hci_scan_enable(uint8_t enable,uint8_t filter_duplicates)1456 static void btm_send_hci_scan_enable(uint8_t enable, uint8_t filter_duplicates) {
1457 if (bluetooth::shim::GetController()->SupportsBleExtendedAdvertising()) {
1458 btsnd_hcic_ble_set_extended_scan_enable(enable, filter_duplicates, 0x0000, 0x0000);
1459 } else {
1460 btsnd_hcic_ble_set_scan_enable(enable, filter_duplicates);
1461 }
1462 }
1463
btm_send_hci_set_scan_params(uint8_t scan_type,uint16_t scan_int,uint16_t scan_win,uint8_t scan_phy,tBLE_ADDR_TYPE addr_type_own,uint8_t scan_filter_policy)1464 void btm_send_hci_set_scan_params(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win,
1465 uint8_t scan_phy, tBLE_ADDR_TYPE addr_type_own,
1466 uint8_t scan_filter_policy) {
1467 if (bluetooth::shim::GetController()->SupportsBleExtendedAdvertising()) {
1468 if (com::android::bluetooth::flags::phy_to_native()) {
1469 int phy_cnt = std::bitset<std::numeric_limits<uint8_t>::digits>(scan_phy).count();
1470
1471 scanning_phy_cfg phy_cfgs[phy_cnt];
1472
1473 for (int i = 0; i < phy_cnt; i++) {
1474 phy_cfgs[i].scan_type = scan_type;
1475 phy_cfgs[i].scan_int = scan_int;
1476 phy_cfgs[i].scan_win = scan_win;
1477 }
1478
1479 btsnd_hcic_ble_set_extended_scan_params(addr_type_own, scan_filter_policy, scan_phy,
1480 phy_cfgs);
1481 } else {
1482 scanning_phy_cfg phy_cfg;
1483 phy_cfg.scan_type = scan_type;
1484 phy_cfg.scan_int = scan_int;
1485 phy_cfg.scan_win = scan_win;
1486
1487 btsnd_hcic_ble_set_extended_scan_params(addr_type_own, scan_filter_policy, 1, &phy_cfg);
1488 }
1489 } else {
1490 btsnd_hcic_ble_set_scan_params(scan_type, scan_int, scan_win, addr_type_own,
1491 scan_filter_policy);
1492 }
1493 }
1494
1495 /* Scan filter param config event */
btm_ble_scan_filt_param_cfg_evt(uint8_t,tBTM_BLE_SCAN_COND_OP,tBTM_STATUS btm_status)1496 static void btm_ble_scan_filt_param_cfg_evt(uint8_t /* avbl_space */,
1497 tBTM_BLE_SCAN_COND_OP /* action_type */,
1498 tBTM_STATUS btm_status) {
1499 if (btm_status != tBTM_STATUS::BTM_SUCCESS) {
1500 log::error("{}", btm_status_text(btm_status));
1501 } else {
1502 log::verbose("");
1503 }
1504 }
1505
1506 /*******************************************************************************
1507 *
1508 * Function btm_ble_start_inquiry
1509 *
1510 * Description This function is called to start BLE inquiry procedure.
1511 * If the duration is zero, the periodic inquiry mode is
1512 * cancelled.
1513 *
1514 * Parameters: duration - Duration of inquiry in seconds. With flag
1515 * le_inquiry_duration duration is a multiplier for
1516 * 1.28 seconds.
1517 *
1518 * Returns tBTM_STATUS::BTM_CMD_STARTED if successfully started
1519 * tBTM_STATUS::BTM_BUSY - if an inquiry is already active
1520 *
1521 ******************************************************************************/
btm_ble_start_inquiry(uint8_t duration)1522 tBTM_STATUS btm_ble_start_inquiry(uint8_t duration) {
1523 log::verbose("btm_ble_start_inquiry: inq_active = 0x{:02x}", btm_cb.btm_inq_vars.inq_active);
1524
1525 /* if selective connection is active, or inquiry is already active, reject it
1526 */
1527 if (btm_cb.ble_ctr_cb.is_ble_inquiry_active()) {
1528 log::error("LE Inquiry is active, can not start inquiry");
1529 return tBTM_STATUS::BTM_BUSY;
1530 }
1531
1532 /* Cleanup anything remaining on index 0 */
1533 BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_DELETE, static_cast<tBTM_BLE_PF_FILT_INDEX>(0),
1534 nullptr, base::Bind(btm_ble_scan_filt_param_cfg_evt));
1535
1536 auto adv_filt_param = std::make_unique<btgatt_filt_param_setup_t>();
1537 /* Add an allow-all filter on index 0*/
1538 adv_filt_param->dely_mode = IMMEDIATE_DELY_MODE;
1539 adv_filt_param->feat_seln = ALLOW_ALL_FILTER;
1540 adv_filt_param->filt_logic_type = BTA_DM_BLE_PF_FILT_LOGIC_OR;
1541 adv_filt_param->list_logic_type = BTA_DM_BLE_PF_LIST_LOGIC_OR;
1542 adv_filt_param->rssi_low_thres = LOWEST_RSSI_VALUE;
1543 adv_filt_param->rssi_high_thres = LOWEST_RSSI_VALUE;
1544 BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_ADD, static_cast<tBTM_BLE_PF_FILT_INDEX>(0),
1545 std::move(adv_filt_param),
1546 base::Bind(btm_ble_scan_filt_param_cfg_evt));
1547
1548 uint16_t scan_interval, scan_window;
1549
1550 std::tie(scan_interval, scan_window) = get_low_latency_scan_params();
1551 uint8_t scan_phy = BTM_BLE_DEFAULT_PHYS;
1552
1553 if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) {
1554 cache.ClearAll();
1555 btm_send_hci_set_scan_params(BTM_BLE_SCAN_MODE_ACTI, scan_interval, scan_window, scan_phy,
1556 btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, SP_ADV_ALL);
1557 btm_cb.ble_ctr_cb.inq_var.scan_type = BTM_BLE_SCAN_MODE_ACTI;
1558 btm_ble_start_scan();
1559 } else if ((btm_cb.ble_ctr_cb.inq_var.scan_interval != scan_interval) ||
1560 (btm_cb.ble_ctr_cb.inq_var.scan_window != scan_window)) {
1561 log::verbose("restart LE scan with low latency scan params");
1562 if (!com::android::bluetooth::flags::le_inquiry_duration()) {
1563 btm_cb.ble_ctr_cb.inq_var.scan_interval = scan_interval;
1564 btm_cb.ble_ctr_cb.inq_var.scan_window = scan_window;
1565 }
1566 btm_send_hci_scan_enable(BTM_BLE_SCAN_DISABLE, BTM_BLE_DUPLICATE_ENABLE);
1567 btm_send_hci_set_scan_params(BTM_BLE_SCAN_MODE_ACTI, scan_interval, scan_window, scan_phy,
1568 btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, SP_ADV_ALL);
1569 btm_send_hci_scan_enable(BTM_BLE_SCAN_ENABLE, BTM_BLE_DUPLICATE_DISABLE);
1570 }
1571
1572 btm_cb.btm_inq_vars.inq_active |= BTM_BLE_GENERAL_INQUIRY;
1573 btm_cb.ble_ctr_cb.set_ble_inquiry_active();
1574
1575 log::verbose("btm_ble_start_inquiry inq_active = 0x{:02x}", btm_cb.btm_inq_vars.inq_active);
1576
1577 if (duration != 0) {
1578 /* start inquiry timer */
1579 uint64_t duration_ms =
1580 duration * (com::android::bluetooth::flags::le_inquiry_duration() ? 1280 : 1000);
1581 alarm_set_on_mloop(btm_cb.ble_ctr_cb.inq_var.inquiry_timer, duration_ms,
1582 btm_ble_inquiry_timer_timeout, NULL);
1583 }
1584
1585 btm_cb.neighbor.le_inquiry = {
1586 .start_time_ms = timestamper_in_milliseconds.GetTimestamp(),
1587 .results = 0,
1588 };
1589 BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le inquiry started");
1590
1591 return tBTM_STATUS::BTM_CMD_STARTED;
1592 }
1593
1594 /*******************************************************************************
1595 *
1596 * Function btm_ble_read_remote_name_cmpl
1597 *
1598 * Description This function is called when BLE remote name is received.
1599 *
1600 * Returns void
1601 *
1602 ******************************************************************************/
btm_ble_read_remote_name_cmpl(bool status,const RawAddress & bda,uint16_t length,char * p_name)1603 void btm_ble_read_remote_name_cmpl(bool status, const RawAddress& bda, uint16_t length,
1604 char* p_name) {
1605 tHCI_STATUS hci_status = HCI_SUCCESS;
1606 BD_NAME bd_name;
1607 bd_name_from_char_pointer(bd_name, p_name);
1608
1609 if ((!status) || (length == 0)) {
1610 hci_status = HCI_ERR_HOST_TIMEOUT;
1611 }
1612
1613 get_stack_rnr_interface().btm_process_remote_name(&bda, bd_name, length + 1, hci_status);
1614 btm_sec_rmt_name_request_complete(&bda, (const uint8_t*)p_name, hci_status);
1615 }
1616
1617 /*******************************************************************************
1618 *
1619 * Function btm_ble_read_remote_name
1620 *
1621 * Description This function read remote LE device name using GATT read
1622 * procedure.
1623 *
1624 * Parameters: None.
1625 *
1626 * Returns void
1627 *
1628 ******************************************************************************/
btm_ble_read_remote_name(const RawAddress & remote_bda,tBTM_NAME_CMPL_CB * p_cb)1629 tBTM_STATUS btm_ble_read_remote_name(const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb) {
1630 if (!bluetooth::shim::GetController()->SupportsBle()) {
1631 return tBTM_STATUS::BTM_ERR_PROCESSING;
1632 }
1633
1634 tINQ_DB_ENT* p_i = btm_inq_db_find(remote_bda);
1635 if (p_i && !ble_evt_type_is_connectable(p_i->inq_info.results.ble_evt_type)) {
1636 log::verbose("name request to non-connectable device failed.");
1637 return tBTM_STATUS::BTM_ERR_PROCESSING;
1638 }
1639
1640 /* read remote device name using GATT procedure */
1641 if (btm_cb.rnr.remname_active) {
1642 log::warn("Unable to start GATT RNR procedure for peer:{} busy with peer:{}", remote_bda,
1643 btm_cb.rnr.remname_bda);
1644 return tBTM_STATUS::BTM_BUSY;
1645 }
1646
1647 if (!GAP_BleReadPeerDevName(remote_bda, btm_ble_read_remote_name_cmpl)) {
1648 return tBTM_STATUS::BTM_BUSY;
1649 }
1650
1651 btm_cb.rnr.p_remname_cmpl_cb = p_cb;
1652 btm_cb.rnr.remname_active = true;
1653 btm_cb.rnr.remname_bda = remote_bda;
1654 btm_cb.rnr.remname_dev_type = BT_DEVICE_TYPE_BLE;
1655
1656 alarm_set_on_mloop(btm_cb.rnr.remote_name_timer, BTM_EXT_BLE_RMT_NAME_TIMEOUT_MS,
1657 btm_inq_remote_name_timer_timeout, NULL);
1658
1659 return tBTM_STATUS::BTM_CMD_STARTED;
1660 }
1661
1662 /*******************************************************************************
1663 *
1664 * Function btm_ble_read_remote_appearance_cmpl
1665 *
1666 * Description This function is called when peer's appearance value is received.
1667 *
1668 * Returns void
1669 *
1670 ******************************************************************************/
btm_ble_read_remote_appearance_cmpl(bool status,const RawAddress & bda,uint16_t length,char * data)1671 static void btm_ble_read_remote_appearance_cmpl(bool status, const RawAddress& bda, uint16_t length,
1672 char* data) {
1673 if (!status) {
1674 log::error("Failed to read appearance of {}", bda);
1675 return;
1676 }
1677 if (length != 2 || data == nullptr) {
1678 log::error("Invalid appearance value size {} for {}", length, bda);
1679 return;
1680 }
1681
1682 uint16_t appearance = data[0] + (data[1] << 8);
1683 DEV_CLASS cod = btm_ble_appearance_to_cod(appearance);
1684 log::info("Appearance 0x{:04x}, Class of Device {} found for {}", appearance, dev_class_text(cod),
1685 bda);
1686
1687 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda);
1688 if (p_dev_rec != nullptr) {
1689 p_dev_rec->dev_class = cod;
1690 }
1691 }
1692
1693 /*******************************************************************************
1694 *
1695 * Function btm_ble_read_remote_cod
1696 *
1697 * Description Finds Class of Device by reading GATT appearance characteristic
1698 *
1699 * Parameters: Device address
1700 *
1701 * Returns void
1702 *
1703 ******************************************************************************/
btm_ble_read_remote_cod(const RawAddress & remote_bda)1704 tBTM_STATUS btm_ble_read_remote_cod(const RawAddress& remote_bda) {
1705 if (!bluetooth::shim::GetController()->SupportsBle()) {
1706 return tBTM_STATUS::BTM_ERR_PROCESSING;
1707 }
1708
1709 if (!GAP_BleReadPeerAppearance(remote_bda, btm_ble_read_remote_appearance_cmpl)) {
1710 return tBTM_STATUS::BTM_BUSY;
1711 }
1712
1713 log::verbose("Reading appearance characteristic {}", remote_bda);
1714 return tBTM_STATUS::BTM_CMD_STARTED;
1715 }
1716
1717 /*******************************************************************************
1718 *
1719 * Function btm_ble_cancel_remote_name
1720 *
1721 * Description This function cancel read remote LE device name.
1722 *
1723 * Parameters: None.
1724 *
1725 * Returns void
1726 *
1727 ******************************************************************************/
btm_ble_cancel_remote_name(const RawAddress & remote_bda)1728 bool btm_ble_cancel_remote_name(const RawAddress& remote_bda) {
1729 bool status;
1730
1731 status = GAP_BleCancelReadPeerDevName(remote_bda);
1732
1733 btm_cb.rnr.remname_active = false;
1734 btm_cb.rnr.remname_bda = RawAddress::kEmpty;
1735 btm_cb.rnr.remname_dev_type = BT_DEVICE_TYPE_UNKNOWN;
1736 alarm_cancel(btm_cb.rnr.remote_name_timer);
1737
1738 return status;
1739 }
1740
1741 /*******************************************************************************
1742 *
1743 * Function btm_ble_update_adv_flag
1744 *
1745 * Description This function update the limited discoverable flag in the
1746 * adv data.
1747 *
1748 * Parameters: None.
1749 *
1750 * Returns void
1751 *
1752 ******************************************************************************/
btm_ble_update_adv_flag(uint8_t flag)1753 static void btm_ble_update_adv_flag(uint8_t flag) {
1754 tBTM_BLE_LOCAL_ADV_DATA* p_adv_data = &btm_cb.ble_ctr_cb.inq_var.adv_data;
1755 uint8_t* p;
1756
1757 log::verbose("btm_ble_update_adv_flag new=0x{:x}", flag);
1758
1759 if (p_adv_data->p_flags != NULL) {
1760 log::verbose("btm_ble_update_adv_flag old=0x{:x}", *p_adv_data->p_flags);
1761 *p_adv_data->p_flags = flag;
1762 } else /* no FLAGS in ADV data*/
1763 {
1764 p = (p_adv_data->p_pad == NULL) ? p_adv_data->ad_data : p_adv_data->p_pad;
1765 /* need 3 bytes space to stuff in the flags, if not */
1766 /* erase all written data, just for flags */
1767 if ((BTM_BLE_AD_DATA_LEN - (p - p_adv_data->ad_data)) < 3) {
1768 p = p_adv_data->p_pad = p_adv_data->ad_data;
1769 memset(p_adv_data->ad_data, 0, BTM_BLE_AD_DATA_LEN);
1770 }
1771
1772 *p++ = 2;
1773 *p++ = BTM_BLE_AD_TYPE_FLAG;
1774 p_adv_data->p_flags = p;
1775 *p++ = flag;
1776 p_adv_data->p_pad = p;
1777 }
1778
1779 btsnd_hcic_ble_set_adv_data((uint8_t)(p_adv_data->p_pad - p_adv_data->ad_data),
1780 p_adv_data->ad_data);
1781 p_adv_data->data_mask |= BTM_BLE_AD_BIT_FLAGS;
1782 }
1783
1784 /**
1785 * Check ADV flag to make sure device is discoverable and match the search
1786 * condition
1787 */
btm_ble_is_discoverable(const RawAddress &,std::vector<uint8_t> const & adv_data)1788 static uint8_t btm_ble_is_discoverable(const RawAddress& /* bda */,
1789 std::vector<uint8_t> const& adv_data) {
1790 uint8_t scan_state = BTM_BLE_NOT_SCANNING;
1791
1792 /* for observer, always "discoverable */
1793 if (btm_cb.ble_ctr_cb.is_ble_observe_active()) {
1794 scan_state |= BTM_BLE_OBS_RESULT;
1795 }
1796
1797 if (!adv_data.empty()) {
1798 uint8_t flag = 0;
1799 uint8_t data_len;
1800 const uint8_t* p_flag =
1801 AdvertiseDataParser::GetFieldByType(adv_data, BTM_BLE_AD_TYPE_FLAG, &data_len);
1802 if (p_flag != NULL && data_len != 0) {
1803 flag = *p_flag;
1804
1805 if ((btm_cb.btm_inq_vars.inq_active & BTM_BLE_GENERAL_INQUIRY) &&
1806 (flag & (BTM_BLE_LIMIT_DISC_FLAG | BTM_BLE_GEN_DISC_FLAG)) != 0) {
1807 scan_state |= BTM_BLE_INQ_RESULT;
1808 }
1809 }
1810 }
1811 return scan_state;
1812 }
1813
btm_ble_appearance_to_cod(uint16_t appearance)1814 static DEV_CLASS btm_ble_appearance_to_cod(uint16_t appearance) {
1815 DEV_CLASS dev_class = kDevClassEmpty;
1816
1817 switch (appearance) {
1818 case BTM_BLE_APPEARANCE_GENERIC_PHONE:
1819 dev_class[1] = BTM_COD_MAJOR_PHONE;
1820 dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
1821 break;
1822 case BTM_BLE_APPEARANCE_GENERIC_COMPUTER:
1823 dev_class[1] = BTM_COD_MAJOR_COMPUTER;
1824 dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
1825 break;
1826 case BTM_BLE_APPEARANCE_GENERIC_REMOTE:
1827 dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1828 dev_class[2] = BTM_COD_MINOR_REMOTE_CONTROL;
1829 break;
1830 case BTM_BLE_APPEARANCE_GENERIC_THERMOMETER:
1831 case BTM_BLE_APPEARANCE_THERMOMETER_EAR:
1832 dev_class[1] = BTM_COD_MAJOR_HEALTH;
1833 dev_class[2] = BTM_COD_MINOR_THERMOMETER;
1834 break;
1835 case BTM_BLE_APPEARANCE_GENERIC_HEART_RATE:
1836 case BTM_BLE_APPEARANCE_HEART_RATE_BELT:
1837 dev_class[1] = BTM_COD_MAJOR_HEALTH;
1838 dev_class[2] = BTM_COD_MINOR_HEART_PULSE_MONITOR;
1839 break;
1840 case BTM_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE:
1841 case BTM_BLE_APPEARANCE_BLOOD_PRESSURE_ARM:
1842 case BTM_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST:
1843 dev_class[1] = BTM_COD_MAJOR_HEALTH;
1844 dev_class[2] = BTM_COD_MINOR_BLOOD_MONITOR;
1845 break;
1846 case BTM_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER:
1847 case BTM_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP:
1848 case BTM_BLE_APPEARANCE_PULSE_OXIMETER_WRIST:
1849 dev_class[1] = BTM_COD_MAJOR_HEALTH;
1850 dev_class[2] = BTM_COD_MINOR_PULSE_OXIMETER;
1851 break;
1852 case BTM_BLE_APPEARANCE_GENERIC_GLUCOSE:
1853 dev_class[1] = BTM_COD_MAJOR_HEALTH;
1854 dev_class[2] = BTM_COD_MINOR_GLUCOSE_METER;
1855 break;
1856 case BTM_BLE_APPEARANCE_GENERIC_WEIGHT:
1857 dev_class[1] = BTM_COD_MAJOR_HEALTH;
1858 dev_class[2] = BTM_COD_MINOR_WEIGHING_SCALE;
1859 break;
1860 case BTM_BLE_APPEARANCE_GENERIC_WALKING:
1861 case BTM_BLE_APPEARANCE_WALKING_IN_SHOE:
1862 case BTM_BLE_APPEARANCE_WALKING_ON_SHOE:
1863 case BTM_BLE_APPEARANCE_WALKING_ON_HIP:
1864 dev_class[1] = BTM_COD_MAJOR_HEALTH;
1865 dev_class[2] = BTM_COD_MINOR_STEP_COUNTER;
1866 break;
1867 case BTM_BLE_APPEARANCE_GENERIC_WATCH:
1868 case BTM_BLE_APPEARANCE_SPORTS_WATCH:
1869 dev_class[1] = BTM_COD_MAJOR_WEARABLE;
1870 dev_class[2] = BTM_COD_MINOR_WRIST_WATCH;
1871 break;
1872 case BTM_BLE_APPEARANCE_GENERIC_EYEGLASSES:
1873 dev_class[1] = BTM_COD_MAJOR_WEARABLE;
1874 dev_class[2] = BTM_COD_MINOR_GLASSES;
1875 break;
1876 case BTM_BLE_APPEARANCE_GENERIC_DISPLAY:
1877 dev_class[1] = BTM_COD_MAJOR_IMAGING;
1878 dev_class[2] = BTM_COD_MINOR_DISPLAY;
1879 break;
1880 case BTM_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER:
1881 dev_class[1] = BTM_COD_MAJOR_AUDIO;
1882 dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
1883 break;
1884 case BTM_BLE_APPEARANCE_GENERIC_WEARABLE_AUDIO_DEVICE:
1885 case BTM_BLE_APPEARANCE_WEARABLE_AUDIO_DEVICE_EARBUD:
1886 case BTM_BLE_APPEARANCE_WEARABLE_AUDIO_DEVICE_HEADSET:
1887 case BTM_BLE_APPEARANCE_WEARABLE_AUDIO_DEVICE_HEADPHONES:
1888 case BTM_BLE_APPEARANCE_WEARABLE_AUDIO_DEVICE_NECK_BAND:
1889 dev_class[0] = (BTM_COD_SERVICE_AUDIO | BTM_COD_SERVICE_RENDERING) >> 8;
1890 dev_class[1] = (BTM_COD_MAJOR_AUDIO | BTM_COD_SERVICE_LE_AUDIO);
1891 dev_class[2] = BTM_COD_MINOR_WEARABLE_HEADSET;
1892 break;
1893 case BTM_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER:
1894 case BTM_BLE_APPEARANCE_HID_BARCODE_SCANNER:
1895 case BTM_BLE_APPEARANCE_GENERIC_HID:
1896 dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1897 dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
1898 break;
1899 case BTM_BLE_APPEARANCE_HID_KEYBOARD:
1900 dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1901 dev_class[2] = BTM_COD_MINOR_KEYBOARD;
1902 break;
1903 case BTM_BLE_APPEARANCE_HID_MOUSE:
1904 dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1905 dev_class[2] = BTM_COD_MINOR_POINTING;
1906 break;
1907 case BTM_BLE_APPEARANCE_HID_JOYSTICK:
1908 dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1909 dev_class[2] = BTM_COD_MINOR_JOYSTICK;
1910 break;
1911 case BTM_BLE_APPEARANCE_HID_GAMEPAD:
1912 dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1913 dev_class[2] = BTM_COD_MINOR_GAMEPAD;
1914 break;
1915 case BTM_BLE_APPEARANCE_HID_DIGITIZER_TABLET:
1916 dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1917 dev_class[2] = BTM_COD_MINOR_DIGITIZING_TABLET;
1918 break;
1919 case BTM_BLE_APPEARANCE_HID_CARD_READER:
1920 dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1921 dev_class[2] = BTM_COD_MINOR_CARD_READER;
1922 break;
1923 case BTM_BLE_APPEARANCE_HID_DIGITAL_PEN:
1924 dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1925 dev_class[2] = BTM_COD_MINOR_DIGITAL_PAN;
1926 break;
1927 case BTM_BLE_APPEARANCE_UKNOWN:
1928 case BTM_BLE_APPEARANCE_GENERIC_CLOCK:
1929 case BTM_BLE_APPEARANCE_GENERIC_TAG:
1930 case BTM_BLE_APPEARANCE_GENERIC_KEYRING:
1931 case BTM_BLE_APPEARANCE_GENERIC_CYCLING:
1932 case BTM_BLE_APPEARANCE_CYCLING_COMPUTER:
1933 case BTM_BLE_APPEARANCE_CYCLING_SPEED:
1934 case BTM_BLE_APPEARANCE_CYCLING_CADENCE:
1935 case BTM_BLE_APPEARANCE_CYCLING_POWER:
1936 case BTM_BLE_APPEARANCE_CYCLING_SPEED_CADENCE:
1937 case BTM_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS:
1938 case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION:
1939 case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV:
1940 case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD:
1941 case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV:
1942 default:
1943 dev_class[1] = BTM_COD_MAJOR_UNCLASSIFIED;
1944 dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
1945 };
1946 return dev_class;
1947 }
1948
btm_ble_get_appearance_as_cod(std::vector<uint8_t> const & data)1949 DEV_CLASS btm_ble_get_appearance_as_cod(std::vector<uint8_t> const& data) {
1950 /* Check to see the BLE device has the Appearance UUID in the advertising
1951 * data. If it does then try to convert the appearance value to a class of
1952 * device value Fluoride can use. Otherwise fall back to trying to infer if
1953 * it is a HID device based on the service class.
1954 */
1955 uint8_t len;
1956 const uint8_t* p_uuid16 =
1957 AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_APPEARANCE, &len);
1958 if (p_uuid16 && len == 2) {
1959 return btm_ble_appearance_to_cod((uint16_t)p_uuid16[0] | (p_uuid16[1] << 8));
1960 }
1961
1962 p_uuid16 = AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_16SRV_CMPL, &len);
1963 if (p_uuid16 == NULL) {
1964 return kDevClassUnclassified;
1965 }
1966
1967 for (uint8_t i = 0; i + 2 <= len; i = i + 2) {
1968 /* if this BLE device supports HID over LE, set HID Major in class of
1969 * device */
1970 if ((p_uuid16[i] | (p_uuid16[i + 1] << 8)) == UUID_SERVCLASS_LE_HID) {
1971 DEV_CLASS dev_class;
1972 dev_class[0] = 0;
1973 dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1974 dev_class[2] = 0;
1975 return dev_class;
1976 }
1977 }
1978
1979 return kDevClassUnclassified;
1980 }
1981
1982 /**
1983 * Update adv packet information into inquiry result.
1984 */
btm_ble_update_inq_result(tINQ_DB_ENT * p_i,uint8_t addr_type,const RawAddress &,uint16_t evt_type,uint8_t primary_phy,uint8_t secondary_phy,uint8_t advertising_sid,int8_t tx_power,int8_t rssi,uint16_t periodic_adv_int,std::vector<uint8_t> const & data)1985 static void btm_ble_update_inq_result(tINQ_DB_ENT* p_i, uint8_t addr_type,
1986 const RawAddress& /* bda */, uint16_t evt_type,
1987 uint8_t primary_phy, uint8_t secondary_phy,
1988 uint8_t advertising_sid, int8_t tx_power, int8_t rssi,
1989 uint16_t periodic_adv_int, std::vector<uint8_t> const& data) {
1990 tBTM_INQ_RESULTS* p_cur = &p_i->inq_info.results;
1991 uint8_t len;
1992
1993 /* Save the info */
1994 p_cur->inq_result_type |= BT_DEVICE_TYPE_BLE;
1995 p_cur->ble_addr_type = static_cast<tBLE_ADDR_TYPE>(addr_type);
1996 p_cur->rssi = rssi;
1997 p_cur->ble_primary_phy = primary_phy;
1998 p_cur->ble_secondary_phy = secondary_phy;
1999 p_cur->ble_advertising_sid = advertising_sid;
2000 p_cur->ble_tx_power = tx_power;
2001 p_cur->ble_periodic_adv_int = periodic_adv_int;
2002
2003 if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI &&
2004 ble_evt_type_is_scannable(evt_type) && !ble_evt_type_is_scan_resp(evt_type)) {
2005 p_i->scan_rsp = false;
2006 } else {
2007 p_i->scan_rsp = true;
2008 }
2009
2010 if (p_i->inq_count != btm_cb.btm_inq_vars.inq_counter) {
2011 p_cur->device_type = BT_DEVICE_TYPE_BLE;
2012 } else {
2013 p_cur->device_type |= BT_DEVICE_TYPE_BLE;
2014 }
2015
2016 if (evt_type != BTM_BLE_SCAN_RSP_EVT) {
2017 p_cur->ble_evt_type = evt_type;
2018 }
2019
2020 p_i->inq_count = btm_cb.btm_inq_vars.inq_counter; /* Mark entry for current inquiry */
2021
2022 bool has_advertising_flags = false;
2023 if (!data.empty()) {
2024 uint8_t local_flag = 0;
2025 const uint8_t* p_flag = AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_FLAG, &len);
2026 if (p_flag != NULL && len != 0) {
2027 has_advertising_flags = true;
2028 p_cur->flag = *p_flag;
2029 local_flag = *p_flag;
2030 }
2031
2032 p_cur->dev_class = btm_ble_get_appearance_as_cod(data);
2033
2034 const uint8_t* p_rsi = AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_RSI, &len);
2035 if (p_rsi != nullptr && len == 6) {
2036 STREAM_TO_BDADDR(p_cur->ble_ad_rsi, p_rsi);
2037 }
2038
2039 const uint8_t* p_service_data = data.data();
2040 uint8_t service_data_len = 0;
2041
2042 while ((p_service_data = AdvertiseDataParser::GetFieldByType(
2043 p_service_data + service_data_len,
2044 data.size() - (p_service_data - data.data()) - service_data_len,
2045 BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE, &service_data_len))) {
2046 uint16_t uuid;
2047 const uint8_t* p_uuid = p_service_data;
2048 if (service_data_len < 2) {
2049 continue;
2050 }
2051 STREAM_TO_UINT16(uuid, p_uuid);
2052
2053 if (uuid == 0x184E /* Audio Stream Control service */ ||
2054 uuid == 0x184F /* Broadcast Audio Scan service */ ||
2055 uuid == 0x1850 /* Published Audio Capabilities service */ ||
2056 uuid == 0x1853 /* Common Audio service */) {
2057 p_cur->ble_ad_is_le_audio_capable = true;
2058 break;
2059 }
2060 }
2061 // Non-connectable packets may omit flags entirely, in which case nothing
2062 // should be assumed about their values (CSSv10, 1.3.1). Thus, do not
2063 // interpret the device type unless this packet has the flags set or is
2064 // connectable.
2065 if (ble_evt_type_is_connectable(evt_type) && !has_advertising_flags) {
2066 // Assume that all-zero flags were received
2067 has_advertising_flags = true;
2068 local_flag = 0;
2069 }
2070 if (has_advertising_flags && (local_flag & BTM_BLE_BREDR_NOT_SPT) == 0) {
2071 if (p_cur->ble_addr_type != BLE_ADDR_RANDOM) {
2072 log::verbose("NOT_BR_EDR support bit not set, treat device as DUMO");
2073 p_cur->device_type |= BT_DEVICE_TYPE_DUMO;
2074 } else {
2075 log::verbose("Random address, treat device as LE only");
2076 }
2077 } else {
2078 log::verbose("NOT_BR/EDR support bit set, treat device as LE only");
2079 }
2080 }
2081 }
2082
btm_ble_process_adv_addr(RawAddress & bda,tBLE_ADDR_TYPE * addr_type)2083 void btm_ble_process_adv_addr(RawAddress& bda, tBLE_ADDR_TYPE* addr_type) {
2084 /* map address to security record */
2085 bool match = btm_identity_addr_to_random_pseudo(&bda, addr_type, false);
2086
2087 log::verbose("bda={}", bda);
2088 /* always do RRA resolution on host */
2089 if (!match && BTM_BLE_IS_RESOLVE_BDA(bda)) {
2090 tBTM_SEC_DEV_REC* match_rec = btm_ble_resolve_random_addr(bda);
2091 if (match_rec) {
2092 match_rec->ble.active_addr_type = BTM_BLE_ADDR_RRA;
2093 match_rec->ble.cur_rand_addr = bda;
2094
2095 if (btm_ble_init_pseudo_addr(match_rec, bda)) {
2096 bda = match_rec->bd_addr;
2097 } else {
2098 // Assign the original address to be the current report address
2099 bda = match_rec->ble.pseudo_addr;
2100 *addr_type = match_rec->ble.AddressType();
2101 }
2102 }
2103 }
2104 }
2105
2106 /**
2107 * This function is called after random address resolution is done, and proceed
2108 * to process adv packet.
2109 */
btm_ble_process_adv_pkt_cont(uint16_t evt_type,tBLE_ADDR_TYPE addr_type,const RawAddress & bda,uint8_t primary_phy,uint8_t secondary_phy,uint8_t advertising_sid,int8_t tx_power,int8_t rssi,uint16_t periodic_adv_int,uint8_t data_len,const uint8_t * data,const RawAddress & original_bda)2110 void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type,
2111 const RawAddress& bda, uint8_t primary_phy, uint8_t secondary_phy,
2112 uint8_t advertising_sid, int8_t tx_power, int8_t rssi,
2113 uint16_t periodic_adv_int, uint8_t data_len, const uint8_t* data,
2114 const RawAddress& original_bda) {
2115 bool update = true;
2116
2117 std::vector<uint8_t> tmp;
2118 if (data_len != 0) {
2119 tmp.insert(tmp.begin(), data, data + data_len);
2120 }
2121
2122 bool is_scannable = ble_evt_type_is_scannable(evt_type);
2123 bool is_scan_resp = ble_evt_type_is_scan_resp(evt_type);
2124 bool is_legacy = ble_evt_type_is_legacy(evt_type);
2125
2126 // We might receive a legacy scan response without receving a ADV_IND
2127 // or ADV_SCAN_IND before. Only parsing the scan response data which
2128 // has no ad flag, the device will be set to DUMO mode. The createbond
2129 // procedure will use the wrong device mode.
2130 // In such case no necessary to report scan response
2131 if (is_legacy && is_scan_resp && !cache.Exist(addr_type, bda)) {
2132 return;
2133 }
2134
2135 bool is_start = is_legacy && is_scannable && !is_scan_resp;
2136
2137 if (is_legacy) {
2138 AdvertiseDataParser::RemoveTrailingZeros(tmp);
2139 }
2140
2141 // We might have send scan request to this device before, but didn't get the
2142 // response. In such case make sure data is put at start, not appended to
2143 // already existing data.
2144 std::vector<uint8_t> const& adv_data = is_start ? cache.Set(addr_type, bda, std::move(tmp))
2145 : cache.Append(addr_type, bda, std::move(tmp));
2146
2147 bool data_complete = (ble_evt_type_data_status(evt_type) != 0x01);
2148
2149 if (!data_complete) {
2150 // If we didn't receive whole adv data yet, don't report the device.
2151 log::verbose("Data not complete yet, waiting for more {}", bda);
2152 return;
2153 }
2154
2155 bool is_active_scan = btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI;
2156 if (is_active_scan && is_scannable && !is_scan_resp) {
2157 // If we didn't receive scan response yet, don't report the device.
2158 log::verbose("Waiting for scan response {}", bda);
2159 return;
2160 }
2161
2162 if (!AdvertiseDataParser::IsValid(adv_data)) {
2163 log::verbose("Dropping bad advertisement packet: {}",
2164 base::HexEncode(adv_data.data(), adv_data.size()));
2165 cache.Clear(addr_type, bda);
2166 return;
2167 }
2168
2169 bool include_rsi = false;
2170 uint8_t len;
2171 if (AdvertiseDataParser::GetFieldByType(adv_data, BTM_BLE_AD_TYPE_RSI, &len)) {
2172 include_rsi = true;
2173 }
2174
2175 tINQ_DB_ENT* p_i = btm_inq_db_find(bda);
2176
2177 /* Check if this address has already been processed for this inquiry */
2178 if (btm_inq_find_bdaddr(bda)) {
2179 /* never been report as an LE device */
2180 if (p_i && (!(p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BLE) ||
2181 /* scan response to be updated */
2182 (!p_i->scan_rsp) || (!p_i->inq_info.results.include_rsi && include_rsi))) {
2183 update = true;
2184 } else if (btm_cb.ble_ctr_cb.is_ble_observe_active()) {
2185 update = false;
2186 } else {
2187 /* if yes, skip it */
2188 cache.Clear(addr_type, bda);
2189 return; /* assumption: one result per event */
2190 }
2191 }
2192 /* If existing entry, use that, else get a new one (possibly reusing the
2193 * oldest) */
2194 if (p_i == NULL) {
2195 p_i = btm_inq_db_new(bda, true);
2196 if (p_i != NULL) {
2197 btm_cb.btm_inq_vars.inq_cmpl_info.num_resp++;
2198 p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms();
2199 } else {
2200 return;
2201 }
2202 } else if (p_i->inq_count !=
2203 btm_cb.btm_inq_vars.inq_counter) /* first time seen in this inquiry */
2204 {
2205 p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms();
2206 btm_cb.btm_inq_vars.inq_cmpl_info.num_resp++;
2207 }
2208
2209 /* update the LE device information in inquiry database */
2210 btm_ble_update_inq_result(p_i, addr_type, bda, evt_type, primary_phy, secondary_phy,
2211 advertising_sid, tx_power, rssi, periodic_adv_int, adv_data);
2212
2213 if (include_rsi) {
2214 (&p_i->inq_info.results)->include_rsi = true;
2215 }
2216
2217 tBTM_INQ_RESULTS_CB* p_opportunistic_obs_results_cb =
2218 btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb;
2219 if (p_opportunistic_obs_results_cb) {
2220 (p_opportunistic_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2221 const_cast<uint8_t*>(adv_data.data()), adv_data.size());
2222 }
2223
2224 tBTM_INQ_RESULTS_CB* p_target_announcement_obs_results_cb =
2225 btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb;
2226 if (p_target_announcement_obs_results_cb) {
2227 (p_target_announcement_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2228 const_cast<uint8_t*>(adv_data.data()), adv_data.size());
2229 }
2230
2231 uint8_t result = btm_ble_is_discoverable(bda, adv_data);
2232 if (result == 0) {
2233 // Device no longer discoverable so discard outstanding advertising packet
2234 cache.Clear(addr_type, bda);
2235 return;
2236 }
2237
2238 if (!update) {
2239 result &= ~BTM_BLE_INQ_RESULT;
2240 }
2241
2242 tBTM_INQ_RESULTS_CB* p_inq_results_cb = btm_cb.btm_inq_vars.p_inq_results_cb;
2243 if (p_inq_results_cb && (result & BTM_BLE_INQ_RESULT)) {
2244 (p_inq_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2245 const_cast<uint8_t*>(adv_data.data()), adv_data.size());
2246 }
2247
2248 // Pass address up to GattService#onScanResult
2249 p_i->inq_info.results.original_bda = original_bda;
2250
2251 tBTM_INQ_RESULTS_CB* p_obs_results_cb = btm_cb.ble_ctr_cb.p_obs_results_cb;
2252 if (p_obs_results_cb && (result & BTM_BLE_OBS_RESULT)) {
2253 (p_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2254 const_cast<uint8_t*>(adv_data.data()), adv_data.size());
2255 }
2256
2257 cache.Clear(addr_type, bda);
2258 }
2259
2260 /**
2261 * This function copy from btm_ble_process_adv_pkt_cont to process adv packet
2262 * from gd scanning module to handle inquiry result callback.
2263 */
btm_ble_process_adv_pkt_cont_for_inquiry(uint16_t evt_type,tBLE_ADDR_TYPE addr_type,const RawAddress & bda,uint8_t primary_phy,uint8_t secondary_phy,uint8_t advertising_sid,int8_t tx_power,int8_t rssi,uint16_t periodic_adv_int,std::vector<uint8_t> advertising_data)2264 void btm_ble_process_adv_pkt_cont_for_inquiry(uint16_t evt_type, tBLE_ADDR_TYPE addr_type,
2265 const RawAddress& bda, uint8_t primary_phy,
2266 uint8_t secondary_phy, uint8_t advertising_sid,
2267 int8_t tx_power, int8_t rssi,
2268 uint16_t periodic_adv_int,
2269 std::vector<uint8_t> advertising_data) {
2270 bool update = true;
2271
2272 bool include_rsi = false;
2273 uint8_t len;
2274 if (AdvertiseDataParser::GetFieldByType(advertising_data, BTM_BLE_AD_TYPE_RSI, &len)) {
2275 include_rsi = true;
2276 }
2277
2278 const uint8_t* p_flag =
2279 AdvertiseDataParser::GetFieldByType(advertising_data, BTM_BLE_AD_TYPE_FLAG, &len);
2280
2281 tINQ_DB_ENT* p_i = btm_inq_db_find(bda);
2282
2283 /* Check if this address has already been processed for this inquiry */
2284 if (btm_inq_find_bdaddr(bda)) {
2285 /* never been report as an LE device */
2286 if (p_i && (!(p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BLE) ||
2287 /* scan response to be updated */
2288 (!p_i->scan_rsp) || (!p_i->inq_info.results.include_rsi && include_rsi) ||
2289 (!p_i->inq_info.results.flag && p_flag && *p_flag))) {
2290 update = true;
2291 } else if (btm_cb.ble_ctr_cb.is_ble_observe_active()) {
2292 btm_cb.neighbor.le_observe.results++;
2293 update = false;
2294 } else {
2295 /* if yes, skip it */
2296 return; /* assumption: one result per event */
2297 }
2298 }
2299
2300 /* If existing entry, use that, else get a new one (possibly reusing the
2301 * oldest) */
2302 if (p_i == NULL) {
2303 p_i = btm_inq_db_new(bda, true);
2304 if (p_i != NULL) {
2305 btm_cb.btm_inq_vars.inq_cmpl_info.num_resp++;
2306 p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms();
2307 btm_cb.neighbor.le_inquiry.results++;
2308 btm_cb.neighbor.le_legacy_scan.results++;
2309 } else {
2310 log::warn("Unable to allocate entry for inquiry result");
2311 return;
2312 }
2313 } else if (p_i->inq_count !=
2314 btm_cb.btm_inq_vars.inq_counter) /* first time seen in this inquiry */
2315 {
2316 p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms();
2317 btm_cb.btm_inq_vars.inq_cmpl_info.num_resp++;
2318 }
2319
2320 /* update the LE device information in inquiry database */
2321 btm_ble_update_inq_result(p_i, addr_type, bda, evt_type, primary_phy, secondary_phy,
2322 advertising_sid, tx_power, rssi, periodic_adv_int, advertising_data);
2323
2324 if (include_rsi) {
2325 (&p_i->inq_info.results)->include_rsi = true;
2326 }
2327
2328 tBTM_INQ_RESULTS_CB* p_opportunistic_obs_results_cb =
2329 btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb;
2330 if (p_opportunistic_obs_results_cb) {
2331 (p_opportunistic_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2332 const_cast<uint8_t*>(advertising_data.data()),
2333 advertising_data.size());
2334 }
2335
2336 tBTM_INQ_RESULTS_CB* p_target_announcement_obs_results_cb =
2337 btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb;
2338 if (p_target_announcement_obs_results_cb) {
2339 (p_target_announcement_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2340 const_cast<uint8_t*>(advertising_data.data()),
2341 advertising_data.size());
2342 }
2343
2344 uint8_t result = btm_ble_is_discoverable(bda, advertising_data);
2345 if (result == 0) {
2346 return;
2347 }
2348
2349 if (!update) {
2350 result &= ~BTM_BLE_INQ_RESULT;
2351 }
2352
2353 tBTM_INQ_RESULTS_CB* p_inq_results_cb = btm_cb.btm_inq_vars.p_inq_results_cb;
2354 if (p_inq_results_cb && (result & BTM_BLE_INQ_RESULT)) {
2355 (p_inq_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2356 const_cast<uint8_t*>(advertising_data.data()), advertising_data.size());
2357 }
2358 }
2359
2360 /*******************************************************************************
2361 *
2362 * Function btm_ble_start_scan
2363 *
2364 * Description Start the BLE scan.
2365 *
2366 * Returns void
2367 *
2368 ******************************************************************************/
btm_ble_start_scan()2369 static void btm_ble_start_scan() {
2370 btm_cb.neighbor.le_legacy_scan = {
2371 .start_time_ms = timestamper_in_milliseconds.GetTimestamp(),
2372 .results = 0,
2373 };
2374 BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le legacy scan started", "Duplicates:disable");
2375
2376 /* start scan, disable duplicate filtering */
2377 btm_send_hci_scan_enable(BTM_BLE_SCAN_ENABLE, BTM_BLE_DUPLICATE_DISABLE);
2378
2379 if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI) {
2380 btm_ble_set_topology_mask(BTM_BLE_STATE_ACTIVE_SCAN_BIT);
2381 } else {
2382 btm_ble_set_topology_mask(BTM_BLE_STATE_PASSIVE_SCAN_BIT);
2383 }
2384 }
2385
2386 /*******************************************************************************
2387 *
2388 * Function btm_update_scanner_filter_policy
2389 *
2390 * Description This function updates the filter policy of scanner
2391 ******************************************************************************/
btm_update_scanner_filter_policy(tBTM_BLE_SFP scan_policy)2392 static void btm_update_scanner_filter_policy(tBTM_BLE_SFP scan_policy) {
2393 uint32_t scan_interval = !btm_cb.ble_ctr_cb.inq_var.scan_interval
2394 ? BTM_BLE_GAP_DISC_SCAN_INT
2395 : btm_cb.ble_ctr_cb.inq_var.scan_interval;
2396 uint32_t scan_window = !btm_cb.ble_ctr_cb.inq_var.scan_window
2397 ? BTM_BLE_GAP_DISC_SCAN_WIN
2398 : btm_cb.ble_ctr_cb.inq_var.scan_window;
2399 uint8_t scan_phy = !btm_cb.ble_ctr_cb.inq_var.scan_phy ? BTM_BLE_DEFAULT_PHYS
2400 : btm_cb.ble_ctr_cb.inq_var.scan_phy;
2401
2402 log::verbose("");
2403
2404 btm_cb.ble_ctr_cb.inq_var.sfp = scan_policy;
2405 btm_cb.ble_ctr_cb.inq_var.scan_type =
2406 btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_NONE
2407 ? BTM_BLE_SCAN_MODE_ACTI
2408 : btm_cb.ble_ctr_cb.inq_var.scan_type;
2409
2410 btm_send_hci_set_scan_params(btm_cb.ble_ctr_cb.inq_var.scan_type, (uint16_t)scan_interval,
2411 (uint16_t)scan_window, (uint8_t)scan_phy,
2412 btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, scan_policy);
2413 }
2414
2415 /*******************************************************************************
2416 *
2417 * Function btm_ble_stop_scan
2418 *
2419 * Description Stop the BLE scan.
2420 *
2421 * Returns void
2422 *
2423 ******************************************************************************/
btm_ble_stop_scan(void)2424 static void btm_ble_stop_scan(void) {
2425 if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI) {
2426 btm_ble_clear_topology_mask(BTM_BLE_STATE_ACTIVE_SCAN_BIT);
2427 } else {
2428 btm_ble_clear_topology_mask(BTM_BLE_STATE_PASSIVE_SCAN_BIT);
2429 }
2430
2431 /* Clear the inquiry callback if set */
2432 btm_cb.ble_ctr_cb.inq_var.scan_type = BTM_BLE_SCAN_MODE_NONE;
2433
2434 /* stop discovery now */
2435 const uint64_t duration_timestamp =
2436 timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.le_legacy_scan.start_time_ms;
2437 BTM_LogHistory(
2438 kBtmLogTag, RawAddress::kEmpty, "Le legacy scan stopped",
2439 base::StringPrintf("duration_s:%6.3f results:%-3lu", (double)duration_timestamp / 1000.0,
2440 (unsigned long)btm_cb.neighbor.le_legacy_scan.results));
2441 btm_send_hci_scan_enable(BTM_BLE_SCAN_DISABLE, BTM_BLE_DUPLICATE_ENABLE);
2442
2443 btm_update_scanner_filter_policy(SP_ADV_ALL);
2444 }
2445 /*******************************************************************************
2446 *
2447 * Function btm_ble_stop_inquiry
2448 *
2449 * Description Stop the BLE Inquiry.
2450 *
2451 * Returns void
2452 *
2453 ******************************************************************************/
btm_ble_stop_inquiry(void)2454 void btm_ble_stop_inquiry(void) {
2455 alarm_cancel(btm_cb.ble_ctr_cb.inq_var.inquiry_timer);
2456
2457 const uint64_t duration_timestamp =
2458 timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.le_inquiry.start_time_ms;
2459 BTM_LogHistory(
2460 kBtmLogTag, RawAddress::kEmpty, "Le inquiry stopped",
2461 base::StringPrintf("duration_s:%6.3f results:%-3lu", (double)duration_timestamp / 1000.0,
2462 (unsigned long)btm_cb.neighbor.le_inquiry.results));
2463 btm_cb.ble_ctr_cb.reset_ble_inquiry();
2464
2465 /* Cleanup anything remaining on index 0 */
2466 BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_DELETE, static_cast<tBTM_BLE_PF_FILT_INDEX>(0),
2467 nullptr, base::Bind(btm_ble_scan_filt_param_cfg_evt));
2468
2469 /* If no more scan activity, stop LE scan now */
2470 if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) {
2471 btm_ble_stop_scan();
2472 } else if (get_low_latency_scan_params() != std::pair(btm_cb.ble_ctr_cb.inq_var.scan_interval,
2473 btm_cb.ble_ctr_cb.inq_var.scan_window)) {
2474 log::verbose("setting default params for ongoing observe");
2475 btm_ble_stop_scan();
2476 btm_ble_start_scan();
2477 }
2478
2479 /* If we have a callback registered for inquiry complete, call it */
2480 log::verbose("BTM Inq Compl Callback: status 0x{:02x}, num results {}",
2481 btm_cb.btm_inq_vars.inq_cmpl_info.status,
2482 btm_cb.btm_inq_vars.inq_cmpl_info.num_resp);
2483
2484 // TODO: remove this call and make btm_process_inq_complete static
2485 btm_process_inq_complete(HCI_SUCCESS,
2486 (uint8_t)(btm_cb.btm_inq_vars.inqparms.mode & BTM_BLE_GENERAL_INQUIRY));
2487 }
2488
2489 /*******************************************************************************
2490 *
2491 * Function btm_ble_stop_observe
2492 *
2493 * Description Stop the BLE Observe.
2494 *
2495 * Returns void
2496 *
2497 ******************************************************************************/
btm_ble_stop_observe(void)2498 static void btm_ble_stop_observe(void) {
2499 tBTM_CMPL_CB* p_obs_cb = btm_cb.ble_ctr_cb.p_obs_cmpl_cb;
2500
2501 alarm_cancel(btm_cb.ble_ctr_cb.observer_timer);
2502
2503 btm_cb.ble_ctr_cb.reset_ble_observe();
2504
2505 btm_cb.ble_ctr_cb.p_obs_results_cb = NULL;
2506 btm_cb.ble_ctr_cb.p_obs_cmpl_cb = NULL;
2507
2508 if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) {
2509 btm_ble_stop_scan();
2510 }
2511
2512 if (p_obs_cb) {
2513 (p_obs_cb)(&btm_cb.btm_inq_vars.inq_cmpl_info);
2514 }
2515 }
2516 /*******************************************************************************
2517 *
2518 * Function btm_ble_adv_states_operation
2519 *
2520 * Description Set or clear adv states in topology mask
2521 *
2522 * Returns operation status. true if sucessful, false otherwise.
2523 *
2524 ******************************************************************************/
2525 typedef bool(BTM_TOPOLOGY_FUNC_PTR)(tBTM_BLE_STATE_MASK);
btm_ble_adv_states_operation(BTM_TOPOLOGY_FUNC_PTR * p_handler,uint8_t adv_evt)2526 static bool btm_ble_adv_states_operation(BTM_TOPOLOGY_FUNC_PTR* p_handler, uint8_t adv_evt) {
2527 bool rt = false;
2528
2529 switch (adv_evt) {
2530 case BTM_BLE_CONNECT_EVT:
2531 rt = (*p_handler)(BTM_BLE_STATE_CONN_ADV_BIT);
2532 break;
2533
2534 case BTM_BLE_NON_CONNECT_EVT:
2535 rt = (*p_handler)(BTM_BLE_STATE_NON_CONN_ADV_BIT);
2536 break;
2537 case BTM_BLE_CONNECT_DIR_EVT:
2538 rt = (*p_handler)(BTM_BLE_STATE_HI_DUTY_DIR_ADV_BIT);
2539 break;
2540
2541 case BTM_BLE_DISCOVER_EVT:
2542 rt = (*p_handler)(BTM_BLE_STATE_SCAN_ADV_BIT);
2543 break;
2544
2545 case BTM_BLE_CONNECT_LO_DUTY_DIR_EVT:
2546 rt = (*p_handler)(BTM_BLE_STATE_LO_DUTY_DIR_ADV_BIT);
2547 break;
2548
2549 default:
2550 log::error("unknown adv event : {}", adv_evt);
2551 break;
2552 }
2553
2554 return rt;
2555 }
2556
2557 /*******************************************************************************
2558 *
2559 * Function btm_ble_start_adv
2560 *
2561 * Description start the BLE advertising.
2562 *
2563 * Returns void
2564 *
2565 ******************************************************************************/
btm_ble_start_adv(void)2566 static tBTM_STATUS btm_ble_start_adv(void) {
2567 if (!btm_ble_adv_states_operation(btm_ble_topology_check, btm_cb.ble_ctr_cb.inq_var.evt_type)) {
2568 return tBTM_STATUS::BTM_WRONG_MODE;
2569 }
2570
2571 btsnd_hcic_ble_set_adv_enable(BTM_BLE_ADV_ENABLE);
2572 btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_ENABLE;
2573 btm_ble_adv_states_operation(btm_ble_set_topology_mask, btm_cb.ble_ctr_cb.inq_var.evt_type);
2574 power_telemetry::GetInstance().LogBleAdvStarted();
2575
2576 return tBTM_STATUS::BTM_SUCCESS;
2577 }
2578
2579 /*******************************************************************************
2580 *
2581 * Function btm_ble_stop_adv
2582 *
2583 * Description Stop the BLE advertising.
2584 *
2585 * Returns void
2586 *
2587 ******************************************************************************/
btm_ble_stop_adv(void)2588 static tBTM_STATUS btm_ble_stop_adv(void) {
2589 if (btm_cb.ble_ctr_cb.inq_var.adv_mode == BTM_BLE_ADV_ENABLE) {
2590 btsnd_hcic_ble_set_adv_enable(BTM_BLE_ADV_DISABLE);
2591
2592 btm_cb.ble_ctr_cb.inq_var.fast_adv_on = false;
2593 btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
2594 /* clear all adv states */
2595 btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_ADV_MASK);
2596 power_telemetry::GetInstance().LogBleAdvStopped();
2597 }
2598 return tBTM_STATUS::BTM_SUCCESS;
2599 }
2600
btm_ble_fast_adv_timer_timeout(void *)2601 static void btm_ble_fast_adv_timer_timeout(void* /* data */) {
2602 /* fast adv is completed, fall back to slow adv interval */
2603 btm_ble_start_slow_adv();
2604 }
2605
2606 /*******************************************************************************
2607 *
2608 * Function btm_ble_start_slow_adv
2609 *
2610 * Description Restart adv with slow adv interval
2611 *
2612 * Returns void
2613 *
2614 ******************************************************************************/
btm_ble_start_slow_adv(void)2615 static void btm_ble_start_slow_adv(void) {
2616 if (btm_cb.ble_ctr_cb.inq_var.adv_mode == BTM_BLE_ADV_ENABLE) {
2617 tBTM_LE_RANDOM_CB* p_addr_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
2618 RawAddress address = RawAddress::kEmpty;
2619 tBLE_ADDR_TYPE init_addr_type = BLE_ADDR_PUBLIC;
2620 tBLE_ADDR_TYPE own_addr_type = p_addr_cb->own_addr_type;
2621
2622 btm_ble_stop_adv();
2623
2624 btm_cb.ble_ctr_cb.inq_var.evt_type =
2625 btm_set_conn_mode_adv_init_addr(address, &init_addr_type, &own_addr_type);
2626
2627 /* slow adv mode never goes into directed adv */
2628 btsnd_hcic_ble_write_adv_params(BTM_BLE_GAP_ADV_SLOW_INT, BTM_BLE_GAP_ADV_SLOW_INT,
2629 btm_cb.ble_ctr_cb.inq_var.evt_type, own_addr_type,
2630 init_addr_type, address, btm_cb.ble_ctr_cb.inq_var.adv_chnl_map,
2631 btm_cb.ble_ctr_cb.inq_var.afp);
2632
2633 btm_ble_start_adv();
2634 }
2635 }
2636
btm_ble_inquiry_timer_gap_limited_discovery_timeout(void *)2637 static void btm_ble_inquiry_timer_gap_limited_discovery_timeout(void* /* data */) {
2638 /* lim_timeout expired, limited discovery should exit now */
2639 btm_cb.btm_inq_vars.discoverable_mode &= ~BTM_BLE_LIMITED_DISCOVERABLE;
2640 btm_ble_set_adv_flag(btm_cb.btm_inq_vars.connectable_mode, btm_cb.btm_inq_vars.discoverable_mode);
2641 }
2642
btm_ble_inquiry_timer_timeout(void *)2643 static void btm_ble_inquiry_timer_timeout(void* /* data */) { btm_ble_stop_inquiry(); }
2644
btm_ble_observer_timer_timeout(void *)2645 static void btm_ble_observer_timer_timeout(void* /* data */) { btm_ble_stop_observe(); }
2646
2647 /*******************************************************************************
2648 *
2649 * Function btm_ble_read_remote_features_complete
2650 *
2651 * Description This function is called when the command complete message
2652 * is received from the HCI for the read LE remote feature
2653 * supported complete event.
2654 *
2655 * Returns void
2656 *
2657 ******************************************************************************/
btm_ble_read_remote_features_complete(uint8_t * p,uint8_t length)2658 void btm_ble_read_remote_features_complete(uint8_t* p, uint8_t length) {
2659 uint16_t handle;
2660 uint8_t status;
2661
2662 if (length < 3) {
2663 goto err_out;
2664 }
2665
2666 STREAM_TO_UINT8(status, p);
2667 STREAM_TO_UINT16(handle, p);
2668 handle = handle & 0x0FFF; // only 12 bits meaningful
2669
2670 if (status != HCI_SUCCESS) {
2671 if (status != HCI_ERR_UNSUPPORTED_REM_FEATURE) {
2672 log::error("Failed to read remote features status:{}",
2673 hci_error_code_text(static_cast<tHCI_STATUS>(status)));
2674 return;
2675 }
2676 log::warn("Remote does not support reading remote feature");
2677 }
2678
2679 if (status == HCI_SUCCESS) {
2680 // BD_FEATURES_LEN additional bytes are read
2681 // in acl_set_peer_le_features_from_handle
2682 if (length < 3 + BD_FEATURES_LEN) {
2683 goto err_out;
2684 }
2685
2686 if (!acl_set_peer_le_features_from_handle(handle, p)) {
2687 log::error("Unable to find existing connection after read remote features");
2688 return;
2689 }
2690 }
2691
2692 btsnd_hcic_rmt_ver_req(handle);
2693
2694 return;
2695
2696 err_out:
2697 log::error("Bogus event packet, too short");
2698 }
2699
2700 /*******************************************************************************
2701 *
2702 * Function btm_ble_write_adv_enable_complete
2703 *
2704 * Description This function process the write adv enable command complete.
2705 *
2706 * Returns void
2707 *
2708 ******************************************************************************/
btm_ble_write_adv_enable_complete(uint8_t * p,uint16_t evt_len)2709 void btm_ble_write_adv_enable_complete(uint8_t* p, uint16_t evt_len) {
2710 /* if write adv enable/disbale not succeed */
2711 if (evt_len < 1 || *p != HCI_SUCCESS) {
2712 /* toggle back the adv mode */
2713 btm_cb.ble_ctr_cb.inq_var.adv_mode = !btm_cb.ble_ctr_cb.inq_var.adv_mode;
2714 }
2715 }
2716
2717 /*******************************************************************************
2718 *
2719 * Function btm_ble_set_topology_mask
2720 *
2721 * Description set BLE topology mask
2722 *
2723 * Returns true is request is allowed, false otherwise.
2724 *
2725 ******************************************************************************/
btm_ble_set_topology_mask(tBTM_BLE_STATE_MASK request_state_mask)2726 bool btm_ble_set_topology_mask(tBTM_BLE_STATE_MASK request_state_mask) {
2727 request_state_mask &= BTM_BLE_STATE_ALL_MASK;
2728 btm_cb.ble_ctr_cb.cur_states |= (request_state_mask & BTM_BLE_STATE_ALL_MASK);
2729 return true;
2730 }
2731
2732 /*******************************************************************************
2733 *
2734 * Function btm_ble_clear_topology_mask
2735 *
2736 * Description Clear BLE topology bit mask
2737 *
2738 * Returns true is request is allowed, false otherwise.
2739 *
2740 ******************************************************************************/
btm_ble_clear_topology_mask(tBTM_BLE_STATE_MASK request_state_mask)2741 bool btm_ble_clear_topology_mask(tBTM_BLE_STATE_MASK request_state_mask) {
2742 request_state_mask &= BTM_BLE_STATE_ALL_MASK;
2743 btm_cb.ble_ctr_cb.cur_states &= ~request_state_mask;
2744 return true;
2745 }
2746
2747 /*******************************************************************************
2748 *
2749 * Function btm_ble_update_link_topology_mask
2750 *
2751 * Description This function update the link topology mask
2752 *
2753 * Returns void
2754 *
2755 ******************************************************************************/
btm_ble_update_link_topology_mask(uint8_t link_role,bool increase)2756 static void btm_ble_update_link_topology_mask(uint8_t link_role, bool increase) {
2757 btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_CONN_MASK);
2758
2759 if (increase) {
2760 btm_cb.ble_ctr_cb.link_count[link_role]++;
2761 } else if (btm_cb.ble_ctr_cb.link_count[link_role] > 0) {
2762 btm_cb.ble_ctr_cb.link_count[link_role]--;
2763 }
2764
2765 if (btm_cb.ble_ctr_cb.link_count[HCI_ROLE_CENTRAL]) {
2766 btm_ble_set_topology_mask(BTM_BLE_STATE_CENTRAL_BIT);
2767 }
2768
2769 if (btm_cb.ble_ctr_cb.link_count[HCI_ROLE_PERIPHERAL]) {
2770 btm_ble_set_topology_mask(BTM_BLE_STATE_PERIPHERAL_BIT);
2771 }
2772
2773 if (link_role == HCI_ROLE_PERIPHERAL && increase) {
2774 btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
2775 /* make device fall back into undirected adv mode by default */
2776 btm_cb.ble_ctr_cb.inq_var.directed_conn = BTM_BLE_ADV_IND_EVT;
2777 /* clear all adv states */
2778 btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_ADV_MASK);
2779 }
2780 }
2781
btm_ble_increment_link_topology_mask(uint8_t link_role)2782 void btm_ble_increment_link_topology_mask(uint8_t link_role) {
2783 btm_ble_update_link_topology_mask(link_role, true);
2784 }
2785
btm_ble_decrement_link_topology_mask(uint8_t link_role)2786 void btm_ble_decrement_link_topology_mask(uint8_t link_role) {
2787 btm_ble_update_link_topology_mask(link_role, false);
2788 }
2789
2790 /*******************************************************************************
2791 *
2792 * Function btm_ble_update_mode_operation
2793 *
2794 * Description This function update the GAP role operation when a link
2795 * status is updated.
2796 *
2797 * Returns void
2798 *
2799 ******************************************************************************/
btm_ble_update_mode_operation(uint8_t,const RawAddress *,tHCI_STATUS status)2800 void btm_ble_update_mode_operation(uint8_t /* link_role */, const RawAddress* /* bd_addr */,
2801 tHCI_STATUS status) {
2802 if (status == HCI_ERR_ADVERTISING_TIMEOUT) {
2803 btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
2804 /* make device fall back into undirected adv mode by default */
2805 btm_cb.ble_ctr_cb.inq_var.directed_conn = BTM_BLE_ADV_IND_EVT;
2806 /* clear all adv states */
2807 btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_ADV_MASK);
2808 }
2809
2810 if (btm_cb.ble_ctr_cb.inq_var.connectable_mode == BTM_BLE_CONNECTABLE) {
2811 btm_ble_set_connectability(btm_cb.btm_inq_vars.connectable_mode |
2812 btm_cb.ble_ctr_cb.inq_var.connectable_mode);
2813 }
2814 }
2815
2816 /*******************************************************************************
2817 *
2818 * Function btm_ble_init
2819 *
2820 * Description Initialize the control block variable values.
2821 *
2822 * Returns void
2823 *
2824 ******************************************************************************/
btm_ble_init(void)2825 void btm_ble_init(void) {
2826 log::verbose("");
2827
2828 alarm_free(btm_cb.ble_ctr_cb.observer_timer);
2829 alarm_free(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer);
2830 memset(&btm_cb.ble_ctr_cb, 0, sizeof(tBTM_BLE_CB));
2831 memset(&(btm_cb.cmn_ble_vsc_cb), 0, sizeof(tBTM_BLE_VSC_CB));
2832 btm_cb.cmn_ble_vsc_cb.values_read = false;
2833
2834 btm_cb.ble_ctr_cb.observer_timer = alarm_new("btm_ble.observer_timer");
2835 btm_cb.ble_ctr_cb.cur_states = 0;
2836
2837 btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
2838 btm_cb.ble_ctr_cb.inq_var.scan_type = BTM_BLE_SCAN_MODE_NONE;
2839 btm_cb.ble_ctr_cb.inq_var.adv_chnl_map = BTM_BLE_DEFAULT_ADV_CHNL_MAP;
2840 btm_cb.ble_ctr_cb.inq_var.afp = BTM_BLE_DEFAULT_AFP;
2841 btm_cb.ble_ctr_cb.inq_var.sfp = BTM_BLE_DEFAULT_SFP;
2842 btm_cb.ble_ctr_cb.inq_var.connectable_mode = BTM_BLE_NON_CONNECTABLE;
2843 btm_cb.ble_ctr_cb.inq_var.discoverable_mode = BTM_BLE_NON_DISCOVERABLE;
2844 btm_cb.ble_ctr_cb.inq_var.fast_adv_timer = alarm_new("btm_ble_inq.fast_adv_timer");
2845 btm_cb.ble_ctr_cb.inq_var.inquiry_timer = alarm_new("btm_ble_inq.inquiry_timer");
2846
2847 btm_cb.ble_ctr_cb.inq_var.evt_type = BTM_BLE_NON_CONNECT_EVT;
2848
2849 btm_cb.ble_ctr_cb.addr_mgnt_cb.refresh_raddr_timer =
2850 alarm_new("btm_ble_addr.refresh_raddr_timer");
2851 btm_ble_pa_sync_cb = {};
2852 sync_timeout_alarm = alarm_new("btm.sync_start_task");
2853 if (!ble_vnd_is_included()) {
2854 btm_ble_adv_filter_init();
2855 }
2856 }
2857
2858 // Clean up btm ble control block
btm_ble_free()2859 void btm_ble_free() { alarm_free(btm_cb.ble_ctr_cb.addr_mgnt_cb.refresh_raddr_timer); }
2860
2861 /*******************************************************************************
2862 *
2863 * Function btm_ble_topology_check
2864 *
2865 * Description check to see requested state is supported. One state check
2866 * at a time is supported
2867 *
2868 * Returns true is request is allowed, false otherwise.
2869 *
2870 ******************************************************************************/
btm_ble_topology_check(tBTM_BLE_STATE_MASK request_state_mask)2871 bool btm_ble_topology_check(tBTM_BLE_STATE_MASK request_state_mask) {
2872 bool rt = false;
2873
2874 uint8_t state_offset = 0;
2875 uint16_t cur_states = btm_cb.ble_ctr_cb.cur_states;
2876 uint8_t request_state = 0;
2877
2878 /* check only one bit is set and within valid range */
2879 if (request_state_mask == BTM_BLE_STATE_INVALID ||
2880 request_state_mask > BTM_BLE_STATE_SCAN_ADV_BIT ||
2881 (request_state_mask & (request_state_mask - 1)) != 0) {
2882 log::error("illegal state requested: {}", request_state_mask);
2883 return rt;
2884 }
2885
2886 while (request_state_mask) {
2887 request_state_mask >>= 1;
2888 request_state++;
2889 }
2890
2891 /* check if the requested state is supported or not */
2892 uint8_t bit_num = btm_le_state_combo_tbl[0][request_state - 1];
2893 uint64_t ble_supported_states = bluetooth::shim::GetController()->GetLeSupportedStates();
2894
2895 if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, bit_num)) {
2896 log::error("state requested not supported: {}", request_state);
2897 return rt;
2898 }
2899
2900 rt = true;
2901 /* make sure currently active states are all supported in conjunction with the
2902 requested state. If the bit in table is UNSUPPORTED, the combination is not
2903 supported */
2904 while (cur_states != 0) {
2905 if (cur_states & 0x01) {
2906 uint8_t bit_num = btm_le_state_combo_tbl[request_state][state_offset];
2907 if (bit_num != UNSUPPORTED) {
2908 if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, bit_num)) {
2909 rt = false;
2910 break;
2911 }
2912 }
2913 }
2914 cur_states >>= 1;
2915 state_offset++;
2916 }
2917 return rt;
2918 }
2919