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