1 /******************************************************************************
2  *
3  *  Copyright 2000-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  *  Name:          btm_acl.cc
22  *
23  *  Description:   This file contains functions that handle ACL connections.
24  *                 This includes operations such as hold and sniff modes,
25  *                 supported packet types.
26  *
27  *                 This module contains both internal and external (API)
28  *                 functions. External (API) functions are distinguishable
29  *                 by their names beginning with uppercase BTM.
30  *
31  *
32  *****************************************************************************/
33 
34 #define LOG_TAG "btm_acl"
35 
36 #include <stddef.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 
41 #include "bt_common.h"
42 #include "bt_target.h"
43 #include "bt_types.h"
44 #include "bt_utils.h"
45 #include "btm_api.h"
46 #include "btm_int.h"
47 #include "btu.h"
48 #include "common/metrics.h"
49 #include "device/include/controller.h"
50 #include "device/include/interop.h"
51 #include "hcidefs.h"
52 #include "hcimsgs.h"
53 #include "l2c_int.h"
54 #include "main/shim/btm_api.h"
55 #include "main/shim/shim.h"
56 #include "osi/include/log.h"
57 #include "osi/include/osi.h"
58 
59 static void btm_read_remote_features(uint16_t handle);
60 static void btm_read_remote_ext_features(uint16_t handle, uint8_t page_number);
61 static void btm_process_remote_ext_features(tACL_CONN* p_acl_cb,
62                                             uint8_t num_read_pages);
63 
64 /* 3 seconds timeout waiting for responses */
65 #define BTM_DEV_REPLY_TIMEOUT_MS (3 * 1000)
66 
67 /*******************************************************************************
68  *
69  * Function         btm_acl_init
70  *
71  * Description      This function is called at BTM startup to initialize
72  *
73  * Returns          void
74  *
75  ******************************************************************************/
btm_acl_init(void)76 void btm_acl_init(void) {
77   BTM_TRACE_DEBUG("btm_acl_init");
78   /* Initialize nonzero defaults */
79   btm_cb.btm_def_link_super_tout = HCI_DEFAULT_INACT_TOUT;
80   btm_cb.acl_disc_reason = 0xff;
81 }
82 
83 /*******************************************************************************
84  *
85  * Function        btm_bda_to_acl
86  *
87  * Description     This function returns the FIRST acl_db entry for the passed
88  *                 BDA.
89  *
90  * Parameters      bda : BD address of the remote device
91  *                 transport : Physical transport used for ACL connection
92  *                 (BR/EDR or LE)
93  *
94  * Returns         Returns pointer to the ACL DB for the requested BDA if found.
95  *                 NULL if not found.
96  *
97  ******************************************************************************/
btm_bda_to_acl(const RawAddress & bda,tBT_TRANSPORT transport)98 tACL_CONN* btm_bda_to_acl(const RawAddress& bda, tBT_TRANSPORT transport) {
99   tACL_CONN* p = &btm_cb.acl_db[0];
100   uint16_t xx;
101   for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p++) {
102     if ((p->in_use) && p->remote_addr == bda && p->transport == transport) {
103       BTM_TRACE_DEBUG("btm_bda_to_acl found");
104       return (p);
105     }
106   }
107 
108   /* If here, no BD Addr found */
109   return ((tACL_CONN*)NULL);
110 }
111 
112 /*******************************************************************************
113  *
114  * Function         btm_handle_to_acl_index
115  *
116  * Description      This function returns the FIRST acl_db entry for the passed
117  *                  hci_handle.
118  *
119  * Returns          index to the acl_db or MAX_L2CAP_LINKS.
120  *
121  ******************************************************************************/
btm_handle_to_acl_index(uint16_t hci_handle)122 uint8_t btm_handle_to_acl_index(uint16_t hci_handle) {
123   tACL_CONN* p = &btm_cb.acl_db[0];
124   uint8_t xx;
125   BTM_TRACE_DEBUG("btm_handle_to_acl_index");
126   for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p++) {
127     if ((p->in_use) && (p->hci_handle == hci_handle)) {
128       break;
129     }
130   }
131 
132   /* If here, no BD Addr found */
133   return (xx);
134 }
135 
136 #if (BLE_PRIVACY_SPT == TRUE)
137 /*******************************************************************************
138  *
139  * Function         btm_ble_get_acl_remote_addr
140  *
141  * Description      This function reads the active remote address used for the
142  *                  connection.
143  *
144  * Returns          success return true, otherwise false.
145  *
146  ******************************************************************************/
btm_ble_get_acl_remote_addr(tBTM_SEC_DEV_REC * p_dev_rec,RawAddress & conn_addr,tBLE_ADDR_TYPE * p_addr_type)147 bool btm_ble_get_acl_remote_addr(tBTM_SEC_DEV_REC* p_dev_rec,
148                                  RawAddress& conn_addr,
149                                  tBLE_ADDR_TYPE* p_addr_type) {
150   bool st = true;
151 
152   if (p_dev_rec == NULL) {
153     BTM_TRACE_ERROR("%s can not find device with matching address", __func__);
154     return false;
155   }
156 
157   switch (p_dev_rec->ble.active_addr_type) {
158     case BTM_BLE_ADDR_PSEUDO:
159       conn_addr = p_dev_rec->bd_addr;
160       *p_addr_type = p_dev_rec->ble.ble_addr_type;
161       break;
162 
163     case BTM_BLE_ADDR_RRA:
164       conn_addr = p_dev_rec->ble.cur_rand_addr;
165       *p_addr_type = BLE_ADDR_RANDOM;
166       break;
167 
168     case BTM_BLE_ADDR_STATIC:
169       conn_addr = p_dev_rec->ble.identity_addr;
170       *p_addr_type = p_dev_rec->ble.identity_addr_type;
171       break;
172 
173     default:
174       BTM_TRACE_ERROR("Unknown active address: %d",
175                       p_dev_rec->ble.active_addr_type);
176       st = false;
177       break;
178   }
179 
180   return st;
181 }
182 #endif
183 /*******************************************************************************
184  *
185  * Function         btm_acl_created
186  *
187  * Description      This function is called by L2CAP when an ACL connection
188  *                  is created.
189  *
190  * Returns          void
191  *
192  ******************************************************************************/
btm_acl_created(const RawAddress & bda,DEV_CLASS dc,BD_NAME bdn,uint16_t hci_handle,uint8_t link_role,tBT_TRANSPORT transport)193 void btm_acl_created(const RawAddress& bda, DEV_CLASS dc, BD_NAME bdn,
194                      uint16_t hci_handle, uint8_t link_role,
195                      tBT_TRANSPORT transport) {
196   tBTM_SEC_DEV_REC* p_dev_rec = NULL;
197   tACL_CONN* p;
198   uint8_t xx;
199 
200   BTM_TRACE_DEBUG("%s: peer %s hci_handle=%d link_role=%d  transport=%d",
201                   __func__, bda.ToString().c_str(), hci_handle, link_role,
202                   transport);
203   /* Ensure we don't have duplicates */
204   p = btm_bda_to_acl(bda, transport);
205   if (p != (tACL_CONN*)NULL) {
206     p->hci_handle = hci_handle;
207     p->link_role = link_role;
208     p->transport = transport;
209     VLOG(1) << "Duplicate btm_acl_created: RemBdAddr: " << bda;
210     BTM_SetLinkPolicy(p->remote_addr, &btm_cb.btm_def_link_policy);
211     return;
212   }
213 
214   /* Allocate acl_db entry */
215   for (xx = 0, p = &btm_cb.acl_db[0]; xx < MAX_L2CAP_LINKS; xx++, p++) {
216     if (!p->in_use) {
217       p->in_use = true;
218       p->hci_handle = hci_handle;
219       p->link_role = link_role;
220       p->link_up_issued = false;
221       p->remote_addr = bda;
222 
223       p->transport = transport;
224 #if (BLE_PRIVACY_SPT == TRUE)
225       if (transport == BT_TRANSPORT_LE)
226         btm_ble_refresh_local_resolvable_private_addr(
227             bda, btm_cb.ble_ctr_cb.addr_mgnt_cb.private_addr);
228 #else
229       p->conn_addr_type = BLE_ADDR_PUBLIC;
230       p->conn_addr = *controller_get_interface()->get_address();
231 
232 #endif
233       p->switch_role_failed_attempts = 0;
234       p->switch_role_state = BTM_ACL_SWKEY_STATE_IDLE;
235 
236       btm_pm_sm_alloc(xx);
237 
238       if (dc) memcpy(p->remote_dc, dc, DEV_CLASS_LEN);
239 
240       if (bdn) memcpy(p->remote_name, bdn, BTM_MAX_REM_BD_NAME_LEN);
241 
242       /* if BR/EDR do something more */
243       if (transport == BT_TRANSPORT_BR_EDR) {
244         btsnd_hcic_read_rmt_clk_offset(p->hci_handle);
245         btsnd_hcic_rmt_ver_req(p->hci_handle);
246       }
247       p_dev_rec = btm_find_dev_by_handle(hci_handle);
248 
249       if (p_dev_rec) {
250         BTM_TRACE_DEBUG("%s: peer %s device_type=0x%x", __func__,
251                         bda.ToString().c_str(), p_dev_rec->device_type);
252       }
253 
254       if (p_dev_rec && !(transport == BT_TRANSPORT_LE)) {
255         /* If remote features already known, copy them and continue connection
256          * setup */
257         if ((p_dev_rec->num_read_pages) &&
258             (p_dev_rec->num_read_pages <= (HCI_EXT_FEATURES_PAGE_MAX + 1))) {
259           memcpy(p->peer_lmp_feature_pages, p_dev_rec->feature_pages,
260                  (HCI_FEATURE_BYTES_PER_PAGE * p_dev_rec->num_read_pages));
261           p->num_read_pages = p_dev_rec->num_read_pages;
262 
263           const uint8_t req_pend = (p_dev_rec->sm4 & BTM_SM4_REQ_PEND);
264 
265           /* Store the Peer Security Capabilites (in SM4 and rmt_sec_caps) */
266           btm_sec_set_peer_sec_caps(p, p_dev_rec);
267 
268           BTM_TRACE_API("%s: pend:%d", __func__, req_pend);
269           if (req_pend) {
270             /* Request for remaining Security Features (if any) */
271             l2cu_resubmit_pending_sec_req(&p_dev_rec->bd_addr);
272           }
273           btm_establish_continue(p);
274           return;
275         }
276       }
277 
278       /* If here, features are not known yet */
279       if (p_dev_rec && transport == BT_TRANSPORT_LE) {
280 #if (BLE_PRIVACY_SPT == TRUE)
281         btm_ble_get_acl_remote_addr(p_dev_rec, p->active_remote_addr,
282                                     &p->active_remote_addr_type);
283 #endif
284 
285         if (controller_get_interface()
286                 ->supports_ble_peripheral_initiated_feature_exchange() ||
287             link_role == HCI_ROLE_MASTER) {
288           btsnd_hcic_ble_read_remote_feat(p->hci_handle);
289         } else {
290           btm_establish_continue(p);
291         }
292       }
293 
294       /* read page 1 - on rmt feature event for buffer reasons */
295       return;
296     }
297   }
298 }
299 
btm_acl_update_conn_addr(uint16_t conn_handle,const RawAddress & address)300 void btm_acl_update_conn_addr(uint16_t conn_handle, const RawAddress& address) {
301   uint8_t idx = btm_handle_to_acl_index(conn_handle);
302   if (idx != MAX_L2CAP_LINKS) {
303     btm_cb.acl_db[idx].conn_addr = address;
304   }
305 }
306 
307 /*******************************************************************************
308  *
309  * Function         btm_acl_report_role_change
310  *
311  * Description      This function is called when the local device is deemed
312  *                  to be down. It notifies L2CAP of the failure.
313  *
314  * Returns          void
315  *
316  ******************************************************************************/
btm_acl_report_role_change(uint8_t hci_status,const RawAddress * bda)317 void btm_acl_report_role_change(uint8_t hci_status, const RawAddress* bda) {
318   tBTM_ROLE_SWITCH_CMPL ref_data;
319   BTM_TRACE_DEBUG("btm_acl_report_role_change");
320   if (btm_cb.devcb.p_switch_role_cb &&
321       (bda && btm_cb.devcb.switch_role_ref_data.remote_bd_addr == *bda)) {
322     memcpy(&ref_data, &btm_cb.devcb.switch_role_ref_data,
323            sizeof(tBTM_ROLE_SWITCH_CMPL));
324     ref_data.hci_status = hci_status;
325     (*btm_cb.devcb.p_switch_role_cb)(&ref_data);
326     memset(&btm_cb.devcb.switch_role_ref_data, 0,
327            sizeof(tBTM_ROLE_SWITCH_CMPL));
328     btm_cb.devcb.p_switch_role_cb = NULL;
329   }
330 }
331 
332 /*******************************************************************************
333  *
334  * Function         btm_acl_removed
335  *
336  * Description      This function is called by L2CAP when an ACL connection
337  *                  is removed. Since only L2CAP creates ACL links, we use
338  *                  the L2CAP link index as our index into the control blocks.
339  *
340  * Returns          void
341  *
342  ******************************************************************************/
btm_acl_removed(const RawAddress & bda,tBT_TRANSPORT transport)343 void btm_acl_removed(const RawAddress& bda, tBT_TRANSPORT transport) {
344   tACL_CONN* p;
345   tBTM_SEC_DEV_REC* p_dev_rec = NULL;
346   BTM_TRACE_DEBUG("btm_acl_removed");
347   p = btm_bda_to_acl(bda, transport);
348   if (p != (tACL_CONN*)NULL) {
349     p->in_use = false;
350 
351     /* if the disconnected channel has a pending role switch, clear it now */
352     btm_acl_report_role_change(HCI_ERR_NO_CONNECTION, &bda);
353 
354     /* Only notify if link up has had a chance to be issued */
355     if (p->link_up_issued) {
356       p->link_up_issued = false;
357 
358       /* If anyone cares, indicate the database changed */
359       if (btm_cb.p_bl_changed_cb) {
360         tBTM_BL_EVENT_DATA evt_data;
361         evt_data.event = BTM_BL_DISCN_EVT;
362         evt_data.discn.p_bda = &bda;
363         evt_data.discn.handle = p->hci_handle;
364         evt_data.discn.transport = p->transport;
365         (*btm_cb.p_bl_changed_cb)(&evt_data);
366       }
367 
368       btm_acl_update_busy_level(BTM_BLI_ACL_DOWN_EVT);
369     }
370 
371     BTM_TRACE_DEBUG(
372         "acl hci_handle=%d transport=%d connectable_mode=0x%0x link_role=%d",
373         p->hci_handle, p->transport, btm_cb.ble_ctr_cb.inq_var.connectable_mode,
374         p->link_role);
375 
376     p_dev_rec = btm_find_dev(bda);
377     if (p_dev_rec) {
378       BTM_TRACE_DEBUG("before update p_dev_rec->sec_flags=0x%x",
379                       p_dev_rec->sec_flags);
380       if (p->transport == BT_TRANSPORT_LE) {
381         BTM_TRACE_DEBUG("LE link down");
382         p_dev_rec->sec_flags &= ~(BTM_SEC_LE_ENCRYPTED | BTM_SEC_ROLE_SWITCHED);
383         if ((p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN) == 0) {
384           BTM_TRACE_DEBUG("Not Bonded");
385           p_dev_rec->sec_flags &=
386               ~(BTM_SEC_LE_LINK_KEY_AUTHED | BTM_SEC_LE_AUTHENTICATED);
387         } else {
388           BTM_TRACE_DEBUG("Bonded");
389         }
390       } else {
391         BTM_TRACE_DEBUG("Bletooth link down");
392         p_dev_rec->sec_flags &= ~(BTM_SEC_AUTHORIZED | BTM_SEC_AUTHENTICATED |
393                                   BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED);
394       }
395       BTM_TRACE_DEBUG("after update p_dev_rec->sec_flags=0x%x",
396                       p_dev_rec->sec_flags);
397     } else {
398       BTM_TRACE_ERROR("Device not found");
399     }
400 
401     /* Clear the ACL connection data */
402     memset(p, 0, sizeof(tACL_CONN));
403   }
404 }
405 
406 /*******************************************************************************
407  *
408  * Function         btm_acl_device_down
409  *
410  * Description      This function is called when the local device is deemed
411  *                  to be down. It notifies L2CAP of the failure.
412  *
413  * Returns          void
414  *
415  ******************************************************************************/
btm_acl_device_down(void)416 void btm_acl_device_down(void) {
417   tACL_CONN* p = &btm_cb.acl_db[0];
418   uint16_t xx;
419   BTM_TRACE_DEBUG("btm_acl_device_down");
420   for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p++) {
421     if (p->in_use) {
422       BTM_TRACE_DEBUG("hci_handle=%d HCI_ERR_HW_FAILURE ", p->hci_handle);
423       l2c_link_hci_disc_comp(p->hci_handle, HCI_ERR_HW_FAILURE);
424     }
425   }
426 }
427 
428 /*******************************************************************************
429  *
430  * Function         btm_acl_update_busy_level
431  *
432  * Description      This function is called to update the busy level of the
433  *                  system.
434  *
435  * Returns          void
436  *
437  ******************************************************************************/
btm_acl_update_busy_level(tBTM_BLI_EVENT event)438 void btm_acl_update_busy_level(tBTM_BLI_EVENT event) {
439   bool old_inquiry_state = btm_cb.is_inquiry;
440   tBTM_BL_UPDATE_DATA evt;
441   evt.busy_level_flags = 0;
442   switch (event) {
443     case BTM_BLI_ACL_UP_EVT:
444       BTM_TRACE_DEBUG("BTM_BLI_ACL_UP_EVT");
445       break;
446     case BTM_BLI_ACL_DOWN_EVT:
447       BTM_TRACE_DEBUG("BTM_BLI_ACL_DOWN_EVT");
448       break;
449     case BTM_BLI_PAGE_EVT:
450       BTM_TRACE_DEBUG("BTM_BLI_PAGE_EVT");
451       btm_cb.is_paging = true;
452       evt.busy_level_flags = BTM_BL_PAGING_STARTED;
453       break;
454     case BTM_BLI_PAGE_DONE_EVT:
455       BTM_TRACE_DEBUG("BTM_BLI_PAGE_DONE_EVT");
456       btm_cb.is_paging = false;
457       evt.busy_level_flags = BTM_BL_PAGING_COMPLETE;
458       break;
459     case BTM_BLI_INQ_EVT:
460       BTM_TRACE_DEBUG("BTM_BLI_INQ_EVT");
461       btm_cb.is_inquiry = true;
462       evt.busy_level_flags = BTM_BL_INQUIRY_STARTED;
463       break;
464     case BTM_BLI_INQ_CANCEL_EVT:
465       BTM_TRACE_DEBUG("BTM_BLI_INQ_CANCEL_EVT");
466       btm_cb.is_inquiry = false;
467       evt.busy_level_flags = BTM_BL_INQUIRY_CANCELLED;
468       break;
469     case BTM_BLI_INQ_DONE_EVT:
470       BTM_TRACE_DEBUG("BTM_BLI_INQ_DONE_EVT");
471       btm_cb.is_inquiry = false;
472       evt.busy_level_flags = BTM_BL_INQUIRY_COMPLETE;
473       break;
474   }
475 
476   uint8_t busy_level;
477   if (btm_cb.is_paging || btm_cb.is_inquiry)
478     busy_level = 10;
479   else
480     busy_level = BTM_GetNumAclLinks();
481 
482   if ((busy_level != btm_cb.busy_level) ||
483       (old_inquiry_state != btm_cb.is_inquiry)) {
484     evt.event = BTM_BL_UPDATE_EVT;
485     evt.busy_level = busy_level;
486     btm_cb.busy_level = busy_level;
487     if (btm_cb.p_bl_changed_cb && (btm_cb.bl_evt_mask & BTM_BL_UPDATE_MASK)) {
488       tBTM_BL_EVENT_DATA btm_bl_event_data;
489       btm_bl_event_data.update = evt;
490       (*btm_cb.p_bl_changed_cb)(&btm_bl_event_data);
491     }
492   }
493 }
494 
495 /*******************************************************************************
496  *
497  * Function         BTM_GetRole
498  *
499  * Description      This function is called to get the role of the local device
500  *                  for the ACL connection with the specified remote device
501  *
502  * Returns          BTM_SUCCESS if connection exists.
503  *                  BTM_UNKNOWN_ADDR if no active link with bd addr specified
504  *
505  ******************************************************************************/
BTM_GetRole(const RawAddress & remote_bd_addr,uint8_t * p_role)506 tBTM_STATUS BTM_GetRole(const RawAddress& remote_bd_addr, uint8_t* p_role) {
507   tACL_CONN* p;
508   BTM_TRACE_DEBUG("BTM_GetRole");
509   p = btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR);
510   if (p == NULL) {
511     *p_role = BTM_ROLE_UNDEFINED;
512     return (BTM_UNKNOWN_ADDR);
513   }
514 
515   /* Get the current role */
516   *p_role = p->link_role;
517   return (BTM_SUCCESS);
518 }
519 
520 /*******************************************************************************
521  *
522  * Function         BTM_SwitchRole
523  *
524  * Description      This function is called to switch role between master and
525  *                  slave.  If role is already set it will do nothing.  If the
526  *                  command was initiated, the callback function is called upon
527  *                  completion.
528  *
529  * Returns          BTM_SUCCESS if already in specified role.
530  *                  BTM_CMD_STARTED if command issued to controller.
531  *                  BTM_NO_RESOURCES if couldn't allocate memory to issue
532  *                                   command
533  *                  BTM_UNKNOWN_ADDR if no active link with bd addr specified
534  *                  BTM_MODE_UNSUPPORTED if local device does not support role
535  *                                       switching
536  *                  BTM_BUSY if the previous command is not completed
537  *
538  ******************************************************************************/
BTM_SwitchRole(const RawAddress & remote_bd_addr,uint8_t new_role,tBTM_CMPL_CB * p_cb)539 tBTM_STATUS BTM_SwitchRole(const RawAddress& remote_bd_addr, uint8_t new_role,
540                            tBTM_CMPL_CB* p_cb) {
541   tACL_CONN* p;
542   tBTM_SEC_DEV_REC* p_dev_rec = NULL;
543   bool is_sco_active;
544   tBTM_STATUS status;
545   tBTM_PM_MODE pwr_mode;
546   tBTM_PM_PWR_MD settings;
547 
548   LOG_INFO("%s: peer %s new_role=0x%x p_cb=%p p_switch_role_cb=%p", __func__,
549            remote_bd_addr.ToString().c_str(), new_role, p_cb,
550            btm_cb.devcb.p_switch_role_cb);
551 
552   /* Make sure the local device supports switching */
553   if (!controller_get_interface()->supports_master_slave_role_switch())
554     return (BTM_MODE_UNSUPPORTED);
555 
556   if (btm_cb.devcb.p_switch_role_cb && p_cb) {
557     VLOG(2) << "Role switch on other device is in progress "
558             << btm_cb.devcb.switch_role_ref_data.remote_bd_addr;
559     return (BTM_BUSY);
560   }
561 
562   p = btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR);
563   if (p == NULL) return (BTM_UNKNOWN_ADDR);
564 
565   /* Finished if already in desired role */
566   if (p->link_role == new_role) return (BTM_SUCCESS);
567 
568   if (interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH, &remote_bd_addr))
569     return BTM_DEV_BLACKLISTED;
570 
571   /* Check if there is any SCO Active on this BD Address */
572   is_sco_active = btm_is_sco_active_by_bdaddr(remote_bd_addr);
573 
574   if (is_sco_active) return (BTM_NO_RESOURCES);
575 
576   /* Ignore role switch request if the previous request was not completed */
577   if (p->switch_role_state != BTM_ACL_SWKEY_STATE_IDLE) {
578     BTM_TRACE_DEBUG("BTM_SwitchRole busy: %d", p->switch_role_state);
579     return (BTM_BUSY);
580   }
581 
582   if (interop_match_addr(INTEROP_DYNAMIC_ROLE_SWITCH, &remote_bd_addr)) {
583     BTM_TRACE_DEBUG("%s, Device blacklisted under INTEROP_DYNAMIC_ROLE_SWITCH.",
584                     __func__);
585     return BTM_DEV_BLACKLISTED;
586   }
587 
588   status = BTM_ReadPowerMode(p->remote_addr, &pwr_mode);
589   if (status != BTM_SUCCESS) return (status);
590 
591   /* Wake up the link if in sniff or park before attempting switch */
592   if (pwr_mode == BTM_PM_MD_PARK || pwr_mode == BTM_PM_MD_SNIFF) {
593     memset((void*)&settings, 0, sizeof(settings));
594     settings.mode = BTM_PM_MD_ACTIVE;
595     status = BTM_SetPowerMode(BTM_PM_SET_ONLY_ID, p->remote_addr, &settings);
596     if (status != BTM_CMD_STARTED) return (BTM_WRONG_MODE);
597 
598     p->switch_role_state = BTM_ACL_SWKEY_STATE_MODE_CHANGE;
599   }
600   /* some devices do not support switch while encryption is on */
601   else {
602     p_dev_rec = btm_find_dev(remote_bd_addr);
603     if ((p_dev_rec != NULL) &&
604         ((p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED) != 0) &&
605         !BTM_EPR_AVAILABLE(p)) {
606       /* bypass turning off encryption if change link key is already doing it */
607       if (p->encrypt_state != BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF) {
608         btsnd_hcic_set_conn_encrypt(p->hci_handle, false);
609         p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF;
610       }
611 
612       p->switch_role_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF;
613     } else {
614       btsnd_hcic_switch_role(remote_bd_addr, new_role);
615       p->switch_role_state = BTM_ACL_SWKEY_STATE_IN_PROGRESS;
616 
617 #if (BTM_DISC_DURING_RS == TRUE)
618       if (p_dev_rec) p_dev_rec->rs_disc_pending = BTM_SEC_RS_PENDING;
619 #endif
620     }
621   }
622 
623   /* Initialize return structure in case request fails */
624   if (p_cb) {
625     btm_cb.devcb.switch_role_ref_data.remote_bd_addr = remote_bd_addr;
626     btm_cb.devcb.switch_role_ref_data.role = new_role;
627     /* initialized to an error code */
628     btm_cb.devcb.switch_role_ref_data.hci_status = HCI_ERR_UNSUPPORTED_VALUE;
629     btm_cb.devcb.p_switch_role_cb = p_cb;
630   }
631   return (BTM_CMD_STARTED);
632 }
633 
634 /*******************************************************************************
635  *
636  * Function         btm_acl_encrypt_change
637  *
638  * Description      This function is when encryption of the connection is
639  *                  completed by the LM.  Checks to see if a role switch or
640  *                  change of link key was active and initiates or continues
641  *                  process if needed.
642  *
643  * Returns          void
644  *
645  ******************************************************************************/
btm_acl_encrypt_change(uint16_t handle,uint8_t status,uint8_t encr_enable)646 void btm_acl_encrypt_change(uint16_t handle, uint8_t status,
647                             uint8_t encr_enable) {
648   tACL_CONN* p;
649   uint8_t xx;
650   tBTM_SEC_DEV_REC* p_dev_rec;
651 
652   BTM_TRACE_DEBUG("btm_acl_encrypt_change handle=%d status=%d encr_enabl=%d",
653                   handle, status, encr_enable);
654   xx = btm_handle_to_acl_index(handle);
655   /* don't assume that we can never get a bad hci_handle */
656   if (xx < MAX_L2CAP_LINKS)
657     p = &btm_cb.acl_db[xx];
658   else
659     return;
660 
661   /* Process Role Switch if active */
662   if (p->switch_role_state == BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF) {
663     /* if encryption turn off failed we still will try to switch role */
664     if (encr_enable) {
665       p->switch_role_state = BTM_ACL_SWKEY_STATE_IDLE;
666       p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
667     } else {
668       p->switch_role_state = BTM_ACL_SWKEY_STATE_SWITCHING;
669       p->encrypt_state = BTM_ACL_ENCRYPT_STATE_TEMP_FUNC;
670     }
671 
672     btsnd_hcic_switch_role(p->remote_addr, (uint8_t)!p->link_role);
673 #if (BTM_DISC_DURING_RS == TRUE)
674     p_dev_rec = btm_find_dev(p->remote_addr);
675     if (p_dev_rec != NULL) p_dev_rec->rs_disc_pending = BTM_SEC_RS_PENDING;
676 #endif
677 
678   }
679   /* Finished enabling Encryption after role switch */
680   else if (p->switch_role_state == BTM_ACL_SWKEY_STATE_ENCRYPTION_ON) {
681     p->switch_role_state = BTM_ACL_SWKEY_STATE_IDLE;
682     p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
683     btm_acl_report_role_change(btm_cb.devcb.switch_role_ref_data.hci_status,
684                                &p->remote_addr);
685 
686     /* if role change event is registered, report it now */
687     if (btm_cb.p_bl_changed_cb && (btm_cb.bl_evt_mask & BTM_BL_ROLE_CHG_MASK)) {
688       tBTM_BL_ROLE_CHG_DATA evt;
689       evt.event = BTM_BL_ROLE_CHG_EVT;
690       evt.new_role = btm_cb.devcb.switch_role_ref_data.role;
691       evt.p_bda = &btm_cb.devcb.switch_role_ref_data.remote_bd_addr;
692       evt.hci_status = btm_cb.devcb.switch_role_ref_data.hci_status;
693       tBTM_BL_EVENT_DATA btm_bl_event_data;
694       btm_bl_event_data.role_chg = evt;
695       (*btm_cb.p_bl_changed_cb)(&btm_bl_event_data);
696 
697       BTM_TRACE_DEBUG(
698           "%s: Role Switch Event: new_role 0x%02x, HCI Status 0x%02x, rs_st:%d",
699           __func__, evt.new_role, evt.hci_status, p->switch_role_state);
700     }
701 
702 #if (BTM_DISC_DURING_RS == TRUE)
703     /* If a disconnect is pending, issue it now that role switch has completed
704      */
705     p_dev_rec = btm_find_dev(p->remote_addr);
706     if (p_dev_rec != NULL) {
707       if (p_dev_rec->rs_disc_pending == BTM_SEC_DISC_PENDING) {
708         BTM_TRACE_WARNING(
709             "btm_acl_encrypt_change -> Issuing delayed HCI_Disconnect!!!");
710         btsnd_hcic_disconnect(p_dev_rec->hci_handle, HCI_ERR_PEER_USER);
711       }
712       BTM_TRACE_ERROR(
713           "btm_acl_encrypt_change: tBTM_SEC_DEV:0x%x rs_disc_pending=%d",
714           PTR_TO_UINT(p_dev_rec), p_dev_rec->rs_disc_pending);
715       p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
716     }
717 #endif
718   }
719 }
720 
check_link_policy(uint16_t * settings)721 void check_link_policy(uint16_t* settings) {
722   const controller_t* controller = controller_get_interface();
723 
724   if ((*settings & HCI_ENABLE_MASTER_SLAVE_SWITCH) &&
725       (!controller->supports_role_switch())) {
726     *settings &= (~HCI_ENABLE_MASTER_SLAVE_SWITCH);
727     BTM_TRACE_API("switch not supported (settings: 0x%04x)", *settings);
728   }
729   if ((*settings & HCI_ENABLE_HOLD_MODE) &&
730       (!controller->supports_hold_mode())) {
731     *settings &= (~HCI_ENABLE_HOLD_MODE);
732     BTM_TRACE_API("hold not supported (settings: 0x%04x)", *settings);
733   }
734   if ((*settings & HCI_ENABLE_SNIFF_MODE) &&
735       (!controller->supports_sniff_mode())) {
736     *settings &= (~HCI_ENABLE_SNIFF_MODE);
737     BTM_TRACE_API("sniff not supported (settings: 0x%04x)", *settings);
738   }
739   if ((*settings & HCI_ENABLE_PARK_MODE) &&
740       (!controller->supports_park_mode())) {
741     *settings &= (~HCI_ENABLE_PARK_MODE);
742     BTM_TRACE_API("park not supported (settings: 0x%04x)", *settings);
743   }
744 }
745 /*******************************************************************************
746  *
747  * Function         BTM_SetLinkPolicy
748  *
749  * Description      Create and send HCI "Write Policy Set" command
750  *
751  * Returns          status of the operation
752  *
753  ******************************************************************************/
BTM_SetLinkPolicy(const RawAddress & remote_bda,uint16_t * settings)754 tBTM_STATUS BTM_SetLinkPolicy(const RawAddress& remote_bda,
755                               uint16_t* settings) {
756   tACL_CONN* p;
757   BTM_TRACE_DEBUG("%s", __func__);
758 
759   /* First, check if hold mode is supported */
760   if (*settings != HCI_DISABLE_ALL_LM_MODES) {
761     check_link_policy(settings);
762   }
763 
764   p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
765   if (p != NULL) {
766     btsnd_hcic_write_policy_set(p->hci_handle, *settings);
767     return BTM_CMD_STARTED;
768   }
769 
770   /* If here, no BD Addr found */
771   return (BTM_UNKNOWN_ADDR);
772 }
773 
774 /*******************************************************************************
775  *
776  * Function         BTM_SetDefaultLinkPolicy
777  *
778  * Description      Set the default value for HCI "Write Policy Set" command
779  *                  to use when an ACL link is created.
780  *
781  * Returns          void
782  *
783  ******************************************************************************/
BTM_SetDefaultLinkPolicy(uint16_t settings)784 void BTM_SetDefaultLinkPolicy(uint16_t settings) {
785   BTM_TRACE_DEBUG("BTM_SetDefaultLinkPolicy setting:0x%04x", settings);
786 
787   check_link_policy(&settings);
788   btm_cb.btm_def_link_policy = settings;
789   BTM_TRACE_DEBUG("Set DefaultLinkPolicy:0x%04x", settings);
790 
791   /* Set the default Link Policy of the controller */
792   btsnd_hcic_write_def_policy_set(settings);
793 }
794 
btm_use_preferred_conn_params(const RawAddress & bda)795 void btm_use_preferred_conn_params(const RawAddress& bda) {
796   tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE);
797   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(bda);
798 
799   /* If there are any preferred connection parameters, set them now */
800   if ((p_lcb != NULL) && (p_dev_rec != NULL) &&
801       (p_dev_rec->conn_params.min_conn_int >= BTM_BLE_CONN_INT_MIN) &&
802       (p_dev_rec->conn_params.min_conn_int <= BTM_BLE_CONN_INT_MAX) &&
803       (p_dev_rec->conn_params.max_conn_int >= BTM_BLE_CONN_INT_MIN) &&
804       (p_dev_rec->conn_params.max_conn_int <= BTM_BLE_CONN_INT_MAX) &&
805       (p_dev_rec->conn_params.slave_latency <= BTM_BLE_CONN_LATENCY_MAX) &&
806       (p_dev_rec->conn_params.supervision_tout >= BTM_BLE_CONN_SUP_TOUT_MIN) &&
807       (p_dev_rec->conn_params.supervision_tout <= BTM_BLE_CONN_SUP_TOUT_MAX) &&
808       ((p_lcb->min_interval < p_dev_rec->conn_params.min_conn_int &&
809         p_dev_rec->conn_params.min_conn_int != BTM_BLE_CONN_PARAM_UNDEF) ||
810        (p_lcb->min_interval > p_dev_rec->conn_params.max_conn_int) ||
811        (p_lcb->latency > p_dev_rec->conn_params.slave_latency) ||
812        (p_lcb->timeout > p_dev_rec->conn_params.supervision_tout))) {
813     BTM_TRACE_DEBUG(
814         "%s: HANDLE=%d min_conn_int=%d max_conn_int=%d slave_latency=%d "
815         "supervision_tout=%d",
816         __func__, p_lcb->handle, p_dev_rec->conn_params.min_conn_int,
817         p_dev_rec->conn_params.max_conn_int,
818         p_dev_rec->conn_params.slave_latency,
819         p_dev_rec->conn_params.supervision_tout);
820 
821     p_lcb->min_interval = p_dev_rec->conn_params.min_conn_int;
822     p_lcb->max_interval = p_dev_rec->conn_params.max_conn_int;
823     p_lcb->timeout = p_dev_rec->conn_params.supervision_tout;
824     p_lcb->latency = p_dev_rec->conn_params.slave_latency;
825 
826     btsnd_hcic_ble_upd_ll_conn_params(
827         p_lcb->handle, p_dev_rec->conn_params.min_conn_int,
828         p_dev_rec->conn_params.max_conn_int,
829         p_dev_rec->conn_params.slave_latency,
830         p_dev_rec->conn_params.supervision_tout, 0, 0);
831   }
832 }
833 
834 /*******************************************************************************
835  *
836  * Function         btm_read_remote_version_complete
837  *
838  * Description      This function is called when the command complete message
839  *                  is received from the HCI for the remote version info.
840  *
841  * Returns          void
842  *
843  ******************************************************************************/
btm_read_remote_version_complete(uint8_t * p)844 void btm_read_remote_version_complete(uint8_t* p) {
845   tACL_CONN* p_acl_cb = &btm_cb.acl_db[0];
846   uint8_t status;
847   uint16_t handle;
848   int xx;
849   BTM_TRACE_DEBUG("btm_read_remote_version_complete");
850 
851   STREAM_TO_UINT8(status, p);
852   STREAM_TO_UINT16(handle, p);
853 
854   /* Look up the connection by handle and copy features */
855   for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_acl_cb++) {
856     if ((p_acl_cb->in_use) && (p_acl_cb->hci_handle == handle)) {
857       if (status == HCI_SUCCESS) {
858         STREAM_TO_UINT8(p_acl_cb->lmp_version, p);
859         STREAM_TO_UINT16(p_acl_cb->manufacturer, p);
860         STREAM_TO_UINT16(p_acl_cb->lmp_subversion, p);
861 
862         if (p_acl_cb->transport == BT_TRANSPORT_BR_EDR) {
863           btm_read_remote_features(p_acl_cb->hci_handle);
864         }
865         bluetooth::common::LogRemoteVersionInfo(
866             handle, status, p_acl_cb->lmp_version, p_acl_cb->manufacturer,
867             p_acl_cb->lmp_subversion);
868       } else {
869         bluetooth::common::LogRemoteVersionInfo(handle, status, 0, 0, 0);
870       }
871 
872       if (p_acl_cb->transport == BT_TRANSPORT_LE) {
873         l2cble_notify_le_connection(p_acl_cb->remote_addr);
874         btm_use_preferred_conn_params(p_acl_cb->remote_addr);
875       }
876       break;
877     }
878   }
879 }
880 
881 /*******************************************************************************
882  *
883  * Function         btm_process_remote_ext_features
884  *
885  * Description      Local function called to process all extended features pages
886  *                  read from a remote device.
887  *
888  * Returns          void
889  *
890  ******************************************************************************/
btm_process_remote_ext_features(tACL_CONN * p_acl_cb,uint8_t num_read_pages)891 void btm_process_remote_ext_features(tACL_CONN* p_acl_cb,
892                                      uint8_t num_read_pages) {
893   uint16_t handle = p_acl_cb->hci_handle;
894   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
895   uint8_t page_idx;
896 
897   BTM_TRACE_DEBUG("btm_process_remote_ext_features");
898 
899   /* Make sure we have the record to save remote features information */
900   if (p_dev_rec == NULL) {
901     /* Get a new device; might be doing dedicated bonding */
902     p_dev_rec = btm_find_or_alloc_dev(p_acl_cb->remote_addr);
903   }
904 
905   p_acl_cb->num_read_pages = num_read_pages;
906   p_dev_rec->num_read_pages = num_read_pages;
907 
908   /* Move the pages to placeholder */
909   for (page_idx = 0; page_idx < num_read_pages; page_idx++) {
910     if (page_idx > HCI_EXT_FEATURES_PAGE_MAX) {
911       BTM_TRACE_ERROR("%s: page=%d unexpected", __func__, page_idx);
912       break;
913     }
914     memcpy(p_dev_rec->feature_pages[page_idx],
915            p_acl_cb->peer_lmp_feature_pages[page_idx],
916            HCI_FEATURE_BYTES_PER_PAGE);
917   }
918 
919   if (!(p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) ||
920       p_dev_rec->is_originator) {
921     BTM_TRACE_DEBUG("%s: Calling Next Security Procedure", __func__);
922     uint8_t status = btm_sec_execute_procedure(p_dev_rec);
923     if (status != BTM_CMD_STARTED) {
924       BTM_TRACE_ERROR("%s: Security procedure not started! status %d", __func__,
925                       status);
926       btm_sec_dev_rec_cback_event(p_dev_rec, status, false);
927     }
928   }
929   const uint8_t req_pend = (p_dev_rec->sm4 & BTM_SM4_REQ_PEND);
930 
931   /* Store the Peer Security Capabilites (in SM4 and rmt_sec_caps) */
932   btm_sec_set_peer_sec_caps(p_acl_cb, p_dev_rec);
933 
934   BTM_TRACE_API("%s: pend:%d", __func__, req_pend);
935   if (req_pend) {
936     /* Request for remaining Security Features (if any) */
937     l2cu_resubmit_pending_sec_req(&p_dev_rec->bd_addr);
938   }
939 }
940 
941 /*******************************************************************************
942  *
943  * Function         btm_read_remote_features
944  *
945  * Description      Local function called to send a read remote supported
946  *                  features/remote extended features page[0].
947  *
948  * Returns          void
949  *
950  ******************************************************************************/
btm_read_remote_features(uint16_t handle)951 void btm_read_remote_features(uint16_t handle) {
952   uint8_t acl_idx;
953   tACL_CONN* p_acl_cb;
954 
955   BTM_TRACE_DEBUG("btm_read_remote_features() handle: %d", handle);
956 
957   acl_idx = btm_handle_to_acl_index(handle);
958   if (acl_idx >= MAX_L2CAP_LINKS) {
959     BTM_TRACE_ERROR("btm_read_remote_features handle=%d invalid", handle);
960     return;
961   }
962 
963   p_acl_cb = &btm_cb.acl_db[acl_idx];
964   p_acl_cb->num_read_pages = 0;
965   memset(p_acl_cb->peer_lmp_feature_pages, 0,
966          sizeof(p_acl_cb->peer_lmp_feature_pages));
967 
968   /* first send read remote supported features HCI command */
969   /* because we don't know whether the remote support extended feature command
970    */
971   btsnd_hcic_rmt_features_req(handle);
972 }
973 
974 /*******************************************************************************
975  *
976  * Function         btm_read_remote_ext_features
977  *
978  * Description      Local function called to send a read remote extended
979  *                  features
980  *
981  * Returns          void
982  *
983  ******************************************************************************/
btm_read_remote_ext_features(uint16_t handle,uint8_t page_number)984 void btm_read_remote_ext_features(uint16_t handle, uint8_t page_number) {
985   BTM_TRACE_DEBUG("btm_read_remote_ext_features() handle: %d page: %d", handle,
986                   page_number);
987 
988   btsnd_hcic_rmt_ext_features(handle, page_number);
989 }
990 
991 /*******************************************************************************
992  *
993  * Function         btm_read_remote_features_complete
994  *
995  * Description      This function is called when the remote supported features
996  *                  complete event is received from the HCI.
997  *
998  * Returns          void
999  *
1000  ******************************************************************************/
btm_read_remote_features_complete(uint8_t * p)1001 void btm_read_remote_features_complete(uint8_t* p) {
1002   tACL_CONN* p_acl_cb;
1003   uint8_t status;
1004   uint16_t handle;
1005   uint8_t acl_idx;
1006 
1007   BTM_TRACE_DEBUG("btm_read_remote_features_complete");
1008   STREAM_TO_UINT8(status, p);
1009 
1010   if (status != HCI_SUCCESS) {
1011     BTM_TRACE_ERROR("btm_read_remote_features_complete failed (status 0x%02x)",
1012                     status);
1013     return;
1014   }
1015 
1016   STREAM_TO_UINT16(handle, p);
1017 
1018   acl_idx = btm_handle_to_acl_index(handle);
1019   if (acl_idx >= MAX_L2CAP_LINKS) {
1020     BTM_TRACE_ERROR("btm_read_remote_features_complete handle=%d invalid",
1021                     handle);
1022     return;
1023   }
1024 
1025   p_acl_cb = &btm_cb.acl_db[acl_idx];
1026 
1027   /* Copy the received features page */
1028   STREAM_TO_ARRAY(p_acl_cb->peer_lmp_feature_pages[0], p,
1029                   HCI_FEATURE_BYTES_PER_PAGE);
1030 
1031   if ((HCI_LMP_EXTENDED_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0])) &&
1032       (controller_get_interface()
1033            ->supports_reading_remote_extended_features())) {
1034     /* if the remote controller has extended features and local controller
1035        supports HCI_Read_Remote_Extended_Features command then start reading
1036        these feature starting with extended features page 1 */
1037     BTM_TRACE_DEBUG("Start reading remote extended features");
1038     btm_read_remote_ext_features(handle, 1);
1039     return;
1040   }
1041 
1042   /* Remote controller has no extended features. Process remote controller
1043      supported features (features page 0). */
1044   btm_process_remote_ext_features(p_acl_cb, 1);
1045 
1046   /* Continue with HCI connection establishment */
1047   btm_establish_continue(p_acl_cb);
1048 }
1049 
1050 /*******************************************************************************
1051  *
1052  * Function         btm_read_remote_ext_features_complete
1053  *
1054  * Description      This function is called when the remote extended features
1055  *                  complete event is received from the HCI.
1056  *
1057  * Returns          void
1058  *
1059  ******************************************************************************/
btm_read_remote_ext_features_complete(uint8_t * p,uint8_t evt_len)1060 void btm_read_remote_ext_features_complete(uint8_t* p, uint8_t evt_len) {
1061   tACL_CONN* p_acl_cb;
1062   uint8_t page_num, max_page;
1063   uint16_t handle;
1064   uint8_t acl_idx;
1065 
1066   BTM_TRACE_DEBUG("btm_read_remote_ext_features_complete");
1067 
1068   if (evt_len < HCI_EXT_FEATURES_SUCCESS_EVT_LEN) {
1069     android_errorWriteLog(0x534e4554, "141552859");
1070     BTM_TRACE_ERROR(
1071         "btm_read_remote_ext_features_complete evt length too short. length=%d",
1072         evt_len);
1073     return;
1074   }
1075 
1076   ++p;
1077   STREAM_TO_UINT16(handle, p);
1078   STREAM_TO_UINT8(page_num, p);
1079   STREAM_TO_UINT8(max_page, p);
1080 
1081   /* Validate parameters */
1082   acl_idx = btm_handle_to_acl_index(handle);
1083   if (acl_idx >= MAX_L2CAP_LINKS) {
1084     BTM_TRACE_ERROR("btm_read_remote_ext_features_complete handle=%d invalid",
1085                     handle);
1086     return;
1087   }
1088 
1089   if (max_page > HCI_EXT_FEATURES_PAGE_MAX) {
1090     BTM_TRACE_ERROR("btm_read_remote_ext_features_complete page=%d unknown",
1091                     max_page);
1092     return;
1093   }
1094 
1095   if (page_num > HCI_EXT_FEATURES_PAGE_MAX) {
1096     android_errorWriteLog(0x534e4554, "141552859");
1097     BTM_TRACE_ERROR("btm_read_remote_ext_features_complete num_page=%d invalid",
1098                     page_num);
1099     return;
1100   }
1101 
1102   if (page_num > max_page) {
1103     BTM_TRACE_WARNING(
1104         "btm_read_remote_ext_features_complete num_page=%d, max_page=%d "
1105         "invalid", page_num, max_page);
1106   }
1107 
1108   p_acl_cb = &btm_cb.acl_db[acl_idx];
1109 
1110   /* Copy the received features page */
1111   STREAM_TO_ARRAY(p_acl_cb->peer_lmp_feature_pages[page_num], p,
1112                   HCI_FEATURE_BYTES_PER_PAGE);
1113 
1114   /* If there is the next remote features page and
1115    * we have space to keep this page data - read this page */
1116   if ((page_num < max_page) && (page_num < HCI_EXT_FEATURES_PAGE_MAX)) {
1117     page_num++;
1118     BTM_TRACE_DEBUG("BTM reads next remote extended features page (%d)",
1119                     page_num);
1120     btm_read_remote_ext_features(handle, page_num);
1121     return;
1122   }
1123 
1124   /* Reading of remote feature pages is complete */
1125   BTM_TRACE_DEBUG("BTM reached last remote extended features page (%d)",
1126                   page_num);
1127 
1128   /* Process the pages */
1129   btm_process_remote_ext_features(p_acl_cb, (uint8_t)(page_num + 1));
1130 
1131   /* Continue with HCI connection establishment */
1132   btm_establish_continue(p_acl_cb);
1133 }
1134 
1135 /*******************************************************************************
1136  *
1137  * Function         btm_read_remote_ext_features_failed
1138  *
1139  * Description      This function is called when the remote extended features
1140  *                  complete event returns a failed status.
1141  *
1142  * Returns          void
1143  *
1144  ******************************************************************************/
btm_read_remote_ext_features_failed(uint8_t status,uint16_t handle)1145 void btm_read_remote_ext_features_failed(uint8_t status, uint16_t handle) {
1146   tACL_CONN* p_acl_cb;
1147   uint8_t acl_idx;
1148 
1149   BTM_TRACE_WARNING(
1150       "btm_read_remote_ext_features_failed (status 0x%02x) for handle %d",
1151       status, handle);
1152 
1153   acl_idx = btm_handle_to_acl_index(handle);
1154   if (acl_idx >= MAX_L2CAP_LINKS) {
1155     BTM_TRACE_ERROR("btm_read_remote_ext_features_failed handle=%d invalid",
1156                     handle);
1157     return;
1158   }
1159 
1160   p_acl_cb = &btm_cb.acl_db[acl_idx];
1161 
1162   /* Process supported features only */
1163   btm_process_remote_ext_features(p_acl_cb, 1);
1164 
1165   /* Continue HCI connection establishment */
1166   btm_establish_continue(p_acl_cb);
1167 }
1168 
1169 /*******************************************************************************
1170  *
1171  * Function         btm_establish_continue
1172  *
1173  * Description      This function is called when the command complete message
1174  *                  is received from the HCI for the read local link policy
1175  *                  request.
1176  *
1177  * Returns          void
1178  *
1179  ******************************************************************************/
btm_establish_continue(tACL_CONN * p_acl_cb)1180 void btm_establish_continue(tACL_CONN* p_acl_cb) {
1181   tBTM_BL_EVENT_DATA evt_data;
1182   BTM_TRACE_DEBUG("btm_establish_continue");
1183 #if (BTM_BYPASS_EXTRA_ACL_SETUP == FALSE)
1184   if (p_acl_cb->transport == BT_TRANSPORT_BR_EDR) {
1185     /* For now there are a some devices that do not like sending */
1186     /* commands events and data at the same time. */
1187     /* Set the packet types to the default allowed by the device */
1188     btm_set_packet_types(p_acl_cb, btm_cb.btm_acl_pkt_types_supported);
1189 
1190     if (btm_cb.btm_def_link_policy)
1191       BTM_SetLinkPolicy(p_acl_cb->remote_addr, &btm_cb.btm_def_link_policy);
1192   }
1193 #endif
1194   if (p_acl_cb->link_up_issued) {
1195     BTM_TRACE_ERROR("%s: Already link is up ", __func__);
1196     return;
1197   }
1198   p_acl_cb->link_up_issued = true;
1199 
1200   /* If anyone cares, tell them that the database changed */
1201   if (btm_cb.p_bl_changed_cb) {
1202     evt_data.event = BTM_BL_CONN_EVT;
1203     evt_data.conn.p_bda = &p_acl_cb->remote_addr;
1204     evt_data.conn.p_bdn = p_acl_cb->remote_name;
1205     evt_data.conn.p_dc = p_acl_cb->remote_dc;
1206     evt_data.conn.p_features = p_acl_cb->peer_lmp_feature_pages[0];
1207     evt_data.conn.handle = p_acl_cb->hci_handle;
1208     evt_data.conn.transport = p_acl_cb->transport;
1209 
1210     (*btm_cb.p_bl_changed_cb)(&evt_data);
1211   }
1212   btm_acl_update_busy_level(BTM_BLI_ACL_UP_EVT);
1213 }
1214 
1215 /*******************************************************************************
1216  *
1217  * Function         BTM_SetDefaultLinkSuperTout
1218  *
1219  * Description      Set the default value for HCI "Write Link Supervision
1220  *                                                 Timeout"
1221  *                  command to use when an ACL link is created.
1222  *
1223  * Returns          void
1224  *
1225  ******************************************************************************/
BTM_SetDefaultLinkSuperTout(uint16_t timeout)1226 void BTM_SetDefaultLinkSuperTout(uint16_t timeout) {
1227   BTM_TRACE_DEBUG("BTM_SetDefaultLinkSuperTout");
1228   btm_cb.btm_def_link_super_tout = timeout;
1229 }
1230 
1231 /*******************************************************************************
1232  *
1233  * Function         BTM_GetLinkSuperTout
1234  *
1235  * Description      Read the link supervision timeout value of the connection
1236  *
1237  * Returns          status of the operation
1238  *
1239  ******************************************************************************/
BTM_GetLinkSuperTout(const RawAddress & remote_bda,uint16_t * p_timeout)1240 tBTM_STATUS BTM_GetLinkSuperTout(const RawAddress& remote_bda,
1241                                  uint16_t* p_timeout) {
1242   tACL_CONN* p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
1243 
1244   BTM_TRACE_DEBUG("BTM_GetLinkSuperTout");
1245   if (p != (tACL_CONN*)NULL) {
1246     *p_timeout = p->link_super_tout;
1247     return (BTM_SUCCESS);
1248   }
1249   /* If here, no BD Addr found */
1250   return (BTM_UNKNOWN_ADDR);
1251 }
1252 
1253 /*******************************************************************************
1254  *
1255  * Function         BTM_SetLinkSuperTout
1256  *
1257  * Description      Create and send HCI "Write Link Supervision Timeout" command
1258  *
1259  * Returns          status of the operation
1260  *
1261  ******************************************************************************/
BTM_SetLinkSuperTout(const RawAddress & remote_bda,uint16_t timeout)1262 tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda,
1263                                  uint16_t timeout) {
1264   tACL_CONN* p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
1265 
1266   BTM_TRACE_DEBUG("BTM_SetLinkSuperTout");
1267   if (p != (tACL_CONN*)NULL) {
1268     p->link_super_tout = timeout;
1269 
1270     /* Only send if current role is Master; 2.0 spec requires this */
1271     if (p->link_role == BTM_ROLE_MASTER) {
1272       btsnd_hcic_write_link_super_tout(LOCAL_BR_EDR_CONTROLLER_ID,
1273                                        p->hci_handle, timeout);
1274       return (BTM_CMD_STARTED);
1275     } else {
1276       return (BTM_SUCCESS);
1277     }
1278   }
1279 
1280   /* If here, no BD Addr found */
1281   return (BTM_UNKNOWN_ADDR);
1282 }
1283 
1284 /*******************************************************************************
1285  *
1286  * Function         BTM_IsAclConnectionUp
1287  *
1288  * Description      This function is called to check if an ACL connection exists
1289  *                  to a specific remote BD Address.
1290  *
1291  * Returns          true if connection is up, else false.
1292  *
1293  ******************************************************************************/
BTM_IsAclConnectionUp(const RawAddress & remote_bda,tBT_TRANSPORT transport)1294 bool BTM_IsAclConnectionUp(const RawAddress& remote_bda,
1295                            tBT_TRANSPORT transport) {
1296   tACL_CONN* p;
1297 
1298   VLOG(2) << __func__ << " RemBdAddr: " << remote_bda;
1299 
1300   p = btm_bda_to_acl(remote_bda, transport);
1301   if (p != (tACL_CONN*)NULL) {
1302     return (true);
1303   }
1304 
1305   /* If here, no BD Addr found */
1306   return (false);
1307 }
1308 
1309 /*******************************************************************************
1310  *
1311  * Function         BTM_GetNumAclLinks
1312  *
1313  * Description      This function is called to count the number of
1314  *                  ACL links that are active.
1315  *
1316  * Returns          uint16_t Number of active ACL links
1317  *
1318  ******************************************************************************/
BTM_GetNumAclLinks(void)1319 uint16_t BTM_GetNumAclLinks(void) {
1320   uint16_t num_acl = 0;
1321 
1322   for (uint16_t i = 0; i < MAX_L2CAP_LINKS; ++i) {
1323     if (btm_cb.acl_db[i].in_use) ++num_acl;
1324   }
1325 
1326   return num_acl;
1327 }
1328 
1329 /*******************************************************************************
1330  *
1331  * Function         btm_get_acl_disc_reason_code
1332  *
1333  * Description      This function is called to get the disconnection reason code
1334  *                  returned by the HCI at disconnection complete event.
1335  *
1336  * Returns          true if connection is up, else false.
1337  *
1338  ******************************************************************************/
btm_get_acl_disc_reason_code(void)1339 uint16_t btm_get_acl_disc_reason_code(void) {
1340   uint8_t res = btm_cb.acl_disc_reason;
1341   BTM_TRACE_DEBUG("btm_get_acl_disc_reason_code");
1342   return (res);
1343 }
1344 
1345 /*******************************************************************************
1346  *
1347  * Function         BTM_GetHCIConnHandle
1348  *
1349  * Description      This function is called to get the handle for an ACL
1350  *                  connection to a specific remote BD Address.
1351  *
1352  * Returns          the handle of the connection, or 0xFFFF if none.
1353  *
1354  ******************************************************************************/
BTM_GetHCIConnHandle(const RawAddress & remote_bda,tBT_TRANSPORT transport)1355 uint16_t BTM_GetHCIConnHandle(const RawAddress& remote_bda,
1356                               tBT_TRANSPORT transport) {
1357   if (bluetooth::shim::is_gd_shim_enabled()) {
1358     return bluetooth::shim::BTM_GetHCIConnHandle(remote_bda, transport);
1359   }
1360 
1361   tACL_CONN* p;
1362   BTM_TRACE_DEBUG("BTM_GetHCIConnHandle");
1363   p = btm_bda_to_acl(remote_bda, transport);
1364   if (p != (tACL_CONN*)NULL) {
1365     return (p->hci_handle);
1366   }
1367 
1368   /* If here, no BD Addr found */
1369   return (0xFFFF);
1370 }
1371 
1372 /*******************************************************************************
1373  *
1374  * Function         btm_process_clk_off_comp_evt
1375  *
1376  * Description      This function is called when clock offset command completes.
1377  *
1378  * Input Parms      hci_handle - connection handle associated with the change
1379  *                  clock offset
1380  *
1381  * Returns          void
1382  *
1383  ******************************************************************************/
btm_process_clk_off_comp_evt(uint16_t hci_handle,uint16_t clock_offset)1384 void btm_process_clk_off_comp_evt(uint16_t hci_handle, uint16_t clock_offset) {
1385   uint8_t xx;
1386   BTM_TRACE_DEBUG("btm_process_clk_off_comp_evt");
1387   /* Look up the connection by handle and set the current mode */
1388   xx = btm_handle_to_acl_index(hci_handle);
1389   if (xx < MAX_L2CAP_LINKS) btm_cb.acl_db[xx].clock_offset = clock_offset;
1390 }
1391 
1392 /*******************************************************************************
1393 *
1394 * Function         btm_blacklist_role_change_device
1395 *
1396 * Description      This function is used to blacklist the device if the role
1397 *                  switch fails for maximum number of times. It also removes
1398 *                  the device from the black list if the role switch succeeds.
1399 *
1400 * Input Parms      bd_addr - remote BD addr
1401 *                  hci_status - role switch status
1402 *
1403 * Returns          void
1404 *
1405 *******************************************************************************/
btm_blacklist_role_change_device(const RawAddress & bd_addr,uint8_t hci_status)1406 void btm_blacklist_role_change_device(const RawAddress& bd_addr,
1407                                       uint8_t hci_status) {
1408   tACL_CONN* p = btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
1409   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1410 
1411   if (!p || !p_dev_rec) {
1412     return;
1413   }
1414   if (hci_status == HCI_SUCCESS) {
1415     p->switch_role_failed_attempts = 0;
1416     return;
1417   }
1418 
1419   /* check for carkits */
1420   const uint32_t cod_audio_device =
1421       (BTM_COD_SERVICE_AUDIO | BTM_COD_MAJOR_AUDIO) << 8;
1422   const uint32_t cod =
1423       ((p_dev_rec->dev_class[0] << 16) | (p_dev_rec->dev_class[1] << 8) |
1424        p_dev_rec->dev_class[2]) &
1425       0xffffff;
1426   if ((hci_status != HCI_SUCCESS) &&
1427       ((p->switch_role_state == BTM_ACL_SWKEY_STATE_SWITCHING) ||
1428        (p->switch_role_state == BTM_ACL_SWKEY_STATE_IN_PROGRESS)) &&
1429       ((cod & cod_audio_device) == cod_audio_device) &&
1430       (!interop_match_addr(INTEROP_DYNAMIC_ROLE_SWITCH, &bd_addr))) {
1431     p->switch_role_failed_attempts++;
1432     if (p->switch_role_failed_attempts == BTM_MAX_SW_ROLE_FAILED_ATTEMPTS) {
1433       BTM_TRACE_WARNING(
1434           "%s: Device %s blacklisted for role switching - "
1435           "multiple role switch failed attempts: %u",
1436           __func__, bd_addr.ToString().c_str(), p->switch_role_failed_attempts);
1437       interop_database_add(INTEROP_DYNAMIC_ROLE_SWITCH, &bd_addr, 3);
1438     }
1439   }
1440 }
1441 
1442 /*******************************************************************************
1443  *
1444  * Function         btm_acl_role_changed
1445  *
1446  * Description      This function is called whan a link's master/slave role
1447  *                  change event or command status event (with error) is
1448  *                  received. It updates the link control block, and calls the
1449  *                  registered callback with status and role (if registered).
1450  *
1451  * Returns          void
1452  *
1453  ******************************************************************************/
btm_acl_role_changed(uint8_t hci_status,const RawAddress * bd_addr,uint8_t new_role)1454 void btm_acl_role_changed(uint8_t hci_status, const RawAddress* bd_addr,
1455                           uint8_t new_role) {
1456   const RawAddress* p_bda =
1457       (bd_addr) ? bd_addr : &btm_cb.devcb.switch_role_ref_data.remote_bd_addr;
1458   tACL_CONN* p = btm_bda_to_acl(*p_bda, BT_TRANSPORT_BR_EDR);
1459   tBTM_ROLE_SWITCH_CMPL* p_data = &btm_cb.devcb.switch_role_ref_data;
1460   tBTM_SEC_DEV_REC* p_dev_rec;
1461 
1462   BTM_TRACE_DEBUG("%s: peer %s hci_status:0x%x new_role:%d", __func__,
1463                   (p_bda != nullptr) ? bd_addr->ToString().c_str() : "nullptr",
1464                   hci_status, new_role);
1465   /* Ignore any stray events */
1466   if (p == NULL) {
1467     /* it could be a failure */
1468     if (hci_status != HCI_SUCCESS)
1469       btm_acl_report_role_change(hci_status, bd_addr);
1470     return;
1471   }
1472 
1473   p_data->hci_status = hci_status;
1474 
1475   if (hci_status == HCI_SUCCESS) {
1476     p_data->role = new_role;
1477     p_data->remote_bd_addr = *p_bda;
1478 
1479     /* Update cached value */
1480     p->link_role = new_role;
1481 
1482     /* Reload LSTO: link supervision timeout is reset in the LM after a role
1483      * switch */
1484     if (new_role == BTM_ROLE_MASTER) {
1485       BTM_SetLinkSuperTout(p->remote_addr, p->link_super_tout);
1486     }
1487   } else {
1488     /* so the BTM_BL_ROLE_CHG_EVT uses the old role */
1489     new_role = p->link_role;
1490   }
1491 
1492   /* Check if any SCO req is pending for role change */
1493   btm_sco_chk_pend_rolechange(p->hci_handle);
1494 
1495   /* if switching state is switching we need to turn encryption on */
1496   /* if idle, we did not change encryption */
1497   if (p->switch_role_state == BTM_ACL_SWKEY_STATE_SWITCHING) {
1498     btsnd_hcic_set_conn_encrypt(p->hci_handle, true);
1499     p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_ON;
1500     p->switch_role_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_ON;
1501     return;
1502   }
1503 
1504   /* Set the switch_role_state to IDLE since the reply received from HCI */
1505   /* regardless of its result either success or failed. */
1506   if (p->switch_role_state == BTM_ACL_SWKEY_STATE_IN_PROGRESS) {
1507     p->switch_role_state = BTM_ACL_SWKEY_STATE_IDLE;
1508     p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
1509   }
1510 
1511   /* if role switch complete is needed, report it now */
1512   btm_acl_report_role_change(hci_status, bd_addr);
1513 
1514   /* if role change event is registered, report it now */
1515   if (btm_cb.p_bl_changed_cb && (btm_cb.bl_evt_mask & BTM_BL_ROLE_CHG_MASK)) {
1516     tBTM_BL_ROLE_CHG_DATA evt;
1517     evt.event = BTM_BL_ROLE_CHG_EVT;
1518     evt.new_role = new_role;
1519     evt.p_bda = p_bda;
1520     evt.hci_status = hci_status;
1521     tBTM_BL_EVENT_DATA btm_bl_event_data;
1522     btm_bl_event_data.role_chg = evt;
1523     (*btm_cb.p_bl_changed_cb)(&btm_bl_event_data);
1524   }
1525 
1526   BTM_TRACE_DEBUG(
1527       "%s: peer %s Role Switch Event: new_role 0x%02x, HCI Status 0x%02x, "
1528       "rs_st:%d",
1529       __func__, (p_bda != nullptr) ? p_bda->ToString().c_str() : "nullptr",
1530       p_data->role, p_data->hci_status, p->switch_role_state);
1531 
1532 #if (BTM_DISC_DURING_RS == TRUE)
1533   /* If a disconnect is pending, issue it now that role switch has completed */
1534   p_dev_rec = btm_find_dev(*p_bda);
1535   if (p_dev_rec != NULL) {
1536     if (p_dev_rec->rs_disc_pending == BTM_SEC_DISC_PENDING) {
1537       BTM_TRACE_WARNING(
1538           "%s peer %s Issuing delayed HCI_Disconnect!!!", __func__,
1539           (p_bda != nullptr) ? p_bda->ToString().c_str() : "nullptr");
1540       btsnd_hcic_disconnect(p_dev_rec->hci_handle, HCI_ERR_PEER_USER);
1541     }
1542     BTM_TRACE_ERROR("%s: peer %s tBTM_SEC_DEV:0x%x rs_disc_pending=%d",
1543                     __func__,
1544                     (p_bda != nullptr) ? p_bda->ToString().c_str() : "nullptr",
1545                     PTR_TO_UINT(p_dev_rec), p_dev_rec->rs_disc_pending);
1546     p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
1547   }
1548 
1549 #endif
1550 }
1551 
1552 /*******************************************************************************
1553  *
1554  * Function         BTM_AllocateSCN
1555  *
1556  * Description      Look through the Server Channel Numbers for a free one.
1557  *
1558  * Returns          Allocated SCN number or 0 if none.
1559  *
1560  ******************************************************************************/
1561 
BTM_AllocateSCN(void)1562 uint8_t BTM_AllocateSCN(void) {
1563   uint8_t x;
1564   BTM_TRACE_DEBUG("BTM_AllocateSCN");
1565 
1566   // stack reserves scn 1 for HFP, HSP we still do the correct way
1567   for (x = 1; x < BTM_MAX_SCN; x++) {
1568     if (!btm_cb.btm_scn[x]) {
1569       btm_cb.btm_scn[x] = true;
1570       return (x + 1);
1571     }
1572   }
1573 
1574   return (0); /* No free ports */
1575 }
1576 
1577 /*******************************************************************************
1578  *
1579  * Function         BTM_TryAllocateSCN
1580  *
1581  * Description      Try to allocate a fixed server channel
1582  *
1583  * Returns          Returns true if server channel was available
1584  *
1585  ******************************************************************************/
1586 
BTM_TryAllocateSCN(uint8_t scn)1587 bool BTM_TryAllocateSCN(uint8_t scn) {
1588   /* Make sure we don't exceed max port range.
1589    * Stack reserves scn 1 for HFP, HSP we still do the correct way.
1590    */
1591   if ((scn >= BTM_MAX_SCN) || (scn == 1)) return false;
1592 
1593   /* check if this port is available */
1594   if (!btm_cb.btm_scn[scn - 1]) {
1595     btm_cb.btm_scn[scn - 1] = true;
1596     return true;
1597   }
1598 
1599   return (false); /* Port was busy */
1600 }
1601 
1602 /*******************************************************************************
1603  *
1604  * Function         BTM_FreeSCN
1605  *
1606  * Description      Free the specified SCN.
1607  *
1608  * Returns          true or false
1609  *
1610  ******************************************************************************/
BTM_FreeSCN(uint8_t scn)1611 bool BTM_FreeSCN(uint8_t scn) {
1612   BTM_TRACE_DEBUG("BTM_FreeSCN ");
1613   if (scn <= BTM_MAX_SCN) {
1614     btm_cb.btm_scn[scn - 1] = false;
1615     return (true);
1616   } else {
1617     return (false); /* Illegal SCN passed in */
1618   }
1619 }
1620 
1621 /*******************************************************************************
1622  *
1623  * Function         btm_set_packet_types
1624  *
1625  * Description      This function sets the packet types used for a specific
1626  *                  ACL connection. It is called internally by btm_acl_created
1627  *                  or by an application/profile by BTM_SetPacketTypes.
1628  *
1629  * Returns          status of the operation
1630  *
1631  ******************************************************************************/
btm_set_packet_types(tACL_CONN * p,uint16_t pkt_types)1632 tBTM_STATUS btm_set_packet_types(tACL_CONN* p, uint16_t pkt_types) {
1633   uint16_t temp_pkt_types;
1634   BTM_TRACE_DEBUG("btm_set_packet_types");
1635   /* Save in the ACL control blocks, types that we support */
1636   temp_pkt_types = (pkt_types & BTM_ACL_SUPPORTED_PKTS_MASK &
1637                     btm_cb.btm_acl_pkt_types_supported);
1638 
1639   /* OR in any exception packet types if at least 2.0 version of spec */
1640   temp_pkt_types |=
1641       ((pkt_types & BTM_ACL_EXCEPTION_PKTS_MASK) |
1642        (btm_cb.btm_acl_pkt_types_supported & BTM_ACL_EXCEPTION_PKTS_MASK));
1643 
1644   /* Exclude packet types not supported by the peer */
1645   btm_acl_chk_peer_pkt_type_support(p, &temp_pkt_types);
1646 
1647   BTM_TRACE_DEBUG("SetPacketType Mask -> 0x%04x", temp_pkt_types);
1648 
1649   btsnd_hcic_change_conn_type(p->hci_handle, temp_pkt_types);
1650   p->pkt_types_mask = temp_pkt_types;
1651 
1652   return (BTM_CMD_STARTED);
1653 }
1654 
1655 /*******************************************************************************
1656  *
1657  * Function         btm_get_max_packet_size
1658  *
1659  * Returns          Returns maximum packet size that can be used for current
1660  *                  connection, 0 if connection is not established
1661  *
1662  ******************************************************************************/
btm_get_max_packet_size(const RawAddress & addr)1663 uint16_t btm_get_max_packet_size(const RawAddress& addr) {
1664   tACL_CONN* p = btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1665   uint16_t pkt_types = 0;
1666   uint16_t pkt_size = 0;
1667   BTM_TRACE_DEBUG("btm_get_max_packet_size");
1668   if (p != NULL) {
1669     pkt_types = p->pkt_types_mask;
1670   } else {
1671     /* Special case for when info for the local device is requested */
1672     if (addr == *controller_get_interface()->get_address()) {
1673       pkt_types = btm_cb.btm_acl_pkt_types_supported;
1674     }
1675   }
1676 
1677   if (pkt_types) {
1678     if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_3_DH5))
1679       pkt_size = HCI_EDR3_DH5_PACKET_SIZE;
1680     else if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_2_DH5))
1681       pkt_size = HCI_EDR2_DH5_PACKET_SIZE;
1682     else if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_3_DH3))
1683       pkt_size = HCI_EDR3_DH3_PACKET_SIZE;
1684     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DH5)
1685       pkt_size = HCI_DH5_PACKET_SIZE;
1686     else if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_2_DH3))
1687       pkt_size = HCI_EDR2_DH3_PACKET_SIZE;
1688     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DM5)
1689       pkt_size = HCI_DM5_PACKET_SIZE;
1690     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DH3)
1691       pkt_size = HCI_DH3_PACKET_SIZE;
1692     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DM3)
1693       pkt_size = HCI_DM3_PACKET_SIZE;
1694     else if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_3_DH1))
1695       pkt_size = HCI_EDR3_DH1_PACKET_SIZE;
1696     else if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_2_DH1))
1697       pkt_size = HCI_EDR2_DH1_PACKET_SIZE;
1698     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DH1)
1699       pkt_size = HCI_DH1_PACKET_SIZE;
1700     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DM1)
1701       pkt_size = HCI_DM1_PACKET_SIZE;
1702   }
1703 
1704   return (pkt_size);
1705 }
1706 
1707 /*******************************************************************************
1708  *
1709  * Function         BTM_ReadRemoteVersion
1710  *
1711  * Returns          If connected report peer device info
1712  *
1713  ******************************************************************************/
BTM_ReadRemoteVersion(const RawAddress & addr,uint8_t * lmp_version,uint16_t * manufacturer,uint16_t * lmp_sub_version)1714 tBTM_STATUS BTM_ReadRemoteVersion(const RawAddress& addr, uint8_t* lmp_version,
1715                                   uint16_t* manufacturer,
1716                                   uint16_t* lmp_sub_version) {
1717   tACL_CONN* p = btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1718   BTM_TRACE_DEBUG("BTM_ReadRemoteVersion");
1719   if (p == NULL) return (BTM_UNKNOWN_ADDR);
1720 
1721   if (lmp_version) *lmp_version = p->lmp_version;
1722 
1723   if (manufacturer) *manufacturer = p->manufacturer;
1724 
1725   if (lmp_sub_version) *lmp_sub_version = p->lmp_subversion;
1726 
1727   return (BTM_SUCCESS);
1728 }
1729 
1730 /*******************************************************************************
1731  *
1732  * Function         BTM_ReadRemoteFeatures
1733  *
1734  * Returns          pointer to the remote supported features mask (8 bytes)
1735  *
1736  ******************************************************************************/
BTM_ReadRemoteFeatures(const RawAddress & addr)1737 uint8_t* BTM_ReadRemoteFeatures(const RawAddress& addr) {
1738   tACL_CONN* p = btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1739   BTM_TRACE_DEBUG("BTM_ReadRemoteFeatures");
1740   if (p == NULL) {
1741     return (NULL);
1742   }
1743 
1744   return (p->peer_lmp_feature_pages[0]);
1745 }
1746 
1747 /*******************************************************************************
1748  *
1749  * Function         BTM_RegBusyLevelNotif
1750  *
1751  * Description      This function is called to register a callback to receive
1752  *                  busy level change events.
1753  *
1754  * Returns          BTM_SUCCESS if successfully registered, otherwise error
1755  *
1756  ******************************************************************************/
BTM_RegBusyLevelNotif(tBTM_BL_CHANGE_CB * p_cb,uint8_t * p_level,tBTM_BL_EVENT_MASK evt_mask)1757 tBTM_STATUS BTM_RegBusyLevelNotif(tBTM_BL_CHANGE_CB* p_cb, uint8_t* p_level,
1758                                   tBTM_BL_EVENT_MASK evt_mask) {
1759   BTM_TRACE_DEBUG("BTM_RegBusyLevelNotif");
1760   if (p_level) *p_level = btm_cb.busy_level;
1761 
1762   btm_cb.bl_evt_mask = evt_mask;
1763 
1764   if (!p_cb)
1765     btm_cb.p_bl_changed_cb = NULL;
1766   else if (btm_cb.p_bl_changed_cb)
1767     return (BTM_BUSY);
1768   else
1769     btm_cb.p_bl_changed_cb = p_cb;
1770 
1771   return (BTM_SUCCESS);
1772 }
1773 
1774 /*******************************************************************************
1775  *
1776  * Function         btm_qos_setup_timeout
1777  *
1778  * Description      Callback when QoS setup times out.
1779  *
1780  * Returns          void
1781  *
1782  ******************************************************************************/
btm_qos_setup_timeout(UNUSED_ATTR void * data)1783 void btm_qos_setup_timeout(UNUSED_ATTR void* data) {
1784   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_qos_setup_cmpl_cb;
1785   btm_cb.devcb.p_qos_setup_cmpl_cb = NULL;
1786   if (p_cb) (*p_cb)((void*)NULL);
1787 }
1788 
1789 /*******************************************************************************
1790  *
1791  * Function         btm_qos_setup_complete
1792  *
1793  * Description      This function is called when the command complete message
1794  *                  is received from the HCI for the qos setup request.
1795  *
1796  * Returns          void
1797  *
1798  ******************************************************************************/
btm_qos_setup_complete(uint8_t status,uint16_t handle,FLOW_SPEC * p_flow)1799 void btm_qos_setup_complete(uint8_t status, uint16_t handle,
1800                             FLOW_SPEC* p_flow) {
1801   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_qos_setup_cmpl_cb;
1802   tBTM_QOS_SETUP_CMPL qossu;
1803 
1804   BTM_TRACE_DEBUG("%s", __func__);
1805   alarm_cancel(btm_cb.devcb.qos_setup_timer);
1806   btm_cb.devcb.p_qos_setup_cmpl_cb = NULL;
1807 
1808   /* If there was a registered callback, call it */
1809   if (p_cb) {
1810     memset(&qossu, 0, sizeof(tBTM_QOS_SETUP_CMPL));
1811     qossu.status = status;
1812     qossu.handle = handle;
1813     if (p_flow != NULL) {
1814       qossu.flow.qos_flags = p_flow->qos_flags;
1815       qossu.flow.service_type = p_flow->service_type;
1816       qossu.flow.token_rate = p_flow->token_rate;
1817       qossu.flow.peak_bandwidth = p_flow->peak_bandwidth;
1818       qossu.flow.latency = p_flow->latency;
1819       qossu.flow.delay_variation = p_flow->delay_variation;
1820     }
1821     BTM_TRACE_DEBUG("BTM: p_flow->delay_variation: 0x%02x",
1822                     qossu.flow.delay_variation);
1823     (*p_cb)(&qossu);
1824   }
1825 }
1826 
1827 /*******************************************************************************
1828  *
1829  * Function         BTM_ReadRSSI
1830  *
1831  * Description      This function is called to read the link policy settings.
1832  *                  The address of link policy results are returned in the
1833  *                  callback.
1834  *                  (tBTM_RSSI_RESULT)
1835  *
1836  * Returns          BTM_CMD_STARTED if successfully initiated or error code
1837  *
1838  ******************************************************************************/
BTM_ReadRSSI(const RawAddress & remote_bda,tBTM_CMPL_CB * p_cb)1839 tBTM_STATUS BTM_ReadRSSI(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb) {
1840   tACL_CONN* p = NULL;
1841   tBT_DEVICE_TYPE dev_type;
1842   tBLE_ADDR_TYPE addr_type;
1843 
1844   /* If someone already waiting on the version, do not allow another */
1845   if (btm_cb.devcb.p_rssi_cmpl_cb) return (BTM_BUSY);
1846 
1847   BTM_ReadDevInfo(remote_bda, &dev_type, &addr_type);
1848 
1849   if (dev_type & BT_DEVICE_TYPE_BLE) {
1850     p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE);
1851   }
1852 
1853   if (p == NULL && dev_type & BT_DEVICE_TYPE_BREDR) {
1854     p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
1855   }
1856 
1857   if (p) {
1858     btm_cb.devcb.p_rssi_cmpl_cb = p_cb;
1859     alarm_set_on_mloop(btm_cb.devcb.read_rssi_timer, BTM_DEV_REPLY_TIMEOUT_MS,
1860                        btm_read_rssi_timeout, NULL);
1861 
1862     btsnd_hcic_read_rssi(p->hci_handle);
1863     return (BTM_CMD_STARTED);
1864   }
1865 
1866   /* If here, no BD Addr found */
1867   return (BTM_UNKNOWN_ADDR);
1868 }
1869 
1870 /*******************************************************************************
1871  *
1872  * Function         BTM_ReadFailedContactCounter
1873  *
1874  * Description      This function is called to read the failed contact counter.
1875  *                  The result is returned in the callback.
1876  *                  (tBTM_FAILED_CONTACT_COUNTER_RESULT)
1877  *
1878  * Returns          BTM_CMD_STARTED if successfully initiated or error code
1879  *
1880  ******************************************************************************/
BTM_ReadFailedContactCounter(const RawAddress & remote_bda,tBTM_CMPL_CB * p_cb)1881 tBTM_STATUS BTM_ReadFailedContactCounter(const RawAddress& remote_bda,
1882                                          tBTM_CMPL_CB* p_cb) {
1883   tACL_CONN* p;
1884   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1885   tBT_DEVICE_TYPE dev_type;
1886   tBLE_ADDR_TYPE addr_type;
1887 
1888   /* If someone already waiting on the result, do not allow another */
1889   if (btm_cb.devcb.p_failed_contact_counter_cmpl_cb) return (BTM_BUSY);
1890 
1891   BTM_ReadDevInfo(remote_bda, &dev_type, &addr_type);
1892   if (dev_type == BT_DEVICE_TYPE_BLE) transport = BT_TRANSPORT_LE;
1893 
1894   p = btm_bda_to_acl(remote_bda, transport);
1895   if (p != (tACL_CONN*)NULL) {
1896     btm_cb.devcb.p_failed_contact_counter_cmpl_cb = p_cb;
1897     alarm_set_on_mloop(btm_cb.devcb.read_failed_contact_counter_timer,
1898                        BTM_DEV_REPLY_TIMEOUT_MS,
1899                        btm_read_failed_contact_counter_timeout, NULL);
1900 
1901     btsnd_hcic_read_failed_contact_counter(p->hci_handle);
1902     return (BTM_CMD_STARTED);
1903   }
1904 
1905   /* If here, no BD Addr found */
1906   return (BTM_UNKNOWN_ADDR);
1907 }
1908 
1909 /*******************************************************************************
1910  *
1911  * Function         BTM_ReadAutomaticFlushTimeout
1912  *
1913  * Description      This function is called to read the automatic flush timeout.
1914  *                  The result is returned in the callback.
1915  *                  (tBTM_AUTOMATIC_FLUSH_TIMEOUT_RESULT)
1916  *
1917  * Returns          BTM_CMD_STARTED if successfully initiated or error code
1918  *
1919  ******************************************************************************/
BTM_ReadAutomaticFlushTimeout(const RawAddress & remote_bda,tBTM_CMPL_CB * p_cb)1920 tBTM_STATUS BTM_ReadAutomaticFlushTimeout(const RawAddress& remote_bda,
1921                                           tBTM_CMPL_CB* p_cb) {
1922   tACL_CONN* p;
1923   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1924   tBT_DEVICE_TYPE dev_type;
1925   tBLE_ADDR_TYPE addr_type;
1926 
1927   /* If someone already waiting on the result, do not allow another */
1928   if (btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb) return (BTM_BUSY);
1929 
1930   BTM_ReadDevInfo(remote_bda, &dev_type, &addr_type);
1931   if (dev_type == BT_DEVICE_TYPE_BLE) transport = BT_TRANSPORT_LE;
1932 
1933   p = btm_bda_to_acl(remote_bda, transport);
1934   if (!p) return BTM_UNKNOWN_ADDR;
1935 
1936   btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb = p_cb;
1937   alarm_set_on_mloop(btm_cb.devcb.read_automatic_flush_timeout_timer,
1938                      BTM_DEV_REPLY_TIMEOUT_MS,
1939                      btm_read_automatic_flush_timeout_timeout, nullptr);
1940 
1941   btsnd_hcic_read_automatic_flush_timeout(p->hci_handle);
1942   return BTM_CMD_STARTED;
1943 }
1944 
1945 /*******************************************************************************
1946  *
1947  * Function         BTM_ReadTxPower
1948  *
1949  * Description      This function is called to read the current
1950  *                  TX power of the connection. The tx power level results
1951  *                  are returned in the callback.
1952  *                  (tBTM_RSSI_RESULT)
1953  *
1954  * Returns          BTM_CMD_STARTED if successfully initiated or error code
1955  *
1956  ******************************************************************************/
BTM_ReadTxPower(const RawAddress & remote_bda,tBT_TRANSPORT transport,tBTM_CMPL_CB * p_cb)1957 tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda,
1958                             tBT_TRANSPORT transport, tBTM_CMPL_CB* p_cb) {
1959   tACL_CONN* p;
1960 #define BTM_READ_RSSI_TYPE_CUR 0x00
1961 #define BTM_READ_RSSI_TYPE_MAX 0X01
1962 
1963   VLOG(2) << __func__ << ": RemBdAddr: " << remote_bda;
1964 
1965   /* If someone already waiting on the version, do not allow another */
1966   if (btm_cb.devcb.p_tx_power_cmpl_cb) return (BTM_BUSY);
1967 
1968   p = btm_bda_to_acl(remote_bda, transport);
1969   if (p != (tACL_CONN*)NULL) {
1970     btm_cb.devcb.p_tx_power_cmpl_cb = p_cb;
1971     alarm_set_on_mloop(btm_cb.devcb.read_tx_power_timer,
1972                        BTM_DEV_REPLY_TIMEOUT_MS, btm_read_tx_power_timeout,
1973                        NULL);
1974 
1975     if (p->transport == BT_TRANSPORT_LE) {
1976       btm_cb.devcb.read_tx_pwr_addr = remote_bda;
1977       btsnd_hcic_ble_read_adv_chnl_tx_power();
1978     } else {
1979       btsnd_hcic_read_tx_power(p->hci_handle, BTM_READ_RSSI_TYPE_CUR);
1980     }
1981 
1982     return (BTM_CMD_STARTED);
1983   }
1984 
1985   /* If here, no BD Addr found */
1986   return (BTM_UNKNOWN_ADDR);
1987 }
1988 
1989 /*******************************************************************************
1990  *
1991  * Function         btm_read_tx_power_timeout
1992  *
1993  * Description      Callback when reading the tx power times out.
1994  *
1995  * Returns          void
1996  *
1997  ******************************************************************************/
btm_read_tx_power_timeout(UNUSED_ATTR void * data)1998 void btm_read_tx_power_timeout(UNUSED_ATTR void* data) {
1999   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_tx_power_cmpl_cb;
2000   btm_cb.devcb.p_tx_power_cmpl_cb = NULL;
2001   if (p_cb) (*p_cb)((void*)NULL);
2002 }
2003 
2004 /*******************************************************************************
2005  *
2006  * Function         btm_read_tx_power_complete
2007  *
2008  * Description      This function is called when the command complete message
2009  *                  is received from the HCI for the read tx power request.
2010  *
2011  * Returns          void
2012  *
2013  ******************************************************************************/
btm_read_tx_power_complete(uint8_t * p,bool is_ble)2014 void btm_read_tx_power_complete(uint8_t* p, bool is_ble) {
2015   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_tx_power_cmpl_cb;
2016   tBTM_TX_POWER_RESULT result;
2017   tACL_CONN* p_acl_cb = &btm_cb.acl_db[0];
2018 
2019   BTM_TRACE_DEBUG("%s", __func__);
2020   alarm_cancel(btm_cb.devcb.read_tx_power_timer);
2021   btm_cb.devcb.p_tx_power_cmpl_cb = NULL;
2022 
2023   /* If there was a registered callback, call it */
2024   if (p_cb) {
2025     STREAM_TO_UINT8(result.hci_status, p);
2026 
2027     if (result.hci_status == HCI_SUCCESS) {
2028       result.status = BTM_SUCCESS;
2029 
2030       if (!is_ble) {
2031         uint16_t handle;
2032         STREAM_TO_UINT16(handle, p);
2033         STREAM_TO_UINT8(result.tx_power, p);
2034 
2035         /* Search through the list of active channels for the correct BD Addr */
2036         for (uint16_t index = 0; index < MAX_L2CAP_LINKS; index++, p_acl_cb++) {
2037           if ((p_acl_cb->in_use) && (handle == p_acl_cb->hci_handle)) {
2038             result.rem_bda = p_acl_cb->remote_addr;
2039             break;
2040           }
2041         }
2042       } else {
2043         STREAM_TO_UINT8(result.tx_power, p);
2044         result.rem_bda = btm_cb.devcb.read_tx_pwr_addr;
2045       }
2046       BTM_TRACE_DEBUG("BTM TX power Complete: tx_power %d, hci status 0x%02x",
2047                       result.tx_power, result.hci_status);
2048     } else {
2049       result.status = BTM_ERR_PROCESSING;
2050     }
2051 
2052     (*p_cb)(&result);
2053   }
2054 }
2055 
2056 /*******************************************************************************
2057  *
2058  * Function         btm_read_rssi_timeout
2059  *
2060  * Description      Callback when reading the RSSI times out.
2061  *
2062  * Returns          void
2063  *
2064  ******************************************************************************/
btm_read_rssi_timeout(UNUSED_ATTR void * data)2065 void btm_read_rssi_timeout(UNUSED_ATTR void* data) {
2066   tBTM_RSSI_RESULT result;
2067   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_rssi_cmpl_cb;
2068   btm_cb.devcb.p_rssi_cmpl_cb = NULL;
2069   result.status = BTM_DEVICE_TIMEOUT;
2070   if (p_cb) (*p_cb)(&result);
2071 }
2072 
2073 /*******************************************************************************
2074  *
2075  * Function         btm_read_rssi_complete
2076  *
2077  * Description      This function is called when the command complete message
2078  *                  is received from the HCI for the read rssi request.
2079  *
2080  * Returns          void
2081  *
2082  ******************************************************************************/
btm_read_rssi_complete(uint8_t * p)2083 void btm_read_rssi_complete(uint8_t* p) {
2084   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_rssi_cmpl_cb;
2085   tBTM_RSSI_RESULT result;
2086   tACL_CONN* p_acl_cb = &btm_cb.acl_db[0];
2087 
2088   BTM_TRACE_DEBUG("%s", __func__);
2089   alarm_cancel(btm_cb.devcb.read_rssi_timer);
2090   btm_cb.devcb.p_rssi_cmpl_cb = NULL;
2091 
2092   /* If there was a registered callback, call it */
2093   if (p_cb) {
2094     STREAM_TO_UINT8(result.hci_status, p);
2095 
2096     if (result.hci_status == HCI_SUCCESS) {
2097       uint16_t handle;
2098       result.status = BTM_SUCCESS;
2099 
2100       STREAM_TO_UINT16(handle, p);
2101 
2102       STREAM_TO_UINT8(result.rssi, p);
2103       BTM_TRACE_DEBUG("BTM RSSI Complete: rssi %d, hci status 0x%02x",
2104                       result.rssi, result.hci_status);
2105 
2106       /* Search through the list of active channels for the correct BD Addr */
2107       for (uint16_t index = 0; index < MAX_L2CAP_LINKS; index++, p_acl_cb++) {
2108         if ((p_acl_cb->in_use) && (handle == p_acl_cb->hci_handle)) {
2109           result.rem_bda = p_acl_cb->remote_addr;
2110           break;
2111         }
2112       }
2113     } else {
2114       result.status = BTM_ERR_PROCESSING;
2115     }
2116 
2117     (*p_cb)(&result);
2118   }
2119 }
2120 
2121 /*******************************************************************************
2122  *
2123  * Function         btm_read_failed_contact_counter_timeout
2124  *
2125  * Description      Callback when reading the failed contact counter times out.
2126  *
2127  * Returns          void
2128  *
2129  ******************************************************************************/
btm_read_failed_contact_counter_timeout(UNUSED_ATTR void * data)2130 void btm_read_failed_contact_counter_timeout(UNUSED_ATTR void* data) {
2131   tBTM_FAILED_CONTACT_COUNTER_RESULT result;
2132   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_failed_contact_counter_cmpl_cb;
2133   btm_cb.devcb.p_failed_contact_counter_cmpl_cb = NULL;
2134   result.status = BTM_DEVICE_TIMEOUT;
2135   if (p_cb) (*p_cb)(&result);
2136 }
2137 
2138 /*******************************************************************************
2139  *
2140  * Function         btm_read_failed_contact_counter_complete
2141  *
2142  * Description      This function is called when the command complete message
2143  *                  is received from the HCI for the read failed contact
2144  *                  counter request.
2145  *
2146  * Returns          void
2147  *
2148  ******************************************************************************/
btm_read_failed_contact_counter_complete(uint8_t * p)2149 void btm_read_failed_contact_counter_complete(uint8_t* p) {
2150   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_failed_contact_counter_cmpl_cb;
2151   tBTM_FAILED_CONTACT_COUNTER_RESULT result;
2152   tACL_CONN* p_acl_cb = &btm_cb.acl_db[0];
2153 
2154   BTM_TRACE_DEBUG("%s", __func__);
2155   alarm_cancel(btm_cb.devcb.read_failed_contact_counter_timer);
2156   btm_cb.devcb.p_failed_contact_counter_cmpl_cb = NULL;
2157 
2158   /* If there was a registered callback, call it */
2159   if (p_cb) {
2160     uint16_t handle;
2161     STREAM_TO_UINT8(result.hci_status, p);
2162 
2163     if (result.hci_status == HCI_SUCCESS) {
2164       result.status = BTM_SUCCESS;
2165 
2166       STREAM_TO_UINT16(handle, p);
2167 
2168       STREAM_TO_UINT16(result.failed_contact_counter, p);
2169       BTM_TRACE_DEBUG(
2170           "BTM Failed Contact Counter Complete: counter %u, hci status 0x%02x",
2171           result.failed_contact_counter, result.hci_status);
2172 
2173       /* Search through the list of active channels for the correct BD Addr */
2174       for (uint16_t index = 0; index < MAX_L2CAP_LINKS; index++, p_acl_cb++) {
2175         if ((p_acl_cb->in_use) && (handle == p_acl_cb->hci_handle)) {
2176           result.rem_bda = p_acl_cb->remote_addr;
2177           break;
2178         }
2179       }
2180     } else {
2181       result.status = BTM_ERR_PROCESSING;
2182     }
2183 
2184     (*p_cb)(&result);
2185   }
2186 }
2187 
2188 /*******************************************************************************
2189  *
2190  * Function         btm_read_automatic_flush_timeout_timeout
2191  *
2192  * Description      Callback when reading the automatic flush timeout times out.
2193  *
2194  * Returns          void
2195  *
2196  ******************************************************************************/
btm_read_automatic_flush_timeout_timeout(UNUSED_ATTR void * data)2197 void btm_read_automatic_flush_timeout_timeout(UNUSED_ATTR void* data) {
2198   tBTM_AUTOMATIC_FLUSH_TIMEOUT_RESULT result;
2199   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb;
2200   btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb = nullptr;
2201   result.status = BTM_DEVICE_TIMEOUT;
2202   if (p_cb) (*p_cb)(&result);
2203 }
2204 
2205 /*******************************************************************************
2206  *
2207  * Function         btm_read_automatic_flush_timeout_complete
2208  *
2209  * Description      This function is called when the command complete message
2210  *                  is received from the HCI for the read automatic flush
2211  *                  timeout request.
2212  *
2213  * Returns          void
2214  *
2215  ******************************************************************************/
btm_read_automatic_flush_timeout_complete(uint8_t * p)2216 void btm_read_automatic_flush_timeout_complete(uint8_t* p) {
2217   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb;
2218   tBTM_AUTOMATIC_FLUSH_TIMEOUT_RESULT result;
2219   tACL_CONN* p_acl_cb = &btm_cb.acl_db[0];
2220 
2221   BTM_TRACE_DEBUG("%s", __func__);
2222   alarm_cancel(btm_cb.devcb.read_automatic_flush_timeout_timer);
2223   btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb = nullptr;
2224 
2225   /* If there was a registered callback, call it */
2226   if (p_cb) {
2227     uint16_t handle;
2228     STREAM_TO_UINT8(result.hci_status, p);
2229 
2230     if (result.hci_status == HCI_SUCCESS) {
2231       result.status = BTM_SUCCESS;
2232 
2233       STREAM_TO_UINT16(handle, p);
2234 
2235       STREAM_TO_UINT16(result.automatic_flush_timeout, p);
2236       BTM_TRACE_DEBUG(
2237           "BTM Automatic Flush Timeout Complete: timeout %u, hci status 0x%02x",
2238           result.automatic_flush_timeout, result.hci_status);
2239 
2240       /* Search through the list of active channels for the correct BD Addr */
2241       for (uint16_t index = 0; index < MAX_L2CAP_LINKS; index++, p_acl_cb++) {
2242         if ((p_acl_cb->in_use) && (handle == p_acl_cb->hci_handle)) {
2243           result.rem_bda = p_acl_cb->remote_addr;
2244           break;
2245         }
2246       }
2247     } else {
2248       result.status = BTM_ERR_PROCESSING;
2249     }
2250 
2251     (*p_cb)(&result);
2252   }
2253 }
2254 
2255 /*******************************************************************************
2256  *
2257  * Function         btm_read_link_quality_timeout
2258  *
2259  * Description      Callback when reading the link quality times out.
2260  *
2261  * Returns          void
2262  *
2263  ******************************************************************************/
btm_read_link_quality_timeout(UNUSED_ATTR void * data)2264 void btm_read_link_quality_timeout(UNUSED_ATTR void* data) {
2265   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_link_qual_cmpl_cb;
2266   btm_cb.devcb.p_link_qual_cmpl_cb = NULL;
2267   if (p_cb) (*p_cb)((void*)NULL);
2268 }
2269 
2270 /*******************************************************************************
2271  *
2272  * Function         btm_read_link_quality_complete
2273  *
2274  * Description      This function is called when the command complete message
2275  *                  is received from the HCI for the read link quality.
2276  *
2277  * Returns          void
2278  *
2279  ******************************************************************************/
btm_read_link_quality_complete(uint8_t * p)2280 void btm_read_link_quality_complete(uint8_t* p) {
2281   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_link_qual_cmpl_cb;
2282   tBTM_LINK_QUALITY_RESULT result;
2283   tACL_CONN* p_acl_cb = &btm_cb.acl_db[0];
2284 
2285   BTM_TRACE_DEBUG("%s", __func__);
2286   alarm_cancel(btm_cb.devcb.read_link_quality_timer);
2287   btm_cb.devcb.p_link_qual_cmpl_cb = NULL;
2288 
2289   /* If there was a registered callback, call it */
2290   if (p_cb) {
2291     STREAM_TO_UINT8(result.hci_status, p);
2292 
2293     if (result.hci_status == HCI_SUCCESS) {
2294       uint16_t handle;
2295       result.status = BTM_SUCCESS;
2296 
2297       STREAM_TO_UINT16(handle, p);
2298 
2299       STREAM_TO_UINT8(result.link_quality, p);
2300       BTM_TRACE_DEBUG(
2301           "BTM Link Quality Complete: Link Quality %d, hci status 0x%02x",
2302           result.link_quality, result.hci_status);
2303 
2304       /* Search through the list of active channels for the correct BD Addr */
2305       for (uint16_t index = 0; index < MAX_L2CAP_LINKS; index++, p_acl_cb++) {
2306         if ((p_acl_cb->in_use) && (handle == p_acl_cb->hci_handle)) {
2307           result.rem_bda = p_acl_cb->remote_addr;
2308           break;
2309         }
2310       }
2311     } else {
2312       result.status = BTM_ERR_PROCESSING;
2313     }
2314 
2315     (*p_cb)(&result);
2316   }
2317 }
2318 
2319 /*******************************************************************************
2320  *
2321  * Function         btm_remove_acl
2322  *
2323  * Description      This function is called to disconnect an ACL connection
2324  *
2325  * Returns          BTM_SUCCESS if successfully initiated, otherwise
2326  *                  BTM_NO_RESOURCES.
2327  *
2328  ******************************************************************************/
btm_remove_acl(const RawAddress & bd_addr,tBT_TRANSPORT transport)2329 tBTM_STATUS btm_remove_acl(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
2330   uint16_t hci_handle = BTM_GetHCIConnHandle(bd_addr, transport);
2331   tBTM_STATUS status = BTM_SUCCESS;
2332 
2333   BTM_TRACE_DEBUG("btm_remove_acl");
2334 #if (BTM_DISC_DURING_RS == TRUE)
2335   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
2336 
2337   /* Role Switch is pending, postpone until completed */
2338   if (p_dev_rec && (p_dev_rec->rs_disc_pending == BTM_SEC_RS_PENDING)) {
2339     p_dev_rec->rs_disc_pending = BTM_SEC_DISC_PENDING;
2340   } else /* otherwise can disconnect right away */
2341 #endif
2342   {
2343     if (hci_handle != 0xFFFF && p_dev_rec &&
2344         p_dev_rec->sec_state != BTM_SEC_STATE_DISCONNECTING) {
2345       btsnd_hcic_disconnect(hci_handle, HCI_ERR_PEER_USER);
2346     } else {
2347       status = BTM_UNKNOWN_ADDR;
2348     }
2349   }
2350 
2351   return status;
2352 }
2353 
2354 /*******************************************************************************
2355  *
2356  * Function         BTM_SetTraceLevel
2357  *
2358  * Description      This function sets the trace level for BTM.  If called with
2359  *                  a value of 0xFF, it simply returns the current trace level.
2360  *
2361  * Returns          The new or current trace level
2362  *
2363  ******************************************************************************/
BTM_SetTraceLevel(uint8_t new_level)2364 uint8_t BTM_SetTraceLevel(uint8_t new_level) {
2365   BTM_TRACE_DEBUG("BTM_SetTraceLevel");
2366   if (new_level != 0xFF) btm_cb.trace_level = new_level;
2367 
2368   return (btm_cb.trace_level);
2369 }
2370 
2371 /*******************************************************************************
2372  *
2373  * Function         btm_cont_rswitch
2374  *
2375  * Description      This function is called to continue processing an active
2376  *                  role switch. It first disables encryption if enabled and
2377  *                  EPR is not supported
2378  *
2379  * Returns          void
2380  *
2381  ******************************************************************************/
btm_cont_rswitch(tACL_CONN * p,tBTM_SEC_DEV_REC * p_dev_rec,uint8_t hci_status)2382 void btm_cont_rswitch(tACL_CONN* p, tBTM_SEC_DEV_REC* p_dev_rec,
2383                       uint8_t hci_status) {
2384   BTM_TRACE_DEBUG("btm_cont_rswitch");
2385   /* Check to see if encryption needs to be turned off if pending
2386      change of link key or role switch */
2387   if (p->switch_role_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE) {
2388     /* Must turn off Encryption first if necessary */
2389     /* Some devices do not support switch or change of link key while encryption
2390      * is on */
2391     if (p_dev_rec != NULL &&
2392         ((p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED) != 0) &&
2393         !BTM_EPR_AVAILABLE(p)) {
2394       btsnd_hcic_set_conn_encrypt(p->hci_handle, false);
2395       p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF;
2396       if (p->switch_role_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE)
2397         p->switch_role_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF;
2398     } else /* Encryption not used or EPR supported, continue with switch
2399               and/or change of link key */
2400     {
2401       if (p->switch_role_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE) {
2402         p->switch_role_state = BTM_ACL_SWKEY_STATE_IN_PROGRESS;
2403 #if (BTM_DISC_DURING_RS == TRUE)
2404         if (p_dev_rec) p_dev_rec->rs_disc_pending = BTM_SEC_RS_PENDING;
2405 #endif
2406         btsnd_hcic_switch_role(p->remote_addr, (uint8_t)!p->link_role);
2407       }
2408     }
2409   }
2410 }
2411 
2412 /*******************************************************************************
2413  *
2414  * Function         btm_acl_resubmit_page
2415  *
2416  * Description      send pending page request
2417  *
2418  ******************************************************************************/
btm_acl_resubmit_page(void)2419 void btm_acl_resubmit_page(void) {
2420   tBTM_SEC_DEV_REC* p_dev_rec;
2421   BT_HDR* p_buf;
2422   uint8_t* pp;
2423   BTM_TRACE_DEBUG("btm_acl_resubmit_page");
2424   /* If there were other page request schedule can start the next one */
2425   p_buf = (BT_HDR*)fixed_queue_try_dequeue(btm_cb.page_queue);
2426   if (p_buf != NULL) {
2427     /* skip 3 (2 bytes opcode and 1 byte len) to get to the bd_addr
2428      * for both create_conn and rmt_name */
2429     pp = (uint8_t*)(p_buf + 1) + p_buf->offset + 3;
2430 
2431     RawAddress bda;
2432     STREAM_TO_BDADDR(bda, pp);
2433 
2434     p_dev_rec = btm_find_or_alloc_dev(bda);
2435 
2436     btm_cb.connecting_bda = p_dev_rec->bd_addr;
2437     memcpy(btm_cb.connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN);
2438 
2439     btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p_buf);
2440   } else {
2441     btm_cb.paging = false;
2442   }
2443 }
2444 
2445 /*******************************************************************************
2446  *
2447  * Function         btm_acl_reset_paging
2448  *
2449  * Description      set paging to false and free the page queue - called at
2450  *                  hci_reset
2451  *
2452  ******************************************************************************/
btm_acl_reset_paging(void)2453 void btm_acl_reset_paging(void) {
2454   BT_HDR* p;
2455   BTM_TRACE_DEBUG("btm_acl_reset_paging");
2456   /* If we sent reset we are definitely not paging any more */
2457   while ((p = (BT_HDR*)fixed_queue_try_dequeue(btm_cb.page_queue)) != NULL)
2458     osi_free(p);
2459 
2460   btm_cb.paging = false;
2461 }
2462 
2463 /*******************************************************************************
2464  *
2465  * Function         btm_acl_paging
2466  *
2467  * Description      send a paging command or queue it in btm_cb
2468  *
2469  ******************************************************************************/
btm_acl_paging(BT_HDR * p,const RawAddress & bda)2470 void btm_acl_paging(BT_HDR* p, const RawAddress& bda) {
2471   tBTM_SEC_DEV_REC* p_dev_rec;
2472 
2473   VLOG(2) << __func__ << ":" << btm_cb.discing << " , paging:" << btm_cb.paging
2474           << " BDA: " << bda;
2475 
2476   if (btm_cb.discing) {
2477     btm_cb.paging = true;
2478     fixed_queue_enqueue(btm_cb.page_queue, p);
2479   } else {
2480     if (!BTM_ACL_IS_CONNECTED(bda)) {
2481       VLOG(1) << "connecting_bda: " << btm_cb.connecting_bda;
2482       if (btm_cb.paging && bda == btm_cb.connecting_bda) {
2483         fixed_queue_enqueue(btm_cb.page_queue, p);
2484       } else {
2485         p_dev_rec = btm_find_or_alloc_dev(bda);
2486         btm_cb.connecting_bda = p_dev_rec->bd_addr;
2487         memcpy(btm_cb.connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN);
2488 
2489         btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
2490       }
2491 
2492       btm_cb.paging = true;
2493     } else /* ACL is already up */
2494     {
2495       btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
2496     }
2497   }
2498 }
2499 
2500 /*******************************************************************************
2501  *
2502  * Function         btm_acl_notif_conn_collision
2503  *
2504  * Description      Send connection collision event to upper layer if registered
2505  *
2506  * Returns          true if sent out to upper layer,
2507  *                  false if no one needs the notification.
2508  *
2509  ******************************************************************************/
btm_acl_notif_conn_collision(const RawAddress & bda)2510 bool btm_acl_notif_conn_collision(const RawAddress& bda) {
2511   /* Report possible collision to the upper layer. */
2512   if (btm_cb.p_bl_changed_cb) {
2513     VLOG(1) << __func__ << " RemBdAddr: " << bda;
2514 
2515     tBTM_BL_EVENT_DATA evt_data;
2516     evt_data.event = BTM_BL_COLLISION_EVT;
2517     evt_data.conn.p_bda = &bda;
2518     evt_data.conn.transport = BT_TRANSPORT_BR_EDR;
2519     evt_data.conn.handle = BTM_INVALID_HCI_HANDLE;
2520     (*btm_cb.p_bl_changed_cb)(&evt_data);
2521     return true;
2522   } else {
2523     return false;
2524   }
2525 }
2526 
2527 /*******************************************************************************
2528  *
2529  * Function         btm_acl_chk_peer_pkt_type_support
2530  *
2531  * Description      Check if peer supports requested packets
2532  *
2533  ******************************************************************************/
btm_acl_chk_peer_pkt_type_support(tACL_CONN * p,uint16_t * p_pkt_type)2534 void btm_acl_chk_peer_pkt_type_support(tACL_CONN* p, uint16_t* p_pkt_type) {
2535   /* 3 and 5 slot packets? */
2536   if (!HCI_3_SLOT_PACKETS_SUPPORTED(p->peer_lmp_feature_pages[0]))
2537     *p_pkt_type &= ~(BTM_ACL_PKT_TYPES_MASK_DH3 + BTM_ACL_PKT_TYPES_MASK_DM3);
2538 
2539   if (!HCI_5_SLOT_PACKETS_SUPPORTED(p->peer_lmp_feature_pages[0]))
2540     *p_pkt_type &= ~(BTM_ACL_PKT_TYPES_MASK_DH5 + BTM_ACL_PKT_TYPES_MASK_DM5);
2541 
2542   /* 2 and 3 MPS support? */
2543   if (!HCI_EDR_ACL_2MPS_SUPPORTED(p->peer_lmp_feature_pages[0]))
2544     /* Not supported. Add 'not_supported' mask for all 2MPS packet types */
2545     *p_pkt_type |=
2546         (BTM_ACL_PKT_TYPES_MASK_NO_2_DH1 + BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 +
2547          BTM_ACL_PKT_TYPES_MASK_NO_2_DH5);
2548 
2549   if (!HCI_EDR_ACL_3MPS_SUPPORTED(p->peer_lmp_feature_pages[0]))
2550     /* Not supported. Add 'not_supported' mask for all 3MPS packet types */
2551     *p_pkt_type |=
2552         (BTM_ACL_PKT_TYPES_MASK_NO_3_DH1 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH3 +
2553          BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
2554 
2555   /* EDR 3 and 5 slot support? */
2556   if (HCI_EDR_ACL_2MPS_SUPPORTED(p->peer_lmp_feature_pages[0]) ||
2557       HCI_EDR_ACL_3MPS_SUPPORTED(p->peer_lmp_feature_pages[0])) {
2558     if (!HCI_3_SLOT_EDR_ACL_SUPPORTED(p->peer_lmp_feature_pages[0]))
2559       /* Not supported. Add 'not_supported' mask for all 3-slot EDR packet types
2560        */
2561       *p_pkt_type |=
2562           (BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH3);
2563 
2564     if (!HCI_5_SLOT_EDR_ACL_SUPPORTED(p->peer_lmp_feature_pages[0]))
2565       /* Not supported. Add 'not_supported' mask for all 5-slot EDR packet types
2566        */
2567       *p_pkt_type |=
2568           (BTM_ACL_PKT_TYPES_MASK_NO_2_DH5 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
2569   }
2570 }
2571