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