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