1 /******************************************************************************
2  *
3  *  Copyright 2003-2014 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /******************************************************************************
20  *
21  *  This file contains the action functions for device manager state
22  *  machine.
23  *
24  ******************************************************************************/
25 
26 #define LOG_TAG "bt_bta_dm"
27 
28 #include <android_bluetooth_sysprop.h>
29 #include <base/location.h>
30 #include <bluetooth/log.h>
31 #include <com_android_bluetooth_flags.h>
32 
33 #include <cstdint>
34 #include <vector>
35 
36 #include "bta/dm/bta_dm_device_search.h"
37 #include "bta/dm/bta_dm_disc.h"
38 #include "bta/dm/bta_dm_gatt_client.h"
39 #include "bta/dm/bta_dm_int.h"
40 #include "bta/dm/bta_dm_sec_int.h"
41 #include "bta/include/bta_api.h"
42 #include "bta/include/bta_le_audio_api.h"
43 #include "bta/include/bta_sdp_api.h"
44 #include "bta/include/bta_sec_api.h"
45 #include "bta/sys/bta_sys.h"
46 #include "btif/include/btif_dm.h"
47 #include "btif/include/stack_manager_t.h"
48 #include "hci/controller_interface.h"
49 #include "internal_include/bt_target.h"
50 #include "main/shim/acl_api.h"
51 #include "main/shim/btm_api.h"
52 #include "main/shim/entry.h"
53 #include "osi/include/allocator.h"
54 #include "osi/include/properties.h"
55 #include "stack/gatt/connection_manager.h"
56 #include "stack/include/acl_api.h"
57 #include "stack/include/bt_hdr.h"
58 #include "stack/include/bt_types.h"
59 #include "stack/include/bt_uuid16.h"
60 #include "stack/include/btm_client_interface.h"
61 #include "stack/include/gatt_api.h"
62 #include "stack/include/l2c_api.h"
63 #include "stack/include/main_thread.h"
64 #include "types/bluetooth/uuid.h"
65 #include "types/raw_address.h"
66 
67 using bluetooth::Uuid;
68 using namespace bluetooth;
69 
70 bool ble_vnd_is_included();
71 void BTIF_dm_disable();
72 void BTIF_dm_enable();
73 void btm_ble_scanner_init(void);
74 
75 static void bta_dm_local_name_cback(void* p_name);
76 static void bta_dm_check_av();
77 
78 void BTA_dm_update_policy(tBTA_SYS_CONN_STATUS status, uint8_t id,
79                           uint8_t app_id, const RawAddress& peer_addr);
80 
81 /* Extended Inquiry Response */
82 static void bta_dm_set_eir(char* local_name);
83 
84 static void bta_dm_disable_conn_down_timer_cback(void* data);
85 static void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id,
86                             uint8_t app_id, const RawAddress& peer_addr);
87 static void bta_dm_adjust_roles(bool delay_role_switch);
88 tBTM_CONTRL_STATE bta_dm_pm_obtain_controller_state(void);
89 static void bta_dm_ctrl_features_rd_cmpl_cback(tHCI_STATUS result);
90 
91 static const char kPropertySniffOffloadEnabled[] =
92     "bluetooth.sniff_offload.enabled";
93 
94 #ifndef BTA_DM_BLE_ADV_CHNL_MAP
95 #define BTA_DM_BLE_ADV_CHNL_MAP \
96   (BTM_BLE_ADV_CHNL_37 | BTM_BLE_ADV_CHNL_38 | BTM_BLE_ADV_CHNL_39)
97 #endif
98 
99 /* Disable timer interval (in milliseconds) */
100 #ifndef BTA_DM_DISABLE_TIMER_MS
101 #define BTA_DM_DISABLE_TIMER_MS (2000)
102 #endif
103 
104 /* Disable timer retrial interval (in milliseconds) */
105 #ifndef BTA_DM_DISABLE_TIMER_RETRIAL_MS
106 #define BTA_DM_DISABLE_TIMER_RETRIAL_MS 1500
107 #endif
108 
109 /* Disable connection down timer (in milliseconds) */
110 #ifndef BTA_DM_DISABLE_CONN_DOWN_TIMER_MS
111 #define BTA_DM_DISABLE_CONN_DOWN_TIMER_MS 100
112 #endif
113 
114 /* Switch delay timer (in milliseconds) */
115 #ifndef BTA_DM_SWITCH_DELAY_TIMER_MS
116 #define BTA_DM_SWITCH_DELAY_TIMER_MS 500
117 #endif
118 
119 /* Sysprop path for page timeout */
120 #ifndef PROPERTY_PAGE_TIMEOUT
121 #define PROPERTY_PAGE_TIMEOUT "bluetooth.core.classic.page_timeout"
122 #endif
123 
124 namespace {
125 
126 struct WaitForAllAclConnectionsToDrain {
127   uint64_t time_to_wait_in_ms;
TimeToWaitInMs__anon328858460111::WaitForAllAclConnectionsToDrain128   unsigned long TimeToWaitInMs() const {
129     return static_cast<unsigned long>(time_to_wait_in_ms);
130   }
AlarmCallbackData__anon328858460111::WaitForAllAclConnectionsToDrain131   void* AlarmCallbackData() const {
132     return const_cast<void*>(static_cast<const void*>(this));
133   }
134 
135   static const WaitForAllAclConnectionsToDrain* FromAlarmCallbackData(
136       void* data);
137   static bool IsFirstPass(const WaitForAllAclConnectionsToDrain*);
138 } first_pass =
139     {
140         .time_to_wait_in_ms = static_cast<uint64_t>(BTA_DM_DISABLE_TIMER_MS),
141 },
142   second_pass = {
143       .time_to_wait_in_ms =
144           static_cast<uint64_t>(BTA_DM_DISABLE_TIMER_RETRIAL_MS),
145 };
146 
IsFirstPass(const WaitForAllAclConnectionsToDrain * pass)147 bool WaitForAllAclConnectionsToDrain::IsFirstPass(
148     const WaitForAllAclConnectionsToDrain* pass) {
149   return pass == &first_pass;
150 }
151 
152 const WaitForAllAclConnectionsToDrain*
FromAlarmCallbackData(void * data)153 WaitForAllAclConnectionsToDrain::FromAlarmCallbackData(void* data) {
154   return const_cast<const WaitForAllAclConnectionsToDrain*>(
155       static_cast<WaitForAllAclConnectionsToDrain*>(data));
156 }
157 
158 }  // namespace
159 
160 static void bta_dm_delay_role_switch_cback(void* data);
161 static void bta_dm_wait_for_acl_to_drain_cback(void* data);
162 
163 /** Initialises the BT device manager */
bta_dm_enable(tBTA_DM_SEC_CBACK * p_sec_cback,tBTA_DM_ACL_CBACK * p_acl_cback)164 void bta_dm_enable(tBTA_DM_SEC_CBACK* p_sec_cback,
165                    tBTA_DM_ACL_CBACK *p_acl_cback) {
166 
167   if (p_acl_cback != NULL) bta_dm_acl_cb.p_acl_cback = p_acl_cback;
168 
169   bta_dm_sec_enable(p_sec_cback);
170 }
171 
172 /*******************************************************************************
173  *
174  * Function         bta_dm_init_cb
175  *
176  * Description      Initializes the bta_dm_cb control block
177  *
178  *
179  * Returns          void
180  *
181  ******************************************************************************/
bta_dm_init_cb(void)182 static void bta_dm_init_cb(void) {
183   bta_dm_cb = {};
184 
185   bta_dm_cb.disable_timer = alarm_new("bta_dm.disable_timer");
186   bta_dm_cb.switch_delay_timer = alarm_new("bta_dm.switch_delay_timer");
187   for (size_t i = 0; i < BTA_DM_NUM_PM_TIMER; i++) {
188     for (size_t j = 0; j < BTA_DM_PM_MODE_TIMER_MAX; j++) {
189       bta_dm_cb.pm_timer[i].timer[j] = alarm_new("bta_dm.pm_timer");
190     }
191   }
192 }
193 
194 /*******************************************************************************
195  *
196  * Function         bta_dm_deinit_cb
197  *
198  * Description      De-initializes the bta_dm_cb control block
199  *
200  *
201  * Returns          void
202  *
203  ******************************************************************************/
bta_dm_deinit_cb(void)204 static void bta_dm_deinit_cb(void) {
205   /*
206    * TODO: Should alarm_free() the bta_dm_cb timers during graceful
207    * shutdown.
208    */
209   alarm_free(bta_dm_cb.disable_timer);
210   alarm_free(bta_dm_cb.switch_delay_timer);
211   for (size_t i = 0; i < BTA_DM_NUM_PM_TIMER; i++) {
212     for (size_t j = 0; j < BTA_DM_PM_MODE_TIMER_MAX; j++) {
213       alarm_free(bta_dm_cb.pm_timer[i].timer[j]);
214     }
215   }
216   bta_dm_cb = {};
217 }
218 
BTA_dm_on_hw_off()219 void BTA_dm_on_hw_off() {
220   BTIF_dm_disable();
221 
222   /* reinitialize the control block */
223   bta_dm_deinit_cb();
224 
225   bta_dm_disc_stop();
226   bta_dm_search_stop();
227 }
228 
BTA_dm_on_hw_on()229 void BTA_dm_on_hw_on() {
230   uint8_t key_mask = 0;
231   tBTA_BLE_LOCAL_ID_KEYS id_key;
232 
233   /* make sure the control block is properly initialized */
234   bta_dm_init_cb();
235 
236   bta_dm_disc_start(
237       osi_property_get_bool("bluetooth.gatt.delay_close.enabled", true));
238 
239   memset(&bta_dm_conn_srvcs, 0, sizeof(bta_dm_conn_srvcs));
240   memset(&bta_dm_di_cb, 0, sizeof(tBTA_DM_DI_CB));
241 
242   DEV_CLASS dev_class = btif_dm_get_local_class_of_device();
243   log::info("Read default class of device [0x{:x}, 0x{:x}, 0x{:x}]",
244             dev_class[0], dev_class[1], dev_class[2]);
245 
246   if (get_btm_client_interface().local.BTM_SetDeviceClass(dev_class) !=
247       BTM_SUCCESS) {
248     log::warn("Unable to set local device class:{}", dev_class_text(dev_class));
249   }
250 
251   /* load BLE local information: ID keys, ER if available */
252   Octet16 er;
253   btif_dm_get_ble_local_keys(&key_mask, &er, &id_key);
254 
255   if (key_mask & BTA_BLE_LOCAL_KEY_TYPE_ER) {
256     get_btm_client_interface().security.BTM_BleLoadLocalKeys(
257         BTA_BLE_LOCAL_KEY_TYPE_ER, (tBTM_BLE_LOCAL_KEYS*)&er);
258   }
259   if (key_mask & BTA_BLE_LOCAL_KEY_TYPE_ID) {
260     get_btm_client_interface().security.BTM_BleLoadLocalKeys(
261         BTA_BLE_LOCAL_KEY_TYPE_ID, (tBTM_BLE_LOCAL_KEYS*)&id_key);
262   }
263 
264   btm_dm_sec_init();
265   btm_sec_on_hw_on();
266 
267   get_btm_client_interface().link_policy.BTM_WritePageTimeout(
268       osi_property_get_int32(PROPERTY_PAGE_TIMEOUT,
269                              p_bta_dm_cfg->page_timeout));
270 
271   if (ble_vnd_is_included()) {
272     get_btm_client_interface().ble.BTM_BleReadControllerFeatures(
273         bta_dm_ctrl_features_rd_cmpl_cback);
274   } else {
275     /* Set controller features even if vendor support is not included */
276     if (bta_dm_acl_cb.p_acl_cback)
277       bta_dm_acl_cb.p_acl_cback(BTA_DM_LE_FEATURES_READ, NULL);
278   }
279 
280   btm_ble_scanner_init();
281 
282   /* Earlier, we used to invoke BTM_ReadLocalAddr which was just copying the
283      bd_addr
284      from the control block and invoking the callback which was sending the
285      DM_ENABLE_EVT.
286      But then we have a few HCI commands being invoked above which were still
287      in progress
288      when the ENABLE_EVT was sent. So modified this to fetch the local name
289      which forces
290      the DM_ENABLE_EVT to be sent only after all the init steps are complete
291      */
292   if (get_btm_client_interface().local.BTM_ReadLocalDeviceNameFromController(
293           bta_dm_local_name_cback) != BTM_CMD_STARTED) {
294     log::warn("Unable to read local device name from controller");
295   }
296 
297   bta_sys_rm_register(bta_dm_rm_cback);
298 
299   /* if sniff is offload, no need to handle it in the stack */
300   if (com::android::bluetooth::flags::enable_sniff_offload() &&
301       osi_property_get_bool(kPropertySniffOffloadEnabled, false)) {
302   } else {
303     /* initialize bluetooth low power manager */
304     bta_dm_init_pm();
305   }
306 
307   bta_dm_disc_gattc_register();
308 }
309 
310 /** Disables the BT device manager */
bta_dm_disable()311 void bta_dm_disable() {
312   /* Set l2cap idle timeout to 0 (so BTE immediately disconnects ACL link after
313    * last channel is closed) */
314   if (!L2CA_SetIdleTimeoutByBdAddr(RawAddress::kAny, 0, BT_TRANSPORT_BR_EDR)) {
315     log::warn(
316         "Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}",
317         RawAddress::kAny, BT_TRANSPORT_BR_EDR, 0);
318   }
319   if (!L2CA_SetIdleTimeoutByBdAddr(RawAddress::kAny, 0, BT_TRANSPORT_LE)) {
320     log::warn(
321         "Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}",
322         RawAddress::kAny, BT_TRANSPORT_LE, 0);
323   }
324 
325   /* disable all active subsystems */
326   bta_sys_disable();
327 
328   if (BTM_SetDiscoverability(BTM_NON_DISCOVERABLE) != BTM_SUCCESS) {
329     log::warn("Unable to disable classic BR/EDR discoverability");
330   }
331   if (BTM_SetConnectability(BTM_NON_CONNECTABLE) != BTM_SUCCESS) {
332     log::warn("Unable to disable classic BR/EDR connectability");
333   }
334 
335   bta_dm_disable_pm();
336   if (com::android::bluetooth::flags::separate_service_and_device_discovery()) {
337     bta_dm_disc_disable_search();
338     bta_dm_disc_disable_disc();
339   } else {
340     bta_dm_disc_disable_search_and_disc();
341   }
342   bta_dm_cb.disabling = true;
343 
344   connection_manager::reset(false);
345 
346   // We can shut down faster if there are no ACL links
347   if (BTM_GetNumAclLinks() == 0) {
348     // Time to wait after receiving shutdown request to delay the actual
349     // shutdown process. This time may be zero which invokes immediate shutdown.
350     const uint64_t disable_delay_ms = GET_SYSPROP(Bta, disable_delay, 200);
351     switch (disable_delay_ms) {
352       case 0:
353         log::debug("Immediately disabling device manager");
354         bta_dm_disable_conn_down_timer_cback(nullptr);
355         break;
356       default:
357         log::debug("Set timer to delay disable initiation:{} ms",
358                    static_cast<unsigned long>(disable_delay_ms));
359         alarm_set_on_mloop(bta_dm_cb.disable_timer, disable_delay_ms,
360                            bta_dm_disable_conn_down_timer_cback, nullptr);
361     }
362   } else {
363     log::debug("Set timer to wait for all ACL connections to close:{} ms",
364                first_pass.TimeToWaitInMs());
365     alarm_set_on_mloop(bta_dm_cb.disable_timer, first_pass.time_to_wait_in_ms,
366                        bta_dm_wait_for_acl_to_drain_cback,
367                        first_pass.AlarmCallbackData());
368   }
369 }
370 
371 /*******************************************************************************
372  *
373  * Function         bta_dm_wait_for_all_acl_to_drain
374  *
375  * Description      Called if the disable timer expires
376  *                  Used to close ACL connections which are still active
377  *
378  * Returns          true if there is a device being forcefully disconnected
379  *
380  ******************************************************************************/
force_disconnect_all_acl_connections()381 static bool force_disconnect_all_acl_connections() {
382   const bool is_force_disconnect_needed = (bta_dm_cb.device_list.count > 0);
383 
384   for (auto i = 0; i < bta_dm_cb.device_list.count; i++) {
385     btm_remove_acl(bta_dm_cb.device_list.peer_device[i].peer_bdaddr,
386                    bta_dm_cb.device_list.peer_device[i].transport);
387   }
388   return is_force_disconnect_needed;
389 }
390 
bta_dm_wait_for_acl_to_drain_cback(void * data)391 static void bta_dm_wait_for_acl_to_drain_cback(void* data) {
392   log::assert_that(data != nullptr, "assert failed: data != nullptr");
393   const WaitForAllAclConnectionsToDrain* pass =
394       WaitForAllAclConnectionsToDrain::FromAlarmCallbackData(data);
395 
396   if (BTM_GetNumAclLinks() && force_disconnect_all_acl_connections() &&
397       WaitForAllAclConnectionsToDrain::IsFirstPass(pass)) {
398     /* DISABLE_EVT still need to be sent out to avoid java layer disable timeout
399      */
400     log::debug(
401         "Set timer for second pass to wait for all ACL connections to close:{} "
402         "ms",
403         second_pass.TimeToWaitInMs());
404     alarm_set_on_mloop(bta_dm_cb.disable_timer, second_pass.time_to_wait_in_ms,
405                        bta_dm_wait_for_acl_to_drain_cback,
406                        second_pass.AlarmCallbackData());
407   } else {
408     // No ACL links to close were up or is second pass at ACL closure
409     log::info("Ensuring all ACL connections have been properly flushed");
410     bluetooth::shim::ACL_Shutdown();
411 
412     bta_dm_cb.disabling = false;
413 
414     bta_sys_remove_uuid(UUID_SERVCLASS_PNP_INFORMATION);
415     BTIF_dm_disable();
416   }
417 }
418 
419 /** Sets local device name */
bta_dm_set_dev_name(const std::vector<uint8_t> & name)420 void bta_dm_set_dev_name(const std::vector<uint8_t>& name) {
421   if (get_btm_client_interface().local.BTM_SetLocalDeviceName(
422           (const char*)name.data()) != BTM_CMD_STARTED) {
423     log::warn("Unable to set local device name");
424   }
425   bta_dm_set_eir((char*)name.data());
426 }
427 
428 /** Sets discoverability, connectability and pairability */
BTA_DmSetVisibility(bt_scan_mode_t mode)429 bool BTA_DmSetVisibility(bt_scan_mode_t mode) {
430   tBTA_DM_DISC disc_mode_param;
431   tBTA_DM_CONN conn_mode_param;
432 
433   switch (mode) {
434     case BT_SCAN_MODE_NONE:
435       disc_mode_param = BTM_NON_DISCOVERABLE;
436       conn_mode_param = BTM_NON_CONNECTABLE;
437       break;
438 
439     case BT_SCAN_MODE_CONNECTABLE:
440       disc_mode_param = BTM_NON_DISCOVERABLE;
441       conn_mode_param = BTM_CONNECTABLE;
442       break;
443 
444     case BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE:
445       disc_mode_param = BTM_GENERAL_DISCOVERABLE;
446       conn_mode_param = BTM_CONNECTABLE;
447       break;
448 
449     case BT_SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE:
450       disc_mode_param = BTM_LIMITED_DISCOVERABLE;
451       conn_mode_param = BTM_CONNECTABLE;
452       break;
453 
454     default:
455       return false;
456   }
457 
458   if (BTM_SetDiscoverability(disc_mode_param) != BTM_SUCCESS) {
459     log::warn("Unable to set classic BR/EDR discoverability 0x{:04x}",
460               disc_mode_param);
461   }
462   if (BTM_SetConnectability(conn_mode_param) != BTM_SUCCESS) {
463     log::warn("Unable to set classic BR/EDR connectability 0x{:04x}",
464               conn_mode_param);
465   }
466   return true;
467 }
bta_dm_process_remove_device_no_callback(const RawAddress & bd_addr)468 void bta_dm_process_remove_device_no_callback(const RawAddress& bd_addr) {
469   /* need to remove all pending background connection before unpair */
470   bta_dm_disc_gatt_cancel_open(bd_addr);
471 
472   get_btm_client_interface().security.BTM_SecDeleteDevice(bd_addr);
473 
474   /* remove all cached GATT information */
475   bta_dm_disc_gatt_refresh(bd_addr);
476 }
477 
bta_dm_process_remove_device(const RawAddress & bd_addr)478 void bta_dm_process_remove_device(const RawAddress& bd_addr) {
479   bta_dm_process_remove_device_no_callback(bd_addr);
480 
481   /* Conclude service search if it was pending */
482   bta_dm_disc_remove_device(bd_addr);
483 
484   if (bta_dm_sec_cb.p_sec_cback) {
485     tBTA_DM_SEC sec_event;
486     sec_event.dev_unpair.bd_addr = bd_addr;
487     bta_dm_sec_cb.p_sec_cback(BTA_DM_DEV_UNPAIRED_EVT, &sec_event);
488   }
489 }
490 
491 /** Removes device, disconnects ACL link if required */
bta_dm_remove_device(const RawAddress & bd_addr)492 void bta_dm_remove_device(const RawAddress& bd_addr) {
493   /* If ACL exists for the device in the remove_bond message*/
494   bool is_bd_addr_connected =
495       get_btm_client_interface().peer.BTM_IsAclConnectionUp(bd_addr,
496                                                             BT_TRANSPORT_LE) ||
497       get_btm_client_interface().peer.BTM_IsAclConnectionUp(
498           bd_addr, BT_TRANSPORT_BR_EDR);
499 
500   tBT_TRANSPORT other_transport = BT_TRANSPORT_AUTO;
501   if (is_bd_addr_connected) {
502     log::verbose("ACL Up count: {}", bta_dm_cb.device_list.count);
503 
504     /* Take the link down first, and mark the device for removal when
505      * disconnected */
506     for (int i = 0; i < bta_dm_cb.device_list.count; i++) {
507       auto& peer_device = bta_dm_cb.device_list.peer_device[i];
508       if (peer_device.peer_bdaddr == bd_addr) {
509         peer_device.conn_state = tBTA_DM_CONN_STATE::BTA_DM_UNPAIRING;
510 
511         /* Make sure device is not in acceptlist before we disconnect */
512         if (!GATT_CancelConnect(0, bd_addr, false)) {
513           log::warn("Unable to cancel GATT connect peer:{} is_direct:{}",
514                     bd_addr, false);
515         }
516 
517         btm_remove_acl(bd_addr, peer_device.transport);
518         log::verbose("transport: {}", peer_device.transport);
519 
520         /* save the other transport to check if device is connected on
521          * other_transport */
522         if (peer_device.transport == BT_TRANSPORT_LE)
523           other_transport = BT_TRANSPORT_BR_EDR;
524         else
525           other_transport = BT_TRANSPORT_LE;
526 
527         break;
528       }
529     }
530   }
531 
532   RawAddress other_address = bd_addr;
533   RawAddress other_address2 = bd_addr;
534 
535   // If it is DUMO device and device is paired as different address, unpair that
536   // device
537   bool other_address_connected =
538       (other_transport)
539           ? get_btm_client_interface().peer.BTM_ReadConnectedTransportAddress(
540                 &other_address, other_transport)
541           : (get_btm_client_interface().peer.BTM_ReadConnectedTransportAddress(
542                  &other_address, BT_TRANSPORT_BR_EDR) ||
543              get_btm_client_interface().peer.BTM_ReadConnectedTransportAddress(
544                  &other_address2, BT_TRANSPORT_LE));
545   if (other_address == bd_addr) other_address = other_address2;
546 
547   if (other_address_connected) {
548     // Get real transport
549     if (other_transport == BT_TRANSPORT_AUTO) {
550       bool connected_with_br_edr =
551           get_btm_client_interface().peer.BTM_IsAclConnectionUp(
552               other_address, BT_TRANSPORT_BR_EDR);
553       other_transport =
554           connected_with_br_edr ? BT_TRANSPORT_BR_EDR : BT_TRANSPORT_LE;
555     }
556     log::info("other_address {} with transport {} connected", other_address,
557               other_transport);
558     /* Take the link down first, and mark the device for removal when
559      * disconnected */
560     for (int i = 0; i < bta_dm_cb.device_list.count; i++) {
561       auto& peer_device = bta_dm_cb.device_list.peer_device[i];
562       if (peer_device.peer_bdaddr == other_address &&
563           peer_device.transport == other_transport) {
564         peer_device.conn_state = tBTA_DM_CONN_STATE::BTA_DM_UNPAIRING;
565         log::info("Remove ACL of address {}", other_address);
566 
567         /* Make sure device is not in acceptlist before we disconnect */
568         if (!GATT_CancelConnect(0, bd_addr, false)) {
569           log::warn("Unable to cancel GATT connect peer:{} is_direct:{}",
570                     bd_addr, false);
571         }
572 
573         btm_remove_acl(other_address, peer_device.transport);
574         break;
575       }
576     }
577   }
578 
579   /* Delete the device mentioned in the msg */
580   if (!is_bd_addr_connected) {
581     bta_dm_process_remove_device(bd_addr);
582   }
583 
584   /* Delete the other paired device too */
585   if (!other_address_connected && !other_address.IsEmpty()) {
586     bta_dm_process_remove_device(other_address);
587   }
588 }
589 
590 /*******************************************************************************
591  *
592  * Function         bta_dm_local_name_cback
593  *
594  * Description      Callback from btm after local name is read
595  *
596  *
597  * Returns          void
598  *
599  ******************************************************************************/
bta_dm_local_name_cback(void *)600 static void bta_dm_local_name_cback(void* /* p_name */) { BTIF_dm_enable(); }
601 
handle_role_change(const RawAddress & bd_addr,tHCI_ROLE new_role,tHCI_STATUS hci_status)602 static void handle_role_change(const RawAddress& bd_addr, tHCI_ROLE new_role,
603                                tHCI_STATUS hci_status) {
604   tBTA_DM_PEER_DEVICE* p_dev = bta_dm_find_peer_device(bd_addr);
605   if (!p_dev) {
606     log::warn(
607         "Unable to find device for role change peer:{} new_role:{} "
608         "hci_status:{}",
609         bd_addr, RoleText(new_role), hci_error_code_text(hci_status));
610     return;
611   }
612 
613   log::info(
614       "Role change callback peer:{} info:{} new_role:{} dev count:{} "
615       "hci_status:{}",
616       bd_addr, p_dev->info_text(), RoleText(new_role),
617       bta_dm_cb.device_list.count, hci_error_code_text(hci_status));
618 
619   if (p_dev->is_av_active()) {
620     bool need_policy_change = false;
621 
622     /* there's AV activity on this link */
623     if (new_role == HCI_ROLE_PERIPHERAL && bta_dm_cb.device_list.count > 1 &&
624         hci_status == HCI_SUCCESS) {
625       /* more than one connections and the AV connection is role switched
626        * to peripheral
627        * switch it back to central and remove the switch policy */
628       const tBTM_STATUS status =
629           get_btm_client_interface().link_policy.BTM_SwitchRoleToCentral(
630               bd_addr);
631       switch (status) {
632         case BTM_SUCCESS:
633           log::debug("Role policy already set to central peer:{}", bd_addr);
634           break;
635         case BTM_CMD_STARTED:
636           log::debug("Role policy started to central peer:{}", bd_addr);
637           break;
638         default:
639           log::warn("Unable to set role policy to central peer:{}", bd_addr);
640           break;
641       }
642       need_policy_change = true;
643     } else if (p_bta_dm_cfg->avoid_scatter && (new_role == HCI_ROLE_CENTRAL)) {
644       /* if the link updated to be central include AV activities, remove
645        * the switch policy */
646       need_policy_change = true;
647     }
648 
649     if (need_policy_change) {
650       get_btm_client_interface().link_policy.BTM_block_role_switch_for(
651           p_dev->peer_bdaddr);
652     }
653   } else {
654     /* there's AV no activity on this link and role switch happened
655      * check if AV is active
656      * if so, make sure the AV link is central */
657     bta_dm_check_av();
658   }
659   bta_sys_notify_role_chg(bd_addr, new_role, hci_status);
660 }
661 
BTA_dm_report_role_change(const RawAddress bd_addr,tHCI_ROLE new_role,tHCI_STATUS hci_status)662 void BTA_dm_report_role_change(const RawAddress bd_addr, tHCI_ROLE new_role,
663                                tHCI_STATUS hci_status) {
664   do_in_main_thread(FROM_HERE, base::BindOnce(handle_role_change, bd_addr,
665                                               new_role, hci_status));
666 }
667 
handle_remote_features_complete(const RawAddress & bd_addr)668 void handle_remote_features_complete(const RawAddress& bd_addr) {
669   tBTA_DM_PEER_DEVICE* p_dev = bta_dm_find_peer_device(bd_addr);
670   if (!p_dev) {
671     log::warn("Unable to find device peer:{}", bd_addr);
672     return;
673   }
674 
675   if (bluetooth::shim::GetController()->SupportsSniffSubrating() &&
676       acl_peer_supports_sniff_subrating(bd_addr)) {
677     log::debug("Device supports sniff subrating peer:{}", bd_addr);
678     p_dev->set_both_device_ssr_capable();
679   } else {
680     log::debug("Device does NOT support sniff subrating peer:{}", bd_addr);
681   }
682 }
683 
BTA_dm_notify_remote_features_complete(const RawAddress bd_addr)684 void BTA_dm_notify_remote_features_complete(const RawAddress bd_addr) {
685   do_in_main_thread(FROM_HERE,
686                     base::BindOnce(handle_remote_features_complete, bd_addr));
687 }
688 
allocate_device_for(const RawAddress & bd_addr,tBT_TRANSPORT transport)689 static tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr,
690                                                 tBT_TRANSPORT transport) {
691   for (uint8_t i = 0; i < bta_dm_cb.device_list.count; i++) {
692     auto device = &bta_dm_cb.device_list.peer_device[i];
693     if (device->peer_bdaddr == bd_addr && device->transport == transport) {
694       return device;
695     }
696   }
697 
698   if (bta_dm_cb.device_list.count < BTA_DM_NUM_PEER_DEVICE) {
699     auto device =
700         &bta_dm_cb.device_list.peer_device[bta_dm_cb.device_list.count];
701     device->peer_bdaddr = bd_addr;
702     bta_dm_cb.device_list.count++;
703     if (transport == BT_TRANSPORT_LE) {
704       bta_dm_cb.device_list.le_count++;
705     }
706     return device;
707   }
708   return nullptr;
709 }
710 
bta_dm_acl_up(const RawAddress & bd_addr,tBT_TRANSPORT transport,uint16_t acl_handle)711 static void bta_dm_acl_up(const RawAddress& bd_addr, tBT_TRANSPORT transport,
712                           uint16_t acl_handle) {
713   auto device = allocate_device_for(bd_addr, transport);
714   if (device == nullptr) {
715     log::warn("Unable to allocate device resources for new connection");
716     return;
717   }
718   log::info("Acl connected peer:{} transport:{} handle:{}", bd_addr,
719             bt_transport_text(transport), acl_handle);
720   device->conn_state = tBTA_DM_CONN_STATE::BTA_DM_CONNECTED;
721   device->pref_role = BTA_ANY_ROLE;
722   device->reset_device_info();
723   device->transport = transport;
724 
725   if (bluetooth::shim::GetController()->SupportsSniffSubrating() &&
726       acl_peer_supports_sniff_subrating(bd_addr)) {
727     // NOTE: This callback assumes upon ACL connection that
728     // the read remote features has completed and is valid.
729     // The only guaranteed contract for valid read remote features
730     // data is when the BTA_dm_notify_remote_features_complete()
731     // callback has completed.  The below assignment is kept for
732     // transitional informational purposes only.
733     device->set_both_device_ssr_capable();
734   }
735 
736   if (bta_dm_acl_cb.p_acl_cback) {
737     tBTA_DM_ACL conn{};
738     conn.link_up.bd_addr = bd_addr;
739     conn.link_up.transport_link_type = transport;
740     conn.link_up.acl_handle = acl_handle;
741 
742     bta_dm_acl_cb.p_acl_cback(BTA_DM_LINK_UP_EVT, &conn);
743     log::debug("Executed security callback for new connection available");
744   }
745   bta_dm_adjust_roles(true);
746 }
747 
BTA_dm_acl_up(const RawAddress bd_addr,tBT_TRANSPORT transport,uint16_t acl_handle)748 void BTA_dm_acl_up(const RawAddress bd_addr, tBT_TRANSPORT transport,
749                    uint16_t acl_handle) {
750   do_in_main_thread(
751       FROM_HERE, base::BindOnce(bta_dm_acl_up, bd_addr, transport, acl_handle));
752 }
753 
bta_dm_acl_up_failed(const RawAddress bd_addr,tBT_TRANSPORT transport,tHCI_STATUS status)754 static void bta_dm_acl_up_failed(const RawAddress bd_addr,
755                                  tBT_TRANSPORT transport, tHCI_STATUS status) {
756   if (bta_dm_acl_cb.p_acl_cback) {
757     tBTA_DM_ACL conn = {};
758     conn.link_up_failed.bd_addr = bd_addr;
759     conn.link_up_failed.transport_link_type = transport;
760     conn.link_up_failed.status = status;
761     bta_dm_acl_cb.p_acl_cback(BTA_DM_LINK_UP_FAILED_EVT, &conn);
762   }
763 }
764 
BTA_dm_acl_up_failed(const RawAddress bd_addr,tBT_TRANSPORT transport,tHCI_STATUS status)765 void BTA_dm_acl_up_failed(const RawAddress bd_addr, tBT_TRANSPORT transport,
766                           tHCI_STATUS status) {
767   do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_acl_up_failed, bd_addr,
768                                               transport, status));
769 }
770 
bta_dm_acl_down(const RawAddress & bd_addr,tBT_TRANSPORT transport)771 static void bta_dm_acl_down(const RawAddress& bd_addr,
772                             tBT_TRANSPORT transport) {
773   bool issue_unpair_cb = false;
774   bool remove_device = false;
775 
776   for (uint8_t i = 0; i < bta_dm_cb.device_list.count; i++) {
777     auto device = &bta_dm_cb.device_list.peer_device[i];
778     if (device->peer_bdaddr != bd_addr || device->transport != transport)
779       continue;
780 
781     if (device->conn_state == tBTA_DM_CONN_STATE::BTA_DM_UNPAIRING) {
782       issue_unpair_cb = get_btm_client_interface().security.BTM_SecDeleteDevice(
783           device->peer_bdaddr);
784 
785       /* remove all cached GATT information */
786       get_gatt_interface().BTA_GATTC_Refresh(bd_addr);
787 
788       log::verbose("Unpairing: issue unpair CB = {}", issue_unpair_cb);
789     }
790 
791     remove_device = device->remove_dev_pending;
792 
793     // Iterate to the one before the last when shrinking the list,
794     // otherwise we memcpy garbage data into the record.
795     // Then clear out the last item in the list since we are shrinking.
796     for (; i < bta_dm_cb.device_list.count - 1; i++) {
797       memcpy(&bta_dm_cb.device_list.peer_device[i],
798              &bta_dm_cb.device_list.peer_device[i + 1],
799              sizeof(bta_dm_cb.device_list.peer_device[i]));
800     }
801     if (bta_dm_cb.device_list.count > 0) {
802       int clear_index = bta_dm_cb.device_list.count - 1;
803       memset(&bta_dm_cb.device_list.peer_device[clear_index], 0,
804              sizeof(bta_dm_cb.device_list.peer_device[clear_index]));
805     }
806     break;
807   }
808   if (bta_dm_cb.device_list.count) bta_dm_cb.device_list.count--;
809   if ((transport == BT_TRANSPORT_LE) && (bta_dm_cb.device_list.le_count)) {
810     bta_dm_cb.device_list.le_count--;
811   }
812 
813   bta_dm_disc_acl_down(bd_addr, transport);
814 
815   if (bta_dm_cb.disabling) {
816     if (!BTM_GetNumAclLinks()) {
817       /*
818        * Start a timer to make sure that the profiles
819        * get the disconnect event.
820        */
821       alarm_set_on_mloop(bta_dm_cb.disable_timer,
822                          BTA_DM_DISABLE_CONN_DOWN_TIMER_MS,
823                          bta_dm_disable_conn_down_timer_cback, NULL);
824     }
825   }
826   if (remove_device) {
827     log::info("remove_dev_pending actually removing {}", bd_addr);
828     bta_dm_process_remove_device_no_callback(bd_addr);
829   }
830 
831   if (bta_dm_acl_cb.p_acl_cback) {
832     tBTA_DM_ACL conn{};
833     conn.link_down.bd_addr = bd_addr;
834     conn.link_down.transport_link_type = transport;
835 
836     bta_dm_acl_cb.p_acl_cback(BTA_DM_LINK_DOWN_EVT, &conn);
837   }
838 
839   // TODO: reorganize and factor out the following logic
840   if (issue_unpair_cb && bta_dm_sec_cb.p_sec_cback) {
841     tBTA_DM_SEC conn{};
842     conn.dev_unpair.bd_addr = bd_addr;
843     conn.dev_unpair.transport_link_type = transport;
844 
845     bta_dm_sec_cb.p_sec_cback(BTA_DM_DEV_UNPAIRED_EVT, &conn);
846   }
847 
848   bta_dm_adjust_roles(true);
849 }
850 
BTA_dm_acl_down(const RawAddress bd_addr,tBT_TRANSPORT transport)851 void BTA_dm_acl_down(const RawAddress bd_addr, tBT_TRANSPORT transport) {
852   do_in_main_thread(FROM_HERE,
853                     base::BindOnce(bta_dm_acl_down, bd_addr, transport));
854 }
855 
856 /*******************************************************************************
857  *
858  * Function         bta_dm_check_av
859  *
860  * Description      This function checks if AV is active
861  *                  if yes, make sure the AV link is central
862  *
863  ******************************************************************************/
bta_dm_check_av()864 static void bta_dm_check_av() {
865   uint8_t i;
866   tBTA_DM_PEER_DEVICE* p_dev;
867 
868   if (bta_dm_cb.cur_av_count) {
869     log::info("av_count:{}", bta_dm_cb.cur_av_count);
870     for (i = 0; i < bta_dm_cb.device_list.count; i++) {
871       p_dev = &bta_dm_cb.device_list.peer_device[i];
872       log::warn("[{}]: state:{}, info:{}", i, p_dev->conn_state,
873                 p_dev->info_text());
874       if ((p_dev->conn_state == tBTA_DM_CONN_STATE::BTA_DM_CONNECTED) &&
875           p_dev->is_av_active()) {
876         /* make central and take away the role switch policy */
877         const tBTM_STATUS status =
878             get_btm_client_interface().link_policy.BTM_SwitchRoleToCentral(
879                 p_dev->peer_bdaddr);
880         switch (status) {
881           case BTM_SUCCESS:
882             log::debug("Role policy already set to central peer:{}",
883                        p_dev->peer_bdaddr);
884             break;
885           case BTM_CMD_STARTED:
886             log::debug("Role policy started to central peer:{}",
887                        p_dev->peer_bdaddr);
888             break;
889           default:
890             log::warn("Unable to set role policy to central peer:{}",
891                       p_dev->peer_bdaddr);
892             break;
893         }
894         /* else either already central or can not switch for some reasons */
895         get_btm_client_interface().link_policy.BTM_block_role_switch_for(
896             p_dev->peer_bdaddr);
897         break;
898       }
899     }
900   }
901 }
902 
903 /*******************************************************************************
904  *
905  * Function         bta_dm_disable_conn_down_timer_cback
906  *
907  * Description      Sends disable event to application
908  *
909  *
910  * Returns          void
911  *
912  ******************************************************************************/
bta_dm_disable_conn_down_timer_cback(void *)913 static void bta_dm_disable_conn_down_timer_cback(void* /* data */) {
914   /* disable the power managment module */
915   bta_dm_disable_pm();
916 
917   bta_dm_cb.disabling = false;
918   log::info("Stack device manager shutdown completed");
919   future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS);
920 }
921 
922 /*******************************************************************************
923  *
924  * Function         bta_dm_rm_cback
925  *
926  * Description      Role management callback from sys
927  *
928  *
929  * Returns          void
930  *
931  ******************************************************************************/
bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status,tBTA_SYS_ID id,uint8_t app_id,const RawAddress & peer_addr)932 static void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id,
933                             uint8_t app_id, const RawAddress& peer_addr) {
934   uint8_t j;
935   tBTA_PREF_ROLES role;
936   tBTA_DM_PEER_DEVICE* p_dev;
937 
938   log::debug("BTA Role management callback count:{} status:{} peer:{}",
939              bta_dm_cb.cur_av_count, bta_sys_conn_status_text(status),
940              peer_addr);
941 
942   p_dev = bta_dm_find_peer_device(peer_addr);
943   if (status == BTA_SYS_CONN_OPEN) {
944     if (p_dev) {
945       /* Do not set to connected if we are in the middle of unpairing. When AV
946        * stream is
947        * started it fakes out a SYS_CONN_OPEN to potentially trigger a role
948        * switch command.
949        * But this should not be done if we are in the middle of unpairing.
950        */
951       if (p_dev->conn_state != tBTA_DM_CONN_STATE::BTA_DM_UNPAIRING)
952         p_dev->conn_state = tBTA_DM_CONN_STATE::BTA_DM_CONNECTED;
953 
954       for (j = 1; j <= p_bta_dm_rm_cfg[0].app_id; j++) {
955         if (((p_bta_dm_rm_cfg[j].app_id == app_id) ||
956              (p_bta_dm_rm_cfg[j].app_id == BTA_ALL_APP_ID)) &&
957             (p_bta_dm_rm_cfg[j].id == id)) {
958           log::assert_that(
959               p_bta_dm_rm_cfg[j].cfg <= BTA_PERIPHERAL_ROLE_ONLY,
960               "Passing illegal preferred role:0x{:02x} [0x{:02x}<=>0x{:02x}]",
961               p_bta_dm_rm_cfg[j].cfg, BTA_ANY_ROLE, BTA_PERIPHERAL_ROLE_ONLY);
962           role = static_cast<tBTA_PREF_ROLES>(p_bta_dm_rm_cfg[j].cfg);
963           if (role > p_dev->pref_role) p_dev->pref_role = role;
964           break;
965         }
966       }
967     }
968   }
969 
970   if (BTA_ID_AV == id) {
971     if (status == BTA_SYS_CONN_BUSY) {
972       if (p_dev) p_dev->set_av_active();
973       /* AV calls bta_sys_conn_open with the A2DP stream count as app_id */
974       if (BTA_ID_AV == id) bta_dm_cb.cur_av_count = bta_dm_get_av_count();
975     } else if (status == BTA_SYS_CONN_IDLE) {
976       if (p_dev) p_dev->reset_av_active();
977 
978       /* get cur_av_count from connected services */
979       if (BTA_ID_AV == id) bta_dm_cb.cur_av_count = bta_dm_get_av_count();
980     }
981   }
982 
983   /* Don't adjust roles for each busy/idle state transition to avoid
984      excessive switch requests when individual profile busy/idle status
985      changes */
986   if ((status != BTA_SYS_CONN_BUSY) && (status != BTA_SYS_CONN_IDLE))
987     bta_dm_adjust_roles(false);
988 }
989 
990 /*******************************************************************************
991  *
992  * Function         bta_dm_delay_role_switch_cback
993  *
994  * Description      Callback from btm to delay a role switch
995  *
996  * Returns          void
997  *
998  ******************************************************************************/
bta_dm_delay_role_switch_cback(void *)999 static void bta_dm_delay_role_switch_cback(void* /* data */) {
1000   log::verbose("initiating Delayed RS");
1001   bta_dm_adjust_roles(false);
1002 }
1003 
1004 /*******************************************************************************
1005  *
1006  * Function         bta_dm_adjust_roles
1007  *
1008  * Description      Adjust roles
1009  *
1010  *
1011  * Returns          void
1012  *
1013  ******************************************************************************/
bta_dm_adjust_roles(bool delay_role_switch)1014 static void bta_dm_adjust_roles(bool delay_role_switch) {
1015   uint8_t i;
1016   uint8_t link_count = bta_dm_cb.device_list.count;
1017   if (link_count) {
1018     for (i = 0; i < bta_dm_cb.device_list.count; i++) {
1019       if (bta_dm_cb.device_list.peer_device[i].conn_state ==
1020               tBTA_DM_CONN_STATE::BTA_DM_CONNECTED &&
1021           bta_dm_cb.device_list.peer_device[i].transport ==
1022               BT_TRANSPORT_BR_EDR) {
1023         if ((bta_dm_cb.device_list.peer_device[i].pref_role ==
1024              BTA_CENTRAL_ROLE_ONLY) ||
1025             (link_count > 1)) {
1026           /* Initiating immediate role switch with certain remote devices
1027             has caused issues due to role  switch colliding with link encryption
1028             setup and
1029             causing encryption (and in turn the link) to fail .  These device .
1030             Firmware
1031             versions are stored in a rejectlist and role switch with these
1032             devices are
1033             delayed to avoid the collision with link encryption setup */
1034 
1035           if (bta_dm_cb.device_list.peer_device[i].pref_role !=
1036                   BTA_PERIPHERAL_ROLE_ONLY &&
1037               !delay_role_switch) {
1038             const tBTM_STATUS status =
1039                 get_btm_client_interface().link_policy.BTM_SwitchRoleToCentral(
1040                     bta_dm_cb.device_list.peer_device[i].peer_bdaddr);
1041             switch (status) {
1042               case BTM_SUCCESS:
1043                 log::debug("Role policy already set to central peer:{}",
1044                            bta_dm_cb.device_list.peer_device[i].peer_bdaddr);
1045                 break;
1046               case BTM_CMD_STARTED:
1047                 log::debug("Role policy started to central peer:{}",
1048                            bta_dm_cb.device_list.peer_device[i].peer_bdaddr);
1049                 break;
1050               default:
1051                 log::warn("Unable to set role policy to central peer:{}",
1052                           bta_dm_cb.device_list.peer_device[i].peer_bdaddr);
1053                 break;
1054             }
1055           } else {
1056             alarm_set_on_mloop(bta_dm_cb.switch_delay_timer,
1057                                BTA_DM_SWITCH_DELAY_TIMER_MS,
1058                                bta_dm_delay_role_switch_cback, NULL);
1059           }
1060         }
1061       }
1062     }
1063   }
1064 }
1065 
1066 /*******************************************************************************
1067  *
1068  * Function         find_utf8_char_boundary
1069  *
1070  * Description      This function checks a UTF8 string |utf8str| starting at
1071  *                  |offset|, moving backwards and returns the offset of the
1072  *                  next valid UTF8 character boundary found.
1073  *
1074  * Returns          Offset of UTF8 character boundary
1075  *
1076  ******************************************************************************/
find_utf8_char_boundary(const char * utf8str,size_t offset)1077 static size_t find_utf8_char_boundary(const char* utf8str, size_t offset) {
1078   log::assert_that(utf8str != nullptr, "assert failed: utf8str != nullptr");
1079   log::assert_that(offset > 0, "assert failed: offset > 0");
1080 
1081   while (--offset) {
1082     uint8_t ch = (uint8_t)utf8str[offset];
1083     if ((ch & 0x80) == 0x00)  // ASCII
1084       return offset + 1;
1085     if ((ch & 0xC0) == 0xC0)  // Multi-byte sequence start
1086       return offset;
1087   }
1088 
1089   return 0;
1090 }
1091 
1092 /*******************************************************************************
1093  *
1094  * Function         bta_dm_set_eir
1095  *
1096  * Description      This function creates EIR tagged data and writes it to
1097  *                  controller.
1098  *
1099  * Returns          None
1100  *
1101  ******************************************************************************/
bta_dm_set_eir(char * local_name)1102 static void bta_dm_set_eir(char* local_name) {
1103   uint8_t* p;
1104   uint8_t* p_length;
1105   uint8_t* p_type;
1106   uint8_t max_num_uuid;
1107 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
1108   uint8_t custom_uuid_idx;
1109 #endif  // BTA_EIR_SERVER_NUM_CUSTOM_UUID
1110   uint8_t free_eir_length = HCI_DM5_PACKET_SIZE;
1111   uint8_t num_uuid;
1112   uint8_t data_type;
1113   uint8_t local_name_len;
1114 
1115   /* wait until complete to disable */
1116   if (alarm_is_scheduled(bta_dm_cb.disable_timer)) return;
1117 
1118   /* if local name is not provided, get it from controller */
1119   if (local_name == NULL) {
1120     if (BTM_ReadLocalDeviceName((const char**)&local_name) != BTM_SUCCESS) {
1121       log::error("Fail to read local device name for EIR");
1122     }
1123   }
1124 
1125   /* Allocate a buffer to hold HCI command */
1126   BT_HDR* p_buf = (BT_HDR*)osi_malloc(BTM_CMD_BUF_SIZE);
1127   log::assert_that(p_buf != nullptr, "assert failed: p_buf != nullptr");
1128   p = (uint8_t*)p_buf + BTM_HCI_EIR_OFFSET;
1129 
1130   memset(p, 0x00, HCI_EXT_INQ_RESPONSE_LEN);
1131 
1132   log::info("Generating extended inquiry response packet EIR");
1133 
1134   if (local_name)
1135     local_name_len = strlen(local_name);
1136   else
1137     local_name_len = 0;
1138 
1139   data_type = HCI_EIR_COMPLETE_LOCAL_NAME_TYPE;
1140   /* if local name is longer than minimum length of shortened name */
1141   /* check whether it needs to be shortened or not */
1142   if (local_name_len > p_bta_dm_eir_cfg->bta_dm_eir_min_name_len) {
1143     /* get number of UUID 16-bit list */
1144     max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes16;
1145     data_type = get_btm_client_interface().eir.BTM_GetEirSupportedServices(
1146         bta_dm_cb.eir_uuid, &p, max_num_uuid, &num_uuid);
1147     p = (uint8_t*)p_buf + BTM_HCI_EIR_OFFSET; /* reset p */
1148 
1149     /* if UUID doesn't fit remaing space, shorten local name */
1150     if (local_name_len > (free_eir_length - 4 - num_uuid * Uuid::kNumBytes16)) {
1151       local_name_len = find_utf8_char_boundary(
1152           local_name, p_bta_dm_eir_cfg->bta_dm_eir_min_name_len);
1153       log::warn("local name is shortened ({})", local_name_len);
1154       data_type = HCI_EIR_SHORTENED_LOCAL_NAME_TYPE;
1155     } else {
1156       data_type = HCI_EIR_COMPLETE_LOCAL_NAME_TYPE;
1157     }
1158   }
1159 
1160   UINT8_TO_STREAM(p, local_name_len + 1);
1161   UINT8_TO_STREAM(p, data_type);
1162 
1163   if (local_name != NULL) {
1164     memcpy(p, local_name, local_name_len);
1165     p += local_name_len;
1166   }
1167   free_eir_length -= local_name_len + 2;
1168 
1169   /* if UUID list is dynamic */
1170   if (free_eir_length >= 2) {
1171     p_length = p++;
1172     p_type = p++;
1173     num_uuid = 0;
1174 
1175     max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes16;
1176     data_type = get_btm_client_interface().eir.BTM_GetEirSupportedServices(
1177         bta_dm_cb.eir_uuid, &p, max_num_uuid, &num_uuid);
1178 
1179     if (data_type == HCI_EIR_MORE_16BITS_UUID_TYPE) {
1180       log::warn("BTA EIR: UUID 16-bit list is truncated");
1181     }
1182 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
1183     else {
1184       for (custom_uuid_idx = 0;
1185            custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID;
1186            custom_uuid_idx++) {
1187         const Uuid& curr = bta_dm_cb.bta_custom_uuid[custom_uuid_idx].custom_uuid;
1188         if (curr.GetShortestRepresentationSize() == Uuid::kNumBytes16) {
1189           if (num_uuid < max_num_uuid) {
1190             UINT16_TO_STREAM(p, curr.As16Bit());
1191             num_uuid++;
1192           } else {
1193             data_type = HCI_EIR_MORE_16BITS_UUID_TYPE;
1194             log::warn("BTA EIR: UUID 16-bit list is truncated");
1195             break;
1196           }
1197         }
1198       }
1199     }
1200 #endif /* (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) */
1201 
1202     UINT8_TO_STREAM(p_length, num_uuid * Uuid::kNumBytes16 + 1);
1203     UINT8_TO_STREAM(p_type, data_type);
1204     free_eir_length -= num_uuid * Uuid::kNumBytes16 + 2;
1205   }
1206 
1207 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
1208   /* Adding 32-bit UUID list */
1209   if (free_eir_length >= 2) {
1210     p_length = p++;
1211     p_type = p++;
1212     num_uuid = 0;
1213     data_type = HCI_EIR_COMPLETE_32BITS_UUID_TYPE;
1214 
1215     max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes32;
1216 
1217     for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID;
1218          custom_uuid_idx++) {
1219       const Uuid& curr = bta_dm_cb.bta_custom_uuid[custom_uuid_idx].custom_uuid;
1220       if (curr.GetShortestRepresentationSize() == Uuid::kNumBytes32) {
1221         if (num_uuid < max_num_uuid) {
1222           UINT32_TO_STREAM(p, curr.As32Bit());
1223           num_uuid++;
1224         } else {
1225           data_type = HCI_EIR_MORE_32BITS_UUID_TYPE;
1226           log::warn("BTA EIR: UUID 32-bit list is truncated");
1227           break;
1228         }
1229       }
1230     }
1231 
1232     UINT8_TO_STREAM(p_length, num_uuid * Uuid::kNumBytes32 + 1);
1233     UINT8_TO_STREAM(p_type, data_type);
1234     free_eir_length -= num_uuid * Uuid::kNumBytes32 + 2;
1235   }
1236 
1237   /* Adding 128-bit UUID list */
1238   if (free_eir_length >= 2) {
1239     p_length = p++;
1240     p_type = p++;
1241     num_uuid = 0;
1242     data_type = HCI_EIR_COMPLETE_128BITS_UUID_TYPE;
1243 
1244     max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes128;
1245 
1246     for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID;
1247          custom_uuid_idx++) {
1248       const Uuid& curr = bta_dm_cb.bta_custom_uuid[custom_uuid_idx].custom_uuid;
1249       if (curr.GetShortestRepresentationSize() == Uuid::kNumBytes128) {
1250         if (num_uuid < max_num_uuid) {
1251           ARRAY16_TO_STREAM(p, curr.To128BitBE().data());
1252           num_uuid++;
1253         } else {
1254           data_type = HCI_EIR_MORE_128BITS_UUID_TYPE;
1255           log::warn("BTA EIR: UUID 128-bit list is truncated");
1256           break;
1257         }
1258       }
1259     }
1260 
1261     UINT8_TO_STREAM(p_length, num_uuid * Uuid::kNumBytes128 + 1);
1262     UINT8_TO_STREAM(p_type, data_type);
1263     free_eir_length -= num_uuid * Uuid::kNumBytes128 + 2;
1264   }
1265 #endif /* BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0 */
1266 
1267   /* if Flags are provided in configuration */
1268   if ((p_bta_dm_eir_cfg->bta_dm_eir_flag_len > 0) &&
1269       (p_bta_dm_eir_cfg->bta_dm_eir_flags) &&
1270       (free_eir_length >= p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 2)) {
1271     UINT8_TO_STREAM(p, p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 1);
1272     UINT8_TO_STREAM(p, HCI_EIR_FLAGS_TYPE);
1273     memcpy(p, p_bta_dm_eir_cfg->bta_dm_eir_flags,
1274            p_bta_dm_eir_cfg->bta_dm_eir_flag_len);
1275     p += p_bta_dm_eir_cfg->bta_dm_eir_flag_len;
1276     free_eir_length -= p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 2;
1277   }
1278 
1279   /* if Manufacturer Specific are provided in configuration */
1280   if ((p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len > 0) &&
1281       (p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec) &&
1282       (free_eir_length >= p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len + 2)) {
1283     p_length = p;
1284 
1285     UINT8_TO_STREAM(p, p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len + 1);
1286     UINT8_TO_STREAM(p, HCI_EIR_MANUFACTURER_SPECIFIC_TYPE);
1287     memcpy(p, p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec,
1288            p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len);
1289     p += p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len;
1290     free_eir_length -= p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len + 2;
1291 
1292   } else {
1293     p_length = NULL;
1294   }
1295 
1296   /* if Inquiry Tx Resp Power compiled */
1297   if ((p_bta_dm_eir_cfg->bta_dm_eir_inq_tx_power) && (free_eir_length >= 3)) {
1298     UINT8_TO_STREAM(p, 2); /* Length field */
1299     UINT8_TO_STREAM(p, HCI_EIR_TX_POWER_LEVEL_TYPE);
1300     UINT8_TO_STREAM(p, *(p_bta_dm_eir_cfg->bta_dm_eir_inq_tx_power));
1301     free_eir_length -= 3;
1302   }
1303 
1304   if (free_eir_length)
1305     UINT8_TO_STREAM(p, 0); /* terminator of significant part */
1306 
1307   if (get_btm_client_interface().eir.BTM_WriteEIR(p_buf) != BTM_SUCCESS) {
1308     log::warn("Unable to write EIR data");
1309   }
1310 }
1311 
1312 /*******************************************************************************
1313  *
1314  * Function         bta_dm_get_cust_uuid_index
1315  *
1316  * Description      Get index of custom uuid from list
1317  *                  Note, handle equals to 0 means to find a vacant
1318  *                  from list.
1319  *
1320  * Returns          Index of array
1321  *                  bta_dm_cb.bta_custom_uuid[BTA_EIR_SERVER_NUM_CUSTOM_UUID]
1322  *
1323  ******************************************************************************/
bta_dm_get_cust_uuid_index(uint32_t handle)1324 static uint8_t bta_dm_get_cust_uuid_index(uint32_t handle) {
1325 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
1326   uint8_t c_uu_idx = 0;
1327 
1328   while(c_uu_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID &&
1329       bta_dm_cb.bta_custom_uuid[c_uu_idx].handle != handle) {
1330     c_uu_idx++;
1331   }
1332 
1333   return c_uu_idx;
1334 #else
1335   return 0;
1336 #endif
1337 }
1338 
1339 /*******************************************************************************
1340  *
1341  * Function         bta_dm_update_cust_uuid
1342  *
1343  * Description      Update custom uuid with given value
1344  *
1345  * Returns          None
1346  *
1347  ******************************************************************************/
bta_dm_update_cust_uuid(uint8_t c_uu_idx,const Uuid & uuid,uint32_t handle)1348 static void bta_dm_update_cust_uuid(uint8_t c_uu_idx, const Uuid& uuid, uint32_t handle) {
1349 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
1350   if (c_uu_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID) {
1351     tBTA_CUSTOM_UUID& curr = bta_dm_cb.bta_custom_uuid[c_uu_idx];
1352     curr.custom_uuid.UpdateUuid(uuid);
1353     curr.handle = handle;
1354   } else {
1355     log::error("invalid uuid index {}", c_uu_idx);
1356   }
1357 #endif
1358 }
1359 
1360 /*******************************************************************************
1361  *
1362  * Function         bta_dm_eir_update_cust_uuid
1363  *
1364  * Description      This function adds or removes custom service UUID in EIR database.
1365  *
1366  * Returns          None
1367  *
1368  ******************************************************************************/
bta_dm_eir_update_cust_uuid(const tBTA_CUSTOM_UUID & curr,bool adding)1369 void bta_dm_eir_update_cust_uuid(const tBTA_CUSTOM_UUID& curr, bool adding) {
1370   log::verbose("");
1371 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
1372   uint8_t c_uu_idx = 0;
1373   if (adding) {
1374     c_uu_idx = bta_dm_get_cust_uuid_index(0); /* find a vacant from uuid list */
1375     bta_dm_update_cust_uuid(c_uu_idx, curr.custom_uuid, curr.handle);
1376   } else {
1377     c_uu_idx = bta_dm_get_cust_uuid_index(curr.handle); /* find the uuid from uuid list */
1378     bta_dm_update_cust_uuid(c_uu_idx, curr.custom_uuid, 0);
1379   }
1380 
1381   /* Update EIR when UUIDs are changed */
1382   if (c_uu_idx <= BTA_EIR_SERVER_NUM_CUSTOM_UUID) {
1383     bta_dm_set_eir(NULL);
1384   }
1385 #endif
1386 }
1387 
1388 /*******************************************************************************
1389  *
1390  * Function         bta_dm_eir_update_uuid
1391  *
1392  * Description      This function adds or removes service UUID in EIR database.
1393  *
1394  * Returns          None
1395  *
1396  ******************************************************************************/
bta_dm_eir_update_uuid(uint16_t uuid16,bool adding)1397 void bta_dm_eir_update_uuid(uint16_t uuid16, bool adding) {
1398   /* if this UUID is not advertised in EIR */
1399   if (!BTM_HasEirService(p_bta_dm_eir_cfg->uuid_mask, uuid16)) return;
1400 
1401   if (adding) {
1402     log::info("EIR Adding UUID=0x{:04X} into extended inquiry response",
1403               uuid16);
1404 
1405     get_btm_client_interface().eir.BTM_AddEirService(bta_dm_cb.eir_uuid,
1406                                                      uuid16);
1407   } else {
1408     log::info("EIR Removing UUID=0x{:04X} from extended inquiry response",
1409               uuid16);
1410 
1411     get_btm_client_interface().eir.BTM_RemoveEirService(bta_dm_cb.eir_uuid,
1412                                                         uuid16);
1413   }
1414 
1415   bta_dm_set_eir(NULL);
1416 }
1417 
find_connected_device(const RawAddress & bd_addr,tBT_TRANSPORT)1418 tBTA_DM_PEER_DEVICE* find_connected_device(const RawAddress& bd_addr,
1419                                            tBT_TRANSPORT /* transport */) {
1420   for (uint8_t i = 0; i < bta_dm_cb.device_list.count; i++) {
1421     if (bta_dm_cb.device_list.peer_device[i].peer_bdaddr == bd_addr &&
1422         bta_dm_cb.device_list.peer_device[i].conn_state ==
1423             tBTA_DM_CONN_STATE::BTA_DM_CONNECTED)
1424       return &bta_dm_cb.device_list.peer_device[i];
1425   }
1426   return nullptr;
1427 }
1428 
bta_dm_check_if_only_hd_connected(const RawAddress & peer_addr)1429 bool bta_dm_check_if_only_hd_connected(const RawAddress& peer_addr) {
1430   log::verbose("count({})", bta_dm_conn_srvcs.count);
1431 
1432   for (uint8_t j = 0; j < bta_dm_conn_srvcs.count; j++) {
1433     // Check if profiles other than hid are connected
1434     if ((bta_dm_conn_srvcs.conn_srvc[j].id != BTA_ID_HD) &&
1435         bta_dm_conn_srvcs.conn_srvc[j].peer_bdaddr == peer_addr) {
1436       log::verbose("Another profile (id={}) is connected",
1437                    bta_dm_conn_srvcs.conn_srvc[j].id);
1438       return false;
1439     }
1440   }
1441 
1442   return true;
1443 }
1444 
1445 /** This function set the preferred connection parameters */
bta_dm_ble_set_conn_params(const RawAddress & bd_addr,uint16_t conn_int_min,uint16_t conn_int_max,uint16_t peripheral_latency,uint16_t supervision_tout)1446 void bta_dm_ble_set_conn_params(const RawAddress& bd_addr,
1447                                 uint16_t conn_int_min, uint16_t conn_int_max,
1448                                 uint16_t peripheral_latency,
1449                                 uint16_t supervision_tout) {
1450   L2CA_AdjustConnectionIntervals(&conn_int_min, &conn_int_max,
1451                                  BTM_BLE_CONN_INT_MIN);
1452 
1453   get_btm_client_interface().ble.BTM_BleSetPrefConnParams(
1454       bd_addr, conn_int_min, conn_int_max, peripheral_latency,
1455       supervision_tout);
1456 }
1457 
1458 /** This function update LE connection parameters */
bta_dm_ble_update_conn_params(const RawAddress & bd_addr,uint16_t min_int,uint16_t max_int,uint16_t latency,uint16_t timeout,uint16_t min_ce_len,uint16_t max_ce_len)1459 void bta_dm_ble_update_conn_params(const RawAddress& bd_addr, uint16_t min_int,
1460                                    uint16_t max_int, uint16_t latency,
1461                                    uint16_t timeout, uint16_t min_ce_len,
1462                                    uint16_t max_ce_len) {
1463   L2CA_AdjustConnectionIntervals(&min_int, &max_int, BTM_BLE_CONN_INT_MIN);
1464 
1465   if (!L2CA_UpdateBleConnParams(bd_addr, min_int, max_int, latency, timeout,
1466                                 min_ce_len, max_ce_len)) {
1467     log::error("Update connection parameters failed!");
1468   }
1469 }
1470 
1471 /** This function set the maximum transmission packet size */
bta_dm_ble_set_data_length(const RawAddress & bd_addr)1472 void bta_dm_ble_set_data_length(const RawAddress& bd_addr) {
1473   uint16_t max_len = bluetooth::shim::GetController()
1474                          ->GetLeMaximumDataLength()
1475                          .supported_max_tx_octets_;
1476 
1477   if (BTM_SetBleDataLength(bd_addr, max_len) != BTM_SUCCESS) {
1478     log::info("Unable to set ble data length:{}", max_len);
1479   }
1480 }
1481 
1482 /** This function returns system context info */
bta_dm_obtain_system_context()1483 static tBTM_CONTRL_STATE bta_dm_obtain_system_context() {
1484   uint32_t total_acl_num = bta_dm_cb.device_list.count;
1485   uint32_t sniff_acl_num = BTM_PM_ReadSniffLinkCount();
1486   uint32_t le_acl_num = BTM_PM_ReadBleLinkCount();
1487   uint32_t active_acl_num = total_acl_num - sniff_acl_num - le_acl_num;
1488   uint32_t le_adv_num =
1489       bluetooth::shim::BTM_BleGetNumberOfAdvertisingInstancesInUse();
1490   uint32_t le_scan_duty_cycle = BTM_PM_ReadBleScanDutyCycle();
1491   bool is_inquiry_active = BTM_PM_DeviceInScanState();
1492   bool is_le_audio_active = LeAudioClient::IsLeAudioClientInStreaming();
1493   bool is_av_active = false;
1494   bool is_sco_active = false;
1495 
1496   for (int i = 0; i < bta_dm_cb.device_list.count; i++) {
1497     tBTA_DM_PEER_DEVICE* p_dev = &bta_dm_cb.device_list.peer_device[i];
1498     if (p_dev->conn_state == tBTA_DM_CONN_STATE::BTA_DM_CONNECTED &&
1499         p_dev->is_av_active()) {
1500       is_av_active = true;
1501       break;
1502     }
1503   }
1504   for (int j = 0; j < bta_dm_conn_srvcs.count; j++) {
1505     /* check for SCO connected index */
1506     if (bta_dm_conn_srvcs.conn_srvc[j].id == BTA_ID_AG ||
1507         bta_dm_conn_srvcs.conn_srvc[j].id == BTA_ID_HS) {
1508       if (bta_dm_conn_srvcs.conn_srvc[j].state == BTA_SYS_SCO_OPEN) {
1509         is_sco_active = true;
1510         break;
1511       }
1512     }
1513   }
1514 
1515   tBTM_CONTRL_STATE ctrl_state = 0;
1516   set_num_acl_active_to_ctrl_state(active_acl_num, ctrl_state);
1517   set_num_acl_sniff_to_ctrl_state(sniff_acl_num, ctrl_state);
1518   set_num_acl_le_to_ctrl_state(le_acl_num, ctrl_state);
1519   set_num_le_adv_to_ctrl_state(le_adv_num, ctrl_state);
1520   set_le_scan_mode_to_ctrl_state(le_scan_duty_cycle, ctrl_state);
1521 
1522   if (is_inquiry_active) {
1523     ctrl_state |= BTM_CONTRL_INQUIRY;
1524   }
1525   if (is_sco_active) {
1526     ctrl_state |= BTM_CONTRL_SCO;
1527   }
1528   if (is_av_active) {
1529     ctrl_state |= BTM_CONTRL_A2DP;
1530   }
1531   if (is_le_audio_active) {
1532     ctrl_state |= BTM_CONTRL_LE_AUDIO;
1533   }
1534   log::debug(
1535       "active_acl_num {} sniff_acl_num {} le_acl_num {} le_adv_num {} "
1536       "le_scan_duty {} inquiry {} sco {} a2dp {} le_audio {} ctrl_state 0x{:x}",
1537       active_acl_num, sniff_acl_num, le_acl_num, le_adv_num, le_scan_duty_cycle,
1538       is_inquiry_active, is_sco_active, is_av_active, is_le_audio_active,
1539       ctrl_state);
1540   return ctrl_state;
1541 }
1542 
1543 /*******************************************************************************
1544  *
1545  * Function         bta_ble_enable_scan_cmpl
1546  *
1547  * Description      ADV payload filtering enable / disable complete callback
1548  *
1549  *
1550  * Returns          None
1551  *
1552  ******************************************************************************/
bta_ble_energy_info_cmpl(tBTM_BLE_TX_TIME_MS tx_time,tBTM_BLE_RX_TIME_MS rx_time,tBTM_BLE_IDLE_TIME_MS idle_time,tBTM_BLE_ENERGY_USED energy_used,tHCI_STATUS status)1553 static void bta_ble_energy_info_cmpl(tBTM_BLE_TX_TIME_MS tx_time,
1554                                      tBTM_BLE_RX_TIME_MS rx_time,
1555                                      tBTM_BLE_IDLE_TIME_MS idle_time,
1556                                      tBTM_BLE_ENERGY_USED energy_used,
1557                                      tHCI_STATUS status) {
1558   tBTA_STATUS st = (status == HCI_SUCCESS) ? BTA_SUCCESS : BTA_FAILURE;
1559   tBTM_CONTRL_STATE ctrl_state = BTM_CONTRL_UNKNOWN;
1560 
1561   if (BTA_SUCCESS == st) {
1562     ctrl_state = com::android::bluetooth::flags::bt_system_context_report()
1563                      ? bta_dm_obtain_system_context()
1564                      : bta_dm_pm_obtain_controller_state();
1565   }
1566 
1567   if (bta_dm_cb.p_energy_info_cback)
1568     bta_dm_cb.p_energy_info_cback(tx_time, rx_time, idle_time, energy_used,
1569                                   ctrl_state, st);
1570 }
1571 
1572 /** This function obtains the energy info */
bta_dm_ble_get_energy_info(tBTA_BLE_ENERGY_INFO_CBACK * p_energy_info_cback)1573 void bta_dm_ble_get_energy_info(
1574     tBTA_BLE_ENERGY_INFO_CBACK* p_energy_info_cback) {
1575   bta_dm_cb.p_energy_info_cback = p_energy_info_cback;
1576   tBTM_STATUS btm_status = get_btm_client_interface().ble.BTM_BleGetEnergyInfo(
1577       bta_ble_energy_info_cmpl);
1578   if (btm_status != BTM_CMD_STARTED)
1579     bta_ble_energy_info_cmpl(0, 0, 0, 0, HCI_ERR_UNSPECIFIED);
1580 }
1581 
1582 /*******************************************************************************
1583  *
1584  * Function         bta_dm_clear_event_filter
1585  *
1586  * Description      clears out the event filter.
1587  *
1588  * Parameters:
1589  *
1590  ******************************************************************************/
bta_dm_clear_event_filter(void)1591 void bta_dm_clear_event_filter(void) {
1592   log::verbose("bta_dm_clear_event_filter in bta_dm_act");
1593   bluetooth::shim::BTM_ClearEventFilter();
1594 }
1595 
1596 /*******************************************************************************
1597  *
1598  * Function         bta_dm_clear_event_mask
1599  *
1600  * Description      Clears out the event mask in the controller.
1601  *
1602  ******************************************************************************/
bta_dm_clear_event_mask(void)1603 void bta_dm_clear_event_mask(void) {
1604   log::verbose("bta_dm_clear_event_mask in bta_dm_act");
1605   bluetooth::shim::BTM_ClearEventMask();
1606 }
1607 
1608 /*******************************************************************************
1609  *
1610  * Function         bta_dm_clear_filter_accept_list
1611  *
1612  * Description      Clears out the connect list in the controller.
1613  *
1614  ******************************************************************************/
bta_dm_clear_filter_accept_list(void)1615 void bta_dm_clear_filter_accept_list(void) {
1616   log::verbose("bta_dm_clear_filter_accept_list in bta_dm_act");
1617   bluetooth::shim::BTM_ClearFilterAcceptList();
1618 }
1619 
1620 /*******************************************************************************
1621  *
1622  * Function         bta_dm_disconnect_all_acls
1623  *
1624  * Description      Disconnects all ACL connections.
1625  *
1626  ******************************************************************************/
bta_dm_disconnect_all_acls(void)1627 void bta_dm_disconnect_all_acls(void) {
1628   log::verbose("bta_dm_disconnect_all_acls in bta_dm_act");
1629   bluetooth::shim::BTM_DisconnectAllAcls();
1630 }
1631 
1632 /*******************************************************************************
1633  *
1634  * Function         bta_dm_le_rand
1635  *
1636  * Description      Generates a random number from the controller.
1637  *
1638  * Parameters:      |cb| Callback to receive the random number.
1639  *
1640  ******************************************************************************/
bta_dm_le_rand(bluetooth::hci::LeRandCallback cb)1641 void bta_dm_le_rand(bluetooth::hci::LeRandCallback cb) {
1642   log::verbose("bta_dm_le_rand in bta_dm_act");
1643   bluetooth::shim::GetController()->LeRand(std::move(cb));
1644 }
1645 
1646 /*******************************************************************************
1647  *
1648  * Function        BTA_DmSetEventFilterConnectionSetupAllDevices
1649  *
1650  * Description    Tell the controller to allow all devices
1651  *
1652  * Parameters
1653  *
1654  *******************************************************************************/
bta_dm_set_event_filter_connection_setup_all_devices()1655 void bta_dm_set_event_filter_connection_setup_all_devices() {
1656   // Autoplumbed
1657   bluetooth::shim::BTM_SetEventFilterConnectionSetupAllDevices();
1658 }
1659 
1660 /*******************************************************************************
1661  *
1662  * Function        BTA_DmAllowWakeByHid
1663  *
1664  * Description     Allow the device to be woken by HID devices
1665  *
1666  * Parameters      std::vector of Classic Address and LE (Address, Address Type)
1667  *
1668  *******************************************************************************/
bta_dm_allow_wake_by_hid(std::vector<RawAddress> classic_hid_devices,std::vector<std::pair<RawAddress,uint8_t>> le_hid_devices)1669 void bta_dm_allow_wake_by_hid(
1670     std::vector<RawAddress> classic_hid_devices,
1671     std::vector<std::pair<RawAddress, uint8_t>> le_hid_devices) {
1672   // If there are any entries in the classic hid list, we should also make
1673   // the adapter connectable for classic.
1674   if (classic_hid_devices.size() > 0) {
1675     if (BTM_SetConnectability(BTM_CONNECTABLE) != BTM_SUCCESS) {
1676       log::warn("Unable to enable classic BR/EDR connectability");
1677     }
1678   }
1679 
1680   bluetooth::shim::BTM_AllowWakeByHid(std::move(classic_hid_devices),
1681                                       std::move(le_hid_devices));
1682 }
1683 
1684 /*******************************************************************************
1685  *
1686  * Function        BTA_DmRestoreFilterAcceptList
1687  *
1688  * Description    Floss: Restore the state of the for the filter accept list
1689  *
1690  * Parameters
1691  *
1692  *******************************************************************************/
bta_dm_restore_filter_accept_list(std::vector<std::pair<RawAddress,uint8_t>> le_devices)1693 void bta_dm_restore_filter_accept_list(
1694     std::vector<std::pair<RawAddress, uint8_t>> le_devices) {
1695   // Autoplumbed
1696   bluetooth::shim::BTM_RestoreFilterAcceptList(le_devices);
1697 }
1698 
1699 /*******************************************************************************
1700  *
1701  * Function       BTA_DmSetDefaultEventMaskExcept
1702  *
1703  * Description    Floss: Set the default event mask for Classic and LE except
1704  *                the given values (they will be disabled in the final set
1705  *                mask).
1706  *
1707  * Parameters     Bits set for event mask and le event mask that should be
1708  *                disabled in the final value.
1709  *
1710  *******************************************************************************/
bta_dm_set_default_event_mask_except(uint64_t mask,uint64_t le_mask)1711 void bta_dm_set_default_event_mask_except(uint64_t mask, uint64_t le_mask) {
1712   // Autoplumbed
1713   bluetooth::shim::BTM_SetDefaultEventMaskExcept(mask, le_mask);
1714 }
1715 
1716 /*******************************************************************************
1717  *
1718  * Function        BTA_DmSetEventFilterInquiryResultAllDevices
1719  *
1720  * Description    Floss: Set the event filter to inquiry result device all
1721  *
1722  * Parameters
1723  *
1724  *******************************************************************************/
bta_dm_set_event_filter_inquiry_result_all_devices()1725 void bta_dm_set_event_filter_inquiry_result_all_devices() {
1726   // Autoplumbed
1727   bluetooth::shim::BTM_SetEventFilterInquiryResultAllDevices();
1728 }
1729 
1730 /*******************************************************************************
1731  *
1732  * Function         bta_dm_ble_reset_id
1733  *
1734  * Description      Reset the local adapter BLE keys.
1735  *
1736  * Parameters:
1737  *
1738  ******************************************************************************/
bta_dm_ble_reset_id(void)1739 void bta_dm_ble_reset_id(void) {
1740   log::verbose("bta_dm_ble_reset_id in bta_dm_act");
1741   bluetooth::shim::BTM_BleResetId();
1742 }
1743 
1744 /*******************************************************************************
1745  *
1746  * Function         bta_dm_ctrl_features_rd_cmpl_cback
1747  *
1748  * Description      callback to handle controller feature read complete
1749  *
1750  * Parameters:
1751  *
1752  ******************************************************************************/
bta_dm_ctrl_features_rd_cmpl_cback(tHCI_STATUS result)1753 static void bta_dm_ctrl_features_rd_cmpl_cback(tHCI_STATUS result) {
1754   log::verbose("status = {}", result);
1755   if (result == HCI_SUCCESS) {
1756     if (bta_dm_acl_cb.p_acl_cback)
1757       bta_dm_acl_cb.p_acl_cback(BTA_DM_LE_FEATURES_READ, NULL);
1758   } else {
1759     log::error("Ctrl BLE feature read failed: status :{}", result);
1760   }
1761 }
1762 
1763 /*******************************************************************************
1764  *
1765  * Function         bta_dm_ble_subrate_request
1766  *
1767  * Description      This function requests BLE subrate procedure.
1768  *
1769  * Parameters:
1770  *
1771  ******************************************************************************/
bta_dm_ble_subrate_request(const RawAddress & bd_addr,uint16_t subrate_min,uint16_t subrate_max,uint16_t max_latency,uint16_t cont_num,uint16_t timeout)1772 void bta_dm_ble_subrate_request(const RawAddress& bd_addr, uint16_t subrate_min,
1773                                 uint16_t subrate_max, uint16_t max_latency,
1774                                 uint16_t cont_num, uint16_t timeout) {
1775     // Logging done in l2c_ble.cc
1776     if (!L2CA_SubrateRequest(bd_addr, subrate_min, subrate_max, max_latency,
1777                              cont_num, timeout)) {
1778       log::warn("Unable to set L2CAP ble subrating peer:{}", bd_addr);
1779     }
1780 }
1781 
1782 namespace bluetooth {
1783 namespace legacy {
1784 namespace testing {
allocate_device_for(const RawAddress & bd_addr,tBT_TRANSPORT transport)1785 tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr,
1786                                          tBT_TRANSPORT transport) {
1787   return ::allocate_device_for(bd_addr, transport);
1788 }
1789 
bta_dm_acl_up(const RawAddress & bd_addr,tBT_TRANSPORT transport,uint16_t acl_handle)1790 void bta_dm_acl_up(const RawAddress& bd_addr, tBT_TRANSPORT transport,
1791                    uint16_t acl_handle) {
1792   ::bta_dm_acl_up(bd_addr, transport, acl_handle);
1793 }
bta_dm_acl_down(const RawAddress & bd_addr,tBT_TRANSPORT transport)1794 void bta_dm_acl_down(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
1795   ::bta_dm_acl_down(bd_addr, transport);
1796 }
bta_dm_init_cb()1797 void bta_dm_init_cb() { ::bta_dm_init_cb(); }
bta_dm_deinit_cb()1798 void bta_dm_deinit_cb() { ::bta_dm_deinit_cb(); }
BTA_dm_on_hw_on()1799 void BTA_dm_on_hw_on() { ::BTA_dm_on_hw_on(); }
1800 
1801 }  // namespace testing
1802 }  // namespace legacy
1803 }  // namespace bluetooth
1804