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