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