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