• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright (C) 2016 The Linux Foundation
4  *  Copyright 2009-2012 Broadcom Corporation
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at:
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  ******************************************************************************/
19 
20 /*******************************************************************************
21  *
22  *  Filename:      bluetooth.c
23  *
24  *  Description:   Bluetooth HAL implementation
25  *
26  ******************************************************************************/
27 
28 #define LOG_TAG "bt_btif"
29 
30 #include <base/logging.h>
31 #include <hardware/bluetooth.h>
32 #include <hardware/bluetooth_headset_interface.h>
33 #include <hardware/bt_av.h>
34 #include <hardware/bt_csis.h>
35 #include <hardware/bt_gatt.h>
36 #include <hardware/bt_has.h>
37 #include <hardware/bt_hd.h>
38 #include <hardware/bt_hearing_aid.h>
39 #include <hardware/bt_hf_client.h>
40 #include <hardware/bt_hh.h>
41 #include <hardware/bt_le_audio.h>
42 #include <hardware/bt_pan.h>
43 #include <hardware/bt_rc.h>
44 #include <hardware/bt_sdp.h>
45 #include <hardware/bt_sock.h>
46 #include <hardware/bt_vc.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 
52 #include "audio_hal_interface/a2dp_encoding.h"
53 #include "bta/hh/bta_hh_int.h"  // for HID HACK profile methods
54 #include "bta/include/bta_api.h"
55 #include "bta/include/bta_ar_api.h"
56 #include "bta/include/bta_csis_api.h"
57 #include "bta/include/bta_has_api.h"
58 #include "bta/include/bta_hearing_aid_api.h"
59 #include "bta/include/bta_hf_client_api.h"
60 #include "bta/include/bta_le_audio_api.h"
61 #include "bta/include/bta_le_audio_broadcaster_api.h"
62 #include "bta/include/bta_vc_api.h"
63 #include "btif/avrcp/avrcp_service.h"
64 #include "btif/include/btif_sock.h"
65 #include "btif/include/core_callbacks.h"
66 #include "btif/include/stack_manager.h"
67 #include "btif_a2dp.h"
68 #include "btif_activity_attribution.h"
69 #include "btif_api.h"
70 #include "btif_av.h"
71 #include "btif_bqr.h"
72 #include "btif_config.h"
73 #include "btif_debug_conn.h"
74 #include "btif_dm.h"
75 #include "btif_hd.h"
76 #include "btif_hf.h"
77 #include "btif_hh.h"
78 #include "btif_keystore.h"
79 #include "btif_metrics_logging.h"
80 #include "btif_pan.h"
81 #include "btif_profile_storage.h"
82 #include "btif_rc.h"
83 #include "btif_sock.h"
84 #include "btif_storage.h"
85 #include "common/address_obfuscator.h"
86 #include "common/metric_id_allocator.h"
87 #include "common/metrics.h"
88 #include "common/os_utils.h"
89 #include "device/include/device_iot_config.h"
90 #include "device/include/interop.h"
91 #include "device/include/interop_config.h"
92 #include "gd/common/init_flags.h"
93 #include "gd/os/parameter_provider.h"
94 #include "main/shim/dumpsys.h"
95 #include "main/shim/shim.h"
96 #include "osi/include/alarm.h"
97 #include "osi/include/allocation_tracker.h"
98 #include "osi/include/allocator.h"
99 #include "osi/include/log.h"
100 #include "osi/include/osi.h"
101 #include "osi/include/wakelock.h"
102 #include "profile_log_levels.h"
103 #include "stack/btm/btm_sco_hfp_hal.h"
104 #include "stack/gatt/connection_manager.h"
105 #include "stack/include/a2dp_api.h"
106 #include "stack/include/avdt_api.h"
107 #include "stack/include/btm_api.h"
108 #include "stack/include/btu.h"
109 #include "stack/include/hfp_msbc_decoder.h"
110 #include "stack/include/hfp_msbc_encoder.h"
111 #include "stack/include/hidh_api.h"
112 #include "stack/include/pan_api.h"
113 #include "stack_config.h"
114 #include "types/raw_address.h"
115 
116 using bluetooth::csis::CsisClientInterface;
117 using bluetooth::has::HasClientInterface;
118 using bluetooth::hearing_aid::HearingAidInterface;
119 #ifndef TARGET_FLOSS
120 using bluetooth::le_audio::LeAudioBroadcasterInterface;
121 using bluetooth::le_audio::LeAudioClientInterface;
122 #endif
123 using bluetooth::vc::VolumeControlInterface;
124 
125 /*******************************************************************************
126  *  Static variables
127  ******************************************************************************/
128 
129 static bt_callbacks_t* bt_hal_cbacks = NULL;
130 bool restricted_mode = false;
131 bool common_criteria_mode = false;
132 const int CONFIG_COMPARE_ALL_PASS = 0b11;
133 int common_criteria_config_compare_result = CONFIG_COMPARE_ALL_PASS;
134 bool is_local_device_atv = false;
135 
136 /*******************************************************************************
137  *  Externs
138  ******************************************************************************/
139 
140 /* list all extended interfaces here */
141 
142 /* handsfree profile - client */
143 extern const bthf_client_interface_t* btif_hf_client_get_interface();
144 /* advanced audio profile */
145 extern const btav_source_interface_t* btif_av_get_src_interface();
146 extern const btav_sink_interface_t* btif_av_get_sink_interface();
147 /*rfc l2cap*/
148 extern const btsock_interface_t* btif_sock_get_interface();
149 /* hid host profile */
150 extern const bthh_interface_t* btif_hh_get_interface();
151 /* hid device profile */
152 extern const bthd_interface_t* btif_hd_get_interface();
153 /*pan*/
154 extern const btpan_interface_t* btif_pan_get_interface();
155 /* gatt */
156 extern const btgatt_interface_t* btif_gatt_get_interface();
157 /* avrc target */
158 extern const btrc_interface_t* btif_rc_get_interface();
159 /* avrc controller */
160 extern const btrc_ctrl_interface_t* btif_rc_ctrl_get_interface();
161 /*SDP search client*/
162 extern const btsdp_interface_t* btif_sdp_get_interface();
163 /*Hearing Aid client*/
164 extern HearingAidInterface* btif_hearing_aid_get_interface();
165 #ifndef TARGET_FLOSS
166 /* Hearing Access client */
167 extern HasClientInterface* btif_has_client_get_interface();
168 /* LeAudio testi client */
169 extern LeAudioClientInterface* btif_le_audio_get_interface();
170 /* LeAudio Broadcaster */
171 extern LeAudioBroadcasterInterface* btif_le_audio_broadcaster_get_interface();
172 #endif
173 /* Coordinated Set Service Client */
174 extern CsisClientInterface* btif_csis_client_get_interface();
175 /* Volume Control client */
176 extern VolumeControlInterface* btif_volume_control_get_interface();
177 
178 bt_status_t btif_av_sink_execute_service(bool b_enable);
179 bt_status_t btif_hh_execute_service(bool b_enable);
180 bt_status_t btif_hf_client_execute_service(bool b_enable);
181 bt_status_t btif_sdp_execute_service(bool b_enable);
182 bt_status_t btif_hh_connect(const RawAddress* bd_addr);
183 bt_status_t btif_hd_execute_service(bool b_enable);
184 
185 /*******************************************************************************
186  *  Callbacks from bluetooth::core (see go/invisalign-bt)
187  ******************************************************************************/
188 
189 struct ConfigInterfaceImpl : bluetooth::core::ConfigInterface {
ConfigInterfaceImplConfigInterfaceImpl190   ConfigInterfaceImpl() : bluetooth::core::ConfigInterface(){};
191 
isRestrictedModeConfigInterfaceImpl192   bool isRestrictedMode() override { return is_restricted_mode(); }
193 
isA2DPOffloadEnabledConfigInterfaceImpl194   bool isA2DPOffloadEnabled() override {
195     char value_sup[PROPERTY_VALUE_MAX] = {'\0'};
196     char value_dis[PROPERTY_VALUE_MAX] = {'\0'};
197 
198     osi_property_get("ro.bluetooth.a2dp_offload.supported", value_sup, "false");
199     osi_property_get("persist.bluetooth.a2dp_offload.disabled", value_dis,
200                      "false");
201     auto a2dp_offload_enabled =
202         (strcmp(value_sup, "true") == 0) && (strcmp(value_dis, "false") == 0);
203     BTIF_TRACE_DEBUG("a2dp_offload.enable = %d", a2dp_offload_enabled);
204 
205     return a2dp_offload_enabled;
206   }
207 
isAndroidTVDeviceConfigInterfaceImpl208   bool isAndroidTVDevice() override { return is_atv_device(); }
209 };
210 
211 // TODO(aryarahul): remove unnecessary indirection through hfp_msbc_*.cc
212 struct MSBCCodec : bluetooth::core::CodecInterface {
MSBCCodecMSBCCodec213   MSBCCodec() : bluetooth::core::CodecInterface(){};
214 
initializeMSBCCodec215   void initialize() override {
216     hfp_msbc_decoder_init();
217     hfp_msbc_encoder_init();
218   }
219 
cleanupMSBCCodec220   void cleanup() override {
221     hfp_msbc_decoder_cleanup();
222     hfp_msbc_encoder_cleanup();
223   }
224 
encodePacketMSBCCodec225   uint32_t encodePacket(int16_t* input, uint8_t* output) {
226     return hfp_msbc_encode_frames(input, output);
227   }
228 
decodePacketMSBCCodec229   bool decodePacket(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) {
230     return hfp_msbc_decoder_decode_packet(i_buf, o_buf, out_len);
231   }
232 };
233 
234 struct CoreInterfaceImpl : bluetooth::core::CoreInterface {
235   using bluetooth::core::CoreInterface::CoreInterface;
236 
onBluetoothEnabledCoreInterfaceImpl237   void onBluetoothEnabled() override {
238     /* init pan */
239     btif_pan_init();
240   }
241 
toggleProfileCoreInterfaceImpl242   bt_status_t toggleProfile(tBTA_SERVICE_ID service_id, bool enable) override {
243     /* Check the service_ID and invoke the profile's BT state changed API */
244     switch (service_id) {
245       case BTA_HFP_SERVICE_ID:
246       case BTA_HSP_SERVICE_ID: {
247         bluetooth::headset::ExecuteService(enable);
248       } break;
249       case BTA_A2DP_SOURCE_SERVICE_ID: {
250         btif_av_source_execute_service(enable);
251       } break;
252       case BTA_A2DP_SINK_SERVICE_ID: {
253         btif_av_sink_execute_service(enable);
254       } break;
255       case BTA_HID_SERVICE_ID: {
256         btif_hh_execute_service(enable);
257       } break;
258       case BTA_HFP_HS_SERVICE_ID: {
259         btif_hf_client_execute_service(enable);
260       } break;
261       case BTA_HIDD_SERVICE_ID: {
262         btif_hd_execute_service(enable);
263       } break;
264       case BTA_PBAP_SERVICE_ID:
265       case BTA_PCE_SERVICE_ID:
266       case BTA_MAP_SERVICE_ID:
267       case BTA_MN_SERVICE_ID: {
268         /**
269          * Do nothing; these services were started elsewhere. However, we need
270          * to flow through this codepath in order to properly report back the
271          * local UUIDs back to adapter properties in Java. To achieve this, we
272          * need to catch these service IDs in order for {@link
273          * btif_in_execute_service_request} to return {@code BT_STATUS_SUCCESS},
274          * so that in {@link btif_dm_enable_service} the check passes and the
275          * UUIDs are allowed to be passed up into the Java layer.
276          */
277       } break;
278       default:
279         BTIF_TRACE_ERROR("%s: Unknown service %d being %s", __func__,
280                          service_id, (enable) ? "enabled" : "disabled");
281         return BT_STATUS_FAIL;
282     }
283     return BT_STATUS_SUCCESS;
284   }
285 
removeDeviceFromProfilesCoreInterfaceImpl286   void removeDeviceFromProfiles(const RawAddress& bd_addr) override {
287 /*special handling for HID devices */
288 #if (defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE))
289     btif_hh_remove_device(bd_addr);
290 #endif
291 #if (defined(BTA_HD_INCLUDED) && (BTA_HD_INCLUDED == TRUE))
292     btif_hd_remove_device(bd_addr);
293 #endif
294     btif_hearing_aid_get_interface()->RemoveDevice(bd_addr);
295 
296 #ifndef TARGET_FLOSS
297     if (bluetooth::csis::CsisClient::IsCsisClientRunning())
298       btif_csis_client_get_interface()->RemoveDevice(bd_addr);
299 
300     if (LeAudioClient::IsLeAudioClientRunning())
301       btif_le_audio_get_interface()->RemoveDevice(bd_addr);
302 
303     if (VolumeControl::IsVolumeControlRunning()) {
304       btif_volume_control_get_interface()->RemoveDevice(bd_addr);
305     }
306 #endif
307   }
308 
onLinkDownCoreInterfaceImpl309   void onLinkDown(const RawAddress& bd_addr) override {
310     btif_av_acl_disconnected(bd_addr);
311   }
312 };
313 
CreateInterfaceToProfiles()314 static bluetooth::core::CoreInterface* CreateInterfaceToProfiles() {
315   static auto eventCallbacks = bluetooth::core::EventCallbacks{
316       .invoke_adapter_state_changed_cb = invoke_adapter_state_changed_cb,
317       .invoke_adapter_properties_cb = invoke_adapter_properties_cb,
318       .invoke_remote_device_properties_cb = invoke_remote_device_properties_cb,
319       .invoke_device_found_cb = invoke_device_found_cb,
320       .invoke_discovery_state_changed_cb = invoke_discovery_state_changed_cb,
321       .invoke_pin_request_cb = invoke_pin_request_cb,
322       .invoke_ssp_request_cb = invoke_ssp_request_cb,
323       .invoke_oob_data_request_cb = invoke_oob_data_request_cb,
324       .invoke_bond_state_changed_cb = invoke_bond_state_changed_cb,
325       .invoke_address_consolidate_cb = invoke_address_consolidate_cb,
326       .invoke_le_address_associate_cb = invoke_le_address_associate_cb,
327       .invoke_acl_state_changed_cb = invoke_acl_state_changed_cb,
328       .invoke_thread_evt_cb = invoke_thread_evt_cb,
329       .invoke_energy_info_cb = invoke_energy_info_cb,
330       .invoke_link_quality_report_cb = invoke_link_quality_report_cb};
331   static auto configInterface = ConfigInterfaceImpl();
332   static auto msbcCodecInterface = MSBCCodec();
333   static auto profileInterface = bluetooth::core::HACK_ProfileInterface{
334       // HID
335       .btif_hh_connect = btif_hh_connect,
336       .btif_hh_virtual_unplug = btif_hh_virtual_unplug,
337       .bta_hh_read_ssr_param = bta_hh_read_ssr_param,
338 
339       // AVDTP
340       .btif_av_set_dynamic_audio_buffer_size =
341           btif_av_set_dynamic_audio_buffer_size,
342 
343       // ASHA
344       .GetHearingAidDeviceCount = HearingAid::GetDeviceCount,
345 
346       // LE Audio
347       .IsLeAudioClientRunning = LeAudioClient::IsLeAudioClientRunning,
348 
349       // AVRCP
350       .AVRC_GetProfileVersion = AVRC_GetProfileVersion};
351 
352   static auto interfaceForCore =
353       CoreInterfaceImpl(&eventCallbacks, &configInterface, &msbcCodecInterface,
354                         &profileInterface);
355   return &interfaceForCore;
356 }
357 
358 /*******************************************************************************
359  *  Functions
360  ******************************************************************************/
361 
interface_ready(void)362 static bool interface_ready(void) { return bt_hal_cbacks != NULL; }
set_hal_cbacks(bt_callbacks_t * callbacks)363 void set_hal_cbacks(bt_callbacks_t* callbacks) { bt_hal_cbacks = callbacks; }
364 
is_profile(const char * p1,const char * p2)365 static bool is_profile(const char* p1, const char* p2) {
366   CHECK(p1);
367   CHECK(p2);
368   return strlen(p1) == strlen(p2) && strncmp(p1, p2, strlen(p2)) == 0;
369 }
370 
371 /*****************************************************************************
372  *
373  *   BLUETOOTH HAL INTERFACE FUNCTIONS
374  *
375  ****************************************************************************/
376 
init(bt_callbacks_t * callbacks,bool start_restricted,bool is_common_criteria_mode,int config_compare_result,const char ** init_flags,bool is_atv,const char * user_data_directory)377 static int init(bt_callbacks_t* callbacks, bool start_restricted,
378                 bool is_common_criteria_mode, int config_compare_result,
379                 const char** init_flags, bool is_atv,
380                 const char* user_data_directory) {
381   (void)user_data_directory;
382   LOG_INFO(
383       "%s: start restricted = %d ; common criteria mode = %d, config compare "
384       "result = %d",
385       __func__, start_restricted, is_common_criteria_mode,
386       config_compare_result);
387 
388   bluetooth::common::InitFlags::Load(init_flags);
389 
390   if (interface_ready()) return BT_STATUS_DONE;
391 
392 #ifdef BLUEDROID_DEBUG
393   allocation_tracker_init();
394 #endif
395 
396   set_hal_cbacks(callbacks);
397 
398   restricted_mode = start_restricted;
399 
400   bluetooth::os::ParameterProvider::SetBtKeystoreInterface(
401       bluetooth::bluetooth_keystore::getBluetoothKeystoreInterface());
402   bluetooth::os::ParameterProvider::SetCommonCriteriaMode(
403       is_common_criteria_mode);
404   if (is_bluetooth_uid() && is_common_criteria_mode) {
405     bluetooth::os::ParameterProvider::SetCommonCriteriaConfigCompareResult(
406         config_compare_result);
407   } else {
408     bluetooth::os::ParameterProvider::SetCommonCriteriaConfigCompareResult(
409         CONFIG_COMPARE_ALL_PASS);
410   }
411 
412   is_local_device_atv = is_atv;
413 
414   stack_manager_get_interface()->init_stack(CreateInterfaceToProfiles());
415   return BT_STATUS_SUCCESS;
416 }
417 
start_profiles()418 static void start_profiles() {
419 #if (BNEP_INCLUDED == TRUE)
420   BNEP_Init();
421 #if (PAN_INCLUDED == TRUE)
422   PAN_Init();
423 #endif /* PAN */
424 #endif /* BNEP Included */
425   A2DP_Init();
426   AVRC_Init();
427 #if (HID_HOST_INCLUDED == TRUE)
428   HID_HostInit();
429 #endif
430   bta_ar_init();
431 
432   // initialize profile-specific logging levels
433   const auto stack_config = stack_config_get_interface();
434   if (stack_config->get_trace_config_enabled()) {
435     load_levels_from_config(stack_config->get_all());
436   }
437 }
438 
stop_profiles()439 static void stop_profiles() {
440   btif_sock_cleanup();
441   btif_pan_cleanup();
442 }
443 
enable()444 static int enable() {
445   if (!interface_ready()) return BT_STATUS_NOT_READY;
446 
447   stack_manager_get_interface()->start_up_stack_async(
448       CreateInterfaceToProfiles(), &start_profiles, &stop_profiles);
449   return BT_STATUS_SUCCESS;
450 }
451 
disable(void)452 static int disable(void) {
453   if (!interface_ready()) return BT_STATUS_NOT_READY;
454 
455   stack_manager_get_interface()->shut_down_stack_async(&stop_profiles);
456   return BT_STATUS_SUCCESS;
457 }
458 
cleanup(void)459 static void cleanup(void) {
460   stack_manager_get_interface()->clean_up_stack(&stop_profiles);
461 }
462 
is_restricted_mode()463 bool is_restricted_mode() { return restricted_mode; }
464 
get_wbs_supported()465 static bool get_wbs_supported() {
466   return hfp_hal_interface::get_wbs_supported();
467 }
468 
get_swb_supported()469 static bool get_swb_supported() {
470   return hfp_hal_interface::get_swb_supported();
471 }
472 
is_common_criteria_mode()473 bool is_common_criteria_mode() {
474   return is_bluetooth_uid() && common_criteria_mode;
475 }
476 // if common criteria mode disable, will always return
477 // CONFIG_COMPARE_ALL_PASS(0b11) indicate don't check config checksum.
get_common_criteria_config_compare_result()478 int get_common_criteria_config_compare_result() {
479   return is_common_criteria_mode() ? common_criteria_config_compare_result
480                                    : CONFIG_COMPARE_ALL_PASS;
481 }
482 
is_atv_device()483 bool is_atv_device() { return is_local_device_atv; }
484 
get_adapter_properties(void)485 static int get_adapter_properties(void) {
486   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
487 
488   do_in_main_thread(FROM_HERE, base::BindOnce(btif_get_adapter_properties));
489   return BT_STATUS_SUCCESS;
490 }
491 
get_adapter_property(bt_property_type_t type)492 static int get_adapter_property(bt_property_type_t type) {
493   /* Allow get_adapter_property only for BDADDR and BDNAME if BT is disabled */
494   if (!btif_is_enabled() && (type != BT_PROPERTY_BDADDR) &&
495       (type != BT_PROPERTY_BDNAME))
496     return BT_STATUS_NOT_READY;
497 
498   do_in_main_thread(FROM_HERE, base::BindOnce(btif_get_adapter_property, type));
499   return BT_STATUS_SUCCESS;
500 }
501 
set_adapter_property(const bt_property_t * property)502 static int set_adapter_property(const bt_property_t* property) {
503   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
504 
505   switch (property->type) {
506     case BT_PROPERTY_BDNAME:
507     case BT_PROPERTY_ADAPTER_SCAN_MODE:
508     case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT:
509     case BT_PROPERTY_CLASS_OF_DEVICE:
510     case BT_PROPERTY_LOCAL_IO_CAPS:
511       break;
512     default:
513       return BT_STATUS_FAIL;
514   }
515 
516   do_in_main_thread(FROM_HERE, base::BindOnce(
517                                    [](bt_property_t* property) {
518                                      btif_set_adapter_property(property);
519                                      osi_free(property);
520                                    },
521                                    property_deep_copy(property)));
522   return BT_STATUS_SUCCESS;
523 }
524 
get_remote_device_properties(RawAddress * remote_addr)525 int get_remote_device_properties(RawAddress* remote_addr) {
526   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
527 
528   do_in_main_thread(FROM_HERE, base::BindOnce(btif_get_remote_device_properties,
529                                               *remote_addr));
530   return BT_STATUS_SUCCESS;
531 }
532 
get_remote_device_property(RawAddress * remote_addr,bt_property_type_t type)533 int get_remote_device_property(RawAddress* remote_addr,
534                                bt_property_type_t type) {
535   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
536 
537   do_in_main_thread(FROM_HERE, base::BindOnce(btif_get_remote_device_property,
538                                               *remote_addr, type));
539   return BT_STATUS_SUCCESS;
540 }
541 
set_remote_device_property(RawAddress * remote_addr,const bt_property_t * property)542 int set_remote_device_property(RawAddress* remote_addr,
543                                const bt_property_t* property) {
544   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
545 
546   do_in_main_thread(
547       FROM_HERE, base::BindOnce(
548                      [](RawAddress remote_addr, bt_property_t* property) {
549                        btif_set_remote_device_property(&remote_addr, property);
550                        osi_free(property);
551                      },
552                      *remote_addr, property_deep_copy(property)));
553   return BT_STATUS_SUCCESS;
554 }
555 
get_remote_services(RawAddress * remote_addr,int transport)556 int get_remote_services(RawAddress* remote_addr, int transport) {
557   if (!interface_ready()) return BT_STATUS_NOT_READY;
558 
559   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_get_remote_services,
560                                               *remote_addr, transport));
561   return BT_STATUS_SUCCESS;
562 }
563 
start_discovery(void)564 static int start_discovery(void) {
565   if (!interface_ready()) return BT_STATUS_NOT_READY;
566 
567   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_start_discovery));
568   return BT_STATUS_SUCCESS;
569 }
570 
cancel_discovery(void)571 static int cancel_discovery(void) {
572   if (!interface_ready()) return BT_STATUS_NOT_READY;
573 
574   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_cancel_discovery));
575   return BT_STATUS_SUCCESS;
576 }
577 
create_bond(const RawAddress * bd_addr,int transport)578 static int create_bond(const RawAddress* bd_addr, int transport) {
579   if (!interface_ready()) return BT_STATUS_NOT_READY;
580   if (btif_dm_pairing_is_busy()) return BT_STATUS_BUSY;
581 
582   do_in_main_thread(FROM_HERE,
583                     base::BindOnce(btif_dm_create_bond, *bd_addr, transport));
584   return BT_STATUS_SUCCESS;
585 }
586 
create_bond_le(const RawAddress * bd_addr,uint8_t addr_type)587 static int create_bond_le(const RawAddress* bd_addr, uint8_t addr_type) {
588   if (!interface_ready()) return BT_STATUS_NOT_READY;
589   if (btif_dm_pairing_is_busy()) return BT_STATUS_BUSY;
590 
591   do_in_main_thread(
592       FROM_HERE, base::BindOnce(btif_dm_create_bond_le, *bd_addr, addr_type));
593   return BT_STATUS_SUCCESS;
594 }
595 
create_bond_out_of_band(const RawAddress * bd_addr,int transport,const bt_oob_data_t * p192_data,const bt_oob_data_t * p256_data)596 static int create_bond_out_of_band(const RawAddress* bd_addr, int transport,
597                                    const bt_oob_data_t* p192_data,
598                                    const bt_oob_data_t* p256_data) {
599   if (!interface_ready()) return BT_STATUS_NOT_READY;
600   if (btif_dm_pairing_is_busy()) return BT_STATUS_BUSY;
601 
602   do_in_main_thread(FROM_HERE,
603                     base::BindOnce(btif_dm_create_bond_out_of_band, *bd_addr,
604                                    transport, *p192_data, *p256_data));
605   return BT_STATUS_SUCCESS;
606 }
607 
generate_local_oob_data(tBT_TRANSPORT transport)608 static int generate_local_oob_data(tBT_TRANSPORT transport) {
609   LOG_INFO("%s", __func__);
610   if (!interface_ready()) return BT_STATUS_NOT_READY;
611 
612   return do_in_main_thread(
613       FROM_HERE, base::BindOnce(btif_dm_generate_local_oob_data, transport));
614 }
615 
cancel_bond(const RawAddress * bd_addr)616 static int cancel_bond(const RawAddress* bd_addr) {
617   if (!interface_ready()) return BT_STATUS_NOT_READY;
618 
619   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_cancel_bond, *bd_addr));
620   return BT_STATUS_SUCCESS;
621 }
622 
remove_bond(const RawAddress * bd_addr)623 static int remove_bond(const RawAddress* bd_addr) {
624   if (is_restricted_mode() && !btif_storage_is_restricted_device(bd_addr))
625     return BT_STATUS_SUCCESS;
626 
627   if (!interface_ready()) return BT_STATUS_NOT_READY;
628 
629   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_remove_bond, *bd_addr));
630   return BT_STATUS_SUCCESS;
631 }
632 
get_connection_state(const RawAddress * bd_addr)633 static int get_connection_state(const RawAddress* bd_addr) {
634   if (!interface_ready()) return 0;
635 
636   return btif_dm_get_connection_state(bd_addr);
637 }
638 
pin_reply(const RawAddress * bd_addr,uint8_t accept,uint8_t pin_len,bt_pin_code_t * pin_code)639 static int pin_reply(const RawAddress* bd_addr, uint8_t accept, uint8_t pin_len,
640                      bt_pin_code_t* pin_code) {
641   bt_pin_code_t tmp_pin_code;
642   if (!interface_ready()) return BT_STATUS_NOT_READY;
643   if (pin_code == nullptr || pin_len > PIN_CODE_LEN) return BT_STATUS_FAIL;
644 
645   memcpy(&tmp_pin_code, pin_code, pin_len);
646 
647   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_pin_reply, *bd_addr,
648                                               accept, pin_len, tmp_pin_code));
649   return BT_STATUS_SUCCESS;
650 }
651 
ssp_reply(const RawAddress * bd_addr,bt_ssp_variant_t variant,uint8_t accept,uint32_t passkey)652 static int ssp_reply(const RawAddress* bd_addr, bt_ssp_variant_t variant,
653                      uint8_t accept, uint32_t passkey) {
654   if (!interface_ready()) return BT_STATUS_NOT_READY;
655   if (variant == BT_SSP_VARIANT_PASSKEY_ENTRY) return BT_STATUS_FAIL;
656 
657   do_in_main_thread(
658       FROM_HERE, base::BindOnce(btif_dm_ssp_reply, *bd_addr, variant, accept));
659   return BT_STATUS_SUCCESS;
660 }
661 
read_energy_info()662 static int read_energy_info() {
663   if (!interface_ready()) return BT_STATUS_NOT_READY;
664 
665   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_read_energy_info));
666   return BT_STATUS_SUCCESS;
667 }
668 
clear_event_filter()669 static int clear_event_filter() {
670   LOG_VERBOSE("%s", __func__);
671   if (!interface_ready()) return BT_STATUS_NOT_READY;
672 
673   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_clear_event_filter));
674   return BT_STATUS_SUCCESS;
675 }
676 
clear_event_mask()677 static int clear_event_mask() {
678   LOG_VERBOSE("%s", __func__);
679   if (!interface_ready()) return BT_STATUS_NOT_READY;
680 
681   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_clear_event_mask));
682   return BT_STATUS_SUCCESS;
683 }
684 
clear_filter_accept_list()685 static int clear_filter_accept_list() {
686   LOG_VERBOSE("%s", __func__);
687   if (!interface_ready()) return BT_STATUS_NOT_READY;
688 
689   do_in_main_thread(FROM_HERE,
690                     base::BindOnce(btif_dm_clear_filter_accept_list));
691   return BT_STATUS_SUCCESS;
692 }
693 
disconnect_all_acls()694 static int disconnect_all_acls() {
695   LOG_VERBOSE("%s", __func__);
696   if (!interface_ready()) return BT_STATUS_NOT_READY;
697 
698   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_disconnect_all_acls));
699   return BT_STATUS_SUCCESS;
700 }
701 
le_rand_btif_cb(uint64_t random_number)702 static void le_rand_btif_cb(uint64_t random_number) {
703   LOG_VERBOSE("%s", __func__);
704   do_in_jni_thread(
705       FROM_HERE,
706       base::BindOnce(
707           [](uint64_t random) { HAL_CBACK(bt_hal_cbacks, le_rand_cb, random); },
708           random_number));
709 }
710 
le_rand()711 static int le_rand() {
712   LOG_VERBOSE("%s", __func__);
713   if (!interface_ready()) return BT_STATUS_NOT_READY;
714 
715   do_in_main_thread(
716       FROM_HERE, base::BindOnce(btif_dm_le_rand, base::Bind(&le_rand_btif_cb)));
717   return BT_STATUS_SUCCESS;
718 }
719 
set_event_filter_inquiry_result_all_devices()720 static int set_event_filter_inquiry_result_all_devices() {
721   if (!interface_ready()) return BT_STATUS_NOT_READY;
722   do_in_main_thread(
723       FROM_HERE,
724       base::BindOnce(btif_dm_set_event_filter_inquiry_result_all_devices));
725   return BT_STATUS_SUCCESS;
726 }
727 
set_default_event_mask_except(uint64_t mask,uint64_t le_mask)728 static int set_default_event_mask_except(uint64_t mask, uint64_t le_mask) {
729   if (!interface_ready()) return BT_STATUS_NOT_READY;
730   do_in_main_thread(
731       FROM_HERE,
732       base::BindOnce(btif_dm_set_default_event_mask_except, mask, le_mask));
733   return BT_STATUS_SUCCESS;
734 }
735 
restore_filter_accept_list()736 static int restore_filter_accept_list() {
737   if (!interface_ready()) return BT_STATUS_NOT_READY;
738   // TODO(b/260922031) - When restoring the filter accept list after a system
739   // suspend, we need to re-arm the LE connections that had `is_direct=False`.
740   // This should be the list of bonded devices and potentially any GATT
741   // connections that have `is_direct=False`. Currently, we only restore LE hid
742   // devices.
743   auto le_hid_addrs = btif_storage_get_le_hid_devices();
744   do_in_main_thread(FROM_HERE,
745                     base::BindOnce(btif_dm_restore_filter_accept_list,
746                                    std::move(le_hid_addrs)));
747   return BT_STATUS_SUCCESS;
748 }
749 
allow_wake_by_hid()750 static int allow_wake_by_hid() {
751   if (!interface_ready()) return BT_STATUS_NOT_READY;
752   auto le_hid_addrs = btif_storage_get_le_hid_devices();
753   auto classic_hid_addrs = btif_storage_get_wake_capable_classic_hid_devices();
754   do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_allow_wake_by_hid,
755                                               std::move(classic_hid_addrs),
756                                               std::move(le_hid_addrs)));
757   return BT_STATUS_SUCCESS;
758 }
759 
set_event_filter_connection_setup_all_devices()760 static int set_event_filter_connection_setup_all_devices() {
761   if (!interface_ready()) return BT_STATUS_NOT_READY;
762   do_in_main_thread(
763       FROM_HERE,
764       base::BindOnce(btif_dm_set_event_filter_connection_setup_all_devices));
765   return BT_STATUS_SUCCESS;
766 }
767 
dump(int fd,const char ** arguments)768 static void dump(int fd, const char** arguments) {
769   btif_debug_conn_dump(fd);
770   btif_debug_bond_event_dump(fd);
771   btif_debug_linkkey_type_dump(fd);
772   btif_debug_rc_dump(fd);
773   btif_debug_a2dp_dump(fd);
774   btif_debug_av_dump(fd);
775   bta_debug_av_dump(fd);
776   stack_debug_avdtp_api_dump(fd);
777   btif_sock_dump(fd);
778   bluetooth::avrcp::AvrcpService::DebugDump(fd);
779   btif_debug_config_dump(fd);
780   device_debug_iot_config_dump(fd);
781   BTA_HfClientDumpStatistics(fd);
782   wakelock_debug_dump(fd);
783   osi_allocator_debug_dump(fd);
784   alarm_debug_dump(fd);
785   bluetooth::csis::CsisClient::DebugDump(fd);
786 #ifndef TARGET_FLOSS
787   le_audio::has::HasClient::DebugDump(fd);
788 #endif
789   HearingAid::DebugDump(fd);
790 #ifndef TARGET_FLOSS
791   LeAudioClient::DebugDump(fd);
792   LeAudioBroadcaster::DebugDump(fd);
793   VolumeControl::DebugDump(fd);
794 #endif
795   connection_manager::dump(fd);
796   bluetooth::bqr::DebugDump(fd);
797   PAN_Dumpsys(fd);
798   DumpsysHid(fd);
799   DumpsysBtaDm(fd);
800   bluetooth::shim::Dump(fd, arguments);
801 }
802 
dumpMetrics(std::string * output)803 static void dumpMetrics(std::string* output) {
804   bluetooth::common::BluetoothMetricsLogger::GetInstance()->WriteString(output);
805 }
806 
get_remote_pbap_pce_version(const RawAddress * bd_addr)807 static int get_remote_pbap_pce_version(const RawAddress* bd_addr) {
808   // Read and restore the PCE version from local storage
809   uint16_t pce_version = 0;
810   size_t version_value_size = sizeof(pce_version);
811   if (!btif_config_get_bin(bd_addr->ToString(), BT_CONFIG_KEY_PBAP_PCE_VERSION,
812                            (uint8_t*)&pce_version, &version_value_size)) {
813     LOG_WARN("Failed to read cached peer PCE version for %s",
814              ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
815   }
816   return pce_version;
817 }
818 
pbap_pse_dynamic_version_upgrade_is_enabled()819 static bool pbap_pse_dynamic_version_upgrade_is_enabled() {
820   if (bluetooth::common::init_flags::
821           pbap_pse_dynamic_version_upgrade_is_enabled()) {
822     return true;
823   }
824   LOG_WARN("PBAP PSE dynamic version upgrade is not enabled");
825   return false;
826 }
827 
get_profile_interface(const char * profile_id)828 static const void* get_profile_interface(const char* profile_id) {
829   LOG_INFO("%s: id = %s", __func__, profile_id);
830 
831   /* sanity check */
832   if (!interface_ready()) return NULL;
833 
834   /* check for supported profile interfaces */
835   if (is_profile(profile_id, BT_PROFILE_HANDSFREE_ID))
836     return bluetooth::headset::GetInterface();
837 
838   if (is_profile(profile_id, BT_PROFILE_HANDSFREE_CLIENT_ID))
839     return btif_hf_client_get_interface();
840 
841   if (is_profile(profile_id, BT_PROFILE_SOCKETS_ID))
842     return btif_sock_get_interface();
843 
844   if (is_profile(profile_id, BT_PROFILE_PAN_ID))
845     return btif_pan_get_interface();
846 
847   if (is_profile(profile_id, BT_PROFILE_ADVANCED_AUDIO_ID))
848     return btif_av_get_src_interface();
849 
850   if (is_profile(profile_id, BT_PROFILE_ADVANCED_AUDIO_SINK_ID))
851     return btif_av_get_sink_interface();
852 
853   if (is_profile(profile_id, BT_PROFILE_HIDHOST_ID))
854     return btif_hh_get_interface();
855 
856   if (is_profile(profile_id, BT_PROFILE_HIDDEV_ID))
857     return btif_hd_get_interface();
858 
859   if (is_profile(profile_id, BT_PROFILE_SDP_CLIENT_ID))
860     return btif_sdp_get_interface();
861 
862   if (is_profile(profile_id, BT_PROFILE_GATT_ID))
863     return btif_gatt_get_interface();
864 
865   if (is_profile(profile_id, BT_PROFILE_AV_RC_ID))
866     return btif_rc_get_interface();
867 
868   if (is_profile(profile_id, BT_PROFILE_AV_RC_CTRL_ID))
869     return btif_rc_ctrl_get_interface();
870 
871   if (is_profile(profile_id, BT_PROFILE_HEARING_AID_ID))
872     return btif_hearing_aid_get_interface();
873 
874 #ifndef TARGET_FLOSS
875   if (is_profile(profile_id, BT_PROFILE_HAP_CLIENT_ID))
876     return btif_has_client_get_interface();
877 #endif
878 
879   if (is_profile(profile_id, BT_KEYSTORE_ID))
880     return bluetooth::bluetooth_keystore::getBluetoothKeystoreInterface();
881 
882   if (is_profile(profile_id, BT_ACTIVITY_ATTRIBUTION_ID)) {
883     return bluetooth::activity_attribution::get_activity_attribution_instance();
884   }
885 
886 #ifndef TARGET_FLOSS
887   if (is_profile(profile_id, BT_PROFILE_LE_AUDIO_ID))
888     return btif_le_audio_get_interface();
889 
890   if (is_profile(profile_id, BT_PROFILE_LE_AUDIO_BROADCASTER_ID))
891     return btif_le_audio_broadcaster_get_interface();
892 #endif
893 
894   if (is_profile(profile_id, BT_PROFILE_VC_ID))
895     return btif_volume_control_get_interface();
896 
897   if (is_profile(profile_id, BT_PROFILE_CSIS_CLIENT_ID))
898     return btif_csis_client_get_interface();
899 
900   bool isBqrEnabled =
901       bluetooth::common::InitFlags::IsBluetoothQualityReportCallbackEnabled();
902   if (isBqrEnabled) {
903     if (is_profile(profile_id, BT_BQR_ID))
904       return bluetooth::bqr::getBluetoothQualityReportInterface();
905   }
906 
907   return NULL;
908 }
909 
910 static bt_os_callouts_t* wakelock_os_callouts_saved = nullptr;
911 
acquire_wake_lock_cb(const char * lock_name)912 static int acquire_wake_lock_cb(const char* lock_name) {
913   return do_in_jni_thread(
914       FROM_HERE, base::Bind(base::IgnoreResult(
915                                 wakelock_os_callouts_saved->acquire_wake_lock),
916                             lock_name));
917 }
918 
release_wake_lock_cb(const char * lock_name)919 static int release_wake_lock_cb(const char* lock_name) {
920   return do_in_jni_thread(
921       FROM_HERE, base::Bind(base::IgnoreResult(
922                                 wakelock_os_callouts_saved->release_wake_lock),
923                             lock_name));
924 }
925 
926 static bt_os_callouts_t wakelock_os_callouts_jni = {
927     sizeof(wakelock_os_callouts_jni),
928     nullptr /* not used */,
929     acquire_wake_lock_cb,
930     release_wake_lock_cb,
931 };
932 
set_os_callouts(bt_os_callouts_t * callouts)933 static int set_os_callouts(bt_os_callouts_t* callouts) {
934   wakelock_os_callouts_saved = callouts;
935   wakelock_set_os_callouts(&wakelock_os_callouts_jni);
936   return BT_STATUS_SUCCESS;
937 }
938 
config_clear(void)939 static int config_clear(void) {
940   LOG_INFO("%s", __func__);
941   int ret = BT_STATUS_SUCCESS;
942   if (!btif_config_clear()) {
943     LOG_ERROR("Failed to clear btif config");
944     ret = BT_STATUS_FAIL;
945   }
946 
947   if (!device_iot_config_clear()) {
948     LOG_ERROR("Failed to clear device iot config");
949     ret = BT_STATUS_FAIL;
950   }
951 
952   return ret;
953 }
954 
get_avrcp_service(void)955 static bluetooth::avrcp::ServiceInterface* get_avrcp_service(void) {
956   return bluetooth::avrcp::AvrcpService::GetServiceInterface();
957 }
958 
obfuscate_address(const RawAddress & address)959 static std::string obfuscate_address(const RawAddress& address) {
960   return bluetooth::common::AddressObfuscator::GetInstance()->Obfuscate(
961       address);
962 }
963 
get_metric_id(const RawAddress & address)964 static int get_metric_id(const RawAddress& address) {
965   return allocate_metric_id_from_metric_id_allocator(address);
966 }
967 
set_dynamic_audio_buffer_size(int codec,int size)968 static int set_dynamic_audio_buffer_size(int codec, int size) {
969   return btif_set_dynamic_audio_buffer_size(codec, size);
970 }
971 
allow_low_latency_audio(bool allowed,const RawAddress & address)972 static bool allow_low_latency_audio(bool allowed, const RawAddress& address) {
973   LOG_INFO("%s %s", __func__, allowed ? "true" : "false");
974   bluetooth::audio::a2dp::set_audio_low_latency_mode_allowed(allowed);
975   return true;
976 }
977 
metadata_changed(const RawAddress & remote_bd_addr,int key,std::vector<uint8_t> value)978 static void metadata_changed(const RawAddress& remote_bd_addr, int key,
979                              std::vector<uint8_t> value) {
980   if (!interface_ready()) {
981     LOG_ERROR("Interface not ready!");
982     return;
983   }
984 
985   do_in_main_thread(
986       FROM_HERE, base::BindOnce(btif_dm_metadata_changed, remote_bd_addr, key,
987                                 std::move(value)));
988 }
989 
interop_match_addr(const char * feature_name,const RawAddress * addr)990 static bool interop_match_addr(const char* feature_name,
991                                const RawAddress* addr) {
992   if (feature_name == NULL || addr == NULL) {
993     return false;
994   }
995 
996   int feature = interop_feature_name_to_feature_id(feature_name);
997   if (feature == -1) {
998     BTIF_TRACE_ERROR("%s: feature doesn't exist: %s", __func__, feature_name);
999     return false;
1000   }
1001 
1002   return interop_match_addr((interop_feature_t)feature, addr);
1003 }
1004 
interop_match_name(const char * feature_name,const char * name)1005 static bool interop_match_name(const char* feature_name, const char* name) {
1006   if (feature_name == NULL || name == NULL) {
1007     return false;
1008   }
1009 
1010   int feature = interop_feature_name_to_feature_id(feature_name);
1011   if (feature == -1) {
1012     BTIF_TRACE_ERROR("%s: feature doesn't exist: %s", __func__, feature_name);
1013     return false;
1014   }
1015 
1016   return interop_match_name((interop_feature_t)feature, name);
1017 }
1018 
interop_match_addr_or_name(const char * feature_name,const RawAddress * addr)1019 static bool interop_match_addr_or_name(const char* feature_name,
1020                                        const RawAddress* addr) {
1021   if (feature_name == NULL || addr == NULL) {
1022     return false;
1023   }
1024 
1025   int feature = interop_feature_name_to_feature_id(feature_name);
1026   if (feature == -1) {
1027     BTIF_TRACE_ERROR("%s: feature doesn't exist: %s", __func__, feature_name);
1028     return false;
1029   }
1030 
1031   return interop_match_addr_or_name((interop_feature_t)feature, addr,
1032                                     &btif_storage_get_remote_device_property);
1033 }
1034 
interop_database_add_remove_addr(bool do_add,const char * feature_name,const RawAddress * addr,int length)1035 static void interop_database_add_remove_addr(bool do_add,
1036                                              const char* feature_name,
1037                                              const RawAddress* addr,
1038                                              int length) {
1039   if (feature_name == NULL || addr == NULL) {
1040     return;
1041   }
1042 
1043   int feature = interop_feature_name_to_feature_id(feature_name);
1044   if (feature == -1) {
1045     BTIF_TRACE_ERROR("%s: feature doesn't exist: %s", __func__, feature_name);
1046     return;
1047   }
1048 
1049   if (do_add) {
1050     interop_database_add_addr((interop_feature_t)feature, addr, (size_t)length);
1051   } else {
1052     interop_database_remove_addr((interop_feature_t)feature, addr);
1053   }
1054 }
1055 
interop_database_add_remove_name(bool do_add,const char * feature_name,const char * name)1056 static void interop_database_add_remove_name(bool do_add,
1057                                              const char* feature_name,
1058                                              const char* name) {
1059   if (feature_name == NULL || name == NULL) {
1060     return;
1061   }
1062 
1063   int feature = interop_feature_name_to_feature_id(feature_name);
1064   if (feature == -1) {
1065     BTIF_TRACE_ERROR("%s: feature doesn't exist: %s", __func__, feature_name);
1066     return;
1067   }
1068 
1069   if (do_add) {
1070     interop_database_add_name((interop_feature_t)feature, name);
1071   } else {
1072     interop_database_remove_name((interop_feature_t)feature, name);
1073   }
1074 }
1075 
1076 EXPORT_SYMBOL bt_interface_t bluetoothInterface = {
1077     sizeof(bluetoothInterface),
1078     .init = init,
1079     .enable = enable,
1080     .disable = disable,
1081     .cleanup = cleanup,
1082     .get_adapter_properties = get_adapter_properties,
1083     .get_adapter_property = get_adapter_property,
1084     .set_adapter_property = set_adapter_property,
1085     .get_remote_device_properties = get_remote_device_properties,
1086     .get_remote_device_property = get_remote_device_property,
1087     .set_remote_device_property = set_remote_device_property,
1088     .get_remote_service_record = nullptr,
1089     .get_remote_services = get_remote_services,
1090     .start_discovery = start_discovery,
1091     .cancel_discovery = cancel_discovery,
1092     .create_bond = create_bond,
1093     .create_bond_le = create_bond_le,
1094     .create_bond_out_of_band = create_bond_out_of_band,
1095     .remove_bond = remove_bond,
1096     .cancel_bond = cancel_bond,
1097     .get_connection_state = get_connection_state,
1098     .pin_reply = pin_reply,
1099     .ssp_reply = ssp_reply,
1100     .get_profile_interface = get_profile_interface,
1101     .set_os_callouts = set_os_callouts,
1102     .read_energy_info = read_energy_info,
1103     .dump = dump,
1104     .dumpMetrics = dumpMetrics,
1105     .config_clear = config_clear,
1106     .interop_database_clear = interop_database_clear,
1107     .interop_database_add = interop_database_add,
1108     .get_avrcp_service = get_avrcp_service,
1109     .obfuscate_address = obfuscate_address,
1110     .get_metric_id = get_metric_id,
1111     .set_dynamic_audio_buffer_size = set_dynamic_audio_buffer_size,
1112     .generate_local_oob_data = generate_local_oob_data,
1113     .allow_low_latency_audio = allow_low_latency_audio,
1114     .clear_event_filter = clear_event_filter,
1115     .clear_event_mask = clear_event_mask,
1116     .clear_filter_accept_list = clear_filter_accept_list,
1117     .disconnect_all_acls = disconnect_all_acls,
1118     .le_rand = le_rand,
1119     .set_event_filter_inquiry_result_all_devices =
1120         set_event_filter_inquiry_result_all_devices,
1121     .set_default_event_mask_except = set_default_event_mask_except,
1122     .restore_filter_accept_list = restore_filter_accept_list,
1123     .allow_wake_by_hid = allow_wake_by_hid,
1124     .set_event_filter_connection_setup_all_devices =
1125         set_event_filter_connection_setup_all_devices,
1126     .get_wbs_supported = get_wbs_supported,
1127     .get_swb_supported = get_swb_supported,
1128     .metadata_changed = metadata_changed,
1129     .interop_match_addr = interop_match_addr,
1130     .interop_match_name = interop_match_name,
1131     .interop_match_addr_or_name = interop_match_addr_or_name,
1132     .interop_database_add_remove_addr = interop_database_add_remove_addr,
1133     .interop_database_add_remove_name = interop_database_add_remove_name,
1134     .get_remote_pbap_pce_version = get_remote_pbap_pce_version,
1135     .pbap_pse_dynamic_version_upgrade_is_enabled =
1136         pbap_pse_dynamic_version_upgrade_is_enabled,
1137 };
1138 
1139 // callback reporting helpers
1140 
property_deep_copy_array(int num_properties,bt_property_t * properties)1141 bt_property_t* property_deep_copy_array(int num_properties,
1142                                         bt_property_t* properties) {
1143   bt_property_t* copy = nullptr;
1144   if (num_properties > 0) {
1145     size_t content_len = 0;
1146     for (int i = 0; i < num_properties; i++) {
1147       auto len = properties[i].len;
1148       if (len > 0) {
1149         content_len += len;
1150       }
1151     }
1152 
1153     copy = (bt_property_t*)osi_calloc((sizeof(bt_property_t) * num_properties) +
1154                                       content_len);
1155     ASSERT(copy != nullptr);
1156     uint8_t* content = (uint8_t*)(copy + num_properties);
1157 
1158     for (int i = 0; i < num_properties; i++) {
1159       auto len = properties[i].len;
1160       copy[i].type = properties[i].type;
1161       copy[i].len = len;
1162       if (len <= 0) {
1163         continue;
1164       }
1165       copy[i].val = content;
1166       memcpy(content, properties[i].val, len);
1167       content += len;
1168     }
1169   }
1170   return copy;
1171 }
1172 
invoke_adapter_state_changed_cb(bt_state_t state)1173 void invoke_adapter_state_changed_cb(bt_state_t state) {
1174   do_in_jni_thread(FROM_HERE, base::BindOnce(
1175                                   [](bt_state_t state) {
1176                                     HAL_CBACK(bt_hal_cbacks,
1177                                               adapter_state_changed_cb, state);
1178                                   },
1179                                   state));
1180 }
1181 
invoke_adapter_properties_cb(bt_status_t status,int num_properties,bt_property_t * properties)1182 void invoke_adapter_properties_cb(bt_status_t status, int num_properties,
1183                                   bt_property_t* properties) {
1184   do_in_jni_thread(FROM_HERE,
1185                    base::BindOnce(
1186                        [](bt_status_t status, int num_properties,
1187                           bt_property_t* properties) {
1188                          HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, status,
1189                                    num_properties, properties);
1190                          if (properties) {
1191                            osi_free(properties);
1192                          }
1193                        },
1194                        status, num_properties,
1195                        property_deep_copy_array(num_properties, properties)));
1196 }
1197 
invoke_remote_device_properties_cb(bt_status_t status,RawAddress bd_addr,int num_properties,bt_property_t * properties)1198 void invoke_remote_device_properties_cb(bt_status_t status, RawAddress bd_addr,
1199                                         int num_properties,
1200                                         bt_property_t* properties) {
1201   do_in_jni_thread(
1202       FROM_HERE, base::BindOnce(
1203                      [](bt_status_t status, RawAddress bd_addr,
1204                         int num_properties, bt_property_t* properties) {
1205                        HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
1206                                  status, &bd_addr, num_properties, properties);
1207                        if (properties) {
1208                          osi_free(properties);
1209                        }
1210                      },
1211                      status, bd_addr, num_properties,
1212                      property_deep_copy_array(num_properties, properties)));
1213 }
1214 
invoke_device_found_cb(int num_properties,bt_property_t * properties)1215 void invoke_device_found_cb(int num_properties, bt_property_t* properties) {
1216   do_in_jni_thread(FROM_HERE,
1217                    base::BindOnce(
1218                        [](int num_properties, bt_property_t* properties) {
1219                          HAL_CBACK(bt_hal_cbacks, device_found_cb,
1220                                    num_properties, properties);
1221                          if (properties) {
1222                            osi_free(properties);
1223                          }
1224                        },
1225                        num_properties,
1226                        property_deep_copy_array(num_properties, properties)));
1227 }
1228 
invoke_discovery_state_changed_cb(bt_discovery_state_t state)1229 void invoke_discovery_state_changed_cb(bt_discovery_state_t state) {
1230   do_in_jni_thread(FROM_HERE, base::BindOnce(
1231                                   [](bt_discovery_state_t state) {
1232                                     HAL_CBACK(bt_hal_cbacks,
1233                                               discovery_state_changed_cb,
1234                                               state);
1235                                   },
1236                                   state));
1237 }
1238 
invoke_pin_request_cb(RawAddress bd_addr,bt_bdname_t bd_name,uint32_t cod,bool min_16_digit)1239 void invoke_pin_request_cb(RawAddress bd_addr, bt_bdname_t bd_name,
1240                            uint32_t cod, bool min_16_digit) {
1241   do_in_jni_thread(FROM_HERE, base::BindOnce(
1242                                   [](RawAddress bd_addr, bt_bdname_t bd_name,
1243                                      uint32_t cod, bool min_16_digit) {
1244                                     HAL_CBACK(bt_hal_cbacks, pin_request_cb,
1245                                               &bd_addr, &bd_name, cod,
1246                                               min_16_digit);
1247                                   },
1248                                   bd_addr, bd_name, cod, min_16_digit));
1249 }
1250 
invoke_ssp_request_cb(RawAddress bd_addr,bt_bdname_t bd_name,uint32_t cod,bt_ssp_variant_t pairing_variant,uint32_t pass_key)1251 void invoke_ssp_request_cb(RawAddress bd_addr, bt_bdname_t bd_name,
1252                            uint32_t cod, bt_ssp_variant_t pairing_variant,
1253                            uint32_t pass_key) {
1254   do_in_jni_thread(FROM_HERE,
1255                    base::BindOnce(
1256                        [](RawAddress bd_addr, bt_bdname_t bd_name, uint32_t cod,
1257                           bt_ssp_variant_t pairing_variant, uint32_t pass_key) {
1258                          HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr,
1259                                    &bd_name, cod, pairing_variant, pass_key);
1260                        },
1261                        bd_addr, bd_name, cod, pairing_variant, pass_key));
1262 }
1263 
invoke_oob_data_request_cb(tBT_TRANSPORT t,bool valid,Octet16 c,Octet16 r,RawAddress raw_address,uint8_t address_type)1264 void invoke_oob_data_request_cb(tBT_TRANSPORT t, bool valid, Octet16 c,
1265                                 Octet16 r, RawAddress raw_address,
1266                                 uint8_t address_type) {
1267   LOG_INFO("%s", __func__);
1268   bt_oob_data_t oob_data = {};
1269   const char* local_name;
1270   BTM_ReadLocalDeviceName(&local_name);
1271   for (int i = 0; i < BTM_MAX_LOC_BD_NAME_LEN; i++) {
1272     oob_data.device_name[i] = local_name[i];
1273   }
1274 
1275   // Set the local address
1276   int j = 5;
1277   for (int i = 0; i < 6; i++) {
1278     oob_data.address[i] = raw_address.address[j];
1279     j--;
1280   }
1281   oob_data.address[6] = address_type;
1282 
1283   // Each value (for C and R) is 16 octets in length
1284   bool c_empty = true;
1285   for (int i = 0; i < 16; i++) {
1286     // C cannot be all 0s, if so then we want to fail
1287     if (c[i] != 0) c_empty = false;
1288     oob_data.c[i] = c[i];
1289     // R is optional and may be empty
1290     oob_data.r[i] = r[i];
1291   }
1292   oob_data.is_valid = valid && !c_empty;
1293   // The oob_data_length is 2 octects in length.  The value includes the length
1294   // of itself. 16 + 16 + 2 = 34 Data 0x0022 Little Endian order 0x2200
1295   oob_data.oob_data_length[0] = 0;
1296   oob_data.oob_data_length[1] = 34;
1297   bt_status_t status = do_in_jni_thread(
1298       FROM_HERE, base::BindOnce(
1299                      [](tBT_TRANSPORT t, bt_oob_data_t oob_data) {
1300                        HAL_CBACK(bt_hal_cbacks, generate_local_oob_data_cb, t,
1301                                  oob_data);
1302                      },
1303                      t, oob_data));
1304   if (status != BT_STATUS_SUCCESS) {
1305     LOG_ERROR("%s: Failed to call callback!", __func__);
1306   }
1307 }
1308 
invoke_bond_state_changed_cb(bt_status_t status,RawAddress bd_addr,bt_bond_state_t state,int fail_reason)1309 void invoke_bond_state_changed_cb(bt_status_t status, RawAddress bd_addr,
1310                                   bt_bond_state_t state, int fail_reason) {
1311   do_in_jni_thread(FROM_HERE, base::BindOnce(
1312                                   [](bt_status_t status, RawAddress bd_addr,
1313                                      bt_bond_state_t state, int fail_reason) {
1314                                     HAL_CBACK(bt_hal_cbacks,
1315                                               bond_state_changed_cb, status,
1316                                               &bd_addr, state, fail_reason);
1317                                   },
1318                                   status, bd_addr, state, fail_reason));
1319 }
1320 
invoke_address_consolidate_cb(RawAddress main_bd_addr,RawAddress secondary_bd_addr)1321 void invoke_address_consolidate_cb(RawAddress main_bd_addr,
1322                                    RawAddress secondary_bd_addr) {
1323   do_in_jni_thread(
1324       FROM_HERE, base::BindOnce(
1325                      [](RawAddress main_bd_addr, RawAddress secondary_bd_addr) {
1326                        HAL_CBACK(bt_hal_cbacks, address_consolidate_cb,
1327                                  &main_bd_addr, &secondary_bd_addr);
1328                      },
1329                      main_bd_addr, secondary_bd_addr));
1330 }
1331 
invoke_le_address_associate_cb(RawAddress main_bd_addr,RawAddress secondary_bd_addr)1332 void invoke_le_address_associate_cb(RawAddress main_bd_addr,
1333                                     RawAddress secondary_bd_addr) {
1334   do_in_jni_thread(
1335       FROM_HERE, base::BindOnce(
1336                      [](RawAddress main_bd_addr, RawAddress secondary_bd_addr) {
1337                        HAL_CBACK(bt_hal_cbacks, le_address_associate_cb,
1338                                  &main_bd_addr, &secondary_bd_addr);
1339                      },
1340                      main_bd_addr, secondary_bd_addr));
1341 }
invoke_acl_state_changed_cb(bt_status_t status,RawAddress bd_addr,bt_acl_state_t state,int transport_link_type,bt_hci_error_code_t hci_reason,bt_conn_direction_t direction,uint16_t acl_handle)1342 void invoke_acl_state_changed_cb(bt_status_t status, RawAddress bd_addr,
1343                                  bt_acl_state_t state, int transport_link_type,
1344                                  bt_hci_error_code_t hci_reason,
1345                                  bt_conn_direction_t direction,
1346                                  uint16_t acl_handle) {
1347   do_in_jni_thread(
1348       FROM_HERE,
1349       base::BindOnce(
1350           [](bt_status_t status, RawAddress bd_addr, bt_acl_state_t state,
1351              int transport_link_type, bt_hci_error_code_t hci_reason,
1352              bt_conn_direction_t direction, uint16_t acl_handle) {
1353             HAL_CBACK(bt_hal_cbacks, acl_state_changed_cb, status, &bd_addr,
1354                       state, transport_link_type, hci_reason, direction,
1355                       acl_handle);
1356           },
1357           status, bd_addr, state, transport_link_type, hci_reason, direction,
1358           acl_handle));
1359 }
1360 
invoke_thread_evt_cb(bt_cb_thread_evt event)1361 void invoke_thread_evt_cb(bt_cb_thread_evt event) {
1362   do_in_jni_thread(FROM_HERE, base::BindOnce(
1363                                   [](bt_cb_thread_evt event) {
1364                                     HAL_CBACK(bt_hal_cbacks, thread_evt_cb,
1365                                               event);
1366                                     if (event == DISASSOCIATE_JVM) {
1367                                       bt_hal_cbacks = NULL;
1368                                     }
1369                                   },
1370                                   event));
1371 }
1372 
1373 // takes ownership of |uid_data|
invoke_energy_info_cb(bt_activity_energy_info energy_info,bt_uid_traffic_t * uid_data)1374 void invoke_energy_info_cb(bt_activity_energy_info energy_info,
1375                            bt_uid_traffic_t* uid_data) {
1376   do_in_jni_thread(
1377       FROM_HERE,
1378       base::BindOnce(
1379           [](bt_activity_energy_info energy_info, bt_uid_traffic_t* uid_data) {
1380             HAL_CBACK(bt_hal_cbacks, energy_info_cb, &energy_info, uid_data);
1381             osi_free(uid_data);
1382           },
1383           energy_info, uid_data));
1384 }
1385 
invoke_link_quality_report_cb(uint64_t timestamp,int report_id,int rssi,int snr,int retransmission_count,int packets_not_receive_count,int negative_acknowledgement_count)1386 void invoke_link_quality_report_cb(uint64_t timestamp, int report_id, int rssi,
1387                                    int snr, int retransmission_count,
1388                                    int packets_not_receive_count,
1389                                    int negative_acknowledgement_count) {
1390   do_in_jni_thread(
1391       FROM_HERE,
1392       base::BindOnce(
1393           [](uint64_t timestamp, int report_id, int rssi, int snr,
1394              int retransmission_count, int packets_not_receive_count,
1395              int negative_acknowledgement_count) {
1396             HAL_CBACK(bt_hal_cbacks, link_quality_report_cb, timestamp,
1397                       report_id, rssi, snr, retransmission_count,
1398                       packets_not_receive_count,
1399                       negative_acknowledgement_count);
1400           },
1401           timestamp, report_id, rssi, snr, retransmission_count,
1402           packets_not_receive_count, negative_acknowledgement_count));
1403 }
1404 
invoke_switch_buffer_size_cb(bool is_low_latency_buffer_size)1405 void invoke_switch_buffer_size_cb(bool is_low_latency_buffer_size) {
1406   do_in_jni_thread(FROM_HERE, base::BindOnce(
1407                                   [](bool is_low_latency_buffer_size) {
1408                                     HAL_CBACK(bt_hal_cbacks,
1409                                               switch_buffer_size_cb,
1410                                               is_low_latency_buffer_size);
1411                                   },
1412                                   is_low_latency_buffer_size));
1413 }
1414 
invoke_switch_codec_cb(bool is_low_latency_buffer_size)1415 void invoke_switch_codec_cb(bool is_low_latency_buffer_size) {
1416   do_in_jni_thread(FROM_HERE, base::BindOnce(
1417                                   [](bool is_low_latency_buffer_size) {
1418                                     HAL_CBACK(bt_hal_cbacks, switch_codec_cb,
1419                                               is_low_latency_buffer_size);
1420                                   },
1421                                   is_low_latency_buffer_size));
1422 }
1423