• 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 <base/functional/bind.h>
28 #include <base/logging.h>
29 #include <base/strings/string_number_conversions.h>
30 
31 #include <cstdint>
32 #include <list>
33 #include <memory>
34 #include <vector>
35 
36 #include "bta/include/bta_api.h"
37 #include "common/time_util.h"
38 #include "device/include/controller.h"
39 #include "main/shim/acl_api.h"
40 #include "main/shim/btm_api.h"
41 #include "main/shim/shim.h"
42 #include "osi/include/log.h"
43 #include "osi/include/osi.h"  // UNUSED_ATTR
44 #include "osi/include/properties.h"
45 #include "stack/acl/acl.h"
46 #include "stack/btm/btm_ble_int.h"
47 #include "stack/btm/btm_ble_int_types.h"
48 #include "stack/btm/btm_dev.h"
49 #include "stack/btm/btm_int_types.h"
50 #include "stack/gatt/gatt_int.h"
51 #include "stack/include/acl_api.h"
52 #include "stack/include/advertise_data_parser.h"
53 #include "stack/include/ble_scanner.h"
54 #include "stack/include/bt_types.h"
55 #include "stack/include/btm_api_types.h"
56 #include "stack/include/gap_api.h"
57 #include "stack/include/hci_error_code.h"
58 #include "stack/include/inq_hci_link_interface.h"
59 #include "types/ble_address_with_type.h"
60 #include "types/raw_address.h"
61 
62 extern tBTM_CB btm_cb;
63 
64 void btm_inq_remote_name_timer_timeout(void* data);
65 bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec,
66                               const RawAddress& new_pseudo_addr);
67 bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr,
68                                         tBLE_ADDR_TYPE* p_addr_type,
69                                         bool refresh);
70 void btm_ble_batchscan_init(void);
71 void btm_ble_adv_filter_init(void);
72 extern const tBLE_BD_ADDR convert_to_address_with_type(
73     const RawAddress& bd_addr, const tBTM_SEC_DEV_REC* p_dev_rec);
74 
75 #define BTM_EXT_BLE_RMT_NAME_TIMEOUT_MS (30 * 1000)
76 #define MIN_ADV_LENGTH 2
77 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN 9
78 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_L_RELEASE \
79   BTM_VSC_CHIP_CAPABILITY_RSP_LEN
80 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_M_RELEASE 15
81 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_S_RELEASE 25
82 
83 /* Sysprop paths for scan parameters */
84 static const char kPropertyInquiryScanInterval[] =
85     "bluetooth.core.le.inquiry_scan_interval";
86 static const char kPropertyInquiryScanWindow[] =
87     "bluetooth.core.le.inquiry_scan_window";
88 
89 static void btm_ble_start_scan();
90 static void btm_ble_stop_scan();
91 static tBTM_STATUS btm_ble_stop_adv(void);
92 static tBTM_STATUS btm_ble_start_adv(void);
93 
94 namespace {
95 
96 constexpr char kBtmLogTag[] = "SCAN";
97 
98 class AdvertisingCache {
99  public:
100   /* Set the data to |data| for device |addr_type, addr| */
Set(uint8_t addr_type,const RawAddress & addr,std::vector<uint8_t> data)101   const std::vector<uint8_t>& Set(uint8_t addr_type, const RawAddress& addr,
102                                   std::vector<uint8_t> data) {
103     auto it = Find(addr_type, addr);
104     if (it != items.end()) {
105       it->data = std::move(data);
106       return it->data;
107     }
108 
109     if (items.size() > cache_max) {
110       items.pop_back();
111     }
112 
113     items.emplace_front(addr_type, addr, std::move(data));
114     return items.front().data;
115   }
116 
Exist(uint8_t addr_type,const RawAddress & addr)117   bool Exist(uint8_t addr_type, const RawAddress& addr) {
118     auto it = Find(addr_type, addr);
119     if (it != items.end()) {
120       return true;
121     }
122     return false;
123   }
124 
125   /* Append |data| for device |addr_type, addr| */
Append(uint8_t addr_type,const RawAddress & addr,std::vector<uint8_t> data)126   const std::vector<uint8_t>& Append(uint8_t addr_type, const RawAddress& addr,
127                                      std::vector<uint8_t> data) {
128     auto it = Find(addr_type, addr);
129     if (it != items.end()) {
130       it->data.insert(it->data.end(), data.begin(), data.end());
131       return it->data;
132     }
133 
134     if (items.size() > cache_max) {
135       items.pop_back();
136     }
137 
138     items.emplace_front(addr_type, addr, std::move(data));
139     return items.front().data;
140   }
141 
142   /* Clear data for device |addr_type, addr| */
Clear(uint8_t addr_type,const RawAddress & addr)143   void Clear(uint8_t addr_type, const RawAddress& addr) {
144     auto it = Find(addr_type, addr);
145     if (it != items.end()) {
146       items.erase(it);
147     }
148   }
149 
ClearAll()150   void ClearAll() { items.clear(); }
151 
152  private:
153   struct Item {
154     uint8_t addr_type;
155     RawAddress addr;
156     std::vector<uint8_t> data;
157 
Item__anon6996e98a0111::AdvertisingCache::Item158     Item(uint8_t addr_type, const RawAddress& addr, std::vector<uint8_t> data)
159         : addr_type(addr_type), addr(addr), data(data) {}
160   };
161 
Find(uint8_t addr_type,const RawAddress & addr)162   std::list<Item>::iterator Find(uint8_t addr_type, const RawAddress& addr) {
163     for (auto it = items.begin(); it != items.end(); it++) {
164       if (it->addr_type == addr_type && it->addr == addr) {
165         return it;
166       }
167     }
168     return items.end();
169   }
170 
171   /* we keep maximum 7 devices in the cache */
172   const size_t cache_max = 7;
173   std::list<Item> items;
174 };
175 
176 /* Devices in this cache are waiting for eiter scan response, or chained packets
177  * on secondary channel */
178 AdvertisingCache cache;
179 
180 }  // namespace
181 
182 #if (BLE_VND_INCLUDED == TRUE)
183 static tBTM_BLE_CTRL_FEATURES_CBACK* p_ctrl_le_feature_rd_cmpl_cback = NULL;
184 #endif
185 /**********PAST & PS *******************/
186 using StartSyncCb = base::Callback<void(
187     uint8_t /*status*/, uint16_t /*sync_handle*/, uint8_t /*advertising_sid*/,
188     uint8_t /*address_type*/, RawAddress /*address*/, uint8_t /*phy*/,
189     uint16_t /*interval*/)>;
190 using SyncReportCb = base::Callback<void(
191     uint16_t /*sync_handle*/, int8_t /*tx_power*/, int8_t /*rssi*/,
192     uint8_t /*status*/, std::vector<uint8_t> /*data*/)>;
193 using SyncLostCb = base::Callback<void(uint16_t /*sync_handle*/)>;
194 using SyncTransferCb = base::Callback<void(uint8_t /*status*/, RawAddress)>;
195 #define MAX_SYNC_TRANSACTION 16
196 #define SYNC_TIMEOUT (30 * 1000)
197 #define ADV_SYNC_ESTB_EVT_LEN 16
198 #define SYNC_LOST_EVT_LEN 3
199 typedef enum {
200   PERIODIC_SYNC_IDLE = 0,
201   PERIODIC_SYNC_PENDING,
202   PERIODIC_SYNC_ESTABLISHED,
203   PERIODIC_SYNC_LOST,
204 } tBTM_BLE_PERIODIC_SYNC_STATE;
205 
206 struct alarm_t* sync_timeout_alarm;
207 typedef struct {
208   uint8_t sid;
209   RawAddress remote_bda;
210   tBTM_BLE_PERIODIC_SYNC_STATE sync_state;
211   uint16_t sync_handle;
212   bool in_use;
213   StartSyncCb sync_start_cb;
214   SyncReportCb sync_report_cb;
215   SyncLostCb sync_lost_cb;
216   BigInfoReportCb biginfo_report_cb;
217 } tBTM_BLE_PERIODIC_SYNC;
218 
219 typedef struct {
220   bool in_use;
221   int conn_handle;
222   RawAddress addr;
223   SyncTransferCb cb;
224 } tBTM_BLE_PERIODIC_SYNC_TRANSFER;
225 
226 static list_t* sync_queue;
227 static std::mutex sync_queue_mutex_;
228 
229 typedef struct {
230   bool busy;
231   uint8_t sid;
232   RawAddress address;
233   uint16_t skip;
234   uint16_t timeout;
235 } sync_node_t;
236 typedef struct {
237   uint8_t sid;
238   RawAddress address;
239 } remove_sync_node_t;
240 typedef enum {
241   BTM_QUEUE_SYNC_REQ_EVT,
242   BTM_QUEUE_SYNC_ADVANCE_EVT,
243   BTM_QUEUE_SYNC_CLEANUP_EVT
244 } btif_queue_event_t;
245 
246 typedef struct {
247   tBTM_BLE_PERIODIC_SYNC p_sync[MAX_SYNC_TRANSACTION];
248   tBTM_BLE_PERIODIC_SYNC_TRANSFER sync_transfer[MAX_SYNC_TRANSACTION];
249 } tBTM_BLE_PA_SYNC_TX_CB;
250 tBTM_BLE_PA_SYNC_TX_CB btm_ble_pa_sync_cb;
251 StartSyncCb sync_rcvd_cb;
252 static bool syncRcvdCbRegistered = false;
253 static int btm_ble_get_psync_index(uint8_t adv_sid, RawAddress addr);
254 static void btm_ble_start_sync_timeout(void* data);
255 
256 /*****************************/
257 /*******************************************************************************
258  *  Local functions
259  ******************************************************************************/
260 static void btm_ble_update_adv_flag(uint8_t flag);
261 void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type,
262                                   const RawAddress& bda, uint8_t primary_phy,
263                                   uint8_t secondary_phy,
264                                   uint8_t advertising_sid, int8_t tx_power,
265                                   int8_t rssi, uint16_t periodic_adv_int,
266                                   uint8_t data_len, const uint8_t* data,
267                                   const RawAddress& original_bda);
268 static uint8_t btm_set_conn_mode_adv_init_addr(RawAddress& p_peer_addr_ptr,
269                                                tBLE_ADDR_TYPE* p_peer_addr_type,
270                                                tBLE_ADDR_TYPE* p_own_addr_type);
271 static void btm_ble_stop_observe(void);
272 static void btm_ble_fast_adv_timer_timeout(void* data);
273 static void btm_ble_start_slow_adv(void);
274 static void btm_ble_inquiry_timer_gap_limited_discovery_timeout(void* data);
275 static void btm_ble_inquiry_timer_timeout(void* data);
276 static void btm_ble_observer_timer_timeout(void* data);
277 
278 enum : uint8_t {
279   BTM_BLE_NOT_SCANNING = 0x00,
280   BTM_BLE_INQ_RESULT = 0x01,
281   BTM_BLE_OBS_RESULT = 0x02,
282 };
283 
ble_evt_type_is_connectable(uint16_t evt_type)284 static bool ble_evt_type_is_connectable(uint16_t evt_type) {
285   return evt_type & (1 << BLE_EVT_CONNECTABLE_BIT);
286 }
287 
ble_evt_type_is_scannable(uint16_t evt_type)288 static bool ble_evt_type_is_scannable(uint16_t evt_type) {
289   return evt_type & (1 << BLE_EVT_SCANNABLE_BIT);
290 }
291 
ble_evt_type_is_directed(uint16_t evt_type)292 static bool ble_evt_type_is_directed(uint16_t evt_type) {
293   return evt_type & (1 << BLE_EVT_DIRECTED_BIT);
294 }
295 
ble_evt_type_is_scan_resp(uint16_t evt_type)296 static bool ble_evt_type_is_scan_resp(uint16_t evt_type) {
297   return evt_type & (1 << BLE_EVT_SCAN_RESPONSE_BIT);
298 }
299 
ble_evt_type_is_legacy(uint16_t evt_type)300 static bool ble_evt_type_is_legacy(uint16_t evt_type) {
301   return evt_type & (1 << BLE_EVT_LEGACY_BIT);
302 }
303 
ble_evt_type_data_status(uint16_t evt_type)304 static uint8_t ble_evt_type_data_status(uint16_t evt_type) {
305   return (evt_type >> 5) & 3;
306 }
307 
308 constexpr uint8_t UNSUPPORTED = 255;
309 
310 /* LE states combo bit to check */
311 const uint8_t btm_le_state_combo_tbl[BTM_BLE_STATE_MAX][BTM_BLE_STATE_MAX] = {
312     {
313         /* single state support */
314         HCI_LE_STATES_CONN_ADV_BIT,   /* conn_adv */
315         HCI_LE_STATES_INIT_BIT,       /* init */
316         HCI_LE_STATES_INIT_BIT,       /* central */
317         HCI_LE_STATES_PERIPHERAL_BIT, /* peripheral */
318         UNSUPPORTED,                  /* todo: lo du dir adv, not covered ? */
319         HCI_LE_STATES_HI_DUTY_DIR_ADV_BIT, /* hi duty dir adv */
320         HCI_LE_STATES_NON_CONN_ADV_BIT,    /* non connectable adv */
321         HCI_LE_STATES_PASS_SCAN_BIT,       /*  passive scan */
322         HCI_LE_STATES_ACTIVE_SCAN_BIT,     /*   active scan */
323         HCI_LE_STATES_SCAN_ADV_BIT         /* scanable adv */
324     },
325     {
326         /* conn_adv =0 */
327         UNSUPPORTED,                            /* conn_adv */
328         HCI_LE_STATES_CONN_ADV_INIT_BIT,        /* init: 32 */
329         HCI_LE_STATES_CONN_ADV_CENTRAL_BIT,     /* central: 35 */
330         HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT,  /* peripheral: 38,*/
331         UNSUPPORTED,                            /* lo du dir adv */
332         UNSUPPORTED,                            /* hi duty dir adv */
333         UNSUPPORTED,                            /* non connectable adv */
334         HCI_LE_STATES_CONN_ADV_PASS_SCAN_BIT,   /*  passive scan */
335         HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_BIT, /*   active scan */
336         UNSUPPORTED                             /* scanable adv */
337     },
338     {
339         /* init */
340         HCI_LE_STATES_CONN_ADV_INIT_BIT,           /* conn_adv: 32 */
341         UNSUPPORTED,                               /* init */
342         HCI_LE_STATES_INIT_CENTRAL_BIT,            /* central 28 */
343         HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT, /* peripheral 41 */
344         HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_BIT,    /* lo du dir adv 34 */
345         HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_BIT,    /* hi duty dir adv 33 */
346         HCI_LE_STATES_NON_CONN_INIT_BIT,           /*  non connectable adv */
347         HCI_LE_STATES_PASS_SCAN_INIT_BIT,          /* passive scan */
348         HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT,        /*  active scan */
349         HCI_LE_STATES_SCAN_ADV_INIT_BIT            /* scanable adv */
350 
351     },
352     {
353         /* central */
354         HCI_LE_STATES_CONN_ADV_CENTRAL_BIT,        /* conn_adv: 35 */
355         HCI_LE_STATES_INIT_CENTRAL_BIT,            /* init 28 */
356         HCI_LE_STATES_INIT_CENTRAL_BIT,            /* central 28 */
357         HCI_LE_STATES_CONN_ADV_INIT_BIT,           /* peripheral: 32 */
358         HCI_LE_STATES_LO_DUTY_DIR_ADV_CENTRAL_BIT, /* lo duty cycle adv 37 */
359         HCI_LE_STATES_HI_DUTY_DIR_ADV_CENTRAL_BIT, /* hi duty cycle adv 36 */
360         HCI_LE_STATES_NON_CONN_ADV_CENTRAL_BIT,    /*  non connectable adv*/
361         HCI_LE_STATES_PASS_SCAN_CENTRAL_BIT,       /*  passive scan */
362         HCI_LE_STATES_ACTIVE_SCAN_CENTRAL_BIT,     /*   active scan */
363         HCI_LE_STATES_SCAN_ADV_CENTRAL_BIT         /*  scanable adv */
364 
365     },
366     {
367         /* peripheral */
368         HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT,        /* conn_adv: 38,*/
369         HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT,    /* init 41 */
370         HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT,    /* central 41 */
371         HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT,        /* peripheral: 38,*/
372         HCI_LE_STATES_LO_DUTY_DIR_ADV_PERIPHERAL_BIT, /* lo duty cycle adv 40 */
373         HCI_LE_STATES_HI_DUTY_DIR_ADV_PERIPHERAL_BIT, /* hi duty cycle adv 39 */
374         HCI_LE_STATES_NON_CONN_ADV_PERIPHERAL_BIT,    /* non connectable adv */
375         HCI_LE_STATES_PASS_SCAN_PERIPHERAL_BIT,       /* passive scan */
376         HCI_LE_STATES_ACTIVE_SCAN_PERIPHERAL_BIT,     /*  active scan */
377         HCI_LE_STATES_SCAN_ADV_PERIPHERAL_BIT         /* scanable adv */
378 
379     },
380     {
381         /* lo duty cycle adv */
382         UNSUPPORTED,                                  /* conn_adv: 38,*/
383         HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_BIT,       /* init 34 */
384         HCI_LE_STATES_LO_DUTY_DIR_ADV_CENTRAL_BIT,    /* central 37 */
385         HCI_LE_STATES_LO_DUTY_DIR_ADV_PERIPHERAL_BIT, /* peripheral: 40 */
386         UNSUPPORTED,                                  /* lo duty cycle adv 40 */
387         UNSUPPORTED,                                  /* hi duty cycle adv 39 */
388         UNSUPPORTED,                                  /*  non connectable adv */
389         UNSUPPORTED, /* TODO: passive scan, not covered? */
390         UNSUPPORTED, /* TODO:  active scan, not covered? */
391         UNSUPPORTED  /*  scanable adv */
392     },
393     {
394         /* hi duty cycle adv */
395         UNSUPPORTED,                                  /* conn_adv: 38,*/
396         HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_BIT,       /* init 33 */
397         HCI_LE_STATES_HI_DUTY_DIR_ADV_CENTRAL_BIT,    /* central 36 */
398         HCI_LE_STATES_HI_DUTY_DIR_ADV_PERIPHERAL_BIT, /* peripheral: 39*/
399         UNSUPPORTED,                                  /* lo duty cycle adv 40 */
400         UNSUPPORTED,                                  /* hi duty cycle adv 39 */
401         UNSUPPORTED,                                  /* non connectable adv */
402         HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_BIT,  /* passive scan */
403         HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_BIT, /* active scan */
404         UNSUPPORTED                                    /* scanable adv */
405     },
406     {
407         /* non connectable adv */
408         UNSUPPORTED,                                /* conn_adv: */
409         HCI_LE_STATES_NON_CONN_INIT_BIT,            /* init  */
410         HCI_LE_STATES_NON_CONN_ADV_CENTRAL_BIT,     /* central  */
411         HCI_LE_STATES_NON_CONN_ADV_PERIPHERAL_BIT,  /* peripheral: */
412         UNSUPPORTED,                                /* lo duty cycle adv */
413         UNSUPPORTED,                                /* hi duty cycle adv */
414         UNSUPPORTED,                                /* non connectable adv */
415         HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_BIT,   /* passive scan */
416         HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_BIT, /* active scan */
417         UNSUPPORTED                                 /* scanable adv */
418     },
419     {
420         /* passive scan */
421         HCI_LE_STATES_CONN_ADV_PASS_SCAN_BIT,        /* conn_adv: */
422         HCI_LE_STATES_PASS_SCAN_INIT_BIT,            /* init  */
423         HCI_LE_STATES_PASS_SCAN_CENTRAL_BIT,         /* central  */
424         HCI_LE_STATES_PASS_SCAN_PERIPHERAL_BIT,      /* peripheral: */
425         UNSUPPORTED,                                 /* lo duty cycle adv */
426         HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_BIT, /* hi duty cycle adv */
427         HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_BIT,    /* non connectable adv */
428         UNSUPPORTED,                                 /* passive scan */
429         UNSUPPORTED,                                 /* active scan */
430         HCI_LE_STATES_SCAN_ADV_PASS_SCAN_BIT         /* scanable adv */
431     },
432     {
433         /* active scan */
434         HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_BIT,        /* conn_adv: */
435         HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT,            /* init  */
436         HCI_LE_STATES_ACTIVE_SCAN_CENTRAL_BIT,         /* central  */
437         HCI_LE_STATES_ACTIVE_SCAN_PERIPHERAL_BIT,      /* peripheral: */
438         UNSUPPORTED,                                   /* lo duty cycle adv */
439         HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_BIT, /* hi duty cycle adv */
440         HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_BIT, /*  non connectable adv */
441         UNSUPPORTED,                                /* TODO: passive scan */
442         UNSUPPORTED,                                /* TODO:  active scan */
443         HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_BIT      /*  scanable adv */
444     },
445     {
446         /* scanable adv */
447         UNSUPPORTED,                            /* conn_adv: */
448         HCI_LE_STATES_SCAN_ADV_INIT_BIT,        /* init  */
449         HCI_LE_STATES_SCAN_ADV_CENTRAL_BIT,     /* central  */
450         HCI_LE_STATES_SCAN_ADV_PERIPHERAL_BIT,  /* peripheral: */
451         UNSUPPORTED,                            /* lo duty cycle adv */
452         UNSUPPORTED,                            /* hi duty cycle adv */
453         UNSUPPORTED,                            /* non connectable adv */
454         HCI_LE_STATES_SCAN_ADV_PASS_SCAN_BIT,   /*  passive scan */
455         HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_BIT, /*  active scan */
456         UNSUPPORTED                             /* scanable adv */
457     }};
458 
459 /* check LE combo state supported */
BTM_LE_STATES_SUPPORTED(const uint8_t * x,uint8_t bit_num)460 inline bool BTM_LE_STATES_SUPPORTED(const uint8_t* x, uint8_t bit_num) {
461   uint8_t mask = 1 << (bit_num % 8);
462   uint8_t offset = bit_num / 8;
463   return ((x)[offset] & mask);
464 }
465 
BTM_BleOpportunisticObserve(bool enable,tBTM_INQ_RESULTS_CB * p_results_cb)466 void BTM_BleOpportunisticObserve(bool enable,
467                                  tBTM_INQ_RESULTS_CB* p_results_cb) {
468   if (enable) {
469     btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb = p_results_cb;
470   } else {
471     btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb = NULL;
472   }
473 }
474 
BTM_BleTargetAnnouncementObserve(bool enable,tBTM_INQ_RESULTS_CB * p_results_cb)475 void BTM_BleTargetAnnouncementObserve(bool enable,
476                                       tBTM_INQ_RESULTS_CB* p_results_cb) {
477   if (enable) {
478     btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb = p_results_cb;
479   } else {
480     btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb = NULL;
481   }
482 }
483 
484 /*******************************************************************************
485  *
486  * Function         BTM_BleObserve
487  *
488  * Description      This procedure keep the device listening for advertising
489  *                  events from a broadcast device.
490  *
491  * Parameters       start: start or stop observe.
492  *                  duration: how long the scan should last, in seconds. 0 means
493  *                  scan without timeout. Starting the scan second time without
494  *                  timeout will disable the timer.
495  *                  low_latency_scan: whether this is a low latency scan,
496  *                                    default is false.
497  *
498  * Returns          void
499  *
500  ******************************************************************************/
BTM_BleObserve(bool start,uint8_t duration,tBTM_INQ_RESULTS_CB * p_results_cb,tBTM_CMPL_CB * p_cmpl_cb,bool low_latency_scan)501 tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration,
502                            tBTM_INQ_RESULTS_CB* p_results_cb,
503                            tBTM_CMPL_CB* p_cmpl_cb, bool low_latency_scan) {
504   tBTM_BLE_INQ_CB* p_inq = &btm_cb.ble_ctr_cb.inq_var;
505   tBTM_STATUS status = BTM_WRONG_MODE;
506 
507   uint32_t scan_interval =
508       !p_inq->scan_interval ? BTM_BLE_GAP_DISC_SCAN_INT : p_inq->scan_interval;
509   uint32_t scan_window =
510       !p_inq->scan_window ? BTM_BLE_GAP_DISC_SCAN_WIN : p_inq->scan_window;
511 
512   // use low latency scanning if the scanning is active
513   if (low_latency_scan) {
514     scan_interval = BTM_BLE_LOW_LATENCY_SCAN_INT;
515     scan_window = BTM_BLE_LOW_LATENCY_SCAN_WIN;
516   }
517 
518   BTM_TRACE_EVENT("%s : scan_type:%d, %d, %d", __func__, p_inq->scan_type,
519                   scan_interval, scan_window);
520 
521   if (!controller_get_interface()->supports_ble()) return BTM_ILLEGAL_VALUE;
522 
523   if (start) {
524     /* shared inquiry database, do not allow observe if any inquiry is active.
525      * except we are doing CSIS active scanning
526      */
527     if (btm_cb.ble_ctr_cb.is_ble_observe_active()) {
528       if (duration == 0) {
529         if (alarm_is_scheduled(btm_cb.ble_ctr_cb.observer_timer)) {
530           alarm_cancel(btm_cb.ble_ctr_cb.observer_timer);
531         } else {
532           BTM_TRACE_ERROR("%s Scan with no duration started twice!", __func__);
533         }
534       } else {
535         if (!low_latency_scan &&
536             alarm_is_scheduled(btm_cb.ble_ctr_cb.observer_timer)) {
537           BTM_TRACE_ERROR("%s Scan with duration started twice!", __func__);
538         }
539       }
540       /*
541        * we stop current observation request for below scenarios
542        * 1. if the scan we wish to start is not low latency
543        * 2. current ongoing scanning is low latency
544        */
545       bool is_ongoing_low_latency =
546           p_inq->scan_interval == BTM_BLE_GAP_DISC_SCAN_INT &&
547           p_inq->scan_window == BTM_BLE_LOW_LATENCY_SCAN_WIN;
548       if (!low_latency_scan || is_ongoing_low_latency) {
549         BTM_TRACE_WARNING("%s Observer was already active, is_low_latency: %d",
550                           __func__, is_ongoing_low_latency);
551         return BTM_CMD_STARTED;
552       }
553       // stop any scan without low latency config
554       btm_ble_stop_observe();
555     }
556 
557     btm_cb.ble_ctr_cb.p_obs_results_cb = p_results_cb;
558     btm_cb.ble_ctr_cb.p_obs_cmpl_cb = p_cmpl_cb;
559     status = BTM_CMD_STARTED;
560 
561     /* scan is not started */
562     if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) {
563       /* allow config of scan type */
564       cache.ClearAll();
565       p_inq->scan_type = (p_inq->scan_type == BTM_BLE_SCAN_MODE_NONE)
566                              ? BTM_BLE_SCAN_MODE_ACTI
567                              : p_inq->scan_type;
568       btm_send_hci_set_scan_params(
569           p_inq->scan_type, (uint16_t)scan_interval, (uint16_t)scan_window,
570           btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, BTM_BLE_DEFAULT_SFP);
571 
572       btm_ble_start_scan();
573     }
574 
575     btm_cb.neighbor.le_observe = {
576         .start_time_ms = timestamper_in_milliseconds.GetTimestamp(),
577         .results = 0,
578     };
579 
580     BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le observe started",
581                    base::StringPrintf("low latency scanning enabled: %d",
582                                       low_latency_scan));
583 
584     if (status == BTM_CMD_STARTED) {
585       btm_cb.ble_ctr_cb.set_ble_observe_active();
586       if (duration != 0) {
587         /* start observer timer */
588         uint64_t duration_ms = duration * 1000;
589         alarm_set_on_mloop(btm_cb.ble_ctr_cb.observer_timer, duration_ms,
590                            btm_ble_observer_timer_timeout, NULL);
591       }
592     }
593   } else if (btm_cb.ble_ctr_cb.is_ble_observe_active()) {
594     const unsigned long long duration_timestamp =
595         timestamper_in_milliseconds.GetTimestamp() -
596         btm_cb.neighbor.le_observe.start_time_ms;
597     BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le observe stopped",
598                    base::StringPrintf("duration_s:%6.3f results:%-3lu",
599                                       (double)duration_timestamp / 1000.0,
600                                       btm_cb.neighbor.le_observe.results));
601     status = BTM_CMD_STARTED;
602     btm_ble_stop_observe();
603   } else {
604     BTM_TRACE_ERROR("%s Observe not active", __func__);
605   }
606 
607   return status;
608 }
609 
610 #if (BLE_VND_INCLUDED == TRUE)
611 
btm_get_dynamic_audio_buffer_vsc_cmpl_cback(tBTM_VSC_CMPL * p_vsc_cmpl_params)612 static void btm_get_dynamic_audio_buffer_vsc_cmpl_cback(
613     tBTM_VSC_CMPL* p_vsc_cmpl_params) {
614   LOG(INFO) << __func__;
615 
616   if (p_vsc_cmpl_params->param_len < 1) {
617     LOG(ERROR) << __func__
618                << ": The length of returned parameters is less than 1";
619     return;
620   }
621   uint8_t* p_event_param_buf = p_vsc_cmpl_params->p_param_buf;
622   uint8_t status = 0xff;
623   uint8_t opcode = 0xff;
624   uint32_t codec_mask = 0xffffffff;
625 
626   // [Return Parameter]         | [Size]   | [Purpose]
627   // Status                     | 1 octet  | Command complete status
628   // Dynamic_Audio_Buffer_opcode| 1 octet  | 0x01 - Get buffer time
629   // Audio_Codedc_Type_Supported| 4 octet  | Bit masks for selected codec types
630   // Audio_Codec_Buffer_Time    | 192 octet| Default/Max/Min buffer time
631   STREAM_TO_UINT8(status, p_event_param_buf);
632   if (status != HCI_SUCCESS) {
633     LOG(ERROR) << __func__
634                << ": Fail to configure DFTB. status: " << loghex(status);
635     return;
636   }
637 
638   if (p_vsc_cmpl_params->param_len != 198) {
639     LOG(FATAL) << __func__
640                << ": The length of returned parameters is not equal to 198: "
641                << std::to_string(p_vsc_cmpl_params->param_len);
642     return;
643   }
644 
645   STREAM_TO_UINT8(opcode, p_event_param_buf);
646   LOG(INFO) << __func__ << ": opcode = " << loghex(opcode);
647 
648   if (opcode == 0x01) {
649     STREAM_TO_UINT32(codec_mask, p_event_param_buf);
650     LOG(INFO) << __func__ << ": codec_mask = " << loghex(codec_mask);
651 
652     for (int i = 0; i < BTM_CODEC_TYPE_MAX_RECORDS; i++) {
653       STREAM_TO_UINT16(btm_cb.dynamic_audio_buffer_cb[i].default_buffer_time,
654                        p_event_param_buf);
655       STREAM_TO_UINT16(btm_cb.dynamic_audio_buffer_cb[i].maximum_buffer_time,
656                        p_event_param_buf);
657       STREAM_TO_UINT16(btm_cb.dynamic_audio_buffer_cb[i].minimum_buffer_time,
658                        p_event_param_buf);
659     }
660 
661     LOG(INFO) << __func__ << ": Succeed to receive Media Tx Buffer.";
662   }
663 }
664 
665 /*******************************************************************************
666  *
667  * Function         btm_vsc_brcm_features_complete
668  *
669  * Description      Command Complete callback for HCI_BLE_VENDOR_CAP
670  *
671  * Returns          void
672  *
673  ******************************************************************************/
btm_ble_vendor_capability_vsc_cmpl_cback(tBTM_VSC_CMPL * p_vcs_cplt_params)674 static void btm_ble_vendor_capability_vsc_cmpl_cback(
675     tBTM_VSC_CMPL* p_vcs_cplt_params) {
676   BTM_TRACE_DEBUG("%s", __func__);
677 
678   /* Check status of command complete event */
679   CHECK(p_vcs_cplt_params->opcode == HCI_BLE_VENDOR_CAP);
680   CHECK(p_vcs_cplt_params->param_len > 0);
681 
682   const uint8_t* p = p_vcs_cplt_params->p_param_buf;
683   uint8_t raw_status;
684   STREAM_TO_UINT8(raw_status, p);
685   tHCI_STATUS status = to_hci_status_code(raw_status);
686 
687   if (status != HCI_SUCCESS) {
688     BTM_TRACE_DEBUG("%s: Status = 0x%02x (0 is success)", __func__, status);
689     return;
690   }
691   CHECK(p_vcs_cplt_params->param_len >= BTM_VSC_CHIP_CAPABILITY_RSP_LEN);
692   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.adv_inst_max, p);
693   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.rpa_offloading, p);
694   STREAM_TO_UINT16(btm_cb.cmn_ble_vsc_cb.tot_scan_results_strg, p);
695   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.max_irk_list_sz, p);
696   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.filter_support, p);
697   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.max_filter, p);
698   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.energy_support, p);
699 
700   if (p_vcs_cplt_params->param_len >
701       BTM_VSC_CHIP_CAPABILITY_RSP_LEN_L_RELEASE) {
702     STREAM_TO_UINT16(btm_cb.cmn_ble_vsc_cb.version_supported, p);
703   } else {
704     btm_cb.cmn_ble_vsc_cb.version_supported = BTM_VSC_CHIP_CAPABILITY_L_VERSION;
705   }
706 
707   if (btm_cb.cmn_ble_vsc_cb.version_supported >=
708       BTM_VSC_CHIP_CAPABILITY_M_VERSION) {
709     CHECK(p_vcs_cplt_params->param_len >=
710           BTM_VSC_CHIP_CAPABILITY_RSP_LEN_M_RELEASE);
711     STREAM_TO_UINT16(btm_cb.cmn_ble_vsc_cb.total_trackable_advertisers, p);
712     STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.extended_scan_support, p);
713     STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.debug_logging_supported, p);
714   }
715 
716   if (btm_cb.cmn_ble_vsc_cb.version_supported >=
717       BTM_VSC_CHIP_CAPABILITY_S_VERSION) {
718     if (p_vcs_cplt_params->param_len >=
719         BTM_VSC_CHIP_CAPABILITY_RSP_LEN_S_RELEASE) {
720       STREAM_TO_UINT8(
721           btm_cb.cmn_ble_vsc_cb.le_address_generation_offloading_support, p);
722       STREAM_TO_UINT32(
723           btm_cb.cmn_ble_vsc_cb.a2dp_source_offload_capability_mask, p);
724       STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.quality_report_support, p);
725       STREAM_TO_UINT32(btm_cb.cmn_ble_vsc_cb.dynamic_audio_buffer_support, p);
726 
727       if (btm_cb.cmn_ble_vsc_cb.dynamic_audio_buffer_support != 0) {
728         uint8_t param[3] = {0};
729         uint8_t* p_param = param;
730 
731         UINT8_TO_STREAM(p_param, HCI_CONTROLLER_DAB_GET_BUFFER_TIME);
732         BTM_VendorSpecificCommand(HCI_CONTROLLER_DAB, p_param - param, param,
733                                   btm_get_dynamic_audio_buffer_vsc_cmpl_cback);
734       }
735     }
736   }
737 
738   if (btm_cb.cmn_ble_vsc_cb.filter_support == 1 &&
739       controller_get_interface()->get_bt_version()->manufacturer ==
740           LMP_COMPID_QTI) {
741     // QTI controller, TDS data filter are supported by default. Check is added
742     // to keep backward compatibility.
743     btm_cb.cmn_ble_vsc_cb.adv_filter_extended_features_mask = 0x01;
744   } else {
745     btm_cb.cmn_ble_vsc_cb.adv_filter_extended_features_mask = 0x00;
746   }
747 
748   btm_cb.cmn_ble_vsc_cb.values_read = true;
749 
750   BTM_TRACE_DEBUG(
751       "%s: stat=%d, irk=%d, ADV ins:%d, rpa=%d, ener=%d, ext_scan=%d", __func__,
752       status, btm_cb.cmn_ble_vsc_cb.max_irk_list_sz,
753       btm_cb.cmn_ble_vsc_cb.adv_inst_max, btm_cb.cmn_ble_vsc_cb.rpa_offloading,
754       btm_cb.cmn_ble_vsc_cb.energy_support,
755       btm_cb.cmn_ble_vsc_cb.extended_scan_support);
756 
757   btm_ble_adv_init();
758 
759   if (btm_cb.cmn_ble_vsc_cb.max_filter > 0) btm_ble_adv_filter_init();
760 
761   /* VS capability included and non-4.2 device */
762   if (controller_get_interface()->supports_ble() &&
763       controller_get_interface()->supports_ble_privacy() &&
764       btm_cb.cmn_ble_vsc_cb.max_irk_list_sz > 0 &&
765       controller_get_interface()->get_ble_resolving_list_max_size() == 0)
766     btm_ble_resolving_list_init(btm_cb.cmn_ble_vsc_cb.max_irk_list_sz);
767 
768   if (btm_cb.cmn_ble_vsc_cb.tot_scan_results_strg > 0) btm_ble_batchscan_init();
769 
770   if (p_ctrl_le_feature_rd_cmpl_cback != NULL)
771     p_ctrl_le_feature_rd_cmpl_cback(static_cast<tHCI_STATUS>(status));
772 }
773 #endif /* (BLE_VND_INCLUDED == TRUE) */
774 
775 /*******************************************************************************
776  *
777  * Function         BTM_BleGetVendorCapabilities
778  *
779  * Description      This function reads local LE features
780  *
781  * Parameters       p_cmn_vsc_cb : Locala LE capability structure
782  *
783  * Returns          void
784  *
785  ******************************************************************************/
BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB * p_cmn_vsc_cb)786 void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB* p_cmn_vsc_cb) {
787   if (NULL != p_cmn_vsc_cb) {
788     *p_cmn_vsc_cb = btm_cb.cmn_ble_vsc_cb;
789   }
790 }
791 
BTM_BleGetDynamicAudioBuffer(tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB p_dynamic_audio_buffer_cb[])792 void BTM_BleGetDynamicAudioBuffer(
793     tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB p_dynamic_audio_buffer_cb[]) {
794   BTM_TRACE_DEBUG("BTM_BleGetDynamicAudioBuffer");
795 
796   if (NULL != p_dynamic_audio_buffer_cb) {
797     for (int i = 0; i < 32; i++) {
798       p_dynamic_audio_buffer_cb[i] = btm_cb.dynamic_audio_buffer_cb[i];
799     }
800   }
801 }
802 
803 /******************************************************************************
804  *
805  * Function         BTM_BleReadControllerFeatures
806  *
807  * Description      Reads BLE specific controller features
808  *
809  * Parameters:      tBTM_BLE_CTRL_FEATURES_CBACK : Callback to notify when
810  *                  features are read
811  *
812  * Returns          void
813  *
814  ******************************************************************************/
815 #if (BLE_VND_INCLUDED == TRUE)
BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK * p_vsc_cback)816 void BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK* p_vsc_cback) {
817   if (btm_cb.cmn_ble_vsc_cb.values_read) return;
818 
819   BTM_TRACE_DEBUG("BTM_BleReadControllerFeatures");
820 
821   p_ctrl_le_feature_rd_cmpl_cback = p_vsc_cback;
822   BTM_VendorSpecificCommand(HCI_BLE_VENDOR_CAP, 0, NULL,
823                             btm_ble_vendor_capability_vsc_cmpl_cback);
824 }
825 #else
BTM_BleReadControllerFeatures(UNUSED_ATTR tBTM_BLE_CTRL_FEATURES_CBACK * p_vsc_cback)826 void BTM_BleReadControllerFeatures(
827     UNUSED_ATTR tBTM_BLE_CTRL_FEATURES_CBACK* p_vsc_cback) {}
828 #endif
829 
830 /*******************************************************************************
831  *
832  * Function         BTM_BleConfigPrivacy
833  *
834  * Description      This function is called to enable or disable the privacy in
835  *                   LE channel of the local device.
836  *
837  * Parameters       privacy_mode:  privacy mode on or off.
838  *
839  * Returns          bool    privacy mode set success; otherwise failed.
840  *
841  ******************************************************************************/
BTM_BleConfigPrivacy(bool privacy_mode)842 bool BTM_BleConfigPrivacy(bool privacy_mode) {
843   tBTM_BLE_CB* p_cb = &btm_cb.ble_ctr_cb;
844 
845   BTM_TRACE_WARNING("%s %d", __func__, (int)privacy_mode);
846 
847   /* if LE is not supported, return error */
848   if (!controller_get_interface()->supports_ble()) return false;
849 
850   tGAP_BLE_ATTR_VALUE gap_ble_attr_value;
851   gap_ble_attr_value.addr_resolution = 0;
852   if (!privacy_mode) /* if privacy disabled, always use public address */
853   {
854     p_cb->addr_mgnt_cb.own_addr_type = BLE_ADDR_PUBLIC;
855     p_cb->privacy_mode = BTM_PRIVACY_NONE;
856   } else /* privacy is turned on*/
857   {
858     /* always set host random address, used when privacy 1.1 or priavcy 1.2 is
859      * disabled */
860     p_cb->addr_mgnt_cb.own_addr_type = BLE_ADDR_RANDOM;
861     btm_gen_resolvable_private_addr(base::Bind(&btm_gen_resolve_paddr_low));
862 
863     /* 4.2 controller only allow privacy 1.2 or mixed mode, resolvable private
864      * address in controller */
865     if (controller_get_interface()->supports_ble_privacy()) {
866       gap_ble_attr_value.addr_resolution = 1;
867       p_cb->privacy_mode = BTM_PRIVACY_1_2;
868     } else /* 4.1/4.0 controller */
869       p_cb->privacy_mode = BTM_PRIVACY_1_1;
870   }
871   VLOG(2) << __func__ << " privacy_mode: " << p_cb->privacy_mode
872           << " own_addr_type: " << p_cb->addr_mgnt_cb.own_addr_type;
873 
874   GAP_BleAttrDBUpdate(GATT_UUID_GAP_CENTRAL_ADDR_RESOL, &gap_ble_attr_value);
875 
876   bluetooth::shim::ACL_ConfigureLePrivacy(privacy_mode);
877   return true;
878 }
879 
880 /*******************************************************************************
881  *
882  * Function          BTM_BleMaxMultiAdvInstanceCount
883  *
884  * Description        Returns max number of multi adv instances supported by
885  *                  controller
886  *
887  * Returns          Max multi adv instance count
888  *
889  ******************************************************************************/
BTM_BleMaxMultiAdvInstanceCount(void)890 uint8_t BTM_BleMaxMultiAdvInstanceCount(void) {
891   return btm_cb.cmn_ble_vsc_cb.adv_inst_max < BTM_BLE_MULTI_ADV_MAX
892              ? btm_cb.cmn_ble_vsc_cb.adv_inst_max
893              : BTM_BLE_MULTI_ADV_MAX;
894 }
895 
896 /*******************************************************************************
897  *
898  * Function         BTM_BleLocalPrivacyEnabled
899  *
900  * Description        Checks if local device supports private address
901  *
902  * Returns          Return true if local privacy is enabled else false
903  *
904  ******************************************************************************/
BTM_BleLocalPrivacyEnabled(void)905 bool BTM_BleLocalPrivacyEnabled(void) {
906   return (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE);
907 }
908 
is_resolving_list_bit_set(void * data,void * context)909 static bool is_resolving_list_bit_set(void* data, void* context) {
910   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
911 
912   if ((p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) != 0)
913     return false;
914 
915   return true;
916 }
917 
918 /*******************************************************************************
919  * PAST and Periodic Sync helper functions
920  ******************************************************************************/
921 
sync_queue_add(sync_node_t * p_param)922 static void sync_queue_add(sync_node_t* p_param) {
923   std::unique_lock<std::mutex> guard(sync_queue_mutex_);
924   if (!sync_queue) {
925     LOG_INFO("%s: allocating sync queue", __func__);
926     sync_queue = list_new(osi_free);
927     CHECK(sync_queue != NULL);
928   }
929 
930   // Validity check
931   CHECK(list_length(sync_queue) < MAX_SYNC_TRANSACTION);
932   sync_node_t* p_node = (sync_node_t*)osi_malloc(sizeof(sync_node_t));
933   *p_node = *p_param;
934   list_append(sync_queue, p_node);
935 }
936 
sync_queue_advance()937 static void sync_queue_advance() {
938   LOG_DEBUG("%s", "");
939   std::unique_lock<std::mutex> guard(sync_queue_mutex_);
940 
941   if (sync_queue && !list_is_empty(sync_queue)) {
942     sync_node_t* p_head = (sync_node_t*)list_front(sync_queue);
943     LOG_INFO("queue_advance");
944     list_remove(sync_queue, p_head);
945   }
946 }
947 
sync_queue_cleanup(remove_sync_node_t * p_param)948 static void sync_queue_cleanup(remove_sync_node_t* p_param) {
949   std::unique_lock<std::mutex> guard(sync_queue_mutex_);
950   if (!sync_queue) {
951     return;
952   }
953 
954   sync_node_t* sync_request;
955   const list_node_t* node = list_begin(sync_queue);
956   while (node && node != list_end(sync_queue)) {
957     sync_request = (sync_node_t*)list_node(node);
958     node = list_next(node);
959     if (sync_request->sid == p_param->sid &&
960         sync_request->address == p_param->address) {
961       LOG_INFO("%s: removing connection request SID=%04X, bd_addr=%s, busy=%d",
962                __func__, sync_request->sid,
963                ADDRESS_TO_LOGGABLE_CSTR(sync_request->address),
964                sync_request->busy);
965       list_remove(sync_queue, sync_request);
966     }
967   }
968 }
969 
btm_ble_start_sync_request(uint8_t sid,RawAddress addr,uint16_t skip,uint16_t timeout)970 void btm_ble_start_sync_request(uint8_t sid, RawAddress addr, uint16_t skip,
971                                 uint16_t timeout) {
972   tBLE_ADDR_TYPE address_type = BLE_ADDR_RANDOM;
973   tINQ_DB_ENT* p_i = btm_inq_db_find(addr);
974   if (p_i) {
975     address_type = p_i->inq_info.results.ble_addr_type;  // Random
976   }
977   btm_random_pseudo_to_identity_addr(&addr, &address_type);
978   address_type &= ~BLE_ADDR_TYPE_ID_BIT;
979   uint8_t options = 0;
980   uint8_t cte_type = 7;
981   int index = btm_ble_get_psync_index(sid, addr);
982 
983   if (index == MAX_SYNC_TRANSACTION) {
984     LOG_ERROR("Failed to get sync transfer index");
985     return;
986   }
987 
988   tBTM_BLE_PERIODIC_SYNC* p = &btm_ble_pa_sync_cb.p_sync[index];
989   p->sync_state = PERIODIC_SYNC_PENDING;
990 
991   if (BleScanningManager::IsInitialized()) {
992     BleScanningManager::Get()->PeriodicScanStart(options, sid, address_type,
993                                                  addr, skip, timeout, cte_type);
994   }
995 
996   alarm_set(sync_timeout_alarm, SYNC_TIMEOUT, btm_ble_start_sync_timeout, NULL);
997 }
998 
btm_queue_sync_next()999 static void btm_queue_sync_next() {
1000   if (!sync_queue || list_is_empty(sync_queue)) {
1001     LOG_DEBUG("sync_queue empty");
1002     return;
1003   }
1004 
1005   sync_node_t* p_head = (sync_node_t*)list_front(sync_queue);
1006 
1007   LOG_INFO("%s: executing sync request SID=%04X, bd_addr=%s", __func__,
1008            p_head->sid, ADDRESS_TO_LOGGABLE_CSTR(p_head->address));
1009   if (p_head->busy) {
1010     LOG_DEBUG("BUSY");
1011     return;
1012   }
1013 
1014   p_head->busy = true;
1015   alarm_cancel(sync_timeout_alarm);
1016   btm_ble_start_sync_request(p_head->sid, p_head->address, p_head->skip,
1017                              p_head->timeout);
1018 }
1019 
btm_ble_sync_queue_handle(uint16_t event,char * param)1020 static void btm_ble_sync_queue_handle(uint16_t event, char* param) {
1021   switch (event) {
1022     case BTM_QUEUE_SYNC_REQ_EVT:
1023       LOG_DEBUG("BTIF_QUEUE_SYNC_REQ_EVT");
1024       sync_queue_add((sync_node_t*)param);
1025       break;
1026     case BTM_QUEUE_SYNC_ADVANCE_EVT:
1027       LOG_DEBUG("BTIF_QUEUE_ADVANCE_EVT");
1028       sync_queue_advance();
1029       break;
1030     case BTM_QUEUE_SYNC_CLEANUP_EVT:
1031       sync_queue_cleanup((remove_sync_node_t*)param);
1032       return;
1033   }
1034   btm_queue_sync_next();
1035 }
1036 
btm_queue_start_sync_req(uint8_t sid,RawAddress address,uint16_t skip,uint16_t timeout)1037 void btm_queue_start_sync_req(uint8_t sid, RawAddress address, uint16_t skip,
1038                               uint16_t timeout) {
1039   LOG_DEBUG("address = %s, sid = %d", ADDRESS_TO_LOGGABLE_CSTR(address), sid);
1040   sync_node_t node = {};
1041   node.sid = sid;
1042   node.address = address;
1043   node.skip = skip;
1044   node.timeout = timeout;
1045   btm_ble_sync_queue_handle(BTM_QUEUE_SYNC_REQ_EVT, (char*)&node);
1046 }
1047 
btm_sync_queue_advance()1048 static void btm_sync_queue_advance() {
1049   LOG_DEBUG("%s", "");
1050   btm_ble_sync_queue_handle(BTM_QUEUE_SYNC_ADVANCE_EVT, nullptr);
1051 }
1052 
btm_ble_start_sync_timeout(void * data)1053 static void btm_ble_start_sync_timeout(void* data) {
1054   LOG_DEBUG("%s", "");
1055   sync_node_t* p_head = (sync_node_t*)list_front(sync_queue);
1056   uint8_t adv_sid = p_head->sid;
1057   RawAddress address = p_head->address;
1058 
1059   int index = btm_ble_get_psync_index(adv_sid, address);
1060 
1061   if (index == MAX_SYNC_TRANSACTION) {
1062     LOG_ERROR("Failed to get sync transfer index");
1063     return;
1064   }
1065 
1066   tBTM_BLE_PERIODIC_SYNC* p = &btm_ble_pa_sync_cb.p_sync[index];
1067 
1068   if (BleScanningManager::IsInitialized()) {
1069     BleScanningManager::Get()->PeriodicScanCancelStart();
1070   }
1071   p->sync_start_cb.Run(0x3C, 0, p->sid, 0, p->remote_bda, 0, 0);
1072 
1073   p->sync_state = PERIODIC_SYNC_IDLE;
1074   p->in_use = false;
1075   p->remote_bda = RawAddress::kEmpty;
1076   p->sid = 0;
1077   p->sync_handle = 0;
1078   p->in_use = false;
1079 }
1080 
btm_ble_get_free_psync_index()1081 static int btm_ble_get_free_psync_index() {
1082   int i;
1083   for (i = 0; i < MAX_SYNC_TRANSACTION; i++) {
1084     if (btm_ble_pa_sync_cb.p_sync[i].in_use == false) {
1085       LOG_DEBUG("found index at %d", i);
1086       return i;
1087     }
1088   }
1089   return i;
1090 }
1091 
btm_ble_get_psync_index_from_handle(uint16_t handle)1092 static int btm_ble_get_psync_index_from_handle(uint16_t handle) {
1093   int i;
1094   for (i = 0; i < MAX_SYNC_TRANSACTION; i++) {
1095     if (btm_ble_pa_sync_cb.p_sync[i].sync_handle == handle &&
1096         btm_ble_pa_sync_cb.p_sync[i].sync_state == PERIODIC_SYNC_ESTABLISHED) {
1097       LOG_DEBUG("found index at %d", i);
1098       return i;
1099     }
1100   }
1101   return i;
1102 }
1103 
btm_ble_get_psync_index(uint8_t adv_sid,RawAddress addr)1104 static int btm_ble_get_psync_index(uint8_t adv_sid, RawAddress addr) {
1105   int i;
1106   for (i = 0; i < MAX_SYNC_TRANSACTION; i++) {
1107     if (btm_ble_pa_sync_cb.p_sync[i].sid == adv_sid &&
1108         btm_ble_pa_sync_cb.p_sync[i].remote_bda == addr) {
1109       LOG_DEBUG("found index at %d", i);
1110       return i;
1111     }
1112   }
1113   return i;
1114 }
1115 
btm_ble_get_free_sync_transfer_index()1116 static int btm_ble_get_free_sync_transfer_index() {
1117   int i;
1118   for (i = 0; i < MAX_SYNC_TRANSACTION; i++) {
1119     if (!btm_ble_pa_sync_cb.sync_transfer[i].in_use) {
1120       LOG_DEBUG("found index at %d", i);
1121       return i;
1122     }
1123   }
1124   return i;
1125 }
1126 
btm_ble_get_sync_transfer_index(uint16_t conn_handle)1127 static int btm_ble_get_sync_transfer_index(uint16_t conn_handle) {
1128   int i;
1129   for (i = 0; i < MAX_SYNC_TRANSACTION; i++) {
1130     if (btm_ble_pa_sync_cb.sync_transfer[i].conn_handle == conn_handle) {
1131       LOG_DEBUG("found index at %d", i);
1132       return i;
1133     }
1134   }
1135   return i;
1136 }
1137 
1138 /*******************************************************************************
1139  *
1140  * Function         btm_ble_periodic_adv_sync_established
1141  *
1142  * Description      Periodic Adv Sync Established callback from controller when
1143  &                  sync to PA is established
1144  *
1145  *
1146  ******************************************************************************/
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)1147 void btm_ble_periodic_adv_sync_established(uint8_t status, uint16_t sync_handle,
1148                                            uint8_t adv_sid,
1149                                            uint8_t address_type,
1150                                            const RawAddress& addr, uint8_t phy,
1151                                            uint16_t interval,
1152                                            uint8_t adv_clock_accuracy) {
1153   LOG_DEBUG(
1154       "[PSync]: status=%d, sync_handle=%d, s_id=%d, "
1155       "addr_type=%d, adv_phy=%d,adv_interval=%d, clock_acc=%d",
1156       status, sync_handle, adv_sid, address_type, phy, interval,
1157       adv_clock_accuracy);
1158 
1159   /*if (param_len != ADV_SYNC_ESTB_EVT_LEN) {
1160     BTM_TRACE_ERROR("[PSync]%s: Invalid event length",__func__);
1161     STREAM_TO_UINT8(status, param);
1162     if (status == BTM_SUCCESS) {
1163       STREAM_TO_UINT16(sync_handle, param);
1164       //btsnd_hcic_ble_terminate_periodic_sync(sync_handle);
1165       if (BleScanningManager::IsInitialized()) {
1166         BleScanningManager::Get()->PeriodicScanTerminate(sync_handle);
1167       }
1168       return;
1169     }
1170   }*/
1171 
1172   RawAddress bda = addr;
1173   alarm_cancel(sync_timeout_alarm);
1174 
1175   tBLE_ADDR_TYPE ble_addr_type = to_ble_addr_type(address_type);
1176   if (ble_addr_type & BLE_ADDR_TYPE_ID_BIT) {
1177     btm_identity_addr_to_random_pseudo(&bda, &ble_addr_type, true);
1178   }
1179   int index = btm_ble_get_psync_index(adv_sid, bda);
1180   if (index == MAX_SYNC_TRANSACTION) {
1181     BTM_TRACE_WARNING("[PSync]%s: Invalid index for sync established",
1182                       __func__);
1183     if (status == BTM_SUCCESS) {
1184       BTM_TRACE_WARNING("%s: Terminate sync", __func__);
1185       if (BleScanningManager::IsInitialized()) {
1186         BleScanningManager::Get()->PeriodicScanTerminate(sync_handle);
1187       }
1188     }
1189     btm_sync_queue_advance();
1190     return;
1191   }
1192   tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index];
1193   ps->sync_handle = sync_handle;
1194   ps->sync_state = PERIODIC_SYNC_ESTABLISHED;
1195   ps->sync_start_cb.Run(status, sync_handle, adv_sid,
1196                         from_ble_addr_type(ble_addr_type), bda, phy, interval);
1197   btm_sync_queue_advance();
1198 }
1199 
1200 /*******************************************************************************
1201  *
1202  * Function        btm_ble_periodic_adv_report
1203  *
1204  * Description     This callback is received when controller estalishes sync
1205  *                 to a PA requested from host
1206  *
1207  ******************************************************************************/
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)1208 void btm_ble_periodic_adv_report(uint16_t sync_handle, uint8_t tx_power,
1209                                  int8_t rssi, uint8_t cte_type,
1210                                  uint8_t data_status, uint8_t data_len,
1211                                  const uint8_t* periodic_data) {
1212   LOG_DEBUG(
1213       "[PSync]: sync_handle = %u, tx_power = %d, rssi = %d,"
1214       "cte_type = %u, data_status = %u, data_len = %u",
1215       sync_handle, tx_power, rssi, cte_type, data_status, data_len);
1216 
1217   std::vector<uint8_t> data;
1218   for (int i = 0; i < data_len; i++) {
1219     data.push_back(periodic_data[i]);
1220   }
1221   int index = btm_ble_get_psync_index_from_handle(sync_handle);
1222   if (index == MAX_SYNC_TRANSACTION) {
1223     LOG_ERROR("[PSync]: index not found for handle %u", sync_handle);
1224     return;
1225   }
1226   tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index];
1227   LOG_DEBUG("%s", "[PSync]: invoking callback");
1228   ps->sync_report_cb.Run(sync_handle, tx_power, rssi, data_status, data);
1229 }
1230 
1231 /*******************************************************************************
1232  *
1233  * Function        btm_ble_periodic_adv_sync_lost
1234  *
1235  * Description     This callback is received when sync to PA is lost
1236  *
1237  ******************************************************************************/
btm_ble_periodic_adv_sync_lost(uint16_t sync_handle)1238 void btm_ble_periodic_adv_sync_lost(uint16_t sync_handle) {
1239   LOG_DEBUG("[PSync]: sync_handle = %d", sync_handle);
1240 
1241   int index = btm_ble_get_psync_index_from_handle(sync_handle);
1242   if (index == MAX_SYNC_TRANSACTION) {
1243     LOG_ERROR("[PSync]: index not found for handle %u", sync_handle);
1244     return;
1245   }
1246   tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index];
1247   ps->sync_lost_cb.Run(sync_handle);
1248 
1249   ps->in_use = false;
1250   ps->sid = 0;
1251   ps->sync_handle = 0;
1252   ps->sync_state = PERIODIC_SYNC_IDLE;
1253   ps->remote_bda = RawAddress::kEmpty;
1254 }
1255 
1256 /*******************************************************************************
1257  *
1258  * Function        BTM_BleStartPeriodicSync
1259  *
1260  * Description     Create sync request to PA associated with address and sid
1261  *
1262  ******************************************************************************/
BTM_BleStartPeriodicSync(uint8_t adv_sid,RawAddress address,uint16_t skip,uint16_t timeout,StartSyncCb syncCb,SyncReportCb reportCb,SyncLostCb lostCb,BigInfoReportCb biginfo_reportCb)1263 void BTM_BleStartPeriodicSync(uint8_t adv_sid, RawAddress address,
1264                               uint16_t skip, uint16_t timeout,
1265                               StartSyncCb syncCb, SyncReportCb reportCb,
1266                               SyncLostCb lostCb, BigInfoReportCb biginfo_reportCb) {
1267   LOG_DEBUG("%s", "[PSync]");
1268   int index = btm_ble_get_free_psync_index();
1269 
1270   if (index == MAX_SYNC_TRANSACTION) {
1271     syncCb.Run(BTM_NO_RESOURCES, 0, adv_sid, BLE_ADDR_RANDOM, address, 0, 0);
1272     return;
1273   }
1274 
1275   tBTM_BLE_PERIODIC_SYNC* p = &btm_ble_pa_sync_cb.p_sync[index];
1276 
1277   p->in_use = true;
1278   p->remote_bda = address;
1279   p->sid = adv_sid;
1280   p->sync_start_cb = syncCb;
1281   p->sync_report_cb = reportCb;
1282   p->sync_lost_cb = lostCb;
1283   p->biginfo_report_cb = biginfo_reportCb;
1284   btm_queue_start_sync_req(adv_sid, address, skip, timeout);
1285 }
1286 
1287 /*******************************************************************************
1288  *
1289  * Function        BTM_BleStopPeriodicSync
1290  *
1291  * Description     Terminate sync request to PA associated with sync handle
1292  *
1293  ******************************************************************************/
BTM_BleStopPeriodicSync(uint16_t handle)1294 void BTM_BleStopPeriodicSync(uint16_t handle) {
1295   LOG_DEBUG("[PSync]: handle = %u", handle);
1296   int index = btm_ble_get_psync_index_from_handle(handle);
1297   if (index == MAX_SYNC_TRANSACTION) {
1298     LOG_ERROR("[PSync]: invalid index for handle %u", handle);
1299     if (BleScanningManager::IsInitialized()) {
1300       BleScanningManager::Get()->PeriodicScanTerminate(handle);
1301     }
1302     return;
1303   }
1304   tBTM_BLE_PERIODIC_SYNC* p = &btm_ble_pa_sync_cb.p_sync[index];
1305   p->sync_state = PERIODIC_SYNC_IDLE;
1306   p->in_use = false;
1307   p->remote_bda = RawAddress::kEmpty;
1308   p->sid = 0;
1309   p->sync_handle = 0;
1310   p->in_use = false;
1311   if (BleScanningManager::IsInitialized()) {
1312     BleScanningManager::Get()->PeriodicScanTerminate(handle);
1313   }
1314 }
1315 
1316 /*******************************************************************************
1317  *
1318  * Function        BTM_BleCancelPeriodicSync
1319  *
1320  * Description     Cancel create sync request to PA associated with sid and
1321  *                 address
1322  *
1323  ******************************************************************************/
BTM_BleCancelPeriodicSync(uint8_t adv_sid,RawAddress address)1324 void BTM_BleCancelPeriodicSync(uint8_t adv_sid, RawAddress address) {
1325   LOG_DEBUG("%s", "[PSync]");
1326   int index = btm_ble_get_psync_index(adv_sid, address);
1327   if (index == MAX_SYNC_TRANSACTION) {
1328     LOG_ERROR("[PSync]:Invalid index for sid=%u", adv_sid);
1329     return;
1330   }
1331   tBTM_BLE_PERIODIC_SYNC* p = &btm_ble_pa_sync_cb.p_sync[index];
1332   if (p->sync_state == PERIODIC_SYNC_PENDING) {
1333     LOG_WARN("[PSync]: Sync state is pending for index %d", index);
1334     if (BleScanningManager::IsInitialized()) {
1335       BleScanningManager::Get()->PeriodicScanCancelStart();
1336     }
1337   } else if (p->sync_state == PERIODIC_SYNC_IDLE) {
1338     LOG_DEBUG("[PSync]: Removing Sync request from queue for index %d", index);
1339     remove_sync_node_t remove_node;
1340     remove_node.sid = adv_sid;
1341     remove_node.address = address;
1342     btm_ble_sync_queue_handle(BTM_QUEUE_SYNC_CLEANUP_EVT, (char*)&remove_node);
1343   }
1344   p->sync_state = PERIODIC_SYNC_IDLE;
1345   p->in_use = false;
1346   p->remote_bda = RawAddress::kEmpty;
1347   p->sid = 0;
1348   p->sync_handle = 0;
1349   p->in_use = false;
1350 }
1351 
1352 /*******************************************************************************
1353  *
1354  * Function        btm_ble_periodic_syc_transfer_cmd_cmpl
1355  *
1356  * Description     PAST complete callback
1357  *
1358  ******************************************************************************/
btm_ble_periodic_syc_transfer_cmd_cmpl(uint8_t status,uint16_t conn_handle)1359 void btm_ble_periodic_syc_transfer_cmd_cmpl(uint8_t status,
1360                                             uint16_t conn_handle) {
1361   LOG_DEBUG("[PAST]: status = %d, conn_handle =%d", status, conn_handle);
1362 
1363   int index = btm_ble_get_sync_transfer_index(conn_handle);
1364   if (index == MAX_SYNC_TRANSACTION) {
1365     LOG_ERROR("[PAST]:Invalid, conn_handle %u not found in DB", conn_handle);
1366     return;
1367   }
1368 
1369   tBTM_BLE_PERIODIC_SYNC_TRANSFER* p_sync_transfer =
1370       &btm_ble_pa_sync_cb.sync_transfer[index];
1371   p_sync_transfer->cb.Run(status, p_sync_transfer->addr);
1372 
1373   p_sync_transfer->in_use = false;
1374   p_sync_transfer->conn_handle = -1;
1375   p_sync_transfer->addr = RawAddress::kEmpty;
1376 }
1377 
btm_ble_periodic_syc_transfer_param_cmpl(uint8_t status)1378 void btm_ble_periodic_syc_transfer_param_cmpl(uint8_t status) {
1379   LOG_DEBUG("[PAST]: status = %d", status);
1380 }
1381 
1382 /*******************************************************************************
1383  *
1384  * Function        BTM_BlePeriodicSyncTransfer
1385  *
1386  * Description     Initiate PAST to connected remote device with sync handle
1387  *
1388  ******************************************************************************/
BTM_BlePeriodicSyncTransfer(RawAddress addr,uint16_t service_data,uint16_t sync_handle,SyncTransferCb cb)1389 void BTM_BlePeriodicSyncTransfer(RawAddress addr, uint16_t service_data,
1390                                  uint16_t sync_handle, SyncTransferCb cb) {
1391   uint16_t conn_handle = BTM_GetHCIConnHandle(addr, BT_TRANSPORT_LE);
1392   tACL_CONN* p_acl = btm_acl_for_bda(addr, BT_TRANSPORT_LE);
1393   BTM_TRACE_DEBUG("[PAST]%s for connection_handle = %x", __func__, conn_handle);
1394   if (conn_handle == 0xFFFF || p_acl == NULL) {
1395     BTM_TRACE_ERROR("[PAST]%s:Invalid connection handle or no LE ACL link",
1396                     __func__);
1397     cb.Run(BTM_UNKNOWN_ADDR, addr);
1398     return;
1399   }
1400 
1401   if (!HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT(
1402           p_acl->peer_le_features)) {
1403     BTM_TRACE_ERROR("[PAST]%s:Remote doesn't support PAST", __func__);
1404     cb.Run(BTM_MODE_UNSUPPORTED, addr);
1405     return;
1406   }
1407 
1408   int index = btm_ble_get_free_sync_transfer_index();
1409   if (index == MAX_SYNC_TRANSACTION) {
1410     BTM_TRACE_ERROR("Failed to get sync transfer index");
1411     cb.Run(BTM_ILLEGAL_VALUE, addr);
1412     return;
1413   }
1414 
1415   tBTM_BLE_PERIODIC_SYNC_TRANSFER* p_sync_transfer =
1416       &btm_ble_pa_sync_cb.sync_transfer[index];
1417   p_sync_transfer->in_use = true;
1418   p_sync_transfer->conn_handle = conn_handle;
1419   p_sync_transfer->addr = addr;
1420   p_sync_transfer->cb = cb;
1421   if (BleScanningManager::IsInitialized()) {
1422     BleScanningManager::Get()->PeriodicAdvSyncTransfer(
1423         addr, service_data, sync_handle,
1424         base::Bind(&btm_ble_periodic_syc_transfer_cmd_cmpl));
1425   }
1426 }
1427 
1428 /*******************************************************************************
1429  *
1430  * Function        BTM_BlePeriodicSyncSetInfo
1431  *
1432  * Description     Initiate PAST to connected remote device with adv handle
1433  *
1434  ******************************************************************************/
BTM_BlePeriodicSyncSetInfo(RawAddress addr,uint16_t service_data,uint8_t adv_handle,SyncTransferCb cb)1435 void BTM_BlePeriodicSyncSetInfo(RawAddress addr, uint16_t service_data,
1436                                 uint8_t adv_handle, SyncTransferCb cb) {
1437   uint16_t conn_handle = BTM_GetHCIConnHandle(addr, BT_TRANSPORT_LE);
1438   tACL_CONN* p_acl = btm_acl_for_bda(addr, BT_TRANSPORT_LE);
1439   LOG_DEBUG("[PAST] for connection_handle = %u", conn_handle);
1440   if (conn_handle == 0xFFFF || p_acl == nullptr) {
1441     LOG_ERROR("[PAST]:Invalid connection handle %u or no LE ACL link",
1442               conn_handle);
1443     cb.Run(BTM_UNKNOWN_ADDR, addr);
1444     return;
1445   }
1446   if (!HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT(
1447           p_acl->peer_le_features)) {
1448     LOG_ERROR("%s", "[PAST]:Remote doesn't support PAST");
1449     cb.Run(BTM_MODE_UNSUPPORTED, addr);
1450     return;
1451   }
1452 
1453   int index = btm_ble_get_free_sync_transfer_index();
1454   if (index == MAX_SYNC_TRANSACTION) {
1455     BTM_TRACE_ERROR("Failed to get sync transfer index");
1456     cb.Run(BTM_ILLEGAL_VALUE, addr);
1457     return;
1458   }
1459 
1460   tBTM_BLE_PERIODIC_SYNC_TRANSFER* p_sync_transfer =
1461       &btm_ble_pa_sync_cb.sync_transfer[index];
1462   p_sync_transfer->in_use = true;
1463   p_sync_transfer->conn_handle = conn_handle;
1464   p_sync_transfer->addr = addr;
1465   p_sync_transfer->cb = cb;
1466   if (BleScanningManager::IsInitialized()) {
1467     BleScanningManager::Get()->PeriodicAdvSetInfoTransfer(
1468         addr, service_data, adv_handle,
1469         base::Bind(&btm_ble_periodic_syc_transfer_cmd_cmpl));
1470   }
1471 }
1472 
1473 /*******************************************************************************
1474  *
1475  * Function        btm_ble_biginfo_adv_report_rcvd
1476  *
1477  * Description     Host receives this event when synced PA has BIGInfo
1478  *
1479  ******************************************************************************/
btm_ble_biginfo_adv_report_rcvd(uint8_t * p,uint16_t param_len)1480 void btm_ble_biginfo_adv_report_rcvd(uint8_t* p, uint16_t param_len) {
1481   LOG_DEBUG("[PAST]: BIGINFO report received, len=%u", param_len);
1482   uint16_t sync_handle, iso_interval, max_pdu, max_sdu;
1483   uint8_t num_bises, nse, bn, pto, irc, phy, framing, encryption;
1484   uint32_t sdu_interval;
1485 
1486   // 2 bytes for sync handle, 1 byte for num_bises, 1 byte for nse, 2 bytes for
1487   // iso_interval, 1 byte each for bn, pto, irc, 2 bytes for max_pdu, 3 bytes
1488   // for sdu_interval, 2 bytes for max_sdu, 1 byte each for phy, framing,
1489   // encryption
1490   if (param_len < 19) {
1491     LOG_ERROR("Insufficient data");
1492     return;
1493   }
1494 
1495   STREAM_TO_UINT16(sync_handle, p);
1496   STREAM_TO_UINT8(num_bises, p);
1497   STREAM_TO_UINT8(nse, p);
1498   STREAM_TO_UINT16(iso_interval, p);
1499   STREAM_TO_UINT8(bn, p);
1500   STREAM_TO_UINT8(pto, p);
1501   STREAM_TO_UINT8(irc, p);
1502   STREAM_TO_UINT16(max_pdu, p);
1503   STREAM_TO_UINT24(sdu_interval, p);
1504   STREAM_TO_UINT16(max_sdu, p);
1505   STREAM_TO_UINT8(phy, p);
1506   STREAM_TO_UINT8(framing, p);
1507   STREAM_TO_UINT8(encryption, p);
1508   LOG_DEBUG(
1509       "[PAST]:sync_handle %u, num_bises = %u, nse = %u,"
1510       "iso_interval = %d, bn = %u, pto = %u, irc = %u, max_pdu = %u "
1511       "sdu_interval = %d, max_sdu = %u, phy = %u, framing = %u, encryption  = "
1512       "%u",
1513       sync_handle, num_bises, nse, iso_interval, bn, pto, irc, max_pdu,
1514       sdu_interval, max_sdu, phy, framing, encryption);
1515 
1516   int index = btm_ble_get_psync_index_from_handle(sync_handle);
1517   if (index == MAX_SYNC_TRANSACTION) {
1518     LOG_ERROR("[PSync]: index not found for handle %u", sync_handle);
1519     return;
1520   }
1521   tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index];
1522   LOG_DEBUG("%s", "[PSync]: invoking callback");
1523   ps->biginfo_report_cb.Run(sync_handle, encryption ? true : false);
1524 }
1525 
1526 /*******************************************************************************
1527  *
1528  * Function        btm_ble_periodic_adv_sync_tx_rcvd
1529  *
1530  * Description     Host receives this event when the controller receives sync
1531  *                 info of PA from the connected remote device and successfully
1532  *                 synced to PA associated with sync handle
1533  *
1534  ******************************************************************************/
btm_ble_periodic_adv_sync_tx_rcvd(uint8_t * p,uint16_t param_len)1535 void btm_ble_periodic_adv_sync_tx_rcvd(uint8_t* p, uint16_t param_len) {
1536   LOG_DEBUG("[PAST]: PAST received, param_len=%u", param_len);
1537   if (param_len < 19) {
1538     LOG_ERROR("%s", "Insufficient data");
1539     return;
1540   }
1541   uint8_t status, adv_sid, address_type, adv_phy, clk_acc;
1542   uint16_t pa_int, sync_handle, service_data, conn_handle;
1543   RawAddress addr;
1544   STREAM_TO_UINT8(status, p);
1545   STREAM_TO_UINT16(conn_handle, p);
1546   STREAM_TO_UINT16(service_data, p);
1547   STREAM_TO_UINT16(sync_handle, p);
1548   STREAM_TO_UINT8(adv_sid, p);
1549   STREAM_TO_UINT8(address_type, p);
1550   STREAM_TO_BDADDR(addr, p);
1551   STREAM_TO_UINT8(adv_phy, p);
1552   STREAM_TO_UINT16(pa_int, p);
1553   STREAM_TO_UINT8(clk_acc, p);
1554   BTM_TRACE_DEBUG(
1555       "[PAST]: status = %u, conn_handle = %u, service_data = %u,"
1556       " sync_handle = %u, adv_sid = %u, address_type = %u, addr = %s,"
1557       " adv_phy = %u, pa_int = %u, clk_acc = %u",
1558       status, conn_handle, service_data, sync_handle, adv_sid, address_type,
1559       ADDRESS_TO_LOGGABLE_CSTR(addr), adv_phy, pa_int, clk_acc);
1560   if (syncRcvdCbRegistered) {
1561     sync_rcvd_cb.Run(status, sync_handle, adv_sid, address_type, addr, adv_phy,
1562                      pa_int);
1563   }
1564 }
1565 
1566 /*******************************************************************************
1567  *
1568  * Function        BTM_BlePeriodicSyncTxParameters
1569  *
1570  * Description     On receiver side this command is used to specify how BT SoC
1571  *                 will process PA sync info received from the remote device
1572  *                 identified by the addr.
1573  *
1574  ******************************************************************************/
BTM_BlePeriodicSyncTxParameters(RawAddress addr,uint8_t mode,uint16_t skip,uint16_t timeout,StartSyncCb syncCb)1575 void BTM_BlePeriodicSyncTxParameters(RawAddress addr, uint8_t mode,
1576                                      uint16_t skip, uint16_t timeout,
1577                                      StartSyncCb syncCb) {
1578   LOG_DEBUG("[PAST]: mode=%u, skip=%u, timeout=%u", mode, skip, timeout);
1579   uint8_t cte_type = 7;
1580   sync_rcvd_cb = syncCb;
1581   syncRcvdCbRegistered = true;
1582   if (BleScanningManager::IsInitialized()) {
1583     BleScanningManager::Get()->SetPeriodicAdvSyncTransferParams(
1584         addr, mode, skip, timeout, cte_type, true,
1585         base::Bind(&btm_ble_periodic_syc_transfer_param_cmpl));
1586   }
1587 }
1588 
1589 /*******************************************************************************
1590  *
1591  * Function         btm_set_conn_mode_adv_init_addr
1592  *
1593  * Description      set initator address type and local address type based on
1594  *                  adv mode.
1595  *
1596  *
1597  ******************************************************************************/
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)1598 static uint8_t btm_set_conn_mode_adv_init_addr(
1599     RawAddress& p_peer_addr_ptr, tBLE_ADDR_TYPE* p_peer_addr_type,
1600     tBLE_ADDR_TYPE* p_own_addr_type) {
1601   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
1602   uint8_t evt_type;
1603   tBTM_SEC_DEV_REC* p_dev_rec;
1604 
1605   if (p_cb->connectable_mode == BTM_BLE_NON_CONNECTABLE) {
1606     if (p_cb->scan_rsp) {
1607       evt_type = BTM_BLE_DISCOVER_EVT;
1608     } else {
1609       evt_type = BTM_BLE_NON_CONNECT_EVT;
1610     }
1611   } else {
1612     evt_type = BTM_BLE_CONNECT_EVT;
1613   }
1614 
1615   if (evt_type == BTM_BLE_CONNECT_EVT) {
1616     CHECK(p_peer_addr_type != nullptr);
1617     const tBLE_BD_ADDR ble_bd_addr = {
1618         .bda = p_peer_addr_ptr,
1619         .type = *p_peer_addr_type,
1620     };
1621     LOG_DEBUG("Received BLE connect event %s", ADDRESS_TO_LOGGABLE_CSTR(ble_bd_addr));
1622 
1623     evt_type = p_cb->directed_conn;
1624 
1625     if (p_cb->directed_conn == BTM_BLE_CONNECT_DIR_EVT ||
1626         p_cb->directed_conn == BTM_BLE_CONNECT_LO_DUTY_DIR_EVT) {
1627       /* for privacy 1.2, convert peer address as static, own address set as ID
1628        * addr */
1629       if (btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_1_2 ||
1630           btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_MIXED) {
1631         /* only do so for bonded device */
1632         if ((p_dev_rec = btm_find_or_alloc_dev(p_cb->direct_bda.bda)) != NULL &&
1633             p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) {
1634           p_peer_addr_ptr = p_dev_rec->ble.identity_address_with_type.bda;
1635           *p_peer_addr_type = p_dev_rec->ble.identity_address_with_type.type;
1636           *p_own_addr_type = BLE_ADDR_RANDOM_ID;
1637           return evt_type;
1638         }
1639         /* otherwise fall though as normal directed adv */
1640       }
1641       /* direct adv mode does not have privacy, if privacy is not enabled  */
1642       *p_peer_addr_type = p_cb->direct_bda.type;
1643       p_peer_addr_ptr = p_cb->direct_bda.bda;
1644       return evt_type;
1645     }
1646   }
1647 
1648   /* undirect adv mode or non-connectable mode*/
1649   /* when privacy 1.2 privacy only mode is used, or mixed mode */
1650   if ((btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_1_2 &&
1651        p_cb->afp != AP_SCAN_CONN_ALL) ||
1652       btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_MIXED) {
1653     list_node_t* n =
1654         list_foreach(btm_cb.sec_dev_rec, is_resolving_list_bit_set, NULL);
1655     if (n) {
1656       /* if enhanced privacy is required, set Identity address and matching IRK
1657        * peer */
1658       tBTM_SEC_DEV_REC* p_dev_rec =
1659           static_cast<tBTM_SEC_DEV_REC*>(list_node(n));
1660       p_peer_addr_ptr = p_dev_rec->ble.identity_address_with_type.bda;
1661       *p_peer_addr_type = p_dev_rec->ble.identity_address_with_type.type;
1662 
1663       *p_own_addr_type = BLE_ADDR_RANDOM_ID;
1664     } else {
1665       /* resolving list is empty, not enabled */
1666       *p_own_addr_type = BLE_ADDR_RANDOM;
1667     }
1668   }
1669   /* privacy 1.1, or privacy 1.2, general discoverable/connectable mode, disable
1670      privacy in */
1671   /* controller fall back to host based privacy */
1672   else if (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE) {
1673     *p_own_addr_type = BLE_ADDR_RANDOM;
1674   }
1675 
1676   /* if no privacy,do not set any peer address,*/
1677   /* local address type go by global privacy setting */
1678   return evt_type;
1679 }
1680 
1681 /**
1682  * This function is called to set scan parameters. |cb| is called with operation
1683  * status
1684  **/
BTM_BleSetScanParams(uint32_t scan_interval,uint32_t scan_window,tBLE_SCAN_MODE scan_mode,base::Callback<void (uint8_t)> cb)1685 void BTM_BleSetScanParams(uint32_t scan_interval, uint32_t scan_window,
1686                           tBLE_SCAN_MODE scan_mode,
1687                           base::Callback<void(uint8_t)> cb) {
1688   if (!controller_get_interface()->supports_ble()) {
1689     LOG_INFO("Controller does not support ble");
1690     return;
1691   }
1692 
1693   uint32_t max_scan_interval = BTM_BLE_EXT_SCAN_INT_MAX;
1694   uint32_t max_scan_window = BTM_BLE_EXT_SCAN_WIN_MAX;
1695   if (btm_cb.cmn_ble_vsc_cb.extended_scan_support == 0) {
1696     max_scan_interval = BTM_BLE_SCAN_INT_MAX;
1697     max_scan_window = BTM_BLE_SCAN_WIN_MAX;
1698   }
1699 
1700   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
1701   if (BTM_BLE_ISVALID_PARAM(scan_interval, BTM_BLE_SCAN_INT_MIN,
1702                             max_scan_interval) &&
1703       BTM_BLE_ISVALID_PARAM(scan_window, BTM_BLE_SCAN_WIN_MIN,
1704                             max_scan_window) &&
1705       (scan_mode == BTM_BLE_SCAN_MODE_ACTI ||
1706        scan_mode == BTM_BLE_SCAN_MODE_PASS)) {
1707     p_cb->scan_type = scan_mode;
1708     p_cb->scan_interval = scan_interval;
1709     p_cb->scan_window = scan_window;
1710 
1711     cb.Run(BTM_SUCCESS);
1712   } else {
1713     cb.Run(BTM_ILLEGAL_VALUE);
1714     LOG_WARN("Illegal params: scan_interval = %d scan_window = %d",
1715              scan_interval, scan_window);
1716   }
1717 }
1718 
1719 /*******************************************************************************
1720  *
1721  * Function         BTM__BLEReadDiscoverability
1722  *
1723  * Description      This function is called to read the current LE
1724  *                  discoverability mode of the device.
1725  *
1726  * Returns          BTM_BLE_NON_DISCOVERABLE ,BTM_BLE_LIMITED_DISCOVERABLE or
1727  *                     BTM_BLE_GENRAL_DISCOVERABLE
1728  *
1729  ******************************************************************************/
BTM_BleReadDiscoverability()1730 uint16_t BTM_BleReadDiscoverability() {
1731   BTM_TRACE_API("%s", __func__);
1732 
1733   return (btm_cb.ble_ctr_cb.inq_var.discoverable_mode);
1734 }
1735 
1736 /*******************************************************************************
1737  *
1738  * Function         BTM__BLEReadConnectability
1739  *
1740  * Description      This function is called to read the current LE
1741  *                  connectability mode of the device.
1742  *
1743  * Returns          BTM_BLE_NON_CONNECTABLE or BTM_BLE_CONNECTABLE
1744  *
1745  ******************************************************************************/
BTM_BleReadConnectability()1746 uint16_t BTM_BleReadConnectability() {
1747   BTM_TRACE_API("%s", __func__);
1748 
1749   return (btm_cb.ble_ctr_cb.inq_var.connectable_mode);
1750 }
1751 
1752 /*******************************************************************************
1753  *
1754  * Function         btm_ble_select_adv_interval
1755  *
1756  * Description      select adv interval based on device mode
1757  *
1758  * Returns          void
1759  *
1760  ******************************************************************************/
btm_ble_select_adv_interval(uint8_t evt_type,uint16_t * p_adv_int_min,uint16_t * p_adv_int_max)1761 static void btm_ble_select_adv_interval(uint8_t evt_type,
1762                                         uint16_t* p_adv_int_min,
1763                                         uint16_t* p_adv_int_max) {
1764   switch (evt_type) {
1765     case BTM_BLE_CONNECT_EVT:
1766     case BTM_BLE_CONNECT_LO_DUTY_DIR_EVT:
1767       *p_adv_int_min = *p_adv_int_max = BTM_BLE_GAP_ADV_FAST_INT_1;
1768       break;
1769 
1770     case BTM_BLE_NON_CONNECT_EVT:
1771     case BTM_BLE_DISCOVER_EVT:
1772       *p_adv_int_min = *p_adv_int_max = BTM_BLE_GAP_ADV_FAST_INT_2;
1773       break;
1774 
1775       /* connectable directed event */
1776     case BTM_BLE_CONNECT_DIR_EVT:
1777       *p_adv_int_min = BTM_BLE_GAP_ADV_DIR_MIN_INT;
1778       *p_adv_int_max = BTM_BLE_GAP_ADV_DIR_MAX_INT;
1779       break;
1780 
1781     default:
1782       *p_adv_int_min = *p_adv_int_max = BTM_BLE_GAP_ADV_SLOW_INT;
1783       break;
1784   }
1785 }
1786 
1787 /*******************************************************************************
1788  *
1789  * Function         btm_ble_update_dmt_flag_bits
1790  *
1791  * Description      Obtain updated adv flag value based on connect and
1792  *                  discoverability mode. Also, setup DMT support value in the
1793  *                  flag based on whether the controller supports both LE and
1794  *                  BR/EDR.
1795  *
1796  * Parameters:      flag_value (Input / Output) - flag value
1797  *                  connect_mode (Input) - Connect mode value
1798  *                  disc_mode (Input) - discoverability mode
1799  *
1800  * Returns          void
1801  *
1802  ******************************************************************************/
btm_ble_update_dmt_flag_bits(uint8_t * adv_flag_value,const uint16_t connect_mode,const uint16_t disc_mode)1803 void btm_ble_update_dmt_flag_bits(uint8_t* adv_flag_value,
1804                                   const uint16_t connect_mode,
1805                                   const uint16_t disc_mode) {
1806   /* BR/EDR non-discoverable , non-connectable */
1807   if ((disc_mode & BTM_DISCOVERABLE_MASK) == 0 &&
1808       (connect_mode & BTM_CONNECTABLE_MASK) == 0)
1809     *adv_flag_value |= BTM_BLE_BREDR_NOT_SPT;
1810   else
1811     *adv_flag_value &= ~BTM_BLE_BREDR_NOT_SPT;
1812 
1813   /* if local controller support, mark both controller and host support in flag
1814    */
1815   if (controller_get_interface()->supports_simultaneous_le_bredr())
1816     *adv_flag_value |= (BTM_BLE_DMT_CONTROLLER_SPT | BTM_BLE_DMT_HOST_SPT);
1817   else
1818     *adv_flag_value &= ~(BTM_BLE_DMT_CONTROLLER_SPT | BTM_BLE_DMT_HOST_SPT);
1819 }
1820 
1821 /*******************************************************************************
1822  *
1823  * Function         btm_ble_set_adv_flag
1824  *
1825  * Description      Set adv flag in adv data.
1826  *
1827  * Parameters:      connect_mode (Input)- Connect mode value
1828  *                  disc_mode (Input) - discoverability mode
1829  *
1830  * Returns          void
1831  *
1832  ******************************************************************************/
btm_ble_set_adv_flag(uint16_t connect_mode,uint16_t disc_mode)1833 void btm_ble_set_adv_flag(uint16_t connect_mode, uint16_t disc_mode) {
1834   uint8_t flag = 0, old_flag = 0;
1835   tBTM_BLE_LOCAL_ADV_DATA* p_adv_data = &btm_cb.ble_ctr_cb.inq_var.adv_data;
1836 
1837   if (p_adv_data->p_flags != NULL) flag = old_flag = *(p_adv_data->p_flags);
1838 
1839   btm_ble_update_dmt_flag_bits(&flag, connect_mode, disc_mode);
1840 
1841   LOG_INFO("disc_mode %04x", disc_mode);
1842   /* update discoverable flag */
1843   if (disc_mode & BTM_BLE_LIMITED_DISCOVERABLE) {
1844     flag &= ~BTM_BLE_GEN_DISC_FLAG;
1845     flag |= BTM_BLE_LIMIT_DISC_FLAG;
1846   } else if (disc_mode & BTM_BLE_GENERAL_DISCOVERABLE) {
1847     flag |= BTM_BLE_GEN_DISC_FLAG;
1848     flag &= ~BTM_BLE_LIMIT_DISC_FLAG;
1849   } else /* remove all discoverable flags */
1850   {
1851     flag &= ~(BTM_BLE_LIMIT_DISC_FLAG | BTM_BLE_GEN_DISC_FLAG);
1852   }
1853 
1854   if (flag != old_flag) {
1855     btm_ble_update_adv_flag(flag);
1856   }
1857 }
1858 /*******************************************************************************
1859  *
1860  * Function         btm_ble_set_discoverability
1861  *
1862  * Description      This function is called to set BLE discoverable mode.
1863  *
1864  * Parameters:      combined_mode: discoverability mode.
1865  *
1866  * Returns          BTM_SUCCESS is status set successfully; otherwise failure.
1867  *
1868  ******************************************************************************/
btm_ble_set_discoverability(uint16_t combined_mode)1869 tBTM_STATUS btm_ble_set_discoverability(uint16_t combined_mode) {
1870   tBTM_LE_RANDOM_CB* p_addr_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
1871   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
1872   uint16_t mode = (combined_mode & BTM_BLE_DISCOVERABLE_MASK);
1873   uint8_t new_mode = BTM_BLE_ADV_ENABLE;
1874   uint8_t evt_type;
1875   tBTM_STATUS status = BTM_SUCCESS;
1876   RawAddress address = RawAddress::kEmpty;
1877   tBLE_ADDR_TYPE init_addr_type = BLE_ADDR_PUBLIC,
1878                  own_addr_type = p_addr_cb->own_addr_type;
1879   uint16_t adv_int_min, adv_int_max;
1880 
1881   BTM_TRACE_EVENT("%s mode=0x%0x combined_mode=0x%x", __func__, mode,
1882                   combined_mode);
1883 
1884   /*** Check mode parameter ***/
1885   if (mode > BTM_BLE_MAX_DISCOVERABLE) return (BTM_ILLEGAL_VALUE);
1886 
1887   p_cb->discoverable_mode = mode;
1888 
1889   evt_type =
1890       btm_set_conn_mode_adv_init_addr(address, &init_addr_type, &own_addr_type);
1891 
1892   if (p_cb->connectable_mode == BTM_BLE_NON_CONNECTABLE &&
1893       mode == BTM_BLE_NON_DISCOVERABLE)
1894     new_mode = BTM_BLE_ADV_DISABLE;
1895 
1896   btm_ble_select_adv_interval(evt_type, &adv_int_min, &adv_int_max);
1897 
1898   alarm_cancel(p_cb->fast_adv_timer);
1899 
1900   /* update adv params if start advertising */
1901   BTM_TRACE_EVENT("evt_type=0x%x p-cb->evt_type=0x%x ", evt_type,
1902                   p_cb->evt_type);
1903 
1904   if (new_mode == BTM_BLE_ADV_ENABLE) {
1905     btm_ble_set_adv_flag(btm_cb.btm_inq_vars.connectable_mode, combined_mode);
1906 
1907     if (evt_type != p_cb->evt_type || p_cb->adv_addr_type != own_addr_type ||
1908         !p_cb->fast_adv_on) {
1909       btm_ble_stop_adv();
1910 
1911       /* update adv params */
1912       btsnd_hcic_ble_write_adv_params(adv_int_min, adv_int_max, evt_type,
1913                                       own_addr_type, init_addr_type, address,
1914                                       p_cb->adv_chnl_map, p_cb->afp);
1915       p_cb->evt_type = evt_type;
1916       p_cb->adv_addr_type = own_addr_type;
1917     }
1918   }
1919 
1920   if (status == BTM_SUCCESS && p_cb->adv_mode != new_mode) {
1921     if (new_mode == BTM_BLE_ADV_ENABLE)
1922       status = btm_ble_start_adv();
1923     else
1924       status = btm_ble_stop_adv();
1925   }
1926 
1927   if (p_cb->adv_mode == BTM_BLE_ADV_ENABLE) {
1928     p_cb->fast_adv_on = true;
1929     /* start initial GAP mode adv timer */
1930     alarm_set_on_mloop(p_cb->fast_adv_timer, BTM_BLE_GAP_FAST_ADV_TIMEOUT_MS,
1931                        btm_ble_fast_adv_timer_timeout, NULL);
1932   }
1933 
1934   /* set up stop advertising timer */
1935   if (status == BTM_SUCCESS && mode == BTM_BLE_LIMITED_DISCOVERABLE) {
1936     BTM_TRACE_EVENT("start timer for limited disc mode duration=%d ms",
1937                     BTM_BLE_GAP_LIM_TIMEOUT_MS);
1938     /* start Tgap(lim_timeout) */
1939     alarm_set_on_mloop(p_cb->inquiry_timer, BTM_BLE_GAP_LIM_TIMEOUT_MS,
1940                        btm_ble_inquiry_timer_gap_limited_discovery_timeout,
1941                        NULL);
1942   }
1943   return status;
1944 }
1945 
1946 /*******************************************************************************
1947  *
1948  * Function         btm_ble_set_connectability
1949  *
1950  * Description      This function is called to set BLE connectability mode.
1951  *
1952  * Parameters:      combined_mode: connectability mode.
1953  *
1954  * Returns          BTM_SUCCESS is status set successfully; otherwise failure.
1955  *
1956  ******************************************************************************/
btm_ble_set_connectability(uint16_t combined_mode)1957 tBTM_STATUS btm_ble_set_connectability(uint16_t combined_mode) {
1958   tBTM_LE_RANDOM_CB* p_addr_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
1959   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
1960   uint16_t mode = (combined_mode & BTM_BLE_CONNECTABLE_MASK);
1961   uint8_t new_mode = BTM_BLE_ADV_ENABLE;
1962   uint8_t evt_type;
1963   tBTM_STATUS status = BTM_SUCCESS;
1964   RawAddress address = RawAddress::kEmpty;
1965   tBLE_ADDR_TYPE peer_addr_type = BLE_ADDR_PUBLIC,
1966                  own_addr_type = p_addr_cb->own_addr_type;
1967   uint16_t adv_int_min, adv_int_max;
1968 
1969   BTM_TRACE_EVENT("%s mode=0x%0x combined_mode=0x%x", __func__, mode,
1970                   combined_mode);
1971 
1972   /*** Check mode parameter ***/
1973   if (mode > BTM_BLE_MAX_CONNECTABLE) return (BTM_ILLEGAL_VALUE);
1974 
1975   p_cb->connectable_mode = mode;
1976 
1977   evt_type =
1978       btm_set_conn_mode_adv_init_addr(address, &peer_addr_type, &own_addr_type);
1979 
1980   if (mode == BTM_BLE_NON_CONNECTABLE &&
1981       p_cb->discoverable_mode == BTM_BLE_NON_DISCOVERABLE)
1982     new_mode = BTM_BLE_ADV_DISABLE;
1983 
1984   btm_ble_select_adv_interval(evt_type, &adv_int_min, &adv_int_max);
1985 
1986   alarm_cancel(p_cb->fast_adv_timer);
1987   /* update adv params if needed */
1988   if (new_mode == BTM_BLE_ADV_ENABLE) {
1989     btm_ble_set_adv_flag(combined_mode, btm_cb.btm_inq_vars.discoverable_mode);
1990     if (p_cb->evt_type != evt_type ||
1991         p_cb->adv_addr_type != p_addr_cb->own_addr_type || !p_cb->fast_adv_on) {
1992       btm_ble_stop_adv();
1993 
1994       btsnd_hcic_ble_write_adv_params(adv_int_min, adv_int_max, evt_type,
1995                                       own_addr_type, peer_addr_type, address,
1996                                       p_cb->adv_chnl_map, p_cb->afp);
1997       p_cb->evt_type = evt_type;
1998       p_cb->adv_addr_type = own_addr_type;
1999     }
2000   }
2001 
2002   /* update advertising mode */
2003   if (status == BTM_SUCCESS && new_mode != p_cb->adv_mode) {
2004     if (new_mode == BTM_BLE_ADV_ENABLE)
2005       status = btm_ble_start_adv();
2006     else
2007       status = btm_ble_stop_adv();
2008   }
2009 
2010   if (p_cb->adv_mode == BTM_BLE_ADV_ENABLE) {
2011     p_cb->fast_adv_on = true;
2012     /* start initial GAP mode adv timer */
2013     alarm_set_on_mloop(p_cb->fast_adv_timer, BTM_BLE_GAP_FAST_ADV_TIMEOUT_MS,
2014                        btm_ble_fast_adv_timer_timeout, NULL);
2015   }
2016   return status;
2017 }
2018 
btm_send_hci_scan_enable(uint8_t enable,uint8_t filter_duplicates)2019 static void btm_send_hci_scan_enable(uint8_t enable,
2020                                      uint8_t filter_duplicates) {
2021   if (controller_get_interface()->supports_ble_extended_advertising()) {
2022     btsnd_hcic_ble_set_extended_scan_enable(enable, filter_duplicates, 0x0000,
2023                                             0x0000);
2024   } else {
2025     btsnd_hcic_ble_set_scan_enable(enable, filter_duplicates);
2026   }
2027 }
2028 
btm_send_hci_set_scan_params(uint8_t scan_type,uint16_t scan_int,uint16_t scan_win,tBLE_ADDR_TYPE addr_type_own,uint8_t scan_filter_policy)2029 void btm_send_hci_set_scan_params(uint8_t scan_type, uint16_t scan_int,
2030                                   uint16_t scan_win,
2031                                   tBLE_ADDR_TYPE addr_type_own,
2032                                   uint8_t scan_filter_policy) {
2033   if (controller_get_interface()->supports_ble_extended_advertising()) {
2034     scanning_phy_cfg phy_cfg;
2035     phy_cfg.scan_type = scan_type;
2036     phy_cfg.scan_int = scan_int;
2037     phy_cfg.scan_win = scan_win;
2038 
2039     btsnd_hcic_ble_set_extended_scan_params(addr_type_own, scan_filter_policy,
2040                                             1, &phy_cfg);
2041   } else {
2042     btsnd_hcic_ble_set_scan_params(scan_type, scan_int, scan_win, addr_type_own,
2043                                    scan_filter_policy);
2044   }
2045 }
2046 
2047 /* Scan filter param config event */
btm_ble_scan_filt_param_cfg_evt(uint8_t avbl_space,tBTM_BLE_SCAN_COND_OP action_type,tBTM_STATUS btm_status)2048 static void btm_ble_scan_filt_param_cfg_evt(uint8_t avbl_space,
2049                                             tBTM_BLE_SCAN_COND_OP action_type,
2050                                             tBTM_STATUS btm_status) {
2051   if (btm_status != btm_status_value(BTM_SUCCESS)) {
2052     BTM_TRACE_ERROR("%s, %d", __func__, btm_status);
2053   } else {
2054     BTM_TRACE_DEBUG("%s", __func__);
2055   }
2056 }
2057 
2058 /*******************************************************************************
2059  *
2060  * Function         btm_ble_start_inquiry
2061  *
2062  * Description      This function is called to start BLE inquiry procedure.
2063  *                  If the duration is zero, the periodic inquiry mode is
2064  *                  cancelled.
2065  *
2066  * Parameters:      duration - Duration of inquiry in seconds
2067  *
2068  * Returns          BTM_CMD_STARTED if successfully started
2069  *                  BTM_BUSY - if an inquiry is already active
2070  *
2071  ******************************************************************************/
btm_ble_start_inquiry(uint8_t duration)2072 tBTM_STATUS btm_ble_start_inquiry(uint8_t duration) {
2073   tBTM_BLE_CB* p_ble_cb = &btm_cb.ble_ctr_cb;
2074   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
2075 
2076   BTM_TRACE_DEBUG("btm_ble_start_inquiry: inq_active = 0x%02x",
2077                   btm_cb.btm_inq_vars.inq_active);
2078 
2079   /* if selective connection is active, or inquiry is already active, reject it
2080    */
2081   if (p_ble_cb->is_ble_inquiry_active()) {
2082     BTM_TRACE_ERROR("LE Inquiry is active, can not start inquiry");
2083     return (BTM_BUSY);
2084   }
2085 
2086   /* Cleanup anything remaining on index 0 */
2087   BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_DELETE,
2088                              static_cast<tBTM_BLE_PF_FILT_INDEX>(0), nullptr,
2089                              base::Bind(btm_ble_scan_filt_param_cfg_evt));
2090 
2091   auto adv_filt_param = std::make_unique<btgatt_filt_param_setup_t>();
2092   /* Add an allow-all filter on index 0*/
2093   adv_filt_param->dely_mode = IMMEDIATE_DELY_MODE;
2094   adv_filt_param->feat_seln = ALLOW_ALL_FILTER;
2095   adv_filt_param->filt_logic_type = BTA_DM_BLE_PF_FILT_LOGIC_OR;
2096   adv_filt_param->list_logic_type = BTA_DM_BLE_PF_LIST_LOGIC_OR;
2097   adv_filt_param->rssi_low_thres = LOWEST_RSSI_VALUE;
2098   adv_filt_param->rssi_high_thres = LOWEST_RSSI_VALUE;
2099   BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_ADD, static_cast<tBTM_BLE_PF_FILT_INDEX>(0),
2100                  std::move(adv_filt_param), base::Bind(btm_ble_scan_filt_param_cfg_evt));
2101 
2102   uint16_t scan_interval = osi_property_get_int32(kPropertyInquiryScanInterval,
2103                                                   BTM_BLE_LOW_LATENCY_SCAN_INT);
2104   uint16_t scan_window = osi_property_get_int32(kPropertyInquiryScanWindow,
2105                                                 BTM_BLE_LOW_LATENCY_SCAN_WIN);
2106 
2107   if (!p_ble_cb->is_ble_scan_active()) {
2108     cache.ClearAll();
2109     btm_send_hci_set_scan_params(
2110         BTM_BLE_SCAN_MODE_ACTI, scan_interval, scan_window,
2111         btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, SP_ADV_ALL);
2112     p_ble_cb->inq_var.scan_type = BTM_BLE_SCAN_MODE_ACTI;
2113     btm_ble_start_scan();
2114   } else if ((p_ble_cb->inq_var.scan_interval != scan_interval) ||
2115              (p_ble_cb->inq_var.scan_window != scan_window)) {
2116     BTM_TRACE_DEBUG("%s, restart LE scan with low latency scan params",
2117                     __func__);
2118     btm_send_hci_scan_enable(BTM_BLE_SCAN_DISABLE, BTM_BLE_DUPLICATE_ENABLE);
2119     btm_send_hci_set_scan_params(
2120         BTM_BLE_SCAN_MODE_ACTI, scan_interval, scan_window,
2121         btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, SP_ADV_ALL);
2122     btm_send_hci_scan_enable(BTM_BLE_SCAN_ENABLE, BTM_BLE_DUPLICATE_DISABLE);
2123   }
2124 
2125   p_inq->inq_active |= BTM_BLE_GENERAL_INQUIRY;
2126   p_ble_cb->set_ble_inquiry_active();
2127 
2128   BTM_TRACE_DEBUG("btm_ble_start_inquiry inq_active = 0x%02x",
2129                   p_inq->inq_active);
2130 
2131   if (duration != 0) {
2132     /* start inquiry timer */
2133     uint64_t duration_ms = duration * 1000;
2134     alarm_set_on_mloop(p_ble_cb->inq_var.inquiry_timer, duration_ms,
2135                        btm_ble_inquiry_timer_timeout, NULL);
2136   }
2137 
2138   btm_cb.neighbor.le_inquiry = {
2139       .start_time_ms = timestamper_in_milliseconds.GetTimestamp(),
2140       .results = 0,
2141   };
2142   BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le inquiry started");
2143 
2144   return BTM_CMD_STARTED;
2145 }
2146 
2147 /*******************************************************************************
2148  *
2149  * Function         btm_ble_read_remote_name_cmpl
2150  *
2151  * Description      This function is called when BLE remote name is received.
2152  *
2153  * Returns          void
2154  *
2155  ******************************************************************************/
btm_ble_read_remote_name_cmpl(bool status,const RawAddress & bda,uint16_t length,char * p_name)2156 void btm_ble_read_remote_name_cmpl(bool status, const RawAddress& bda,
2157                                    uint16_t length, char* p_name) {
2158   tHCI_STATUS hci_status = HCI_SUCCESS;
2159   BD_NAME bd_name;
2160 
2161   memset(bd_name, 0, (BD_NAME_LEN + 1));
2162   if (length > BD_NAME_LEN) {
2163     length = BD_NAME_LEN;
2164   }
2165   memcpy((uint8_t*)bd_name, p_name, length);
2166 
2167   if ((!status) || (length == 0)) {
2168     hci_status = HCI_ERR_HOST_TIMEOUT;
2169   }
2170 
2171   btm_process_remote_name(&bda, bd_name, length + 1, hci_status);
2172   btm_sec_rmt_name_request_complete(&bda, (const uint8_t*)p_name, hci_status);
2173 }
2174 
2175 /*******************************************************************************
2176  *
2177  * Function         btm_ble_read_remote_name
2178  *
2179  * Description      This function read remote LE device name using GATT read
2180  *                  procedure.
2181  *
2182  * Parameters:       None.
2183  *
2184  * Returns          void
2185  *
2186  ******************************************************************************/
btm_ble_read_remote_name(const RawAddress & remote_bda,tBTM_NAME_CMPL_CB * p_cb)2187 tBTM_STATUS btm_ble_read_remote_name(const RawAddress& remote_bda,
2188                                      tBTM_NAME_CMPL_CB* p_cb) {
2189   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
2190 
2191   if (!controller_get_interface()->supports_ble()) return BTM_ERR_PROCESSING;
2192 
2193   tINQ_DB_ENT* p_i = btm_inq_db_find(remote_bda);
2194   if (p_i && !ble_evt_type_is_connectable(p_i->inq_info.results.ble_evt_type)) {
2195     BTM_TRACE_DEBUG("name request to non-connectable device failed.");
2196     return BTM_ERR_PROCESSING;
2197   }
2198 
2199   /* read remote device name using GATT procedure */
2200   if (p_inq->remname_active) return BTM_BUSY;
2201 
2202   if (!GAP_BleReadPeerDevName(remote_bda, btm_ble_read_remote_name_cmpl))
2203     return BTM_BUSY;
2204 
2205   p_inq->p_remname_cmpl_cb = p_cb;
2206   p_inq->remname_active = true;
2207   p_inq->remname_bda = remote_bda;
2208 
2209   alarm_set_on_mloop(p_inq->remote_name_timer, BTM_EXT_BLE_RMT_NAME_TIMEOUT_MS,
2210                      btm_inq_remote_name_timer_timeout, NULL);
2211 
2212   return BTM_CMD_STARTED;
2213 }
2214 
2215 /*******************************************************************************
2216  *
2217  * Function         btm_ble_cancel_remote_name
2218  *
2219  * Description      This function cancel read remote LE device name.
2220  *
2221  * Parameters:       None.
2222  *
2223  * Returns          void
2224  *
2225  ******************************************************************************/
btm_ble_cancel_remote_name(const RawAddress & remote_bda)2226 bool btm_ble_cancel_remote_name(const RawAddress& remote_bda) {
2227   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
2228   bool status;
2229 
2230   status = GAP_BleCancelReadPeerDevName(remote_bda);
2231 
2232   p_inq->remname_active = false;
2233   p_inq->remname_bda = RawAddress::kEmpty;
2234   alarm_cancel(p_inq->remote_name_timer);
2235 
2236   return status;
2237 }
2238 
2239 /*******************************************************************************
2240  *
2241  * Function         btm_ble_update_adv_flag
2242  *
2243  * Description      This function update the limited discoverable flag in the
2244  *                  adv data.
2245  *
2246  * Parameters:       None.
2247  *
2248  * Returns          void
2249  *
2250  ******************************************************************************/
btm_ble_update_adv_flag(uint8_t flag)2251 static void btm_ble_update_adv_flag(uint8_t flag) {
2252   tBTM_BLE_LOCAL_ADV_DATA* p_adv_data = &btm_cb.ble_ctr_cb.inq_var.adv_data;
2253   uint8_t* p;
2254 
2255   BTM_TRACE_DEBUG("btm_ble_update_adv_flag new=0x%x", flag);
2256 
2257   if (p_adv_data->p_flags != NULL) {
2258     BTM_TRACE_DEBUG("btm_ble_update_adv_flag old=0x%x", *p_adv_data->p_flags);
2259     *p_adv_data->p_flags = flag;
2260   } else /* no FLAGS in ADV data*/
2261   {
2262     p = (p_adv_data->p_pad == NULL) ? p_adv_data->ad_data : p_adv_data->p_pad;
2263     /* need 3 bytes space to stuff in the flags, if not */
2264     /* erase all written data, just for flags */
2265     if ((BTM_BLE_AD_DATA_LEN - (p - p_adv_data->ad_data)) < 3) {
2266       p = p_adv_data->p_pad = p_adv_data->ad_data;
2267       memset(p_adv_data->ad_data, 0, BTM_BLE_AD_DATA_LEN);
2268     }
2269 
2270     *p++ = 2;
2271     *p++ = BTM_BLE_AD_TYPE_FLAG;
2272     p_adv_data->p_flags = p;
2273     *p++ = flag;
2274     p_adv_data->p_pad = p;
2275   }
2276 
2277   btsnd_hcic_ble_set_adv_data(
2278       (uint8_t)(p_adv_data->p_pad - p_adv_data->ad_data), p_adv_data->ad_data);
2279   p_adv_data->data_mask |= BTM_BLE_AD_BIT_FLAGS;
2280 }
2281 
2282 /**
2283  * Check ADV flag to make sure device is discoverable and match the search
2284  * condition
2285  */
btm_ble_is_discoverable(const RawAddress & bda,std::vector<uint8_t> const & adv_data)2286 static uint8_t btm_ble_is_discoverable(const RawAddress& bda,
2287                                        std::vector<uint8_t> const& adv_data) {
2288   uint8_t scan_state = BTM_BLE_NOT_SCANNING;
2289 
2290   /* for observer, always "discoverable */
2291   if (btm_cb.ble_ctr_cb.is_ble_observe_active())
2292     scan_state |= BTM_BLE_OBS_RESULT;
2293 
2294   if (!adv_data.empty()) {
2295     uint8_t flag = 0;
2296     uint8_t data_len;
2297     const uint8_t* p_flag = AdvertiseDataParser::GetFieldByType(
2298         adv_data, BTM_BLE_AD_TYPE_FLAG, &data_len);
2299     if (p_flag != NULL && data_len != 0) {
2300       flag = *p_flag;
2301 
2302       if ((btm_cb.btm_inq_vars.inq_active & BTM_BLE_GENERAL_INQUIRY) &&
2303           (flag & (BTM_BLE_LIMIT_DISC_FLAG | BTM_BLE_GEN_DISC_FLAG)) != 0) {
2304         scan_state |= BTM_BLE_INQ_RESULT;
2305       }
2306     }
2307   }
2308   return scan_state;
2309 }
2310 
btm_ble_appearance_to_cod(uint16_t appearance,uint8_t * dev_class)2311 static void btm_ble_appearance_to_cod(uint16_t appearance, uint8_t* dev_class) {
2312   dev_class[0] = 0;
2313 
2314   switch (appearance) {
2315     case BTM_BLE_APPEARANCE_GENERIC_PHONE:
2316       dev_class[1] = BTM_COD_MAJOR_PHONE;
2317       dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
2318       break;
2319     case BTM_BLE_APPEARANCE_GENERIC_COMPUTER:
2320       dev_class[1] = BTM_COD_MAJOR_COMPUTER;
2321       dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
2322       break;
2323     case BTM_BLE_APPEARANCE_GENERIC_REMOTE:
2324       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
2325       dev_class[2] = BTM_COD_MINOR_REMOTE_CONTROL;
2326       break;
2327     case BTM_BLE_APPEARANCE_GENERIC_THERMOMETER:
2328     case BTM_BLE_APPEARANCE_THERMOMETER_EAR:
2329       dev_class[1] = BTM_COD_MAJOR_HEALTH;
2330       dev_class[2] = BTM_COD_MINOR_THERMOMETER;
2331       break;
2332     case BTM_BLE_APPEARANCE_GENERIC_HEART_RATE:
2333     case BTM_BLE_APPEARANCE_HEART_RATE_BELT:
2334       dev_class[1] = BTM_COD_MAJOR_HEALTH;
2335       dev_class[2] = BTM_COD_MINOR_HEART_PULSE_MONITOR;
2336       break;
2337     case BTM_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE:
2338     case BTM_BLE_APPEARANCE_BLOOD_PRESSURE_ARM:
2339     case BTM_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST:
2340       dev_class[1] = BTM_COD_MAJOR_HEALTH;
2341       dev_class[2] = BTM_COD_MINOR_BLOOD_MONITOR;
2342       break;
2343     case BTM_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER:
2344     case BTM_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP:
2345     case BTM_BLE_APPEARANCE_PULSE_OXIMETER_WRIST:
2346       dev_class[1] = BTM_COD_MAJOR_HEALTH;
2347       dev_class[2] = BTM_COD_MINOR_PULSE_OXIMETER;
2348       break;
2349     case BTM_BLE_APPEARANCE_GENERIC_GLUCOSE:
2350       dev_class[1] = BTM_COD_MAJOR_HEALTH;
2351       dev_class[2] = BTM_COD_MINOR_GLUCOSE_METER;
2352       break;
2353     case BTM_BLE_APPEARANCE_GENERIC_WEIGHT:
2354       dev_class[1] = BTM_COD_MAJOR_HEALTH;
2355       dev_class[2] = BTM_COD_MINOR_WEIGHING_SCALE;
2356       break;
2357     case BTM_BLE_APPEARANCE_GENERIC_WALKING:
2358     case BTM_BLE_APPEARANCE_WALKING_IN_SHOE:
2359     case BTM_BLE_APPEARANCE_WALKING_ON_SHOE:
2360     case BTM_BLE_APPEARANCE_WALKING_ON_HIP:
2361       dev_class[1] = BTM_COD_MAJOR_HEALTH;
2362       dev_class[2] = BTM_COD_MINOR_STEP_COUNTER;
2363       break;
2364     case BTM_BLE_APPEARANCE_GENERIC_WATCH:
2365     case BTM_BLE_APPEARANCE_SPORTS_WATCH:
2366       dev_class[1] = BTM_COD_MAJOR_WEARABLE;
2367       dev_class[2] = BTM_COD_MINOR_WRIST_WATCH;
2368       break;
2369     case BTM_BLE_APPEARANCE_GENERIC_EYEGLASSES:
2370       dev_class[1] = BTM_COD_MAJOR_WEARABLE;
2371       dev_class[2] = BTM_COD_MINOR_GLASSES;
2372       break;
2373     case BTM_BLE_APPEARANCE_GENERIC_DISPLAY:
2374       dev_class[1] = BTM_COD_MAJOR_IMAGING;
2375       dev_class[2] = BTM_COD_MINOR_DISPLAY;
2376       break;
2377     case BTM_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER:
2378       dev_class[1] = BTM_COD_MAJOR_AUDIO;
2379       dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
2380       break;
2381     case BTM_BLE_APPEARANCE_GENERIC_WEARABLE_AUDIO_DEVICE:
2382     case BTM_BLE_APPEARANCE_WEARABLE_AUDIO_DEVICE_EARBUD:
2383     case BTM_BLE_APPEARANCE_WEARABLE_AUDIO_DEVICE_HEADSET:
2384     case BTM_BLE_APPEARANCE_WEARABLE_AUDIO_DEVICE_HEADPHONES:
2385     case BTM_BLE_APPEARANCE_WEARABLE_AUDIO_DEVICE_NECK_BAND:
2386       dev_class[0] = (BTM_COD_SERVICE_AUDIO | BTM_COD_SERVICE_RENDERING) >> 8;
2387       dev_class[1] = (BTM_COD_MAJOR_AUDIO | BTM_COD_SERVICE_LE_AUDIO);
2388       dev_class[2] = BTM_COD_MINOR_WEARABLE_HEADSET;
2389       break;
2390     case BTM_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER:
2391     case BTM_BLE_APPEARANCE_HID_BARCODE_SCANNER:
2392     case BTM_BLE_APPEARANCE_GENERIC_HID:
2393       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
2394       dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
2395       break;
2396     case BTM_BLE_APPEARANCE_HID_KEYBOARD:
2397       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
2398       dev_class[2] = BTM_COD_MINOR_KEYBOARD;
2399       break;
2400     case BTM_BLE_APPEARANCE_HID_MOUSE:
2401       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
2402       dev_class[2] = BTM_COD_MINOR_POINTING;
2403       break;
2404     case BTM_BLE_APPEARANCE_HID_JOYSTICK:
2405       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
2406       dev_class[2] = BTM_COD_MINOR_JOYSTICK;
2407       break;
2408     case BTM_BLE_APPEARANCE_HID_GAMEPAD:
2409       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
2410       dev_class[2] = BTM_COD_MINOR_GAMEPAD;
2411       break;
2412     case BTM_BLE_APPEARANCE_HID_DIGITIZER_TABLET:
2413       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
2414       dev_class[2] = BTM_COD_MINOR_DIGITIZING_TABLET;
2415       break;
2416     case BTM_BLE_APPEARANCE_HID_CARD_READER:
2417       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
2418       dev_class[2] = BTM_COD_MINOR_CARD_READER;
2419       break;
2420     case BTM_BLE_APPEARANCE_HID_DIGITAL_PEN:
2421       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
2422       dev_class[2] = BTM_COD_MINOR_DIGITAL_PAN;
2423       break;
2424     case BTM_BLE_APPEARANCE_UKNOWN:
2425     case BTM_BLE_APPEARANCE_GENERIC_CLOCK:
2426     case BTM_BLE_APPEARANCE_GENERIC_TAG:
2427     case BTM_BLE_APPEARANCE_GENERIC_KEYRING:
2428     case BTM_BLE_APPEARANCE_GENERIC_CYCLING:
2429     case BTM_BLE_APPEARANCE_CYCLING_COMPUTER:
2430     case BTM_BLE_APPEARANCE_CYCLING_SPEED:
2431     case BTM_BLE_APPEARANCE_CYCLING_CADENCE:
2432     case BTM_BLE_APPEARANCE_CYCLING_POWER:
2433     case BTM_BLE_APPEARANCE_CYCLING_SPEED_CADENCE:
2434     case BTM_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS:
2435     case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION:
2436     case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV:
2437     case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD:
2438     case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV:
2439     default:
2440       dev_class[1] = BTM_COD_MAJOR_UNCLASSIFIED;
2441       dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
2442   };
2443 }
2444 
btm_ble_get_appearance_as_cod(std::vector<uint8_t> const & data,DEV_CLASS dev_class)2445 bool btm_ble_get_appearance_as_cod(std::vector<uint8_t> const& data,
2446                                    DEV_CLASS dev_class) {
2447   /* Check to see the BLE device has the Appearance UUID in the advertising
2448    * data. If it does then try to convert the appearance value to a class of
2449    * device value Fluoride can use. Otherwise fall back to trying to infer if
2450    * it is a HID device based on the service class.
2451    */
2452   uint8_t len;
2453   const uint8_t* p_uuid16 = AdvertiseDataParser::GetFieldByType(
2454       data, BTM_BLE_AD_TYPE_APPEARANCE, &len);
2455   if (p_uuid16 && len == 2) {
2456     btm_ble_appearance_to_cod((uint16_t)p_uuid16[0] | (p_uuid16[1] << 8),
2457                               dev_class);
2458     return true;
2459   }
2460 
2461   p_uuid16 = AdvertiseDataParser::GetFieldByType(
2462       data, BTM_BLE_AD_TYPE_16SRV_CMPL, &len);
2463   if (p_uuid16 == NULL) {
2464     return false;
2465   }
2466 
2467   for (uint8_t i = 0; i + 2 <= len; i = i + 2) {
2468     /* if this BLE device supports HID over LE, set HID Major in class of
2469      * device */
2470     if ((p_uuid16[i] | (p_uuid16[i + 1] << 8)) == UUID_SERVCLASS_LE_HID) {
2471       dev_class[0] = 0;
2472       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
2473       dev_class[2] = 0;
2474       return true;
2475     }
2476   }
2477 
2478   return false;
2479 }
2480 
2481 /**
2482  * Update adv packet information into inquiry result.
2483  */
btm_ble_update_inq_result(tINQ_DB_ENT * p_i,uint8_t addr_type,const RawAddress & bda,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)2484 void btm_ble_update_inq_result(tINQ_DB_ENT* p_i, uint8_t addr_type,
2485                                const RawAddress& bda, uint16_t evt_type,
2486                                uint8_t primary_phy, uint8_t secondary_phy,
2487                                uint8_t advertising_sid, int8_t tx_power,
2488                                int8_t rssi, uint16_t periodic_adv_int,
2489                                std::vector<uint8_t> const& data) {
2490   tBTM_INQ_RESULTS* p_cur = &p_i->inq_info.results;
2491   uint8_t len;
2492   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
2493 
2494   /* Save the info */
2495   p_cur->inq_result_type |= BTM_INQ_RESULT_BLE;
2496   p_cur->ble_addr_type = static_cast<tBLE_ADDR_TYPE>(addr_type);
2497   p_cur->rssi = rssi;
2498   p_cur->ble_primary_phy = primary_phy;
2499   p_cur->ble_secondary_phy = secondary_phy;
2500   p_cur->ble_advertising_sid = advertising_sid;
2501   p_cur->ble_tx_power = tx_power;
2502   p_cur->ble_periodic_adv_int = periodic_adv_int;
2503 
2504   if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI &&
2505       ble_evt_type_is_scannable(evt_type) &&
2506       !ble_evt_type_is_scan_resp(evt_type)) {
2507     p_i->scan_rsp = false;
2508   } else
2509     p_i->scan_rsp = true;
2510 
2511   if (p_i->inq_count != p_inq->inq_counter)
2512     p_cur->device_type = BT_DEVICE_TYPE_BLE;
2513   else
2514     p_cur->device_type |= BT_DEVICE_TYPE_BLE;
2515 
2516   if (evt_type != BTM_BLE_SCAN_RSP_EVT) p_cur->ble_evt_type = evt_type;
2517 
2518   p_i->inq_count = p_inq->inq_counter; /* Mark entry for current inquiry */
2519 
2520   bool has_advertising_flags = false;
2521   if (!data.empty()) {
2522     const uint8_t* p_flag =
2523         AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_FLAG, &len);
2524     if (p_flag != NULL && len != 0) {
2525       has_advertising_flags = true;
2526       p_cur->flag = *p_flag;
2527     }
2528 
2529     btm_ble_get_appearance_as_cod(data, p_cur->dev_class);
2530 
2531     const uint8_t* p_rsi =
2532         AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_RSI, &len);
2533     if (p_rsi != nullptr && len == 6) {
2534       STREAM_TO_BDADDR(p_cur->ble_ad_rsi, p_rsi);
2535     }
2536 
2537     const uint8_t* p_service_data = data.data();
2538     uint8_t service_data_len = 0;
2539 
2540     while ((p_service_data = AdvertiseDataParser::GetFieldByType(
2541                 p_service_data + service_data_len,
2542                 data.size() - (p_service_data - data.data()) - service_data_len,
2543                 BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE, &service_data_len))) {
2544       uint16_t uuid;
2545       const uint8_t* p_uuid = p_service_data;
2546       if (service_data_len < 2) {
2547         continue;
2548       }
2549       STREAM_TO_UINT16(uuid, p_uuid);
2550 
2551       if (uuid == 0x184E /* Audio Stream Control service */ ||
2552           uuid == 0x184F /* Broadcast Audio Scan service */ ||
2553           uuid == 0x1850 /* Published Audio Capabilities service */ ||
2554           uuid == 0x1853 /* Common Audio service */) {
2555         p_cur->ble_ad_is_le_audio_capable = true;
2556         break;
2557       }
2558     }
2559   }
2560 
2561   // Non-connectable packets may omit flags entirely, in which case nothing
2562   // should be assumed about their values (CSSv10, 1.3.1). Thus, do not
2563   // interpret the device type unless this packet has the flags set or is
2564   // connectable.
2565   bool should_process_flags =
2566       has_advertising_flags || ble_evt_type_is_connectable(evt_type);
2567   if (should_process_flags && (p_cur->flag & BTM_BLE_BREDR_NOT_SPT) == 0 &&
2568       !ble_evt_type_is_directed(evt_type)) {
2569     if (p_cur->ble_addr_type != BLE_ADDR_RANDOM) {
2570       LOG_VERBOSE("NOT_BR_EDR support bit not set, treat device as DUMO");
2571       p_cur->device_type |= BT_DEVICE_TYPE_DUMO;
2572     } else {
2573       LOG_VERBOSE("Random address, treat device as LE only");
2574     }
2575   } else {
2576     LOG_VERBOSE("NOT_BR/EDR support bit set, treat device as LE only");
2577   }
2578 }
2579 
btm_ble_process_adv_addr(RawAddress & bda,tBLE_ADDR_TYPE * addr_type)2580 void btm_ble_process_adv_addr(RawAddress& bda, tBLE_ADDR_TYPE* addr_type) {
2581   /* map address to security record */
2582   bool match = btm_identity_addr_to_random_pseudo(&bda, addr_type, false);
2583 
2584   VLOG(1) << __func__ << ": bda=" << bda;
2585   /* always do RRA resolution on host */
2586   if (!match && BTM_BLE_IS_RESOLVE_BDA(bda)) {
2587     tBTM_SEC_DEV_REC* match_rec = btm_ble_resolve_random_addr(bda);
2588     if (match_rec) {
2589       match_rec->ble.active_addr_type = tBTM_SEC_BLE::BTM_BLE_ADDR_RRA;
2590       match_rec->ble.cur_rand_addr = bda;
2591 
2592       if (btm_ble_init_pseudo_addr(match_rec, bda)) {
2593         bda = match_rec->bd_addr;
2594       } else {
2595         // Assign the original address to be the current report address
2596         bda = match_rec->ble.pseudo_addr;
2597         *addr_type = match_rec->ble.AddressType();
2598       }
2599     }
2600   }
2601 }
2602 
2603 /**
2604  * This function is called when extended advertising report event is received .
2605  * It updates the inquiry database. If the inquiry database is full, the oldest
2606  * entry is discarded.
2607  */
btm_ble_process_ext_adv_pkt(uint8_t data_len,const uint8_t * data)2608 void btm_ble_process_ext_adv_pkt(uint8_t data_len, const uint8_t* data) {
2609   RawAddress bda, direct_address;
2610   const uint8_t* p = data;
2611   uint8_t addr_type, num_reports, pkt_data_len, primary_phy, secondary_phy,
2612       advertising_sid;
2613   int8_t rssi, tx_power;
2614   uint16_t event_type, periodic_adv_int, direct_address_type;
2615   size_t bytes_to_process;
2616 
2617   /* Only process the results if the inquiry is still active */
2618   if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) return;
2619 
2620   bytes_to_process = 1;
2621 
2622   if (data_len < bytes_to_process) {
2623     LOG(ERROR) << "Malformed LE extended advertising packet: not enough room "
2624                   "for num reports";
2625     return;
2626   }
2627 
2628   /* Extract the number of reports in this event. */
2629   STREAM_TO_UINT8(num_reports, p);
2630 
2631   while (num_reports--) {
2632     bytes_to_process += 24;
2633     if (data_len < bytes_to_process) {
2634       LOG(ERROR) << "Malformed LE extended advertising packet: not enough room "
2635                     "for metadata";
2636       return;
2637     }
2638 
2639     /* Extract inquiry results */
2640     STREAM_TO_UINT16(event_type, p);
2641     STREAM_TO_UINT8(addr_type, p);
2642     STREAM_TO_BDADDR(bda, p);
2643     STREAM_TO_UINT8(primary_phy, p);
2644     STREAM_TO_UINT8(secondary_phy, p);
2645     STREAM_TO_UINT8(advertising_sid, p);
2646     STREAM_TO_INT8(tx_power, p);
2647     STREAM_TO_INT8(rssi, p);
2648     STREAM_TO_UINT16(periodic_adv_int, p);
2649     STREAM_TO_UINT8(direct_address_type, p);
2650     STREAM_TO_BDADDR(direct_address, p);
2651     STREAM_TO_UINT8(pkt_data_len, p);
2652 
2653     const uint8_t* pkt_data = p;
2654     p += pkt_data_len; /* Advance to the the next packet*/
2655 
2656     bytes_to_process += pkt_data_len;
2657     if (data_len < bytes_to_process) {
2658       LOG(ERROR) << "Malformed LE extended advertising packet: not enough room "
2659                     "for packet data";
2660       return;
2661     }
2662 
2663     if (rssi >= 21 && rssi <= 126) {
2664       BTM_TRACE_ERROR("%s: bad rssi value in advertising report: %d", __func__,
2665                       rssi);
2666     }
2667 
2668     // Store this to pass up the callback chain to GattService#onScanResult for
2669     // the check in ScanFilter#matches
2670     RawAddress original_bda = bda;
2671 
2672     if (addr_type != BLE_ADDR_ANONYMOUS) {
2673       btm_ble_process_adv_addr(bda, &addr_type);
2674     }
2675 
2676     btm_ble_process_adv_pkt_cont(
2677         event_type, addr_type, bda, primary_phy, secondary_phy, advertising_sid,
2678         tx_power, rssi, periodic_adv_int, pkt_data_len, pkt_data, original_bda);
2679   }
2680 }
2681 
2682 /**
2683  * This function is called when advertising report event is received. It updates
2684  * the inquiry database. If the inquiry database is full, the oldest entry is
2685  * discarded.
2686  */
btm_ble_process_adv_pkt(uint8_t data_len,const uint8_t * data)2687 void btm_ble_process_adv_pkt(uint8_t data_len, const uint8_t* data) {
2688   RawAddress bda;
2689   const uint8_t* p = data;
2690   uint8_t legacy_evt_type, addr_type, num_reports, pkt_data_len;
2691   int8_t rssi;
2692   size_t bytes_to_process;
2693 
2694   /* Only process the results if the inquiry is still active */
2695   if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) return;
2696 
2697   bytes_to_process = 1;
2698 
2699   if (data_len < bytes_to_process) {
2700     LOG(ERROR)
2701         << "Malformed LE advertising packet: not enough room for num reports";
2702     return;
2703   }
2704 
2705   /* Extract the number of reports in this event. */
2706   STREAM_TO_UINT8(num_reports, p);
2707 
2708   while (num_reports--) {
2709     bytes_to_process += 9;
2710 
2711     if (data_len < bytes_to_process) {
2712       LOG(ERROR)
2713           << "Malformed LE advertising packet: not enough room for metadata";
2714       return;
2715     }
2716 
2717     /* Extract inquiry results */
2718     STREAM_TO_UINT8(legacy_evt_type, p);
2719     STREAM_TO_UINT8(addr_type, p);
2720     STREAM_TO_BDADDR(bda, p);
2721     STREAM_TO_UINT8(pkt_data_len, p);
2722 
2723     const uint8_t* pkt_data = p;
2724     p += pkt_data_len; /* Advance to the the rssi byte */
2725 
2726     // include rssi for this check
2727     bytes_to_process += pkt_data_len + 1;
2728     if (data_len < bytes_to_process) {
2729       LOG(ERROR) << "Malformed LE advertising packet: not enough room for "
2730                     "packet data and/or RSSI";
2731       return;
2732     }
2733 
2734     STREAM_TO_INT8(rssi, p);
2735 
2736     if (rssi >= 21 && rssi <= 126) {
2737       BTM_TRACE_ERROR("%s: bad rssi value in advertising report: ", __func__,
2738                       pkt_data_len, rssi);
2739     }
2740 
2741     // Pass up the address to GattService#onScanResult to use in
2742     // ScanFilter#matches
2743     RawAddress original_bda = bda;
2744 
2745     btm_ble_process_adv_addr(bda, &addr_type);
2746 
2747     uint16_t event_type;
2748     event_type = 1 << BLE_EVT_LEGACY_BIT;
2749     if (legacy_evt_type == BTM_BLE_ADV_IND_EVT) {
2750       event_type |=
2751           (1 << BLE_EVT_CONNECTABLE_BIT) | (1 << BLE_EVT_SCANNABLE_BIT);
2752     } else if (legacy_evt_type == BTM_BLE_ADV_DIRECT_IND_EVT) {
2753       event_type |=
2754           (1 << BLE_EVT_CONNECTABLE_BIT) | (1 << BLE_EVT_DIRECTED_BIT);
2755     } else if (legacy_evt_type == BTM_BLE_ADV_SCAN_IND_EVT) {
2756       event_type |= (1 << BLE_EVT_SCANNABLE_BIT);
2757     } else if (legacy_evt_type == BTM_BLE_ADV_NONCONN_IND_EVT) {
2758       event_type = (1 << BLE_EVT_LEGACY_BIT);              // 0x0010;
2759     } else if (legacy_evt_type == BTM_BLE_SCAN_RSP_EVT) {  // SCAN_RSP;
2760       // We can't distinguish between "SCAN_RSP to an ADV_IND", and "SCAN_RSP to
2761       // an ADV_SCAN_IND", so always return "SCAN_RSP to an ADV_IND"
2762       event_type |= (1 << BLE_EVT_CONNECTABLE_BIT) |
2763                     (1 << BLE_EVT_SCANNABLE_BIT) |
2764                     (1 << BLE_EVT_SCAN_RESPONSE_BIT);
2765     } else {
2766       BTM_TRACE_ERROR(
2767           "Malformed LE Advertising Report Event - unsupported "
2768           "legacy_event_type 0x%02x",
2769           legacy_evt_type);
2770       return;
2771     }
2772 
2773     btm_ble_process_adv_pkt_cont(
2774         event_type, addr_type, bda, PHY_LE_1M, PHY_LE_NO_PACKET, NO_ADI_PRESENT,
2775         TX_POWER_NOT_PRESENT, rssi, 0x00 /* no periodic adv */, pkt_data_len,
2776         pkt_data, original_bda);
2777   }
2778 }
2779 
2780 /**
2781  * This function is called after random address resolution is done, and proceed
2782  * to process adv packet.
2783  */
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)2784 void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type,
2785                                   const RawAddress& bda, uint8_t primary_phy,
2786                                   uint8_t secondary_phy,
2787                                   uint8_t advertising_sid, int8_t tx_power,
2788                                   int8_t rssi, uint16_t periodic_adv_int,
2789                                   uint8_t data_len, const uint8_t* data,
2790                                   const RawAddress& original_bda) {
2791   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
2792   bool update = true;
2793 
2794   std::vector<uint8_t> tmp;
2795   if (data_len != 0) tmp.insert(tmp.begin(), data, data + data_len);
2796 
2797   bool is_scannable = ble_evt_type_is_scannable(evt_type);
2798   bool is_scan_resp = ble_evt_type_is_scan_resp(evt_type);
2799   bool is_legacy = ble_evt_type_is_legacy(evt_type);
2800 
2801   // We might receive a legacy scan response without receving a ADV_IND
2802   // or ADV_SCAN_IND before. Only parsing the scan response data which
2803   // has no ad flag, the device will be set to DUMO mode. The createbond
2804   // procedure will use the wrong device mode.
2805   // In such case no necessary to report scan response
2806   if (is_legacy && is_scan_resp && !cache.Exist(addr_type, bda)) return;
2807 
2808   bool is_start = is_legacy && is_scannable && !is_scan_resp;
2809 
2810   if (is_legacy) AdvertiseDataParser::RemoveTrailingZeros(tmp);
2811 
2812   // We might have send scan request to this device before, but didn't get the
2813   // response. In such case make sure data is put at start, not appended to
2814   // already existing data.
2815   std::vector<uint8_t> const& adv_data =
2816       is_start ? cache.Set(addr_type, bda, std::move(tmp))
2817                : cache.Append(addr_type, bda, std::move(tmp));
2818 
2819   bool data_complete = (ble_evt_type_data_status(evt_type) != 0x01);
2820 
2821   if (!data_complete) {
2822     // If we didn't receive whole adv data yet, don't report the device.
2823     DVLOG(1) << "Data not complete yet, waiting for more " << bda;
2824     return;
2825   }
2826 
2827   bool is_active_scan =
2828       btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI;
2829   if (is_active_scan && is_scannable && !is_scan_resp) {
2830     // If we didn't receive scan response yet, don't report the device.
2831     DVLOG(1) << " Waiting for scan response " << bda;
2832     return;
2833   }
2834 
2835   if (!AdvertiseDataParser::IsValid(adv_data)) {
2836     DVLOG(1) << __func__ << "Dropping bad advertisement packet: "
2837              << base::HexEncode(adv_data.data(), adv_data.size());
2838     cache.Clear(addr_type, bda);
2839     return;
2840   }
2841 
2842   bool include_rsi = false;
2843   uint8_t len;
2844   if (AdvertiseDataParser::GetFieldByType(adv_data, BTM_BLE_AD_TYPE_RSI,
2845                                           &len)) {
2846     include_rsi = true;
2847   }
2848 
2849   tINQ_DB_ENT* p_i = btm_inq_db_find(bda);
2850 
2851   /* Check if this address has already been processed for this inquiry */
2852   if (btm_inq_find_bdaddr(bda)) {
2853     /* never been report as an LE device */
2854     if (p_i && (!(p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BLE) ||
2855                 /* scan response to be updated */
2856                 (!p_i->scan_rsp) ||
2857                 (!p_i->inq_info.results.include_rsi && include_rsi))) {
2858       update = true;
2859     } else if (btm_cb.ble_ctr_cb.is_ble_observe_active()) {
2860       update = false;
2861     } else {
2862       /* if yes, skip it */
2863       cache.Clear(addr_type, bda);
2864       return; /* assumption: one result per event */
2865     }
2866   }
2867   /* If existing entry, use that, else get  a new one (possibly reusing the
2868    * oldest) */
2869   if (p_i == NULL) {
2870     p_i = btm_inq_db_new(bda);
2871     if (p_i != NULL) {
2872       p_inq->inq_cmpl_info.num_resp++;
2873       p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms();
2874     } else
2875       return;
2876   } else if (p_i->inq_count !=
2877              p_inq->inq_counter) /* first time seen in this inquiry */
2878   {
2879     p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms();
2880     p_inq->inq_cmpl_info.num_resp++;
2881   }
2882 
2883   /* update the LE device information in inquiry database */
2884   btm_ble_update_inq_result(p_i, addr_type, bda, evt_type, primary_phy,
2885                             secondary_phy, advertising_sid, tx_power, rssi,
2886                             periodic_adv_int, adv_data);
2887 
2888   if (include_rsi) {
2889     (&p_i->inq_info.results)->include_rsi = true;
2890   }
2891 
2892   tBTM_INQ_RESULTS_CB* p_opportunistic_obs_results_cb =
2893       btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb;
2894   if (p_opportunistic_obs_results_cb) {
2895     (p_opportunistic_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2896                                      const_cast<uint8_t*>(adv_data.data()),
2897                                      adv_data.size());
2898   }
2899 
2900   tBTM_INQ_RESULTS_CB* p_target_announcement_obs_results_cb =
2901       btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb;
2902   if (p_target_announcement_obs_results_cb) {
2903     (p_target_announcement_obs_results_cb)(
2904         (tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2905         const_cast<uint8_t*>(adv_data.data()), adv_data.size());
2906   }
2907 
2908   uint8_t result = btm_ble_is_discoverable(bda, adv_data);
2909   if (result == 0) {
2910     // Device no longer discoverable so discard outstanding advertising packet
2911     cache.Clear(addr_type, bda);
2912     return;
2913   }
2914 
2915   if (!update) result &= ~BTM_BLE_INQ_RESULT;
2916 
2917   tBTM_INQ_RESULTS_CB* p_inq_results_cb = p_inq->p_inq_results_cb;
2918   if (p_inq_results_cb && (result & BTM_BLE_INQ_RESULT)) {
2919     (p_inq_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2920                        const_cast<uint8_t*>(adv_data.data()), adv_data.size());
2921   }
2922 
2923   // Pass address up to GattService#onScanResult
2924   p_i->inq_info.results.original_bda = original_bda;
2925 
2926   tBTM_INQ_RESULTS_CB* p_obs_results_cb = btm_cb.ble_ctr_cb.p_obs_results_cb;
2927   if (p_obs_results_cb && (result & BTM_BLE_OBS_RESULT)) {
2928     (p_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
2929                        const_cast<uint8_t*>(adv_data.data()), adv_data.size());
2930   }
2931 
2932   cache.Clear(addr_type, bda);
2933 }
2934 
2935 /**
2936  * This function copy from btm_ble_process_adv_pkt_cont to process adv packet
2937  * from gd scanning module to handle inquiry result callback.
2938  */
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)2939 void btm_ble_process_adv_pkt_cont_for_inquiry(
2940     uint16_t evt_type, tBLE_ADDR_TYPE addr_type, const RawAddress& bda,
2941     uint8_t primary_phy, uint8_t secondary_phy, uint8_t advertising_sid,
2942     int8_t tx_power, int8_t rssi, uint16_t periodic_adv_int,
2943     std::vector<uint8_t> advertising_data) {
2944   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
2945   bool update = true;
2946 
2947   bool include_rsi = false;
2948   uint8_t len;
2949   if (AdvertiseDataParser::GetFieldByType(advertising_data, BTM_BLE_AD_TYPE_RSI,
2950                                           &len)) {
2951     include_rsi = true;
2952   }
2953 
2954   tINQ_DB_ENT* p_i = btm_inq_db_find(bda);
2955 
2956   /* Check if this address has already been processed for this inquiry */
2957   if (btm_inq_find_bdaddr(bda)) {
2958     /* never been report as an LE device */
2959     if (p_i && (!(p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BLE) ||
2960                 /* scan response to be updated */
2961                 (!p_i->scan_rsp) ||
2962                 (!p_i->inq_info.results.include_rsi && include_rsi))) {
2963       update = true;
2964     } else if (btm_cb.ble_ctr_cb.is_ble_observe_active()) {
2965       btm_cb.neighbor.le_observe.results++;
2966       update = false;
2967     } else {
2968       /* if yes, skip it */
2969       return; /* assumption: one result per event */
2970     }
2971   }
2972 
2973   /* If existing entry, use that, else get  a new one (possibly reusing the
2974    * oldest) */
2975   if (p_i == NULL) {
2976     p_i = btm_inq_db_new(bda);
2977     if (p_i != NULL) {
2978       p_inq->inq_cmpl_info.num_resp++;
2979       p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms();
2980       btm_cb.neighbor.le_inquiry.results++;
2981       btm_cb.neighbor.le_legacy_scan.results++;
2982     } else {
2983       LOG_WARN("Unable to allocate entry for inquiry result");
2984       return;
2985     }
2986   } else if (p_i->inq_count !=
2987              p_inq->inq_counter) /* first time seen in this inquiry */
2988   {
2989     p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms();
2990     p_inq->inq_cmpl_info.num_resp++;
2991   }
2992 
2993   /* update the LE device information in inquiry database */
2994   btm_ble_update_inq_result(p_i, addr_type, bda, evt_type, primary_phy,
2995                             secondary_phy, advertising_sid, tx_power, rssi,
2996                             periodic_adv_int, advertising_data);
2997 
2998   if (include_rsi) {
2999     (&p_i->inq_info.results)->include_rsi = true;
3000   }
3001 
3002   tBTM_INQ_RESULTS_CB* p_opportunistic_obs_results_cb =
3003       btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb;
3004   if (p_opportunistic_obs_results_cb) {
3005     (p_opportunistic_obs_results_cb)(
3006         (tBTM_INQ_RESULTS*)&p_i->inq_info.results,
3007         const_cast<uint8_t*>(advertising_data.data()), advertising_data.size());
3008   }
3009 
3010   tBTM_INQ_RESULTS_CB* p_target_announcement_obs_results_cb =
3011       btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb;
3012   if (p_target_announcement_obs_results_cb) {
3013     (p_target_announcement_obs_results_cb)(
3014         (tBTM_INQ_RESULTS*)&p_i->inq_info.results,
3015         const_cast<uint8_t*>(advertising_data.data()), advertising_data.size());
3016   }
3017 
3018   uint8_t result = btm_ble_is_discoverable(bda, advertising_data);
3019   if (result == 0) {
3020     return;
3021   }
3022 
3023   if (!update) result &= ~BTM_BLE_INQ_RESULT;
3024 
3025   tBTM_INQ_RESULTS_CB* p_inq_results_cb = p_inq->p_inq_results_cb;
3026   if (p_inq_results_cb && (result & BTM_BLE_INQ_RESULT)) {
3027     (p_inq_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
3028                        const_cast<uint8_t*>(advertising_data.data()),
3029                        advertising_data.size());
3030   }
3031 }
3032 
btm_ble_process_phy_update_pkt(uint8_t len,uint8_t * data)3033 void btm_ble_process_phy_update_pkt(uint8_t len, uint8_t* data) {
3034   uint8_t status, tx_phy, rx_phy;
3035   uint16_t handle;
3036 
3037   LOG_ASSERT(len == 5);
3038   uint8_t* p = data;
3039   STREAM_TO_UINT8(status, p);
3040   STREAM_TO_UINT16(handle, p);
3041   handle = handle & 0x0FFF;
3042   STREAM_TO_UINT8(tx_phy, p);
3043   STREAM_TO_UINT8(rx_phy, p);
3044 
3045   gatt_notify_phy_updated(static_cast<tGATT_STATUS>(status), handle, tx_phy,
3046                           rx_phy);
3047 }
3048 
3049 /*******************************************************************************
3050  *
3051  * Function         btm_ble_start_scan
3052  *
3053  * Description      Start the BLE scan.
3054  *
3055  * Returns          void
3056  *
3057  ******************************************************************************/
btm_ble_start_scan()3058 static void btm_ble_start_scan() {
3059   btm_cb.neighbor.le_legacy_scan = {
3060       .start_time_ms = timestamper_in_milliseconds.GetTimestamp(),
3061       .results = 0,
3062   };
3063   BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le legacy scan started",
3064                  "Duplicates:disable");
3065 
3066   /* start scan, disable duplicate filtering */
3067   btm_send_hci_scan_enable(BTM_BLE_SCAN_ENABLE, BTM_BLE_DUPLICATE_DISABLE);
3068 
3069   if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI)
3070     btm_ble_set_topology_mask(BTM_BLE_STATE_ACTIVE_SCAN_BIT);
3071   else
3072     btm_ble_set_topology_mask(BTM_BLE_STATE_PASSIVE_SCAN_BIT);
3073 }
3074 
3075 /*******************************************************************************
3076  *
3077  * Function         btm_ble_stop_scan
3078  *
3079  * Description      Stop the BLE scan.
3080  *
3081  * Returns          void
3082  *
3083  ******************************************************************************/
btm_ble_stop_scan(void)3084 static void btm_ble_stop_scan(void) {
3085   if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI)
3086     btm_ble_clear_topology_mask(BTM_BLE_STATE_ACTIVE_SCAN_BIT);
3087   else
3088     btm_ble_clear_topology_mask(BTM_BLE_STATE_PASSIVE_SCAN_BIT);
3089 
3090   /* Clear the inquiry callback if set */
3091   btm_cb.ble_ctr_cb.inq_var.scan_type = BTM_BLE_SCAN_MODE_NONE;
3092 
3093   /* stop discovery now */
3094   const unsigned long long duration_timestamp =
3095       timestamper_in_milliseconds.GetTimestamp() -
3096       btm_cb.neighbor.le_legacy_scan.start_time_ms;
3097   BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le legacy scan stopped",
3098                  base::StringPrintf("duration_s:%6.3f results:%-3lu",
3099                                     (double)duration_timestamp / 1000.0,
3100                                     btm_cb.neighbor.le_legacy_scan.results));
3101   btm_send_hci_scan_enable(BTM_BLE_SCAN_DISABLE, BTM_BLE_DUPLICATE_ENABLE);
3102 
3103   btm_update_scanner_filter_policy(SP_ADV_ALL);
3104 }
3105 /*******************************************************************************
3106  *
3107  * Function         btm_ble_stop_inquiry
3108  *
3109  * Description      Stop the BLE Inquiry.
3110  *
3111  * Returns          void
3112  *
3113  ******************************************************************************/
btm_ble_stop_inquiry(void)3114 void btm_ble_stop_inquiry(void) {
3115   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
3116   tBTM_BLE_CB* p_ble_cb = &btm_cb.ble_ctr_cb;
3117 
3118   alarm_cancel(p_ble_cb->inq_var.inquiry_timer);
3119 
3120   const unsigned long long duration_timestamp =
3121       timestamper_in_milliseconds.GetTimestamp() -
3122       btm_cb.neighbor.le_inquiry.start_time_ms;
3123   BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le inquiry stopped",
3124                  base::StringPrintf("duration_s:%6.3f results:%-3lu",
3125                                     (double)duration_timestamp / 1000.0,
3126                                     btm_cb.neighbor.le_inquiry.results));
3127   p_ble_cb->reset_ble_inquiry();
3128 
3129   /* Cleanup anything remaining on index 0 */
3130   BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_DELETE,
3131                              static_cast<tBTM_BLE_PF_FILT_INDEX>(0), nullptr,
3132                              base::Bind(btm_ble_scan_filt_param_cfg_evt));
3133 
3134   /* If no more scan activity, stop LE scan now */
3135   if (!p_ble_cb->is_ble_scan_active()) {
3136     btm_ble_stop_scan();
3137   } else if ((p_ble_cb->inq_var.scan_interval !=
3138               BTM_BLE_LOW_LATENCY_SCAN_INT) ||
3139              (p_ble_cb->inq_var.scan_window != BTM_BLE_LOW_LATENCY_SCAN_WIN)) {
3140     BTM_TRACE_DEBUG("%s: setting default params for ongoing observe", __func__);
3141     btm_ble_stop_scan();
3142     btm_ble_start_scan();
3143   }
3144 
3145   /* If we have a callback registered for inquiry complete, call it */
3146   BTM_TRACE_DEBUG("BTM Inq Compl Callback: status 0x%02x, num results %d",
3147                   p_inq->inq_cmpl_info.status, p_inq->inq_cmpl_info.num_resp);
3148 
3149   btm_process_inq_complete(
3150       HCI_SUCCESS, (uint8_t)(p_inq->inqparms.mode & BTM_BLE_INQUIRY_MASK));
3151 }
3152 
3153 /*******************************************************************************
3154  *
3155  * Function         btm_ble_stop_observe
3156  *
3157  * Description      Stop the BLE Observe.
3158  *
3159  * Returns          void
3160  *
3161  ******************************************************************************/
btm_ble_stop_observe(void)3162 static void btm_ble_stop_observe(void) {
3163   tBTM_BLE_CB* p_ble_cb = &btm_cb.ble_ctr_cb;
3164   tBTM_CMPL_CB* p_obs_cb = p_ble_cb->p_obs_cmpl_cb;
3165 
3166   alarm_cancel(p_ble_cb->observer_timer);
3167 
3168   p_ble_cb->reset_ble_observe();
3169 
3170   p_ble_cb->p_obs_results_cb = NULL;
3171   p_ble_cb->p_obs_cmpl_cb = NULL;
3172 
3173   if (!p_ble_cb->is_ble_scan_active()) {
3174     btm_ble_stop_scan();
3175   }
3176 
3177   if (p_obs_cb) (p_obs_cb)(&btm_cb.btm_inq_vars.inq_cmpl_info);
3178 }
3179 /*******************************************************************************
3180  *
3181  * Function         btm_ble_adv_states_operation
3182  *
3183  * Description      Set or clear adv states in topology mask
3184  *
3185  * Returns          operation status. true if sucessful, false otherwise.
3186  *
3187  ******************************************************************************/
3188 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)3189 static bool btm_ble_adv_states_operation(BTM_TOPOLOGY_FUNC_PTR* p_handler,
3190                                          uint8_t adv_evt) {
3191   bool rt = false;
3192 
3193   switch (adv_evt) {
3194     case BTM_BLE_CONNECT_EVT:
3195       rt = (*p_handler)(BTM_BLE_STATE_CONN_ADV_BIT);
3196       break;
3197 
3198     case BTM_BLE_NON_CONNECT_EVT:
3199       rt = (*p_handler)(BTM_BLE_STATE_NON_CONN_ADV_BIT);
3200       break;
3201     case BTM_BLE_CONNECT_DIR_EVT:
3202       rt = (*p_handler)(BTM_BLE_STATE_HI_DUTY_DIR_ADV_BIT);
3203       break;
3204 
3205     case BTM_BLE_DISCOVER_EVT:
3206       rt = (*p_handler)(BTM_BLE_STATE_SCAN_ADV_BIT);
3207       break;
3208 
3209     case BTM_BLE_CONNECT_LO_DUTY_DIR_EVT:
3210       rt = (*p_handler)(BTM_BLE_STATE_LO_DUTY_DIR_ADV_BIT);
3211       break;
3212 
3213     default:
3214       BTM_TRACE_ERROR("unknown adv event : %d", adv_evt);
3215       break;
3216   }
3217 
3218   return rt;
3219 }
3220 
3221 /*******************************************************************************
3222  *
3223  * Function         btm_ble_start_adv
3224  *
3225  * Description      start the BLE advertising.
3226  *
3227  * Returns          void
3228  *
3229  ******************************************************************************/
btm_ble_start_adv(void)3230 static tBTM_STATUS btm_ble_start_adv(void) {
3231   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
3232 
3233   if (!btm_ble_adv_states_operation(btm_ble_topology_check, p_cb->evt_type))
3234     return BTM_WRONG_MODE;
3235 
3236   btsnd_hcic_ble_set_adv_enable(BTM_BLE_ADV_ENABLE);
3237   p_cb->adv_mode = BTM_BLE_ADV_ENABLE;
3238   btm_ble_adv_states_operation(btm_ble_set_topology_mask, p_cb->evt_type);
3239   return BTM_SUCCESS;
3240 }
3241 
3242 /*******************************************************************************
3243  *
3244  * Function         btm_ble_stop_adv
3245  *
3246  * Description      Stop the BLE advertising.
3247  *
3248  * Returns          void
3249  *
3250  ******************************************************************************/
btm_ble_stop_adv(void)3251 static tBTM_STATUS btm_ble_stop_adv(void) {
3252   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
3253 
3254   if (p_cb->adv_mode == BTM_BLE_ADV_ENABLE) {
3255     btsnd_hcic_ble_set_adv_enable(BTM_BLE_ADV_DISABLE);
3256 
3257     p_cb->fast_adv_on = false;
3258     p_cb->adv_mode = BTM_BLE_ADV_DISABLE;
3259 
3260     /* clear all adv states */
3261     btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_ADV_MASK);
3262   }
3263   return BTM_SUCCESS;
3264 }
3265 
btm_ble_fast_adv_timer_timeout(UNUSED_ATTR void * data)3266 static void btm_ble_fast_adv_timer_timeout(UNUSED_ATTR void* data) {
3267   /* fast adv is completed, fall back to slow adv interval */
3268   btm_ble_start_slow_adv();
3269 }
3270 
3271 /*******************************************************************************
3272  *
3273  * Function         btm_ble_start_slow_adv
3274  *
3275  * Description      Restart adv with slow adv interval
3276  *
3277  * Returns          void
3278  *
3279  ******************************************************************************/
btm_ble_start_slow_adv(void)3280 static void btm_ble_start_slow_adv(void) {
3281   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
3282 
3283   if (p_cb->adv_mode == BTM_BLE_ADV_ENABLE) {
3284     tBTM_LE_RANDOM_CB* p_addr_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
3285     RawAddress address = RawAddress::kEmpty;
3286     tBLE_ADDR_TYPE init_addr_type = BLE_ADDR_PUBLIC;
3287     tBLE_ADDR_TYPE own_addr_type = p_addr_cb->own_addr_type;
3288 
3289     btm_ble_stop_adv();
3290 
3291     p_cb->evt_type = btm_set_conn_mode_adv_init_addr(address, &init_addr_type,
3292                                                      &own_addr_type);
3293 
3294     /* slow adv mode never goes into directed adv */
3295     btsnd_hcic_ble_write_adv_params(
3296         BTM_BLE_GAP_ADV_SLOW_INT, BTM_BLE_GAP_ADV_SLOW_INT, p_cb->evt_type,
3297         own_addr_type, init_addr_type, address, p_cb->adv_chnl_map, p_cb->afp);
3298 
3299     btm_ble_start_adv();
3300   }
3301 }
3302 
btm_ble_inquiry_timer_gap_limited_discovery_timeout(UNUSED_ATTR void * data)3303 static void btm_ble_inquiry_timer_gap_limited_discovery_timeout(
3304     UNUSED_ATTR void* data) {
3305   /* lim_timeout expired, limited discovery should exit now */
3306   btm_cb.btm_inq_vars.discoverable_mode &= ~BTM_BLE_LIMITED_DISCOVERABLE;
3307   btm_ble_set_adv_flag(btm_cb.btm_inq_vars.connectable_mode,
3308                        btm_cb.btm_inq_vars.discoverable_mode);
3309 }
3310 
btm_ble_inquiry_timer_timeout(UNUSED_ATTR void * data)3311 static void btm_ble_inquiry_timer_timeout(UNUSED_ATTR void* data) {
3312   btm_ble_stop_inquiry();
3313 }
3314 
btm_ble_observer_timer_timeout(UNUSED_ATTR void * data)3315 static void btm_ble_observer_timer_timeout(UNUSED_ATTR void* data) {
3316   btm_ble_stop_observe();
3317 }
3318 
3319 /*******************************************************************************
3320  *
3321  * Function         btm_ble_read_remote_features_complete
3322  *
3323  * Description      This function is called when the command complete message
3324  *                  is received from the HCI for the read LE remote feature
3325  *                  supported complete event.
3326  *
3327  * Returns          void
3328  *
3329  ******************************************************************************/
btm_ble_read_remote_features_complete(uint8_t * p,uint8_t length)3330 void btm_ble_read_remote_features_complete(uint8_t* p, uint8_t length) {
3331   uint16_t handle;
3332   uint8_t status;
3333 
3334   if (length < 3) {
3335     goto err_out;
3336   }
3337 
3338   STREAM_TO_UINT8(status, p);
3339   STREAM_TO_UINT16(handle, p);
3340   handle = handle & 0x0FFF;  // only 12 bits meaningful
3341 
3342   if (status != HCI_SUCCESS) {
3343     if (status != HCI_ERR_UNSUPPORTED_REM_FEATURE) {
3344       LOG_ERROR("Failed to read remote features status:%s",
3345                 hci_error_code_text(static_cast<tHCI_STATUS>(status)).c_str());
3346       return;
3347     }
3348     LOG_WARN("Remote does not support reading remote feature");
3349   }
3350 
3351   if (status == HCI_SUCCESS) {
3352     // BD_FEATURES_LEN additional bytes are read
3353     // in acl_set_peer_le_features_from_handle
3354     if (length < 3 + BD_FEATURES_LEN) {
3355       goto err_out;
3356     }
3357 
3358     if (!acl_set_peer_le_features_from_handle(handle, p)) {
3359       LOG_ERROR(
3360           "Unable to find existing connection after read remote features");
3361       return;
3362     }
3363   }
3364 
3365   btsnd_hcic_rmt_ver_req(handle);
3366 
3367   return;
3368 
3369 err_out:
3370   LOG_ERROR("Bogus event packet, too short");
3371 }
3372 
3373 /*******************************************************************************
3374  *
3375  * Function         btm_ble_write_adv_enable_complete
3376  *
3377  * Description      This function process the write adv enable command complete.
3378  *
3379  * Returns          void
3380  *
3381  ******************************************************************************/
btm_ble_write_adv_enable_complete(uint8_t * p,uint16_t evt_len)3382 void btm_ble_write_adv_enable_complete(uint8_t* p, uint16_t evt_len) {
3383   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
3384 
3385   /* if write adv enable/disbale not succeed */
3386   if (evt_len < 1 || *p != HCI_SUCCESS) {
3387     /* toggle back the adv mode */
3388     p_cb->adv_mode = !p_cb->adv_mode;
3389   }
3390 }
3391 
3392 /*******************************************************************************
3393  *
3394  * Function         btm_ble_dir_adv_tout
3395  *
3396  * Description      when directed adv time out
3397  *
3398  * Returns          void
3399  *
3400  ******************************************************************************/
btm_ble_dir_adv_tout(void)3401 void btm_ble_dir_adv_tout(void) {
3402   btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
3403 
3404   /* make device fall back into undirected adv mode by default */
3405   btm_cb.ble_ctr_cb.inq_var.directed_conn = BTM_BLE_ADV_IND_EVT;
3406 }
3407 
3408 /*******************************************************************************
3409  *
3410  * Function         btm_ble_set_topology_mask
3411  *
3412  * Description      set BLE topology mask
3413  *
3414  * Returns          true is request is allowed, false otherwise.
3415  *
3416  ******************************************************************************/
btm_ble_set_topology_mask(tBTM_BLE_STATE_MASK request_state_mask)3417 bool btm_ble_set_topology_mask(tBTM_BLE_STATE_MASK request_state_mask) {
3418   request_state_mask &= BTM_BLE_STATE_ALL_MASK;
3419   btm_cb.ble_ctr_cb.cur_states |= (request_state_mask & BTM_BLE_STATE_ALL_MASK);
3420   return true;
3421 }
3422 
3423 /*******************************************************************************
3424  *
3425  * Function         btm_ble_clear_topology_mask
3426  *
3427  * Description      Clear BLE topology bit mask
3428  *
3429  * Returns          true is request is allowed, false otherwise.
3430  *
3431  ******************************************************************************/
btm_ble_clear_topology_mask(tBTM_BLE_STATE_MASK request_state_mask)3432 bool btm_ble_clear_topology_mask(tBTM_BLE_STATE_MASK request_state_mask) {
3433   request_state_mask &= BTM_BLE_STATE_ALL_MASK;
3434   btm_cb.ble_ctr_cb.cur_states &= ~request_state_mask;
3435   return true;
3436 }
3437 
3438 /*******************************************************************************
3439  *
3440  * Function         btm_ble_update_link_topology_mask
3441  *
3442  * Description      This function update the link topology mask
3443  *
3444  * Returns          void
3445  *
3446  ******************************************************************************/
btm_ble_update_link_topology_mask(uint8_t link_role,bool increase)3447 static void btm_ble_update_link_topology_mask(uint8_t link_role,
3448                                               bool increase) {
3449   btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_CONN_MASK);
3450 
3451   if (increase)
3452     btm_cb.ble_ctr_cb.link_count[link_role]++;
3453   else if (btm_cb.ble_ctr_cb.link_count[link_role] > 0)
3454     btm_cb.ble_ctr_cb.link_count[link_role]--;
3455 
3456   if (btm_cb.ble_ctr_cb.link_count[HCI_ROLE_CENTRAL])
3457     btm_ble_set_topology_mask(BTM_BLE_STATE_CENTRAL_BIT);
3458 
3459   if (btm_cb.ble_ctr_cb.link_count[HCI_ROLE_PERIPHERAL])
3460     btm_ble_set_topology_mask(BTM_BLE_STATE_PERIPHERAL_BIT);
3461 
3462   if (link_role == HCI_ROLE_PERIPHERAL && increase) {
3463     btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
3464     /* make device fall back into undirected adv mode by default */
3465     btm_cb.ble_ctr_cb.inq_var.directed_conn = BTM_BLE_ADV_IND_EVT;
3466     /* clear all adv states */
3467     btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_ADV_MASK);
3468   }
3469 }
3470 
btm_ble_increment_link_topology_mask(uint8_t link_role)3471 void btm_ble_increment_link_topology_mask(uint8_t link_role) {
3472   btm_ble_update_link_topology_mask(link_role, true);
3473 }
3474 
btm_ble_decrement_link_topology_mask(uint8_t link_role)3475 void btm_ble_decrement_link_topology_mask(uint8_t link_role) {
3476   btm_ble_update_link_topology_mask(link_role, false);
3477 }
3478 
3479 /*******************************************************************************
3480  *
3481  * Function         btm_ble_update_mode_operation
3482  *
3483  * Description      This function update the GAP role operation when a link
3484  *                  status is updated.
3485  *
3486  * Returns          void
3487  *
3488  ******************************************************************************/
btm_ble_update_mode_operation(uint8_t link_role,const RawAddress * bd_addr,tHCI_STATUS status)3489 void btm_ble_update_mode_operation(uint8_t link_role, const RawAddress* bd_addr,
3490                                    tHCI_STATUS status) {
3491   if (status == HCI_ERR_ADVERTISING_TIMEOUT) {
3492     btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
3493     /* make device fall back into undirected adv mode by default */
3494     btm_cb.ble_ctr_cb.inq_var.directed_conn = BTM_BLE_ADV_IND_EVT;
3495     /* clear all adv states */
3496     btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_ADV_MASK);
3497   }
3498 
3499   if (btm_cb.ble_ctr_cb.inq_var.connectable_mode == BTM_BLE_CONNECTABLE) {
3500     btm_ble_set_connectability(btm_cb.btm_inq_vars.connectable_mode |
3501                                btm_cb.ble_ctr_cb.inq_var.connectable_mode);
3502   }
3503 
3504   /* in case of disconnected, we must cancel bgconn and restart
3505      in order to add back device to acceptlist in order to reconnect */
3506   if (bd_addr != nullptr) {
3507       LOG_DEBUG("gd_acl enabled so skip background connection logic");
3508   }
3509 
3510   /* when no connection is attempted, and controller is not rejecting last
3511      request
3512      due to resource limitation, start next direct connection or background
3513      connection
3514      now in order */
3515   if (btm_cb.ble_ctr_cb.is_connection_state_idle() &&
3516       status != HCI_ERR_HOST_REJECT_RESOURCES &&
3517       status != HCI_ERR_MAX_NUM_OF_CONNECTIONS) {
3518     LOG_DEBUG("Resuming le background connections");
3519     btm_ble_resume_bg_conn();
3520   }
3521 }
3522 
3523 /*******************************************************************************
3524  *
3525  * Function         btm_ble_init
3526  *
3527  * Description      Initialize the control block variable values.
3528  *
3529  * Returns          void
3530  *
3531  ******************************************************************************/
btm_ble_init(void)3532 void btm_ble_init(void) {
3533   tBTM_BLE_CB* p_cb = &btm_cb.ble_ctr_cb;
3534 
3535   BTM_TRACE_DEBUG("%s", __func__);
3536 
3537   alarm_free(p_cb->observer_timer);
3538   alarm_free(p_cb->inq_var.fast_adv_timer);
3539   memset(p_cb, 0, sizeof(tBTM_BLE_CB));
3540   memset(&(btm_cb.cmn_ble_vsc_cb), 0, sizeof(tBTM_BLE_VSC_CB));
3541   btm_cb.cmn_ble_vsc_cb.values_read = false;
3542 
3543   p_cb->observer_timer = alarm_new("btm_ble.observer_timer");
3544   p_cb->cur_states = 0;
3545 
3546   p_cb->inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
3547   p_cb->inq_var.scan_type = BTM_BLE_SCAN_MODE_NONE;
3548   p_cb->inq_var.adv_chnl_map = BTM_BLE_DEFAULT_ADV_CHNL_MAP;
3549   p_cb->inq_var.afp = BTM_BLE_DEFAULT_AFP;
3550   p_cb->inq_var.sfp = BTM_BLE_DEFAULT_SFP;
3551   p_cb->inq_var.connectable_mode = BTM_BLE_NON_CONNECTABLE;
3552   p_cb->inq_var.discoverable_mode = BTM_BLE_NON_DISCOVERABLE;
3553   p_cb->inq_var.fast_adv_timer = alarm_new("btm_ble_inq.fast_adv_timer");
3554   p_cb->inq_var.inquiry_timer = alarm_new("btm_ble_inq.inquiry_timer");
3555 
3556   p_cb->inq_var.evt_type = BTM_BLE_NON_CONNECT_EVT;
3557 
3558   p_cb->addr_mgnt_cb.refresh_raddr_timer =
3559       alarm_new("btm_ble_addr.refresh_raddr_timer");
3560   btm_ble_pa_sync_cb = {};
3561   sync_timeout_alarm = alarm_new("btm.sync_start_task");
3562 #if (BLE_VND_INCLUDED == FALSE)
3563   btm_ble_adv_filter_init();
3564 #endif
3565 }
3566 
3567 // Clean up btm ble control block
btm_ble_free()3568 void btm_ble_free() {
3569   tBTM_BLE_CB* p_cb = &btm_cb.ble_ctr_cb;
3570   alarm_free(p_cb->addr_mgnt_cb.refresh_raddr_timer);
3571 }
3572 
3573 /*******************************************************************************
3574  *
3575  * Function         btm_ble_topology_check
3576  *
3577  * Description      check to see requested state is supported. One state check
3578  *                  at a time is supported
3579  *
3580  * Returns          true is request is allowed, false otherwise.
3581  *
3582  ******************************************************************************/
btm_ble_topology_check(tBTM_BLE_STATE_MASK request_state_mask)3583 bool btm_ble_topology_check(tBTM_BLE_STATE_MASK request_state_mask) {
3584   bool rt = false;
3585 
3586   uint8_t state_offset = 0;
3587   uint16_t cur_states = btm_cb.ble_ctr_cb.cur_states;
3588   uint8_t request_state = 0;
3589 
3590   /* check only one bit is set and within valid range */
3591   if (request_state_mask == BTM_BLE_STATE_INVALID ||
3592       request_state_mask > BTM_BLE_STATE_SCAN_ADV_BIT ||
3593       (request_state_mask & (request_state_mask - 1)) != 0) {
3594     BTM_TRACE_ERROR("illegal state requested: %d", request_state_mask);
3595     return rt;
3596   }
3597 
3598   while (request_state_mask) {
3599     request_state_mask >>= 1;
3600     request_state++;
3601   }
3602 
3603   /* check if the requested state is supported or not */
3604   uint8_t bit_num = btm_le_state_combo_tbl[0][request_state - 1];
3605   const uint8_t* ble_supported_states =
3606       controller_get_interface()->get_ble_supported_states();
3607 
3608   if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, bit_num)) {
3609     BTM_TRACE_ERROR("state requested not supported: %d", request_state);
3610     return rt;
3611   }
3612 
3613   rt = true;
3614   /* make sure currently active states are all supported in conjunction with the
3615      requested state. If the bit in table is UNSUPPORTED, the combination is not
3616      supported */
3617   while (cur_states != 0) {
3618     if (cur_states & 0x01) {
3619       uint8_t bit_num = btm_le_state_combo_tbl[request_state][state_offset];
3620       if (bit_num != UNSUPPORTED) {
3621         if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, bit_num)) {
3622           rt = false;
3623           break;
3624         }
3625       }
3626     }
3627     cur_states >>= 1;
3628     state_offset++;
3629   }
3630   return rt;
3631 }
3632