1 // 2 // Copyright 2016 The Android Open Source Project 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 // 16 17 #include "vendor_interface.h" 18 19 #include <assert.h> 20 21 #define LOG_TAG "android.hardware.bluetooth (at) 1.0-impl" 22 #include <android-base/logging.h> 23 #include <cutils/properties.h> 24 #include <utils/Log.h> 25 26 #include <dlfcn.h> 27 #include <fcntl.h> 28 29 #include "bluetooth_address.h" 30 #include "h4_protocol.h" 31 #include "mct_protocol.h" 32 33 static const char* VENDOR_LIBRARY_NAME = "libbt-vendor.so"; 34 static const char* VENDOR_LIBRARY_SYMBOL_NAME = 35 "BLUETOOTH_VENDOR_LIB_INTERFACE"; 36 37 static const int INVALID_FD = -1; 38 39 namespace { 40 41 using android::hardware::bluetooth::V1_0::implementation::VendorInterface; 42 using android::hardware::hidl_vec; 43 44 struct { 45 tINT_CMD_CBACK cb; 46 uint16_t opcode; 47 } internal_command; 48 49 // True when LPM is not enabled yet or wake is not asserted. 50 bool lpm_wake_deasserted; 51 uint32_t lpm_timeout_ms; 52 bool recent_activity_flag; 53 54 VendorInterface* g_vendor_interface = nullptr; 55 56 HC_BT_HDR* WrapPacketAndCopy(uint16_t event, const hidl_vec<uint8_t>& data) { 57 size_t packet_size = data.size() + sizeof(HC_BT_HDR); 58 HC_BT_HDR* packet = reinterpret_cast<HC_BT_HDR*>(new uint8_t[packet_size]); 59 packet->offset = 0; 60 packet->len = data.size(); 61 packet->layer_specific = 0; 62 packet->event = event; 63 // TODO(eisenbach): Avoid copy here; if BT_HDR->data can be ensured to 64 // be the only way the data is accessed, a pointer could be passed here... 65 memcpy(packet->data, data.data(), data.size()); 66 return packet; 67 } 68 69 bool internal_command_event_match(const hidl_vec<uint8_t>& packet) { 70 uint8_t event_code = packet[0]; 71 if (event_code != HCI_COMMAND_COMPLETE_EVENT) { 72 ALOGE("%s: Unhandled event type %02X", __func__, event_code); 73 return false; 74 } 75 76 size_t opcode_offset = HCI_EVENT_PREAMBLE_SIZE + 1; // Skip num packets. 77 78 uint16_t opcode = packet[opcode_offset] | (packet[opcode_offset + 1] << 8); 79 80 ALOGV("%s internal_command.opcode = %04X opcode = %04x", __func__, 81 internal_command.opcode, opcode); 82 return opcode == internal_command.opcode; 83 } 84 85 uint8_t transmit_cb(uint16_t opcode, void* buffer, tINT_CMD_CBACK callback) { 86 ALOGV("%s opcode: 0x%04x, ptr: %p, cb: %p", __func__, opcode, buffer, 87 callback); 88 internal_command.cb = callback; 89 internal_command.opcode = opcode; 90 uint8_t type = HCI_PACKET_TYPE_COMMAND; 91 HC_BT_HDR* bt_hdr = reinterpret_cast<HC_BT_HDR*>(buffer); 92 VendorInterface::get()->Send(type, bt_hdr->data, bt_hdr->len); 93 delete[] reinterpret_cast<uint8_t*>(buffer); 94 return true; 95 } 96 97 void firmware_config_cb(bt_vendor_op_result_t result) { 98 ALOGV("%s result: %d", __func__, result); 99 VendorInterface::get()->OnFirmwareConfigured(result); 100 } 101 102 void sco_config_cb(bt_vendor_op_result_t result) { 103 ALOGD("%s result: %d", __func__, result); 104 } 105 106 void low_power_mode_cb(bt_vendor_op_result_t result) { 107 ALOGD("%s result: %d", __func__, result); 108 } 109 110 void sco_audiostate_cb(bt_vendor_op_result_t result) { 111 ALOGD("%s result: %d", __func__, result); 112 } 113 114 void* buffer_alloc_cb(int size) { 115 void* p = new uint8_t[size]; 116 ALOGV("%s pts: %p, size: %d", __func__, p, size); 117 return p; 118 } 119 120 void buffer_free_cb(void* buffer) { 121 ALOGV("%s ptr: %p", __func__, buffer); 122 delete[] reinterpret_cast<uint8_t*>(buffer); 123 } 124 125 void epilog_cb(bt_vendor_op_result_t result) { 126 ALOGD("%s result: %d", __func__, result); 127 } 128 129 void a2dp_offload_cb(bt_vendor_op_result_t result, bt_vendor_opcode_t op, 130 uint8_t av_handle) { 131 ALOGD("%s result: %d, op: %d, handle: %d", __func__, result, op, av_handle); 132 } 133 134 const bt_vendor_callbacks_t lib_callbacks = { 135 sizeof(lib_callbacks), firmware_config_cb, sco_config_cb, 136 low_power_mode_cb, sco_audiostate_cb, buffer_alloc_cb, 137 buffer_free_cb, transmit_cb, epilog_cb, 138 a2dp_offload_cb}; 139 140 } // namespace 141 142 namespace android { 143 namespace hardware { 144 namespace bluetooth { 145 namespace V1_0 { 146 namespace implementation { 147 148 class FirmwareStartupTimer { 149 public: 150 FirmwareStartupTimer() : start_time_(std::chrono::steady_clock::now()) {} 151 152 ~FirmwareStartupTimer() { 153 std::chrono::duration<double> duration = 154 std::chrono::steady_clock::now() - start_time_; 155 double s = duration.count(); 156 if (s == 0) return; 157 ALOGI("Firmware configured in %.3fs", s); 158 } 159 160 private: 161 std::chrono::steady_clock::time_point start_time_; 162 }; 163 164 bool VendorInterface::Initialize( 165 InitializeCompleteCallback initialize_complete_cb, 166 PacketReadCallback event_cb, PacketReadCallback acl_cb, 167 PacketReadCallback sco_cb) { 168 assert(!g_vendor_interface); 169 g_vendor_interface = new VendorInterface(); 170 return g_vendor_interface->Open(initialize_complete_cb, event_cb, acl_cb, 171 sco_cb); 172 } 173 174 void VendorInterface::Shutdown() { 175 CHECK(g_vendor_interface); 176 g_vendor_interface->Close(); 177 delete g_vendor_interface; 178 g_vendor_interface = nullptr; 179 } 180 181 VendorInterface* VendorInterface::get() { return g_vendor_interface; } 182 183 bool VendorInterface::Open(InitializeCompleteCallback initialize_complete_cb, 184 PacketReadCallback event_cb, 185 PacketReadCallback acl_cb, 186 PacketReadCallback sco_cb) { 187 initialize_complete_cb_ = initialize_complete_cb; 188 189 // Initialize vendor interface 190 191 lib_handle_ = dlopen(VENDOR_LIBRARY_NAME, RTLD_NOW); 192 if (!lib_handle_) { 193 ALOGE("%s unable to open %s (%s)", __func__, VENDOR_LIBRARY_NAME, 194 dlerror()); 195 return false; 196 } 197 198 lib_interface_ = reinterpret_cast<bt_vendor_interface_t*>( 199 dlsym(lib_handle_, VENDOR_LIBRARY_SYMBOL_NAME)); 200 if (!lib_interface_) { 201 ALOGE("%s unable to find symbol %s in %s (%s)", __func__, 202 VENDOR_LIBRARY_SYMBOL_NAME, VENDOR_LIBRARY_NAME, dlerror()); 203 return false; 204 } 205 206 // Get the local BD address 207 208 uint8_t local_bda[BluetoothAddress::kBytes]; 209 CHECK(BluetoothAddress::get_local_address(local_bda)); 210 int status = lib_interface_->init(&lib_callbacks, (unsigned char*)local_bda); 211 if (status) { 212 ALOGE("%s unable to initialize vendor library: %d", __func__, status); 213 return false; 214 } 215 216 ALOGD("%s vendor library loaded", __func__); 217 218 // Power on the controller 219 220 int power_state = BT_VND_PWR_ON; 221 lib_interface_->op(BT_VND_OP_POWER_CTRL, &power_state); 222 223 // Get the UART socket(s) 224 225 int fd_list[CH_MAX] = {0}; 226 int fd_count = lib_interface_->op(BT_VND_OP_USERIAL_OPEN, &fd_list); 227 228 for (int i = 0; i < fd_count; i++) { 229 if (fd_list[i] == INVALID_FD) { 230 ALOGE("%s: fd %d is invalid!", __func__, fd_list[i]); 231 return false; 232 } 233 } 234 235 event_cb_ = event_cb; 236 PacketReadCallback intercept_events = [this](const hidl_vec<uint8_t>& event) { 237 HandleIncomingEvent(event); 238 }; 239 240 if (fd_count == 1) { 241 hci::H4Protocol* h4_hci = 242 new hci::H4Protocol(fd_list[0], intercept_events, acl_cb, sco_cb); 243 fd_watcher_.WatchFdForNonBlockingReads( 244 fd_list[0], [h4_hci](int fd) { h4_hci->OnDataReady(fd); }); 245 hci_ = h4_hci; 246 } else { 247 hci::MctProtocol* mct_hci = 248 new hci::MctProtocol(fd_list, intercept_events, acl_cb); 249 fd_watcher_.WatchFdForNonBlockingReads( 250 fd_list[CH_EVT], [mct_hci](int fd) { mct_hci->OnEventDataReady(fd); }); 251 fd_watcher_.WatchFdForNonBlockingReads( 252 fd_list[CH_ACL_IN], 253 [mct_hci](int fd) { mct_hci->OnAclDataReady(fd); }); 254 hci_ = mct_hci; 255 } 256 257 // Initially, the power management is off. 258 lpm_wake_deasserted = true; 259 260 // Start configuring the firmware 261 firmware_startup_timer_ = new FirmwareStartupTimer(); 262 lib_interface_->op(BT_VND_OP_FW_CFG, nullptr); 263 264 return true; 265 } 266 267 void VendorInterface::Close() { 268 // These callbacks may send HCI events (vendor-dependent), so make sure to 269 // StopWatching the file descriptor after this. 270 if (lib_interface_ != nullptr) { 271 bt_vendor_lpm_mode_t mode = BT_VND_LPM_DISABLE; 272 lib_interface_->op(BT_VND_OP_LPM_SET_MODE, &mode); 273 } 274 275 fd_watcher_.StopWatchingFileDescriptors(); 276 277 if (hci_ != nullptr) { 278 delete hci_; 279 hci_ = nullptr; 280 } 281 282 if (lib_interface_ != nullptr) { 283 lib_interface_->op(BT_VND_OP_USERIAL_CLOSE, nullptr); 284 285 int power_state = BT_VND_PWR_OFF; 286 lib_interface_->op(BT_VND_OP_POWER_CTRL, &power_state); 287 288 lib_interface_->cleanup(); 289 } 290 291 if (lib_handle_ != nullptr) { 292 dlclose(lib_handle_); 293 lib_handle_ = nullptr; 294 } 295 296 if (firmware_startup_timer_ != nullptr) { 297 delete firmware_startup_timer_; 298 firmware_startup_timer_ = nullptr; 299 } 300 } 301 302 size_t VendorInterface::Send(uint8_t type, const uint8_t* data, size_t length) { 303 recent_activity_flag = true; 304 305 if (lpm_wake_deasserted == true) { 306 // Restart the timer. 307 fd_watcher_.ConfigureTimeout(std::chrono::milliseconds(lpm_timeout_ms), 308 [this]() { OnTimeout(); }); 309 // Assert wake. 310 lpm_wake_deasserted = false; 311 bt_vendor_lpm_wake_state_t wakeState = BT_VND_LPM_WAKE_ASSERT; 312 lib_interface_->op(BT_VND_OP_LPM_WAKE_SET_STATE, &wakeState); 313 ALOGV("%s: Sent wake before (%02x)", __func__, data[0] | (data[1] << 8)); 314 } 315 316 return hci_->Send(type, data, length); 317 } 318 319 void VendorInterface::OnFirmwareConfigured(uint8_t result) { 320 ALOGD("%s result: %d", __func__, result); 321 322 if (firmware_startup_timer_ != nullptr) { 323 delete firmware_startup_timer_; 324 firmware_startup_timer_ = nullptr; 325 } 326 327 if (initialize_complete_cb_ != nullptr) { 328 initialize_complete_cb_(result == 0); 329 initialize_complete_cb_ = nullptr; 330 } 331 332 lib_interface_->op(BT_VND_OP_GET_LPM_IDLE_TIMEOUT, &lpm_timeout_ms); 333 ALOGI("%s: lpm_timeout_ms %d", __func__, lpm_timeout_ms); 334 335 bt_vendor_lpm_mode_t mode = BT_VND_LPM_ENABLE; 336 lib_interface_->op(BT_VND_OP_LPM_SET_MODE, &mode); 337 338 ALOGD("%s Calling StartLowPowerWatchdog()", __func__); 339 fd_watcher_.ConfigureTimeout(std::chrono::milliseconds(lpm_timeout_ms), 340 [this]() { OnTimeout(); }); 341 } 342 343 void VendorInterface::OnTimeout() { 344 ALOGV("%s", __func__); 345 if (recent_activity_flag == false) { 346 lpm_wake_deasserted = true; 347 bt_vendor_lpm_wake_state_t wakeState = BT_VND_LPM_WAKE_DEASSERT; 348 lib_interface_->op(BT_VND_OP_LPM_WAKE_SET_STATE, &wakeState); 349 fd_watcher_.ConfigureTimeout(std::chrono::seconds(0), []() { 350 ALOGE("Zero timeout! Should never happen."); 351 }); 352 } 353 recent_activity_flag = false; 354 } 355 356 void VendorInterface::HandleIncomingEvent(const hidl_vec<uint8_t>& hci_packet) { 357 if (internal_command.cb != nullptr && 358 internal_command_event_match(hci_packet)) { 359 HC_BT_HDR* bt_hdr = WrapPacketAndCopy(HCI_PACKET_TYPE_EVENT, hci_packet); 360 361 // The callbacks can send new commands, so don't zero after calling. 362 tINT_CMD_CBACK saved_cb = internal_command.cb; 363 internal_command.cb = nullptr; 364 saved_cb(bt_hdr); 365 } else { 366 event_cb_(hci_packet); 367 } 368 } 369 370 } // namespace implementation 371 } // namespace V1_0 372 } // namespace bluetooth 373 } // namespace hardware 374 } // namespace android 375