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