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/bind.h>
28 #include <base/callback.h>
29 #include <base/strings/string_number_conversions.h>
30 #include <stddef.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <list>
34 #include <vector>
35 
36 #include "bt_types.h"
37 #include "bt_utils.h"
38 #include "btm_ble_api.h"
39 #include "btm_int.h"
40 #include "btu.h"
41 #include "device/include/controller.h"
42 #include "gap_api.h"
43 #include "hcimsgs.h"
44 #include "osi/include/osi.h"
45 
46 #include "advertise_data_parser.h"
47 #include "btm_ble_int.h"
48 #include "gatt_int.h"
49 #include "gattdefs.h"
50 #include "l2c_int.h"
51 #include "osi/include/log.h"
52 #include "common/time_util.h"
53 
54 #include "main/shim/btm_api.h"
55 #include "main/shim/shim.h"
56 
57 #define BTM_BLE_NAME_SHORT 0x01
58 #define BTM_BLE_NAME_CMPL 0x02
59 
60 #define BTM_BLE_FILTER_TARGET_UNKNOWN 0xff
61 #define BTM_BLE_POLICY_UNKNOWN 0xff
62 
63 #define BTM_EXT_BLE_RMT_NAME_TIMEOUT_MS (30 * 1000)
64 #define MIN_ADV_LENGTH 2
65 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN 9
66 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_L_RELEASE \
67   BTM_VSC_CHIP_CAPABILITY_RSP_LEN
68 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_M_RELEASE 15
69 
70 namespace {
71 
72 class AdvertisingCache {
73  public:
74   /* Set the data to |data| for device |addr_type, addr| */
Set(uint8_t addr_type,const RawAddress & addr,std::vector<uint8_t> data)75   const std::vector<uint8_t>& Set(uint8_t addr_type, const RawAddress& addr,
76                                   std::vector<uint8_t> data) {
77     auto it = Find(addr_type, addr);
78     if (it != items.end()) {
79       it->data = std::move(data);
80       return it->data;
81     }
82 
83     if (items.size() > cache_max) {
84       items.pop_back();
85     }
86 
87     items.emplace_front(addr_type, addr, std::move(data));
88     return items.front().data;
89   }
90 
Exist(uint8_t addr_type,const RawAddress & addr)91   bool Exist(uint8_t addr_type, const RawAddress& addr) {
92     auto it = Find(addr_type, addr);
93     if (it != items.end()) {
94         return true;
95     }
96     return false;
97   }
98 
99   /* Append |data| for device |addr_type, addr| */
Append(uint8_t addr_type,const RawAddress & addr,std::vector<uint8_t> data)100   const std::vector<uint8_t>& Append(uint8_t addr_type, const RawAddress& addr,
101                                      std::vector<uint8_t> data) {
102     auto it = Find(addr_type, addr);
103     if (it != items.end()) {
104       it->data.insert(it->data.end(), data.begin(), data.end());
105       return it->data;
106     }
107 
108     if (items.size() > cache_max) {
109       items.pop_back();
110     }
111 
112     items.emplace_front(addr_type, addr, std::move(data));
113     return items.front().data;
114   }
115 
116   /* Clear data for device |addr_type, addr| */
Clear(uint8_t addr_type,const RawAddress & addr)117   void Clear(uint8_t addr_type, const RawAddress& addr) {
118     auto it = Find(addr_type, addr);
119     if (it != items.end()) {
120       items.erase(it);
121     }
122   }
123 
ClearAll()124   void ClearAll() {
125     items.clear();
126   }
127 
128  private:
129   struct Item {
130     uint8_t addr_type;
131     RawAddress addr;
132     std::vector<uint8_t> data;
133 
Item__anon44c17b2f0111::AdvertisingCache::Item134     Item(uint8_t addr_type, const RawAddress& addr, std::vector<uint8_t> data)
135         : addr_type(addr_type), addr(addr), data(data) {}
136   };
137 
Find(uint8_t addr_type,const RawAddress & addr)138   std::list<Item>::iterator Find(uint8_t addr_type, const RawAddress& addr) {
139     for (auto it = items.begin(); it != items.end(); it++) {
140       if (it->addr_type == addr_type && it->addr == addr) {
141         return it;
142       }
143     }
144     return items.end();
145   }
146 
147   /* we keep maximum 7 devices in the cache */
148   const size_t cache_max = 7;
149   std::list<Item> items;
150 };
151 
152 /* Devices in this cache are waiting for eiter scan response, or chained packets
153  * on secondary channel */
154 AdvertisingCache cache;
155 
156 }  // namespace
157 
158 #if (BLE_VND_INCLUDED == TRUE)
159 static tBTM_BLE_CTRL_FEATURES_CBACK* p_ctrl_le_feature_rd_cmpl_cback = NULL;
160 #endif
161 
162 /*******************************************************************************
163  *  Local functions
164  ******************************************************************************/
165 static void btm_ble_update_adv_flag(uint8_t flag);
166 void btm_ble_process_adv_pkt_cont(uint16_t evt_type, uint8_t addr_type,
167                                   const RawAddress& bda, uint8_t primary_phy,
168                                   uint8_t secondary_phy,
169                                   uint8_t advertising_sid, int8_t tx_power,
170                                   int8_t rssi, uint16_t periodic_adv_int,
171                                   uint8_t data_len, uint8_t* data);
172 static uint8_t btm_set_conn_mode_adv_init_addr(tBTM_BLE_INQ_CB* p_cb,
173                                                RawAddress& p_peer_addr_ptr,
174                                                tBLE_ADDR_TYPE* p_peer_addr_type,
175                                                tBLE_ADDR_TYPE* p_own_addr_type);
176 static void btm_ble_stop_observe(void);
177 static void btm_ble_fast_adv_timer_timeout(void* data);
178 static void btm_ble_start_slow_adv(void);
179 static void btm_ble_inquiry_timer_gap_limited_discovery_timeout(void* data);
180 static void btm_ble_inquiry_timer_timeout(void* data);
181 static void btm_ble_observer_timer_timeout(void* data);
182 
183 #define BTM_BLE_INQ_RESULT 0x01
184 #define BTM_BLE_OBS_RESULT 0x02
185 
ble_evt_type_is_connectable(uint16_t evt_type)186 bool ble_evt_type_is_connectable(uint16_t evt_type) {
187   return evt_type & (1 << BLE_EVT_CONNECTABLE_BIT);
188 }
189 
ble_evt_type_is_scannable(uint16_t evt_type)190 bool ble_evt_type_is_scannable(uint16_t evt_type) {
191   return evt_type & (1 << BLE_EVT_SCANNABLE_BIT);
192 }
193 
ble_evt_type_is_directed(uint16_t evt_type)194 bool ble_evt_type_is_directed(uint16_t evt_type) {
195   return evt_type & (1 << BLE_EVT_DIRECTED_BIT);
196 }
197 
ble_evt_type_is_scan_resp(uint16_t evt_type)198 bool ble_evt_type_is_scan_resp(uint16_t evt_type) {
199   return evt_type & (1 << BLE_EVT_SCAN_RESPONSE_BIT);
200 }
201 
ble_evt_type_is_legacy(uint16_t evt_type)202 bool ble_evt_type_is_legacy(uint16_t evt_type) {
203   return evt_type & (1 << BLE_EVT_LEGACY_BIT);
204 }
205 
ble_evt_type_data_status(uint16_t evt_type)206 uint8_t ble_evt_type_data_status(uint16_t evt_type) {
207   return (evt_type >> 5) & 3;
208 }
209 
210 constexpr uint8_t UNSUPPORTED = 255;
211 
212 /* LE states combo bit to check */
213 const uint8_t btm_le_state_combo_tbl[BTM_BLE_STATE_MAX][BTM_BLE_STATE_MAX] = {
214     {
215         /* single state support */
216         HCI_LE_STATES_CONN_ADV_BIT, /* conn_adv */
217         HCI_LE_STATES_INIT_BIT,     /* init */
218         HCI_LE_STATES_INIT_BIT,     /* master */
219         HCI_LE_STATES_SLAVE_BIT,    /* slave */
220         UNSUPPORTED,                /* todo: lo du dir adv, not covered ? */
221         HCI_LE_STATES_HI_DUTY_DIR_ADV_BIT, /* hi duty dir adv */
222         HCI_LE_STATES_NON_CONN_ADV_BIT,    /* non connectable adv */
223         HCI_LE_STATES_PASS_SCAN_BIT,       /*  passive scan */
224         HCI_LE_STATES_ACTIVE_SCAN_BIT,     /*   active scan */
225         HCI_LE_STATES_SCAN_ADV_BIT         /* scanable adv */
226     },
227     {
228         /* conn_adv =0 */
229         UNSUPPORTED,                            /* conn_adv */
230         HCI_LE_STATES_CONN_ADV_INIT_BIT,        /* init: 32 */
231         HCI_LE_STATES_CONN_ADV_MASTER_BIT,      /* master: 35 */
232         HCI_LE_STATES_CONN_ADV_SLAVE_BIT,       /* slave: 38,*/
233         UNSUPPORTED,                            /* lo du dir adv */
234         UNSUPPORTED,                            /* hi duty dir adv */
235         UNSUPPORTED,                            /* non connectable adv */
236         HCI_LE_STATES_CONN_ADV_PASS_SCAN_BIT,   /*  passive scan */
237         HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_BIT, /*   active scan */
238         UNSUPPORTED                             /* scanable adv */
239     },
240     {
241         /* init */
242         HCI_LE_STATES_CONN_ADV_INIT_BIT,        /* conn_adv: 32 */
243         UNSUPPORTED,                            /* init */
244         HCI_LE_STATES_INIT_MASTER_BIT,          /* master 28 */
245         HCI_LE_STATES_INIT_MASTER_SLAVE_BIT,    /* slave 41 */
246         HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_BIT, /* lo du dir adv 34 */
247         HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_BIT, /* hi duty dir adv 33 */
248         HCI_LE_STATES_NON_CONN_INIT_BIT,        /*  non connectable adv */
249         HCI_LE_STATES_PASS_SCAN_INIT_BIT,       /* passive scan */
250         HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT,     /*  active scan */
251         HCI_LE_STATES_SCAN_ADV_INIT_BIT         /* scanable adv */
252 
253     },
254     {
255         /* master */
256         HCI_LE_STATES_CONN_ADV_MASTER_BIT,        /* conn_adv: 35 */
257         HCI_LE_STATES_INIT_MASTER_BIT,            /* init 28 */
258         HCI_LE_STATES_INIT_MASTER_BIT,            /* master 28 */
259         HCI_LE_STATES_CONN_ADV_INIT_BIT,          /* slave: 32 */
260         HCI_LE_STATES_LO_DUTY_DIR_ADV_MASTER_BIT, /* lo duty cycle adv 37 */
261         HCI_LE_STATES_HI_DUTY_DIR_ADV_MASTER_BIT, /* hi duty cycle adv 36 */
262         HCI_LE_STATES_NON_CONN_ADV_MASTER_BIT,    /*  non connectable adv*/
263         HCI_LE_STATES_PASS_SCAN_MASTER_BIT,       /*  passive scan */
264         HCI_LE_STATES_ACTIVE_SCAN_MASTER_BIT,     /*   active scan */
265         HCI_LE_STATES_SCAN_ADV_MASTER_BIT         /*  scanable adv */
266 
267     },
268     {
269         /* slave */
270         HCI_LE_STATES_CONN_ADV_SLAVE_BIT,        /* conn_adv: 38,*/
271         HCI_LE_STATES_INIT_MASTER_SLAVE_BIT,     /* init 41 */
272         HCI_LE_STATES_INIT_MASTER_SLAVE_BIT,     /* master 41 */
273         HCI_LE_STATES_CONN_ADV_SLAVE_BIT,        /* slave: 38,*/
274         HCI_LE_STATES_LO_DUTY_DIR_ADV_SLAVE_BIT, /* lo duty cycle adv 40 */
275         HCI_LE_STATES_HI_DUTY_DIR_ADV_SLAVE_BIT, /* hi duty cycle adv 39 */
276         HCI_LE_STATES_NON_CONN_ADV_SLAVE_BIT,    /* non connectable adv */
277         HCI_LE_STATES_PASS_SCAN_SLAVE_BIT,       /* passive scan */
278         HCI_LE_STATES_ACTIVE_SCAN_SLAVE_BIT,     /*  active scan */
279         HCI_LE_STATES_SCAN_ADV_SLAVE_BIT         /* scanable adv */
280 
281     },
282     {
283         /* lo duty cycle adv */
284         UNSUPPORTED,                              /* conn_adv: 38,*/
285         HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_BIT,   /* init 34 */
286         HCI_LE_STATES_LO_DUTY_DIR_ADV_MASTER_BIT, /* master 37 */
287         HCI_LE_STATES_LO_DUTY_DIR_ADV_SLAVE_BIT,  /* slave: 40 */
288         UNSUPPORTED,                              /* lo duty cycle adv 40 */
289         UNSUPPORTED,                              /* hi duty cycle adv 39 */
290         UNSUPPORTED,                              /*  non connectable adv */
291         UNSUPPORTED, /* TODO: passive scan, not covered? */
292         UNSUPPORTED, /* TODO:  active scan, not covered? */
293         UNSUPPORTED  /*  scanable adv */
294     },
295     {
296         /* hi duty cycle adv */
297         UNSUPPORTED,                                 /* conn_adv: 38,*/
298         HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_BIT,      /* init 33 */
299         HCI_LE_STATES_HI_DUTY_DIR_ADV_MASTER_BIT,    /* master 36 */
300         HCI_LE_STATES_HI_DUTY_DIR_ADV_SLAVE_BIT,     /* slave: 39*/
301         UNSUPPORTED,                                 /* lo duty cycle adv 40 */
302         UNSUPPORTED,                                 /* hi duty cycle adv 39 */
303         UNSUPPORTED,                                 /* non connectable adv */
304         HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_BIT, /* passive scan */
305         HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_BIT, /* active scan */
306         UNSUPPORTED                                    /* scanable adv */
307     },
308     {
309         /* non connectable adv */
310         UNSUPPORTED,                                /* conn_adv: */
311         HCI_LE_STATES_NON_CONN_INIT_BIT,            /* init  */
312         HCI_LE_STATES_NON_CONN_ADV_MASTER_BIT,      /* master  */
313         HCI_LE_STATES_NON_CONN_ADV_SLAVE_BIT,       /* slave: */
314         UNSUPPORTED,                                /* lo duty cycle adv */
315         UNSUPPORTED,                                /* hi duty cycle adv */
316         UNSUPPORTED,                                /* non connectable adv */
317         HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_BIT,   /* passive scan */
318         HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_BIT, /* active scan */
319         UNSUPPORTED                                 /* scanable adv */
320     },
321     {
322         /* passive scan */
323         HCI_LE_STATES_CONN_ADV_PASS_SCAN_BIT,        /* conn_adv: */
324         HCI_LE_STATES_PASS_SCAN_INIT_BIT,            /* init  */
325         HCI_LE_STATES_PASS_SCAN_MASTER_BIT,          /* master  */
326         HCI_LE_STATES_PASS_SCAN_SLAVE_BIT,           /* slave: */
327         UNSUPPORTED,                                 /* lo duty cycle adv */
328         HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_BIT, /* hi duty cycle adv */
329         HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_BIT,    /* non connectable adv */
330         UNSUPPORTED,                                 /* passive scan */
331         UNSUPPORTED,                                 /* active scan */
332         HCI_LE_STATES_SCAN_ADV_PASS_SCAN_BIT         /* scanable adv */
333     },
334     {
335         /* active scan */
336         HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_BIT,        /* conn_adv: */
337         HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT,            /* init  */
338         HCI_LE_STATES_ACTIVE_SCAN_MASTER_BIT,          /* master  */
339         HCI_LE_STATES_ACTIVE_SCAN_SLAVE_BIT,           /* slave: */
340         UNSUPPORTED,                                   /* lo duty cycle adv */
341         HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_BIT, /* hi duty cycle adv */
342         HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_BIT, /*  non connectable adv */
343         UNSUPPORTED,                                /* TODO: passive scan */
344         UNSUPPORTED,                                /* TODO:  active scan */
345         HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_BIT      /*  scanable adv */
346     },
347     {
348         /* scanable adv */
349         UNSUPPORTED,                            /* conn_adv: */
350         HCI_LE_STATES_SCAN_ADV_INIT_BIT,        /* init  */
351         HCI_LE_STATES_SCAN_ADV_MASTER_BIT,      /* master  */
352         HCI_LE_STATES_SCAN_ADV_SLAVE_BIT,       /* slave: */
353         UNSUPPORTED,                            /* lo duty cycle adv */
354         UNSUPPORTED,                            /* hi duty cycle adv */
355         UNSUPPORTED,                            /* non connectable adv */
356         HCI_LE_STATES_SCAN_ADV_PASS_SCAN_BIT,   /*  passive scan */
357         HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_BIT, /*  active scan */
358         UNSUPPORTED                             /* scanable adv */
359     }};
360 
361 /* check LE combo state supported */
BTM_LE_STATES_SUPPORTED(const uint8_t * x,uint8_t bit_num)362 inline bool BTM_LE_STATES_SUPPORTED(const uint8_t* x, uint8_t bit_num) {
363   uint8_t mask = 1 << (bit_num % 8);
364   uint8_t offset = bit_num / 8;
365   return ((x)[offset] & mask);
366 }
367 
368 /*******************************************************************************
369  *
370  * Function         BTM_BleObserve
371  *
372  * Description      This procedure keep the device listening for advertising
373  *                  events from a broadcast device.
374  *
375  * Parameters       start: start or stop observe.
376  *                  white_list: use white list in observer mode or not.
377  *
378  * Returns          void
379  *
380  ******************************************************************************/
BTM_BleObserve(bool start,uint8_t duration,tBTM_INQ_RESULTS_CB * p_results_cb,tBTM_CMPL_CB * p_cmpl_cb)381 tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration,
382                            tBTM_INQ_RESULTS_CB* p_results_cb,
383                            tBTM_CMPL_CB* p_cmpl_cb) {
384   if (bluetooth::shim::is_gd_shim_enabled()) {
385     return bluetooth::shim::BTM_BleObserve(start, duration, p_results_cb,
386                                            p_cmpl_cb);
387   }
388 
389   tBTM_BLE_INQ_CB* p_inq = &btm_cb.ble_ctr_cb.inq_var;
390   tBTM_STATUS status = BTM_WRONG_MODE;
391 
392   uint32_t scan_interval =
393       !p_inq->scan_interval ? BTM_BLE_GAP_DISC_SCAN_INT : p_inq->scan_interval;
394   uint32_t scan_window =
395       !p_inq->scan_window ? BTM_BLE_GAP_DISC_SCAN_WIN : p_inq->scan_window;
396 
397   BTM_TRACE_EVENT("%s : scan_type:%d, %d, %d", __func__,
398                   btm_cb.btm_inq_vars.scan_type, p_inq->scan_interval,
399                   p_inq->scan_window);
400 
401   if (!controller_get_interface()->supports_ble()) return BTM_ILLEGAL_VALUE;
402 
403   if (start) {
404     /* shared inquiry database, do not allow observe if any inquiry is active */
405     if (BTM_BLE_IS_OBS_ACTIVE(btm_cb.ble_ctr_cb.scan_activity)) {
406       BTM_TRACE_ERROR("%s Observe Already Active", __func__);
407       return status;
408     }
409 
410     btm_cb.ble_ctr_cb.p_obs_results_cb = p_results_cb;
411     btm_cb.ble_ctr_cb.p_obs_cmpl_cb = p_cmpl_cb;
412     status = BTM_CMD_STARTED;
413 
414     /* scan is not started */
415     if (!BTM_BLE_IS_SCAN_ACTIVE(btm_cb.ble_ctr_cb.scan_activity)) {
416       /* allow config of scan type */
417       cache.ClearAll();
418       p_inq->scan_type = (p_inq->scan_type == BTM_BLE_SCAN_MODE_NONE)
419                              ? BTM_BLE_SCAN_MODE_ACTI
420                              : p_inq->scan_type;
421 /* assume observe always not using white list */
422 #if (defined BLE_PRIVACY_SPT && BLE_PRIVACY_SPT == TRUE)
423       /* enable resolving list */
424       btm_ble_enable_resolving_list_for_platform(BTM_BLE_RL_SCAN);
425 #endif
426 
427       btm_send_hci_set_scan_params(
428           p_inq->scan_type, (uint16_t)scan_interval, (uint16_t)scan_window,
429           btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, BTM_BLE_DEFAULT_SFP);
430 
431       p_inq->scan_duplicate_filter = BTM_BLE_DUPLICATE_DISABLE;
432       status = btm_ble_start_scan();
433     }
434 
435     if (status == BTM_CMD_STARTED) {
436       btm_cb.ble_ctr_cb.scan_activity |= BTM_LE_OBSERVE_ACTIVE;
437       if (duration != 0) {
438         /* start observer timer */
439         uint64_t duration_ms = duration * 1000;
440         alarm_set_on_mloop(btm_cb.ble_ctr_cb.observer_timer, duration_ms,
441                            btm_ble_observer_timer_timeout, NULL);
442       }
443     }
444   } else if (BTM_BLE_IS_OBS_ACTIVE(btm_cb.ble_ctr_cb.scan_activity)) {
445     status = BTM_CMD_STARTED;
446     btm_ble_stop_observe();
447   } else {
448     BTM_TRACE_ERROR("%s Observe not active", __func__);
449   }
450 
451   return status;
452 }
453 
454 #if (BLE_VND_INCLUDED == TRUE)
455 /*******************************************************************************
456  *
457  * Function         btm_vsc_brcm_features_complete
458  *
459  * Description      Command Complete callback for HCI_BLE_VENDOR_CAP
460  *
461  * Returns          void
462  *
463  ******************************************************************************/
btm_ble_vendor_capability_vsc_cmpl_cback(tBTM_VSC_CMPL * p_vcs_cplt_params)464 static void btm_ble_vendor_capability_vsc_cmpl_cback(
465     tBTM_VSC_CMPL* p_vcs_cplt_params) {
466   uint8_t status = 0xFF;
467   uint8_t* p;
468 
469   BTM_TRACE_DEBUG("%s", __func__);
470 
471   /* Check status of command complete event */
472   CHECK(p_vcs_cplt_params->opcode == HCI_BLE_VENDOR_CAP);
473   CHECK(p_vcs_cplt_params->param_len > 0);
474 
475   p = p_vcs_cplt_params->p_param_buf;
476   STREAM_TO_UINT8(status, p);
477 
478   if (status != HCI_SUCCESS) {
479     BTM_TRACE_DEBUG("%s: Status = 0x%02x (0 is success)", __func__, status);
480     return;
481   }
482   CHECK(p_vcs_cplt_params->param_len >= BTM_VSC_CHIP_CAPABILITY_RSP_LEN);
483   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.adv_inst_max, p);
484   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.rpa_offloading, p);
485   STREAM_TO_UINT16(btm_cb.cmn_ble_vsc_cb.tot_scan_results_strg, p);
486   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.max_irk_list_sz, p);
487   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.filter_support, p);
488   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.max_filter, p);
489   STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.energy_support, p);
490 
491   if (p_vcs_cplt_params->param_len >
492       BTM_VSC_CHIP_CAPABILITY_RSP_LEN_L_RELEASE) {
493     STREAM_TO_UINT16(btm_cb.cmn_ble_vsc_cb.version_supported, p);
494   } else {
495     btm_cb.cmn_ble_vsc_cb.version_supported = BTM_VSC_CHIP_CAPABILITY_L_VERSION;
496   }
497 
498   if (btm_cb.cmn_ble_vsc_cb.version_supported >=
499       BTM_VSC_CHIP_CAPABILITY_M_VERSION) {
500     CHECK(p_vcs_cplt_params->param_len >= BTM_VSC_CHIP_CAPABILITY_RSP_LEN_M_RELEASE);
501     STREAM_TO_UINT16(btm_cb.cmn_ble_vsc_cb.total_trackable_advertisers, p);
502     STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.extended_scan_support, p);
503     STREAM_TO_UINT8(btm_cb.cmn_ble_vsc_cb.debug_logging_supported, p);
504   }
505   btm_cb.cmn_ble_vsc_cb.values_read = true;
506 
507   BTM_TRACE_DEBUG(
508       "%s: stat=%d, irk=%d, ADV ins:%d, rpa=%d, ener=%d, ext_scan=%d", __func__,
509       status, btm_cb.cmn_ble_vsc_cb.max_irk_list_sz,
510       btm_cb.cmn_ble_vsc_cb.adv_inst_max, btm_cb.cmn_ble_vsc_cb.rpa_offloading,
511       btm_cb.cmn_ble_vsc_cb.energy_support,
512       btm_cb.cmn_ble_vsc_cb.extended_scan_support);
513 
514   btm_ble_adv_init();
515 
516   if (btm_cb.cmn_ble_vsc_cb.max_filter > 0) btm_ble_adv_filter_init();
517 
518 #if (BLE_PRIVACY_SPT == TRUE)
519   /* VS capability included and non-4.2 device */
520   if (btm_cb.cmn_ble_vsc_cb.max_irk_list_sz > 0 &&
521       controller_get_interface()->get_ble_resolving_list_max_size() == 0)
522     btm_ble_resolving_list_init(btm_cb.cmn_ble_vsc_cb.max_irk_list_sz);
523 #endif /* (BLE_PRIVACY_SPT == TRUE) */
524 
525   if (btm_cb.cmn_ble_vsc_cb.tot_scan_results_strg > 0) btm_ble_batchscan_init();
526 
527   if (p_ctrl_le_feature_rd_cmpl_cback != NULL)
528     p_ctrl_le_feature_rd_cmpl_cback(status);
529 }
530 #endif /* (BLE_VND_INCLUDED == TRUE) */
531 
532 /*******************************************************************************
533  *
534  * Function         BTM_BleGetVendorCapabilities
535  *
536  * Description      This function reads local LE features
537  *
538  * Parameters       p_cmn_vsc_cb : Locala LE capability structure
539  *
540  * Returns          void
541  *
542  ******************************************************************************/
BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB * p_cmn_vsc_cb)543 extern void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB* p_cmn_vsc_cb) {
544   BTM_TRACE_DEBUG("BTM_BleGetVendorCapabilities");
545 
546   if (NULL != p_cmn_vsc_cb) {
547     *p_cmn_vsc_cb = btm_cb.cmn_ble_vsc_cb;
548   }
549 }
550 
551 /******************************************************************************
552  *
553  * Function         BTM_BleReadControllerFeatures
554  *
555  * Description      Reads BLE specific controller features
556  *
557  * Parameters:      tBTM_BLE_CTRL_FEATURES_CBACK : Callback to notify when
558  *                  features are read
559  *
560  * Returns          void
561  *
562  ******************************************************************************/
563 #if (BLE_VND_INCLUDED == TRUE)
BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK * p_vsc_cback)564 extern void BTM_BleReadControllerFeatures(
565     tBTM_BLE_CTRL_FEATURES_CBACK* p_vsc_cback) {
566   if (btm_cb.cmn_ble_vsc_cb.values_read) return;
567 
568   BTM_TRACE_DEBUG("BTM_BleReadControllerFeatures");
569 
570   p_ctrl_le_feature_rd_cmpl_cback = p_vsc_cback;
571   BTM_VendorSpecificCommand(HCI_BLE_VENDOR_CAP, 0, NULL,
572                             btm_ble_vendor_capability_vsc_cmpl_cback);
573 }
574 #else
BTM_BleReadControllerFeatures(UNUSED_ATTR tBTM_BLE_CTRL_FEATURES_CBACK * p_vsc_cback)575 extern void BTM_BleReadControllerFeatures(
576     UNUSED_ATTR tBTM_BLE_CTRL_FEATURES_CBACK* p_vsc_cback) {}
577 #endif
578 
579 /*******************************************************************************
580  *
581  * Function         BTM_BleConfigPrivacy
582  *
583  * Description      This function is called to enable or disable the privacy in
584  *                   LE channel of the local device.
585  *
586  * Parameters       privacy_mode:  privacy mode on or off.
587  *
588  * Returns          bool    privacy mode set success; otherwise failed.
589  *
590  ******************************************************************************/
BTM_BleConfigPrivacy(bool privacy_mode)591 bool BTM_BleConfigPrivacy(bool privacy_mode) {
592 #if (BLE_PRIVACY_SPT == TRUE)
593   tBTM_BLE_CB* p_cb = &btm_cb.ble_ctr_cb;
594 
595   BTM_TRACE_EVENT("%s", __func__);
596 
597   /* if LE is not supported, return error */
598   if (!controller_get_interface()->supports_ble()) return false;
599 
600   tGAP_BLE_ATTR_VALUE gap_ble_attr_value;
601   gap_ble_attr_value.addr_resolution = 0;
602   if (!privacy_mode) /* if privacy disabled, always use public address */
603   {
604     p_cb->addr_mgnt_cb.own_addr_type = BLE_ADDR_PUBLIC;
605     p_cb->privacy_mode = BTM_PRIVACY_NONE;
606   } else /* privacy is turned on*/
607   {
608     /* always set host random address, used when privacy 1.1 or priavcy 1.2 is
609      * disabled */
610     p_cb->addr_mgnt_cb.own_addr_type = BLE_ADDR_RANDOM;
611     btm_gen_resolvable_private_addr(base::Bind(&btm_gen_resolve_paddr_low));
612 
613     /* 4.2 controller only allow privacy 1.2 or mixed mode, resolvable private
614      * address in controller */
615     if (controller_get_interface()->supports_ble_privacy()) {
616       gap_ble_attr_value.addr_resolution = 1;
617       /* check vendor specific capability */
618       p_cb->privacy_mode =
619           btm_cb.ble_ctr_cb.mixed_mode ? BTM_PRIVACY_MIXED : BTM_PRIVACY_1_2;
620     } else /* 4.1/4.0 controller */
621       p_cb->privacy_mode = BTM_PRIVACY_1_1;
622   }
623 
624   GAP_BleAttrDBUpdate(GATT_UUID_GAP_CENTRAL_ADDR_RESOL, &gap_ble_attr_value);
625 
626   return true;
627 #else
628   return false;
629 #endif
630 }
631 
632 /*******************************************************************************
633  *
634  * Function          BTM_BleMaxMultiAdvInstanceCount
635  *
636  * Description        Returns max number of multi adv instances supported by
637  *                  controller
638  *
639  * Returns          Max multi adv instance count
640  *
641  ******************************************************************************/
BTM_BleMaxMultiAdvInstanceCount(void)642 extern uint8_t BTM_BleMaxMultiAdvInstanceCount(void) {
643   if (bluetooth::shim::is_gd_shim_enabled()) {
644     return bluetooth::shim::BTM_BleMaxMultiAdvInstanceCount();
645   }
646   return btm_cb.cmn_ble_vsc_cb.adv_inst_max < BTM_BLE_MULTI_ADV_MAX
647              ? btm_cb.cmn_ble_vsc_cb.adv_inst_max
648              : BTM_BLE_MULTI_ADV_MAX;
649 }
650 
651 /*******************************************************************************
652  *
653  * Function         BTM_BleLocalPrivacyEnabled
654  *
655  * Description        Checks if local device supports private address
656  *
657  * Returns          Return true if local privacy is enabled else false
658  *
659  ******************************************************************************/
BTM_BleLocalPrivacyEnabled(void)660 bool BTM_BleLocalPrivacyEnabled(void) {
661 #if (BLE_PRIVACY_SPT == TRUE)
662   if (bluetooth::shim::is_gd_shim_enabled()) {
663     return bluetooth::shim::BTM_BleLocalPrivacyEnabled();
664   }
665   return (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE);
666 #else
667   return false;
668 #endif
669 }
670 
671 #if (BLE_PRIVACY_SPT == TRUE)
is_resolving_list_bit_set(void * data,void * context)672 static bool is_resolving_list_bit_set(void* data, void* context) {
673   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
674 
675   if ((p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) != 0)
676     return false;
677 
678   return true;
679 }
680 #endif
681 
682 /*******************************************************************************
683  *
684  * Function         btm_set_conn_mode_adv_init_addr
685  *
686  * Description      set initator address type and local address type based on
687  *                  adv mode.
688  *
689  *
690  ******************************************************************************/
btm_set_conn_mode_adv_init_addr(tBTM_BLE_INQ_CB * p_cb,RawAddress & p_peer_addr_ptr,tBLE_ADDR_TYPE * p_peer_addr_type,tBLE_ADDR_TYPE * p_own_addr_type)691 static uint8_t btm_set_conn_mode_adv_init_addr(
692     tBTM_BLE_INQ_CB* p_cb, RawAddress& p_peer_addr_ptr,
693     tBLE_ADDR_TYPE* p_peer_addr_type, tBLE_ADDR_TYPE* p_own_addr_type) {
694   uint8_t evt_type;
695 #if (BLE_PRIVACY_SPT == TRUE)
696   tBTM_SEC_DEV_REC* p_dev_rec;
697 #endif
698 
699   evt_type =
700       (p_cb->connectable_mode == BTM_BLE_NON_CONNECTABLE)
701           ? ((p_cb->scan_rsp) ? BTM_BLE_DISCOVER_EVT : BTM_BLE_NON_CONNECT_EVT)
702           : BTM_BLE_CONNECT_EVT;
703 
704   if (evt_type == BTM_BLE_CONNECT_EVT) {
705     evt_type = p_cb->directed_conn;
706 
707     if (p_cb->directed_conn == BTM_BLE_CONNECT_DIR_EVT ||
708         p_cb->directed_conn == BTM_BLE_CONNECT_LO_DUTY_DIR_EVT) {
709 #if (BLE_PRIVACY_SPT == TRUE)
710       /* for privacy 1.2, convert peer address as static, own address set as ID
711        * addr */
712       if (btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_1_2 ||
713           btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_MIXED) {
714         /* only do so for bonded device */
715         if ((p_dev_rec = btm_find_or_alloc_dev(p_cb->direct_bda.bda)) != NULL &&
716             p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) {
717           btm_ble_enable_resolving_list(BTM_BLE_RL_ADV);
718           p_peer_addr_ptr = p_dev_rec->ble.identity_addr;
719           *p_peer_addr_type = p_dev_rec->ble.identity_addr_type;
720           *p_own_addr_type = BLE_ADDR_RANDOM_ID;
721           return evt_type;
722         }
723         /* otherwise fall though as normal directed adv */
724         else {
725           btm_ble_disable_resolving_list(BTM_BLE_RL_ADV, true);
726         }
727       }
728 #endif
729       /* direct adv mode does not have privacy, if privacy is not enabled  */
730       *p_peer_addr_type = p_cb->direct_bda.type;
731       p_peer_addr_ptr = p_cb->direct_bda.bda;
732       return evt_type;
733     }
734   }
735 
736 /* undirect adv mode or non-connectable mode*/
737 #if (BLE_PRIVACY_SPT == TRUE)
738   /* when privacy 1.2 privacy only mode is used, or mixed mode */
739   if ((btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_1_2 &&
740        p_cb->afp != AP_SCAN_CONN_ALL) ||
741       btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_MIXED) {
742     list_node_t* n =
743         list_foreach(btm_cb.sec_dev_rec, is_resolving_list_bit_set, NULL);
744     if (n) {
745       /* if enhanced privacy is required, set Identity address and matching IRK
746        * peer */
747       tBTM_SEC_DEV_REC* p_dev_rec =
748           static_cast<tBTM_SEC_DEV_REC*>(list_node(n));
749       p_peer_addr_ptr = p_dev_rec->ble.identity_addr;
750       *p_peer_addr_type = p_dev_rec->ble.identity_addr_type;
751 
752       *p_own_addr_type = BLE_ADDR_RANDOM_ID;
753     } else {
754       /* resolving list is empty, not enabled */
755       *p_own_addr_type = BLE_ADDR_RANDOM;
756     }
757   }
758   /* privacy 1.1, or privacy 1.2, general discoverable/connectable mode, disable
759      privacy in */
760   /* controller fall back to host based privacy */
761   else if (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE) {
762     *p_own_addr_type = BLE_ADDR_RANDOM;
763   }
764 #endif
765 
766   /* if no privacy,do not set any peer address,*/
767   /* local address type go by global privacy setting */
768   return evt_type;
769 }
770 
771 /**
772  * This function is called to set scan parameters. |cb| is called with operation
773  * status
774  **/
BTM_BleSetScanParams(uint32_t scan_interval,uint32_t scan_window,tBLE_SCAN_MODE scan_mode,base::Callback<void (uint8_t)> cb)775 void BTM_BleSetScanParams(uint32_t scan_interval, uint32_t scan_window,
776                           tBLE_SCAN_MODE scan_mode,
777                           base::Callback<void(uint8_t)> cb) {
778   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
779   uint32_t max_scan_interval;
780   uint32_t max_scan_window;
781 
782   BTM_TRACE_EVENT("%s", __func__);
783   if (!controller_get_interface()->supports_ble()) return;
784 
785   /* If not supporting extended scan support, use the older range for checking
786    */
787   if (btm_cb.cmn_ble_vsc_cb.extended_scan_support == 0) {
788     max_scan_interval = BTM_BLE_SCAN_INT_MAX;
789     max_scan_window = BTM_BLE_SCAN_WIN_MAX;
790   } else {
791     /* If supporting extended scan support, use the new extended range for
792      * checking */
793     max_scan_interval = BTM_BLE_EXT_SCAN_INT_MAX;
794     max_scan_window = BTM_BLE_EXT_SCAN_WIN_MAX;
795   }
796 
797   if (BTM_BLE_ISVALID_PARAM(scan_interval, BTM_BLE_SCAN_INT_MIN,
798                             max_scan_interval) &&
799       BTM_BLE_ISVALID_PARAM(scan_window, BTM_BLE_SCAN_WIN_MIN,
800                             max_scan_window) &&
801       (scan_mode == BTM_BLE_SCAN_MODE_ACTI ||
802        scan_mode == BTM_BLE_SCAN_MODE_PASS)) {
803     p_cb->scan_type = scan_mode;
804     p_cb->scan_interval = scan_interval;
805     p_cb->scan_window = scan_window;
806 
807     cb.Run(BTM_SUCCESS);
808   } else {
809     cb.Run(BTM_ILLEGAL_VALUE);
810 
811     BTM_TRACE_ERROR("Illegal params: scan_interval = %d scan_window = %d",
812                     scan_interval, scan_window);
813   }
814 }
815 
816 /*******************************************************************************
817  *
818  * Function         BTM__BLEReadDiscoverability
819  *
820  * Description      This function is called to read the current LE
821  *                  discoverability mode of the device.
822  *
823  * Returns          BTM_BLE_NON_DISCOVERABLE ,BTM_BLE_LIMITED_DISCOVERABLE or
824  *                     BTM_BLE_GENRAL_DISCOVERABLE
825  *
826  ******************************************************************************/
BTM_BleReadDiscoverability()827 uint16_t BTM_BleReadDiscoverability() {
828   BTM_TRACE_API("%s", __func__);
829 
830   return (btm_cb.ble_ctr_cb.inq_var.discoverable_mode);
831 }
832 
833 /*******************************************************************************
834  *
835  * Function         BTM__BLEReadConnectability
836  *
837  * Description      This function is called to read the current LE
838  *                  connectability mode of the device.
839  *
840  * Returns          BTM_BLE_NON_CONNECTABLE or BTM_BLE_CONNECTABLE
841  *
842  ******************************************************************************/
BTM_BleReadConnectability()843 uint16_t BTM_BleReadConnectability() {
844   BTM_TRACE_API("%s", __func__);
845 
846   return (btm_cb.ble_ctr_cb.inq_var.connectable_mode);
847 }
848 
849 /*******************************************************************************
850  *
851  * Function         btm_ble_select_adv_interval
852  *
853  * Description      select adv interval based on device mode
854  *
855  * Returns          void
856  *
857  ******************************************************************************/
btm_ble_select_adv_interval(tBTM_BLE_INQ_CB * p_cb,uint8_t evt_type,uint16_t * p_adv_int_min,uint16_t * p_adv_int_max)858 void btm_ble_select_adv_interval(tBTM_BLE_INQ_CB* p_cb, uint8_t evt_type,
859                                  uint16_t* p_adv_int_min,
860                                  uint16_t* p_adv_int_max) {
861   if (p_cb->adv_interval_min && p_cb->adv_interval_max) {
862     *p_adv_int_min = p_cb->adv_interval_min;
863     *p_adv_int_max = p_cb->adv_interval_max;
864   } else {
865     switch (evt_type) {
866       case BTM_BLE_CONNECT_EVT:
867       case BTM_BLE_CONNECT_LO_DUTY_DIR_EVT:
868         *p_adv_int_min = *p_adv_int_max = BTM_BLE_GAP_ADV_FAST_INT_1;
869         break;
870 
871       case BTM_BLE_NON_CONNECT_EVT:
872       case BTM_BLE_DISCOVER_EVT:
873         *p_adv_int_min = *p_adv_int_max = BTM_BLE_GAP_ADV_FAST_INT_2;
874         break;
875 
876       /* connectable directed event */
877       case BTM_BLE_CONNECT_DIR_EVT:
878         *p_adv_int_min = BTM_BLE_GAP_ADV_DIR_MIN_INT;
879         *p_adv_int_max = BTM_BLE_GAP_ADV_DIR_MAX_INT;
880         break;
881 
882       default:
883         *p_adv_int_min = *p_adv_int_max = BTM_BLE_GAP_ADV_SLOW_INT;
884         break;
885     }
886   }
887   return;
888 }
889 
890 /*******************************************************************************
891  *
892  * Function         btm_ble_update_dmt_flag_bits
893  *
894  * Description      Obtain updated adv flag value based on connect and
895  *                  discoverability mode. Also, setup DMT support value in the
896  *                  flag based on whether the controller supports both LE and
897  *                  BR/EDR.
898  *
899  * Parameters:      flag_value (Input / Output) - flag value
900  *                  connect_mode (Input) - Connect mode value
901  *                  disc_mode (Input) - discoverability mode
902  *
903  * Returns          void
904  *
905  ******************************************************************************/
btm_ble_update_dmt_flag_bits(uint8_t * adv_flag_value,const uint16_t connect_mode,const uint16_t disc_mode)906 void btm_ble_update_dmt_flag_bits(uint8_t* adv_flag_value,
907                                   const uint16_t connect_mode,
908                                   const uint16_t disc_mode) {
909   /* BR/EDR non-discoverable , non-connectable */
910   if ((disc_mode & BTM_DISCOVERABLE_MASK) == 0 &&
911       (connect_mode & BTM_CONNECTABLE_MASK) == 0)
912     *adv_flag_value |= BTM_BLE_BREDR_NOT_SPT;
913   else
914     *adv_flag_value &= ~BTM_BLE_BREDR_NOT_SPT;
915 
916   /* if local controller support, mark both controller and host support in flag
917    */
918   if (controller_get_interface()->supports_simultaneous_le_bredr())
919     *adv_flag_value |= (BTM_BLE_DMT_CONTROLLER_SPT | BTM_BLE_DMT_HOST_SPT);
920   else
921     *adv_flag_value &= ~(BTM_BLE_DMT_CONTROLLER_SPT | BTM_BLE_DMT_HOST_SPT);
922 }
923 
924 /*******************************************************************************
925  *
926  * Function         btm_ble_set_adv_flag
927  *
928  * Description      Set adv flag in adv data.
929  *
930  * Parameters:      connect_mode (Input)- Connect mode value
931  *                  disc_mode (Input) - discoverability mode
932  *
933  * Returns          void
934  *
935  ******************************************************************************/
btm_ble_set_adv_flag(uint16_t connect_mode,uint16_t disc_mode)936 void btm_ble_set_adv_flag(uint16_t connect_mode, uint16_t disc_mode) {
937   uint8_t flag = 0, old_flag = 0;
938   tBTM_BLE_LOCAL_ADV_DATA* p_adv_data = &btm_cb.ble_ctr_cb.inq_var.adv_data;
939 
940   if (p_adv_data->p_flags != NULL) flag = old_flag = *(p_adv_data->p_flags);
941 
942   btm_ble_update_dmt_flag_bits(&flag, connect_mode, disc_mode);
943 
944   LOG_DEBUG("disc_mode %04x", disc_mode);
945   /* update discoverable flag */
946   if (disc_mode & BTM_BLE_LIMITED_DISCOVERABLE) {
947     flag &= ~BTM_BLE_GEN_DISC_FLAG;
948     flag |= BTM_BLE_LIMIT_DISC_FLAG;
949   } else if (disc_mode & BTM_BLE_GENERAL_DISCOVERABLE) {
950     flag |= BTM_BLE_GEN_DISC_FLAG;
951     flag &= ~BTM_BLE_LIMIT_DISC_FLAG;
952   } else /* remove all discoverable flags */
953   {
954     flag &= ~(BTM_BLE_LIMIT_DISC_FLAG | BTM_BLE_GEN_DISC_FLAG);
955   }
956 
957   if (flag != old_flag) {
958     btm_ble_update_adv_flag(flag);
959   }
960 }
961 /*******************************************************************************
962  *
963  * Function         btm_ble_set_discoverability
964  *
965  * Description      This function is called to set BLE discoverable mode.
966  *
967  * Parameters:      combined_mode: discoverability mode.
968  *
969  * Returns          BTM_SUCCESS is status set successfully; otherwise failure.
970  *
971  ******************************************************************************/
btm_ble_set_discoverability(uint16_t combined_mode)972 tBTM_STATUS btm_ble_set_discoverability(uint16_t combined_mode) {
973   tBTM_LE_RANDOM_CB* p_addr_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
974   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
975   uint16_t mode = (combined_mode & BTM_BLE_DISCOVERABLE_MASK);
976   uint8_t new_mode = BTM_BLE_ADV_ENABLE;
977   uint8_t evt_type;
978   tBTM_STATUS status = BTM_SUCCESS;
979   RawAddress address = RawAddress::kEmpty;
980   tBLE_ADDR_TYPE init_addr_type = BLE_ADDR_PUBLIC,
981                  own_addr_type = p_addr_cb->own_addr_type;
982   uint16_t adv_int_min, adv_int_max;
983 
984   BTM_TRACE_EVENT("%s mode=0x%0x combined_mode=0x%x", __func__, mode,
985                   combined_mode);
986 
987   /*** Check mode parameter ***/
988   if (mode > BTM_BLE_MAX_DISCOVERABLE) return (BTM_ILLEGAL_VALUE);
989 
990   p_cb->discoverable_mode = mode;
991 
992   evt_type = btm_set_conn_mode_adv_init_addr(p_cb, address, &init_addr_type,
993                                              &own_addr_type);
994 
995   if (p_cb->connectable_mode == BTM_BLE_NON_CONNECTABLE &&
996       mode == BTM_BLE_NON_DISCOVERABLE)
997     new_mode = BTM_BLE_ADV_DISABLE;
998 
999   btm_ble_select_adv_interval(p_cb, evt_type, &adv_int_min, &adv_int_max);
1000 
1001   alarm_cancel(p_cb->fast_adv_timer);
1002 
1003   /* update adv params if start advertising */
1004   BTM_TRACE_EVENT("evt_type=0x%x p-cb->evt_type=0x%x ", evt_type,
1005                   p_cb->evt_type);
1006 
1007   if (new_mode == BTM_BLE_ADV_ENABLE) {
1008     btm_ble_set_adv_flag(btm_cb.btm_inq_vars.connectable_mode, combined_mode);
1009 
1010     if (evt_type != p_cb->evt_type || p_cb->adv_addr_type != own_addr_type ||
1011         !p_cb->fast_adv_on) {
1012       btm_ble_stop_adv();
1013 
1014       /* update adv params */
1015       btsnd_hcic_ble_write_adv_params(adv_int_min, adv_int_max, evt_type,
1016                                       own_addr_type, init_addr_type, address,
1017                                       p_cb->adv_chnl_map, p_cb->afp);
1018       p_cb->evt_type = evt_type;
1019       p_cb->adv_addr_type = own_addr_type;
1020     }
1021   }
1022 
1023   if (status == BTM_SUCCESS && p_cb->adv_mode != new_mode) {
1024     if (new_mode == BTM_BLE_ADV_ENABLE)
1025       status = btm_ble_start_adv();
1026     else
1027       status = btm_ble_stop_adv();
1028   }
1029 
1030   if (p_cb->adv_mode == BTM_BLE_ADV_ENABLE) {
1031     p_cb->fast_adv_on = true;
1032     /* start initial GAP mode adv timer */
1033     alarm_set_on_mloop(p_cb->fast_adv_timer, BTM_BLE_GAP_FAST_ADV_TIMEOUT_MS,
1034                        btm_ble_fast_adv_timer_timeout, NULL);
1035   } else {
1036 #if (BLE_PRIVACY_SPT == TRUE)
1037     btm_ble_disable_resolving_list(BTM_BLE_RL_ADV, true);
1038 #endif
1039   }
1040 
1041   /* set up stop advertising timer */
1042   if (status == BTM_SUCCESS && mode == BTM_BLE_LIMITED_DISCOVERABLE) {
1043     BTM_TRACE_EVENT("start timer for limited disc mode duration=%d ms",
1044                     BTM_BLE_GAP_LIM_TIMEOUT_MS);
1045     /* start Tgap(lim_timeout) */
1046     alarm_set_on_mloop(p_cb->inquiry_timer, BTM_BLE_GAP_LIM_TIMEOUT_MS,
1047                        btm_ble_inquiry_timer_gap_limited_discovery_timeout,
1048                        NULL);
1049   }
1050   return status;
1051 }
1052 
1053 /*******************************************************************************
1054  *
1055  * Function         btm_ble_set_connectability
1056  *
1057  * Description      This function is called to set BLE connectability mode.
1058  *
1059  * Parameters:      combined_mode: connectability mode.
1060  *
1061  * Returns          BTM_SUCCESS is status set successfully; otherwise failure.
1062  *
1063  ******************************************************************************/
btm_ble_set_connectability(uint16_t combined_mode)1064 tBTM_STATUS btm_ble_set_connectability(uint16_t combined_mode) {
1065   tBTM_LE_RANDOM_CB* p_addr_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
1066   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
1067   uint16_t mode = (combined_mode & BTM_BLE_CONNECTABLE_MASK);
1068   uint8_t new_mode = BTM_BLE_ADV_ENABLE;
1069   uint8_t evt_type;
1070   tBTM_STATUS status = BTM_SUCCESS;
1071   RawAddress address = RawAddress::kEmpty;
1072   tBLE_ADDR_TYPE peer_addr_type = BLE_ADDR_PUBLIC,
1073                  own_addr_type = p_addr_cb->own_addr_type;
1074   uint16_t adv_int_min, adv_int_max;
1075 
1076   BTM_TRACE_EVENT("%s mode=0x%0x combined_mode=0x%x", __func__, mode,
1077                   combined_mode);
1078 
1079   /*** Check mode parameter ***/
1080   if (mode > BTM_BLE_MAX_CONNECTABLE) return (BTM_ILLEGAL_VALUE);
1081 
1082   p_cb->connectable_mode = mode;
1083 
1084   evt_type = btm_set_conn_mode_adv_init_addr(p_cb, address, &peer_addr_type,
1085                                              &own_addr_type);
1086 
1087   if (mode == BTM_BLE_NON_CONNECTABLE &&
1088       p_cb->discoverable_mode == BTM_BLE_NON_DISCOVERABLE)
1089     new_mode = BTM_BLE_ADV_DISABLE;
1090 
1091   btm_ble_select_adv_interval(p_cb, evt_type, &adv_int_min, &adv_int_max);
1092 
1093   alarm_cancel(p_cb->fast_adv_timer);
1094   /* update adv params if needed */
1095   if (new_mode == BTM_BLE_ADV_ENABLE) {
1096     btm_ble_set_adv_flag(combined_mode, btm_cb.btm_inq_vars.discoverable_mode);
1097     if (p_cb->evt_type != evt_type ||
1098         p_cb->adv_addr_type != p_addr_cb->own_addr_type || !p_cb->fast_adv_on) {
1099       btm_ble_stop_adv();
1100 
1101       btsnd_hcic_ble_write_adv_params(adv_int_min, adv_int_max, evt_type,
1102                                       own_addr_type, peer_addr_type, address,
1103                                       p_cb->adv_chnl_map, p_cb->afp);
1104       p_cb->evt_type = evt_type;
1105       p_cb->adv_addr_type = own_addr_type;
1106     }
1107   }
1108 
1109   /* update advertising mode */
1110   if (status == BTM_SUCCESS && new_mode != p_cb->adv_mode) {
1111     if (new_mode == BTM_BLE_ADV_ENABLE)
1112       status = btm_ble_start_adv();
1113     else
1114       status = btm_ble_stop_adv();
1115   }
1116 
1117   if (p_cb->adv_mode == BTM_BLE_ADV_ENABLE) {
1118     p_cb->fast_adv_on = true;
1119     /* start initial GAP mode adv timer */
1120     alarm_set_on_mloop(p_cb->fast_adv_timer, BTM_BLE_GAP_FAST_ADV_TIMEOUT_MS,
1121                        btm_ble_fast_adv_timer_timeout, NULL);
1122   } else {
1123 #if (BLE_PRIVACY_SPT == TRUE)
1124     btm_ble_disable_resolving_list(BTM_BLE_RL_ADV, true);
1125 #endif
1126   }
1127   return status;
1128 }
1129 
btm_send_hci_scan_enable(uint8_t enable,uint8_t filter_duplicates)1130 void btm_send_hci_scan_enable(uint8_t enable, uint8_t filter_duplicates) {
1131   if (controller_get_interface()->supports_ble_extended_advertising()) {
1132     btsnd_hcic_ble_set_extended_scan_enable(enable, filter_duplicates, 0x0000,
1133                                             0x0000);
1134   } else {
1135     btsnd_hcic_ble_set_scan_enable(enable, filter_duplicates);
1136   }
1137 }
1138 
btm_send_hci_set_scan_params(uint8_t scan_type,uint16_t scan_int,uint16_t scan_win,uint8_t addr_type_own,uint8_t scan_filter_policy)1139 void btm_send_hci_set_scan_params(uint8_t scan_type, uint16_t scan_int,
1140                                   uint16_t scan_win, uint8_t addr_type_own,
1141                                   uint8_t scan_filter_policy) {
1142   if (controller_get_interface()->supports_ble_extended_advertising()) {
1143     scanning_phy_cfg phy_cfg;
1144     phy_cfg.scan_type = scan_type;
1145     phy_cfg.scan_int = scan_int;
1146     phy_cfg.scan_win = scan_win;
1147 
1148     btsnd_hcic_ble_set_extended_scan_params(addr_type_own, scan_filter_policy,
1149                                             1, &phy_cfg);
1150   } else {
1151     btsnd_hcic_ble_set_scan_params(scan_type, scan_int, scan_win, addr_type_own,
1152                                    scan_filter_policy);
1153   }
1154 }
1155 
1156 /*******************************************************************************
1157  *
1158  * Function         btm_ble_start_inquiry
1159  *
1160  * Description      This function is called to start BLE inquiry procedure.
1161  *                  If the duration is zero, the periodic inquiry mode is
1162  *                  cancelled.
1163  *
1164  * Parameters:      mode - GENERAL or LIMITED inquiry
1165  *                  p_inq_params - pointer to the BLE inquiry parameter.
1166  *                  p_results_cb - callback returning pointer to results
1167  *                                 (tBTM_INQ_RESULTS)
1168  *                  p_cmpl_cb - callback indicating the end of an inquiry
1169  *
1170  *
1171  *
1172  * Returns          BTM_CMD_STARTED if successfully started
1173  *                  BTM_NO_RESOURCES if could not allocate a message buffer
1174  *                  BTM_BUSY - if an inquiry is already active
1175  *
1176  ******************************************************************************/
btm_ble_start_inquiry(uint8_t mode,uint8_t duration)1177 tBTM_STATUS btm_ble_start_inquiry(uint8_t mode, uint8_t duration) {
1178   tBTM_STATUS status = BTM_CMD_STARTED;
1179   tBTM_BLE_CB* p_ble_cb = &btm_cb.ble_ctr_cb;
1180   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
1181 
1182   BTM_TRACE_DEBUG("btm_ble_start_inquiry: mode = %02x inq_active = 0x%02x",
1183                   mode, btm_cb.btm_inq_vars.inq_active);
1184 
1185   /* if selective connection is active, or inquiry is already active, reject it
1186    */
1187   if (BTM_BLE_IS_INQ_ACTIVE(p_ble_cb->scan_activity)) {
1188     BTM_TRACE_ERROR("LE Inquiry is active, can not start inquiry");
1189     return (BTM_BUSY);
1190   }
1191 
1192   if (!BTM_BLE_IS_SCAN_ACTIVE(p_ble_cb->scan_activity)) {
1193     cache.ClearAll();
1194     btm_send_hci_set_scan_params(
1195         BTM_BLE_SCAN_MODE_ACTI, BTM_BLE_LOW_LATENCY_SCAN_INT,
1196         BTM_BLE_LOW_LATENCY_SCAN_WIN,
1197         btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, SP_ADV_ALL);
1198 #if (BLE_PRIVACY_SPT == TRUE)
1199     /* enable IRK list */
1200     btm_ble_enable_resolving_list_for_platform(BTM_BLE_RL_SCAN);
1201 #endif
1202     p_ble_cb->inq_var.scan_type = BTM_BLE_SCAN_MODE_ACTI;
1203     p_ble_cb->inq_var.scan_duplicate_filter = BTM_BLE_DUPLICATE_DISABLE;
1204     status = btm_ble_start_scan();
1205   } else if ((p_ble_cb->inq_var.scan_interval !=
1206               BTM_BLE_LOW_LATENCY_SCAN_INT) ||
1207              (p_ble_cb->inq_var.scan_window != BTM_BLE_LOW_LATENCY_SCAN_WIN)) {
1208     BTM_TRACE_DEBUG("%s, restart LE scan with low latency scan params",
1209                     __func__);
1210     btm_send_hci_scan_enable(BTM_BLE_SCAN_DISABLE, BTM_BLE_DUPLICATE_ENABLE);
1211     btm_send_hci_set_scan_params(
1212         BTM_BLE_SCAN_MODE_ACTI, BTM_BLE_LOW_LATENCY_SCAN_INT,
1213         BTM_BLE_LOW_LATENCY_SCAN_WIN,
1214         btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, SP_ADV_ALL);
1215     btm_send_hci_scan_enable(BTM_BLE_SCAN_ENABLE, BTM_BLE_DUPLICATE_DISABLE);
1216   }
1217 
1218   if (status == BTM_CMD_STARTED) {
1219     p_inq->inq_active |= mode;
1220     p_ble_cb->scan_activity |= mode;
1221 
1222     BTM_TRACE_DEBUG("btm_ble_start_inquiry inq_active = 0x%02x",
1223                     p_inq->inq_active);
1224 
1225     if (duration != 0) {
1226       /* start inquiry timer */
1227       uint64_t duration_ms = duration * 1000;
1228       alarm_set_on_mloop(p_ble_cb->inq_var.inquiry_timer, duration_ms,
1229                          btm_ble_inquiry_timer_timeout, NULL);
1230     }
1231   }
1232 
1233   return status;
1234 }
1235 
1236 /*******************************************************************************
1237  *
1238  * Function         btm_ble_read_remote_name_cmpl
1239  *
1240  * Description      This function is called when BLE remote name is received.
1241  *
1242  * Returns          void
1243  *
1244  ******************************************************************************/
btm_ble_read_remote_name_cmpl(bool status,const RawAddress & bda,uint16_t length,char * p_name)1245 void btm_ble_read_remote_name_cmpl(bool status, const RawAddress& bda,
1246                                    uint16_t length, char* p_name) {
1247   uint8_t hci_status = HCI_SUCCESS;
1248   BD_NAME bd_name;
1249 
1250   memset(bd_name, 0, (BD_NAME_LEN + 1));
1251   if (length > BD_NAME_LEN) {
1252     length = BD_NAME_LEN;
1253   }
1254   memcpy((uint8_t*)bd_name, p_name, length);
1255 
1256   if ((!status) || (length == 0)) {
1257     hci_status = HCI_ERR_HOST_TIMEOUT;
1258   }
1259 
1260   btm_process_remote_name(&bda, bd_name, length + 1, hci_status);
1261   btm_sec_rmt_name_request_complete(&bda, (uint8_t*)p_name, hci_status);
1262 }
1263 
1264 /*******************************************************************************
1265  *
1266  * Function         btm_ble_read_remote_name
1267  *
1268  * Description      This function read remote LE device name using GATT read
1269  *                  procedure.
1270  *
1271  * Parameters:       None.
1272  *
1273  * Returns          void
1274  *
1275  ******************************************************************************/
btm_ble_read_remote_name(const RawAddress & remote_bda,tBTM_CMPL_CB * p_cb)1276 tBTM_STATUS btm_ble_read_remote_name(const RawAddress& remote_bda,
1277                                      tBTM_CMPL_CB* p_cb) {
1278   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
1279 
1280   if (!controller_get_interface()->supports_ble()) return BTM_ERR_PROCESSING;
1281 
1282   tINQ_DB_ENT* p_i = btm_inq_db_find(remote_bda);
1283   if (p_i && !ble_evt_type_is_connectable(p_i->inq_info.results.ble_evt_type)) {
1284     BTM_TRACE_DEBUG("name request to non-connectable device failed.");
1285     return BTM_ERR_PROCESSING;
1286   }
1287 
1288   /* read remote device name using GATT procedure */
1289   if (p_inq->remname_active) return BTM_BUSY;
1290 
1291   if (!GAP_BleReadPeerDevName(remote_bda, btm_ble_read_remote_name_cmpl))
1292     return BTM_BUSY;
1293 
1294   p_inq->p_remname_cmpl_cb = p_cb;
1295   p_inq->remname_active = true;
1296   p_inq->remname_bda = remote_bda;
1297 
1298   alarm_set_on_mloop(p_inq->remote_name_timer, BTM_EXT_BLE_RMT_NAME_TIMEOUT_MS,
1299                      btm_inq_remote_name_timer_timeout, NULL);
1300 
1301   return BTM_CMD_STARTED;
1302 }
1303 
1304 /*******************************************************************************
1305  *
1306  * Function         btm_ble_cancel_remote_name
1307  *
1308  * Description      This function cancel read remote LE device name.
1309  *
1310  * Parameters:       None.
1311  *
1312  * Returns          void
1313  *
1314  ******************************************************************************/
btm_ble_cancel_remote_name(const RawAddress & remote_bda)1315 bool btm_ble_cancel_remote_name(const RawAddress& remote_bda) {
1316   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
1317   bool status;
1318 
1319   status = GAP_BleCancelReadPeerDevName(remote_bda);
1320 
1321   p_inq->remname_active = false;
1322   p_inq->remname_bda = RawAddress::kEmpty;
1323   alarm_cancel(p_inq->remote_name_timer);
1324 
1325   return status;
1326 }
1327 
1328 /*******************************************************************************
1329  *
1330  * Function         btm_ble_update_adv_flag
1331  *
1332  * Description      This function update the limited discoverable flag in the
1333  *                  adv data.
1334  *
1335  * Parameters:       None.
1336  *
1337  * Returns          void
1338  *
1339  ******************************************************************************/
btm_ble_update_adv_flag(uint8_t flag)1340 static void btm_ble_update_adv_flag(uint8_t flag) {
1341   tBTM_BLE_LOCAL_ADV_DATA* p_adv_data = &btm_cb.ble_ctr_cb.inq_var.adv_data;
1342   uint8_t* p;
1343 
1344   BTM_TRACE_DEBUG("btm_ble_update_adv_flag new=0x%x", flag);
1345 
1346   if (p_adv_data->p_flags != NULL) {
1347     BTM_TRACE_DEBUG("btm_ble_update_adv_flag old=0x%x", *p_adv_data->p_flags);
1348     *p_adv_data->p_flags = flag;
1349   } else /* no FLAGS in ADV data*/
1350   {
1351     p = (p_adv_data->p_pad == NULL) ? p_adv_data->ad_data : p_adv_data->p_pad;
1352     /* need 3 bytes space to stuff in the flags, if not */
1353     /* erase all written data, just for flags */
1354     if ((BTM_BLE_AD_DATA_LEN - (p - p_adv_data->ad_data)) < 3) {
1355       p = p_adv_data->p_pad = p_adv_data->ad_data;
1356       memset(p_adv_data->ad_data, 0, BTM_BLE_AD_DATA_LEN);
1357     }
1358 
1359     *p++ = 2;
1360     *p++ = BTM_BLE_AD_TYPE_FLAG;
1361     p_adv_data->p_flags = p;
1362     *p++ = flag;
1363     p_adv_data->p_pad = p;
1364   }
1365 
1366   btsnd_hcic_ble_set_adv_data(
1367       (uint8_t)(p_adv_data->p_pad - p_adv_data->ad_data), p_adv_data->ad_data);
1368   p_adv_data->data_mask |= BTM_BLE_AD_BIT_FLAGS;
1369 }
1370 
1371 /**
1372  * Check ADV flag to make sure device is discoverable and match the search
1373  * condition
1374  */
btm_ble_is_discoverable(const RawAddress & bda,std::vector<uint8_t> const & adv_data)1375 uint8_t btm_ble_is_discoverable(const RawAddress& bda,
1376                                 std::vector<uint8_t> const& adv_data) {
1377   uint8_t flag = 0, rt = 0;
1378   uint8_t data_len;
1379   tBTM_INQ_PARMS* p_cond = &btm_cb.btm_inq_vars.inqparms;
1380 
1381   /* for observer, always "discoverable */
1382   if (BTM_BLE_IS_OBS_ACTIVE(btm_cb.ble_ctr_cb.scan_activity))
1383     rt |= BTM_BLE_OBS_RESULT;
1384 
1385   /* does not match filter condition */
1386   if (p_cond->filter_cond_type == BTM_FILTER_COND_BD_ADDR &&
1387       bda != p_cond->filter_cond.bdaddr_cond) {
1388     BTM_TRACE_DEBUG("BD ADDR does not meet filter condition");
1389     return rt;
1390   }
1391 
1392   if (!adv_data.empty()) {
1393     const uint8_t* p_flag = AdvertiseDataParser::GetFieldByType(
1394         adv_data, BTM_BLE_AD_TYPE_FLAG, &data_len);
1395     if (p_flag != NULL && data_len != 0) {
1396       flag = *p_flag;
1397 
1398       if ((btm_cb.btm_inq_vars.inq_active & BTM_BLE_GENERAL_INQUIRY) &&
1399           (flag & (BTM_BLE_LIMIT_DISC_FLAG | BTM_BLE_GEN_DISC_FLAG)) != 0) {
1400         BTM_TRACE_DEBUG("Find Generable Discoverable device");
1401         rt |= BTM_BLE_INQ_RESULT;
1402       }
1403 
1404       else if (btm_cb.btm_inq_vars.inq_active & BTM_BLE_LIMITED_INQUIRY &&
1405                (flag & BTM_BLE_LIMIT_DISC_FLAG) != 0) {
1406         BTM_TRACE_DEBUG("Find limited discoverable device");
1407         rt |= BTM_BLE_INQ_RESULT;
1408       }
1409     }
1410   }
1411   return rt;
1412 }
1413 
btm_ble_appearance_to_cod(uint16_t appearance,uint8_t * dev_class)1414 static void btm_ble_appearance_to_cod(uint16_t appearance, uint8_t* dev_class) {
1415   dev_class[0] = 0;
1416 
1417   switch (appearance) {
1418     case BTM_BLE_APPEARANCE_GENERIC_PHONE:
1419       dev_class[1] = BTM_COD_MAJOR_PHONE;
1420       dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
1421       break;
1422     case BTM_BLE_APPEARANCE_GENERIC_COMPUTER:
1423       dev_class[1] = BTM_COD_MAJOR_COMPUTER;
1424       dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
1425       break;
1426     case BTM_BLE_APPEARANCE_GENERIC_REMOTE:
1427       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1428       dev_class[2] = BTM_COD_MINOR_REMOTE_CONTROL;
1429       break;
1430     case BTM_BLE_APPEARANCE_GENERIC_THERMOMETER:
1431     case BTM_BLE_APPEARANCE_THERMOMETER_EAR:
1432       dev_class[1] = BTM_COD_MAJOR_HEALTH;
1433       dev_class[2] = BTM_COD_MINOR_THERMOMETER;
1434       break;
1435     case BTM_BLE_APPEARANCE_GENERIC_HEART_RATE:
1436     case BTM_BLE_APPEARANCE_HEART_RATE_BELT:
1437       dev_class[1] = BTM_COD_MAJOR_HEALTH;
1438       dev_class[2] = BTM_COD_MINOR_HEART_PULSE_MONITOR;
1439       break;
1440     case BTM_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE:
1441     case BTM_BLE_APPEARANCE_BLOOD_PRESSURE_ARM:
1442     case BTM_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST:
1443       dev_class[1] = BTM_COD_MAJOR_HEALTH;
1444       dev_class[2] = BTM_COD_MINOR_BLOOD_MONITOR;
1445       break;
1446     case BTM_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER:
1447     case BTM_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP:
1448     case BTM_BLE_APPEARANCE_PULSE_OXIMETER_WRIST:
1449       dev_class[1] = BTM_COD_MAJOR_HEALTH;
1450       dev_class[2] = BTM_COD_MINOR_PULSE_OXIMETER;
1451       break;
1452     case BTM_BLE_APPEARANCE_GENERIC_GLUCOSE:
1453       dev_class[1] = BTM_COD_MAJOR_HEALTH;
1454       dev_class[2] = BTM_COD_MINOR_GLUCOSE_METER;
1455       break;
1456     case BTM_BLE_APPEARANCE_GENERIC_WEIGHT:
1457       dev_class[1] = BTM_COD_MAJOR_HEALTH;
1458       dev_class[2] = BTM_COD_MINOR_WEIGHING_SCALE;
1459       break;
1460     case BTM_BLE_APPEARANCE_GENERIC_WALKING:
1461     case BTM_BLE_APPEARANCE_WALKING_IN_SHOE:
1462     case BTM_BLE_APPEARANCE_WALKING_ON_SHOE:
1463     case BTM_BLE_APPEARANCE_WALKING_ON_HIP:
1464       dev_class[1] = BTM_COD_MAJOR_HEALTH;
1465       dev_class[2] = BTM_COD_MINOR_STEP_COUNTER;
1466       break;
1467     case BTM_BLE_APPEARANCE_GENERIC_WATCH:
1468     case BTM_BLE_APPEARANCE_SPORTS_WATCH:
1469       dev_class[1] = BTM_COD_MAJOR_WEARABLE;
1470       dev_class[2] = BTM_COD_MINOR_WRIST_WATCH;
1471       break;
1472     case BTM_BLE_APPEARANCE_GENERIC_EYEGLASSES:
1473       dev_class[1] = BTM_COD_MAJOR_WEARABLE;
1474       dev_class[2] = BTM_COD_MINOR_GLASSES;
1475       break;
1476     case BTM_BLE_APPEARANCE_GENERIC_DISPLAY:
1477       dev_class[1] = BTM_COD_MAJOR_IMAGING;
1478       dev_class[2] = BTM_COD_MINOR_DISPLAY;
1479       break;
1480     case BTM_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER:
1481       dev_class[1] = BTM_COD_MAJOR_AUDIO;
1482       dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
1483       break;
1484     case BTM_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER:
1485     case BTM_BLE_APPEARANCE_HID_BARCODE_SCANNER:
1486     case BTM_BLE_APPEARANCE_GENERIC_HID:
1487       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1488       dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
1489       break;
1490     case BTM_BLE_APPEARANCE_HID_KEYBOARD:
1491       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1492       dev_class[2] = BTM_COD_MINOR_KEYBOARD;
1493       break;
1494     case BTM_BLE_APPEARANCE_HID_MOUSE:
1495       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1496       dev_class[2] = BTM_COD_MINOR_POINTING;
1497       break;
1498     case BTM_BLE_APPEARANCE_HID_JOYSTICK:
1499       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1500       dev_class[2] = BTM_COD_MINOR_JOYSTICK;
1501       break;
1502     case BTM_BLE_APPEARANCE_HID_GAMEPAD:
1503       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1504       dev_class[2] = BTM_COD_MINOR_GAMEPAD;
1505       break;
1506     case BTM_BLE_APPEARANCE_HID_DIGITIZER_TABLET:
1507       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1508       dev_class[2] = BTM_COD_MINOR_DIGITIZING_TABLET;
1509       break;
1510     case BTM_BLE_APPEARANCE_HID_CARD_READER:
1511       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1512       dev_class[2] = BTM_COD_MINOR_CARD_READER;
1513       break;
1514     case BTM_BLE_APPEARANCE_HID_DIGITAL_PEN:
1515       dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1516       dev_class[2] = BTM_COD_MINOR_DIGITAL_PAN;
1517       break;
1518     case BTM_BLE_APPEARANCE_UKNOWN:
1519     case BTM_BLE_APPEARANCE_GENERIC_CLOCK:
1520     case BTM_BLE_APPEARANCE_GENERIC_TAG:
1521     case BTM_BLE_APPEARANCE_GENERIC_KEYRING:
1522     case BTM_BLE_APPEARANCE_GENERIC_CYCLING:
1523     case BTM_BLE_APPEARANCE_CYCLING_COMPUTER:
1524     case BTM_BLE_APPEARANCE_CYCLING_SPEED:
1525     case BTM_BLE_APPEARANCE_CYCLING_CADENCE:
1526     case BTM_BLE_APPEARANCE_CYCLING_POWER:
1527     case BTM_BLE_APPEARANCE_CYCLING_SPEED_CADENCE:
1528     case BTM_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS:
1529     case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION:
1530     case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV:
1531     case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD:
1532     case BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV:
1533     default:
1534       dev_class[1] = BTM_COD_MAJOR_UNCLASSIFIED;
1535       dev_class[2] = BTM_COD_MINOR_UNCLASSIFIED;
1536   };
1537 }
1538 
1539 /**
1540  * Update adv packet information into inquiry result.
1541  */
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)1542 void btm_ble_update_inq_result(tINQ_DB_ENT* p_i, uint8_t addr_type,
1543                                const RawAddress& bda, uint16_t evt_type,
1544                                uint8_t primary_phy, uint8_t secondary_phy,
1545                                uint8_t advertising_sid, int8_t tx_power,
1546                                int8_t rssi, uint16_t periodic_adv_int,
1547                                std::vector<uint8_t> const& data) {
1548   tBTM_INQ_RESULTS* p_cur = &p_i->inq_info.results;
1549   uint8_t len;
1550   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
1551 
1552   /* Save the info */
1553   p_cur->inq_result_type |= BTM_INQ_RESULT_BLE;
1554   p_cur->ble_addr_type = addr_type;
1555   p_cur->rssi = rssi;
1556   p_cur->ble_primary_phy = primary_phy;
1557   p_cur->ble_secondary_phy = secondary_phy;
1558   p_cur->ble_advertising_sid = advertising_sid;
1559   p_cur->ble_tx_power = tx_power;
1560   p_cur->ble_periodic_adv_int = periodic_adv_int;
1561 
1562   if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI &&
1563       ble_evt_type_is_scannable(evt_type) &&
1564       !ble_evt_type_is_scan_resp(evt_type)) {
1565     p_i->scan_rsp = false;
1566   } else
1567     p_i->scan_rsp = true;
1568 
1569   if (p_i->inq_count != p_inq->inq_counter)
1570     p_cur->device_type = BT_DEVICE_TYPE_BLE;
1571   else
1572     p_cur->device_type |= BT_DEVICE_TYPE_BLE;
1573 
1574   if (evt_type != BTM_BLE_SCAN_RSP_EVT) p_cur->ble_evt_type = evt_type;
1575 
1576   p_i->inq_count = p_inq->inq_counter; /* Mark entry for current inquiry */
1577 
1578   if (!data.empty()) {
1579     const uint8_t* p_flag =
1580         AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_FLAG, &len);
1581     if (p_flag != NULL && len != 0) p_cur->flag = *p_flag;
1582   }
1583 
1584   if (!data.empty()) {
1585     /* Check to see the BLE device has the Appearance UUID in the advertising
1586      * data.  If it does
1587      * then try to convert the appearance value to a class of device value
1588      * Bluedroid can use.
1589      * Otherwise fall back to trying to infer if it is a HID device based on the
1590      * service class.
1591      */
1592     const uint8_t* p_uuid16 = AdvertiseDataParser::GetFieldByType(
1593         data, BTM_BLE_AD_TYPE_APPEARANCE, &len);
1594     if (p_uuid16 && len == 2) {
1595       btm_ble_appearance_to_cod((uint16_t)p_uuid16[0] | (p_uuid16[1] << 8),
1596                                 p_cur->dev_class);
1597     } else {
1598       p_uuid16 = AdvertiseDataParser::GetFieldByType(
1599           data, BTM_BLE_AD_TYPE_16SRV_CMPL, &len);
1600       if (p_uuid16 != NULL) {
1601         uint8_t i;
1602         for (i = 0; i + 2 <= len; i = i + 2) {
1603           /* if this BLE device support HID over LE, set HID Major in class of
1604            * device */
1605           if ((p_uuid16[i] | (p_uuid16[i + 1] << 8)) == UUID_SERVCLASS_LE_HID) {
1606             p_cur->dev_class[0] = 0;
1607             p_cur->dev_class[1] = BTM_COD_MAJOR_PERIPHERAL;
1608             p_cur->dev_class[2] = 0;
1609             break;
1610           }
1611         }
1612       }
1613     }
1614   }
1615 
1616   /* if BR/EDR not supported is not set, assume is a DUMO device */
1617   if ((p_cur->flag & BTM_BLE_BREDR_NOT_SPT) == 0 &&
1618       !ble_evt_type_is_directed(evt_type)) {
1619     if (p_cur->ble_addr_type != BLE_ADDR_RANDOM) {
1620       BTM_TRACE_DEBUG("BR/EDR NOT support bit not set, treat as DUMO");
1621       p_cur->device_type |= BT_DEVICE_TYPE_DUMO;
1622     } else {
1623       BTM_TRACE_DEBUG("Random address, treating device as LE only");
1624     }
1625   } else {
1626     BTM_TRACE_DEBUG("BR/EDR NOT SUPPORT bit set, LE only device");
1627   }
1628 }
1629 
1630 /*******************************************************************************
1631  *
1632  * Function         btm_clear_all_pending_le_entry
1633  *
1634  * Description      This function is called to clear all LE pending entry in
1635  *                  inquiry database.
1636  *
1637  * Returns          void
1638  *
1639  ******************************************************************************/
btm_clear_all_pending_le_entry(void)1640 void btm_clear_all_pending_le_entry(void) {
1641   uint16_t xx;
1642   tINQ_DB_ENT* p_ent = btm_cb.btm_inq_vars.inq_db;
1643 
1644   for (xx = 0; xx < BTM_INQ_DB_SIZE; xx++, p_ent++) {
1645     /* mark all pending LE entry as unused if an LE only device has scan
1646      * response outstanding */
1647     if ((p_ent->in_use) &&
1648         (p_ent->inq_info.results.device_type == BT_DEVICE_TYPE_BLE) &&
1649         !p_ent->scan_rsp)
1650       p_ent->in_use = false;
1651   }
1652 }
1653 
btm_ble_process_adv_addr(RawAddress & bda,uint8_t * addr_type)1654 void btm_ble_process_adv_addr(RawAddress& bda, uint8_t* addr_type) {
1655 #if (BLE_PRIVACY_SPT == TRUE)
1656   /* map address to security record */
1657   bool match = btm_identity_addr_to_random_pseudo(&bda, addr_type, false);
1658 
1659   VLOG(1) << __func__ << ": bda=" << bda;
1660   /* always do RRA resolution on host */
1661   if (!match && BTM_BLE_IS_RESOLVE_BDA(bda)) {
1662     tBTM_SEC_DEV_REC* match_rec = btm_ble_resolve_random_addr(bda);
1663     if (match_rec) {
1664       match_rec->ble.active_addr_type = BTM_BLE_ADDR_RRA;
1665       match_rec->ble.cur_rand_addr = bda;
1666 
1667       if (btm_ble_init_pseudo_addr(match_rec, bda)) {
1668         bda = match_rec->bd_addr;
1669       } else {
1670         // Assign the original address to be the current report address
1671         bda = match_rec->ble.pseudo_addr;
1672         *addr_type = match_rec->ble.ble_addr_type;
1673       }
1674     }
1675   }
1676 #endif
1677 }
1678 
1679 /**
1680  * This function is called when extended advertising report event is received .
1681  * It updates the inquiry database. If the inquiry database is full, the oldest
1682  * entry is discarded.
1683  */
btm_ble_process_ext_adv_pkt(uint8_t data_len,uint8_t * data)1684 void btm_ble_process_ext_adv_pkt(uint8_t data_len, uint8_t* data) {
1685   RawAddress bda, direct_address;
1686   uint8_t* p = data;
1687   uint8_t addr_type, num_reports, pkt_data_len, primary_phy, secondary_phy,
1688       advertising_sid;
1689   int8_t rssi, tx_power;
1690   uint16_t event_type, periodic_adv_int, direct_address_type;
1691 
1692   /* Only process the results if the inquiry is still active */
1693   if (!BTM_BLE_IS_SCAN_ACTIVE(btm_cb.ble_ctr_cb.scan_activity)) return;
1694 
1695   /* Extract the number of reports in this event. */
1696   STREAM_TO_UINT8(num_reports, p);
1697 
1698   while (num_reports--) {
1699     if (p > data + data_len) {
1700       // TODO(jpawlowski): we should crash the stack here
1701       BTM_TRACE_ERROR(
1702           "Malformed LE Extended Advertising Report Event from controller - "
1703           "can't loop the data");
1704       return;
1705     }
1706 
1707     /* Extract inquiry results */
1708     STREAM_TO_UINT16(event_type, p);
1709     STREAM_TO_UINT8(addr_type, p);
1710     STREAM_TO_BDADDR(bda, p);
1711     STREAM_TO_UINT8(primary_phy, p);
1712     STREAM_TO_UINT8(secondary_phy, p);
1713     STREAM_TO_UINT8(advertising_sid, p);
1714     STREAM_TO_INT8(tx_power, p);
1715     STREAM_TO_INT8(rssi, p);
1716     STREAM_TO_UINT16(periodic_adv_int, p);
1717     STREAM_TO_UINT8(direct_address_type, p);
1718     STREAM_TO_BDADDR(direct_address, p);
1719     STREAM_TO_UINT8(pkt_data_len, p);
1720 
1721     uint8_t* pkt_data = p;
1722     p += pkt_data_len; /* Advance to the the next packet*/
1723     if (p > data + data_len) {
1724       LOG(ERROR) << "Invalid pkt_data_len: " << +pkt_data_len;
1725       return;
1726     }
1727 
1728     if (rssi >= 21 && rssi <= 126) {
1729       BTM_TRACE_ERROR("%s: bad rssi value in advertising report: %d", __func__,
1730                       rssi);
1731     }
1732 
1733     if (addr_type != BLE_ADDR_ANONYMOUS) {
1734       btm_ble_process_adv_addr(bda, &addr_type);
1735     }
1736 
1737     btm_ble_process_adv_pkt_cont(event_type, addr_type, bda, primary_phy,
1738                                  secondary_phy, advertising_sid, tx_power, rssi,
1739                                  periodic_adv_int, pkt_data_len, pkt_data);
1740   }
1741 }
1742 
1743 /**
1744  * This function is called when advertising report event is received. It updates
1745  * the inquiry database. If the inquiry database is full, the oldest entry is
1746  * discarded.
1747  */
btm_ble_process_adv_pkt(uint8_t data_len,uint8_t * data)1748 void btm_ble_process_adv_pkt(uint8_t data_len, uint8_t* data) {
1749   RawAddress bda;
1750   uint8_t* p = data;
1751   uint8_t legacy_evt_type, addr_type, num_reports, pkt_data_len;
1752   int8_t rssi;
1753 
1754   /* Only process the results if the inquiry is still active */
1755   if (!BTM_BLE_IS_SCAN_ACTIVE(btm_cb.ble_ctr_cb.scan_activity)) return;
1756 
1757   /* Extract the number of reports in this event. */
1758   STREAM_TO_UINT8(num_reports, p);
1759 
1760   while (num_reports--) {
1761     if (p > data + data_len) {
1762       // TODO(jpawlowski): we should crash the stack here
1763       BTM_TRACE_ERROR("Malformed LE Advertising Report Event from controller");
1764       return;
1765     }
1766 
1767     /* Extract inquiry results */
1768     STREAM_TO_UINT8(legacy_evt_type, p);
1769     STREAM_TO_UINT8(addr_type, p);
1770     STREAM_TO_BDADDR(bda, p);
1771     STREAM_TO_UINT8(pkt_data_len, p);
1772 
1773     uint8_t* pkt_data = p;
1774     p += pkt_data_len; /* Advance to the the rssi byte */
1775     if (p > data + data_len - sizeof(rssi)) {
1776       LOG(ERROR) << "Invalid pkt_data_len: " << +pkt_data_len;
1777       return;
1778     }
1779 
1780     STREAM_TO_INT8(rssi, p);
1781 
1782     if (rssi >= 21 && rssi <= 126) {
1783       BTM_TRACE_ERROR("%s: bad rssi value in advertising report: ", __func__,
1784                       pkt_data_len, rssi);
1785     }
1786 
1787     btm_ble_process_adv_addr(bda, &addr_type);
1788 
1789     uint16_t event_type;
1790     event_type = 1 << BLE_EVT_LEGACY_BIT;
1791     if (legacy_evt_type == BTM_BLE_ADV_IND_EVT) {
1792       event_type |= (1 << BLE_EVT_CONNECTABLE_BIT)|
1793                     (1 << BLE_EVT_SCANNABLE_BIT);
1794     } else if (legacy_evt_type == BTM_BLE_ADV_DIRECT_IND_EVT) {
1795       event_type |= (1 << BLE_EVT_CONNECTABLE_BIT)|
1796                     (1 << BLE_EVT_DIRECTED_BIT);
1797     } else if (legacy_evt_type == BTM_BLE_ADV_SCAN_IND_EVT) {
1798       event_type |= (1 << BLE_EVT_SCANNABLE_BIT);
1799     } else if (legacy_evt_type == BTM_BLE_ADV_NONCONN_IND_EVT) {
1800       event_type = (1 << BLE_EVT_LEGACY_BIT);//0x0010;
1801     } else if (legacy_evt_type == BTM_BLE_SCAN_RSP_EVT) {  // SCAN_RSP;
1802       // We can't distinguish between "SCAN_RSP to an ADV_IND", and "SCAN_RSP to
1803       // an ADV_SCAN_IND", so always return "SCAN_RSP to an ADV_IND"
1804       event_type |= (1 << BLE_EVT_CONNECTABLE_BIT)|
1805                     (1 << BLE_EVT_SCANNABLE_BIT)|
1806                     (1 << BLE_EVT_SCAN_RESPONSE_BIT);
1807     } else {
1808       BTM_TRACE_ERROR(
1809           "Malformed LE Advertising Report Event - unsupported "
1810           "legacy_event_type 0x%02x",
1811           legacy_evt_type);
1812       return;
1813     }
1814 
1815     btm_ble_process_adv_pkt_cont(
1816         event_type, addr_type, bda, PHY_LE_1M, PHY_LE_NO_PACKET, NO_ADI_PRESENT,
1817         TX_POWER_NOT_PRESENT, rssi, 0x00 /* no periodic adv */, pkt_data_len,
1818         pkt_data);
1819   }
1820 }
1821 
1822 /**
1823  * This function is called after random address resolution is done, and proceed
1824  * to process adv packet.
1825  */
btm_ble_process_adv_pkt_cont(uint16_t evt_type,uint8_t 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,uint8_t * data)1826 void btm_ble_process_adv_pkt_cont(uint16_t evt_type, uint8_t addr_type,
1827                                   const RawAddress& bda, uint8_t primary_phy,
1828                                   uint8_t secondary_phy,
1829                                   uint8_t advertising_sid, int8_t tx_power,
1830                                   int8_t rssi, uint16_t periodic_adv_int,
1831                                   uint8_t data_len, uint8_t* data) {
1832   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
1833   bool update = true;
1834 
1835   std::vector<uint8_t> tmp;
1836   if (data_len != 0) tmp.insert(tmp.begin(), data, data + data_len);
1837 
1838   bool is_scannable = ble_evt_type_is_scannable(evt_type);
1839   bool is_scan_resp = ble_evt_type_is_scan_resp(evt_type);
1840   bool is_legacy = ble_evt_type_is_legacy(evt_type);
1841 
1842   // We might receive a legacy scan response without receving a ADV_IND
1843   // or ADV_SCAN_IND before. Only parsing the scan response data which
1844   // has no ad flag, the device will be set to DUMO mode. The createbond
1845   // procedure will use the wrong device mode.
1846   // In such case no necessary to report scan response
1847   if(is_legacy && is_scan_resp && !cache.Exist(addr_type, bda))
1848     return;
1849 
1850   bool is_start = is_legacy && is_scannable && !is_scan_resp;
1851 
1852   if (is_legacy)
1853     AdvertiseDataParser::RemoveTrailingZeros(tmp);
1854 
1855   // We might have send scan request to this device before, but didn't get the
1856   // response. In such case make sure data is put at start, not appended to
1857   // already existing data.
1858   std::vector<uint8_t> const& adv_data =
1859       is_start ? cache.Set(addr_type, bda, std::move(tmp))
1860                : cache.Append(addr_type, bda, std::move(tmp));
1861 
1862   bool data_complete = (ble_evt_type_data_status(evt_type) != 0x01);
1863 
1864   if (!data_complete) {
1865     // If we didn't receive whole adv data yet, don't report the device.
1866     DVLOG(1) << "Data not complete yet, waiting for more " << bda;
1867     return;
1868   }
1869 
1870   bool is_active_scan =
1871       btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI;
1872   if (is_active_scan && is_scannable && !is_scan_resp) {
1873     // If we didn't receive scan response yet, don't report the device.
1874     DVLOG(1) << " Waiting for scan response " << bda;
1875     return;
1876   }
1877 
1878   if (!AdvertiseDataParser::IsValid(adv_data)) {
1879     DVLOG(1) << __func__ << "Dropping bad advertisement packet: "
1880              << base::HexEncode(adv_data.data(), adv_data.size());
1881     return;
1882   }
1883 
1884   tINQ_DB_ENT* p_i = btm_inq_db_find(bda);
1885 
1886   /* Check if this address has already been processed for this inquiry */
1887   if (btm_inq_find_bdaddr(bda)) {
1888     /* never been report as an LE device */
1889     if (p_i && (!(p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BLE) ||
1890                 /* scan repsonse to be updated */
1891                 (!p_i->scan_rsp))) {
1892       update = true;
1893     } else if (BTM_BLE_IS_OBS_ACTIVE(btm_cb.ble_ctr_cb.scan_activity)) {
1894       update = false;
1895     } else {
1896       /* if yes, skip it */
1897       cache.Clear(addr_type, bda);
1898       return; /* assumption: one result per event */
1899     }
1900   }
1901   /* If existing entry, use that, else get  a new one (possibly reusing the
1902    * oldest) */
1903   if (p_i == NULL) {
1904     p_i = btm_inq_db_new(bda);
1905     if (p_i != NULL) {
1906       p_inq->inq_cmpl_info.num_resp++;
1907       p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms();
1908     } else
1909       return;
1910   } else if (p_i->inq_count !=
1911              p_inq->inq_counter) /* first time seen in this inquiry */
1912   {
1913     p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms();
1914     p_inq->inq_cmpl_info.num_resp++;
1915   }
1916 
1917   /* update the LE device information in inquiry database */
1918   btm_ble_update_inq_result(p_i, addr_type, bda, evt_type, primary_phy,
1919                             secondary_phy, advertising_sid, tx_power, rssi,
1920                             periodic_adv_int, adv_data);
1921 
1922   uint8_t result = btm_ble_is_discoverable(bda, adv_data);
1923   if (result == 0) {
1924     cache.Clear(addr_type, bda);
1925     LOG_WARN("%s device no longer discoverable, discarding advertising packet",
1926              __func__);
1927     return;
1928   }
1929 
1930   if (!update) result &= ~BTM_BLE_INQ_RESULT;
1931   /* If the number of responses found and limited, issue a cancel inquiry */
1932   if (p_inq->inqparms.max_resps &&
1933       p_inq->inq_cmpl_info.num_resp == p_inq->inqparms.max_resps) {
1934     /* new device */
1935     if (p_i == NULL ||
1936         /* assume a DUMO device, BR/EDR inquiry is always active */
1937         (p_i &&
1938          (p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BLE) ==
1939              BT_DEVICE_TYPE_BLE &&
1940          p_i->scan_rsp)) {
1941       BTM_TRACE_WARNING(
1942           "INQ RES: Extra Response Received...cancelling inquiry..");
1943 
1944       /* if is non-periodic inquiry active, cancel now */
1945       if ((p_inq->inq_active & BTM_BR_INQ_ACTIVE_MASK) != 0 &&
1946           (p_inq->inq_active & BTM_PERIODIC_INQUIRY_ACTIVE) == 0)
1947         btsnd_hcic_inq_cancel();
1948 
1949       btm_ble_stop_inquiry();
1950 
1951       btm_acl_update_busy_level(BTM_BLI_INQ_DONE_EVT);
1952     }
1953   }
1954 
1955   tBTM_INQ_RESULTS_CB* p_inq_results_cb = p_inq->p_inq_results_cb;
1956   if (p_inq_results_cb && (result & BTM_BLE_INQ_RESULT)) {
1957     (p_inq_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
1958                        const_cast<uint8_t*>(adv_data.data()), adv_data.size());
1959   }
1960 
1961   tBTM_INQ_RESULTS_CB* p_obs_results_cb = btm_cb.ble_ctr_cb.p_obs_results_cb;
1962   if (p_obs_results_cb && (result & BTM_BLE_OBS_RESULT)) {
1963     (p_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results,
1964                        const_cast<uint8_t*>(adv_data.data()), adv_data.size());
1965   }
1966 
1967   cache.Clear(addr_type, bda);
1968 }
1969 
btm_ble_process_phy_update_pkt(uint8_t len,uint8_t * data)1970 void btm_ble_process_phy_update_pkt(uint8_t len, uint8_t* data) {
1971   uint8_t status, tx_phy, rx_phy;
1972   uint16_t handle;
1973 
1974   LOG_ASSERT(len == 5);
1975   uint8_t* p = data;
1976   STREAM_TO_UINT8(status, p);
1977   STREAM_TO_UINT16(handle, p);
1978   handle = handle & 0x0FFF;
1979   STREAM_TO_UINT8(tx_phy, p);
1980   STREAM_TO_UINT8(rx_phy, p);
1981 
1982   gatt_notify_phy_updated(status, handle, tx_phy, rx_phy);
1983 }
1984 
1985 /*******************************************************************************
1986  *
1987  * Function         btm_ble_start_scan
1988  *
1989  * Description      Start the BLE scan.
1990  *
1991  * Returns          void
1992  *
1993  ******************************************************************************/
btm_ble_start_scan(void)1994 tBTM_STATUS btm_ble_start_scan(void) {
1995   tBTM_BLE_INQ_CB* p_inq = &btm_cb.ble_ctr_cb.inq_var;
1996   /* start scan, disable duplicate filtering */
1997   btm_send_hci_scan_enable(BTM_BLE_SCAN_ENABLE, p_inq->scan_duplicate_filter);
1998 
1999   if (p_inq->scan_type == BTM_BLE_SCAN_MODE_ACTI)
2000     btm_ble_set_topology_mask(BTM_BLE_STATE_ACTIVE_SCAN_BIT);
2001   else
2002     btm_ble_set_topology_mask(BTM_BLE_STATE_PASSIVE_SCAN_BIT);
2003 
2004   return BTM_CMD_STARTED;
2005 }
2006 
2007 /*******************************************************************************
2008  *
2009  * Function         btm_ble_stop_scan
2010  *
2011  * Description      Stop the BLE scan.
2012  *
2013  * Returns          void
2014  *
2015  ******************************************************************************/
btm_ble_stop_scan(void)2016 void btm_ble_stop_scan(void) {
2017   BTM_TRACE_EVENT("btm_ble_stop_scan ");
2018 
2019   if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI)
2020     btm_ble_clear_topology_mask(BTM_BLE_STATE_ACTIVE_SCAN_BIT);
2021   else
2022     btm_ble_clear_topology_mask(BTM_BLE_STATE_PASSIVE_SCAN_BIT);
2023 
2024   /* Clear the inquiry callback if set */
2025   btm_cb.ble_ctr_cb.inq_var.scan_type = BTM_BLE_SCAN_MODE_NONE;
2026 
2027   /* stop discovery now */
2028   btm_send_hci_scan_enable(BTM_BLE_SCAN_DISABLE, BTM_BLE_DUPLICATE_ENABLE);
2029 
2030   btm_update_scanner_filter_policy(SP_ADV_ALL);
2031 }
2032 /*******************************************************************************
2033  *
2034  * Function         btm_ble_stop_inquiry
2035  *
2036  * Description      Stop the BLE Inquiry.
2037  *
2038  * Returns          void
2039  *
2040  ******************************************************************************/
btm_ble_stop_inquiry(void)2041 void btm_ble_stop_inquiry(void) {
2042   tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
2043   tBTM_BLE_CB* p_ble_cb = &btm_cb.ble_ctr_cb;
2044 
2045   alarm_cancel(p_ble_cb->inq_var.inquiry_timer);
2046 
2047   p_ble_cb->scan_activity &= ~BTM_BLE_INQUIRY_MASK;
2048 
2049   /* If no more scan activity, stop LE scan now */
2050   if (!BTM_BLE_IS_SCAN_ACTIVE(p_ble_cb->scan_activity))
2051     btm_ble_stop_scan();
2052   else if ((p_ble_cb->inq_var.scan_interval != BTM_BLE_LOW_LATENCY_SCAN_INT) ||
2053            (p_ble_cb->inq_var.scan_window != BTM_BLE_LOW_LATENCY_SCAN_WIN)) {
2054     BTM_TRACE_DEBUG("%s: setting default params for ongoing observe", __func__);
2055     btm_ble_stop_scan();
2056     btm_ble_start_scan();
2057   }
2058 
2059   /* If we have a callback registered for inquiry complete, call it */
2060   BTM_TRACE_DEBUG("BTM Inq Compl Callback: status 0x%02x, num results %d",
2061                   p_inq->inq_cmpl_info.status, p_inq->inq_cmpl_info.num_resp);
2062 
2063   btm_process_inq_complete(
2064       HCI_SUCCESS, (uint8_t)(p_inq->inqparms.mode & BTM_BLE_INQUIRY_MASK));
2065 }
2066 
2067 /*******************************************************************************
2068  *
2069  * Function         btm_ble_stop_observe
2070  *
2071  * Description      Stop the BLE Observe.
2072  *
2073  * Returns          void
2074  *
2075  ******************************************************************************/
btm_ble_stop_observe(void)2076 static void btm_ble_stop_observe(void) {
2077   tBTM_BLE_CB* p_ble_cb = &btm_cb.ble_ctr_cb;
2078   tBTM_CMPL_CB* p_obs_cb = p_ble_cb->p_obs_cmpl_cb;
2079 
2080   alarm_cancel(p_ble_cb->observer_timer);
2081 
2082   p_ble_cb->scan_activity &= ~BTM_LE_OBSERVE_ACTIVE;
2083 
2084   p_ble_cb->p_obs_results_cb = NULL;
2085   p_ble_cb->p_obs_cmpl_cb = NULL;
2086 
2087   if (!BTM_BLE_IS_SCAN_ACTIVE(p_ble_cb->scan_activity)) btm_ble_stop_scan();
2088 
2089   if (p_obs_cb) (p_obs_cb)(&btm_cb.btm_inq_vars.inq_cmpl_info);
2090 }
2091 /*******************************************************************************
2092  *
2093  * Function         btm_ble_adv_states_operation
2094  *
2095  * Description      Set or clear adv states in topology mask
2096  *
2097  * Returns          operation status. true if sucessful, false otherwise.
2098  *
2099  ******************************************************************************/
2100 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)2101 static bool btm_ble_adv_states_operation(BTM_TOPOLOGY_FUNC_PTR* p_handler,
2102                                          uint8_t adv_evt) {
2103   bool rt = false;
2104 
2105   switch (adv_evt) {
2106     case BTM_BLE_CONNECT_EVT:
2107       rt = (*p_handler)(BTM_BLE_STATE_CONN_ADV_BIT);
2108       break;
2109 
2110     case BTM_BLE_NON_CONNECT_EVT:
2111       rt = (*p_handler)(BTM_BLE_STATE_NON_CONN_ADV_BIT);
2112       break;
2113     case BTM_BLE_CONNECT_DIR_EVT:
2114       rt = (*p_handler)(BTM_BLE_STATE_HI_DUTY_DIR_ADV_BIT);
2115       break;
2116 
2117     case BTM_BLE_DISCOVER_EVT:
2118       rt = (*p_handler)(BTM_BLE_STATE_SCAN_ADV_BIT);
2119       break;
2120 
2121     case BTM_BLE_CONNECT_LO_DUTY_DIR_EVT:
2122       rt = (*p_handler)(BTM_BLE_STATE_LO_DUTY_DIR_ADV_BIT);
2123       break;
2124 
2125     default:
2126       BTM_TRACE_ERROR("unknown adv event : %d", adv_evt);
2127       break;
2128   }
2129 
2130   return rt;
2131 }
2132 
2133 /*******************************************************************************
2134  *
2135  * Function         btm_ble_start_adv
2136  *
2137  * Description      start the BLE advertising.
2138  *
2139  * Returns          void
2140  *
2141  ******************************************************************************/
btm_ble_start_adv(void)2142 tBTM_STATUS btm_ble_start_adv(void) {
2143   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
2144 
2145   if (!btm_ble_adv_states_operation(btm_ble_topology_check, p_cb->evt_type))
2146     return BTM_WRONG_MODE;
2147 
2148 #if (BLE_PRIVACY_SPT == TRUE)
2149   /* To relax resolving list,  always have resolving list enabled, unless
2150    * directed adv */
2151   if (p_cb->evt_type != BTM_BLE_CONNECT_LO_DUTY_DIR_EVT &&
2152       p_cb->evt_type != BTM_BLE_CONNECT_DIR_EVT)
2153     /* enable resolving list is desired */
2154     btm_ble_enable_resolving_list_for_platform(BTM_BLE_RL_ADV);
2155 #endif
2156 
2157   btsnd_hcic_ble_set_adv_enable(BTM_BLE_ADV_ENABLE);
2158   p_cb->adv_mode = BTM_BLE_ADV_ENABLE;
2159   btm_ble_adv_states_operation(btm_ble_set_topology_mask, p_cb->evt_type);
2160   return BTM_SUCCESS;
2161 }
2162 
2163 /*******************************************************************************
2164  *
2165  * Function         btm_ble_stop_adv
2166  *
2167  * Description      Stop the BLE advertising.
2168  *
2169  * Returns          void
2170  *
2171  ******************************************************************************/
btm_ble_stop_adv(void)2172 tBTM_STATUS btm_ble_stop_adv(void) {
2173   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
2174 
2175   if (p_cb->adv_mode == BTM_BLE_ADV_ENABLE) {
2176     btsnd_hcic_ble_set_adv_enable(BTM_BLE_ADV_DISABLE);
2177 
2178     p_cb->fast_adv_on = false;
2179     p_cb->adv_mode = BTM_BLE_ADV_DISABLE;
2180 
2181     /* clear all adv states */
2182     btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_ADV_MASK);
2183   }
2184   return BTM_SUCCESS;
2185 }
2186 
btm_ble_fast_adv_timer_timeout(UNUSED_ATTR void * data)2187 static void btm_ble_fast_adv_timer_timeout(UNUSED_ATTR void* data) {
2188   /* fast adv is completed, fall back to slow adv interval */
2189   btm_ble_start_slow_adv();
2190 }
2191 
2192 /*******************************************************************************
2193  *
2194  * Function         btm_ble_start_slow_adv
2195  *
2196  * Description      Restart adv with slow adv interval
2197  *
2198  * Returns          void
2199  *
2200  ******************************************************************************/
btm_ble_start_slow_adv(void)2201 static void btm_ble_start_slow_adv(void) {
2202   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
2203 
2204   if (p_cb->adv_mode == BTM_BLE_ADV_ENABLE) {
2205     tBTM_LE_RANDOM_CB* p_addr_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
2206     RawAddress address = RawAddress::kEmpty;
2207     tBLE_ADDR_TYPE init_addr_type = BLE_ADDR_PUBLIC;
2208     tBLE_ADDR_TYPE own_addr_type = p_addr_cb->own_addr_type;
2209 
2210     btm_ble_stop_adv();
2211 
2212     p_cb->evt_type = btm_set_conn_mode_adv_init_addr(
2213         p_cb, address, &init_addr_type, &own_addr_type);
2214 
2215     /* slow adv mode never goes into directed adv */
2216     btsnd_hcic_ble_write_adv_params(
2217         BTM_BLE_GAP_ADV_SLOW_INT, BTM_BLE_GAP_ADV_SLOW_INT, p_cb->evt_type,
2218         own_addr_type, init_addr_type, address, p_cb->adv_chnl_map, p_cb->afp);
2219 
2220     btm_ble_start_adv();
2221   }
2222 }
2223 
btm_ble_inquiry_timer_gap_limited_discovery_timeout(UNUSED_ATTR void * data)2224 static void btm_ble_inquiry_timer_gap_limited_discovery_timeout(
2225     UNUSED_ATTR void* data) {
2226   /* lim_timeout expired, limited discovery should exit now */
2227   btm_cb.btm_inq_vars.discoverable_mode &= ~BTM_BLE_LIMITED_DISCOVERABLE;
2228   btm_ble_set_adv_flag(btm_cb.btm_inq_vars.connectable_mode,
2229                        btm_cb.btm_inq_vars.discoverable_mode);
2230 }
2231 
btm_ble_inquiry_timer_timeout(UNUSED_ATTR void * data)2232 static void btm_ble_inquiry_timer_timeout(UNUSED_ATTR void* data) {
2233   btm_ble_stop_inquiry();
2234 }
2235 
btm_ble_observer_timer_timeout(UNUSED_ATTR void * data)2236 static void btm_ble_observer_timer_timeout(UNUSED_ATTR void* data) {
2237   btm_ble_stop_observe();
2238 }
2239 
btm_ble_refresh_raddr_timer_timeout(UNUSED_ATTR void * data)2240 void btm_ble_refresh_raddr_timer_timeout(UNUSED_ATTR void* data) {
2241   if (btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type == BLE_ADDR_RANDOM) {
2242     /* refresh the random addr */
2243     btm_gen_resolvable_private_addr(base::Bind(&btm_gen_resolve_paddr_low));
2244   }
2245 }
2246 
2247 /*******************************************************************************
2248  *
2249  * Function         btm_ble_read_remote_features_complete
2250  *
2251  * Description      This function is called when the command complete message
2252  *                  is received from the HCI for the read LE remote feature
2253  *                  supported complete event.
2254  *
2255  * Returns          void
2256  *
2257  ******************************************************************************/
btm_ble_read_remote_features_complete(uint8_t * p)2258 void btm_ble_read_remote_features_complete(uint8_t* p) {
2259   BTM_TRACE_EVENT("%s", __func__);
2260 
2261   uint16_t handle;
2262   uint8_t status;
2263   STREAM_TO_UINT8(status, p);
2264   STREAM_TO_UINT16(handle, p);
2265   handle = handle & 0x0FFF;  // only 12 bits meaningful
2266 
2267   if (status != HCI_SUCCESS) {
2268     BTM_TRACE_ERROR("%s: failed for handle: 0x%04d, status 0x%02x", __func__,
2269                     handle, status);
2270     if (status != HCI_ERR_UNSUPPORTED_REM_FEATURE) return;
2271   }
2272 
2273   int idx = btm_handle_to_acl_index(handle);
2274   if (idx == MAX_L2CAP_LINKS) {
2275     BTM_TRACE_ERROR("%s: can't find acl for handle: 0x%04d", __func__, handle);
2276     return;
2277   }
2278 
2279   if (status == HCI_SUCCESS) {
2280     STREAM_TO_ARRAY(btm_cb.acl_db[idx].peer_le_features, p, BD_FEATURES_LEN);
2281   }
2282 
2283   btsnd_hcic_rmt_ver_req(handle);
2284 }
2285 
2286 /*******************************************************************************
2287  *
2288  * Function         btm_ble_write_adv_enable_complete
2289  *
2290  * Description      This function process the write adv enable command complete.
2291  *
2292  * Returns          void
2293  *
2294  ******************************************************************************/
btm_ble_write_adv_enable_complete(uint8_t * p)2295 void btm_ble_write_adv_enable_complete(uint8_t* p) {
2296   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
2297 
2298   /* if write adv enable/disbale not succeed */
2299   if (*p != HCI_SUCCESS) {
2300     /* toggle back the adv mode */
2301     p_cb->adv_mode = !p_cb->adv_mode;
2302   }
2303 }
2304 
2305 /*******************************************************************************
2306  *
2307  * Function         btm_ble_dir_adv_tout
2308  *
2309  * Description      when directed adv time out
2310  *
2311  * Returns          void
2312  *
2313  ******************************************************************************/
btm_ble_dir_adv_tout(void)2314 void btm_ble_dir_adv_tout(void) {
2315   btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
2316 
2317   /* make device fall back into undirected adv mode by default */
2318   btm_cb.ble_ctr_cb.inq_var.directed_conn = false;
2319 }
2320 
2321 /*******************************************************************************
2322  *
2323  * Function         btm_ble_set_topology_mask
2324  *
2325  * Description      set BLE topology mask
2326  *
2327  * Returns          true is request is allowed, false otherwise.
2328  *
2329  ******************************************************************************/
btm_ble_set_topology_mask(tBTM_BLE_STATE_MASK request_state_mask)2330 bool btm_ble_set_topology_mask(tBTM_BLE_STATE_MASK request_state_mask) {
2331   request_state_mask &= BTM_BLE_STATE_ALL_MASK;
2332   btm_cb.ble_ctr_cb.cur_states |= (request_state_mask & BTM_BLE_STATE_ALL_MASK);
2333   return true;
2334 }
2335 
2336 /*******************************************************************************
2337  *
2338  * Function         btm_ble_clear_topology_mask
2339  *
2340  * Description      Clear BLE topology bit mask
2341  *
2342  * Returns          true is request is allowed, false otherwise.
2343  *
2344  ******************************************************************************/
btm_ble_clear_topology_mask(tBTM_BLE_STATE_MASK request_state_mask)2345 bool btm_ble_clear_topology_mask(tBTM_BLE_STATE_MASK request_state_mask) {
2346   request_state_mask &= BTM_BLE_STATE_ALL_MASK;
2347   btm_cb.ble_ctr_cb.cur_states &= ~request_state_mask;
2348   return true;
2349 }
2350 
2351 /*******************************************************************************
2352  *
2353  * Function         btm_ble_update_link_topology_mask
2354  *
2355  * Description      This function update the link topology mask
2356  *
2357  * Returns          void
2358  *
2359  ******************************************************************************/
btm_ble_update_link_topology_mask(uint8_t link_role,bool increase)2360 void btm_ble_update_link_topology_mask(uint8_t link_role, bool increase) {
2361   btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_CONN_MASK);
2362 
2363   if (increase)
2364     btm_cb.ble_ctr_cb.link_count[link_role]++;
2365   else if (btm_cb.ble_ctr_cb.link_count[link_role] > 0)
2366     btm_cb.ble_ctr_cb.link_count[link_role]--;
2367 
2368   if (btm_cb.ble_ctr_cb.link_count[HCI_ROLE_MASTER])
2369     btm_ble_set_topology_mask(BTM_BLE_STATE_MASTER_BIT);
2370 
2371   if (btm_cb.ble_ctr_cb.link_count[HCI_ROLE_SLAVE])
2372     btm_ble_set_topology_mask(BTM_BLE_STATE_SLAVE_BIT);
2373 
2374   if (link_role == HCI_ROLE_SLAVE && increase) {
2375     btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
2376     /* make device fall back into undirected adv mode by default */
2377     btm_cb.ble_ctr_cb.inq_var.directed_conn = BTM_BLE_CONNECT_EVT;
2378     /* clear all adv states */
2379     btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_ADV_MASK);
2380   }
2381 }
2382 
2383 /*******************************************************************************
2384  *
2385  * Function         btm_ble_update_mode_operation
2386  *
2387  * Description      This function update the GAP role operation when a link
2388  *                  status is updated.
2389  *
2390  * Returns          void
2391  *
2392  ******************************************************************************/
btm_ble_update_mode_operation(uint8_t link_role,const RawAddress * bd_addr,uint8_t status)2393 void btm_ble_update_mode_operation(uint8_t link_role, const RawAddress* bd_addr,
2394                                    uint8_t status) {
2395   if (status == HCI_ERR_ADVERTISING_TIMEOUT) {
2396     btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
2397     /* make device fall back into undirected adv mode by default */
2398     btm_cb.ble_ctr_cb.inq_var.directed_conn = BTM_BLE_CONNECT_EVT;
2399     /* clear all adv states */
2400     btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_ADV_MASK);
2401   }
2402 
2403   if (btm_cb.ble_ctr_cb.inq_var.connectable_mode == BTM_BLE_CONNECTABLE) {
2404     btm_ble_set_connectability(btm_cb.btm_inq_vars.connectable_mode |
2405                                btm_cb.ble_ctr_cb.inq_var.connectable_mode);
2406   }
2407 
2408   /* in case of disconnected, we must cancel bgconn and restart
2409      in order to add back device to white list in order to reconnect */
2410   if (bd_addr) btm_ble_bgconn_cancel_if_disconnected(*bd_addr);
2411 
2412   /* when no connection is attempted, and controller is not rejecting last
2413      request
2414      due to resource limitation, start next direct connection or background
2415      connection
2416      now in order */
2417   if (btm_ble_get_conn_st() == BLE_CONN_IDLE &&
2418       status != HCI_ERR_HOST_REJECT_RESOURCES &&
2419       status != HCI_ERR_MAX_NUM_OF_CONNECTIONS) {
2420     btm_ble_resume_bg_conn();
2421   }
2422 }
2423 
2424 /*******************************************************************************
2425  *
2426  * Function         btm_ble_init
2427  *
2428  * Description      Initialize the control block variable values.
2429  *
2430  * Returns          void
2431  *
2432  ******************************************************************************/
btm_ble_init(void)2433 void btm_ble_init(void) {
2434   tBTM_BLE_CB* p_cb = &btm_cb.ble_ctr_cb;
2435 
2436   BTM_TRACE_DEBUG("%s", __func__);
2437 
2438   alarm_free(p_cb->observer_timer);
2439   alarm_free(p_cb->inq_var.fast_adv_timer);
2440   memset(p_cb, 0, sizeof(tBTM_BLE_CB));
2441   memset(&(btm_cb.cmn_ble_vsc_cb), 0, sizeof(tBTM_BLE_VSC_CB));
2442   btm_cb.cmn_ble_vsc_cb.values_read = false;
2443 
2444   p_cb->observer_timer = alarm_new("btm_ble.observer_timer");
2445   p_cb->cur_states = 0;
2446 
2447   p_cb->inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
2448   p_cb->inq_var.scan_type = BTM_BLE_SCAN_MODE_NONE;
2449   p_cb->inq_var.adv_chnl_map = BTM_BLE_DEFAULT_ADV_CHNL_MAP;
2450   p_cb->inq_var.afp = BTM_BLE_DEFAULT_AFP;
2451   p_cb->inq_var.sfp = BTM_BLE_DEFAULT_SFP;
2452   p_cb->inq_var.connectable_mode = BTM_BLE_NON_CONNECTABLE;
2453   p_cb->inq_var.discoverable_mode = BTM_BLE_NON_DISCOVERABLE;
2454   p_cb->inq_var.fast_adv_timer = alarm_new("btm_ble_inq.fast_adv_timer");
2455   p_cb->inq_var.inquiry_timer = alarm_new("btm_ble_inq.inquiry_timer");
2456 
2457   /* for background connection, reset connection params to be undefined */
2458   p_cb->scan_int = p_cb->scan_win = BTM_BLE_SCAN_PARAM_UNDEF;
2459 
2460   p_cb->inq_var.evt_type = BTM_BLE_NON_CONNECT_EVT;
2461 
2462   p_cb->addr_mgnt_cb.refresh_raddr_timer =
2463       alarm_new("btm_ble_addr.refresh_raddr_timer");
2464 
2465 #if (BLE_VND_INCLUDED == FALSE)
2466   btm_ble_adv_filter_init();
2467 #endif
2468 }
2469 
2470 /*******************************************************************************
2471  *
2472  * Function         btm_ble_topology_check
2473  *
2474  * Description      check to see requested state is supported. One state check
2475  *                  at a time is supported
2476  *
2477  * Returns          true is request is allowed, false otherwise.
2478  *
2479  ******************************************************************************/
btm_ble_topology_check(tBTM_BLE_STATE_MASK request_state_mask)2480 bool btm_ble_topology_check(tBTM_BLE_STATE_MASK request_state_mask) {
2481   bool rt = false;
2482 
2483   uint8_t state_offset = 0;
2484   uint16_t cur_states = btm_cb.ble_ctr_cb.cur_states;
2485   uint8_t request_state = 0;
2486 
2487   /* check only one bit is set and within valid range */
2488   if (request_state_mask == BTM_BLE_STATE_INVALID ||
2489       request_state_mask > BTM_BLE_STATE_SCAN_ADV_BIT ||
2490       (request_state_mask & (request_state_mask - 1)) != 0) {
2491     BTM_TRACE_ERROR("illegal state requested: %d", request_state_mask);
2492     return rt;
2493   }
2494 
2495   while (request_state_mask) {
2496     request_state_mask >>= 1;
2497     request_state++;
2498   }
2499 
2500   /* check if the requested state is supported or not */
2501   uint8_t bit_num = btm_le_state_combo_tbl[0][request_state - 1];
2502   const uint8_t* ble_supported_states =
2503       controller_get_interface()->get_ble_supported_states();
2504 
2505   if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, bit_num)) {
2506     BTM_TRACE_ERROR("state requested not supported: %d", request_state);
2507     return rt;
2508   }
2509 
2510   rt = true;
2511   /* make sure currently active states are all supported in conjunction with the
2512      requested state. If the bit in table is UNSUPPORTED, the combination is not
2513      supported */
2514   while (cur_states != 0) {
2515     if (cur_states & 0x01) {
2516       uint8_t bit_num = btm_le_state_combo_tbl[request_state][state_offset];
2517       if (bit_num != UNSUPPORTED) {
2518         if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, bit_num)) {
2519           rt = false;
2520           break;
2521         }
2522       }
2523     }
2524     cur_states >>= 1;
2525     state_offset++;
2526   }
2527   return rt;
2528 }
2529