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