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 <cstdint>
37 
38 #include "bta/include/bta_dm_acl.h"
39 #include "bta/sys/bta_sys.h"
40 #include "btif/include/btif_acl.h"
41 #include "common/metrics.h"
42 #include "device/include/controller.h"
43 #include "device/include/interop.h"
44 #include "include/l2cap_hci_link_interface.h"
45 #include "main/shim/acl_api.h"
46 #include "main/shim/btm_api.h"
47 #include "main/shim/dumpsys.h"
48 #include "main/shim/l2c_api.h"
49 #include "main/shim/shim.h"
50 #include "osi/include/log.h"
51 #include "stack/acl/acl.h"
52 #include "stack/acl/peer_packet_types.h"
53 #include "stack/btm/btm_dev.h"
54 #include "stack/btm/btm_int_types.h"
55 #include "stack/btm/btm_sec.h"
56 #include "stack/btm/security_device_record.h"
57 #include "stack/gatt/connection_manager.h"
58 #include "stack/include/acl_api.h"
59 #include "stack/include/acl_hci_link_interface.h"
60 #include "stack/include/btm_api.h"
61 #include "stack/include/btm_iso_api.h"
62 #include "stack/include/btu.h"
63 #include "stack/include/hci_error_code.h"
64 #include "stack/include/hcimsgs.h"
65 #include "stack/include/l2cap_acl_interface.h"
66 #include "stack/include/sco_hci_link_interface.h"
67 #include "types/hci_role.h"
68 #include "types/raw_address.h"
69 
70 void BTM_update_version_info(const RawAddress& bd_addr,
71                              const remote_version_info& remote_version_info);
72 
73 void gatt_find_in_device_record(const RawAddress& bd_addr,
74                                 tBLE_BD_ADDR* address_with_type);
75 void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle,
76                             const RawAddress& p_bda);
77 
78 void BTM_db_reset(void);
79 
80 extern tBTM_CB btm_cb;
81 
82 struct StackAclBtmAcl {
83   tACL_CONN* acl_allocate_connection();
84   tACL_CONN* acl_get_connection_from_handle(uint16_t handle);
85   tACL_CONN* btm_bda_to_acl(const RawAddress& bda, tBT_TRANSPORT transport);
86   bool change_connection_packet_types(tACL_CONN& link,
87                                       const uint16_t new_packet_type_bitmask);
88   void btm_establish_continue(tACL_CONN* p_acl_cb);
89   void btm_read_remote_features(uint16_t handle);
90   void btm_set_default_link_policy(tLINK_POLICY settings);
91   void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr,
92                             tHCI_ROLE new_role);
93   void hci_start_role_switch_to_central(tACL_CONN& p_acl);
set_default_packet_types_supportedStackAclBtmAcl94   void set_default_packet_types_supported(uint16_t packet_types_supported) {
95     btm_cb.acl_cb_.btm_acl_pkt_types_supported = packet_types_supported;
96   }
97 };
98 
99 struct RoleChangeView {
100   tHCI_ROLE new_role = HCI_ROLE_UNKNOWN;
101   RawAddress bd_addr;
102 };
103 
104 namespace {
105 StackAclBtmAcl internal_;
106 std::unique_ptr<RoleChangeView> delayed_role_change_ = nullptr;
GetLegacyHciInterface()107 const bluetooth::legacy::hci::Interface& GetLegacyHciInterface() {
108   return bluetooth::legacy::hci::GetInterface();
109 }
110 }
111 
112 typedef struct {
113   uint16_t handle;
114   uint16_t hci_len;
115 } __attribute__((packed)) acl_header_t;
116 
117 constexpr uint8_t BTM_MAX_SW_ROLE_FAILED_ATTEMPTS = 3;
118 
119 /* Define masks for supported and exception 2.0 ACL packet types
120  */
121 constexpr uint16_t BTM_ACL_SUPPORTED_PKTS_MASK =
122     (HCI_PKT_TYPES_MASK_DM1 | HCI_PKT_TYPES_MASK_DH1 | HCI_PKT_TYPES_MASK_DM3 |
123      HCI_PKT_TYPES_MASK_DH3 | HCI_PKT_TYPES_MASK_DM5 | HCI_PKT_TYPES_MASK_DH5);
124 
125 constexpr uint16_t BTM_ACL_EXCEPTION_PKTS_MASK =
126     (HCI_PKT_TYPES_MASK_NO_2_DH1 | HCI_PKT_TYPES_MASK_NO_3_DH1 |
127      HCI_PKT_TYPES_MASK_NO_2_DH3 | HCI_PKT_TYPES_MASK_NO_3_DH3 |
128      HCI_PKT_TYPES_MASK_NO_2_DH5 | HCI_PKT_TYPES_MASK_NO_3_DH5);
129 
IsEprAvailable(const tACL_CONN & p_acl)130 inline bool IsEprAvailable(const tACL_CONN& p_acl) {
131   if (!p_acl.peer_lmp_feature_valid[0]) {
132     LOG_WARN("Checking incomplete feature page read");
133     return false;
134   }
135   return HCI_ATOMIC_ENCRYPT_SUPPORTED(p_acl.peer_lmp_feature_pages[0]) &&
136          controller_get_interface()->supports_encryption_pause();
137 }
138 
139 static void btm_process_remote_ext_features(tACL_CONN* p_acl_cb,
140                                             uint8_t max_page_number);
141 static void btm_read_failed_contact_counter_timeout(void* data);
142 static void btm_read_remote_ext_features(uint16_t handle, uint8_t page_number);
143 static void btm_read_rssi_timeout(void* data);
144 static void btm_read_tx_power_timeout(void* data);
145 static void check_link_policy(tLINK_POLICY* settings);
146 void btm_set_link_policy(tACL_CONN* conn, tLINK_POLICY policy);
147 
148 namespace {
NotifyAclLinkUp(tACL_CONN & p_acl)149 void NotifyAclLinkUp(tACL_CONN& p_acl) {
150   if (p_acl.link_up_issued) {
151     LOG_INFO("Already notified BTA layer that the link is up");
152     return;
153   }
154   p_acl.link_up_issued = true;
155   BTA_dm_acl_up(p_acl.remote_addr, p_acl.transport);
156 }
157 
NotifyAclLinkDown(tACL_CONN & p_acl)158 void NotifyAclLinkDown(tACL_CONN& p_acl) {
159   /* Only notify if link up has had a chance to be issued */
160   if (p_acl.link_up_issued) {
161     p_acl.link_up_issued = false;
162     BTA_dm_acl_down(p_acl.remote_addr, p_acl.transport);
163   }
164 }
165 
NotifyAclRoleSwitchComplete(const RawAddress & bda,tHCI_ROLE new_role,tHCI_STATUS hci_status)166 void NotifyAclRoleSwitchComplete(const RawAddress& bda, tHCI_ROLE new_role,
167                                  tHCI_STATUS hci_status) {
168   BTA_dm_report_role_change(bda, new_role, hci_status);
169 }
170 
NotifyAclFeaturesReadComplete(tACL_CONN & p_acl,UNUSED_ATTR uint8_t max_page_number)171 void NotifyAclFeaturesReadComplete(tACL_CONN& p_acl,
172                                    UNUSED_ATTR uint8_t max_page_number) {
173   ASSERT_LOG(bluetooth::shim::is_gd_acl_enabled(),
174              "For right now only called with gd_acl support");
175   btm_process_remote_ext_features(&p_acl, max_page_number);
176   btm_set_link_policy(&p_acl, btm_cb.acl_cb_.DefaultLinkPolicy());
177   BTA_dm_notify_remote_features_complete(p_acl.remote_addr);
178 }
179 
180 }  // namespace
181 
hci_btsnd_hcic_disconnect(tACL_CONN & p_acl,tHCI_STATUS reason)182 static void hci_btsnd_hcic_disconnect(tACL_CONN& p_acl, tHCI_STATUS reason) {
183   LOG_INFO("Disconnecting peer:%s reason:%s",
184            PRIVATE_ADDRESS(p_acl.remote_addr),
185            hci_error_code_text(reason).c_str());
186   p_acl.disconnect_reason = reason;
187 
188   if (bluetooth::shim::is_gd_acl_enabled()) {
189     return bluetooth::shim::ACL_Disconnect(p_acl.hci_handle,
190                                            p_acl.is_transport_br_edr(), reason);
191   } else {
192     GetLegacyHciInterface().Disconnect(p_acl.hci_handle,
193                                        static_cast<uint16_t>(reason));
194   }
195 }
196 
hci_start_role_switch_to_central(tACL_CONN & p_acl)197 void StackAclBtmAcl::hci_start_role_switch_to_central(tACL_CONN& p_acl) {
198   GetLegacyHciInterface().StartRoleSwitch(
199       p_acl.remote_addr, static_cast<uint8_t>(HCI_ROLE_CENTRAL));
200   p_acl.set_switch_role_in_progress();
201   p_acl.rs_disc_pending = BTM_SEC_RS_PENDING;
202 }
203 
hci_btm_set_link_supervision_timeout(tACL_CONN & link,uint16_t timeout)204 void hci_btm_set_link_supervision_timeout(tACL_CONN& link, uint16_t timeout) {
205   if (link.link_role != HCI_ROLE_CENTRAL) {
206     /* Only send if current role is Central; 2.0 spec requires this */
207     LOG_WARN("Can only set link supervision timeout if central role:%s",
208              RoleText(link.link_role).c_str());
209     return;
210   }
211 
212   LOG_DEBUG("Setting link supervision timeout:%.2fs peer:%s",
213             double(timeout) * 0.01, PRIVATE_ADDRESS(link.RemoteAddress()));
214   link.link_super_tout = timeout;
215   btsnd_hcic_write_link_super_tout(LOCAL_BR_EDR_CONTROLLER_ID, link.Handle(),
216                                    timeout);
217 }
218 
219 /* 3 seconds timeout waiting for responses */
220 #define BTM_DEV_REPLY_TIMEOUT_MS (3 * 1000)
221 
BTM_acl_after_controller_started(const controller_t * controller)222 void BTM_acl_after_controller_started(const controller_t* controller) {
223   internal_.btm_set_default_link_policy(
224       HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH | HCI_ENABLE_HOLD_MODE |
225       HCI_ENABLE_SNIFF_MODE | HCI_ENABLE_PARK_MODE);
226 
227   /* Create ACL supported packet types mask */
228   uint16_t btm_acl_pkt_types_supported =
229       (HCI_PKT_TYPES_MASK_DH1 + HCI_PKT_TYPES_MASK_DM1);
230 
231   if (controller->supports_3_slot_packets())
232     btm_acl_pkt_types_supported |=
233         (HCI_PKT_TYPES_MASK_DH3 + HCI_PKT_TYPES_MASK_DM3);
234 
235   if (controller->supports_5_slot_packets())
236     btm_acl_pkt_types_supported |=
237         (HCI_PKT_TYPES_MASK_DH5 + HCI_PKT_TYPES_MASK_DM5);
238 
239   /* Add in EDR related ACL types */
240   if (!controller->supports_classic_2m_phy()) {
241     btm_acl_pkt_types_supported |=
242         (HCI_PKT_TYPES_MASK_NO_2_DH1 + HCI_PKT_TYPES_MASK_NO_2_DH3 +
243          HCI_PKT_TYPES_MASK_NO_2_DH5);
244   }
245 
246   if (!controller->supports_classic_3m_phy()) {
247     btm_acl_pkt_types_supported |=
248         (HCI_PKT_TYPES_MASK_NO_3_DH1 + HCI_PKT_TYPES_MASK_NO_3_DH3 +
249          HCI_PKT_TYPES_MASK_NO_3_DH5);
250   }
251 
252   /* Check to see if 3 and 5 slot packets are available */
253   if (controller->supports_classic_2m_phy() ||
254       controller->supports_classic_3m_phy()) {
255     if (!controller->supports_3_slot_edr_packets())
256       btm_acl_pkt_types_supported |=
257           (HCI_PKT_TYPES_MASK_NO_2_DH3 + HCI_PKT_TYPES_MASK_NO_3_DH3);
258 
259     if (!controller->supports_5_slot_edr_packets())
260       btm_acl_pkt_types_supported |=
261           (HCI_PKT_TYPES_MASK_NO_2_DH5 + HCI_PKT_TYPES_MASK_NO_3_DH5);
262   }
263   internal_.set_default_packet_types_supported(btm_acl_pkt_types_supported);
264 }
265 
266 /*******************************************************************************
267  *
268  * Function        btm_bda_to_acl
269  *
270  * Description     This function returns the FIRST acl_db entry for the passed
271  *                 BDA.
272  *
273  * Parameters      bda : BD address of the remote device
274  *                 transport : Physical transport used for ACL connection
275  *                 (BR/EDR or LE)
276  *
277  * Returns         Returns pointer to the ACL DB for the requested BDA if found.
278  *                 nullptr if not found.
279  *
280  ******************************************************************************/
btm_bda_to_acl(const RawAddress & bda,tBT_TRANSPORT transport)281 tACL_CONN* StackAclBtmAcl::btm_bda_to_acl(const RawAddress& bda,
282                                           tBT_TRANSPORT transport) {
283   tACL_CONN* p_acl = &btm_cb.acl_cb_.acl_db[0];
284   for (uint8_t index = 0; index < MAX_L2CAP_LINKS; index++, p_acl++) {
285     if ((p_acl->in_use) && p_acl->remote_addr == bda &&
286         p_acl->transport == transport) {
287       return p_acl;
288     }
289   }
290   return nullptr;
291 }
292 
acl_get_connection_from_address(const RawAddress & bd_addr,tBT_TRANSPORT transport)293 tACL_CONN* acl_get_connection_from_address(const RawAddress& bd_addr,
294                                            tBT_TRANSPORT transport) {
295   return internal_.btm_bda_to_acl(bd_addr, transport);
296 }
297 
298 /*******************************************************************************
299  *
300  * Function         btm_handle_to_acl_index
301  *
302  * Description      This function returns the FIRST acl_db entry for the passed
303  *                  hci_handle.
304  *
305  * Returns          index to the acl_db or MAX_L2CAP_LINKS.
306  *
307  ******************************************************************************/
btm_handle_to_acl_index(uint16_t hci_handle)308 uint8_t btm_handle_to_acl_index(uint16_t hci_handle) {
309   tACL_CONN* p = &btm_cb.acl_cb_.acl_db[0];
310   uint8_t xx;
311   for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p++) {
312     if ((p->in_use) && (p->hci_handle == hci_handle)) {
313       break;
314     }
315   }
316 
317   /* If here, no BD Addr found */
318   return (xx);
319 }
320 
acl_get_connection_from_handle(uint16_t hci_handle)321 tACL_CONN* StackAclBtmAcl::acl_get_connection_from_handle(uint16_t hci_handle) {
322   uint8_t index = btm_handle_to_acl_index(hci_handle);
323   if (index >= MAX_L2CAP_LINKS) return nullptr;
324   return &btm_cb.acl_cb_.acl_db[index];
325 }
326 
acl_get_connection_from_handle(uint16_t handle)327 tACL_CONN* acl_get_connection_from_handle(uint16_t handle) {
328   return internal_.acl_get_connection_from_handle(handle);
329 }
330 
btm_acl_process_sca_cmpl_pkt(uint8_t len,uint8_t * data)331 void btm_acl_process_sca_cmpl_pkt(uint8_t len, uint8_t* data) {
332   uint16_t handle;
333   uint8_t sca;
334   uint8_t status;
335 
336   STREAM_TO_UINT8(status, data);
337 
338   if (status != HCI_SUCCESS) {
339     LOG_WARN("Peer SCA Command complete failed:%s",
340              hci_error_code_text(static_cast<tHCI_STATUS>(status)).c_str());
341     return;
342   }
343 
344   STREAM_TO_UINT16(handle, data);
345   STREAM_TO_UINT8(sca, data);
346 
347   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
348   if (p_acl == nullptr) {
349     LOG_WARN("Unable to find active acl");
350     return;
351   }
352   p_acl->sca = sca;
353 }
354 
acl_allocate_connection()355 tACL_CONN* StackAclBtmAcl::acl_allocate_connection() {
356   tACL_CONN* p_acl = &btm_cb.acl_cb_.acl_db[0];
357   for (uint8_t xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_acl++) {
358     if (!p_acl->in_use) {
359       return p_acl;
360     }
361   }
362   return nullptr;
363 }
364 
btm_acl_created(const RawAddress & bda,uint16_t hci_handle,tHCI_ROLE link_role,tBT_TRANSPORT transport)365 void btm_acl_created(const RawAddress& bda, uint16_t hci_handle,
366                      tHCI_ROLE link_role, tBT_TRANSPORT transport) {
367   tACL_CONN* p_acl = internal_.btm_bda_to_acl(bda, transport);
368   if (p_acl != (tACL_CONN*)NULL) {
369     p_acl->hci_handle = hci_handle;
370     p_acl->link_role = link_role;
371     p_acl->transport = transport;
372     btm_set_link_policy(p_acl, btm_cb.acl_cb_.DefaultLinkPolicy());
373     LOG_WARN(
374         "Unable to create duplicate acl when one already exists handle:%hu"
375         " role:%s transport:%s",
376         hci_handle, RoleText(link_role).c_str(),
377         bt_transport_text(transport).c_str());
378     return;
379   }
380 
381   p_acl = internal_.acl_allocate_connection();
382   if (p_acl == nullptr) {
383     LOG_WARN("Unable to find active acl");
384     return;
385   }
386 
387   p_acl->in_use = true;
388   p_acl->hci_handle = hci_handle;
389   p_acl->link_role = link_role;
390   p_acl->link_up_issued = false;
391   p_acl->remote_addr = bda;
392   p_acl->sca = 0xFF;
393   p_acl->transport = transport;
394   p_acl->switch_role_failed_attempts = 0;
395   p_acl->reset_switch_role();
396   BTM_PM_OnConnected(hci_handle, bda);
397 
398   LOG_DEBUG(
399       "Created new ACL connection peer:%s role:%s handle:0x%04x transport:%s",
400       PRIVATE_ADDRESS(bda), RoleText(p_acl->link_role).c_str(), hci_handle,
401       bt_transport_text(transport).c_str());
402   btm_set_link_policy(p_acl, btm_cb.acl_cb_.DefaultLinkPolicy());
403 
404   if (transport == BT_TRANSPORT_LE) {
405     btm_ble_refresh_local_resolvable_private_addr(
406         bda, btm_cb.ble_ctr_cb.addr_mgnt_cb.private_addr);
407   }
408   /* if BR/EDR do something more */
409   if (transport == BT_TRANSPORT_BR_EDR) {
410     btsnd_hcic_read_rmt_clk_offset(hci_handle);
411     if (!bluetooth::shim::is_gd_l2cap_enabled() &&
412         !bluetooth::shim::is_gd_acl_enabled()) {
413       // GD L2cap and GD Acl read this automatically
414       btsnd_hcic_rmt_ver_req(hci_handle);
415     }
416   }
417 
418   if (transport == BT_TRANSPORT_LE) {
419     btm_ble_get_acl_remote_addr(hci_handle, p_acl->active_remote_addr,
420                                 &p_acl->active_remote_addr_type);
421 
422     if (controller_get_interface()
423             ->supports_ble_peripheral_initiated_feature_exchange() ||
424         link_role == HCI_ROLE_CENTRAL) {
425       btsnd_hcic_ble_read_remote_feat(p_acl->hci_handle);
426     } else {
427       internal_.btm_establish_continue(p_acl);
428     }
429   }
430 }
431 
btm_acl_update_conn_addr(uint16_t handle,const RawAddress & address)432 void btm_acl_update_conn_addr(uint16_t handle, const RawAddress& address) {
433   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
434   if (p_acl == nullptr) {
435     LOG_WARN("Unable to find active acl");
436     return;
437   }
438   p_acl->conn_addr = address;
439 }
440 
441 /*******************************************************************************
442  *
443  * Function         btm_acl_removed
444  *
445  * Description      This function is called by L2CAP when an ACL connection
446  *                  is removed. Since only L2CAP creates ACL links, we use
447  *                  the L2CAP link index as our index into the control blocks.
448  *
449  * Returns          void
450  *
451  ******************************************************************************/
btm_acl_removed(uint16_t handle)452 void btm_acl_removed(uint16_t handle) {
453   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
454   if (p_acl == nullptr) {
455     LOG_WARN("Unable to find active acl");
456     return;
457   }
458   p_acl->in_use = false;
459   NotifyAclLinkDown(*p_acl);
460   p_acl->Reset();
461   BTM_PM_OnDisconnected(handle);
462 }
463 
464 /*******************************************************************************
465  *
466  * Function         btm_acl_device_down
467  *
468  * Description      This function is called when the local device is deemed
469  *                  to be down. It notifies L2CAP of the failure.
470  *
471  * Returns          void
472  *
473  ******************************************************************************/
btm_acl_device_down(void)474 void btm_acl_device_down(void) {
475   tACL_CONN* p = &btm_cb.acl_cb_.acl_db[0];
476   uint16_t xx;
477   for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p++) {
478     if (p->in_use) {
479       l2c_link_hci_disc_comp(p->hci_handle, HCI_ERR_HW_FAILURE);
480     }
481   }
482   BTM_db_reset();
483 }
484 
btm_acl_set_paging(bool value)485 void btm_acl_set_paging(bool value) { btm_cb.is_paging = value; }
486 
btm_acl_update_inquiry_status(uint8_t status)487 void btm_acl_update_inquiry_status(uint8_t status) {
488   btm_cb.is_inquiry = status == BTM_INQUIRY_STARTED;
489   BTIF_dm_report_inquiry_status_change(status);
490 }
491 
BTM_GetRole(const RawAddress & remote_bd_addr,tHCI_ROLE * p_role)492 tBTM_STATUS BTM_GetRole(const RawAddress& remote_bd_addr, tHCI_ROLE* p_role) {
493   if (p_role == nullptr) {
494     return BTM_ILLEGAL_VALUE;
495   }
496   *p_role = HCI_ROLE_UNKNOWN;
497 
498   tACL_CONN* p_acl =
499       internal_.btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR);
500   if (p_acl == nullptr) {
501     LOG_WARN("Unable to find active acl");
502     return BTM_UNKNOWN_ADDR;
503   }
504   *p_role = p_acl->link_role;
505   return BTM_SUCCESS;
506 }
507 
508 /*******************************************************************************
509  *
510  * Function         BTM_SwitchRoleToCentral
511  *
512  * Description      This function is called to switch role between central and
513  *                  peripheral.  If role is already set it will do nothing.
514  *
515  * Returns          BTM_SUCCESS if already in specified role.
516  *                  BTM_CMD_STARTED if command issued to controller.
517  *                  BTM_NO_RESOURCES if couldn't allocate memory to issue
518  *                                   command
519  *                  BTM_UNKNOWN_ADDR if no active link with bd addr specified
520  *                  BTM_MODE_UNSUPPORTED if local device does not support role
521  *                                       switching
522  *                  BTM_BUSY if the previous command is not completed
523  *
524  ******************************************************************************/
BTM_SwitchRoleToCentral(const RawAddress & remote_bd_addr)525 tBTM_STATUS BTM_SwitchRoleToCentral(const RawAddress& remote_bd_addr) {
526   if (bluetooth::shim::is_gd_l2cap_enabled()) {
527     bluetooth::shim::L2CA_SwitchRoleToCentral(remote_bd_addr);
528     return BTM_SUCCESS;
529   }
530   if (!controller_get_interface()->supports_central_peripheral_role_switch()) {
531     LOG_INFO("Local controller does not support role switching");
532     return BTM_MODE_UNSUPPORTED;
533   }
534 
535   tACL_CONN* p_acl =
536       internal_.btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR);
537   if (p_acl == nullptr) {
538     LOG_WARN("Unable to find active acl");
539     return BTM_UNKNOWN_ADDR;
540   }
541 
542   if (p_acl->link_role == HCI_ROLE_CENTRAL) {
543     LOG_INFO("Requested role is already in effect");
544     return BTM_SUCCESS;
545   }
546 
547   if (interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH, &remote_bd_addr)) {
548     LOG_INFO("Remote device is on list preventing role switch");
549     return BTM_DEV_RESTRICT_LISTED;
550   }
551 
552   if (BTM_IsScoActiveByBdaddr(remote_bd_addr)) {
553     LOG_INFO("An active SCO to device prevents role switch at this time");
554     return BTM_NO_RESOURCES;
555   }
556 
557   if (!p_acl->is_switch_role_idle()) {
558     LOG_INFO("Role switch is already progress");
559     return BTM_BUSY;
560   }
561 
562   tBTM_PM_MODE pwr_mode;
563   if (!BTM_ReadPowerMode(p_acl->remote_addr, &pwr_mode)) {
564     LOG_WARN(
565         "Unable to find device to read current power mode prior to role "
566         "switch");
567     return BTM_UNKNOWN_ADDR;
568   };
569 
570   if (pwr_mode == BTM_PM_MD_PARK || pwr_mode == BTM_PM_MD_SNIFF) {
571     if (!BTM_SetLinkPolicyActiveMode(p_acl->remote_addr)) {
572       LOG_WARN("Unable to set link policy active before attempting switch");
573       return BTM_WRONG_MODE;
574     }
575     p_acl->set_switch_role_changing();
576   }
577   /* some devices do not support switch while encryption is on */
578   else {
579     if (p_acl->is_encrypted && !IsEprAvailable(*p_acl)) {
580       /* bypass turning off encryption if change link key is already doing it */
581       p_acl->set_encryption_off();
582       p_acl->set_switch_role_encryption_off();
583     } else {
584       internal_.hci_start_role_switch_to_central(*p_acl);
585     }
586   }
587 
588   return BTM_CMD_STARTED;
589 }
590 
591 /*******************************************************************************
592  *
593  * Function         btm_acl_encrypt_change
594  *
595  * Description      This function is when encryption of the connection is
596  *                  completed by the LM.  Checks to see if a role switch or
597  *                  change of link key was active and initiates or continues
598  *                  process if needed.
599  *
600  * Returns          void
601  *
602  ******************************************************************************/
btm_acl_encrypt_change(uint16_t handle,uint8_t status,uint8_t encr_enable)603 void btm_acl_encrypt_change(uint16_t handle, uint8_t status,
604                             uint8_t encr_enable) {
605   tACL_CONN* p = internal_.acl_get_connection_from_handle(handle);
606   if (p == nullptr) {
607     LOG_WARN("Unable to find active acl");
608     return;
609   }
610 
611   p->is_encrypted = encr_enable;
612 
613   /* Process Role Switch if active */
614   if (p->is_switch_role_encryption_off()) {
615     /* if encryption turn off failed we still will try to switch role */
616     if (encr_enable) {
617       p->set_encryption_idle();
618       p->reset_switch_role();
619     } else {
620       p->set_encryption_switching();
621       p->set_switch_role_switching();
622     }
623     internal_.hci_start_role_switch_to_central(*p);
624   }
625   /* Finished enabling Encryption after role switch */
626   else if (p->is_switch_role_encryption_on()) {
627     p->reset_switch_role();
628     p->set_encryption_idle();
629     NotifyAclRoleSwitchComplete(
630         btm_cb.acl_cb_.switch_role_ref_data.remote_bd_addr,
631         btm_cb.acl_cb_.switch_role_ref_data.role,
632         btm_cb.acl_cb_.switch_role_ref_data.hci_status);
633 
634     /* If a disconnect is pending, issue it now that role switch has completed
635      */
636     if (p->rs_disc_pending == BTM_SEC_DISC_PENDING) {
637       hci_btsnd_hcic_disconnect(*p, HCI_ERR_PEER_USER);
638     }
639     p->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
640   }
641 }
642 
check_link_policy(tLINK_POLICY * settings)643 static void check_link_policy(tLINK_POLICY* settings) {
644   const controller_t* controller = controller_get_interface();
645 
646   if ((*settings & HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH) &&
647       (!controller->supports_role_switch())) {
648     *settings &= (~HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH);
649     LOG_INFO("Role switch not supported (settings: 0x%04x)", *settings);
650   }
651   if ((*settings & HCI_ENABLE_HOLD_MODE) &&
652       (!controller->supports_hold_mode())) {
653     *settings &= (~HCI_ENABLE_HOLD_MODE);
654     LOG_INFO("hold not supported (settings: 0x%04x)", *settings);
655   }
656   if ((*settings & HCI_ENABLE_SNIFF_MODE) &&
657       (!controller->supports_sniff_mode())) {
658     *settings &= (~HCI_ENABLE_SNIFF_MODE);
659     LOG_INFO("sniff not supported (settings: 0x%04x)", *settings);
660   }
661   if ((*settings & HCI_ENABLE_PARK_MODE) &&
662       (!controller->supports_park_mode())) {
663     *settings &= (~HCI_ENABLE_PARK_MODE);
664     LOG_INFO("park not supported (settings: 0x%04x)", *settings);
665   }
666 }
667 
btm_set_link_policy(tACL_CONN * conn,tLINK_POLICY policy)668 void btm_set_link_policy(tACL_CONN* conn, tLINK_POLICY policy) {
669   conn->link_policy = policy;
670   check_link_policy(&conn->link_policy);
671   if ((conn->link_policy & HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH) &&
672       interop_match_addr(INTEROP_DISABLE_SNIFF, &(conn->remote_addr))) {
673     conn->link_policy &= (~HCI_ENABLE_SNIFF_MODE);
674   }
675   btsnd_hcic_write_policy_set(conn->hci_handle,
676                               static_cast<uint16_t>(conn->link_policy));
677 }
678 
btm_toggle_policy_on_for(const RawAddress & peer_addr,uint16_t flag)679 static void btm_toggle_policy_on_for(const RawAddress& peer_addr,
680                                      uint16_t flag) {
681   auto conn = internal_.btm_bda_to_acl(peer_addr, BT_TRANSPORT_BR_EDR);
682   if (!conn) {
683     LOG_WARN("Unable to find active acl");
684     return;
685   }
686   btm_set_link_policy(conn, conn->link_policy | flag);
687 }
688 
btm_toggle_policy_off_for(const RawAddress & peer_addr,uint16_t flag)689 static void btm_toggle_policy_off_for(const RawAddress& peer_addr,
690                                       uint16_t flag) {
691   auto conn = internal_.btm_bda_to_acl(peer_addr, BT_TRANSPORT_BR_EDR);
692   if (!conn) {
693     LOG_WARN("Unable to find active acl");
694     return;
695   }
696   btm_set_link_policy(conn, conn->link_policy & ~flag);
697 }
698 
BTM_is_sniff_allowed_for(const RawAddress & peer_addr)699 bool BTM_is_sniff_allowed_for(const RawAddress& peer_addr) {
700   auto conn = internal_.btm_bda_to_acl(peer_addr, BT_TRANSPORT_BR_EDR);
701   if (!conn) {
702     LOG_WARN("Unable to find active acl");
703     return false;
704   }
705   return conn->link_policy & HCI_ENABLE_SNIFF_MODE;
706 }
707 
BTM_unblock_sniff_mode_for(const RawAddress & peer_addr)708 void BTM_unblock_sniff_mode_for(const RawAddress& peer_addr) {
709   btm_toggle_policy_on_for(peer_addr, HCI_ENABLE_SNIFF_MODE);
710 }
711 
BTM_block_sniff_mode_for(const RawAddress & peer_addr)712 void BTM_block_sniff_mode_for(const RawAddress& peer_addr) {
713   btm_toggle_policy_off_for(peer_addr, HCI_ENABLE_SNIFF_MODE);
714 }
715 
BTM_unblock_role_switch_for(const RawAddress & peer_addr)716 void BTM_unblock_role_switch_for(const RawAddress& peer_addr) {
717   btm_toggle_policy_on_for(peer_addr, HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH);
718 }
719 
BTM_block_role_switch_for(const RawAddress & peer_addr)720 void BTM_block_role_switch_for(const RawAddress& peer_addr) {
721   btm_toggle_policy_off_for(peer_addr, HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH);
722 }
723 
btm_set_default_link_policy(tLINK_POLICY settings)724 void StackAclBtmAcl::btm_set_default_link_policy(tLINK_POLICY settings) {
725   check_link_policy(&settings);
726   btm_cb.acl_cb_.btm_def_link_policy = settings;
727   btsnd_hcic_write_def_policy_set(settings);
728 }
729 
BTM_default_unblock_role_switch()730 void BTM_default_unblock_role_switch() {
731   internal_.btm_set_default_link_policy(btm_cb.acl_cb_.DefaultLinkPolicy() |
732                                         HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH);
733 }
734 
BTM_default_block_role_switch()735 void BTM_default_block_role_switch() {
736   internal_.btm_set_default_link_policy(btm_cb.acl_cb_.DefaultLinkPolicy() &
737                                         ~HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH);
738 }
739 
740 /*******************************************************************************
741  *
742  * Function         btm_read_remote_version_complete
743  *
744  * Description      This function is called when the command complete message
745  *                  is received from the HCI for the remote version info.
746  *
747  * Returns          void
748  *
749  ******************************************************************************/
maybe_chain_more_commands_after_read_remote_version_complete(uint8_t status,uint16_t handle)750 static void maybe_chain_more_commands_after_read_remote_version_complete(
751     uint8_t status, uint16_t handle) {
752   tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
753   if (p_acl_cb == nullptr) {
754     LOG_WARN("Received remote version complete for unknown device");
755     return;
756   }
757 
758   switch (p_acl_cb->transport) {
759     case BT_TRANSPORT_LE:
760       l2cble_notify_le_connection(p_acl_cb->remote_addr);
761       l2cble_use_preferred_conn_params(p_acl_cb->remote_addr);
762       break;
763     case BT_TRANSPORT_BR_EDR:
764       /**
765        * When running legacy stack continue chain of executing various
766        * read commands.  Skip when gd_acl is enabled because that
767        * module handles all remote read functionality.
768        */
769       if (!bluetooth::shim::is_gd_acl_enabled()) {
770         if (status == HCI_SUCCESS) {
771           internal_.btm_read_remote_features(p_acl_cb->hci_handle);
772         }
773       }
774   }
775 }
776 
btm_process_remote_version_complete(uint8_t status,uint16_t handle,uint8_t lmp_version,uint16_t manufacturer,uint16_t lmp_subversion)777 void btm_process_remote_version_complete(uint8_t status, uint16_t handle,
778                                          uint8_t lmp_version,
779                                          uint16_t manufacturer,
780                                          uint16_t lmp_subversion) {
781   tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
782   if (p_acl_cb == nullptr) {
783     LOG_WARN("Received remote version complete for unknown acl");
784     return;
785   }
786 
787   if (status == HCI_SUCCESS) {
788     p_acl_cb->remote_version_info.lmp_version = lmp_version;
789     p_acl_cb->remote_version_info.manufacturer = manufacturer;
790     p_acl_cb->remote_version_info.lmp_subversion = lmp_subversion;
791     p_acl_cb->remote_version_info.valid = true;
792     BTM_update_version_info(p_acl_cb->RemoteAddress(),
793                             p_acl_cb->remote_version_info);
794 
795     bluetooth::common::LogRemoteVersionInfo(handle, status, lmp_version,
796                                             manufacturer, lmp_subversion);
797   } else {
798     bluetooth::common::LogRemoteVersionInfo(handle, status, 0, 0, 0);
799   }
800 }
801 
btm_read_remote_version_complete_raw(uint8_t * p)802 void btm_read_remote_version_complete_raw(uint8_t* p) {
803   uint8_t status;
804   uint16_t handle;
805   uint8_t lmp_version;
806   uint16_t manufacturer;
807   uint16_t lmp_subversion;
808 
809   STREAM_TO_UINT8(status, p);
810   STREAM_TO_UINT16(handle, p);
811   STREAM_TO_UINT8(lmp_version, p);
812   STREAM_TO_UINT16(manufacturer, p);
813   STREAM_TO_UINT16(lmp_subversion, p);
814 
815   ASSERT_LOG(!bluetooth::shim::is_gd_acl_enabled(),
816              "gd acl layer should be receiving this completion");
817   btm_read_remote_version_complete(static_cast<tHCI_STATUS>(status), handle,
818                                    lmp_version, manufacturer, lmp_version);
819 }
820 
btm_read_remote_version_complete(tHCI_STATUS status,uint16_t handle,uint8_t lmp_version,uint16_t manufacturer,uint16_t lmp_subversion)821 void btm_read_remote_version_complete(tHCI_STATUS status, uint16_t handle,
822                                       uint8_t lmp_version,
823                                       uint16_t manufacturer,
824                                       uint16_t lmp_subversion) {
825   btm_process_remote_version_complete(status, handle, lmp_version, manufacturer,
826                                       lmp_subversion);
827   maybe_chain_more_commands_after_read_remote_version_complete(status, handle);
828 }
829 
830 /*******************************************************************************
831  *
832  * Function         btm_process_remote_ext_features
833  *
834  * Description      Local function called to process all extended features pages
835  *                  read from a remote device.
836  *
837  * Returns          void
838  *
839  ******************************************************************************/
btm_process_remote_ext_features(tACL_CONN * p_acl_cb,uint8_t max_page_number)840 void btm_process_remote_ext_features(tACL_CONN* p_acl_cb,
841                                      uint8_t max_page_number) {
842   CHECK(p_acl_cb != nullptr);
843   if (!p_acl_cb->peer_lmp_feature_valid[max_page_number]) {
844     LOG_WARN(
845         "Checking remote features but remote feature read is "
846         "incomplete");
847   }
848 
849   bool ssp_supported =
850       HCI_SSP_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1]);
851   bool secure_connections_supported =
852       HCI_SC_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1]);
853   bool role_switch_supported =
854       HCI_SWITCH_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0]);
855   bool br_edr_supported =
856       !HCI_BREDR_NOT_SPT_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0]);
857   bool le_supported =
858       HCI_LE_SPT_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0]) &&
859       HCI_LE_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1]);
860   btm_sec_set_peer_sec_caps(p_acl_cb->hci_handle, ssp_supported,
861                             secure_connections_supported, role_switch_supported,
862                             br_edr_supported, le_supported);
863 }
864 
865 /*******************************************************************************
866  *
867  * Function         btm_read_remote_features
868  *
869  * Description      Local function called to send a read remote supported
870  *                  features/remote extended features page[0].
871  *
872  * Returns          void
873  *
874  ******************************************************************************/
btm_read_remote_features(uint16_t handle)875 void StackAclBtmAcl::btm_read_remote_features(uint16_t handle) {
876   uint8_t acl_idx;
877   tACL_CONN* p_acl_cb;
878 
879   acl_idx = btm_handle_to_acl_index(handle);
880   if (acl_idx >= MAX_L2CAP_LINKS) {
881     LOG_WARN("Unable to find active acl");
882     return;
883   }
884 
885   p_acl_cb = &btm_cb.acl_cb_.acl_db[acl_idx];
886   memset(p_acl_cb->peer_lmp_feature_pages, 0,
887          sizeof(p_acl_cb->peer_lmp_feature_pages));
888 
889   /* first send read remote supported features HCI command */
890   /* because we don't know whether the remote support extended feature command
891    */
892   if (bluetooth::shim::is_gd_l2cap_enabled()) {
893     // GD L2cap reads this automatically
894     return;
895   }
896   btsnd_hcic_rmt_features_req(handle);
897 }
898 
899 /*******************************************************************************
900  *
901  * Function         btm_read_remote_ext_features
902  *
903  * Description      Local function called to send a read remote extended
904  *                  features
905  *
906  * Returns          void
907  *
908  ******************************************************************************/
btm_read_remote_ext_features(uint16_t handle,uint8_t page_number)909 void btm_read_remote_ext_features(uint16_t handle, uint8_t page_number) {
910   if (bluetooth::shim::is_gd_l2cap_enabled()) {
911     // GD L2cap reads this automatically
912     return;
913   }
914   btsnd_hcic_rmt_ext_features(handle, page_number);
915 }
916 
917 /*******************************************************************************
918  *
919  * Function         btm_read_remote_features_complete
920  *
921  * Description      This function is called when the remote supported features
922  *                  complete event is received from the HCI.
923  *
924  * Returns          void
925  *
926  ******************************************************************************/
btm_read_remote_features_complete_raw(uint8_t * p)927 void btm_read_remote_features_complete_raw(uint8_t* p) {
928   uint8_t status;
929   uint16_t handle;
930 
931   STREAM_TO_UINT8(status, p);
932 
933   if (status != HCI_SUCCESS) {
934     LOG_WARN("Uanble to read remote features status:%s",
935              hci_error_code_text(static_cast<tHCI_STATUS>(status)).c_str());
936     return;
937   }
938 
939   STREAM_TO_UINT16(handle, p);
940 
941   btm_read_remote_features_complete(handle, p);
942 }
943 
btm_read_remote_features_complete(uint16_t handle,uint8_t * features)944 void btm_read_remote_features_complete(uint16_t handle, uint8_t* features) {
945   tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
946   if (p_acl_cb == nullptr) {
947     LOG_WARN("Unable to find active acl");
948     return;
949   }
950 
951   /* Copy the received features page */
952   STREAM_TO_ARRAY(p_acl_cb->peer_lmp_feature_pages[0], features,
953                   HCI_FEATURE_BYTES_PER_PAGE);
954   p_acl_cb->peer_lmp_feature_valid[0] = true;
955 
956   if ((HCI_LMP_EXTENDED_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0])) &&
957       (controller_get_interface()
958            ->supports_reading_remote_extended_features())) {
959     /* if the remote controller has extended features and local controller
960        supports HCI_Read_Remote_Extended_Features command then start reading
961        these feature starting with extended features page 1 */
962     LOG_DEBUG("Start reading remote extended features");
963     btm_read_remote_ext_features(handle, 1);
964     return;
965   }
966 
967   /* Remote controller has no extended features. Process remote controller
968      supported features (features page 0). */
969   btm_process_remote_ext_features(p_acl_cb, 0);
970 
971   /* Continue with HCI connection establishment */
972   internal_.btm_establish_continue(p_acl_cb);
973 }
974 
975 /*******************************************************************************
976  *
977  * Function         btm_read_remote_ext_features_complete
978  *
979  * Description      This function is called when the remote extended features
980  *                  complete event is received from the HCI.
981  *
982  * Returns          void
983  *
984  ******************************************************************************/
btm_read_remote_ext_features_complete_raw(uint8_t * p,uint8_t evt_len)985 void btm_read_remote_ext_features_complete_raw(uint8_t* p, uint8_t evt_len) {
986   uint8_t page_num, max_page;
987   uint16_t handle;
988 
989   if (evt_len < HCI_EXT_FEATURES_SUCCESS_EVT_LEN) {
990     android_errorWriteLog(0x534e4554, "141552859");
991     LOG_WARN("Remote extended feature length too short. length=%d", evt_len);
992     return;
993   }
994 
995   ++p;
996   STREAM_TO_UINT16(handle, p);
997   STREAM_TO_UINT8(page_num, p);
998   STREAM_TO_UINT8(max_page, p);
999 
1000   if (max_page > HCI_EXT_FEATURES_PAGE_MAX) {
1001     LOG_WARN("Too many max pages read page=%d unknown", max_page);
1002     return;
1003   }
1004 
1005   if (page_num > HCI_EXT_FEATURES_PAGE_MAX) {
1006     android_errorWriteLog(0x534e4554, "141552859");
1007     LOG_WARN("Too many received pages num_page=%d invalid", page_num);
1008     return;
1009   }
1010 
1011   if (page_num > max_page) {
1012     LOG_WARN("num_page=%d, max_page=%d invalid", page_num, max_page);
1013   }
1014 
1015   btm_read_remote_ext_features_complete(handle, page_num, max_page, p);
1016 }
1017 
btm_read_remote_ext_features_complete(uint16_t handle,uint8_t page_num,uint8_t max_page,uint8_t * features)1018 void btm_read_remote_ext_features_complete(uint16_t handle, uint8_t page_num,
1019                                            uint8_t max_page,
1020                                            uint8_t* features) {
1021   /* Validate parameters */
1022   auto* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
1023   if (p_acl_cb == nullptr) {
1024     LOG_WARN("Unable to find active acl");
1025     return;
1026   }
1027 
1028   /* Copy the received features page */
1029   STREAM_TO_ARRAY(p_acl_cb->peer_lmp_feature_pages[page_num], features,
1030                   HCI_FEATURE_BYTES_PER_PAGE);
1031   p_acl_cb->peer_lmp_feature_valid[page_num] = true;
1032 
1033   /* If there is the next remote features page and
1034    * we have space to keep this page data - read this page */
1035   if ((page_num < max_page) && (page_num < HCI_EXT_FEATURES_PAGE_MAX)) {
1036     page_num++;
1037     LOG_DEBUG("BTM reads next remote extended features page (%d)", page_num);
1038     btm_read_remote_ext_features(handle, page_num);
1039     return;
1040   }
1041 
1042   /* Reading of remote feature pages is complete */
1043   LOG_DEBUG("BTM reached last remote extended features page (%d)", page_num);
1044 
1045   /* Process the pages */
1046   btm_process_remote_ext_features(p_acl_cb, max_page);
1047 
1048   /* Continue with HCI connection establishment */
1049   internal_.btm_establish_continue(p_acl_cb);
1050 }
1051 
1052 /*******************************************************************************
1053  *
1054  * Function         btm_read_remote_ext_features_failed
1055  *
1056  * Description      This function is called when the remote extended features
1057  *                  complete event returns a failed status.
1058  *
1059  * Returns          void
1060  *
1061  ******************************************************************************/
btm_read_remote_ext_features_failed(uint8_t status,uint16_t handle)1062 void btm_read_remote_ext_features_failed(uint8_t status, uint16_t handle) {
1063   LOG_WARN("status 0x%02x for handle %d", status, handle);
1064 
1065   tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
1066   if (p_acl_cb == nullptr) {
1067     LOG_WARN("Unable to find active acl");
1068     return;
1069   }
1070 
1071   /* Process supported features only */
1072   btm_process_remote_ext_features(p_acl_cb, 0);
1073 
1074   /* Continue HCI connection establishment */
1075   internal_.btm_establish_continue(p_acl_cb);
1076 }
1077 
1078 /*******************************************************************************
1079  *
1080  * Function         btm_establish_continue
1081  *
1082  * Description      This function is called when the command complete message
1083  *                  is received from the HCI for the read local link policy
1084  *                  request.
1085  *
1086  * Returns          void
1087  *
1088  ******************************************************************************/
btm_establish_continue(tACL_CONN * p_acl)1089 void StackAclBtmAcl::btm_establish_continue(tACL_CONN* p_acl) {
1090   CHECK(p_acl != nullptr);
1091 
1092   if (p_acl->is_transport_br_edr()) {
1093     /* For now there are a some devices that do not like sending */
1094     /* commands events and data at the same time. */
1095     /* Set the packet types to the default allowed by the device */
1096     const uint16_t default_packet_type_mask =
1097         btm_cb.acl_cb_.DefaultPacketTypes();
1098     if (!internal_.change_connection_packet_types(*p_acl,
1099                                                   default_packet_type_mask)) {
1100       LOG_ERROR("Unable to change connection packet type types:%04x address:%s",
1101                 default_packet_type_mask,
1102                 PRIVATE_ADDRESS(p_acl->RemoteAddress()));
1103     }
1104     btm_set_link_policy(p_acl, btm_cb.acl_cb_.DefaultLinkPolicy());
1105   }
1106   NotifyAclLinkUp(*p_acl);
1107 }
1108 
btm_establish_continue_from_address(const RawAddress & bda,tBT_TRANSPORT transport)1109 void btm_establish_continue_from_address(const RawAddress& bda,
1110                                          tBT_TRANSPORT transport) {
1111   tACL_CONN* p_acl = internal_.btm_bda_to_acl(bda, transport);
1112   if (p_acl == nullptr) {
1113     LOG_WARN("Unable to find active acl");
1114     return;
1115   }
1116   internal_.btm_establish_continue(p_acl);
1117 }
1118 
1119 /*******************************************************************************
1120  *
1121  * Function         BTM_GetLinkSuperTout
1122  *
1123  * Description      Read the link supervision timeout value of the connection
1124  *
1125  * Returns          status of the operation
1126  *
1127  ******************************************************************************/
BTM_GetLinkSuperTout(const RawAddress & remote_bda,uint16_t * p_timeout)1128 tBTM_STATUS BTM_GetLinkSuperTout(const RawAddress& remote_bda,
1129                                  uint16_t* p_timeout) {
1130   CHECK(p_timeout != nullptr);
1131   const tACL_CONN* p_acl =
1132       internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
1133   if (p_acl == nullptr) {
1134     LOG_WARN("Unable to find active acl");
1135     return BTM_UNKNOWN_ADDR;
1136   }
1137   *p_timeout = p_acl->link_super_tout;
1138   return BTM_SUCCESS;
1139 }
1140 
1141 /*******************************************************************************
1142  *
1143  * Function         BTM_SetLinkSuperTout
1144  *
1145  * Description      Create and send HCI "Write Link Supervision Timeout" command
1146  *
1147  * Returns          status of the operation
1148  *
1149  ******************************************************************************/
BTM_SetLinkSuperTout(const RawAddress & remote_bda,uint16_t timeout)1150 tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda,
1151                                  uint16_t timeout) {
1152   tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
1153   if (p_acl == nullptr) {
1154     LOG_WARN("Unable to find active acl");
1155     return BTM_UNKNOWN_ADDR;
1156   }
1157 
1158   /* Only send if current role is Central; 2.0 spec requires this */
1159   if (p_acl->link_role == HCI_ROLE_CENTRAL) {
1160     p_acl->link_super_tout = timeout;
1161     btsnd_hcic_write_link_super_tout(LOCAL_BR_EDR_CONTROLLER_ID,
1162                                      p_acl->hci_handle, timeout);
1163     LOG_DEBUG("Set supervision timeout:%.2fms bd_addr:%s",
1164               supervision_timeout_to_seconds(timeout),
1165               PRIVATE_ADDRESS(remote_bda));
1166     return BTM_CMD_STARTED;
1167   } else {
1168     LOG_WARN(
1169         "Role is peripheral so unable to set supervision timeout:%.2fms "
1170         "bd_addr:%s",
1171         supervision_timeout_to_seconds(timeout), PRIVATE_ADDRESS(remote_bda));
1172     return BTM_SUCCESS;
1173   }
1174 }
1175 
BTM_IsAclConnectionUp(const RawAddress & remote_bda,tBT_TRANSPORT transport)1176 bool BTM_IsAclConnectionUp(const RawAddress& remote_bda,
1177                            tBT_TRANSPORT transport) {
1178   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1179     return bluetooth::shim::L2CA_IsLinkEstablished(remote_bda, transport);
1180   }
1181 
1182   return internal_.btm_bda_to_acl(remote_bda, transport) != nullptr;
1183 }
1184 
BTM_IsAclConnectionUpAndHandleValid(const RawAddress & remote_bda,tBT_TRANSPORT transport)1185 bool BTM_IsAclConnectionUpAndHandleValid(const RawAddress& remote_bda,
1186                                          tBT_TRANSPORT transport) {
1187   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1188     return bluetooth::shim::L2CA_IsLinkEstablished(remote_bda, transport);
1189   }
1190 
1191   tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, transport);
1192   if (p_acl == nullptr) {
1193     LOG_WARN("Unable to find active acl");
1194     return false;
1195   }
1196   return p_acl->hci_handle != HCI_INVALID_HANDLE;
1197 }
1198 
BTM_IsAclConnectionUpFromHandle(uint16_t hci_handle)1199 bool BTM_IsAclConnectionUpFromHandle(uint16_t hci_handle) {
1200   return internal_.acl_get_connection_from_handle(hci_handle) != nullptr;
1201 }
1202 
1203 /*******************************************************************************
1204  *
1205  * Function         BTM_GetNumAclLinks
1206  *
1207  * Description      This function is called to count the number of
1208  *                  ACL links that are active.
1209  *
1210  * Returns          uint16_t Number of active ACL links
1211  *
1212  ******************************************************************************/
BTM_GetNumAclLinks(void)1213 uint16_t BTM_GetNumAclLinks(void) {
1214   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1215     return bluetooth::shim::L2CA_GetNumLinks();
1216   }
1217   return static_cast<uint16_t>(btm_cb.acl_cb_.NumberOfActiveLinks());
1218 }
1219 
1220 /*******************************************************************************
1221  *
1222  * Function         btm_get_acl_disc_reason_code
1223  *
1224  * Description      This function is called to get the disconnection reason code
1225  *                  returned by the HCI at disconnection complete event.
1226  *
1227  * Returns          true if connection is up, else false.
1228  *
1229  ******************************************************************************/
btm_get_acl_disc_reason_code(void)1230 tHCI_REASON btm_get_acl_disc_reason_code(void) {
1231   return btm_cb.acl_cb_.get_disconnect_reason();
1232 }
1233 
1234 /*******************************************************************************
1235  *
1236  * Function         BTM_GetHCIConnHandle
1237  *
1238  * Description      This function is called to get the handle for an ACL
1239  *                  connection to a specific remote BD Address.
1240  *
1241  * Returns          the handle of the connection, or HCI_INVALID_HANDLE if none.
1242  *
1243  ******************************************************************************/
BTM_GetHCIConnHandle(const RawAddress & remote_bda,tBT_TRANSPORT transport)1244 uint16_t BTM_GetHCIConnHandle(const RawAddress& remote_bda,
1245                               tBT_TRANSPORT transport) {
1246   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1247     return bluetooth::shim::BTM_GetHCIConnHandle(remote_bda, transport);
1248   }
1249 
1250   tACL_CONN* p;
1251   p = internal_.btm_bda_to_acl(remote_bda, transport);
1252   if (p != (tACL_CONN*)NULL) {
1253     return (p->hci_handle);
1254   }
1255 
1256   /* If here, no BD Addr found */
1257   return HCI_INVALID_HANDLE;
1258 }
1259 
1260 /*******************************************************************************
1261  *
1262  * Function         BTM_IsPhy2mSupported
1263  *
1264  * Description      This function is called to check PHY 2M support
1265  *                  from peer device
1266  * Returns          True when PHY 2M supported false otherwise
1267  *
1268  ******************************************************************************/
BTM_IsPhy2mSupported(const RawAddress & remote_bda,tBT_TRANSPORT transport)1269 bool BTM_IsPhy2mSupported(const RawAddress& remote_bda, tBT_TRANSPORT transport) {
1270   tACL_CONN* p;
1271   BTM_TRACE_DEBUG("BTM_IsPhy2mSupported");
1272   p = internal_.btm_bda_to_acl(remote_bda, transport);
1273   if (p == (tACL_CONN*)NULL) {
1274     BTM_TRACE_DEBUG("BTM_IsPhy2mSupported: no connection");
1275     return false;
1276   }
1277 
1278   if (!p->peer_le_features_valid) {
1279     LOG_WARN(
1280         "Checking remote features but remote feature read is "
1281         "incomplete");
1282   }
1283   return HCI_LE_2M_PHY_SUPPORTED(p->peer_le_features);
1284 }
1285 
1286 /*******************************************************************************
1287  *
1288  * Function         BTM_RequestPeerSCA
1289  *
1290  * Description      This function is called to request sleep clock accuracy
1291  *                  from peer device
1292  *
1293  ******************************************************************************/
BTM_RequestPeerSCA(const RawAddress & remote_bda,tBT_TRANSPORT transport)1294 void BTM_RequestPeerSCA(const RawAddress& remote_bda, tBT_TRANSPORT transport) {
1295   tACL_CONN* p;
1296   p = internal_.btm_bda_to_acl(remote_bda, transport);
1297   if (p == (tACL_CONN*)NULL) {
1298     LOG_WARN("Unable to find active acl");
1299     return;
1300   }
1301 
1302   btsnd_hcic_req_peer_sca(p->hci_handle);
1303 }
1304 
1305 /*******************************************************************************
1306  *
1307  * Function         BTM_GetPeerSCA
1308  *
1309  * Description      This function is called to get peer sleep clock accuracy
1310  *
1311  * Returns          SCA or 0xFF if SCA was never previously requested, request
1312  *                  is not supported by peer device or ACL does not exist
1313  *
1314  ******************************************************************************/
BTM_GetPeerSCA(const RawAddress & remote_bda,tBT_TRANSPORT transport)1315 uint8_t BTM_GetPeerSCA(const RawAddress& remote_bda, tBT_TRANSPORT transport) {
1316   tACL_CONN* p;
1317   p = internal_.btm_bda_to_acl(remote_bda, transport);
1318   if (p != (tACL_CONN*)NULL) {
1319     return (p->sca);
1320   }
1321   LOG_WARN("Unable to find active acl");
1322 
1323   /* If here, no BD Addr found */
1324   return (0xFF);
1325 }
1326 
1327 /*******************************************************************************
1328  *
1329  * Function         btm_rejectlist_role_change_device
1330  *
1331  * Description      This function is used to rejectlist the device if the role
1332  *                  switch fails for maximum number of times. It also removes
1333  *                  the device from the black list if the role switch succeeds.
1334  *
1335  * Input Parms      bd_addr - remote BD addr
1336  *                  hci_status - role switch status
1337  *
1338  * Returns          void
1339  *
1340  *******************************************************************************/
btm_rejectlist_role_change_device(const RawAddress & bd_addr,uint8_t hci_status)1341 void btm_rejectlist_role_change_device(const RawAddress& bd_addr,
1342                                        uint8_t hci_status) {
1343   tACL_CONN* p = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
1344 
1345   if (!p) {
1346     LOG_WARN("Unable to find active acl");
1347     return;
1348   }
1349   if (hci_status == HCI_SUCCESS) {
1350     p->switch_role_failed_attempts = 0;
1351     return;
1352   }
1353 
1354   /* check for carkits */
1355   const uint32_t cod_audio_device =
1356       (BTM_COD_SERVICE_AUDIO | BTM_COD_MAJOR_AUDIO) << 8;
1357   const uint8_t* dev_class = btm_get_dev_class(bd_addr);
1358   if (dev_class == nullptr) return;
1359   const uint32_t cod =
1360       ((dev_class[0] << 16) | (dev_class[1] << 8) | dev_class[2]) & 0xffffff;
1361   if ((hci_status != HCI_SUCCESS) &&
1362       (p->is_switch_role_switching_or_in_progress()) &&
1363       ((cod & cod_audio_device) == cod_audio_device) &&
1364       (!interop_match_addr(INTEROP_DYNAMIC_ROLE_SWITCH, &bd_addr))) {
1365     p->switch_role_failed_attempts++;
1366     if (p->switch_role_failed_attempts == BTM_MAX_SW_ROLE_FAILED_ATTEMPTS) {
1367       LOG_WARN(
1368           "Device %s rejectlisted for role switching - "
1369           "multiple role switch failed attempts: %u",
1370           bd_addr.ToString().c_str(), p->switch_role_failed_attempts);
1371       interop_database_add(INTEROP_DYNAMIC_ROLE_SWITCH, &bd_addr, 3);
1372     }
1373   }
1374 }
1375 
1376 /*******************************************************************************
1377  *
1378  * Function         btm_acl_role_changed
1379  *
1380  * Description      This function is called whan a link's central/peripheral
1381  *role change event or command status event (with error) is received. It updates
1382  *the link control block, and calls the registered callback with status and role
1383  *(if registered).
1384  *
1385  * Returns          void
1386  *
1387  ******************************************************************************/
btm_acl_role_changed(tHCI_STATUS hci_status,const RawAddress & bd_addr,tHCI_ROLE new_role)1388 void StackAclBtmAcl::btm_acl_role_changed(tHCI_STATUS hci_status,
1389                                           const RawAddress& bd_addr,
1390                                           tHCI_ROLE new_role) {
1391   tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
1392   if (p_acl == nullptr) {
1393     // If we get a role change before connection complete, we cache the new
1394     // role here and then propagate it when ACL Link is created.
1395     RoleChangeView role_change;
1396     role_change.new_role = new_role;
1397     role_change.bd_addr = bd_addr;
1398     delayed_role_change_ =
1399         std::make_unique<RoleChangeView>(std::move(role_change));
1400     LOG_WARN("Unable to find active acl");
1401     return;
1402   }
1403 
1404   tBTM_ROLE_SWITCH_CMPL* p_switch_role = &btm_cb.acl_cb_.switch_role_ref_data;
1405   LOG_DEBUG("Role change event received peer:%s hci_status:%s new_role:%s",
1406             PRIVATE_ADDRESS(bd_addr), hci_error_code_text(hci_status).c_str(),
1407             RoleText(new_role).c_str());
1408 
1409   p_switch_role->hci_status = hci_status;
1410   if (hci_status == HCI_SUCCESS) {
1411     p_switch_role->role = new_role;
1412     p_switch_role->remote_bd_addr = bd_addr;
1413 
1414     /* Update cached value */
1415     p_acl->link_role = new_role;
1416 
1417     /* Reload LSTO: link supervision timeout is reset in the LM after a role
1418      * switch */
1419     if (new_role == HCI_ROLE_CENTRAL) {
1420       constexpr uint16_t link_supervision_timeout = 8000;
1421       BTM_SetLinkSuperTout(bd_addr, link_supervision_timeout);
1422     }
1423   } else {
1424     new_role = p_acl->link_role;
1425   }
1426 
1427   /* Check if any SCO req is pending for role change */
1428   btm_sco_chk_pend_rolechange(p_acl->hci_handle);
1429 
1430   /* if switching state is switching we need to turn encryption on */
1431   /* if idle, we did not change encryption */
1432   if (p_acl->is_switch_role_switching()) {
1433     p_acl->set_encryption_on();
1434     p_acl->set_switch_role_encryption_on();
1435     return;
1436   }
1437 
1438   /* Set the switch_role_state to IDLE since the reply received from HCI */
1439   /* regardless of its result either success or failed. */
1440   if (p_acl->is_switch_role_in_progress()) {
1441     p_acl->set_encryption_idle();
1442     p_acl->reset_switch_role();
1443   }
1444 
1445   BTA_dm_report_role_change(bd_addr, new_role, hci_status);
1446 
1447   /* If a disconnect is pending, issue it now that role switch has completed */
1448   if (p_acl->rs_disc_pending == BTM_SEC_DISC_PENDING) {
1449     hci_btsnd_hcic_disconnect(*p_acl, HCI_ERR_PEER_USER);
1450   }
1451   p_acl->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
1452 }
1453 
btm_acl_role_changed(tHCI_STATUS hci_status,const RawAddress & bd_addr,tHCI_ROLE new_role)1454 void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr,
1455                           tHCI_ROLE new_role) {
1456   if (hci_status == HCI_SUCCESS) {
1457     l2c_link_role_changed(&bd_addr, new_role, hci_status);
1458   } else {
1459     l2c_link_role_changed(nullptr, HCI_ROLE_UNKNOWN,
1460                           HCI_ERR_COMMAND_DISALLOWED);
1461   }
1462   internal_.btm_acl_role_changed(hci_status, bd_addr, new_role);
1463 }
1464 
1465 /*******************************************************************************
1466  *
1467  * Function         change_connection_packet_types
1468  *
1469  * Description      This function sets the packet types used for a specific
1470  *                  ACL connection. It is called internally by btm_acl_created
1471  *                  or by an application/profile by BTM_SetPacketTypes.
1472  *
1473  * Returns          status of the operation
1474  *
1475  ******************************************************************************/
change_connection_packet_types(tACL_CONN & link,const uint16_t new_packet_type_mask)1476 bool StackAclBtmAcl::change_connection_packet_types(
1477     tACL_CONN& link, const uint16_t new_packet_type_mask) {
1478   // Start with the default configured packet types
1479   const uint16_t default_packet_type_mask = btm_cb.acl_cb_.DefaultPacketTypes();
1480 
1481   uint16_t packet_type_mask =
1482       default_packet_type_mask &
1483       (new_packet_type_mask & BTM_ACL_SUPPORTED_PKTS_MASK);
1484 
1485   /* OR in any exception packet types if at least 2.0 version of spec */
1486   packet_type_mask |=
1487       ((new_packet_type_mask & BTM_ACL_EXCEPTION_PKTS_MASK) |
1488        (BTM_ACL_EXCEPTION_PKTS_MASK & default_packet_type_mask));
1489 
1490   /* Exclude packet types not supported by the peer */
1491   if (link.peer_lmp_feature_valid[0]) {
1492     PeerPacketTypes peer_packet_types(link.peer_lmp_feature_pages[0]);
1493     packet_type_mask &= peer_packet_types.acl.supported;
1494     packet_type_mask |= peer_packet_types.acl.unsupported;
1495   } else {
1496     LOG_INFO(
1497         "Unable to include remote supported packet types as read feature "
1498         "incomplete");
1499     LOG_INFO("TIP: Maybe wait until read feature complete beforehand");
1500   }
1501 
1502   if (packet_type_mask == 0) {
1503     LOG_WARN("Unable to send controller illegal change packet mask:0x%04x",
1504              packet_type_mask);
1505     return false;
1506   }
1507 
1508   link.pkt_types_mask = packet_type_mask;
1509   bluetooth::legacy::hci::GetInterface().ChangeConnectionPacketType(
1510       link.Handle(), link.pkt_types_mask);
1511   LOG_DEBUG("Started change connection packet type:0x%04x address:%s",
1512             link.pkt_types_mask, PRIVATE_ADDRESS(link.RemoteAddress()));
1513   return true;
1514 }
1515 
btm_set_packet_types_from_address(const RawAddress & bd_addr,uint16_t pkt_types)1516 void btm_set_packet_types_from_address(const RawAddress& bd_addr,
1517                                        uint16_t pkt_types) {
1518   tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
1519   if (p_acl == nullptr) {
1520     LOG_WARN("Unable to find active acl");
1521     return;
1522   }
1523 
1524   if (!internal_.change_connection_packet_types(*p_acl, pkt_types)) {
1525     LOG_ERROR("Unable to change connection packet type types:%04x address:%s",
1526               pkt_types, PRIVATE_ADDRESS(bd_addr));
1527   }
1528 }
1529 
1530 /*******************************************************************************
1531  *
1532  * Function         BTM_GetMaxPacketSize
1533  *
1534  * Returns          Returns maximum packet size that can be used for current
1535  *                  connection, 0 if connection is not established
1536  *
1537  ******************************************************************************/
BTM_GetMaxPacketSize(const RawAddress & addr)1538 uint16_t BTM_GetMaxPacketSize(const RawAddress& addr) {
1539   tACL_CONN* p = internal_.btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1540   uint16_t pkt_types = 0;
1541   uint16_t pkt_size = 0;
1542   if (p != NULL) {
1543     pkt_types = p->pkt_types_mask;
1544   } else {
1545     /* Special case for when info for the local device is requested */
1546     if (addr == *controller_get_interface()->get_address()) {
1547       pkt_types = btm_cb.acl_cb_.DefaultPacketTypes();
1548     }
1549   }
1550 
1551   if (pkt_types) {
1552     if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_3_DH5))
1553       pkt_size = HCI_EDR3_DH5_PACKET_SIZE;
1554     else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_2_DH5))
1555       pkt_size = HCI_EDR2_DH5_PACKET_SIZE;
1556     else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_3_DH3))
1557       pkt_size = HCI_EDR3_DH3_PACKET_SIZE;
1558     else if (pkt_types & HCI_PKT_TYPES_MASK_DH5)
1559       pkt_size = HCI_DH5_PACKET_SIZE;
1560     else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_2_DH3))
1561       pkt_size = HCI_EDR2_DH3_PACKET_SIZE;
1562     else if (pkt_types & HCI_PKT_TYPES_MASK_DM5)
1563       pkt_size = HCI_DM5_PACKET_SIZE;
1564     else if (pkt_types & HCI_PKT_TYPES_MASK_DH3)
1565       pkt_size = HCI_DH3_PACKET_SIZE;
1566     else if (pkt_types & HCI_PKT_TYPES_MASK_DM3)
1567       pkt_size = HCI_DM3_PACKET_SIZE;
1568     else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_3_DH1))
1569       pkt_size = HCI_EDR3_DH1_PACKET_SIZE;
1570     else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_2_DH1))
1571       pkt_size = HCI_EDR2_DH1_PACKET_SIZE;
1572     else if (pkt_types & HCI_PKT_TYPES_MASK_DH1)
1573       pkt_size = HCI_DH1_PACKET_SIZE;
1574     else if (pkt_types & HCI_PKT_TYPES_MASK_DM1)
1575       pkt_size = HCI_DM1_PACKET_SIZE;
1576   }
1577 
1578   return (pkt_size);
1579 }
1580 
1581 /*******************************************************************************
1582  *
1583  * Function         BTM_ReadRemoteVersion
1584  *
1585  * Returns          If connected report peer device info
1586  *
1587  ******************************************************************************/
BTM_ReadRemoteVersion(const RawAddress & addr,uint8_t * lmp_version,uint16_t * manufacturer,uint16_t * lmp_sub_version)1588 bool BTM_ReadRemoteVersion(const RawAddress& addr, uint8_t* lmp_version,
1589                            uint16_t* manufacturer, uint16_t* lmp_sub_version) {
1590   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1591     return bluetooth::shim::L2CA_ReadRemoteVersion(
1592         addr, lmp_version, manufacturer, lmp_sub_version);
1593   }
1594 
1595   const tACL_CONN* p_acl = internal_.btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1596   if (p_acl == nullptr) {
1597     p_acl = internal_.btm_bda_to_acl(addr, BT_TRANSPORT_LE);
1598     if (p_acl == nullptr) {
1599       LOG_WARN("Unable to find active acl");
1600       return false;
1601     }
1602   }
1603 
1604   if (!p_acl->remote_version_info.valid) {
1605     LOG_WARN("Remote version information is invalid");
1606     return false;
1607   }
1608 
1609   if (lmp_version) *lmp_version = p_acl->remote_version_info.lmp_version;
1610 
1611   if (manufacturer) *manufacturer = p_acl->remote_version_info.manufacturer;
1612 
1613   if (lmp_sub_version)
1614     *lmp_sub_version = p_acl->remote_version_info.lmp_subversion;
1615 
1616   return true;
1617 }
1618 
1619 /*******************************************************************************
1620  *
1621  * Function         BTM_ReadRemoteFeatures
1622  *
1623  * Returns          pointer to the remote supported features mask (8 bytes)
1624  *
1625  ******************************************************************************/
BTM_ReadRemoteFeatures(const RawAddress & addr)1626 uint8_t* BTM_ReadRemoteFeatures(const RawAddress& addr) {
1627   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1628     return bluetooth::shim::L2CA_ReadRemoteFeatures(addr);
1629   }
1630   tACL_CONN* p = internal_.btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1631   if (p == NULL) {
1632     LOG_WARN("Unable to find active acl");
1633     return (NULL);
1634   }
1635 
1636   return (p->peer_lmp_feature_pages[0]);
1637 }
1638 
1639 /*******************************************************************************
1640  *
1641  * Function         BTM_ReadRSSI
1642  *
1643  * Description      This function is called to read the link policy settings.
1644  *                  The address of link policy results are returned in the
1645  *                  callback.
1646  *                  (tBTM_RSSI_RESULT)
1647  *
1648  * Returns          BTM_CMD_STARTED if successfully initiated or error code
1649  *
1650  ******************************************************************************/
BTM_ReadRSSI(const RawAddress & remote_bda,tBTM_CMPL_CB * p_cb)1651 tBTM_STATUS BTM_ReadRSSI(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb) {
1652   tACL_CONN* p = NULL;
1653   tBT_DEVICE_TYPE dev_type;
1654   tBLE_ADDR_TYPE addr_type;
1655 
1656   /* If someone already waiting on the version, do not allow another */
1657   if (btm_cb.devcb.p_rssi_cmpl_cb) return (BTM_BUSY);
1658 
1659   BTM_ReadDevInfo(remote_bda, &dev_type, &addr_type);
1660 
1661   if (dev_type & BT_DEVICE_TYPE_BLE) {
1662     p = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE);
1663   }
1664 
1665   if (p == NULL && dev_type & BT_DEVICE_TYPE_BREDR) {
1666     p = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
1667   }
1668 
1669   if (p) {
1670     btm_cb.devcb.p_rssi_cmpl_cb = p_cb;
1671     alarm_set_on_mloop(btm_cb.devcb.read_rssi_timer, BTM_DEV_REPLY_TIMEOUT_MS,
1672                        btm_read_rssi_timeout, NULL);
1673 
1674     btsnd_hcic_read_rssi(p->hci_handle);
1675     return (BTM_CMD_STARTED);
1676   }
1677   LOG_WARN("Unable to find active acl");
1678 
1679   /* If here, no BD Addr found */
1680   return (BTM_UNKNOWN_ADDR);
1681 }
1682 
1683 /*******************************************************************************
1684  *
1685  * Function         BTM_ReadFailedContactCounter
1686  *
1687  * Description      This function is called to read the failed contact counter.
1688  *                  The result is returned in the callback.
1689  *                  (tBTM_FAILED_CONTACT_COUNTER_RESULT)
1690  *
1691  * Returns          BTM_CMD_STARTED if successfully initiated or error code
1692  *
1693  ******************************************************************************/
BTM_ReadFailedContactCounter(const RawAddress & remote_bda,tBTM_CMPL_CB * p_cb)1694 tBTM_STATUS BTM_ReadFailedContactCounter(const RawAddress& remote_bda,
1695                                          tBTM_CMPL_CB* p_cb) {
1696   tACL_CONN* p;
1697   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1698   tBT_DEVICE_TYPE dev_type;
1699   tBLE_ADDR_TYPE addr_type;
1700 
1701   /* If someone already waiting on the result, do not allow another */
1702   if (btm_cb.devcb.p_failed_contact_counter_cmpl_cb) return (BTM_BUSY);
1703 
1704   BTM_ReadDevInfo(remote_bda, &dev_type, &addr_type);
1705   if (dev_type == BT_DEVICE_TYPE_BLE) transport = BT_TRANSPORT_LE;
1706 
1707   p = internal_.btm_bda_to_acl(remote_bda, transport);
1708   if (p != (tACL_CONN*)NULL) {
1709     btm_cb.devcb.p_failed_contact_counter_cmpl_cb = p_cb;
1710     alarm_set_on_mloop(btm_cb.devcb.read_failed_contact_counter_timer,
1711                        BTM_DEV_REPLY_TIMEOUT_MS,
1712                        btm_read_failed_contact_counter_timeout, NULL);
1713 
1714     btsnd_hcic_read_failed_contact_counter(p->hci_handle);
1715     return (BTM_CMD_STARTED);
1716   }
1717   LOG_WARN("Unable to find active acl");
1718 
1719   /* If here, no BD Addr found */
1720   return (BTM_UNKNOWN_ADDR);
1721 }
1722 
1723 /*******************************************************************************
1724  *
1725  * Function         BTM_ReadTxPower
1726  *
1727  * Description      This function is called to read the current
1728  *                  TX power of the connection. The tx power level results
1729  *                  are returned in the callback.
1730  *                  (tBTM_RSSI_RESULT)
1731  *
1732  * Returns          BTM_CMD_STARTED if successfully initiated or error code
1733  *
1734  ******************************************************************************/
BTM_ReadTxPower(const RawAddress & remote_bda,tBT_TRANSPORT transport,tBTM_CMPL_CB * p_cb)1735 tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda,
1736                             tBT_TRANSPORT transport, tBTM_CMPL_CB* p_cb) {
1737   tACL_CONN* p;
1738 #define BTM_READ_RSSI_TYPE_CUR 0x00
1739 #define BTM_READ_RSSI_TYPE_MAX 0X01
1740 
1741   VLOG(2) << __func__ << ": RemBdAddr: " << remote_bda;
1742 
1743   /* If someone already waiting on the version, do not allow another */
1744   if (btm_cb.devcb.p_tx_power_cmpl_cb) return (BTM_BUSY);
1745 
1746   p = internal_.btm_bda_to_acl(remote_bda, transport);
1747   if (p != (tACL_CONN*)NULL) {
1748     btm_cb.devcb.p_tx_power_cmpl_cb = p_cb;
1749     alarm_set_on_mloop(btm_cb.devcb.read_tx_power_timer,
1750                        BTM_DEV_REPLY_TIMEOUT_MS, btm_read_tx_power_timeout,
1751                        NULL);
1752 
1753     if (p->transport == BT_TRANSPORT_LE) {
1754       btm_cb.devcb.read_tx_pwr_addr = remote_bda;
1755       btsnd_hcic_ble_read_adv_chnl_tx_power();
1756     } else {
1757       btsnd_hcic_read_tx_power(p->hci_handle, BTM_READ_RSSI_TYPE_CUR);
1758     }
1759 
1760     return (BTM_CMD_STARTED);
1761   }
1762 
1763   LOG_WARN("Unable to find active acl");
1764 
1765   /* If here, no BD Addr found */
1766   return (BTM_UNKNOWN_ADDR);
1767 }
1768 
1769 /*******************************************************************************
1770  *
1771  * Function         btm_read_tx_power_timeout
1772  *
1773  * Description      Callback when reading the tx power times out.
1774  *
1775  * Returns          void
1776  *
1777  ******************************************************************************/
btm_read_tx_power_timeout(UNUSED_ATTR void * data)1778 void btm_read_tx_power_timeout(UNUSED_ATTR void* data) {
1779   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_tx_power_cmpl_cb;
1780   btm_cb.devcb.p_tx_power_cmpl_cb = NULL;
1781   if (p_cb) (*p_cb)((void*)NULL);
1782 }
1783 
1784 /*******************************************************************************
1785  *
1786  * Function         btm_read_tx_power_complete
1787  *
1788  * Description      This function is called when the command complete message
1789  *                  is received from the HCI for the read tx power request.
1790  *
1791  * Returns          void
1792  *
1793  ******************************************************************************/
btm_read_tx_power_complete(uint8_t * p,bool is_ble)1794 void btm_read_tx_power_complete(uint8_t* p, bool is_ble) {
1795   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_tx_power_cmpl_cb;
1796   tBTM_TX_POWER_RESULT result;
1797 
1798   alarm_cancel(btm_cb.devcb.read_tx_power_timer);
1799   btm_cb.devcb.p_tx_power_cmpl_cb = NULL;
1800 
1801   /* If there was a registered callback, call it */
1802   if (p_cb) {
1803     STREAM_TO_UINT8(result.hci_status, p);
1804 
1805     if (result.hci_status == HCI_SUCCESS) {
1806       result.status = BTM_SUCCESS;
1807 
1808       if (!is_ble) {
1809         uint16_t handle;
1810         STREAM_TO_UINT16(handle, p);
1811         STREAM_TO_UINT8(result.tx_power, p);
1812 
1813         tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
1814         if (p_acl_cb != nullptr) {
1815           result.rem_bda = p_acl_cb->remote_addr;
1816         }
1817       } else {
1818         STREAM_TO_UINT8(result.tx_power, p);
1819         result.rem_bda = btm_cb.devcb.read_tx_pwr_addr;
1820       }
1821       LOG_DEBUG("Transmit power complete: tx_power:%d hci status:%s",
1822                 result.tx_power,
1823                 hci_error_code_text(static_cast<tHCI_STATUS>(result.hci_status))
1824                     .c_str());
1825     } else {
1826       result.status = BTM_ERR_PROCESSING;
1827     }
1828 
1829     (*p_cb)(&result);
1830   }
1831 }
1832 
1833 /*******************************************************************************
1834  *
1835  * Function         btm_read_rssi_timeout
1836  *
1837  * Description      Callback when reading the RSSI times out.
1838  *
1839  * Returns          void
1840  *
1841  ******************************************************************************/
btm_read_rssi_timeout(UNUSED_ATTR void * data)1842 void btm_read_rssi_timeout(UNUSED_ATTR void* data) {
1843   tBTM_RSSI_RESULT result;
1844   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_rssi_cmpl_cb;
1845   btm_cb.devcb.p_rssi_cmpl_cb = NULL;
1846   result.status = BTM_DEVICE_TIMEOUT;
1847   if (p_cb) (*p_cb)(&result);
1848 }
1849 
1850 /*******************************************************************************
1851  *
1852  * Function         btm_read_rssi_complete
1853  *
1854  * Description      This function is called when the command complete message
1855  *                  is received from the HCI for the read rssi request.
1856  *
1857  * Returns          void
1858  *
1859  ******************************************************************************/
btm_read_rssi_complete(uint8_t * p)1860 void btm_read_rssi_complete(uint8_t* p) {
1861   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_rssi_cmpl_cb;
1862   tBTM_RSSI_RESULT result;
1863 
1864   alarm_cancel(btm_cb.devcb.read_rssi_timer);
1865   btm_cb.devcb.p_rssi_cmpl_cb = NULL;
1866 
1867   /* If there was a registered callback, call it */
1868   if (p_cb) {
1869     STREAM_TO_UINT8(result.hci_status, p);
1870     result.status = BTM_ERR_PROCESSING;
1871 
1872     if (result.hci_status == HCI_SUCCESS) {
1873       uint16_t handle;
1874       STREAM_TO_UINT16(handle, p);
1875 
1876       STREAM_TO_UINT8(result.rssi, p);
1877       LOG_DEBUG("Read rrsi complete rssi:%hhd hci status:%s", result.rssi,
1878                 hci_error_code_text(static_cast<tHCI_STATUS>(result.hci_status))
1879                     .c_str());
1880 
1881       tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
1882       if (p_acl_cb != nullptr) {
1883         result.rem_bda = p_acl_cb->remote_addr;
1884         result.status = BTM_SUCCESS;
1885       }
1886     }
1887     (*p_cb)(&result);
1888   }
1889 }
1890 
1891 /*******************************************************************************
1892  *
1893  * Function         btm_read_failed_contact_counter_timeout
1894  *
1895  * Description      Callback when reading the failed contact counter times out.
1896  *
1897  * Returns          void
1898  *
1899  ******************************************************************************/
btm_read_failed_contact_counter_timeout(UNUSED_ATTR void * data)1900 void btm_read_failed_contact_counter_timeout(UNUSED_ATTR void* data) {
1901   tBTM_FAILED_CONTACT_COUNTER_RESULT result;
1902   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_failed_contact_counter_cmpl_cb;
1903   btm_cb.devcb.p_failed_contact_counter_cmpl_cb = NULL;
1904   result.status = BTM_DEVICE_TIMEOUT;
1905   if (p_cb) (*p_cb)(&result);
1906 }
1907 
1908 /*******************************************************************************
1909  *
1910  * Function         btm_read_failed_contact_counter_complete
1911  *
1912  * Description      This function is called when the command complete message
1913  *                  is received from the HCI for the read failed contact
1914  *                  counter request.
1915  *
1916  * Returns          void
1917  *
1918  ******************************************************************************/
btm_read_failed_contact_counter_complete(uint8_t * p)1919 void btm_read_failed_contact_counter_complete(uint8_t* p) {
1920   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_failed_contact_counter_cmpl_cb;
1921   tBTM_FAILED_CONTACT_COUNTER_RESULT result;
1922 
1923   alarm_cancel(btm_cb.devcb.read_failed_contact_counter_timer);
1924   btm_cb.devcb.p_failed_contact_counter_cmpl_cb = NULL;
1925 
1926   /* If there was a registered callback, call it */
1927   if (p_cb) {
1928     uint16_t handle;
1929     STREAM_TO_UINT8(result.hci_status, p);
1930 
1931     if (result.hci_status == HCI_SUCCESS) {
1932       result.status = BTM_SUCCESS;
1933 
1934       STREAM_TO_UINT16(handle, p);
1935 
1936       STREAM_TO_UINT16(result.failed_contact_counter, p);
1937       LOG_DEBUG(
1938           "Failed contact counter complete: counter %u, hci status:%s",
1939           result.failed_contact_counter,
1940           hci_status_code_text(to_hci_status_code(result.hci_status)).c_str());
1941 
1942       tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
1943       if (p_acl_cb != nullptr) {
1944         result.rem_bda = p_acl_cb->remote_addr;
1945       }
1946     } else {
1947       result.status = BTM_ERR_PROCESSING;
1948     }
1949 
1950     (*p_cb)(&result);
1951   }
1952 }
1953 
1954 /*******************************************************************************
1955  *
1956  * Function         btm_read_automatic_flush_timeout_complete
1957  *
1958  * Description      This function is called when the command complete message
1959  *                  is received from the HCI for the read automatic flush
1960  *                  timeout request.
1961  *
1962  * Returns          void
1963  *
1964  ******************************************************************************/
btm_read_automatic_flush_timeout_complete(uint8_t * p)1965 void btm_read_automatic_flush_timeout_complete(uint8_t* p) {
1966   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb;
1967   tBTM_AUTOMATIC_FLUSH_TIMEOUT_RESULT result;
1968 
1969   alarm_cancel(btm_cb.devcb.read_automatic_flush_timeout_timer);
1970   btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb = nullptr;
1971 
1972   /* If there was a registered callback, call it */
1973   if (p_cb) {
1974     uint16_t handle;
1975     STREAM_TO_UINT8(result.hci_status, p);
1976     result.status = BTM_ERR_PROCESSING;
1977 
1978     if (result.hci_status == HCI_SUCCESS) {
1979       result.status = BTM_SUCCESS;
1980 
1981       STREAM_TO_UINT16(handle, p);
1982       STREAM_TO_UINT16(result.automatic_flush_timeout, p);
1983       LOG_DEBUG(
1984           "Read automatic flush timeout complete timeout:%hu hci_status:%s",
1985           result.automatic_flush_timeout,
1986           hci_error_code_text(static_cast<tHCI_STATUS>(result.hci_status))
1987               .c_str());
1988 
1989       tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
1990       if (p_acl_cb != nullptr) {
1991         result.rem_bda = p_acl_cb->remote_addr;
1992       }
1993     }
1994     (*p_cb)(&result);
1995   }
1996 }
1997 
1998 /*******************************************************************************
1999  *
2000  * Function         btm_read_link_quality_timeout
2001  *
2002  * Description      Callback when reading the link quality times out.
2003  *
2004  * Returns          void
2005  *
2006  ******************************************************************************/
btm_read_link_quality_timeout(UNUSED_ATTR void * data)2007 void btm_read_link_quality_timeout(UNUSED_ATTR void* data) {
2008   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_link_qual_cmpl_cb;
2009   btm_cb.devcb.p_link_qual_cmpl_cb = NULL;
2010   if (p_cb) (*p_cb)((void*)NULL);
2011 }
2012 
2013 /*******************************************************************************
2014  *
2015  * Function         btm_read_link_quality_complete
2016  *
2017  * Description      This function is called when the command complete message
2018  *                  is received from the HCI for the read link quality.
2019  *
2020  * Returns          void
2021  *
2022  ******************************************************************************/
btm_read_link_quality_complete(uint8_t * p)2023 void btm_read_link_quality_complete(uint8_t* p) {
2024   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_link_qual_cmpl_cb;
2025   tBTM_LINK_QUALITY_RESULT result;
2026 
2027   alarm_cancel(btm_cb.devcb.read_link_quality_timer);
2028   btm_cb.devcb.p_link_qual_cmpl_cb = NULL;
2029 
2030   /* If there was a registered callback, call it */
2031   if (p_cb) {
2032     STREAM_TO_UINT8(result.hci_status, p);
2033 
2034     if (result.hci_status == HCI_SUCCESS) {
2035       uint16_t handle;
2036       result.status = BTM_SUCCESS;
2037 
2038       STREAM_TO_UINT16(handle, p);
2039 
2040       STREAM_TO_UINT8(result.link_quality, p);
2041       LOG_DEBUG("BTM Link Quality Complete: Link Quality %d, hci status:%s",
2042                 result.link_quality,
2043                 hci_error_code_text(static_cast<tHCI_STATUS>(result.hci_status))
2044                     .c_str());
2045 
2046       tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
2047       if (p_acl_cb != nullptr) {
2048         result.rem_bda = p_acl_cb->remote_addr;
2049       }
2050     } else {
2051       result.status = BTM_ERR_PROCESSING;
2052     }
2053 
2054     (*p_cb)(&result);
2055   }
2056 }
2057 
2058 /*******************************************************************************
2059  *
2060  * Function         btm_remove_acl
2061  *
2062  * Description      This function is called to disconnect an ACL connection
2063  *
2064  * Returns          BTM_SUCCESS if successfully initiated, otherwise
2065  *                  BTM_NO_RESOURCES.
2066  *
2067  ******************************************************************************/
btm_remove_acl(const RawAddress & bd_addr,tBT_TRANSPORT transport)2068 tBTM_STATUS btm_remove_acl(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
2069   if (bluetooth::shim::is_gd_l2cap_enabled()) {
2070     if (transport == BT_TRANSPORT_LE) {
2071       LOG(ERROR) << __func__ << ": Unsupported";
2072     }
2073     bluetooth::shim::L2CA_DisconnectLink(bd_addr);
2074     return BTM_SUCCESS;
2075   }
2076 
2077   tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, transport);
2078   if (p_acl == nullptr) {
2079     LOG_WARN("Unable to find active acl");
2080     return BTM_UNKNOWN_ADDR;
2081   }
2082 
2083   if (p_acl->Handle() == HCI_INVALID_HANDLE) {
2084     LOG_WARN("Cannot remove unknown acl bd_addr:%s transport:%s",
2085              PRIVATE_ADDRESS(bd_addr), bt_transport_text(transport).c_str());
2086     return BTM_UNKNOWN_ADDR;
2087   }
2088 
2089   if (p_acl->rs_disc_pending == BTM_SEC_RS_PENDING) {
2090     LOG_DEBUG(
2091         "Delay disconnect until role switch is complete bd_addr:%s "
2092         "transport:%s",
2093         PRIVATE_ADDRESS(bd_addr), bt_transport_text(transport).c_str());
2094     p_acl->rs_disc_pending = BTM_SEC_DISC_PENDING;
2095     return BTM_SUCCESS;
2096   }
2097 
2098   hci_btsnd_hcic_disconnect(*p_acl, HCI_ERR_PEER_USER);
2099   return BTM_SUCCESS;
2100 }
2101 
2102 /*******************************************************************************
2103  *
2104  * Function         BTM_SetTraceLevel
2105  *
2106  * Description      This function sets the trace level for BTM.  If called with
2107  *                  a value of 0xFF, it simply returns the current trace level.
2108  *
2109  * Returns          The new or current trace level
2110  *
2111  ******************************************************************************/
BTM_SetTraceLevel(uint8_t new_level)2112 uint8_t BTM_SetTraceLevel(uint8_t new_level) {
2113   if (new_level != 0xFF) btm_cb.trace_level = new_level;
2114 
2115   return (btm_cb.trace_level);
2116 }
2117 
btm_cont_rswitch_from_handle(uint16_t hci_handle)2118 void btm_cont_rswitch_from_handle(uint16_t hci_handle) {
2119   tACL_CONN* p = internal_.acl_get_connection_from_handle(hci_handle);
2120   if (p == nullptr) {
2121     LOG_WARN("Role switch received but with no active ACL");
2122     return;
2123   }
2124 
2125   /* Check to see if encryption needs to be turned off if pending
2126    change of link key or role switch */
2127   if (p->is_switch_role_mode_change()) {
2128     /* Must turn off Encryption first if necessary */
2129     /* Some devices do not support switch or change of link key while encryption
2130      * is on */
2131     if (p->is_encrypted && !IsEprAvailable(*p)) {
2132       p->set_encryption_off();
2133       if (p->is_switch_role_mode_change()) {
2134         p->set_switch_role_encryption_off();
2135       }
2136     } else /* Encryption not used or EPR supported, continue with switch
2137               and/or change of link key */
2138     {
2139       if (p->is_switch_role_mode_change()) {
2140         internal_.hci_start_role_switch_to_central(*p);
2141       }
2142     }
2143   }
2144 }
2145 
2146 /*******************************************************************************
2147  *
2148  * Function         btm_acl_resubmit_page
2149  *
2150  * Description      send pending page request
2151  *
2152  ******************************************************************************/
btm_acl_resubmit_page(void)2153 void btm_acl_resubmit_page(void) {
2154   BT_HDR* p_buf;
2155   uint8_t* pp;
2156   /* If there were other page request schedule can start the next one */
2157   p_buf = (BT_HDR*)fixed_queue_try_dequeue(btm_cb.page_queue);
2158   if (p_buf != NULL) {
2159     /* skip 3 (2 bytes opcode and 1 byte len) to get to the bd_addr
2160      * for both create_conn and rmt_name */
2161     pp = (uint8_t*)(p_buf + 1) + p_buf->offset + 3;
2162 
2163     RawAddress bda;
2164     STREAM_TO_BDADDR(bda, pp);
2165 
2166     btm_cb.connecting_bda = bda;
2167     memcpy(btm_cb.connecting_dc, btm_get_dev_class(bda), DEV_CLASS_LEN);
2168 
2169     btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p_buf);
2170   } else {
2171     btm_cb.paging = false;
2172   }
2173 }
2174 
2175 /*******************************************************************************
2176  *
2177  * Function         btm_acl_reset_paging
2178  *
2179  * Description      set paging to false and free the page queue - called at
2180  *                  hci_reset
2181  *
2182  ******************************************************************************/
btm_acl_reset_paging(void)2183 void btm_acl_reset_paging(void) {
2184   BT_HDR* p;
2185   /* If we sent reset we are definitely not paging any more */
2186   while ((p = (BT_HDR*)fixed_queue_try_dequeue(btm_cb.page_queue)) != NULL)
2187     osi_free(p);
2188 
2189   btm_cb.paging = false;
2190 }
2191 
2192 /*******************************************************************************
2193  *
2194  * Function         btm_acl_paging
2195  *
2196  * Description      send a paging command or queue it in btm_cb
2197  *
2198  ******************************************************************************/
btm_acl_paging(BT_HDR * p,const RawAddress & bda)2199 void btm_acl_paging(BT_HDR* p, const RawAddress& bda) {
2200   // This function is called by the device initiating the connection.
2201   // If no role change is requested from the remote device, we want
2202   // to classify the connection initiator as the central device.
2203   if (delayed_role_change_ == nullptr) {
2204     RoleChangeView role_change;
2205     role_change.bd_addr = bda;
2206     role_change.new_role = HCI_ROLE_CENTRAL;
2207     delayed_role_change_ =
2208         std::make_unique<RoleChangeView>(std::move(role_change));
2209   }
2210   if (!BTM_IsAclConnectionUp(bda, BT_TRANSPORT_BR_EDR)) {
2211     VLOG(1) << "connecting_bda: " << btm_cb.connecting_bda;
2212     if (btm_cb.paging && bda == btm_cb.connecting_bda) {
2213       fixed_queue_enqueue(btm_cb.page_queue, p);
2214     } else {
2215       btm_cb.connecting_bda = bda;
2216       memcpy(btm_cb.connecting_dc, btm_get_dev_class(bda), DEV_CLASS_LEN);
2217 
2218       btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
2219     }
2220 
2221     btm_cb.paging = true;
2222   } else /* ACL is already up */
2223   {
2224     btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
2225   }
2226 }
2227 
2228 /*******************************************************************************
2229  *
2230  * Function         btm_acl_notif_conn_collision
2231  *
2232  * Description      Send connection collision event to upper layer if registered
2233  *
2234  *
2235  ******************************************************************************/
btm_acl_notif_conn_collision(const RawAddress & bda)2236 void btm_acl_notif_conn_collision(const RawAddress& bda) {
2237   do_in_main_thread(FROM_HERE, base::Bind(bta_sys_notify_collision, bda));
2238 }
2239 
BTM_BLE_IS_RESOLVE_BDA(const RawAddress & x)2240 bool BTM_BLE_IS_RESOLVE_BDA(const RawAddress& x) {
2241   return ((x.address)[0] & BLE_RESOLVE_ADDR_MASK) == BLE_RESOLVE_ADDR_MSB;
2242 }
2243 
acl_refresh_remote_address(const RawAddress & identity_address,tBLE_ADDR_TYPE identity_address_type,const RawAddress & bda,tBLE_ADDR_TYPE rra_type,const RawAddress & rpa)2244 bool acl_refresh_remote_address(const RawAddress& identity_address,
2245                                 tBLE_ADDR_TYPE identity_address_type,
2246                                 const RawAddress& bda, tBLE_ADDR_TYPE rra_type,
2247                                 const RawAddress& rpa) {
2248   tACL_CONN* p_acl = internal_.btm_bda_to_acl(bda, BT_TRANSPORT_LE);
2249   if (p_acl == nullptr) {
2250     LOG_WARN("Unable to find active acl");
2251     return false;
2252   }
2253 
2254   if (rra_type == tBTM_SEC_BLE::BTM_BLE_ADDR_PSEUDO) {
2255     /* use identity address, resolvable_private_addr is empty */
2256     if (rpa.IsEmpty()) {
2257       p_acl->active_remote_addr_type = identity_address_type;
2258       p_acl->active_remote_addr = identity_address;
2259     } else {
2260       p_acl->active_remote_addr_type = BLE_ADDR_RANDOM;
2261       p_acl->active_remote_addr = rpa;
2262     }
2263   } else {
2264     p_acl->active_remote_addr_type = rra_type;
2265     p_acl->active_remote_addr = rpa;
2266   }
2267 
2268   LOG_DEBUG("active_remote_addr_type: %d ", p_acl->active_remote_addr_type);
2269   return true;
2270 }
2271 
acl_peer_supports_ble_connection_parameters_request(const RawAddress & remote_bda)2272 bool acl_peer_supports_ble_connection_parameters_request(
2273     const RawAddress& remote_bda) {
2274   tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE);
2275   if (p_acl == nullptr) {
2276     LOG_WARN("Unable to find active acl");
2277     return false;
2278   }
2279   if (!p_acl->peer_le_features_valid) {
2280     LOG_WARN(
2281         "Checking remote features but remote feature read is "
2282         "incomplete");
2283   }
2284   return HCI_LE_CONN_PARAM_REQ_SUPPORTED(p_acl->peer_le_features);
2285 }
2286 
acl_peer_supports_sniff_subrating(const RawAddress & remote_bda)2287 bool acl_peer_supports_sniff_subrating(const RawAddress& remote_bda) {
2288   tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
2289   if (p_acl == nullptr) {
2290     LOG_WARN("Unable to find active acl");
2291     return false;
2292   }
2293   if (!p_acl->peer_lmp_feature_valid[0]) {
2294     LOG_WARN(
2295         "Checking remote features but remote feature read is "
2296         "incomplete");
2297   }
2298   return HCI_SNIFF_SUB_RATE_SUPPORTED(p_acl->peer_lmp_feature_pages[0]);
2299 }
2300 
2301 /*******************************************************************************
2302  *
2303  * Function         BTM_ReadConnectionAddr
2304  *
2305  * Description      This function is called to get the local device address
2306  *                  information.
2307  *
2308  * Returns          void
2309  *
2310  ******************************************************************************/
BTM_ReadConnectionAddr(const RawAddress & remote_bda,RawAddress & local_conn_addr,tBLE_ADDR_TYPE * p_addr_type)2311 void BTM_ReadConnectionAddr(const RawAddress& remote_bda,
2312                             RawAddress& local_conn_addr,
2313                             tBLE_ADDR_TYPE* p_addr_type) {
2314   if (bluetooth::shim::is_gd_shim_enabled()) {
2315     return bluetooth::shim::BTM_ReadConnectionAddr(remote_bda, local_conn_addr,
2316                                                    p_addr_type);
2317   }
2318 
2319   if (bluetooth::shim::is_gd_l2cap_enabled()) {
2320     bluetooth::shim::L2CA_ReadConnectionAddr(remote_bda, local_conn_addr,
2321                                              p_addr_type);
2322     return;
2323   } else if (bluetooth::shim::is_gd_scanning_enabled()) {
2324     bluetooth::shim::ACL_ReadConnectionAddress(remote_bda, local_conn_addr,
2325                                                p_addr_type);
2326     return;
2327   }
2328 
2329   tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE);
2330 
2331   if (p_acl == NULL) {
2332     LOG_WARN("Unable to find active acl");
2333     return;
2334   }
2335   local_conn_addr = p_acl->conn_addr;
2336   *p_addr_type = p_acl->conn_addr_type;
2337 
2338   LOG_DEBUG("BTM_ReadConnectionAddr address type: %d addr: 0x%02x",
2339             p_acl->conn_addr_type, p_acl->conn_addr.address[0]);
2340 }
2341 
2342 /*******************************************************************************
2343  *
2344  * Function         BTM_IsBleConnection
2345  *
2346  * Description      This function is called to check if the connection handle
2347  *                  for an LE link
2348  *
2349  * Returns          true if connection is LE link, otherwise false.
2350  *
2351  ******************************************************************************/
BTM_IsBleConnection(uint16_t hci_handle)2352 bool BTM_IsBleConnection(uint16_t hci_handle) {
2353   if (bluetooth::shim::is_gd_shim_enabled()) {
2354     ASSERT_LOG(false, "This should not be invoked from code path");
2355   }
2356 
2357   if (bluetooth::shim::is_gd_l2cap_enabled()) {
2358     return bluetooth::shim::L2CA_IsLeLink(hci_handle);
2359   }
2360 
2361   const tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(hci_handle);
2362   if (p_acl == nullptr) return false;
2363   return p_acl->is_transport_ble();
2364 }
2365 
acl_address_from_handle(uint16_t handle)2366 const RawAddress acl_address_from_handle(uint16_t handle) {
2367   tACL_CONN* p_acl = acl_get_connection_from_handle(handle);
2368   if (p_acl == nullptr) {
2369     return RawAddress::kEmpty;
2370   }
2371   return p_acl->remote_addr;
2372 }
2373 
2374 /*******************************************************************************
2375  *
2376  * Function         btm_ble_refresh_local_resolvable_private_addr
2377  *
2378  * Description      This function refresh the currently used resolvable private
2379  *                  address for the active link to the remote device
2380  *
2381  ******************************************************************************/
btm_ble_refresh_local_resolvable_private_addr(const RawAddress & pseudo_addr,const RawAddress & local_rpa)2382 void btm_ble_refresh_local_resolvable_private_addr(
2383     const RawAddress& pseudo_addr, const RawAddress& local_rpa) {
2384   tACL_CONN* p_acl = internal_.btm_bda_to_acl(pseudo_addr, BT_TRANSPORT_LE);
2385   if (p_acl == nullptr) {
2386     LOG_WARN("Unable to find active acl");
2387     return;
2388   }
2389 
2390   if (btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_NONE) {
2391     p_acl->conn_addr_type = BLE_ADDR_PUBLIC;
2392     p_acl->conn_addr = *controller_get_interface()->get_address();
2393   } else {
2394     p_acl->conn_addr_type = BLE_ADDR_RANDOM;
2395     if (local_rpa.IsEmpty()) {
2396       p_acl->conn_addr = btm_cb.ble_ctr_cb.addr_mgnt_cb.private_addr;
2397     } else {
2398       p_acl->conn_addr = local_rpa;
2399     }
2400   }
2401 }
2402 
sco_peer_supports_esco_2m_phy(const RawAddress & remote_bda)2403 bool sco_peer_supports_esco_2m_phy(const RawAddress& remote_bda) {
2404   uint8_t* features = BTM_ReadRemoteFeatures(remote_bda);
2405   if (features == nullptr) {
2406     LOG_WARN(
2407         "Checking remote features but remote feature read is "
2408         "incomplete");
2409     return false;
2410   }
2411   return HCI_EDR_ESCO_2MPS_SUPPORTED(features);
2412 }
2413 
sco_peer_supports_esco_3m_phy(const RawAddress & remote_bda)2414 bool sco_peer_supports_esco_3m_phy(const RawAddress& remote_bda) {
2415   uint8_t* features = BTM_ReadRemoteFeatures(remote_bda);
2416   if (features == nullptr) {
2417     LOG_WARN(
2418         "Checking remote features but remote feature read is "
2419         "incomplete");
2420     return false;
2421   }
2422   return HCI_EDR_ESCO_3MPS_SUPPORTED(features);
2423 }
2424 
acl_is_switch_role_idle(const RawAddress & bd_addr,tBT_TRANSPORT transport)2425 bool acl_is_switch_role_idle(const RawAddress& bd_addr,
2426                              tBT_TRANSPORT transport) {
2427   tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, transport);
2428   if (p_acl == nullptr) {
2429     LOG_WARN("Unable to find active acl");
2430     return false;
2431   }
2432   return p_acl->is_switch_role_idle();
2433 }
2434 
2435 /*******************************************************************************
2436  *
2437  * Function       BTM_ReadRemoteConnectionAddr
2438  *
2439  * Description    This function is read the remote device address currently used
2440  *
2441  * Parameters     pseudo_addr: pseudo random address available
2442  *                conn_addr:connection address used
2443  *                p_addr_type : BD Address type, Public or Random of the address
2444  *                              used
2445  *
2446  * Returns        bool, true if connection to remote device exists, else false
2447  *
2448  ******************************************************************************/
BTM_ReadRemoteConnectionAddr(const RawAddress & pseudo_addr,RawAddress & conn_addr,tBLE_ADDR_TYPE * p_addr_type)2449 bool BTM_ReadRemoteConnectionAddr(const RawAddress& pseudo_addr,
2450                                   RawAddress& conn_addr,
2451                                   tBLE_ADDR_TYPE* p_addr_type) {
2452   if (bluetooth::shim::is_gd_shim_enabled()) {
2453     return bluetooth::shim::BTM_ReadRemoteConnectionAddr(pseudo_addr, conn_addr,
2454                                                          p_addr_type);
2455   }
2456 
2457   if (bluetooth::shim::is_gd_l2cap_enabled()) {
2458     return bluetooth::shim::L2CA_ReadRemoteConnectionAddr(
2459         pseudo_addr, conn_addr, p_addr_type);
2460   }
2461 
2462   bool st = true;
2463   tACL_CONN* p_acl = internal_.btm_bda_to_acl(pseudo_addr, BT_TRANSPORT_LE);
2464 
2465   if (p_acl == NULL) {
2466     LOG_WARN("Unable to find active acl");
2467     return false;
2468   }
2469 
2470   conn_addr = p_acl->active_remote_addr;
2471   *p_addr_type = p_acl->active_remote_addr_type;
2472   return st;
2473 }
2474 
acl_link_role_from_handle(uint16_t handle)2475 uint8_t acl_link_role_from_handle(uint16_t handle) {
2476   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
2477   if (p_acl == nullptr) {
2478     return HCI_ROLE_UNKNOWN;
2479   }
2480   return p_acl->link_role;
2481 }
2482 
acl_peer_supports_ble_packet_extension(uint16_t hci_handle)2483 bool acl_peer_supports_ble_packet_extension(uint16_t hci_handle) {
2484   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(hci_handle);
2485   if (p_acl == nullptr) {
2486     return false;
2487   }
2488   if (!p_acl->peer_le_features_valid) {
2489     LOG_WARN(
2490         "Checking remote features but remote feature read is "
2491         "incomplete");
2492   }
2493   return HCI_LE_DATA_LEN_EXT_SUPPORTED(p_acl->peer_le_features);
2494 }
2495 
acl_peer_supports_ble_2m_phy(uint16_t hci_handle)2496 bool acl_peer_supports_ble_2m_phy(uint16_t hci_handle) {
2497   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(hci_handle);
2498   if (p_acl == nullptr) {
2499     return false;
2500   }
2501   if (!p_acl->peer_le_features_valid) {
2502     LOG_WARN(
2503         "Checking remote features but remote feature read is "
2504         "incomplete");
2505   }
2506   return HCI_LE_2M_PHY_SUPPORTED(p_acl->peer_le_features);
2507 }
2508 
acl_peer_supports_ble_coded_phy(uint16_t hci_handle)2509 bool acl_peer_supports_ble_coded_phy(uint16_t hci_handle) {
2510   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(hci_handle);
2511   if (p_acl == nullptr) {
2512     return false;
2513   }
2514   if (!p_acl->peer_le_features_valid) {
2515     LOG_WARN(
2516         "Checking remote features but remote feature read is "
2517         "incomplete");
2518     return false;
2519   }
2520   return HCI_LE_CODED_PHY_SUPPORTED(p_acl->peer_le_features);
2521 }
2522 
acl_set_disconnect_reason(tHCI_STATUS acl_disc_reason)2523 void acl_set_disconnect_reason(tHCI_STATUS acl_disc_reason) {
2524   btm_cb.acl_cb_.set_disconnect_reason(acl_disc_reason);
2525 }
2526 
acl_is_role_switch_allowed()2527 bool acl_is_role_switch_allowed() {
2528   return btm_cb.acl_cb_.DefaultLinkPolicy() &
2529          HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH;
2530 }
2531 
acl_get_supported_packet_types()2532 uint16_t acl_get_supported_packet_types() {
2533   return btm_cb.acl_cb_.DefaultPacketTypes();
2534 }
2535 
acl_set_peer_le_features_from_handle(uint16_t hci_handle,const uint8_t * p)2536 bool acl_set_peer_le_features_from_handle(uint16_t hci_handle,
2537                                           const uint8_t* p) {
2538   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(hci_handle);
2539   if (p_acl == nullptr) {
2540     return false;
2541   }
2542   STREAM_TO_ARRAY(p_acl->peer_le_features, p, BD_FEATURES_LEN);
2543   p_acl->peer_le_features_valid = true;
2544   LOG_DEBUG("Completed le feature read request");
2545   return true;
2546 }
2547 
on_acl_br_edr_connected(const RawAddress & bda,uint16_t handle,uint8_t enc_mode)2548 void on_acl_br_edr_connected(const RawAddress& bda, uint16_t handle,
2549                              uint8_t enc_mode) {
2550   if (delayed_role_change_ != nullptr && delayed_role_change_->bd_addr == bda) {
2551     btm_sec_connected(bda, handle, HCI_SUCCESS, enc_mode,
2552                       delayed_role_change_->new_role);
2553   } else {
2554     btm_sec_connected(bda, handle, HCI_SUCCESS, enc_mode);
2555   }
2556   delayed_role_change_ = nullptr;
2557   btm_acl_set_paging(false);
2558   l2c_link_hci_conn_comp(HCI_SUCCESS, handle, bda);
2559   constexpr uint16_t link_supervision_timeout = 8000;
2560   BTM_SetLinkSuperTout(bda, link_supervision_timeout);
2561 
2562   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
2563   if (p_acl == nullptr) {
2564     LOG_WARN("Unable to find active acl");
2565     return;
2566   }
2567 
2568   /*
2569    * The legacy code path informs the upper layer via the BTA
2570    * layer after all relevant read_remote_ commands are complete.
2571    * The GD code path has ownership of the read_remote_ commands
2572    * and thus may inform the upper layers about the connection.
2573    */
2574   if (bluetooth::shim::is_gd_acl_enabled()) {
2575     NotifyAclLinkUp(*p_acl);
2576   }
2577 }
2578 
on_acl_br_edr_failed(const RawAddress & bda,tHCI_STATUS status)2579 void on_acl_br_edr_failed(const RawAddress& bda, tHCI_STATUS status) {
2580   ASSERT_LOG(status != HCI_SUCCESS,
2581              "Successful connection entering failing code path");
2582   if (delayed_role_change_ != nullptr && delayed_role_change_->bd_addr == bda) {
2583     btm_sec_connected(bda, HCI_INVALID_HANDLE, status, false,
2584                       delayed_role_change_->new_role);
2585   } else {
2586     btm_sec_connected(bda, HCI_INVALID_HANDLE, status, false);
2587   }
2588   delayed_role_change_ = nullptr;
2589   btm_acl_set_paging(false);
2590   l2c_link_hci_conn_comp(status, HCI_INVALID_HANDLE, bda);
2591 }
2592 
btm_acl_connected(const RawAddress & bda,uint16_t handle,tHCI_STATUS status,uint8_t enc_mode)2593 void btm_acl_connected(const RawAddress& bda, uint16_t handle,
2594                        tHCI_STATUS status, uint8_t enc_mode) {
2595   switch (status) {
2596     case HCI_SUCCESS:
2597       return on_acl_br_edr_connected(bda, handle, enc_mode);
2598     default:
2599       return on_acl_br_edr_failed(bda, status);
2600   }
2601 }
2602 
btm_acl_disconnected(tHCI_STATUS status,uint16_t handle,tHCI_REASON reason)2603 void btm_acl_disconnected(tHCI_STATUS status, uint16_t handle,
2604                           tHCI_REASON reason) {
2605   if (status != HCI_SUCCESS) {
2606     LOG_WARN("Received disconnect with error:%s",
2607              hci_error_code_text(status).c_str());
2608   }
2609 
2610   /* There can be a case when we rejected PIN code authentication */
2611   /* otherwise save a new reason */
2612   if (btm_get_acl_disc_reason_code() != HCI_ERR_HOST_REJECT_SECURITY) {
2613     acl_set_disconnect_reason(static_cast<tHCI_STATUS>(reason));
2614   }
2615 
2616   /* If L2CAP or SCO doesn't know about it, send it to ISO */
2617   if (!l2c_link_hci_disc_comp(handle, reason) &&
2618       !btm_sco_removed(handle, reason)) {
2619     bluetooth::hci::IsoManager::GetInstance()->HandleDisconnect(handle, reason);
2620   }
2621 
2622   /* Notify security manager */
2623   btm_sec_disconnected(handle, reason);
2624 }
2625 
2626 constexpr uint16_t kDefaultPacketTypes =
2627     HCI_PKT_TYPES_MASK_DM1 | HCI_PKT_TYPES_MASK_DH1 | HCI_PKT_TYPES_MASK_DM3 |
2628     HCI_PKT_TYPES_MASK_DH3 | HCI_PKT_TYPES_MASK_DM5 | HCI_PKT_TYPES_MASK_DH5;
2629 
acl_create_classic_connection(const RawAddress & bd_addr,bool there_are_high_priority_channels,bool is_bonding)2630 void acl_create_classic_connection(const RawAddress& bd_addr,
2631                                    bool there_are_high_priority_channels,
2632                                    bool is_bonding) {
2633   if (bluetooth::shim::is_gd_acl_enabled()) {
2634     return bluetooth::shim::ACL_CreateClassicConnection(bd_addr);
2635   }
2636 
2637   const bool controller_supports_role_switch =
2638       controller_get_interface()->supports_role_switch();
2639   const bool acl_allows_role_switch = acl_is_role_switch_allowed();
2640 
2641   /* FW team says that we can participant in 4 piconets
2642    * typically 3 piconet + 1 for scanning.
2643    * We can enhance the code to count the number of piconets later. */
2644   uint8_t allow_role_switch = HCI_CR_CONN_NOT_ALLOW_SWITCH;
2645   if (((acl_allows_role_switch && (BTM_GetNumAclLinks() < 3)) ||
2646        (is_bonding && !there_are_high_priority_channels &&
2647         controller_supports_role_switch)))
2648     allow_role_switch = HCI_CR_CONN_ALLOW_SWITCH;
2649 
2650   /* Check with the BT manager if details about remote device are known */
2651   uint8_t page_scan_rep_mode{HCI_PAGE_SCAN_REP_MODE_R1};
2652   uint8_t page_scan_mode{HCI_MANDATARY_PAGE_SCAN_MODE};
2653   uint16_t clock_offset = BTM_GetClockOffset(bd_addr);
2654 
2655   tBTM_INQ_INFO* p_inq_info = BTM_InqDbRead(bd_addr);
2656   if (p_inq_info != nullptr &&
2657       (p_inq_info->results.inq_result_type & BTM_INQ_RESULT_BR)) {
2658     page_scan_rep_mode = p_inq_info->results.page_scan_rep_mode;
2659     page_scan_mode = p_inq_info->results.page_scan_mode;
2660     clock_offset = p_inq_info->results.clock_offset;
2661   }
2662 
2663   btsnd_hcic_create_conn(bd_addr, kDefaultPacketTypes, page_scan_rep_mode,
2664                          page_scan_mode, clock_offset, allow_role_switch);
2665   btm_acl_set_paging(true);
2666 }
2667 
btm_acl_connection_request(const RawAddress & bda,uint8_t * dc)2668 void btm_acl_connection_request(const RawAddress& bda, uint8_t* dc) {
2669   btm_sec_conn_req(bda, dc);
2670   l2c_link_hci_conn_req(bda);
2671 }
2672 
acl_accept_connection_request(const RawAddress & bd_addr,uint8_t role)2673 void acl_accept_connection_request(const RawAddress& bd_addr, uint8_t role) {
2674   btsnd_hcic_accept_conn(bd_addr, role);
2675 }
2676 
acl_reject_connection_request(const RawAddress & bd_addr,uint8_t reason)2677 void acl_reject_connection_request(const RawAddress& bd_addr, uint8_t reason) {
2678   btsnd_hcic_reject_conn(bd_addr, reason);
2679 }
2680 
acl_disconnect_from_handle(uint16_t handle,tHCI_STATUS reason)2681 void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason) {
2682   acl_disconnect_after_role_switch(handle, reason);
2683 }
2684 
acl_disconnect_after_role_switch(uint16_t conn_handle,tHCI_STATUS reason)2685 void acl_disconnect_after_role_switch(uint16_t conn_handle,
2686                                       tHCI_STATUS reason) {
2687   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(conn_handle);
2688   if (p_acl == nullptr) {
2689     LOG_ERROR("Sending disconnect for unknown acl:%hu PLEASE FIX", conn_handle);
2690     GetLegacyHciInterface().Disconnect(conn_handle, reason);
2691     return;
2692   }
2693 
2694   /* If a role switch is in progress, delay the HCI Disconnect to avoid
2695    * controller problem */
2696   if (p_acl->rs_disc_pending == BTM_SEC_RS_PENDING) {
2697     LOG_DEBUG(
2698         "Role switch in progress - Set DISC Pending flag in "
2699         "btm_sec_send_hci_disconnect "
2700         "to delay disconnect");
2701     p_acl->rs_disc_pending = BTM_SEC_DISC_PENDING;
2702   } else {
2703     LOG_DEBUG("Sending acl disconnect reason:%s [%hu]",
2704               hci_error_code_text(reason).c_str(), reason);
2705     hci_btsnd_hcic_disconnect(*p_acl, reason);
2706   }
2707 }
2708 
2709 constexpr uint16_t kDataPacketEventBrEdr = (BT_EVT_TO_LM_HCI_ACL);
2710 constexpr uint16_t kDataPacketEventBle =
2711     (BT_EVT_TO_LM_HCI_ACL | LOCAL_BLE_CONTROLLER_ID);
2712 
acl_send_data_packet_br_edr(const RawAddress & bd_addr,BT_HDR * p_buf)2713 void acl_send_data_packet_br_edr(const RawAddress& bd_addr, BT_HDR* p_buf) {
2714   if (bluetooth::shim::is_gd_acl_enabled()) {
2715     tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
2716     if (p_acl == nullptr) {
2717       LOG_WARN("Acl br_edr data write for unknown device:%s",
2718                PRIVATE_ADDRESS(bd_addr));
2719       osi_free(p_buf);
2720       return;
2721     }
2722     return bluetooth::shim::ACL_WriteData(p_acl->hci_handle, p_buf);
2723   }
2724   bte_main_hci_send(p_buf, kDataPacketEventBrEdr);
2725 }
2726 
acl_send_data_packet_ble(const RawAddress & bd_addr,BT_HDR * p_buf)2727 void acl_send_data_packet_ble(const RawAddress& bd_addr, BT_HDR* p_buf) {
2728   if (bluetooth::shim::is_gd_acl_enabled()) {
2729     tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_LE);
2730     if (p_acl == nullptr) {
2731       LOG_WARN("Acl le data write for unknown device:%s",
2732                PRIVATE_ADDRESS(bd_addr));
2733       osi_free(p_buf);
2734       return;
2735     }
2736     return bluetooth::shim::ACL_WriteData(p_acl->hci_handle, p_buf);
2737   }
2738   bte_main_hci_send(p_buf, kDataPacketEventBle);
2739 }
2740 
acl_write_automatic_flush_timeout(const RawAddress & bd_addr,uint16_t flush_timeout_in_ticks)2741 void acl_write_automatic_flush_timeout(const RawAddress& bd_addr,
2742                                        uint16_t flush_timeout_in_ticks) {
2743   tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
2744   if (p_acl == nullptr) {
2745     LOG_WARN("Unable to find active acl");
2746     return;
2747   }
2748   if (p_acl->flush_timeout_in_ticks == flush_timeout_in_ticks) {
2749     LOG_INFO(
2750         "Ignoring since cached value is same as requested flush_timeout:%hd",
2751         flush_timeout_in_ticks);
2752     return;
2753   }
2754   flush_timeout_in_ticks &= HCI_MAX_AUTOMATIC_FLUSH_TIMEOUT;
2755   p_acl->flush_timeout_in_ticks = flush_timeout_in_ticks;
2756   btsnd_hcic_write_auto_flush_tout(p_acl->hci_handle, flush_timeout_in_ticks);
2757 }
2758 
acl_create_le_connection_with_id(uint8_t id,const RawAddress & bd_addr)2759 bool acl_create_le_connection_with_id(uint8_t id, const RawAddress& bd_addr) {
2760   if (bluetooth::shim::is_gd_acl_enabled()) {
2761     tBLE_BD_ADDR address_with_type{
2762         .bda = bd_addr,
2763         .type = BLE_ADDR_RANDOM,
2764     };
2765     gatt_find_in_device_record(bd_addr, &address_with_type);
2766     LOG_DEBUG("Creating le connection to:%s",
2767               address_with_type.ToString().c_str());
2768     bluetooth::shim::ACL_AcceptLeConnectionFrom(address_with_type,
2769                                                 /* is_direct */ true);
2770     return true;
2771   }
2772   return connection_manager::direct_connect_add(id, bd_addr);
2773 }
2774 
acl_create_le_connection(const RawAddress & bd_addr)2775 bool acl_create_le_connection(const RawAddress& bd_addr) {
2776   return acl_create_le_connection_with_id(CONN_MGR_ID_L2CAP, bd_addr);
2777 }
2778 
acl_rcv_acl_data(BT_HDR * p_msg)2779 void acl_rcv_acl_data(BT_HDR* p_msg) {
2780   acl_header_t acl_header{
2781       .handle = HCI_INVALID_HANDLE,
2782       .hci_len = 0,
2783   };
2784   const uint8_t* p = (uint8_t*)(p_msg + 1) + p_msg->offset;
2785 
2786   STREAM_TO_UINT16(acl_header.handle, p);
2787   acl_header.handle = HCID_GET_HANDLE(acl_header.handle);
2788 
2789   STREAM_TO_UINT16(acl_header.hci_len, p);
2790   if (acl_header.hci_len < L2CAP_PKT_OVERHEAD ||
2791       acl_header.hci_len != p_msg->len - sizeof(acl_header)) {
2792     LOG_WARN("Received mismatched hci header length:%u data_len:%zu",
2793              acl_header.hci_len, p_msg->len - sizeof(acl_header));
2794     osi_free(p_msg);
2795     return;
2796   }
2797   l2c_rcv_acl_data(p_msg);
2798 }
2799 
acl_link_segments_xmitted(BT_HDR * p_msg)2800 void acl_link_segments_xmitted(BT_HDR* p_msg) {
2801   l2c_link_segments_xmitted(p_msg);
2802 }
2803 
acl_packets_completed(uint16_t handle,uint16_t credits)2804 void acl_packets_completed(uint16_t handle, uint16_t credits) {
2805   l2c_packets_completed(handle, credits);
2806 }
2807 
acl_parse_num_completed_pkts(uint8_t * p,uint8_t evt_len)2808 static void acl_parse_num_completed_pkts(uint8_t* p, uint8_t evt_len) {
2809   if (evt_len == 0) {
2810     LOG_ERROR("Received num completed packets with zero length");
2811     return;
2812   }
2813 
2814   uint8_t num_handles{0};
2815   STREAM_TO_UINT8(num_handles, p);
2816 
2817   if (num_handles > evt_len / (2 * sizeof(uint16_t))) {
2818     android_errorWriteLog(0x534e4554, "141617601");
2819     num_handles = evt_len / (2 * sizeof(uint16_t));
2820   }
2821 
2822   for (uint8_t xx = 0; xx < num_handles; xx++) {
2823     uint16_t handle{0};
2824     uint16_t num_packets{0};
2825     STREAM_TO_UINT16(handle, p);
2826     handle = HCID_GET_HANDLE(handle);
2827     STREAM_TO_UINT16(num_packets, p);
2828     acl_packets_completed(handle, num_packets);
2829   }
2830 }
2831 
acl_process_num_completed_pkts(uint8_t * p,uint8_t evt_len)2832 void acl_process_num_completed_pkts(uint8_t* p, uint8_t evt_len) {
2833   if (bluetooth::shim::is_gd_acl_enabled()) {
2834     acl_parse_num_completed_pkts(p, evt_len);
2835   } else {
2836     l2c_link_process_num_completed_pkts(p, evt_len);
2837   }
2838   bluetooth::hci::IsoManager::GetInstance()->HandleNumComplDataPkts(p, evt_len);
2839 }
2840 
acl_process_supported_features(uint16_t handle,uint64_t features)2841 void acl_process_supported_features(uint16_t handle, uint64_t features) {
2842   ASSERT_LOG(bluetooth::shim::is_gd_acl_enabled(),
2843              "Should only be called when gd_acl enabled");
2844 
2845   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
2846   if (p_acl == nullptr) {
2847     LOG_WARN("Unable to find active acl");
2848     return;
2849   }
2850   const uint8_t current_page_number = 0;
2851 
2852   memcpy(p_acl->peer_lmp_feature_pages[current_page_number],
2853          (uint8_t*)&features, sizeof(uint64_t));
2854   p_acl->peer_lmp_feature_valid[current_page_number] = true;
2855 
2856   LOG_DEBUG(
2857       "Copied supported feature pages handle:%hu current_page_number:%hhu "
2858       "features:%s",
2859       handle, current_page_number,
2860       bd_features_text(p_acl->peer_lmp_feature_pages[current_page_number])
2861           .c_str());
2862 
2863   if ((HCI_LMP_EXTENDED_SUPPORTED(p_acl->peer_lmp_feature_pages[0])) &&
2864       (controller_get_interface()
2865            ->supports_reading_remote_extended_features())) {
2866     LOG_DEBUG("Waiting for remote extended feature response to arrive");
2867   } else {
2868     LOG_DEBUG("No more remote features outstanding so notify upper layer");
2869     NotifyAclFeaturesReadComplete(*p_acl, current_page_number);
2870   }
2871 }
2872 
acl_process_extended_features(uint16_t handle,uint8_t current_page_number,uint8_t max_page_number,uint64_t features)2873 void acl_process_extended_features(uint16_t handle, uint8_t current_page_number,
2874                                    uint8_t max_page_number, uint64_t features) {
2875   ASSERT_LOG(bluetooth::shim::is_gd_acl_enabled(),
2876              "Should only be called when gd_acl enabled");
2877 
2878   if (current_page_number > HCI_EXT_FEATURES_PAGE_MAX) {
2879     LOG_WARN("Unable to process current_page_number:%hhu", current_page_number);
2880     return;
2881   }
2882   tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
2883   if (p_acl == nullptr) {
2884     LOG_WARN("Unable to find active acl");
2885     return;
2886   }
2887   memcpy(p_acl->peer_lmp_feature_pages[current_page_number],
2888          (uint8_t*)&features, sizeof(uint64_t));
2889   p_acl->peer_lmp_feature_valid[current_page_number] = true;
2890 
2891   LOG_DEBUG(
2892       "Copied extended feature pages handle:%hu current_page_number:%hhu "
2893       "max_page_number:%hhu features:%s",
2894       handle, current_page_number, max_page_number,
2895       bd_features_text(p_acl->peer_lmp_feature_pages[current_page_number])
2896           .c_str());
2897 
2898   if (max_page_number == current_page_number) {
2899     NotifyAclFeaturesReadComplete(*p_acl, max_page_number);
2900   }
2901 }
2902 
ACL_RegisterClient(struct acl_client_callback_s * callbacks)2903 void ACL_RegisterClient(struct acl_client_callback_s* callbacks) {
2904   LOG_DEBUG("UNIMPLEMENTED");
2905 }
2906 
ACL_UnregisterClient(struct acl_client_callback_s * callbacks)2907 void ACL_UnregisterClient(struct acl_client_callback_s* callbacks) {
2908   LOG_DEBUG("UNIMPLEMENTED");
2909 }
2910 
ACL_SupportTransparentSynchronousData(const RawAddress & bd_addr)2911 bool ACL_SupportTransparentSynchronousData(const RawAddress& bd_addr) {
2912   const tACL_CONN* p_acl =
2913       internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
2914   if (p_acl == nullptr) {
2915     LOG_WARN("Unable to find active acl");
2916     return false;
2917   }
2918 
2919   return HCI_LMP_TRANSPNT_SUPPORTED(p_acl->peer_lmp_feature_pages[0]);
2920 }
2921 
acl_add_to_ignore_auto_connect_after_disconnect(const RawAddress & bd_addr)2922 void acl_add_to_ignore_auto_connect_after_disconnect(
2923     const RawAddress& bd_addr) {
2924   btm_cb.acl_cb_.AddToIgnoreAutoConnectAfterDisconnect(bd_addr);
2925 }
2926 
acl_check_and_clear_ignore_auto_connect_after_disconnect(const RawAddress & bd_addr)2927 bool acl_check_and_clear_ignore_auto_connect_after_disconnect(
2928     const RawAddress& bd_addr) {
2929   return btm_cb.acl_cb_.CheckAndClearIgnoreAutoConnectAfterDisconnect(bd_addr);
2930 }
2931 
acl_clear_all_ignore_auto_connect_after_disconnect()2932 void acl_clear_all_ignore_auto_connect_after_disconnect() {
2933   btm_cb.acl_cb_.ClearAllIgnoreAutoConnectAfterDisconnect();
2934 }
2935 
2936 /**
2937  * Confusingly, immutable device features are stored in the
2938  * ephemeral connection data structure while connection security
2939  * is stored in the device record.
2940  *
2941  * This HACK allows legacy security protocols to work as intended under
2942  * those conditions.
2943  */
HACK_acl_check_sm4(tBTM_SEC_DEV_REC & record)2944 void HACK_acl_check_sm4(tBTM_SEC_DEV_REC& record) {
2945   // Return if we already know this info
2946   if ((record.sm4 & BTM_SM4_TRUE) != BTM_SM4_UNKNOWN) return;
2947 
2948   tACL_CONN* p_acl =
2949       internal_.btm_bda_to_acl(record.RemoteAddress(), BT_TRANSPORT_BR_EDR);
2950   if (p_acl == nullptr) {
2951     LOG_WARN("Unable to find active acl for authentication device:%s",
2952              PRIVATE_ADDRESS(record.RemoteAddress()));
2953   }
2954 
2955   // If we have not received the SSP feature record
2956   // we have to wait
2957   if (!p_acl->peer_lmp_feature_valid[1]) {
2958     LOG_WARN(
2959         "Authentication started without extended feature page 1 request "
2960         "response");
2961     return;
2962   }
2963   record.sm4 = (HCI_SSP_HOST_SUPPORTED(p_acl->peer_lmp_feature_pages[1]))
2964                    ? BTM_SM4_TRUE
2965                    : BTM_SM4_KNOWN;
2966 }
2967