• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define LOG_TAG "bt_shim_hci"
18 
19 #include "hci/hci_layer.h"
20 
21 #include <base/bind.h>
22 
23 #include <algorithm>
24 #include <cstdint>
25 
26 #include "callbacks/callbacks.h"
27 #include "gd/common/init_flags.h"
28 #include "hci/hci_packets.h"
29 #include "hci/include/packet_fragmenter.h"
30 #include "hci/le_acl_connection_interface.h"
31 #include "hci/vendor_specific_event_manager.h"
32 #include "main/shim/hci_layer.h"
33 #include "main/shim/shim.h"
34 #include "main/shim/stack.h"
35 #include "osi/include/allocator.h"
36 #include "osi/include/future.h"
37 #include "packet/raw_builder.h"
38 #include "src/bridge.rs.h"
39 #include "stack/include/bt_hdr.h"
40 #include "stack/include/bt_types.h"
41 
42 /**
43  * Callback data wrapped as opaque token bundled with the command
44  * transmit request to the Gd layer.
45  *
46  * Upon completion a token for a corresponding command transmit.
47  * request is returned from the Gd layer.
48  */
49 using CommandCallbackData = struct { void* context; };
50 
51 constexpr size_t kBtHdrSize = sizeof(BT_HDR);
52 constexpr size_t kCommandLengthSize = sizeof(uint8_t);
53 constexpr size_t kCommandOpcodeSize = sizeof(uint16_t);
54 
55 static base::Callback<void(const base::Location&, BT_HDR*)> send_data_upwards;
56 static const packet_fragmenter_t* packet_fragmenter;
57 
58 namespace {
is_valid_event_code(bluetooth::hci::EventCode event_code)59 bool is_valid_event_code(bluetooth::hci::EventCode event_code) {
60   switch (event_code) {
61     case bluetooth::hci::EventCode::INQUIRY_COMPLETE:
62     case bluetooth::hci::EventCode::INQUIRY_RESULT:
63     case bluetooth::hci::EventCode::CONNECTION_COMPLETE:
64     case bluetooth::hci::EventCode::CONNECTION_REQUEST:
65     case bluetooth::hci::EventCode::DISCONNECTION_COMPLETE:
66     case bluetooth::hci::EventCode::AUTHENTICATION_COMPLETE:
67     case bluetooth::hci::EventCode::REMOTE_NAME_REQUEST_COMPLETE:
68     case bluetooth::hci::EventCode::ENCRYPTION_CHANGE:
69     case bluetooth::hci::EventCode::CHANGE_CONNECTION_LINK_KEY_COMPLETE:
70     case bluetooth::hci::EventCode::CENTRAL_LINK_KEY_COMPLETE:
71     case bluetooth::hci::EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
72     case bluetooth::hci::EventCode::READ_REMOTE_VERSION_INFORMATION_COMPLETE:
73     case bluetooth::hci::EventCode::QOS_SETUP_COMPLETE:
74     case bluetooth::hci::EventCode::COMMAND_COMPLETE:
75     case bluetooth::hci::EventCode::COMMAND_STATUS:
76     case bluetooth::hci::EventCode::HARDWARE_ERROR:
77     case bluetooth::hci::EventCode::FLUSH_OCCURRED:
78     case bluetooth::hci::EventCode::ROLE_CHANGE:
79     case bluetooth::hci::EventCode::NUMBER_OF_COMPLETED_PACKETS:
80     case bluetooth::hci::EventCode::MODE_CHANGE:
81     case bluetooth::hci::EventCode::RETURN_LINK_KEYS:
82     case bluetooth::hci::EventCode::PIN_CODE_REQUEST:
83     case bluetooth::hci::EventCode::LINK_KEY_REQUEST:
84     case bluetooth::hci::EventCode::LINK_KEY_NOTIFICATION:
85     case bluetooth::hci::EventCode::LOOPBACK_COMMAND:
86     case bluetooth::hci::EventCode::DATA_BUFFER_OVERFLOW:
87     case bluetooth::hci::EventCode::MAX_SLOTS_CHANGE:
88     case bluetooth::hci::EventCode::READ_CLOCK_OFFSET_COMPLETE:
89     case bluetooth::hci::EventCode::CONNECTION_PACKET_TYPE_CHANGED:
90     case bluetooth::hci::EventCode::QOS_VIOLATION:
91     case bluetooth::hci::EventCode::PAGE_SCAN_REPETITION_MODE_CHANGE:
92     case bluetooth::hci::EventCode::FLOW_SPECIFICATION_COMPLETE:
93     case bluetooth::hci::EventCode::INQUIRY_RESULT_WITH_RSSI:
94     case bluetooth::hci::EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
95     case bluetooth::hci::EventCode::SYNCHRONOUS_CONNECTION_COMPLETE:
96     case bluetooth::hci::EventCode::SYNCHRONOUS_CONNECTION_CHANGED:
97     case bluetooth::hci::EventCode::SNIFF_SUBRATING:
98     case bluetooth::hci::EventCode::EXTENDED_INQUIRY_RESULT:
99     case bluetooth::hci::EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE:
100     case bluetooth::hci::EventCode::IO_CAPABILITY_REQUEST:
101     case bluetooth::hci::EventCode::IO_CAPABILITY_RESPONSE:
102     case bluetooth::hci::EventCode::USER_CONFIRMATION_REQUEST:
103     case bluetooth::hci::EventCode::USER_PASSKEY_REQUEST:
104     case bluetooth::hci::EventCode::REMOTE_OOB_DATA_REQUEST:
105     case bluetooth::hci::EventCode::SIMPLE_PAIRING_COMPLETE:
106     case bluetooth::hci::EventCode::LINK_SUPERVISION_TIMEOUT_CHANGED:
107     case bluetooth::hci::EventCode::ENHANCED_FLUSH_COMPLETE:
108     case bluetooth::hci::EventCode::USER_PASSKEY_NOTIFICATION:
109     case bluetooth::hci::EventCode::KEYPRESS_NOTIFICATION:
110     case bluetooth::hci::EventCode::REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION:
111     case bluetooth::hci::EventCode::NUMBER_OF_COMPLETED_DATA_BLOCKS:
112       return true;
113     case bluetooth::hci::EventCode::VENDOR_SPECIFIC:
114     case bluetooth::hci::EventCode::LE_META_EVENT:  // Private to hci
115       return false;
116   }
117   return false;
118 };
119 
is_valid_subevent_code(bluetooth::hci::SubeventCode subevent_code)120 bool is_valid_subevent_code(bluetooth::hci::SubeventCode subevent_code) {
121   switch (subevent_code) {
122     case bluetooth::hci::SubeventCode::CONNECTION_COMPLETE:
123     case bluetooth::hci::SubeventCode::CONNECTION_UPDATE_COMPLETE:
124     case bluetooth::hci::SubeventCode::DATA_LENGTH_CHANGE:
125     case bluetooth::hci::SubeventCode::ENHANCED_CONNECTION_COMPLETE:
126     case bluetooth::hci::SubeventCode::PHY_UPDATE_COMPLETE:
127     case bluetooth::hci::SubeventCode::READ_REMOTE_FEATURES_COMPLETE:
128     case bluetooth::hci::SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST:
129     case bluetooth::hci::SubeventCode::READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
130     case bluetooth::hci::SubeventCode::GENERATE_DHKEY_COMPLETE:
131     case bluetooth::hci::SubeventCode::DIRECTED_ADVERTISING_REPORT:
132     case bluetooth::hci::SubeventCode::EXTENDED_ADVERTISING_REPORT:
133     case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED:
134     case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_REPORT:
135     case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_LOST:
136     case bluetooth::hci::SubeventCode::SCAN_TIMEOUT:
137     case bluetooth::hci::SubeventCode::ADVERTISING_SET_TERMINATED:
138     case bluetooth::hci::SubeventCode::SCAN_REQUEST_RECEIVED:
139     case bluetooth::hci::SubeventCode::CHANNEL_SELECTION_ALGORITHM:
140     case bluetooth::hci::SubeventCode::CONNECTIONLESS_IQ_REPORT:
141     case bluetooth::hci::SubeventCode::CONNECTION_IQ_REPORT:
142     case bluetooth::hci::SubeventCode::CTE_REQUEST_FAILED:
143     case bluetooth::hci::SubeventCode::
144         PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED:
145     case bluetooth::hci::SubeventCode::CIS_ESTABLISHED:
146     case bluetooth::hci::SubeventCode::CIS_REQUEST:
147     case bluetooth::hci::SubeventCode::CREATE_BIG_COMPLETE:
148     case bluetooth::hci::SubeventCode::TERMINATE_BIG_COMPLETE:
149     case bluetooth::hci::SubeventCode::BIG_SYNC_ESTABLISHED:
150     case bluetooth::hci::SubeventCode::BIG_SYNC_LOST:
151     case bluetooth::hci::SubeventCode::REQUEST_PEER_SCA_COMPLETE:
152     case bluetooth::hci::SubeventCode::PATH_LOSS_THRESHOLD:
153     case bluetooth::hci::SubeventCode::TRANSMIT_POWER_REPORTING:
154     case bluetooth::hci::SubeventCode::BIG_INFO_ADVERTISING_REPORT:
155     case bluetooth::hci::SubeventCode::ADVERTISING_REPORT:
156     case bluetooth::hci::SubeventCode::LONG_TERM_KEY_REQUEST:
157       return true;
158     default:
159       return false;
160   }
161 }
162 
event_already_registered_in_hci_layer(bluetooth::hci::EventCode event_code)163 static bool event_already_registered_in_hci_layer(
164     bluetooth::hci::EventCode event_code) {
165   switch (event_code) {
166     case bluetooth::hci::EventCode::COMMAND_COMPLETE:
167     case bluetooth::hci::EventCode::COMMAND_STATUS:
168     case bluetooth::hci::EventCode::PAGE_SCAN_REPETITION_MODE_CHANGE:
169     case bluetooth::hci::EventCode::MAX_SLOTS_CHANGE:
170     case bluetooth::hci::EventCode::LE_META_EVENT:
171     case bluetooth::hci::EventCode::DISCONNECTION_COMPLETE:
172     case bluetooth::hci::EventCode::READ_REMOTE_VERSION_INFORMATION_COMPLETE:
173       return true;
174     default:
175       return false;
176   }
177 }
178 
event_already_registered_in_controller_layer(bluetooth::hci::EventCode event_code)179 static bool event_already_registered_in_controller_layer(
180     bluetooth::hci::EventCode event_code) {
181   switch (event_code) {
182     case bluetooth::hci::EventCode::NUMBER_OF_COMPLETED_PACKETS:
183       return true;
184     default:
185       return false;
186   }
187 }
188 
event_already_registered_in_acl_layer(bluetooth::hci::EventCode event_code)189 static bool event_already_registered_in_acl_layer(
190     bluetooth::hci::EventCode event_code) {
191   for (auto event : bluetooth::hci::AclConnectionEvents) {
192     if (event == event_code) {
193       return true;
194     }
195   }
196   return false;
197 }
198 
subevent_already_registered_in_le_hci_layer(bluetooth::hci::SubeventCode subevent_code)199 static bool subevent_already_registered_in_le_hci_layer(
200     bluetooth::hci::SubeventCode subevent_code) {
201   switch (subevent_code) {
202     case bluetooth::hci::SubeventCode::CONNECTION_COMPLETE:
203     case bluetooth::hci::SubeventCode::CONNECTION_UPDATE_COMPLETE:
204     case bluetooth::hci::SubeventCode::DATA_LENGTH_CHANGE:
205     case bluetooth::hci::SubeventCode::ENHANCED_CONNECTION_COMPLETE:
206     case bluetooth::hci::SubeventCode::PHY_UPDATE_COMPLETE:
207     case bluetooth::hci::SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST:
208     case bluetooth::hci::SubeventCode::ADVERTISING_SET_TERMINATED:
209     case bluetooth::hci::SubeventCode::SCAN_REQUEST_RECEIVED:
210     case bluetooth::hci::SubeventCode::SCAN_TIMEOUT:
211     case bluetooth::hci::SubeventCode::ADVERTISING_REPORT:
212     case bluetooth::hci::SubeventCode::DIRECTED_ADVERTISING_REPORT:
213     case bluetooth::hci::SubeventCode::EXTENDED_ADVERTISING_REPORT:
214     case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_REPORT:
215     case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED:
216     case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_LOST:
217     case bluetooth::hci::SubeventCode::
218         PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED:
219       return true;
220     case bluetooth::hci::SubeventCode::READ_REMOTE_FEATURES_COMPLETE:
221     case bluetooth::hci::SubeventCode::READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
222     case bluetooth::hci::SubeventCode::GENERATE_DHKEY_COMPLETE:
223     case bluetooth::hci::SubeventCode::CHANNEL_SELECTION_ALGORITHM:
224     case bluetooth::hci::SubeventCode::CONNECTIONLESS_IQ_REPORT:
225     case bluetooth::hci::SubeventCode::CONNECTION_IQ_REPORT:
226     case bluetooth::hci::SubeventCode::CTE_REQUEST_FAILED:
227     case bluetooth::hci::SubeventCode::CIS_ESTABLISHED:
228     case bluetooth::hci::SubeventCode::CIS_REQUEST:
229     case bluetooth::hci::SubeventCode::CREATE_BIG_COMPLETE:
230     case bluetooth::hci::SubeventCode::TERMINATE_BIG_COMPLETE:
231     case bluetooth::hci::SubeventCode::BIG_SYNC_ESTABLISHED:
232     case bluetooth::hci::SubeventCode::BIG_SYNC_LOST:
233     case bluetooth::hci::SubeventCode::REQUEST_PEER_SCA_COMPLETE:
234     case bluetooth::hci::SubeventCode::PATH_LOSS_THRESHOLD:
235     case bluetooth::hci::SubeventCode::TRANSMIT_POWER_REPORTING:
236     case bluetooth::hci::SubeventCode::BIG_INFO_ADVERTISING_REPORT:
237     case bluetooth::hci::SubeventCode::LONG_TERM_KEY_REQUEST:
238     default:
239       return false;
240   }
241 }
242 
event_already_registered_in_le_advertising_manager(bluetooth::hci::EventCode event_code)243 static bool event_already_registered_in_le_advertising_manager(
244     bluetooth::hci::EventCode event_code) {
245   for (auto event : bluetooth::hci::AclConnectionEvents) {
246     if (event == event_code) {
247       return true;
248     }
249   }
250   return false;
251 }
252 
event_already_registered_in_le_scanning_manager(bluetooth::hci::EventCode event_code)253 static bool event_already_registered_in_le_scanning_manager(
254     bluetooth::hci::EventCode event_code) {
255   for (auto event : bluetooth::hci::AclConnectionEvents) {
256     if (event == event_code) {
257       return true;
258     }
259   }
260   return false;
261 }
262 
263 }  // namespace
264 
265 namespace cpp {
266 bluetooth::common::BidiQueueEnd<bluetooth::hci::AclBuilder,
267                                 bluetooth::hci::AclView>* hci_queue_end =
268     nullptr;
269 bluetooth::common::BidiQueueEnd<bluetooth::hci::ScoBuilder,
270                                 bluetooth::hci::ScoView>* hci_sco_queue_end =
271     nullptr;
272 bluetooth::common::BidiQueueEnd<bluetooth::hci::IsoBuilder,
273                                 bluetooth::hci::IsoView>* hci_iso_queue_end =
274     nullptr;
275 static bluetooth::os::EnqueueBuffer<bluetooth::hci::AclBuilder>* pending_data =
276     nullptr;
277 static bluetooth::os::EnqueueBuffer<bluetooth::hci::IsoBuilder>*
278     pending_iso_data = nullptr;
279 static bluetooth::os::EnqueueBuffer<bluetooth::hci::ScoBuilder>*
280     pending_sco_data = nullptr;
281 
MakeUniquePacket(const uint8_t * data,size_t len)282 static std::unique_ptr<bluetooth::packet::RawBuilder> MakeUniquePacket(
283     const uint8_t* data, size_t len) {
284   bluetooth::packet::RawBuilder builder;
285   std::vector<uint8_t> bytes(data, data + len);
286 
287   auto payload = std::make_unique<bluetooth::packet::RawBuilder>();
288   payload->AddOctets(bytes);
289 
290   return payload;
291 }
292 
WrapPacketAndCopy(uint16_t event,bluetooth::hci::PacketView<bluetooth::hci::kLittleEndian> * data)293 static BT_HDR* WrapPacketAndCopy(
294     uint16_t event,
295     bluetooth::hci::PacketView<bluetooth::hci::kLittleEndian>* data) {
296   size_t packet_size = data->size() + kBtHdrSize;
297   BT_HDR* packet = reinterpret_cast<BT_HDR*>(osi_malloc(packet_size));
298   packet->offset = 0;
299   packet->len = data->size();
300   packet->layer_specific = 0;
301   packet->event = event;
302   std::copy(data->begin(), data->end(), packet->data);
303   return packet;
304 }
305 
event_callback(bluetooth::hci::EventView event_packet_view)306 static void event_callback(bluetooth::hci::EventView event_packet_view) {
307   if (!send_data_upwards) {
308     return;
309   }
310   send_data_upwards.Run(FROM_HERE, WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT,
311                                                      &event_packet_view));
312 }
313 
subevent_callback(bluetooth::hci::LeMetaEventView le_meta_event_view)314 static void subevent_callback(
315     bluetooth::hci::LeMetaEventView le_meta_event_view) {
316   if (!send_data_upwards) {
317     return;
318   }
319   send_data_upwards.Run(FROM_HERE, WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT,
320                                                      &le_meta_event_view));
321 }
322 
vendor_specific_event_callback(bluetooth::hci::VendorSpecificEventView vendor_specific_event_view)323 static void vendor_specific_event_callback(
324     bluetooth::hci::VendorSpecificEventView vendor_specific_event_view) {
325   if (!send_data_upwards) {
326     return;
327   }
328   send_data_upwards.Run(
329       FROM_HERE,
330       WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &vendor_specific_event_view));
331 }
332 
OnTransmitPacketCommandComplete(command_complete_cb complete_callback,void * context,bluetooth::hci::CommandCompleteView view)333 void OnTransmitPacketCommandComplete(command_complete_cb complete_callback,
334                                      void* context,
335                                      bluetooth::hci::CommandCompleteView view) {
336   LOG_DEBUG("Received cmd complete for %s",
337             bluetooth::hci::OpCodeText(view.GetCommandOpCode()).c_str());
338   std::vector<uint8_t> data(view.begin(), view.end());
339   BT_HDR* response = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &view);
340   complete_callback(response, context);
341 }
342 
OnTransmitPacketStatus(command_status_cb status_callback,void * context,std::unique_ptr<OsiObject> command,bluetooth::hci::CommandStatusView view)343 void OnTransmitPacketStatus(command_status_cb status_callback, void* context,
344                             std::unique_ptr<OsiObject> command,
345                             bluetooth::hci::CommandStatusView view) {
346   LOG_DEBUG("Received cmd status %s for %s",
347             bluetooth::hci::ErrorCodeText(view.GetStatus()).c_str(),
348             bluetooth::hci::OpCodeText(view.GetCommandOpCode()).c_str());
349   uint8_t status = static_cast<uint8_t>(view.GetStatus());
350   status_callback(status, static_cast<BT_HDR*>(command->Release()), context);
351 }
352 
transmit_command(const BT_HDR * command,command_complete_cb complete_callback,command_status_cb status_callback,void * context)353 static void transmit_command(const BT_HDR* command,
354                              command_complete_cb complete_callback,
355                              command_status_cb status_callback, void* context) {
356   CHECK(command != nullptr);
357   const uint8_t* data = command->data + command->offset;
358   size_t len = command->len;
359   CHECK(len >= (kCommandOpcodeSize + kCommandLengthSize));
360 
361   // little endian command opcode
362   uint16_t command_op_code = (data[1] << 8 | data[0]);
363   // Gd stack API requires opcode specification and calculates length, so
364   // no need to provide opcode or length here.
365   data += (kCommandOpcodeSize + kCommandLengthSize);
366   len -= (kCommandOpcodeSize + kCommandLengthSize);
367 
368   auto op_code = static_cast<const bluetooth::hci::OpCode>(command_op_code);
369 
370   auto payload = MakeUniquePacket(data, len);
371   auto packet =
372       bluetooth::hci::CommandBuilder::Create(op_code, std::move(payload));
373 
374   LOG_DEBUG("Sending command %s", bluetooth::hci::OpCodeText(op_code).c_str());
375 
376   if (bluetooth::hci::Checker::IsCommandStatusOpcode(op_code)) {
377     auto command_unique = std::make_unique<OsiObject>(command);
378     bluetooth::shim::GetHciLayer()->EnqueueCommand(
379         std::move(packet), bluetooth::shim::GetGdShimHandler()->BindOnce(
380                                OnTransmitPacketStatus, status_callback, context,
381                                std::move(command_unique)));
382   } else {
383     bluetooth::shim::GetHciLayer()->EnqueueCommand(
384         std::move(packet),
385         bluetooth::shim::GetGdShimHandler()->BindOnce(
386             OnTransmitPacketCommandComplete, complete_callback, context));
387     osi_free(const_cast<void*>(static_cast<const void*>(command)));
388   }
389 }
390 
transmit_fragment(const uint8_t * stream,size_t length)391 static void transmit_fragment(const uint8_t* stream, size_t length) {
392   uint16_t handle_with_flags;
393   STREAM_TO_UINT16(handle_with_flags, stream);
394   auto pb_flag = static_cast<bluetooth::hci::PacketBoundaryFlag>(
395       handle_with_flags >> 12 & 0b11);
396   auto bc_flag =
397       static_cast<bluetooth::hci::BroadcastFlag>(handle_with_flags >> 14);
398   uint16_t handle = handle_with_flags & 0xFFF;
399   ASSERT_LOG(handle <= 0xEFF, "Require handle <= 0xEFF, but is 0x%X", handle);
400   length -= 2;
401   // skip data total length
402   stream += 2;
403   length -= 2;
404   auto payload = MakeUniquePacket(stream, length);
405   auto acl_packet = bluetooth::hci::AclBuilder::Create(handle, pb_flag, bc_flag,
406                                                        std::move(payload));
407   pending_data->Enqueue(std::move(acl_packet),
408                         bluetooth::shim::GetGdShimHandler());
409 }
410 
transmit_sco_fragment(const uint8_t * stream,size_t length)411 static void transmit_sco_fragment(const uint8_t* stream, size_t length) {
412   uint16_t handle_with_flags;
413   STREAM_TO_UINT16(handle_with_flags, stream);
414   uint16_t handle = handle_with_flags & 0xFFF;
415   ASSERT_LOG(handle <= 0xEFF, "Require handle <= 0xEFF, but is 0x%X", handle);
416   length -= 2;
417   // skip data total length
418   stream += 1;
419   length -= 1;
420   auto payload = std::vector<uint8_t>(stream, stream + length);
421   auto sco_packet = bluetooth::hci::ScoBuilder::Create(
422       handle, bluetooth::hci::PacketStatusFlag::CORRECTLY_RECEIVED,
423       std::move(payload));
424 
425   pending_sco_data->Enqueue(std::move(sco_packet),
426                             bluetooth::shim::GetGdShimHandler());
427 }
428 
transmit_iso_fragment(const uint8_t * stream,size_t length)429 static void transmit_iso_fragment(const uint8_t* stream, size_t length) {
430   uint16_t handle_with_flags;
431   STREAM_TO_UINT16(handle_with_flags, stream);
432   auto pb_flag = static_cast<bluetooth::hci::IsoPacketBoundaryFlag>(
433       handle_with_flags >> 12 & 0b11);
434   auto ts_flag =
435       static_cast<bluetooth::hci::TimeStampFlag>(handle_with_flags >> 14);
436   uint16_t handle = handle_with_flags & 0xFFF;
437   ASSERT_LOG(handle <= 0xEFF, "Require handle <= 0xEFF, but is 0x%X", handle);
438   length -= 2;
439   // skip data total length
440   stream += 2;
441   length -= 2;
442   auto payload = MakeUniquePacket(stream, length);
443   auto iso_packet = bluetooth::hci::IsoBuilder::Create(handle, pb_flag, ts_flag,
444                                                        std::move(payload));
445 
446   pending_iso_data->Enqueue(std::move(iso_packet),
447                             bluetooth::shim::GetGdShimHandler());
448 }
449 
register_event(bluetooth::hci::EventCode event_code)450 static void register_event(bluetooth::hci::EventCode event_code) {
451   auto handler = bluetooth::shim::GetGdShimHandler();
452   bluetooth::shim::GetHciLayer()->RegisterEventHandler(
453       event_code, handler->Bind(event_callback));
454 }
455 
register_le_event(bluetooth::hci::SubeventCode subevent_code)456 static void register_le_event(bluetooth::hci::SubeventCode subevent_code) {
457   auto handler = bluetooth::shim::GetGdShimHandler();
458   bluetooth::shim::GetHciLayer()->RegisterLeEventHandler(
459       subevent_code, handler->Bind(subevent_callback));
460 }
461 
sco_data_callback()462 static void sco_data_callback() {
463   if (hci_sco_queue_end == nullptr) {
464     return;
465   }
466   auto packet = hci_sco_queue_end->TryDequeue();
467   ASSERT(packet != nullptr);
468   if (!packet->IsValid()) {
469     LOG_INFO("Dropping invalid packet of size %zu", packet->size());
470     return;
471   }
472   if (!send_data_upwards) {
473     return;
474   }
475   auto data = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_SCO, packet.get());
476   packet_fragmenter->reassemble_and_dispatch(data);
477 }
478 
iso_data_callback()479 static void iso_data_callback() {
480   if (hci_iso_queue_end == nullptr) {
481     return;
482   }
483   auto packet = hci_iso_queue_end->TryDequeue();
484   ASSERT(packet != nullptr);
485   if (!packet->IsValid()) {
486     LOG_INFO("Dropping invalid packet of size %zu", packet->size());
487     return;
488   }
489   if (!send_data_upwards) {
490     return;
491   }
492   auto data = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_ISO, packet.get());
493   packet_fragmenter->reassemble_and_dispatch(data);
494 }
495 
register_for_sco()496 static void register_for_sco() {
497   hci_sco_queue_end = bluetooth::shim::GetHciLayer()->GetScoQueueEnd();
498   hci_sco_queue_end->RegisterDequeue(
499       bluetooth::shim::GetGdShimHandler(),
500       bluetooth::common::Bind(sco_data_callback));
501   pending_sco_data =
502       new bluetooth::os::EnqueueBuffer<bluetooth::hci::ScoBuilder>(
503           hci_sco_queue_end);
504 }
505 
register_for_iso()506 static void register_for_iso() {
507   hci_iso_queue_end = bluetooth::shim::GetHciLayer()->GetIsoQueueEnd();
508   hci_iso_queue_end->RegisterDequeue(
509       bluetooth::shim::GetGdShimHandler(),
510       bluetooth::common::Bind(iso_data_callback));
511   pending_iso_data =
512       new bluetooth::os::EnqueueBuffer<bluetooth::hci::IsoBuilder>(
513           hci_iso_queue_end);
514 }
515 
on_shutting_down()516 static void on_shutting_down() {
517   if (pending_data != nullptr) {
518     pending_data->Clear();
519     delete pending_data;
520     pending_data = nullptr;
521   }
522   if (pending_sco_data != nullptr) {
523     pending_sco_data->Clear();
524     delete pending_sco_data;
525     pending_sco_data = nullptr;
526   }
527   if (pending_iso_data != nullptr) {
528     pending_iso_data->Clear();
529     delete pending_iso_data;
530     pending_iso_data = nullptr;
531   }
532   if (hci_queue_end != nullptr) {
533     for (uint16_t event_code_raw = 0; event_code_raw < 0x100;
534          event_code_raw++) {
535       auto event_code = static_cast<bluetooth::hci::EventCode>(event_code_raw);
536       if (!is_valid_event_code(event_code)) {
537         continue;
538       }
539       if (event_already_registered_in_hci_layer(event_code)) {
540         continue;
541       } else if (event_already_registered_in_le_advertising_manager(
542                      event_code)) {
543         continue;
544       } else if (event_already_registered_in_le_scanning_manager(event_code)) {
545         continue;
546       }
547       bluetooth::shim::GetHciLayer()->UnregisterEventHandler(event_code);
548     }
549     hci_queue_end = nullptr;
550   }
551   if (hci_sco_queue_end != nullptr) {
552     hci_sco_queue_end->UnregisterDequeue();
553     hci_sco_queue_end = nullptr;
554   }
555   if (hci_iso_queue_end != nullptr) {
556     hci_iso_queue_end->UnregisterDequeue();
557     hci_iso_queue_end = nullptr;
558   }
559 }
560 
561 }  // namespace cpp
562 
563 using bluetooth::common::Bind;
564 using bluetooth::common::BindOnce;
565 using bluetooth::common::Unretained;
566 
567 namespace rust {
568 
569 using bluetooth::shim::rust::u8SliceCallback;
570 using bluetooth::shim::rust::u8SliceOnceCallback;
571 
WrapRustPacketAndCopy(uint16_t event,::rust::Slice<const uint8_t> * data)572 static BT_HDR* WrapRustPacketAndCopy(uint16_t event,
573                                      ::rust::Slice<const uint8_t>* data) {
574   size_t packet_size = data->length() + kBtHdrSize;
575   BT_HDR* packet = reinterpret_cast<BT_HDR*>(osi_malloc(packet_size));
576   packet->offset = 0;
577   packet->len = data->length();
578   packet->layer_specific = 0;
579   packet->event = event;
580   std::copy(data->data(), data->data() + data->length(), packet->data);
581   return packet;
582 }
583 
on_sco(::rust::Slice<const uint8_t> data)584 static void on_sco(::rust::Slice<const uint8_t> data) {
585   if (!send_data_upwards) {
586     return;
587   }
588   auto legacy_data = WrapRustPacketAndCopy(MSG_HC_TO_STACK_HCI_SCO, &data);
589   packet_fragmenter->reassemble_and_dispatch(legacy_data);
590 }
591 
on_iso(::rust::Slice<const uint8_t> data)592 static void on_iso(::rust::Slice<const uint8_t> data) {
593   if (!send_data_upwards) {
594     return;
595   }
596   auto legacy_data = WrapRustPacketAndCopy(MSG_HC_TO_STACK_HCI_ISO, &data);
597   packet_fragmenter->reassemble_and_dispatch(legacy_data);
598 }
599 
on_event(::rust::Slice<const uint8_t> data)600 static void on_event(::rust::Slice<const uint8_t> data) {
601   if (!send_data_upwards) {
602     return;
603   }
604   send_data_upwards.Run(FROM_HERE,
605                         WrapRustPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &data));
606 }
607 
OnRustTransmitPacketCommandComplete(command_complete_cb complete_callback,void * context,::rust::Slice<const uint8_t> data)608 void OnRustTransmitPacketCommandComplete(command_complete_cb complete_callback,
609                                          void* context,
610                                          ::rust::Slice<const uint8_t> data) {
611   BT_HDR* response = WrapRustPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &data);
612   complete_callback(response, context);
613 }
614 
OnRustTransmitPacketStatus(command_status_cb status_callback,void * context,std::unique_ptr<OsiObject> command,::rust::Slice<const uint8_t> data)615 void OnRustTransmitPacketStatus(command_status_cb status_callback,
616                                 void* context,
617                                 std::unique_ptr<OsiObject> command,
618                                 ::rust::Slice<const uint8_t> data) {
619   ASSERT(data.length() >= 3);
620   uint8_t status = data.data()[2];
621   status_callback(status, static_cast<BT_HDR*>(command->Release()), context);
622 }
623 
transmit_command(const BT_HDR * command,command_complete_cb complete_callback,command_status_cb status_callback,void * context)624 static void transmit_command(const BT_HDR* command,
625                              command_complete_cb complete_callback,
626                              command_status_cb status_callback, void* context) {
627   CHECK(command != nullptr);
628   const uint8_t* data = command->data + command->offset;
629   size_t len = command->len;
630   CHECK(len >= (kCommandOpcodeSize + kCommandLengthSize));
631 
632   // little endian command opcode
633   uint16_t command_op_code = (data[1] << 8 | data[0]);
634   auto op_code = static_cast<const bluetooth::hci::OpCode>(command_op_code);
635 
636   LOG_DEBUG("Sending command %s", bluetooth::hci::OpCodeText(op_code).c_str());
637 
638   if (bluetooth::hci::Checker::IsCommandStatusOpcode(op_code)) {
639     auto command_unique = std::make_unique<OsiObject>(command);
640     bluetooth::shim::rust::hci_send_command(
641         **bluetooth::shim::Stack::Stack::GetInstance()->GetRustHci(),
642         ::rust::Slice(data, len),
643         std::make_unique<u8SliceOnceCallback>(
644             BindOnce(OnRustTransmitPacketStatus, status_callback, context,
645                      std::move(command_unique))));
646   } else {
647     bluetooth::shim::rust::hci_send_command(
648         **bluetooth::shim::Stack::Stack::GetInstance()->GetRustHci(),
649         ::rust::Slice(data, len),
650         std::make_unique<u8SliceOnceCallback>(BindOnce(
651             OnRustTransmitPacketCommandComplete, complete_callback, context)));
652     osi_free(const_cast<void*>(static_cast<const void*>(command)));
653   }
654 }
655 
transmit_fragment(const uint8_t * stream,size_t length)656 static void transmit_fragment(const uint8_t* stream, size_t length) {
657   bluetooth::shim::rust::hci_send_acl(
658       **bluetooth::shim::Stack::Stack::GetInstance()->GetRustHci(),
659       ::rust::Slice(stream, length));
660 }
661 
transmit_sco_fragment(const uint8_t * stream,size_t length)662 static void transmit_sco_fragment(const uint8_t* stream, size_t length) {
663   bluetooth::shim::rust::hci_send_sco(
664       **bluetooth::shim::Stack::Stack::GetInstance()->GetRustHci(),
665       ::rust::Slice(stream, length));
666 }
667 
transmit_iso_fragment(const uint8_t * stream,size_t length)668 static void transmit_iso_fragment(const uint8_t* stream, size_t length) {
669   bluetooth::shim::rust::hci_send_iso(
670       **bluetooth::shim::Stack::Stack::GetInstance()->GetRustHci(),
671       ::rust::Slice(stream, length));
672 }
673 
register_event(bluetooth::hci::EventCode event_code)674 static void register_event(bluetooth::hci::EventCode event_code) {
675   bluetooth::shim::rust::hci_register_event(
676       **bluetooth::shim::Stack::GetInstance()->GetRustHci(),
677       static_cast<uint8_t>(event_code));
678 }
679 
register_le_event(bluetooth::hci::SubeventCode subevent_code)680 static void register_le_event(bluetooth::hci::SubeventCode subevent_code) {
681   bluetooth::shim::rust::hci_register_le_event(
682       **bluetooth::shim::Stack::Stack::GetInstance()->GetRustHci(),
683       static_cast<uint8_t>(subevent_code));
684 }
685 
hci_on_reset_complete()686 static void hci_on_reset_complete() {
687   bluetooth::shim::rust::hci_set_evt_callback(
688       **bluetooth::shim::Stack::GetInstance()->GetRustHci(),
689       std::make_unique<u8SliceCallback>(Bind(rust::on_event)));
690   bluetooth::shim::rust::hci_set_le_evt_callback(
691       **bluetooth::shim::Stack::GetInstance()->GetRustHci(),
692       std::make_unique<u8SliceCallback>(Bind(rust::on_event)));
693 }
694 
register_for_sco()695 static void register_for_sco() {
696   bluetooth::shim::rust::hci_set_sco_callback(
697       **bluetooth::shim::Stack::GetInstance()->GetRustHci(),
698       std::make_unique<u8SliceCallback>(Bind(rust::on_sco)));
699 }
700 
register_for_iso()701 static void register_for_iso() {
702   bluetooth::shim::rust::hci_set_iso_callback(
703       **bluetooth::shim::Stack::GetInstance()->GetRustHci(),
704       std::make_unique<u8SliceCallback>(Bind(rust::on_iso)));
705 }
706 
on_shutting_down()707 static void on_shutting_down() {}
708 
709 }  // namespace rust
710 
set_data_cb(base::Callback<void (const base::Location &,BT_HDR *)> send_data_cb)711 static void set_data_cb(
712     base::Callback<void(const base::Location&, BT_HDR*)> send_data_cb) {
713   send_data_upwards = std::move(send_data_cb);
714 }
715 
transmit_command(const BT_HDR * command,command_complete_cb complete_callback,command_status_cb status_callback,void * context)716 static void transmit_command(const BT_HDR* command,
717                              command_complete_cb complete_callback,
718                              command_status_cb status_callback, void* context) {
719   if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
720     rust::transmit_command(command, complete_callback, status_callback,
721                            context);
722   } else {
723     cpp::transmit_command(command, complete_callback, status_callback, context);
724   }
725 }
726 
command_complete_callback(BT_HDR * response,void * context)727 static void command_complete_callback(BT_HDR* response, void* context) {
728   auto future = static_cast<future_t*>(context);
729   future_ready(future, response);
730 }
731 
command_status_callback(uint8_t status,BT_HDR * command,void * context)732 static void command_status_callback(uint8_t status, BT_HDR* command,
733                                     void* context) {
734   LOG_ALWAYS_FATAL(
735       "transmit_command_futured should only send command complete opcode");
736 }
737 
transmit_command_futured(const BT_HDR * command)738 static future_t* transmit_command_futured(const BT_HDR* command) {
739   future_t* future = future_new();
740   transmit_command(command, command_complete_callback, command_status_callback,
741                    future);
742   return future;
743 }
744 
transmit_fragment(BT_HDR * packet,bool send_transmit_finished)745 static void transmit_fragment(BT_HDR* packet, bool send_transmit_finished) {
746   uint16_t event = packet->event & MSG_EVT_MASK;
747 
748   // HCI command packets are freed on a different thread when the matching
749   // event is received. Check packet->event before sending to avoid a race.
750   bool free_after_transmit =
751       event != MSG_STACK_TO_HC_HCI_CMD && send_transmit_finished;
752 
753   if (event == MSG_STACK_TO_HC_HCI_ACL) {
754     const uint8_t* stream = packet->data + packet->offset;
755     size_t length = packet->len;
756     if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
757       rust::transmit_fragment(stream, length);
758     } else {
759       cpp::transmit_fragment(stream, length);
760     }
761   } else if (event == MSG_STACK_TO_HC_HCI_SCO) {
762     const uint8_t* stream = packet->data + packet->offset;
763     size_t length = packet->len;
764     if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
765       rust::transmit_sco_fragment(stream, length);
766     } else {
767       cpp::transmit_sco_fragment(stream, length);
768     }
769   } else if (event == MSG_STACK_TO_HC_HCI_ISO) {
770     const uint8_t* stream = packet->data + packet->offset;
771     size_t length = packet->len;
772     if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
773       rust::transmit_iso_fragment(stream, length);
774     } else {
775       cpp::transmit_iso_fragment(stream, length);
776     }
777   }
778 
779   if (free_after_transmit) {
780     osi_free(packet);
781   }
782 }
dispatch_reassembled(BT_HDR * packet)783 static void dispatch_reassembled(BT_HDR* packet) {
784   // Events should already have been dispatched before this point
785   CHECK((packet->event & MSG_EVT_MASK) != MSG_HC_TO_STACK_HCI_EVT);
786   CHECK(!send_data_upwards.is_null());
787   send_data_upwards.Run(FROM_HERE, packet);
788 }
fragmenter_transmit_finished(BT_HDR * packet,bool all_fragments_sent)789 static void fragmenter_transmit_finished(BT_HDR* packet,
790                                          bool all_fragments_sent) {
791   if (all_fragments_sent) {
792     osi_free(packet);
793   } else {
794     // This is kind of a weird case, since we're dispatching a partially sent
795     // packet up to a higher layer.
796     // TODO(zachoverflow): rework upper layer so this isn't necessary.
797     send_data_upwards.Run(FROM_HERE, packet);
798   }
799 }
800 
801 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = {
802     transmit_fragment, dispatch_reassembled, fragmenter_transmit_finished};
803 
transmit_downward(uint16_t type,void * raw_data)804 static void transmit_downward(uint16_t type, void* raw_data) {
805   if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
806     packet_fragmenter->fragment_and_dispatch(static_cast<BT_HDR*>(raw_data));
807   } else {
808     bluetooth::shim::GetGdShimHandler()->Call(
809         packet_fragmenter->fragment_and_dispatch,
810         static_cast<BT_HDR*>(raw_data));
811   }
812 }
813 
814 static hci_t interface = {.set_data_cb = set_data_cb,
815                           .transmit_command = transmit_command,
816                           .transmit_command_futured = transmit_command_futured,
817                           .transmit_downward = transmit_downward};
818 
hci_layer_get_interface()819 const hci_t* bluetooth::shim::hci_layer_get_interface() {
820   packet_fragmenter = packet_fragmenter_get_interface();
821   packet_fragmenter->init(&packet_fragmenter_callbacks);
822   return &interface;
823 }
824 
hci_on_reset_complete()825 void bluetooth::shim::hci_on_reset_complete() {
826   ASSERT(send_data_upwards);
827   if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
828     ::rust::hci_on_reset_complete();
829   }
830 
831   for (uint16_t event_code_raw = 0; event_code_raw < 0x100; event_code_raw++) {
832     auto event_code = static_cast<bluetooth::hci::EventCode>(event_code_raw);
833     if (!is_valid_event_code(event_code)) {
834       continue;
835     }
836     if (event_already_registered_in_acl_layer(event_code)) {
837       continue;
838     } else if (event_already_registered_in_controller_layer(event_code)) {
839       continue;
840     } else if (event_already_registered_in_hci_layer(event_code)) {
841       continue;
842     } else if (event_already_registered_in_le_advertising_manager(event_code)) {
843       continue;
844     } else if (event_already_registered_in_le_scanning_manager(event_code)) {
845       continue;
846     }
847 
848     if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
849       ::rust::register_event(event_code);
850     } else {
851       cpp::register_event(event_code);
852     }
853   }
854 
855   for (uint16_t subevent_code_raw = 0; subevent_code_raw < 0x100;
856        subevent_code_raw++) {
857     auto subevent_code =
858         static_cast<bluetooth::hci::SubeventCode>(subevent_code_raw);
859     if (!is_valid_subevent_code(subevent_code)) {
860       continue;
861     }
862     if (subevent_already_registered_in_le_hci_layer(subevent_code)) {
863       continue;
864     }
865 
866     if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
867       ::rust::register_le_event(subevent_code);
868     } else {
869       cpp::register_le_event(subevent_code);
870     }
871   }
872 
873   // TODO handle BQR event in GD
874   if (!bluetooth::common::init_flags::gd_rust_is_enabled()) {
875     auto handler = bluetooth::shim::GetGdShimHandler();
876     bluetooth::shim::GetVendorSpecificEventManager()->RegisterEventHandler(
877         bluetooth::hci::VseSubeventCode::BQR_EVENT,
878         handler->Bind(cpp::vendor_specific_event_callback));
879   }
880 
881   if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
882     ::rust::register_for_sco();
883   } else {
884     cpp::register_for_sco();
885   }
886 
887   if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
888     ::rust::register_for_iso();
889   } else {
890     cpp::register_for_iso();
891   }
892 }
893 
hci_on_shutting_down()894 void bluetooth::shim::hci_on_shutting_down() {
895   if (bluetooth::common::init_flags::gd_rust_is_enabled()) {
896     ::rust::on_shutting_down();
897   } else {
898     cpp::on_shutting_down();
899   }
900 }
901