• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 1999-2012 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 that handle BTM interface functions for the
22  *  Bluetooth device including Rest, HCI buffer size and others
23  *
24  ******************************************************************************/
25 
26 #include <base/logging.h>
27 #include <stddef.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 
32 #include "bt_types.h"
33 #include "bt_utils.h"
34 #include "btcore/include/module.h"
35 #include "btm_int.h"
36 #include "btu.h"
37 #include "common/message_loop_thread.h"
38 #include "device/include/controller.h"
39 #include "hci_layer.h"
40 #include "hcimsgs.h"
41 #include "l2c_int.h"
42 #include "osi/include/osi.h"
43 #include "stack/gatt/connection_manager.h"
44 
45 #include "gatt_int.h"
46 #include "main/shim/btm_api.h"
47 #include "main/shim/controller.h"
48 #include "main/shim/shim.h"
49 
50 extern bluetooth::common::MessageLoopThread bt_startup_thread;
51 
52 /******************************************************************************/
53 /*               L O C A L    D A T A    D E F I N I T I O N S                */
54 /******************************************************************************/
55 
56 #ifndef BTM_DEV_RESET_TIMEOUT
57 #define BTM_DEV_RESET_TIMEOUT 4
58 #endif
59 
60 // TODO: Reevaluate this value in the context of timers with ms granularity
61 #define BTM_DEV_NAME_REPLY_TIMEOUT_MS    \
62   (2 * 1000) /* 2 seconds for name reply \
63                 */
64 
65 #define BTM_INFO_TIMEOUT 5 /* 5 seconds for info response */
66 
67 /******************************************************************************/
68 /*            L O C A L    F U N C T I O N     P R O T O T Y P E S            */
69 /******************************************************************************/
70 
71 static void btm_decode_ext_features_page(uint8_t page_number,
72                                          const BD_FEATURES p_features);
73 static void BTM_BT_Quality_Report_VSE_CBack(uint8_t length, uint8_t* p_stream);
74 
75 /*******************************************************************************
76  *
77  * Function         btm_dev_init
78  *
79  * Description      This function is on the BTM startup
80  *
81  * Returns          void
82  *
83  ******************************************************************************/
btm_dev_init()84 void btm_dev_init() {
85   /* Initialize nonzero defaults */
86   memset(btm_cb.cfg.bd_name, 0, sizeof(tBTM_LOC_BD_NAME));
87 
88   btm_cb.devcb.read_local_name_timer = alarm_new("btm.read_local_name_timer");
89   btm_cb.devcb.read_rssi_timer = alarm_new("btm.read_rssi_timer");
90   btm_cb.devcb.read_failed_contact_counter_timer =
91       alarm_new("btm.read_failed_contact_counter_timer");
92   btm_cb.devcb.read_automatic_flush_timeout_timer =
93       alarm_new("btm.read_automatic_flush_timeout_timer");
94   btm_cb.devcb.read_link_quality_timer =
95       alarm_new("btm.read_link_quality_timer");
96   btm_cb.devcb.read_inq_tx_power_timer =
97       alarm_new("btm.read_inq_tx_power_timer");
98   btm_cb.devcb.qos_setup_timer = alarm_new("btm.qos_setup_timer");
99   btm_cb.devcb.read_tx_power_timer = alarm_new("btm.read_tx_power_timer");
100 
101   btm_cb.btm_acl_pkt_types_supported =
102       BTM_ACL_PKT_TYPES_MASK_DH1 + BTM_ACL_PKT_TYPES_MASK_DM1 +
103       BTM_ACL_PKT_TYPES_MASK_DH3 + BTM_ACL_PKT_TYPES_MASK_DM3 +
104       BTM_ACL_PKT_TYPES_MASK_DH5 + BTM_ACL_PKT_TYPES_MASK_DM5;
105 
106   btm_cb.btm_sco_pkt_types_supported =
107       ESCO_PKT_TYPES_MASK_HV1 + ESCO_PKT_TYPES_MASK_HV2 +
108       ESCO_PKT_TYPES_MASK_HV3 + ESCO_PKT_TYPES_MASK_EV3 +
109       ESCO_PKT_TYPES_MASK_EV4 + ESCO_PKT_TYPES_MASK_EV5;
110 }
111 
112 /*******************************************************************************
113  *
114  * Function         btm_db_reset
115  *
116  * Description      This function is called by BTM_DeviceReset and clears out
117  *                  any pending callbacks for inquiries, discoveries, other
118  *                  pending functions that may be in progress.
119  *
120  * Returns          void
121  *
122  ******************************************************************************/
btm_db_reset(void)123 static void btm_db_reset(void) {
124   tBTM_CMPL_CB* p_cb;
125 
126   btm_inq_db_reset();
127 
128   if (btm_cb.devcb.p_rln_cmpl_cb) {
129     p_cb = btm_cb.devcb.p_rln_cmpl_cb;
130     btm_cb.devcb.p_rln_cmpl_cb = NULL;
131 
132     if (p_cb) (*p_cb)((void*)NULL);
133   }
134 
135   if (btm_cb.devcb.p_rssi_cmpl_cb) {
136     p_cb = btm_cb.devcb.p_rssi_cmpl_cb;
137     btm_cb.devcb.p_rssi_cmpl_cb = NULL;
138 
139     if (p_cb) {
140       tBTM_RSSI_RESULT btm_rssi_result;
141       btm_rssi_result.status = BTM_DEV_RESET;
142       (*p_cb)(&btm_rssi_result);
143     }
144   }
145 
146   if (btm_cb.devcb.p_failed_contact_counter_cmpl_cb) {
147     p_cb = btm_cb.devcb.p_failed_contact_counter_cmpl_cb;
148     btm_cb.devcb.p_failed_contact_counter_cmpl_cb = NULL;
149 
150     if (p_cb) {
151       tBTM_FAILED_CONTACT_COUNTER_RESULT btm_failed_contact_counter_result;
152       btm_failed_contact_counter_result.status = BTM_DEV_RESET;
153       (*p_cb)(&btm_failed_contact_counter_result);
154     }
155   }
156 
157   if (btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb) {
158     p_cb = btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb;
159     btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb = NULL;
160 
161     if (p_cb) {
162       tBTM_AUTOMATIC_FLUSH_TIMEOUT_RESULT btm_automatic_flush_timeout_result;
163       btm_automatic_flush_timeout_result.status = BTM_DEV_RESET;
164       (*p_cb)(&btm_automatic_flush_timeout_result);
165     }
166   }
167 }
168 
set_sec_state_idle(void * data,void * context)169 bool set_sec_state_idle(void* data, void* context) {
170   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
171   p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
172   return true;
173 }
174 
reset_complete(void * result)175 static void reset_complete(void* result) {
176   CHECK(result == FUTURE_SUCCESS);
177   const controller_t* controller = controller_get_interface();
178 
179   /* Tell L2CAP that all connections are gone */
180   l2cu_device_reset();
181 
182   /* Clear current security state */
183   list_foreach(btm_cb.sec_dev_rec, set_sec_state_idle, NULL);
184 
185   /* After the reset controller should restore all parameters to defaults. */
186   btm_cb.btm_inq_vars.inq_counter = 1;
187   btm_cb.btm_inq_vars.inq_scan_window = HCI_DEF_INQUIRYSCAN_WINDOW;
188   btm_cb.btm_inq_vars.inq_scan_period = HCI_DEF_INQUIRYSCAN_INTERVAL;
189   btm_cb.btm_inq_vars.inq_scan_type = HCI_DEF_SCAN_TYPE;
190 
191   btm_cb.btm_inq_vars.page_scan_window = HCI_DEF_PAGESCAN_WINDOW;
192   btm_cb.btm_inq_vars.page_scan_period = HCI_DEF_PAGESCAN_INTERVAL;
193   btm_cb.btm_inq_vars.page_scan_type = HCI_DEF_SCAN_TYPE;
194 
195   btm_cb.ble_ctr_cb.conn_state = BLE_CONN_IDLE;
196   connection_manager::reset(true);
197 
198   btm_pm_reset();
199 
200   l2c_link_processs_num_bufs(controller->get_acl_buffer_count_classic());
201 
202   // setup the random number generator
203   std::srand(std::time(nullptr));
204 
205 #if (BLE_PRIVACY_SPT == TRUE)
206   /* Set up the BLE privacy settings */
207   if (controller->supports_ble() && controller->supports_ble_privacy() &&
208       controller->get_ble_resolving_list_max_size() > 0) {
209     btm_ble_resolving_list_init(controller->get_ble_resolving_list_max_size());
210     /* set the default random private address timeout */
211     btsnd_hcic_ble_set_rand_priv_addr_timeout(
212         btm_get_next_private_addrress_interval_ms() / 1000);
213   }
214 #endif
215 
216   if (controller->supports_ble()) {
217     btm_ble_white_list_init(controller->get_ble_white_list_size());
218     l2c_link_processs_ble_num_bufs(controller->get_acl_buffer_count_ble());
219   }
220 
221   BTM_SetPinType(btm_cb.cfg.pin_type, btm_cb.cfg.pin_code,
222                  btm_cb.cfg.pin_code_len);
223 
224   for (int i = 0; i <= controller->get_last_features_classic_index(); i++) {
225     btm_decode_ext_features_page(i,
226                                  controller->get_features_classic(i)->as_array);
227   }
228 
229   btm_report_device_status(BTM_DEV_STATUS_UP);
230 }
231 
232 // TODO(zachoverflow): remove this function
BTM_DeviceReset(UNUSED_ATTR tBTM_CMPL_CB * p_cb)233 void BTM_DeviceReset(UNUSED_ATTR tBTM_CMPL_CB* p_cb) {
234   /* Flush all ACL connections */
235   btm_acl_device_down();
236 
237   /* Clear the callback, so application would not hang on reset */
238   btm_db_reset();
239 
240   if (bluetooth::shim::is_gd_shim_enabled()) {
241     module_start_up_callbacked_wrapper(get_module(GD_CONTROLLER_MODULE),
242                                        &bt_startup_thread, reset_complete);
243   } else {
244     module_start_up_callbacked_wrapper(get_module(CONTROLLER_MODULE),
245                                        &bt_startup_thread, reset_complete);
246   }
247 }
248 
249 /*******************************************************************************
250  *
251  * Function         BTM_IsDeviceUp
252  *
253  * Description      This function is called to check if the device is up.
254  *
255  * Returns          true if device is up, else false
256  *
257  ******************************************************************************/
BTM_IsDeviceUp(void)258 bool BTM_IsDeviceUp(void) { return controller_get_interface()->get_is_ready(); }
259 
260 /*******************************************************************************
261  *
262  * Function         btm_read_local_name_timeout
263  *
264  * Description      Callback when reading the local name times out.
265  *
266  * Returns          void
267  *
268  ******************************************************************************/
btm_read_local_name_timeout(UNUSED_ATTR void * data)269 void btm_read_local_name_timeout(UNUSED_ATTR void* data) {
270   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_rln_cmpl_cb;
271   btm_cb.devcb.p_rln_cmpl_cb = NULL;
272   if (p_cb) (*p_cb)((void*)NULL);
273 }
274 
275 /*******************************************************************************
276  *
277  * Function         btm_decode_ext_features_page
278  *
279  * Description      This function is decodes a features page.
280  *
281  * Returns          void
282  *
283  ******************************************************************************/
btm_decode_ext_features_page(uint8_t page_number,const uint8_t * p_features)284 static void btm_decode_ext_features_page(uint8_t page_number,
285                                          const uint8_t* p_features) {
286   CHECK(p_features != nullptr);
287   BTM_TRACE_DEBUG("btm_decode_ext_features_page page: %d", page_number);
288   switch (page_number) {
289     /* Extended (Legacy) Page 0 */
290     case 0:
291 
292       /* Create ACL supported packet types mask */
293       btm_cb.btm_acl_pkt_types_supported =
294           (BTM_ACL_PKT_TYPES_MASK_DH1 + BTM_ACL_PKT_TYPES_MASK_DM1);
295 
296       if (HCI_3_SLOT_PACKETS_SUPPORTED(p_features))
297         btm_cb.btm_acl_pkt_types_supported |=
298             (BTM_ACL_PKT_TYPES_MASK_DH3 + BTM_ACL_PKT_TYPES_MASK_DM3);
299 
300       if (HCI_5_SLOT_PACKETS_SUPPORTED(p_features))
301         btm_cb.btm_acl_pkt_types_supported |=
302             (BTM_ACL_PKT_TYPES_MASK_DH5 + BTM_ACL_PKT_TYPES_MASK_DM5);
303 
304       /* Add in EDR related ACL types */
305       if (!HCI_EDR_ACL_2MPS_SUPPORTED(p_features)) {
306         btm_cb.btm_acl_pkt_types_supported |=
307             (BTM_ACL_PKT_TYPES_MASK_NO_2_DH1 + BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 +
308              BTM_ACL_PKT_TYPES_MASK_NO_2_DH5);
309       }
310 
311       if (!HCI_EDR_ACL_3MPS_SUPPORTED(p_features)) {
312         btm_cb.btm_acl_pkt_types_supported |=
313             (BTM_ACL_PKT_TYPES_MASK_NO_3_DH1 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH3 +
314              BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
315       }
316 
317       /* Check to see if 3 and 5 slot packets are available */
318       if (HCI_EDR_ACL_2MPS_SUPPORTED(p_features) ||
319           HCI_EDR_ACL_3MPS_SUPPORTED(p_features)) {
320         if (!HCI_3_SLOT_EDR_ACL_SUPPORTED(p_features))
321           btm_cb.btm_acl_pkt_types_supported |=
322               (BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 +
323                BTM_ACL_PKT_TYPES_MASK_NO_3_DH3);
324 
325         if (!HCI_5_SLOT_EDR_ACL_SUPPORTED(p_features))
326           btm_cb.btm_acl_pkt_types_supported |=
327               (BTM_ACL_PKT_TYPES_MASK_NO_2_DH5 +
328                BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
329       }
330 
331       BTM_TRACE_DEBUG("Local supported ACL packet types: 0x%04x",
332                       btm_cb.btm_acl_pkt_types_supported);
333 
334       /* Create (e)SCO supported packet types mask */
335       btm_cb.btm_sco_pkt_types_supported = 0;
336       btm_cb.sco_cb.esco_supported = false;
337       if (HCI_SCO_LINK_SUPPORTED(p_features)) {
338         btm_cb.btm_sco_pkt_types_supported = ESCO_PKT_TYPES_MASK_HV1;
339 
340         if (HCI_HV2_PACKETS_SUPPORTED(p_features))
341           btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_HV2;
342 
343         if (HCI_HV3_PACKETS_SUPPORTED(p_features))
344           btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_HV3;
345       }
346 
347       if (HCI_ESCO_EV3_SUPPORTED(p_features))
348         btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_EV3;
349 
350       if (HCI_ESCO_EV4_SUPPORTED(p_features))
351         btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_EV4;
352 
353       if (HCI_ESCO_EV5_SUPPORTED(p_features))
354         btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_EV5;
355       if (btm_cb.btm_sco_pkt_types_supported & BTM_ESCO_LINK_ONLY_MASK) {
356         btm_cb.sco_cb.esco_supported = true;
357 
358         /* Add in EDR related eSCO types */
359         if (HCI_EDR_ESCO_2MPS_SUPPORTED(p_features)) {
360           if (!HCI_3_SLOT_EDR_ESCO_SUPPORTED(p_features))
361             btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_NO_2_EV5;
362         } else {
363           btm_cb.btm_sco_pkt_types_supported |=
364               (ESCO_PKT_TYPES_MASK_NO_2_EV3 + ESCO_PKT_TYPES_MASK_NO_2_EV5);
365         }
366 
367         if (HCI_EDR_ESCO_3MPS_SUPPORTED(p_features)) {
368           if (!HCI_3_SLOT_EDR_ESCO_SUPPORTED(p_features))
369             btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_NO_3_EV5;
370         } else {
371           btm_cb.btm_sco_pkt_types_supported |=
372               (ESCO_PKT_TYPES_MASK_NO_3_EV3 + ESCO_PKT_TYPES_MASK_NO_3_EV5);
373         }
374       }
375 
376       BTM_TRACE_DEBUG("Local supported SCO packet types: 0x%04x",
377                       btm_cb.btm_sco_pkt_types_supported);
378 
379       /* Create Default Policy Settings */
380       if (HCI_SWITCH_SUPPORTED(p_features))
381         btm_cb.btm_def_link_policy |= HCI_ENABLE_MASTER_SLAVE_SWITCH;
382       else
383         btm_cb.btm_def_link_policy &= ~HCI_ENABLE_MASTER_SLAVE_SWITCH;
384 
385       if (HCI_HOLD_MODE_SUPPORTED(p_features))
386         btm_cb.btm_def_link_policy |= HCI_ENABLE_HOLD_MODE;
387       else
388         btm_cb.btm_def_link_policy &= ~HCI_ENABLE_HOLD_MODE;
389 
390       if (HCI_SNIFF_MODE_SUPPORTED(p_features))
391         btm_cb.btm_def_link_policy |= HCI_ENABLE_SNIFF_MODE;
392       else
393         btm_cb.btm_def_link_policy &= ~HCI_ENABLE_SNIFF_MODE;
394 
395       if (HCI_PARK_MODE_SUPPORTED(p_features))
396         btm_cb.btm_def_link_policy |= HCI_ENABLE_PARK_MODE;
397       else
398         btm_cb.btm_def_link_policy &= ~HCI_ENABLE_PARK_MODE;
399 
400       btm_sec_dev_reset();
401 
402       if (HCI_LMP_INQ_RSSI_SUPPORTED(p_features)) {
403         if (HCI_EXT_INQ_RSP_SUPPORTED(p_features))
404           BTM_SetInquiryMode(BTM_INQ_RESULT_EXTENDED);
405         else
406           BTM_SetInquiryMode(BTM_INQ_RESULT_WITH_RSSI);
407       }
408 
409 #if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE)
410       if (HCI_NON_FLUSHABLE_PB_SUPPORTED(p_features))
411         l2cu_set_non_flushable_pbf(true);
412       else
413         l2cu_set_non_flushable_pbf(false);
414 #endif
415       BTM_SetPageScanType(BTM_DEFAULT_SCAN_TYPE);
416       BTM_SetInquiryScanType(BTM_DEFAULT_SCAN_TYPE);
417 
418       break;
419 
420     default:
421       BTM_TRACE_WARNING("%s: feature page %d ignored", __func__, page_number);
422       break;
423   }
424 }
425 
426 /*******************************************************************************
427  *
428  * Function         BTM_SetLocalDeviceName
429  *
430  * Description      This function is called to set the local device name.
431  *
432  * Returns          status of the operation
433  *
434  ******************************************************************************/
BTM_SetLocalDeviceName(char * p_name)435 tBTM_STATUS BTM_SetLocalDeviceName(char* p_name) {
436   uint8_t* p;
437 
438   if (!p_name || !p_name[0] || (strlen((char*)p_name) > BD_NAME_LEN))
439     return (BTM_ILLEGAL_VALUE);
440 
441   if (!controller_get_interface()->get_is_ready()) return (BTM_DEV_RESET);
442   /* Save the device name if local storage is enabled */
443   p = (uint8_t*)btm_cb.cfg.bd_name;
444   if (p != (uint8_t*)p_name)
445     strlcpy(btm_cb.cfg.bd_name, p_name, BTM_MAX_LOC_BD_NAME_LEN);
446 
447   btsnd_hcic_change_name(p);
448   return (BTM_CMD_STARTED);
449 }
450 
451 /*******************************************************************************
452  *
453  * Function         BTM_ReadLocalDeviceName
454  *
455  * Description      This function is called to read the local device name.
456  *
457  * Returns          status of the operation
458  *                  If success, BTM_SUCCESS is returned and p_name points stored
459  *                              local device name
460  *                  If BTM doesn't store local device name, BTM_NO_RESOURCES is
461  *                              is returned and p_name is set to NULL
462  *
463  ******************************************************************************/
BTM_ReadLocalDeviceName(char ** p_name)464 tBTM_STATUS BTM_ReadLocalDeviceName(char** p_name) {
465   *p_name = btm_cb.cfg.bd_name;
466   return (BTM_SUCCESS);
467 }
468 
469 /*******************************************************************************
470  *
471  * Function         BTM_ReadLocalDeviceNameFromController
472  *
473  * Description      Get local device name from controller. Do not use cached
474  *                  name (used to get chip-id prior to btm reset complete).
475  *
476  * Returns          BTM_CMD_STARTED if successful, otherwise an error
477  *
478  ******************************************************************************/
BTM_ReadLocalDeviceNameFromController(tBTM_CMPL_CB * p_rln_cmpl_cback)479 tBTM_STATUS BTM_ReadLocalDeviceNameFromController(
480     tBTM_CMPL_CB* p_rln_cmpl_cback) {
481   /* Check if rln already in progress */
482   if (btm_cb.devcb.p_rln_cmpl_cb) return (BTM_NO_RESOURCES);
483 
484   /* Save callback */
485   btm_cb.devcb.p_rln_cmpl_cb = p_rln_cmpl_cback;
486 
487   btsnd_hcic_read_name();
488   alarm_set_on_mloop(btm_cb.devcb.read_local_name_timer,
489                      BTM_DEV_NAME_REPLY_TIMEOUT_MS, btm_read_local_name_timeout,
490                      NULL);
491 
492   return BTM_CMD_STARTED;
493 }
494 
495 /*******************************************************************************
496  *
497  * Function         btm_read_local_name_complete
498  *
499  * Description      This function is called when local name read complete.
500  *                  message is received from the HCI.
501  *
502  * Returns          void
503  *
504  ******************************************************************************/
btm_read_local_name_complete(uint8_t * p,UNUSED_ATTR uint16_t evt_len)505 void btm_read_local_name_complete(uint8_t* p, UNUSED_ATTR uint16_t evt_len) {
506   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_rln_cmpl_cb;
507   uint8_t status;
508 
509   alarm_cancel(btm_cb.devcb.read_local_name_timer);
510 
511   /* If there was a callback address for read local name, call it */
512   btm_cb.devcb.p_rln_cmpl_cb = NULL;
513 
514   if (p_cb) {
515     STREAM_TO_UINT8(status, p);
516 
517     if (status == HCI_SUCCESS)
518       (*p_cb)(p);
519     else
520       (*p_cb)(NULL);
521   }
522 }
523 
524 /*******************************************************************************
525  *
526  * Function         BTM_SetDeviceClass
527  *
528  * Description      This function is called to set the local device class
529  *
530  * Returns          status of the operation
531  *
532  ******************************************************************************/
BTM_SetDeviceClass(DEV_CLASS dev_class)533 tBTM_STATUS BTM_SetDeviceClass(DEV_CLASS dev_class) {
534   if (!memcmp(btm_cb.devcb.dev_class, dev_class, DEV_CLASS_LEN))
535     return (BTM_SUCCESS);
536 
537   memcpy(btm_cb.devcb.dev_class, dev_class, DEV_CLASS_LEN);
538 
539   if (!controller_get_interface()->get_is_ready()) return (BTM_DEV_RESET);
540 
541   btsnd_hcic_write_dev_class(dev_class);
542 
543   return (BTM_SUCCESS);
544 }
545 
546 /*******************************************************************************
547  *
548  * Function         BTM_ReadDeviceClass
549  *
550  * Description      This function is called to read the local device class
551  *
552  * Returns          pointer to the device class
553  *
554  ******************************************************************************/
BTM_ReadDeviceClass(void)555 uint8_t* BTM_ReadDeviceClass(void) {
556   return ((uint8_t*)btm_cb.devcb.dev_class);
557 }
558 
559 /*******************************************************************************
560  *
561  * Function         BTM_ReadLocalFeatures
562  *
563  * Description      This function is called to read the local features
564  *
565  * Returns          pointer to the local features string
566  *
567  ******************************************************************************/
568 // TODO(zachoverflow): get rid of this function
BTM_ReadLocalFeatures(void)569 uint8_t* BTM_ReadLocalFeatures(void) {
570   // Discarding const modifier for now, until this function dies
571   return (uint8_t*)controller_get_interface()
572       ->get_features_classic(0)
573       ->as_array;
574 }
575 
576 /*******************************************************************************
577  *
578  * Function         BTM_RegisterForDeviceStatusNotif
579  *
580  * Description      This function is called to register for device status
581  *                  change notifications.
582  *
583  *                  If one registration is already there calling function should
584  *                  save the pointer to the function that is return and
585  *                  call it when processing of the event is complete
586  *
587  * Returns          status of the operation
588  *
589  ******************************************************************************/
BTM_RegisterForDeviceStatusNotif(tBTM_DEV_STATUS_CB * p_cb)590 tBTM_DEV_STATUS_CB* BTM_RegisterForDeviceStatusNotif(tBTM_DEV_STATUS_CB* p_cb) {
591   tBTM_DEV_STATUS_CB* p_prev = btm_cb.devcb.p_dev_status_cb;
592 
593   btm_cb.devcb.p_dev_status_cb = p_cb;
594   return (p_prev);
595 }
596 
597 /*******************************************************************************
598  *
599  * Function         BTM_VendorSpecificCommand
600  *
601  * Description      Send a vendor specific HCI command to the controller.
602  *
603  * Notes
604  *      Opcode will be OR'd with HCI_GRP_VENDOR_SPECIFIC.
605  *
606  ******************************************************************************/
BTM_VendorSpecificCommand(uint16_t opcode,uint8_t param_len,uint8_t * p_param_buf,tBTM_VSC_CMPL_CB * p_cb)607 void BTM_VendorSpecificCommand(uint16_t opcode, uint8_t param_len,
608                                uint8_t* p_param_buf, tBTM_VSC_CMPL_CB* p_cb) {
609   /* Allocate a buffer to hold HCI command plus the callback function */
610   void* p_buf = osi_malloc(sizeof(BT_HDR) + sizeof(tBTM_CMPL_CB*) + param_len +
611                            HCIC_PREAMBLE_SIZE);
612 
613   BTM_TRACE_EVENT("BTM: %s: Opcode: 0x%04X, ParamLen: %i.", __func__, opcode,
614                   param_len);
615 
616   /* Send the HCI command (opcode will be OR'd with HCI_GRP_VENDOR_SPECIFIC) */
617   btsnd_hcic_vendor_spec_cmd(p_buf, opcode, param_len, p_param_buf,
618                              (void*)p_cb);
619 }
620 
621 /*******************************************************************************
622  *
623  * Function         btm_vsc_complete
624  *
625  * Description      This function is called when local HCI Vendor Specific
626  *                  Command complete message is received from the HCI.
627  *
628  * Returns          void
629  *
630  ******************************************************************************/
btm_vsc_complete(uint8_t * p,uint16_t opcode,uint16_t evt_len,tBTM_VSC_CMPL_CB * p_vsc_cplt_cback)631 void btm_vsc_complete(uint8_t* p, uint16_t opcode, uint16_t evt_len,
632                       tBTM_VSC_CMPL_CB* p_vsc_cplt_cback) {
633   tBTM_VSC_CMPL vcs_cplt_params;
634 
635   /* If there was a callback address for vcs complete, call it */
636   if (p_vsc_cplt_cback) {
637     /* Pass paramters to the callback function */
638     vcs_cplt_params.opcode = opcode;     /* Number of bytes in return info */
639     vcs_cplt_params.param_len = evt_len; /* Number of bytes in return info */
640     vcs_cplt_params.p_param_buf = p;
641     (*p_vsc_cplt_cback)(
642         &vcs_cplt_params); /* Call the VSC complete callback function */
643   }
644 }
645 
646 /*******************************************************************************
647  *
648  * Function         BTM_RegisterForVSEvents
649  *
650  * Description      This function is called to register/deregister for vendor
651  *                  specific HCI events.
652  *
653  *                  If is_register=true, then the function will be registered;
654  *                  otherwise, the the function will be deregistered.
655  *
656  * Returns          BTM_SUCCESS if successful,
657  *                  BTM_BUSY if maximum number of callbacks have already been
658  *                           registered.
659  *
660  ******************************************************************************/
BTM_RegisterForVSEvents(tBTM_VS_EVT_CB * p_cb,bool is_register)661 tBTM_STATUS BTM_RegisterForVSEvents(tBTM_VS_EVT_CB* p_cb, bool is_register) {
662   tBTM_STATUS retval = BTM_SUCCESS;
663   uint8_t i, free_idx = BTM_MAX_VSE_CALLBACKS;
664 
665   /* See if callback is already registered */
666   for (i = 0; i < BTM_MAX_VSE_CALLBACKS; i++) {
667     if (btm_cb.devcb.p_vend_spec_cb[i] == NULL) {
668       /* Found a free slot. Store index */
669       free_idx = i;
670     } else if (btm_cb.devcb.p_vend_spec_cb[i] == p_cb) {
671       /* Found callback in lookup table. If deregistering, clear the entry. */
672       if (!is_register) {
673         btm_cb.devcb.p_vend_spec_cb[i] = NULL;
674         BTM_TRACE_EVENT("BTM Deregister For VSEvents is successfully");
675       }
676       return (BTM_SUCCESS);
677     }
678   }
679 
680   /* Didn't find callback. Add callback to free slot if registering */
681   if (is_register) {
682     if (free_idx < BTM_MAX_VSE_CALLBACKS) {
683       btm_cb.devcb.p_vend_spec_cb[free_idx] = p_cb;
684       BTM_TRACE_EVENT("BTM Register For VSEvents is successfully");
685     } else {
686       /* No free entries available */
687       BTM_TRACE_ERROR("BTM_RegisterForVSEvents: too many callbacks registered");
688 
689       retval = BTM_NO_RESOURCES;
690     }
691   }
692 
693   return (retval);
694 }
695 
696 /*******************************************************************************
697  *
698  * Function         btm_vendor_specific_evt
699  *
700  * Description      Process event HCI_VENDOR_SPECIFIC_EVT
701  *
702  *                  Note: Some controllers do not send command complete, so
703  *                  the callback and busy flag are cleared here also.
704  *
705  * Returns          void
706  *
707  ******************************************************************************/
btm_vendor_specific_evt(uint8_t * p,uint8_t evt_len)708 void btm_vendor_specific_evt(uint8_t* p, uint8_t evt_len) {
709   uint8_t i;
710 
711   BTM_TRACE_DEBUG("BTM Event: Vendor Specific event from controller");
712 
713   for (i = 0; i < BTM_MAX_VSE_CALLBACKS; i++) {
714     if (btm_cb.devcb.p_vend_spec_cb[i])
715       (*btm_cb.devcb.p_vend_spec_cb[i])(evt_len, p);
716   }
717 }
718 
719 /*******************************************************************************
720  *
721  * Function         BTM_WritePageTimeout
722  *
723  * Description      Send HCI Write Page Timeout.
724  *
725  ******************************************************************************/
BTM_WritePageTimeout(uint16_t timeout)726 void BTM_WritePageTimeout(uint16_t timeout) {
727   BTM_TRACE_EVENT("BTM: BTM_WritePageTimeout: Timeout: %d.", timeout);
728 
729   /* Send the HCI command */
730   btsnd_hcic_write_page_tout(timeout);
731 }
732 
733 /*******************************************************************************
734  *
735  * Function         BTM_WriteVoiceSettings
736  *
737  * Description      Send HCI Write Voice Settings command.
738  *                  See hcidefs.h for settings bitmask values.
739  *
740  ******************************************************************************/
BTM_WriteVoiceSettings(uint16_t settings)741 void BTM_WriteVoiceSettings(uint16_t settings) {
742   BTM_TRACE_EVENT("BTM: BTM_WriteVoiceSettings: Settings: 0x%04x.", settings);
743 
744   /* Send the HCI command */
745   btsnd_hcic_write_voice_settings((uint16_t)(settings & 0x03ff));
746 }
747 
748 /*******************************************************************************
749  *
750  * Function         BTM_EnableTestMode
751  *
752  * Description      Send HCI the enable device under test command.
753  *
754  *                  Note: Controller can only be taken out of this mode by
755  *                      resetting the controller.
756  *
757  * Returns
758  *      BTM_SUCCESS         Command sent.
759  *      BTM_NO_RESOURCES    If out of resources to send the command.
760  *
761  *
762  ******************************************************************************/
BTM_EnableTestMode(void)763 tBTM_STATUS BTM_EnableTestMode(void) {
764   uint8_t cond;
765 
766   BTM_TRACE_EVENT("BTM: BTM_EnableTestMode");
767 
768   /* set auto accept connection as this is needed during test mode */
769   /* Allocate a buffer to hold HCI command */
770   cond = HCI_DO_AUTO_ACCEPT_CONNECT;
771   btsnd_hcic_set_event_filter(HCI_FILTER_CONNECTION_SETUP,
772                               HCI_FILTER_COND_NEW_DEVICE, &cond, sizeof(cond));
773 
774   /* put device to connectable mode */
775   if (BTM_SetConnectability(BTM_CONNECTABLE, BTM_DEFAULT_CONN_WINDOW,
776                             BTM_DEFAULT_CONN_INTERVAL) != BTM_SUCCESS) {
777     return BTM_NO_RESOURCES;
778   }
779 
780   /* put device to discoverable mode */
781   if (BTM_SetDiscoverability(BTM_GENERAL_DISCOVERABLE, BTM_DEFAULT_DISC_WINDOW,
782                              BTM_DEFAULT_DISC_INTERVAL) != BTM_SUCCESS) {
783     return BTM_NO_RESOURCES;
784   }
785 
786   /* mask off all of event from controller */
787   hci_layer_get_interface()->transmit_command(
788       hci_packet_factory_get_interface()->make_set_event_mask(
789           (const bt_event_mask_t*)("\x00\x00\x00\x00\x00\x00\x00\x00")),
790       NULL, NULL, NULL);
791 
792   /* Send the HCI command */
793   btsnd_hcic_enable_test_mode();
794   return (BTM_SUCCESS);
795 }
796 
797 /*******************************************************************************
798  *
799  * Function         BTM_DeleteStoredLinkKey
800  *
801  * Description      This function is called to delete link key for the specified
802  *                  device addresses from the NVRAM storage attached to the
803  *                  Bluetooth controller.
804  *
805  * Parameters:      bd_addr      - Addresses of the devices
806  *                  p_cb         - Call back function to be called to return
807  *                                 the results
808  *
809  ******************************************************************************/
BTM_DeleteStoredLinkKey(const RawAddress * bd_addr,tBTM_CMPL_CB * p_cb)810 tBTM_STATUS BTM_DeleteStoredLinkKey(const RawAddress* bd_addr,
811                                     tBTM_CMPL_CB* p_cb) {
812   /* Check if the previous command is completed */
813   if (btm_cb.devcb.p_stored_link_key_cmpl_cb) return (BTM_BUSY);
814 
815   bool delete_all_flag = !bd_addr;
816 
817   BTM_TRACE_EVENT("BTM: BTM_DeleteStoredLinkKey: delete_all_flag: %s",
818                   delete_all_flag ? "true" : "false");
819 
820   btm_cb.devcb.p_stored_link_key_cmpl_cb = p_cb;
821   if (!bd_addr) {
822     /* This is to delete all link keys */
823     /* We don't care the BD address. Just pass a non zero pointer */
824     RawAddress local_bd_addr = RawAddress::kEmpty;
825     btsnd_hcic_delete_stored_key(local_bd_addr, delete_all_flag);
826   } else {
827     btsnd_hcic_delete_stored_key(*bd_addr, delete_all_flag);
828   }
829 
830   return (BTM_SUCCESS);
831 }
832 
833 /*******************************************************************************
834  *
835  * Function         btm_delete_stored_link_key_complete
836  *
837  * Description      This function is called when the command complete message
838  *                  is received from the HCI for the delete stored link key
839  *                  command.
840  *
841  * Returns          void
842  *
843  ******************************************************************************/
btm_delete_stored_link_key_complete(uint8_t * p)844 void btm_delete_stored_link_key_complete(uint8_t* p) {
845   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_stored_link_key_cmpl_cb;
846   tBTM_DELETE_STORED_LINK_KEY_COMPLETE result;
847 
848   /* If there was a callback registered for read stored link key, call it */
849   btm_cb.devcb.p_stored_link_key_cmpl_cb = NULL;
850 
851   if (p_cb) {
852     /* Set the call back event to indicate command complete */
853     result.event = BTM_CB_EVT_DELETE_STORED_LINK_KEYS;
854 
855     /* Extract the result fields from the HCI event */
856     STREAM_TO_UINT8(result.status, p);
857     STREAM_TO_UINT16(result.num_keys, p);
858 
859     /* Call the call back and pass the result */
860     (*p_cb)(&result);
861   }
862 }
863 
864 /*******************************************************************************
865  *
866  * Function         btm_report_device_status
867  *
868  * Description      This function is called when there is a change in the device
869  *                  status. This function will report the new device status to
870  *                  the application
871  *
872  * Returns          void
873  *
874  ******************************************************************************/
btm_report_device_status(tBTM_DEV_STATUS status)875 void btm_report_device_status(tBTM_DEV_STATUS status) {
876   tBTM_DEV_STATUS_CB* p_cb = btm_cb.devcb.p_dev_status_cb;
877 
878   /* Call the call back to pass the device status to application */
879   if (p_cb) (*p_cb)(status);
880 }
881 
882 /*******************************************************************************
883  *
884  * Function         BTM_BT_Quality_Report_VSE_CBack
885  *
886  * Description      Callback invoked on receiving of Vendor Specific Events.
887  *                  This function will call registered BQR report receiver if
888  *                  Bluetooth Quality Report sub-event is identified.
889  *
890  * Parameters:      length - Lengths of all of the parameters contained in the
891  *                    Vendor Specific Event.
892  *                  p_stream - A pointer to the quality report which is sent
893  *                    from the Bluetooth controller via Vendor Specific Event.
894  *
895  ******************************************************************************/
BTM_BT_Quality_Report_VSE_CBack(uint8_t length,uint8_t * p_stream)896 static void BTM_BT_Quality_Report_VSE_CBack(uint8_t length, uint8_t* p_stream) {
897   if (length == 0) {
898     LOG(WARNING) << __func__ << ": Lengths of all of the parameters are zero.";
899     return;
900   }
901 
902   uint8_t sub_event = 0;
903   STREAM_TO_UINT8(sub_event, p_stream);
904   length--;
905 
906   if (sub_event == HCI_VSE_SUBCODE_BQR_SUB_EVT) {
907     if (btm_cb.p_bqr_report_receiver == nullptr) {
908       LOG(WARNING) << __func__ << ": No registered report receiver.";
909       return;
910     }
911 
912     btm_cb.p_bqr_report_receiver(length, p_stream);
913   }
914 }
915 
916 /*******************************************************************************
917  *
918  * Function         BTM_BT_Quality_Report_VSE_Register
919  *
920  * Description      Register/Deregister for Bluetooth Quality Report VSE sub
921  *                  event Callback.
922  *
923  * Parameters:      is_register - True/False to register/unregister for VSE.
924  *                  p_bqr_report_receiver - The receiver for receiving Bluetooth
925  *                    Quality Report VSE sub event.
926  *
927  ******************************************************************************/
BTM_BT_Quality_Report_VSE_Register(bool is_register,tBTM_BT_QUALITY_REPORT_RECEIVER * p_bqr_report_receiver)928 tBTM_STATUS BTM_BT_Quality_Report_VSE_Register(
929     bool is_register, tBTM_BT_QUALITY_REPORT_RECEIVER* p_bqr_report_receiver) {
930   tBTM_STATUS retval =
931       BTM_RegisterForVSEvents(BTM_BT_Quality_Report_VSE_CBack, is_register);
932 
933   if (retval != BTM_SUCCESS) {
934     LOG(WARNING) << __func__ << ": Fail to (un)register VSEvents: " << retval
935                  << ", is_register: " << logbool(is_register);
936     return retval;
937   }
938 
939   if (is_register) {
940     btm_cb.p_bqr_report_receiver = p_bqr_report_receiver;
941   } else {
942     btm_cb.p_bqr_report_receiver = nullptr;
943   }
944 
945   LOG(INFO) << __func__ << ": Success to (un)register VSEvents."
946             << " is_register: " << logbool(is_register);
947   return retval;
948 }
949