1 /*
2 * Copyright 2019 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 <aidl/android/hardware/bluetooth/BnBluetoothHci.h>
18 #include <aidl/android/hardware/bluetooth/BnBluetoothHciCallbacks.h>
19 #include <aidl/android/hardware/bluetooth/IBluetoothHci.h>
20 #include <android/binder_ibinder.h>
21 #include <android/binder_manager.h>
22 #include <android/binder_process.h>
23 #include <android/hardware/bluetooth/1.0/types.h>
24 #include <android/hardware/bluetooth/1.1/IBluetoothHci.h>
25 #include <android/hardware/bluetooth/1.1/IBluetoothHciCallbacks.h>
26 #include <stdlib.h>
27
28 // AIDL uses syslog.h, so these defines conflict with os/log.h
29 #undef LOG_DEBUG
30 #undef LOG_INFO
31 #undef LOG_WARNING
32
33 #include <future>
34 #include <mutex>
35 #include <vector>
36
37 #include "btaa/activity_attribution.h"
38 #include "common/init_flags.h"
39 #include "common/stop_watch.h"
40 #include "common/strings.h"
41 #include "hal/hci_hal.h"
42 #include "hal/snoop_logger.h"
43 #include "os/alarm.h"
44 #include "os/log.h"
45 #include "os/system_properties.h"
46
47 using ::android::hardware::hidl_vec;
48 using ::android::hardware::Return;
49 using ::android::hardware::Void;
50 using IBluetoothHci_1_1 = ::android::hardware::bluetooth::V1_1::IBluetoothHci;
51 using IBluetoothHciCallbacks_1_1 = ::android::hardware::bluetooth::V1_1::IBluetoothHciCallbacks;
52 using HidlStatus = ::android::hardware::bluetooth::V1_0::Status;
53 using aidl::android::hardware::bluetooth::IBluetoothHci;
54 using AidlStatus = ::aidl::android::hardware::bluetooth::Status;
55 using IBluetoothHci_1_0 = ::android::hardware::bluetooth::V1_0::IBluetoothHci;
56 using bluetooth::common::BindOnce;
57
58 namespace bluetooth {
59 namespace hal {
60 namespace {
61
62 class HciDeathRecipient : public ::android::hardware::hidl_death_recipient {
63 public:
serviceDied(uint64_t,const android::wp<::android::hidl::base::V1_0::IBase> &)64 virtual void serviceDied(uint64_t /*cookie*/, const android::wp<::android::hidl::base::V1_0::IBase>& /*who*/) {
65 LOG_ERROR("Bluetooth HAL service died. Calling exit(0);");
66 common::StopWatch::DumpStopWatchLog();
67 exit(0);
68 }
69 };
70
71 android::sp<HciDeathRecipient> hci_death_recipient_ = new HciDeathRecipient();
72
73 template <class VecType>
GetTimerText(const char * func_name,VecType vec)74 std::string GetTimerText(const char* func_name, VecType vec) {
75 return common::StringFormat(
76 "%s: len %zu, 1st 5 bytes '%s'",
77 func_name,
78 vec.size(),
79 common::ToHexString(vec.begin(), std::min(vec.end(), vec.begin() + 5)).c_str());
80 }
81
82 class InternalHciCallbacks : public IBluetoothHciCallbacks_1_1 {
83 public:
InternalHciCallbacks(activity_attribution::ActivityAttribution * btaa_logger_,SnoopLogger * btsnoop_logger)84 InternalHciCallbacks(activity_attribution::ActivityAttribution* btaa_logger_, SnoopLogger* btsnoop_logger)
85 : btaa_logger_(btaa_logger_), btsnoop_logger_(btsnoop_logger) {
86 init_promise_ = new std::promise<void>();
87 }
88
SetCallback(HciHalCallbacks * callback)89 void SetCallback(HciHalCallbacks* callback) {
90 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
91 ASSERT(callback_ == nullptr && callback != nullptr);
92 callback_ = callback;
93 }
94
ResetCallback()95 void ResetCallback() {
96 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
97 LOG_INFO("callbacks have been reset!");
98 callback_ = nullptr;
99 }
100
GetInitPromise()101 std::promise<void>* GetInitPromise() {
102 return init_promise_;
103 }
104
initializationComplete(HidlStatus status)105 Return<void> initializationComplete(HidlStatus status) {
106 common::StopWatch stop_watch(__func__);
107 LOG_INFO("initialization complete with status: %d", status);
108 CHECK_EQ(status, HidlStatus::SUCCESS);
109 init_promise_->set_value();
110 return Void();
111 }
112
hciEventReceived(const hidl_vec<uint8_t> & event)113 Return<void> hciEventReceived(const hidl_vec<uint8_t>& event) override {
114 common::StopWatch stop_watch(GetTimerText(__func__, event));
115 std::vector<uint8_t> received_hci_packet(event.begin(), event.end());
116 btsnoop_logger_->Capture(received_hci_packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::EVT);
117 if (common::init_flags::btaa_hci_is_enabled()) {
118 btaa_logger_->Capture(received_hci_packet, SnoopLogger::PacketType::EVT);
119 }
120 {
121 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
122 if (callback_ != nullptr) {
123 callback_->hciEventReceived(std::move(received_hci_packet));
124 }
125 }
126 return Void();
127 }
128
aclDataReceived(const hidl_vec<uint8_t> & data)129 Return<void> aclDataReceived(const hidl_vec<uint8_t>& data) override {
130 common::StopWatch stop_watch(GetTimerText(__func__, data));
131 std::vector<uint8_t> received_hci_packet(data.begin(), data.end());
132 btsnoop_logger_->Capture(received_hci_packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL);
133 if (common::init_flags::btaa_hci_is_enabled()) {
134 btaa_logger_->Capture(received_hci_packet, SnoopLogger::PacketType::ACL);
135 }
136 {
137 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
138 if (callback_ != nullptr) {
139 callback_->aclDataReceived(std::move(received_hci_packet));
140 }
141 }
142 return Void();
143 }
144
scoDataReceived(const hidl_vec<uint8_t> & data)145 Return<void> scoDataReceived(const hidl_vec<uint8_t>& data) override {
146 common::StopWatch stop_watch(GetTimerText(__func__, data));
147 std::vector<uint8_t> received_hci_packet(data.begin(), data.end());
148 btsnoop_logger_->Capture(received_hci_packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::SCO);
149 if (common::init_flags::btaa_hci_is_enabled()) {
150 btaa_logger_->Capture(received_hci_packet, SnoopLogger::PacketType::SCO);
151 }
152
153 {
154 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
155 if (callback_ != nullptr) {
156 callback_->scoDataReceived(std::move(received_hci_packet));
157 }
158 }
159 return Void();
160 }
161
isoDataReceived(const hidl_vec<uint8_t> & data)162 Return<void> isoDataReceived(const hidl_vec<uint8_t>& data) override {
163 common::StopWatch stop_watch(GetTimerText(__func__, data));
164 std::vector<uint8_t> received_hci_packet(data.begin(), data.end());
165 btsnoop_logger_->Capture(received_hci_packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ISO);
166
167 {
168 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
169 if (callback_ != nullptr) {
170 callback_->isoDataReceived(std::move(received_hci_packet));
171 }
172 }
173 return Void();
174 }
175
176 private:
177 std::mutex incoming_packet_callback_mutex_;
178 std::promise<void>* init_promise_ = nullptr;
179 HciHalCallbacks* callback_ = nullptr;
180 activity_attribution::ActivityAttribution* btaa_logger_ = nullptr;
181 SnoopLogger* btsnoop_logger_ = nullptr;
182 };
183
184 static constexpr char kBluetoothAidlHalServiceName[] =
185 "android.hardware.bluetooth.IBluetoothHci/default";
186
187 class AidlHciCallbacks : public ::aidl::android::hardware::bluetooth::BnBluetoothHciCallbacks {
188 public:
AidlHciCallbacks(activity_attribution::ActivityAttribution * btaa_logger_,SnoopLogger * btsnoop_logger)189 AidlHciCallbacks(
190 activity_attribution::ActivityAttribution* btaa_logger_, SnoopLogger* btsnoop_logger)
191 : btaa_logger_(btaa_logger_), btsnoop_logger_(btsnoop_logger) {
192 init_promise_ = new std::promise<void>();
193 }
194
SetCallback(HciHalCallbacks * callback)195 void SetCallback(HciHalCallbacks* callback) {
196 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
197 ASSERT(callback_ == nullptr && callback != nullptr);
198 callback_ = callback;
199 }
200
ResetCallback()201 void ResetCallback() {
202 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
203 callback_ = nullptr;
204 }
205
GetInitPromise()206 std::promise<void>* GetInitPromise() {
207 return init_promise_;
208 }
209
initializationComplete(AidlStatus status)210 ::ndk::ScopedAStatus initializationComplete(AidlStatus status) {
211 common::StopWatch stop_watch(__func__);
212 ASSERT(status == AidlStatus::SUCCESS);
213 init_promise_->set_value();
214 return ::ndk::ScopedAStatus::ok();
215 }
216
hciEventReceived(const std::vector<uint8_t> & event)217 ::ndk::ScopedAStatus hciEventReceived(const std::vector<uint8_t>& event) override {
218 common::StopWatch stop_watch(GetTimerText(__func__, event));
219 std::vector<uint8_t> received_hci_packet(event.begin(), event.end());
220 btsnoop_logger_->Capture(
221 received_hci_packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::EVT);
222 if (common::init_flags::btaa_hci_is_enabled()) {
223 btaa_logger_->Capture(received_hci_packet, SnoopLogger::PacketType::EVT);
224 }
225 bool sent = false;
226 {
227 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
228 if (callback_ != nullptr) {
229 callback_->hciEventReceived(std::move(received_hci_packet));
230 sent = true;
231 }
232 }
233 if (!sent) {
234 LOG_INFO("Dropping HCI Event, since callback_ is null");
235 }
236 return ::ndk::ScopedAStatus::ok();
237 }
238
aclDataReceived(const std::vector<uint8_t> & data)239 ::ndk::ScopedAStatus aclDataReceived(const std::vector<uint8_t>& data) override {
240 common::StopWatch stop_watch(GetTimerText(__func__, data));
241 std::vector<uint8_t> received_hci_packet(data.begin(), data.end());
242 btsnoop_logger_->Capture(
243 received_hci_packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL);
244 if (common::init_flags::btaa_hci_is_enabled()) {
245 btaa_logger_->Capture(received_hci_packet, SnoopLogger::PacketType::ACL);
246 }
247 bool sent = false;
248 {
249 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
250 if (callback_ != nullptr) {
251 callback_->aclDataReceived(std::move(received_hci_packet));
252 sent = true;
253 }
254 }
255 if (!sent) {
256 LOG_INFO("Dropping ACL Data, since callback_ is null");
257 }
258 return ::ndk::ScopedAStatus::ok();
259 }
260
scoDataReceived(const std::vector<uint8_t> & data)261 ::ndk::ScopedAStatus scoDataReceived(const std::vector<uint8_t>& data) override {
262 common::StopWatch stop_watch(GetTimerText(__func__, data));
263 std::vector<uint8_t> received_hci_packet(data.begin(), data.end());
264 btsnoop_logger_->Capture(
265 received_hci_packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::SCO);
266 if (common::init_flags::btaa_hci_is_enabled()) {
267 btaa_logger_->Capture(received_hci_packet, SnoopLogger::PacketType::SCO);
268 }
269 bool sent = false;
270 {
271 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
272 if (callback_ != nullptr) {
273 callback_->scoDataReceived(std::move(received_hci_packet));
274 sent = true;
275 }
276 }
277 if (!sent) {
278 LOG_INFO("Dropping SCO Data, since callback_ is null");
279 }
280 return ::ndk::ScopedAStatus::ok();
281 }
282
isoDataReceived(const std::vector<uint8_t> & data)283 ::ndk::ScopedAStatus isoDataReceived(const std::vector<uint8_t>& data) override {
284 common::StopWatch stop_watch(GetTimerText(__func__, data));
285 std::vector<uint8_t> received_hci_packet(data.begin(), data.end());
286 btsnoop_logger_->Capture(
287 received_hci_packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ISO);
288 bool sent = false;
289 {
290 std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
291 if (callback_ != nullptr) {
292 callback_->isoDataReceived(std::move(received_hci_packet));
293 sent = true;
294 }
295 }
296 if (!sent) {
297 LOG_INFO("Dropping ISO Data, since callback_ is null");
298 }
299 return ::ndk::ScopedAStatus::ok();
300 }
301
302 private:
303 std::mutex incoming_packet_callback_mutex_;
304 std::promise<void>* init_promise_ = nullptr;
305 HciHalCallbacks* callback_ = nullptr;
306 activity_attribution::ActivityAttribution* btaa_logger_ = nullptr;
307 SnoopLogger* btsnoop_logger_ = nullptr;
308 };
309
310 } // namespace
311
312 class HciHalHidl : public HciHal {
313 public:
registerIncomingPacketCallback(HciHalCallbacks * callback)314 void registerIncomingPacketCallback(HciHalCallbacks* callback) override {
315 if (aidl_callbacks_) {
316 aidl_callbacks_->SetCallback(callback);
317 }
318 if (hidl_callbacks_) {
319 hidl_callbacks_->SetCallback(callback);
320 }
321 }
322
unregisterIncomingPacketCallback()323 void unregisterIncomingPacketCallback() override {
324 if (aidl_callbacks_) {
325 aidl_callbacks_->ResetCallback();
326 }
327 if (hidl_callbacks_) {
328 hidl_callbacks_->ResetCallback();
329 }
330 }
331
sendHciCommand(HciPacket command)332 void sendHciCommand(HciPacket command) override {
333 btsnoop_logger_->Capture(command, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD);
334 if (common::init_flags::btaa_hci_is_enabled()) {
335 btaa_logger_->Capture(command, SnoopLogger::PacketType::CMD);
336 }
337 if (aidl_hci_) {
338 aidl_hci_->sendHciCommand(command);
339 } else {
340 bt_hci_->sendHciCommand(command);
341 }
342 }
343
sendAclData(HciPacket packet)344 void sendAclData(HciPacket packet) override {
345 btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL);
346 if (common::init_flags::btaa_hci_is_enabled()) {
347 btaa_logger_->Capture(packet, SnoopLogger::PacketType::ACL);
348 }
349 if (aidl_hci_) {
350 aidl_hci_->sendAclData(packet);
351 } else {
352 bt_hci_->sendAclData(packet);
353 }
354 }
355
sendScoData(HciPacket packet)356 void sendScoData(HciPacket packet) override {
357 btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::SCO);
358 if (common::init_flags::btaa_hci_is_enabled()) {
359 btaa_logger_->Capture(packet, SnoopLogger::PacketType::SCO);
360 }
361 if (aidl_hci_) {
362 aidl_hci_->sendScoData(packet);
363 } else {
364 bt_hci_->sendScoData(packet);
365 }
366 }
367
sendIsoData(HciPacket packet)368 void sendIsoData(HciPacket packet) override {
369 if (aidl_hci_ == nullptr && bt_hci_1_1_ == nullptr) {
370 LOG_ERROR("ISO is not supported in HAL v1.0");
371 return;
372 }
373
374 btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ISO);
375 if (aidl_hci_) {
376 aidl_hci_->sendIsoData(packet);
377 } else {
378 bt_hci_1_1_->sendIsoData(packet);
379 }
380 }
381
382 protected:
ListDependencies(ModuleList * list) const383 void ListDependencies(ModuleList* list) const {
384 list->add<SnoopLogger>();
385 if (common::init_flags::btaa_hci_is_enabled()) {
386 list->add<activity_attribution::ActivityAttribution>();
387 }
388 }
389
Start()390 void Start() override {
391 common::StopWatch stop_watch(__func__);
392
393 // Start can't be called more than once before Stop is called.
394 ASSERT(bt_hci_ == nullptr);
395 ASSERT(bt_hci_1_1_ == nullptr);
396 ASSERT(aidl_hci_ == nullptr);
397
398 if (common::init_flags::btaa_hci_is_enabled()) {
399 btaa_logger_ = GetDependency<activity_attribution::ActivityAttribution>();
400 }
401 btsnoop_logger_ = GetDependency<SnoopLogger>();
402
403 if (AServiceManager_isDeclared(kBluetoothAidlHalServiceName)) {
404 start_aidl();
405 aidl_callbacks_->GetInitPromise()->get_future().wait();
406 } else {
407 start_hidl();
408 hidl_callbacks_->GetInitPromise()->get_future().wait();
409 }
410 }
411
start_aidl()412 void start_aidl() {
413 common::StopWatch stop_watch(__func__);
414 ::ndk::SpAIBinder binder(AServiceManager_waitForService(kBluetoothAidlHalServiceName));
415 aidl_hci_ = IBluetoothHci::fromBinder(binder);
416 if (aidl_hci_ != nullptr) {
417 LOG_INFO("Using the AIDL interface");
418 aidl_death_recipient_ =
419 ::ndk::ScopedAIBinder_DeathRecipient(AIBinder_DeathRecipient_new([](void* cookie) {
420 LOG_ERROR("Bluetooth HAL service died. Calling exit(0);");
421 common::StopWatch::DumpStopWatchLog();
422 exit(0);
423 }));
424
425 auto death_link =
426 AIBinder_linkToDeath(aidl_hci_->asBinder().get(), aidl_death_recipient_.get(), this);
427
428 ASSERT_LOG(
429 death_link == STATUS_OK, "Unable to set the death recipient for the Bluetooth HAL");
430
431 aidl_callbacks_ = ::ndk::SharedRefBase::make<AidlHciCallbacks>(btaa_logger_, btsnoop_logger_);
432 aidl_hci_->initialize(aidl_callbacks_);
433 }
434 }
435
start_hidl()436 void start_hidl() {
437 common::StopWatch stop_watch(__func__);
438
439 LOG_INFO("Trying to find a HIDL interface");
440
441 auto get_service_alarm = new os::Alarm(GetHandler());
442 get_service_alarm->Schedule(
443 BindOnce([] {
444 const std::string kBoardProperty = "ro.product.board";
445 const std::string kCuttlefishBoard = "cutf";
446 auto board_name = os::GetSystemProperty(kBoardProperty);
447 bool emulator = board_name.has_value() && board_name.value() == kCuttlefishBoard;
448 if (emulator) {
449 LOG_ERROR("board_name: %s", board_name.value().c_str());
450 LOG_ERROR("Unable to get a Bluetooth service after 500ms, start the HAL before starting Bluetooth");
451 return;
452 }
453 LOG_ALWAYS_FATAL("Unable to get a Bluetooth service after 500ms, start the HAL before starting Bluetooth");
454 }),
455 std::chrono::milliseconds(500));
456
457 bt_hci_1_1_ = IBluetoothHci_1_1::getService();
458
459 if (bt_hci_1_1_ != nullptr) {
460 bt_hci_ = bt_hci_1_1_;
461 } else {
462 bt_hci_ = IBluetoothHci_1_0::getService();
463 }
464
465 get_service_alarm->Cancel();
466 delete get_service_alarm;
467
468 ASSERT(bt_hci_ != nullptr);
469 auto death_link = bt_hci_->linkToDeath(hci_death_recipient_, 0);
470 ASSERT_LOG(death_link.isOk(), "Unable to set the death recipient for the Bluetooth HAL");
471 hidl_callbacks_ = new InternalHciCallbacks(btaa_logger_, btsnoop_logger_);
472
473 if (bt_hci_1_1_ != nullptr) {
474 bt_hci_1_1_->initialize_1_1(hidl_callbacks_);
475 } else {
476 bt_hci_->initialize(hidl_callbacks_);
477 }
478 }
479
Stop()480 void Stop() override {
481 if (bt_hci_ != nullptr) {
482 stop_hidl();
483 }
484 if (aidl_hci_ != nullptr) {
485 stop_aidl();
486 }
487 }
488
ToString() const489 std::string ToString() const override {
490 return std::string("HciHalHidl");
491 }
492
493 private:
stop_hidl()494 void stop_hidl() {
495 ASSERT(bt_hci_ != nullptr);
496 auto death_unlink = bt_hci_->unlinkToDeath(hci_death_recipient_);
497 if (!death_unlink.isOk()) {
498 LOG_ERROR("Error unlinking death recipient from the Bluetooth HAL");
499 }
500 auto close_status = bt_hci_->close();
501 if (!close_status.isOk()) {
502 LOG_ERROR("Error calling close on the Bluetooth HAL");
503 }
504 bt_hci_ = nullptr;
505 bt_hci_1_1_ = nullptr;
506 hidl_callbacks_->ResetCallback();
507 }
508
stop_aidl()509 void stop_aidl() {
510 ASSERT(aidl_hci_ != nullptr);
511 auto death_unlink =
512 AIBinder_unlinkToDeath(aidl_hci_->asBinder().get(), aidl_death_recipient_.get(), this);
513 if (death_unlink != STATUS_OK) {
514 LOG_ERROR("Error unlinking death recipient from the Bluetooth HAL");
515 }
516 auto close_status = aidl_hci_->close();
517 if (!close_status.isOk()) {
518 LOG_ERROR("Error calling close on the Bluetooth HAL");
519 }
520 aidl_hci_ = nullptr;
521 aidl_callbacks_->ResetCallback();
522 }
523 android::sp<InternalHciCallbacks> hidl_callbacks_;
524 android::sp<IBluetoothHci_1_0> bt_hci_;
525 android::sp<IBluetoothHci_1_1> bt_hci_1_1_;
526 std::shared_ptr<IBluetoothHci> aidl_hci_;
527 std::shared_ptr<AidlHciCallbacks> aidl_callbacks_;
528 ::ndk::ScopedAIBinder_DeathRecipient aidl_death_recipient_;
529 activity_attribution::ActivityAttribution* btaa_logger_;
530 SnoopLogger* btsnoop_logger_;
531 };
532
__anon7c31fccd0402() 533 const ModuleFactory HciHal::Factory = ModuleFactory([]() { return new HciHalHidl(); });
534
535 } // namespace hal
536 } // namespace bluetooth
537