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