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 "hci/hci_layer.h"
18
19 #ifdef TARGET_FLOSS
20 #include <signal.h>
21 #endif
22 #include <bluetooth/log.h>
23
24 #include <map>
25 #include <utility>
26 #include <vector>
27
28 #include "common/bind.h"
29 #include "common/stop_watch.h"
30 #include "hal/hci_hal.h"
31 #include "hci/class_of_device.h"
32 #include "hci/hci_metrics_logging.h"
33 #include "hci/inquiry_interface.h"
34 #include "os/alarm.h"
35 #include "os/metrics.h"
36 #include "os/queue.h"
37 #include "os/system_properties.h"
38 #include "osi/include/stack_power_telemetry.h"
39 #include "packet/raw_builder.h"
40 #include "storage/storage_module.h"
41
42 namespace bluetooth {
43 namespace hci {
44 using bluetooth::common::BindOn;
45 using bluetooth::common::BindOnce;
46 using bluetooth::common::ContextualCallback;
47 using bluetooth::common::ContextualOnceCallback;
48 using bluetooth::hci::CommandBuilder;
49 using bluetooth::hci::CommandCompleteView;
50 using bluetooth::hci::CommandStatusOrCompleteView;
51 using bluetooth::hci::CommandStatusView;
52 using bluetooth::hci::EventView;
53 using bluetooth::hci::LeMetaEventView;
54 using bluetooth::os::Handler;
55 using common::BidiQueue;
56 using common::BidiQueueEnd;
57 using hci::OpCode;
58 using hci::ResetCompleteView;
59 using os::Alarm;
60 using os::Handler;
61 using std::unique_ptr;
62
63 static std::recursive_mutex life_cycle_guard;
64 static bool life_cycle_stopped = true;
65
getHciTimeoutMs()66 static std::chrono::milliseconds getHciTimeoutMs() {
67 static auto sHciTimeoutMs = std::chrono::milliseconds(bluetooth::os::GetSystemPropertyUint32Base(
68 "bluetooth.hci.timeout_milliseconds", HciLayer::kHciTimeoutMs.count()));
69 return sHciTimeoutMs;
70 }
71
getHciTimeoutRestartMs()72 static std::chrono::milliseconds getHciTimeoutRestartMs() {
73 static auto sRestartHciTimeoutMs = std::chrono::milliseconds(
74 bluetooth::os::GetSystemPropertyUint32Base("bluetooth.hci.restart_timeout_milliseconds",
75 HciLayer::kHciTimeoutRestartMs.count()));
76 return sRestartHciTimeoutMs;
77 }
78
fail_if_reset_complete_not_success(CommandCompleteView complete)79 static void fail_if_reset_complete_not_success(CommandCompleteView complete) {
80 auto reset_complete = ResetCompleteView::Create(complete);
81 log::assert_that(reset_complete.IsValid(), "assert failed: reset_complete.IsValid()");
82 log::debug("Reset completed with status: {}", ErrorCodeText(ErrorCode::SUCCESS));
83 log::assert_that(reset_complete.GetStatus() == ErrorCode::SUCCESS,
84 "assert failed: reset_complete.GetStatus() == ErrorCode::SUCCESS");
85 }
86
abort_after_time_out(OpCode op_code)87 static void abort_after_time_out(OpCode op_code) {
88 log::fatal("Done waiting for debug information after HCI timeout ({}) for {}ms",
89 OpCodeText(op_code), getHciTimeoutRestartMs().count());
90 }
91
92 class CommandQueueEntry {
93 public:
94 enum class WaitingFor { STATUS, COMPLETE, STATUS_OR_COMPLETE };
95
CommandQueueEntry(unique_ptr<CommandBuilder> command_packet,ContextualOnceCallback<void (CommandCompleteView)> on_complete_function)96 CommandQueueEntry(unique_ptr<CommandBuilder> command_packet,
97 ContextualOnceCallback<void(CommandCompleteView)> on_complete_function)
98 : command(std::move(command_packet)),
99 waiting_for_(WaitingFor::COMPLETE),
100 on_complete(std::move(on_complete_function)) {}
101
CommandQueueEntry(unique_ptr<CommandBuilder> command_packet,ContextualOnceCallback<void (CommandStatusView)> on_status_function)102 CommandQueueEntry(unique_ptr<CommandBuilder> command_packet,
103 ContextualOnceCallback<void(CommandStatusView)> on_status_function)
104 : command(std::move(command_packet)),
105 waiting_for_(WaitingFor::STATUS),
106 on_status(std::move(on_status_function)) {}
107
CommandQueueEntry(unique_ptr<CommandBuilder> command_packet,ContextualOnceCallback<void (CommandStatusOrCompleteView)> on_status_or_complete_function)108 CommandQueueEntry(
109 unique_ptr<CommandBuilder> command_packet,
110 ContextualOnceCallback<void(CommandStatusOrCompleteView)> on_status_or_complete_function)
111 : command(std::move(command_packet)),
112 waiting_for_(WaitingFor::STATUS_OR_COMPLETE),
113 on_status_or_complete(std::move(on_status_or_complete_function)) {}
114
115 unique_ptr<CommandBuilder> command;
116 unique_ptr<CommandView> command_view;
117
118 WaitingFor waiting_for_;
119 ContextualOnceCallback<void(CommandStatusView)> on_status;
120 ContextualOnceCallback<void(CommandCompleteView)> on_complete;
121 ContextualOnceCallback<void(CommandStatusOrCompleteView)> on_status_or_complete;
122
123 template <typename TView>
GetCallback()124 ContextualOnceCallback<void(TView)>* GetCallback() {
125 return nullptr;
126 }
127
128 template <>
GetCallback()129 ContextualOnceCallback<void(CommandStatusView)>* GetCallback<CommandStatusView>() {
130 return &on_status;
131 }
132
133 template <>
GetCallback()134 ContextualOnceCallback<void(CommandCompleteView)>* GetCallback<CommandCompleteView>() {
135 return &on_complete;
136 }
137
138 template <>
139 ContextualOnceCallback<void(CommandStatusOrCompleteView)>*
GetCallback()140 GetCallback<CommandStatusOrCompleteView>() {
141 return &on_status_or_complete;
142 }
143 };
144
145 struct HciLayer::impl {
implbluetooth::hci::HciLayer::impl146 impl(hal::HciHal* hal, HciLayer& module) : hal_(hal), module_(module) {
147 hci_timeout_alarm_ = new Alarm(module.GetHandler());
148 }
149
~implbluetooth::hci::HciLayer::impl150 ~impl() {
151 incoming_acl_buffer_.Clear();
152 incoming_sco_buffer_.Clear();
153 incoming_iso_buffer_.Clear();
154 if (hci_timeout_alarm_ != nullptr) {
155 delete hci_timeout_alarm_;
156 }
157 if (hci_abort_alarm_ != nullptr) {
158 delete hci_abort_alarm_;
159 }
160 command_queue_.clear();
161 }
162
dropbluetooth::hci::HciLayer::impl163 void drop(EventView event) {
164 log::info("Dropping event {}", EventCodeText(event.GetEventCode()));
165 }
166
on_outbound_acl_readybluetooth::hci::HciLayer::impl167 void on_outbound_acl_ready() {
168 auto packet = acl_queue_.GetDownEnd()->TryDequeue();
169 std::vector<uint8_t> bytes;
170 BitInserter bi(bytes);
171 packet->Serialize(bi);
172 hal_->sendAclData(bytes);
173 }
174
on_outbound_sco_readybluetooth::hci::HciLayer::impl175 void on_outbound_sco_ready() {
176 auto packet = sco_queue_.GetDownEnd()->TryDequeue();
177 std::vector<uint8_t> bytes;
178 BitInserter bi(bytes);
179 packet->Serialize(bi);
180 hal_->sendScoData(bytes);
181 }
182
on_outbound_iso_readybluetooth::hci::HciLayer::impl183 void on_outbound_iso_ready() {
184 auto packet = iso_queue_.GetDownEnd()->TryDequeue();
185 std::vector<uint8_t> bytes;
186 BitInserter bi(bytes);
187 packet->Serialize(bi);
188 hal_->sendIsoData(bytes);
189 }
190
191 template <typename TResponse>
enqueue_commandbluetooth::hci::HciLayer::impl192 void enqueue_command(unique_ptr<CommandBuilder> command,
193 ContextualOnceCallback<void(TResponse)> on_response) {
194 command_queue_.emplace_back(std::move(command), std::move(on_response));
195 send_next_command();
196 }
197
on_command_statusbluetooth::hci::HciLayer::impl198 void on_command_status(EventView event) {
199 CommandStatusView response_view = CommandStatusView::Create(event);
200 log::assert_that(response_view.IsValid(), "assert failed: response_view.IsValid()");
201 OpCode op_code = response_view.GetCommandOpCode();
202 ErrorCode status = response_view.GetStatus();
203 if (status != ErrorCode::SUCCESS) {
204 log::warn("Received UNEXPECTED command status:{} opcode:{}", ErrorCodeText(status),
205 OpCodeText(op_code));
206 }
207 handle_command_response<CommandStatusView>(event, "status");
208 }
209
on_command_completebluetooth::hci::HciLayer::impl210 void on_command_complete(EventView event) {
211 handle_command_response<CommandCompleteView>(event, "complete");
212 }
213
214 template <typename TResponse>
handle_command_responsebluetooth::hci::HciLayer::impl215 void handle_command_response(EventView event, std::string logging_id) {
216 TResponse response_view = TResponse::Create(event);
217 log::assert_that(response_view.IsValid(), "assert failed: response_view.IsValid()");
218 command_credits_ = response_view.GetNumHciCommandPackets();
219 OpCode op_code = response_view.GetCommandOpCode();
220 if (op_code == OpCode::NONE) {
221 send_next_command();
222 return;
223 }
224 bool is_status = logging_id == "status";
225
226 log::assert_that(!command_queue_.empty(), "Unexpected {} event with OpCode {}", logging_id,
227 OpCodeText(op_code));
228 if (waiting_command_ == OpCode::CONTROLLER_DEBUG_INFO &&
229 op_code != OpCode::CONTROLLER_DEBUG_INFO) {
230 log::error("Discarding event that came after timeout {}", OpCodeText(op_code));
231 common::StopWatch::DumpStopWatchLog();
232 return;
233 }
234 log::assert_that(waiting_command_ == op_code, "Waiting for {}, got {}",
235 OpCodeText(waiting_command_), OpCodeText(op_code));
236
237 bool is_vendor_specific = static_cast<int>(op_code) & (0x3f << 10);
238 using WaitingFor = CommandQueueEntry::WaitingFor;
239 WaitingFor waiting_for = command_queue_.front().waiting_for_;
240 CommandStatusView status_view = CommandStatusView::Create(event);
241 if (is_vendor_specific && (is_status && waiting_for == WaitingFor::COMPLETE) &&
242 (status_view.IsValid() && status_view.GetStatus() == ErrorCode::UNKNOWN_HCI_COMMAND)) {
243 // If this is a command status of a vendor specific command, and command complete is expected,
244 // we can't treat this as hard failure since we have no way of probing this lack of support at
245 // earlier time. Instead we let the command complete handler handle a empty Command Complete
246 // packet, which will be interpreted as invalid response.
247
248 auto payload = std::make_unique<packet::RawBuilder>();
249 payload->AddOctets1(static_cast<uint8_t>(status_view.GetStatus()));
250 auto complete_event_builder =
251 CommandCompleteBuilder::Create(status_view.GetNumHciCommandPackets(),
252 status_view.GetCommandOpCode(), std::move(payload));
253 auto complete = std::make_shared<std::vector<std::uint8_t>>(
254 complete_event_builder->SerializeToBytes());
255 CommandCompleteView command_complete_view =
256 CommandCompleteView::Create(EventView::Create(PacketView<kLittleEndian>(complete)));
257 log::assert_that(command_complete_view.IsValid(),
258 "assert failed: command_complete_view.IsValid()");
259 (*command_queue_.front().GetCallback<CommandCompleteView>())(command_complete_view);
260 } else if (waiting_for != WaitingFor::STATUS_OR_COMPLETE) {
261 log::assert_that((waiting_for == WaitingFor::STATUS) == is_status,
262 "{} was not expecting {} event", OpCodeText(op_code), logging_id);
263
264 (*command_queue_.front().GetCallback<TResponse>())(std::move(response_view));
265 } else {
266 (*command_queue_.front().GetCallback<CommandStatusOrCompleteView>())(
267 std::move(response_view));
268 }
269
270 #ifdef TARGET_FLOSS
271 // Although UNKNOWN_CONNECTION might be a controller issue in some command status, we treat it
272 // as a disconnect event to maintain consistent connection state between stack and controller
273 // since there might not be further HCI Disconnect Event after this status event.
274 // Currently only do this on LE_READ_REMOTE_FEATURES because it is the only one we know that
275 // would return UNKNOWN_CONNECTION in some cases.
276 if (op_code == OpCode::LE_READ_REMOTE_FEATURES && is_status && status_view.IsValid() &&
277 status_view.GetStatus() == ErrorCode::UNKNOWN_CONNECTION) {
278 auto& command_view = *command_queue_.front().command_view;
279 auto le_read_features_view = bluetooth::hci::LeReadRemoteFeaturesView::Create(
280 LeConnectionManagementCommandView::Create(AclCommandView::Create(command_view)));
281 if (le_read_features_view.IsValid()) {
282 uint16_t handle = le_read_features_view.GetConnectionHandle();
283 module_.Disconnect(handle, ErrorCode::UNKNOWN_CONNECTION);
284 }
285 }
286 #endif
287
288 command_queue_.pop_front();
289 waiting_command_ = OpCode::NONE;
290 if (hci_timeout_alarm_ != nullptr) {
291 hci_timeout_alarm_->Cancel();
292 send_next_command();
293 }
294 }
295
on_hci_timeoutbluetooth::hci::HciLayer::impl296 void on_hci_timeout(OpCode op_code) {
297 common::StopWatch::DumpStopWatchLog();
298 log::error("Timed out waiting for {} for {}ms", OpCodeText(op_code), getHciTimeoutMs().count());
299
300 bluetooth::os::LogMetricHciTimeoutEvent(static_cast<uint32_t>(op_code));
301
302 log::error("Flushing {} waiting commands", command_queue_.size());
303 // Clear any waiting commands (there is an abort coming anyway)
304 command_queue_.clear();
305 command_credits_ = 1;
306 waiting_command_ = OpCode::NONE;
307
308 #ifdef TARGET_FLOSS
309 log::warn("Ignoring the timeouted HCI command {}.", OpCodeText(op_code));
310 // Terminate the process to trigger controller reset, also mark the controller
311 // is broken to prevent further error while terminating.
312 auto hal = module_.GetDependency<hal::HciHal>();
313 hal->markControllerBroken();
314 kill(getpid(), SIGTERM);
315 return;
316 #endif
317
318 // Ignore the response, since we don't know what might come back.
319 enqueue_command(ControllerDebugInfoBuilder::Create(),
320 module_.GetHandler()->BindOnce([](CommandCompleteView) {}));
321 // Don't time out for this one;
322 if (hci_timeout_alarm_ != nullptr) {
323 hci_timeout_alarm_->Cancel();
324 delete hci_timeout_alarm_;
325 hci_timeout_alarm_ = nullptr;
326 }
327 if (hci_abort_alarm_ == nullptr) {
328 hci_abort_alarm_ = new Alarm(module_.GetHandler());
329 hci_abort_alarm_->Schedule(BindOnce(&abort_after_time_out, op_code),
330 getHciTimeoutRestartMs());
331 } else {
332 log::warn("Unable to schedul abort timer");
333 }
334 }
335
send_next_commandbluetooth::hci::HciLayer::impl336 void send_next_command() {
337 if (command_credits_ == 0) {
338 return;
339 }
340 if (waiting_command_ != OpCode::NONE) {
341 return;
342 }
343 if (command_queue_.size() == 0) {
344 return;
345 }
346 std::shared_ptr<std::vector<uint8_t>> bytes = std::make_shared<std::vector<uint8_t>>();
347 BitInserter bi(*bytes);
348 command_queue_.front().command->Serialize(bi);
349 hal_->sendHciCommand(*bytes);
350
351 auto cmd_view = CommandView::Create(PacketView<kLittleEndian>(bytes));
352 log::assert_that(cmd_view.IsValid(), "assert failed: cmd_view.IsValid()");
353 OpCode op_code = cmd_view.GetOpCode();
354 power_telemetry::GetInstance().LogHciCmdDetail();
355 command_queue_.front().command_view = std::make_unique<CommandView>(std::move(cmd_view));
356 log_link_layer_connection_command(command_queue_.front().command_view);
357 log_classic_pairing_command_status(command_queue_.front().command_view,
358 ErrorCode::STATUS_UNKNOWN);
359 waiting_command_ = op_code;
360 command_credits_ = 0; // Only allow one outstanding command
361 if (hci_timeout_alarm_ != nullptr) {
362 hci_timeout_alarm_->Schedule(
363 BindOnce(&impl::on_hci_timeout, common::Unretained(this), op_code),
364 getHciTimeoutMs());
365 } else {
366 log::warn("{} sent without an hci-timeout timer", OpCodeText(op_code));
367 }
368 }
369
register_eventbluetooth::hci::HciLayer::impl370 void register_event(EventCode event, ContextualCallback<void(EventView)> handler) {
371 log::assert_that(event != EventCode::LE_META_EVENT, "Can not register handler for {}",
372 EventCodeText(EventCode::LE_META_EVENT));
373 // Allow GD Cert tests to register for CONNECTION_REQUEST
374 if (event == EventCode::CONNECTION_REQUEST && !module_.on_acl_connection_request_) {
375 log::info("Registering test for CONNECTION_REQUEST, since there's no ACL");
376 event_handlers_.erase(event);
377 }
378 log::assert_that(event_handlers_.count(event) == 0, "Can not register a second handler for {}",
379 EventCodeText(event));
380 event_handlers_[event] = handler;
381 }
382
unregister_eventbluetooth::hci::HciLayer::impl383 void unregister_event(EventCode event) { event_handlers_.erase(event); }
384
register_le_eventbluetooth::hci::HciLayer::impl385 void register_le_event(SubeventCode event, ContextualCallback<void(LeMetaEventView)> handler) {
386 log::assert_that(le_event_handlers_.count(event) == 0,
387 "Can not register a second handler for {}", SubeventCodeText(event));
388 le_event_handlers_[event] = handler;
389 }
390
unregister_le_eventbluetooth::hci::HciLayer::impl391 void unregister_le_event(SubeventCode event) {
392 le_event_handlers_.erase(le_event_handlers_.find(event));
393 }
394
register_vs_eventbluetooth::hci::HciLayer::impl395 void register_vs_event(VseSubeventCode event,
396 ContextualCallback<void(VendorSpecificEventView)> handler) {
397 log::assert_that(vs_event_handlers_.count(event) == 0,
398 "Can not register a second handler for {}", VseSubeventCodeText(event));
399 vs_event_handlers_[event] = handler;
400 }
401
unregister_vs_eventbluetooth::hci::HciLayer::impl402 void unregister_vs_event(VseSubeventCode event) {
403 vs_event_handlers_.erase(vs_event_handlers_.find(event));
404 }
405
register_vs_event_defaultbluetooth::hci::HciLayer::impl406 void register_vs_event_default(ContextualCallback<void(VendorSpecificEventView)> handler) {
407 vs_event_default_handler_ = std::move(handler);
408 }
409
unregister_vs_event_defaultbluetooth::hci::HciLayer::impl410 void unregister_vs_event_default() { vs_event_default_handler_.reset(); }
411
abort_after_root_inflammationbluetooth::hci::HciLayer::impl412 static void abort_after_root_inflammation(uint8_t vse_error) {
413 log::fatal("Root inflammation with reason 0x{:02x}", vse_error);
414 }
415
handle_root_inflammationbluetooth::hci::HciLayer::impl416 void handle_root_inflammation(uint8_t vse_error_reason) {
417 log::error("Received a Root Inflammation Event vendor reason 0x{:02x}, scheduling an abort",
418 vse_error_reason);
419 bluetooth::os::LogMetricBluetoothHalCrashReason(Address::kEmpty, 0, vse_error_reason);
420 // Add Logging for crash reason
421 if (hci_timeout_alarm_ != nullptr) {
422 hci_timeout_alarm_->Cancel();
423 delete hci_timeout_alarm_;
424 hci_timeout_alarm_ = nullptr;
425 }
426 if (hci_abort_alarm_ == nullptr) {
427 hci_abort_alarm_ = new Alarm(module_.GetHandler());
428 hci_abort_alarm_->Schedule(BindOnce(&abort_after_root_inflammation, vse_error_reason),
429 getHciTimeoutRestartMs());
430 } else {
431 log::warn("Abort timer already scheduled");
432 }
433 }
434
on_hci_eventbluetooth::hci::HciLayer::impl435 void on_hci_event(EventView event) {
436 log::assert_that(event.IsValid(), "assert failed: event.IsValid()");
437 if (command_queue_.empty()) {
438 auto event_code = event.GetEventCode();
439 // BT Core spec 5.2 (Volume 4, Part E section 4.4) allows anytime
440 // COMMAND_COMPLETE and COMMAND_STATUS with opcode 0x0 for flow control
441 if (event_code == EventCode::COMMAND_COMPLETE) {
442 auto view = CommandCompleteView::Create(event);
443 log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
444 auto op_code = view.GetCommandOpCode();
445 log::assert_that(op_code == OpCode::NONE,
446 "Received {} event with OpCode {} without a waiting command(is the HAL "
447 "sending commands, but not handling the events?)",
448 EventCodeText(event_code), OpCodeText(op_code));
449 }
450 if (event_code == EventCode::COMMAND_STATUS) {
451 auto view = CommandStatusView::Create(event);
452 log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
453 auto op_code = view.GetCommandOpCode();
454 log::assert_that(op_code == OpCode::NONE,
455 "Received {} event with OpCode {} without a waiting command(is the HAL "
456 "sending commands, but not handling the events?)",
457 EventCodeText(event_code), OpCodeText(op_code));
458 }
459 std::unique_ptr<CommandView> no_waiting_command{nullptr};
460 log_hci_event(no_waiting_command, event, module_.GetDependency<storage::StorageModule>());
461 } else {
462 log_hci_event(command_queue_.front().command_view, event,
463 module_.GetDependency<storage::StorageModule>());
464 }
465 power_telemetry::GetInstance().LogHciEvtDetail();
466 EventCode event_code = event.GetEventCode();
467 // Root Inflamation is a special case, since it aborts here
468 if (event_code == EventCode::VENDOR_SPECIFIC) {
469 auto view = VendorSpecificEventView::Create(event);
470 log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
471 if (view.GetSubeventCode() == VseSubeventCode::BQR_EVENT) {
472 auto bqr_event = BqrEventView::Create(view);
473 auto inflammation = BqrRootInflammationEventView::Create(bqr_event);
474 if (bqr_event.IsValid() && inflammation.IsValid()) {
475 handle_root_inflammation(inflammation.GetVendorSpecificErrorCode());
476 return;
477 }
478 }
479 }
480 switch (event_code) {
481 case EventCode::COMMAND_COMPLETE:
482 on_command_complete(event);
483 break;
484 case EventCode::COMMAND_STATUS:
485 on_command_status(event);
486 break;
487 case EventCode::LE_META_EVENT:
488 on_le_meta_event(event);
489 break;
490 case EventCode::HARDWARE_ERROR:
491 on_hardware_error(event);
492 break;
493 case EventCode::VENDOR_SPECIFIC:
494 on_vs_event(event);
495 break;
496 default:
497 if (event_handlers_.find(event_code) == event_handlers_.end()) {
498 log::warn("Unhandled event of type {}", EventCodeText(event_code));
499 } else {
500 event_handlers_[event_code](event);
501 }
502 }
503 }
504
on_hardware_errorbluetooth::hci::HciLayer::impl505 void on_hardware_error(EventView event) {
506 HardwareErrorView event_view = HardwareErrorView::Create(event);
507 log::assert_that(event_view.IsValid(), "assert failed: event_view.IsValid()");
508 #ifdef TARGET_FLOSS
509 log::warn("Hardware Error Event with code 0x{:02x}", event_view.GetHardwareCode());
510 // Sending SIGTERM to process the exception from BT controller.
511 // The Floss daemon will be restarted. HCI reset during restart will clear the
512 // error state of the BT controller.
513 auto hal = module_.GetDependency<hal::HciHal>();
514 hal->markControllerBroken();
515 kill(getpid(), SIGTERM);
516 #else
517 log::fatal("Hardware Error Event with code 0x{:02x}", event_view.GetHardwareCode());
518 #endif
519 }
520
on_le_meta_eventbluetooth::hci::HciLayer::impl521 void on_le_meta_event(EventView event) {
522 LeMetaEventView meta_event_view = LeMetaEventView::Create(event);
523 log::assert_that(meta_event_view.IsValid(), "assert failed: meta_event_view.IsValid()");
524 SubeventCode subevent_code = meta_event_view.GetSubeventCode();
525 if (le_event_handlers_.find(subevent_code) == le_event_handlers_.end()) {
526 log::warn("Unhandled le subevent of type {}", SubeventCodeText(subevent_code));
527 return;
528 }
529 le_event_handlers_[subevent_code](meta_event_view);
530 }
531
on_vs_eventbluetooth::hci::HciLayer::impl532 void on_vs_event(EventView event) {
533 VendorSpecificEventView vs_event_view = VendorSpecificEventView::Create(event);
534 log::assert_that(vs_event_view.IsValid(), "assert failed: vs_event_view.IsValid()");
535 VseSubeventCode subevent_code = vs_event_view.GetSubeventCode();
536 if (vs_event_handlers_.find(subevent_code) != vs_event_handlers_.end()) {
537 vs_event_handlers_[subevent_code](vs_event_view);
538 } else if (vs_event_default_handler_.has_value()) {
539 (*vs_event_default_handler_)(vs_event_view);
540 } else {
541 log::warn("Unhandled vendor specific event of type {}", VseSubeventCodeText(subevent_code));
542 }
543 }
544
545 hal::HciHal* hal_;
546 HciLayer& module_;
547
548 // Command Handling
549 std::list<CommandQueueEntry> command_queue_;
550
551 std::map<EventCode, ContextualCallback<void(EventView)>> event_handlers_;
552 std::map<SubeventCode, ContextualCallback<void(LeMetaEventView)>> le_event_handlers_;
553 std::map<VseSubeventCode, ContextualCallback<void(VendorSpecificEventView)>> vs_event_handlers_;
554 std::optional<ContextualCallback<void(VendorSpecificEventView)>> vs_event_default_handler_;
555
556 OpCode waiting_command_{OpCode::NONE};
557 uint8_t command_credits_{1}; // Send reset first
558 Alarm* hci_timeout_alarm_{nullptr};
559 Alarm* hci_abort_alarm_{nullptr};
560
561 // Acl packets
562 BidiQueue<AclView, AclBuilder> acl_queue_{3 /* TODO: Set queue depth */};
563 os::EnqueueBuffer<AclView> incoming_acl_buffer_{acl_queue_.GetDownEnd()};
564
565 // SCO packets
566 BidiQueue<ScoView, ScoBuilder> sco_queue_{3 /* TODO: Set queue depth */};
567 os::EnqueueBuffer<ScoView> incoming_sco_buffer_{sco_queue_.GetDownEnd()};
568
569 // ISO packets
570 BidiQueue<IsoView, IsoBuilder> iso_queue_{3 /* TODO: Set queue depth */};
571 os::EnqueueBuffer<IsoView> incoming_iso_buffer_{iso_queue_.GetDownEnd()};
572 };
573
574 // All functions here are running on the HAL thread
575 struct HciLayer::hal_callbacks : public hal::HciHalCallbacks {
hal_callbacksbluetooth::hci::HciLayer::hal_callbacks576 explicit hal_callbacks(HciLayer& module) : module_(module) {}
577
hciEventReceivedbluetooth::hci::HciLayer::hal_callbacks578 void hciEventReceived(hal::HciPacket event_bytes) override {
579 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
580 if (life_cycle_stopped) {
581 return;
582 }
583 auto packet = packet::PacketView<packet::kLittleEndian>(
584 std::make_shared<std::vector<uint8_t>>(event_bytes));
585 EventView event = EventView::Create(packet);
586 module_.CallOn(module_.impl_, &impl::on_hci_event, std::move(event));
587 }
588
aclDataReceivedbluetooth::hci::HciLayer::hal_callbacks589 void aclDataReceived(hal::HciPacket data_bytes) override {
590 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
591 if (life_cycle_stopped) {
592 return;
593 }
594 auto packet = packet::PacketView<packet::kLittleEndian>(
595 std::make_shared<std::vector<uint8_t>>(std::move(data_bytes)));
596 auto acl = std::make_unique<AclView>(AclView::Create(packet));
597 module_.impl_->incoming_acl_buffer_.Enqueue(std::move(acl), module_.GetHandler());
598 }
599
scoDataReceivedbluetooth::hci::HciLayer::hal_callbacks600 void scoDataReceived(hal::HciPacket data_bytes) override {
601 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
602 if (life_cycle_stopped) {
603 return;
604 }
605 auto packet = packet::PacketView<packet::kLittleEndian>(
606 std::make_shared<std::vector<uint8_t>>(std::move(data_bytes)));
607 auto sco = std::make_unique<ScoView>(ScoView::Create(packet));
608 module_.impl_->incoming_sco_buffer_.Enqueue(std::move(sco), module_.GetHandler());
609 }
610
isoDataReceivedbluetooth::hci::HciLayer::hal_callbacks611 void isoDataReceived(hal::HciPacket data_bytes) override {
612 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
613 if (life_cycle_stopped) {
614 return;
615 }
616 auto packet = packet::PacketView<packet::kLittleEndian>(
617 std::make_shared<std::vector<uint8_t>>(std::move(data_bytes)));
618 auto iso = std::make_unique<IsoView>(IsoView::Create(packet));
619 module_.impl_->incoming_iso_buffer_.Enqueue(std::move(iso), module_.GetHandler());
620 }
621
622 HciLayer& module_;
623 };
624
HciLayer()625 HciLayer::HciLayer() : impl_(nullptr), hal_callbacks_(nullptr) {}
626
~HciLayer()627 HciLayer::~HciLayer() {}
628
GetAclQueueEnd()629 common::BidiQueueEnd<AclBuilder, AclView>* HciLayer::GetAclQueueEnd() {
630 return impl_->acl_queue_.GetUpEnd();
631 }
632
GetScoQueueEnd()633 common::BidiQueueEnd<ScoBuilder, ScoView>* HciLayer::GetScoQueueEnd() {
634 return impl_->sco_queue_.GetUpEnd();
635 }
636
GetIsoQueueEnd()637 common::BidiQueueEnd<IsoBuilder, IsoView>* HciLayer::GetIsoQueueEnd() {
638 return impl_->iso_queue_.GetUpEnd();
639 }
640
EnqueueCommand(unique_ptr<CommandBuilder> command,ContextualOnceCallback<void (CommandCompleteView)> on_complete)641 void HciLayer::EnqueueCommand(unique_ptr<CommandBuilder> command,
642 ContextualOnceCallback<void(CommandCompleteView)> on_complete) {
643 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
644 if (life_cycle_stopped) {
645 return;
646 }
647 CallOn(impl_, &impl::enqueue_command<CommandCompleteView>, std::move(command),
648 std::move(on_complete));
649 }
650
EnqueueCommand(unique_ptr<CommandBuilder> command,ContextualOnceCallback<void (CommandStatusView)> on_status)651 void HciLayer::EnqueueCommand(unique_ptr<CommandBuilder> command,
652 ContextualOnceCallback<void(CommandStatusView)> on_status) {
653 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
654 if (life_cycle_stopped) {
655 return;
656 }
657 CallOn(impl_, &impl::enqueue_command<CommandStatusView>, std::move(command),
658 std::move(on_status));
659 }
660
EnqueueCommand(unique_ptr<CommandBuilder> command,ContextualOnceCallback<void (CommandStatusOrCompleteView)> on_status_or_complete)661 void HciLayer::EnqueueCommand(
662 unique_ptr<CommandBuilder> command,
663 ContextualOnceCallback<void(CommandStatusOrCompleteView)> on_status_or_complete) {
664 CallOn(impl_, &impl::enqueue_command<CommandStatusOrCompleteView>, std::move(command),
665 std::move(on_status_or_complete));
666 }
667
RegisterEventHandler(EventCode event,ContextualCallback<void (EventView)> handler)668 void HciLayer::RegisterEventHandler(EventCode event, ContextualCallback<void(EventView)> handler) {
669 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
670 if (life_cycle_stopped) {
671 return;
672 }
673 CallOn(impl_, &impl::register_event, event, handler);
674 }
675
UnregisterEventHandler(EventCode event)676 void HciLayer::UnregisterEventHandler(EventCode event) {
677 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
678 if (life_cycle_stopped) {
679 return;
680 }
681 CallOn(impl_, &impl::unregister_event, event);
682 }
683
RegisterLeEventHandler(SubeventCode event,ContextualCallback<void (LeMetaEventView)> handler)684 void HciLayer::RegisterLeEventHandler(SubeventCode event,
685 ContextualCallback<void(LeMetaEventView)> handler) {
686 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
687 if (life_cycle_stopped) {
688 return;
689 }
690 CallOn(impl_, &impl::register_le_event, event, handler);
691 }
692
UnregisterLeEventHandler(SubeventCode event)693 void HciLayer::UnregisterLeEventHandler(SubeventCode event) {
694 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
695 if (life_cycle_stopped) {
696 return;
697 }
698 CallOn(impl_, &impl::unregister_le_event, event);
699 }
700
RegisterVendorSpecificEventHandler(VseSubeventCode event,ContextualCallback<void (VendorSpecificEventView)> handler)701 void HciLayer::RegisterVendorSpecificEventHandler(
702 VseSubeventCode event, ContextualCallback<void(VendorSpecificEventView)> handler) {
703 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
704 if (life_cycle_stopped) {
705 return;
706 }
707 CallOn(impl_, &impl::register_vs_event, event, handler);
708 }
709
UnregisterVendorSpecificEventHandler(VseSubeventCode event)710 void HciLayer::UnregisterVendorSpecificEventHandler(VseSubeventCode event) {
711 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
712 if (life_cycle_stopped) {
713 return;
714 }
715 CallOn(impl_, &impl::unregister_vs_event, event);
716 }
717
RegisterDefaultVendorSpecificEventHandler(ContextualCallback<void (VendorSpecificEventView)> handler)718 void HciLayer::RegisterDefaultVendorSpecificEventHandler(
719 ContextualCallback<void(VendorSpecificEventView)> handler) {
720 CallOn(impl_, &impl::register_vs_event_default, handler);
721 }
722
UnregisterDefaultVendorSpecificEventHandler()723 void HciLayer::UnregisterDefaultVendorSpecificEventHandler() {
724 CallOn(impl_, &impl::unregister_vs_event_default);
725 }
726
on_disconnection_complete(EventView event_view)727 void HciLayer::on_disconnection_complete(EventView event_view) {
728 auto disconnection_view = DisconnectionCompleteView::Create(event_view);
729 if (!disconnection_view.IsValid()) {
730 log::info("Dropping invalid disconnection packet");
731 return;
732 }
733
734 uint16_t handle = disconnection_view.GetConnectionHandle();
735 ErrorCode reason = disconnection_view.GetReason();
736 Disconnect(handle, reason);
737 }
738
on_connection_request(EventView event_view)739 void HciLayer::on_connection_request(EventView event_view) {
740 auto view = ConnectionRequestView::Create(event_view);
741 if (!view.IsValid()) {
742 log::info("Dropping invalid connection request packet");
743 return;
744 }
745
746 Address address = view.GetBdAddr();
747 ClassOfDevice cod = view.GetClassOfDevice();
748 ConnectionRequestLinkType link_type = view.GetLinkType();
749 switch (link_type) {
750 case ConnectionRequestLinkType::ACL:
751 if (!on_acl_connection_request_) {
752 log::warn("No callback registered for ACL connection requests.");
753 } else {
754 on_acl_connection_request_(address, cod);
755 }
756 break;
757 case ConnectionRequestLinkType::SCO:
758 case ConnectionRequestLinkType::ESCO:
759 if (!on_sco_connection_request_) {
760 log::warn("No callback registered for SCO connection requests.");
761 } else {
762 on_sco_connection_request_(address, cod, link_type);
763 }
764 break;
765 }
766 }
767
Disconnect(uint16_t handle,ErrorCode reason)768 void HciLayer::Disconnect(uint16_t handle, ErrorCode reason) {
769 std::unique_lock<std::mutex> lock(callback_handlers_guard_);
770 for (auto callback : disconnect_handlers_) {
771 callback(handle, reason);
772 }
773 }
774
RegisterForDisconnects(ContextualCallback<void (uint16_t,ErrorCode)> on_disconnect)775 void HciLayer::RegisterForDisconnects(ContextualCallback<void(uint16_t, ErrorCode)> on_disconnect) {
776 std::unique_lock<std::mutex> lock(callback_handlers_guard_);
777 disconnect_handlers_.push_back(on_disconnect);
778 }
779
on_read_remote_version_complete(EventView event_view)780 void HciLayer::on_read_remote_version_complete(EventView event_view) {
781 auto view = ReadRemoteVersionInformationCompleteView::Create(event_view);
782 log::assert_that(view.IsValid(), "Read remote version information packet invalid");
783 ReadRemoteVersion(view.GetStatus(), view.GetConnectionHandle(), view.GetVersion(),
784 view.GetManufacturerName(), view.GetSubVersion());
785 }
786
ReadRemoteVersion(hci::ErrorCode hci_status,uint16_t handle,uint8_t version,uint16_t manufacturer_name,uint16_t sub_version)787 void HciLayer::ReadRemoteVersion(hci::ErrorCode hci_status, uint16_t handle, uint8_t version,
788 uint16_t manufacturer_name, uint16_t sub_version) {
789 std::unique_lock<std::mutex> lock(callback_handlers_guard_);
790 for (auto callback : read_remote_version_handlers_) {
791 callback(hci_status, handle, version, manufacturer_name, sub_version);
792 }
793 }
794
GetAclConnectionInterface(ContextualCallback<void (EventView)> event_handler,ContextualCallback<void (uint16_t,ErrorCode)> on_disconnect,ContextualCallback<void (Address,ClassOfDevice)> on_connection_request,ContextualCallback<void (hci::ErrorCode hci_status,uint16_t,uint8_t version,uint16_t manufacturer_name,uint16_t sub_version)> on_read_remote_version)795 AclConnectionInterface* HciLayer::GetAclConnectionInterface(
796 ContextualCallback<void(EventView)> event_handler,
797 ContextualCallback<void(uint16_t, ErrorCode)> on_disconnect,
798 ContextualCallback<void(Address, ClassOfDevice)> on_connection_request,
799 ContextualCallback<void(hci::ErrorCode hci_status, uint16_t, uint8_t version,
800 uint16_t manufacturer_name, uint16_t sub_version)>
801 on_read_remote_version) {
802 {
803 std::unique_lock<std::mutex> lock(callback_handlers_guard_);
804 disconnect_handlers_.push_back(on_disconnect);
805 read_remote_version_handlers_.push_back(on_read_remote_version);
806 on_acl_connection_request_ = on_connection_request;
807 }
808 for (const auto event : AclConnectionEvents) {
809 RegisterEventHandler(event, event_handler);
810 }
811 return &acl_connection_manager_interface_;
812 }
813
PutAclConnectionInterface()814 void HciLayer::PutAclConnectionInterface() {
815 for (const auto event : AclConnectionEvents) {
816 UnregisterEventHandler(event);
817 }
818 {
819 std::unique_lock<std::mutex> lock(callback_handlers_guard_);
820 disconnect_handlers_.clear();
821 read_remote_version_handlers_.clear();
822 }
823 }
824
GetLeAclConnectionInterface(ContextualCallback<void (LeMetaEventView)> event_handler,ContextualCallback<void (uint16_t,ErrorCode)> on_disconnect,ContextualCallback<void (hci::ErrorCode hci_status,uint16_t,uint8_t version,uint16_t manufacturer_name,uint16_t sub_version)> on_read_remote_version)825 LeAclConnectionInterface* HciLayer::GetLeAclConnectionInterface(
826 ContextualCallback<void(LeMetaEventView)> event_handler,
827 ContextualCallback<void(uint16_t, ErrorCode)> on_disconnect,
828 ContextualCallback<void(hci::ErrorCode hci_status, uint16_t, uint8_t version,
829 uint16_t manufacturer_name, uint16_t sub_version)>
830 on_read_remote_version) {
831 {
832 std::unique_lock<std::mutex> lock(callback_handlers_guard_);
833 disconnect_handlers_.push_back(on_disconnect);
834 read_remote_version_handlers_.push_back(on_read_remote_version);
835 }
836 for (const auto event : LeConnectionManagementEvents) {
837 RegisterLeEventHandler(event, event_handler);
838 }
839 return &le_acl_connection_manager_interface_;
840 }
841
PutLeAclConnectionInterface()842 void HciLayer::PutLeAclConnectionInterface() {
843 for (const auto event : LeConnectionManagementEvents) {
844 UnregisterLeEventHandler(event);
845 }
846 {
847 std::unique_lock<std::mutex> lock(callback_handlers_guard_);
848 disconnect_handlers_.clear();
849 read_remote_version_handlers_.clear();
850 }
851 }
852
RegisterForScoConnectionRequests(common::ContextualCallback<void (Address,ClassOfDevice,ConnectionRequestLinkType)> on_sco_connection_request)853 void HciLayer::RegisterForScoConnectionRequests(
854 common::ContextualCallback<void(Address, ClassOfDevice, ConnectionRequestLinkType)>
855 on_sco_connection_request) {
856 std::unique_lock<std::mutex> lock(callback_handlers_guard_);
857 on_sco_connection_request_ = on_sco_connection_request;
858 }
859
GetSecurityInterface(ContextualCallback<void (EventView)> event_handler)860 SecurityInterface* HciLayer::GetSecurityInterface(
861 ContextualCallback<void(EventView)> event_handler) {
862 for (const auto event : SecurityEvents) {
863 RegisterEventHandler(event, event_handler);
864 }
865 return &security_interface;
866 }
867
GetLeSecurityInterface(ContextualCallback<void (LeMetaEventView)> event_handler)868 LeSecurityInterface* HciLayer::GetLeSecurityInterface(
869 ContextualCallback<void(LeMetaEventView)> event_handler) {
870 for (const auto subevent : LeSecurityEvents) {
871 RegisterLeEventHandler(subevent, event_handler);
872 }
873 return &le_security_interface;
874 }
875
GetLeAdvertisingInterface(ContextualCallback<void (LeMetaEventView)> event_handler)876 LeAdvertisingInterface* HciLayer::GetLeAdvertisingInterface(
877 ContextualCallback<void(LeMetaEventView)> event_handler) {
878 for (const auto subevent : LeAdvertisingEvents) {
879 RegisterLeEventHandler(subevent, event_handler);
880 }
881 return &le_advertising_interface;
882 }
883
GetLeScanningInterface(ContextualCallback<void (LeMetaEventView)> event_handler)884 LeScanningInterface* HciLayer::GetLeScanningInterface(
885 ContextualCallback<void(LeMetaEventView)> event_handler) {
886 for (const auto subevent : LeScanningEvents) {
887 RegisterLeEventHandler(subevent, event_handler);
888 }
889 return &le_scanning_interface;
890 }
891
GetLeIsoInterface(ContextualCallback<void (LeMetaEventView)> event_handler)892 LeIsoInterface* HciLayer::GetLeIsoInterface(
893 ContextualCallback<void(LeMetaEventView)> event_handler) {
894 for (const auto subevent : LeIsoEvents) {
895 RegisterLeEventHandler(subevent, event_handler);
896 }
897 return &le_iso_interface;
898 }
899
GetDistanceMeasurementInterface(ContextualCallback<void (LeMetaEventView)> event_handler)900 DistanceMeasurementInterface* HciLayer::GetDistanceMeasurementInterface(
901 ContextualCallback<void(LeMetaEventView)> event_handler) {
902 for (const auto subevent : DistanceMeasurementEvents) {
903 RegisterLeEventHandler(subevent, event_handler);
904 }
905 return &distance_measurement_interface;
906 }
907
GetInquiryInterface(ContextualCallback<void (EventView)> event_handler)908 std::unique_ptr<InquiryInterface> HciLayer::GetInquiryInterface(
909 ContextualCallback<void(EventView)> event_handler) {
910 for (const auto event : InquiryEvents) {
911 RegisterEventHandler(event, event_handler);
912 }
913 auto cleanup = common::BindOnce(
914 [](HciLayer* hci) {
915 for (const auto event : InquiryEvents) {
916 hci->UnregisterEventHandler(event);
917 }
918 },
919 common::Unretained(this));
920 return std::make_unique<CommandInterfaceImpl<DiscoveryCommandBuilder>>(this, std::move(cleanup));
921 }
922
__anoncb6023650302() 923 const ModuleFactory HciLayer::Factory = ModuleFactory([]() { return new HciLayer(); });
924
ListDependencies(ModuleList * list) const925 void HciLayer::ListDependencies(ModuleList* list) const {
926 list->add<hal::HciHal>();
927 list->add<storage::StorageModule>();
928 }
929
Start()930 void HciLayer::Start() {
931 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
932 auto hal = GetDependency<hal::HciHal>();
933 impl_ = new impl(hal, *this);
934 hal_callbacks_ = new hal_callbacks(*this);
935 life_cycle_stopped = false;
936
937 Handler* handler = GetHandler();
938 impl_->acl_queue_.GetDownEnd()->RegisterDequeue(handler,
939 BindOn(impl_, &impl::on_outbound_acl_ready));
940 impl_->sco_queue_.GetDownEnd()->RegisterDequeue(handler,
941 BindOn(impl_, &impl::on_outbound_sco_ready));
942 impl_->iso_queue_.GetDownEnd()->RegisterDequeue(handler,
943 BindOn(impl_, &impl::on_outbound_iso_ready));
944 StartWithNoHalDependencies(handler);
945 hal->registerIncomingPacketCallback(hal_callbacks_);
946 EnqueueCommand(ResetBuilder::Create(), handler->BindOnce(&fail_if_reset_complete_not_success));
947 }
948
949 // Initialize event handlers that don't depend on the HAL
StartWithNoHalDependencies(Handler * handler)950 void HciLayer::StartWithNoHalDependencies(Handler* handler) {
951 RegisterEventHandler(EventCode::DISCONNECTION_COMPLETE,
952 handler->BindOn(this, &HciLayer::on_disconnection_complete));
953 RegisterEventHandler(EventCode::READ_REMOTE_VERSION_INFORMATION_COMPLETE,
954 handler->BindOn(this, &HciLayer::on_read_remote_version_complete));
955 auto drop_packet = handler->BindOn(impl_, &impl::drop);
956 RegisterEventHandler(EventCode::PAGE_SCAN_REPETITION_MODE_CHANGE, drop_packet);
957 RegisterEventHandler(EventCode::MAX_SLOTS_CHANGE, drop_packet);
958 RegisterEventHandler(EventCode::CONNECTION_REQUEST,
959 handler->BindOn(this, &HciLayer::on_connection_request));
960 }
961
Stop()962 void HciLayer::Stop() {
963 std::unique_lock<std::recursive_mutex> lock(life_cycle_guard);
964 auto hal = GetDependency<hal::HciHal>();
965 hal->unregisterIncomingPacketCallback();
966 delete hal_callbacks_;
967
968 impl_->acl_queue_.GetDownEnd()->UnregisterDequeue();
969 impl_->sco_queue_.GetDownEnd()->UnregisterDequeue();
970 impl_->iso_queue_.GetDownEnd()->UnregisterDequeue();
971 delete impl_;
972
973 life_cycle_stopped = true;
974 }
975
976 } // namespace hci
977 } // namespace bluetooth
978