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