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