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 "main/shim/hci_layer.h"
20
21 #include <base/functional/bind.h>
22 #include <bluetooth/log.h>
23
24 #include <algorithm>
25 #include <cstdint>
26
27 #include "common/bidi_queue.h"
28 #include "hci/hci_interface.h"
29 #include "hci/hci_packets.h"
30 #include "hci/include/packet_fragmenter.h"
31 #include "main/shim/entry.h"
32 #include "osi/include/allocator.h"
33 #include "packet/raw_builder.h"
34 #include "stack/include/bt_hdr.h"
35 #include "stack/include/bt_types.h"
36 #include "stack/include/btm_iso_api.h"
37 #include "stack/include/hcimsgs.h"
38 #include "stack/include/main_thread.h"
39
40 using namespace bluetooth;
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 {
50 void* context;
51 };
52
53 constexpr size_t kBtHdrSize = sizeof(BT_HDR);
54 constexpr size_t kCommandLengthSize = sizeof(uint8_t);
55 constexpr size_t kCommandOpcodeSize = sizeof(uint16_t);
56
57 static base::Callback<void(BT_HDR*)> send_data_upwards;
58 static const packet_fragmenter_t* packet_fragmenter;
59
60 namespace {
register_event_code(bluetooth::hci::EventCode event_code)61 bool register_event_code(bluetooth::hci::EventCode event_code) {
62 switch (event_code) {
63 // SCO
64 case bluetooth::hci::EventCode::SYNCHRONOUS_CONNECTION_COMPLETE:
65 case bluetooth::hci::EventCode::SYNCHRONOUS_CONNECTION_CHANGED:
66
67 // SecurityEvents
68 case bluetooth::hci::EventCode::ENCRYPTION_CHANGE:
69 case bluetooth::hci::EventCode::PIN_CODE_REQUEST:
70 case bluetooth::hci::EventCode::LINK_KEY_REQUEST:
71 case bluetooth::hci::EventCode::LINK_KEY_NOTIFICATION:
72 case bluetooth::hci::EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE:
73 case bluetooth::hci::EventCode::IO_CAPABILITY_REQUEST:
74 case bluetooth::hci::EventCode::IO_CAPABILITY_RESPONSE:
75 case bluetooth::hci::EventCode::REMOTE_OOB_DATA_REQUEST:
76 case bluetooth::hci::EventCode::SIMPLE_PAIRING_COMPLETE:
77 case bluetooth::hci::EventCode::USER_PASSKEY_NOTIFICATION:
78 case bluetooth::hci::EventCode::USER_CONFIRMATION_REQUEST:
79 case bluetooth::hci::EventCode::USER_PASSKEY_REQUEST:
80 case bluetooth::hci::EventCode::ENCRYPTION_CHANGE_V2:
81 return true;
82 default:
83 return false;
84 }
85 }
86
register_subevent_code(bluetooth::hci::SubeventCode subevent_code)87 static bool register_subevent_code(bluetooth::hci::SubeventCode subevent_code) {
88 switch (subevent_code) {
89 case bluetooth::hci::SubeventCode::READ_REMOTE_FEATURES_COMPLETE:
90 case bluetooth::hci::SubeventCode::LONG_TERM_KEY_REQUEST:
91 case bluetooth::hci::SubeventCode::READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
92 case bluetooth::hci::SubeventCode::GENERATE_DHKEY_COMPLETE:
93 case bluetooth::hci::SubeventCode::CHANNEL_SELECTION_ALGORITHM:
94 case bluetooth::hci::SubeventCode::CONNECTIONLESS_IQ_REPORT:
95 case bluetooth::hci::SubeventCode::CONNECTION_IQ_REPORT:
96 case bluetooth::hci::SubeventCode::CTE_REQUEST_FAILED:
97 case bluetooth::hci::SubeventCode::CIS_ESTABLISHED:
98 case bluetooth::hci::SubeventCode::CIS_REQUEST:
99 case bluetooth::hci::SubeventCode::CREATE_BIG_COMPLETE:
100 case bluetooth::hci::SubeventCode::TERMINATE_BIG_COMPLETE:
101 case bluetooth::hci::SubeventCode::BIG_SYNC_ESTABLISHED:
102 case bluetooth::hci::SubeventCode::BIG_SYNC_LOST:
103 case bluetooth::hci::SubeventCode::REQUEST_PEER_SCA_COMPLETE:
104 case bluetooth::hci::SubeventCode::PATH_LOSS_THRESHOLD:
105 return true;
106 default:
107 return false;
108 }
109 }
110
111 } // namespace
112
113 namespace cpp {
114 bluetooth::common::BidiQueueEnd<bluetooth::hci::IsoBuilder, bluetooth::hci::IsoView>*
115 hci_iso_queue_end = nullptr;
116 static bluetooth::os::EnqueueBuffer<bluetooth::hci::IsoBuilder>* pending_iso_data = nullptr;
117
MakeUniquePacket(const uint8_t * data,size_t len)118 static std::unique_ptr<bluetooth::packet::RawBuilder> MakeUniquePacket(const uint8_t* data,
119 size_t len) {
120 bluetooth::packet::RawBuilder builder;
121 std::vector<uint8_t> bytes(data, data + len);
122
123 auto payload = std::make_unique<bluetooth::packet::RawBuilder>();
124 payload->AddOctets(bytes);
125
126 return payload;
127 }
128
WrapPacketAndCopy(uint16_t event,bluetooth::hci::PacketView<bluetooth::hci::kLittleEndian> * data)129 static BT_HDR* WrapPacketAndCopy(uint16_t event,
130 bluetooth::hci::PacketView<bluetooth::hci::kLittleEndian>* data) {
131 size_t packet_size = data->size() + kBtHdrSize;
132 BT_HDR* packet = reinterpret_cast<BT_HDR*>(osi_malloc(packet_size));
133 packet->offset = 0;
134 packet->len = data->size();
135 packet->layer_specific = 0;
136 packet->event = event;
137 std::copy(data->begin(), data->end(), packet->data);
138 return packet;
139 }
140
event_callback(bluetooth::hci::EventView event_packet_view)141 static void event_callback(bluetooth::hci::EventView event_packet_view) {
142 if (!send_data_upwards) {
143 return;
144 }
145 send_data_upwards.Run(WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &event_packet_view));
146 }
147
subevent_callback(bluetooth::hci::LeMetaEventView le_meta_event_view)148 static void subevent_callback(bluetooth::hci::LeMetaEventView le_meta_event_view) {
149 if (!send_data_upwards) {
150 return;
151 }
152 send_data_upwards.Run(WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &le_meta_event_view));
153 }
154
OnTransmitPacketCommandComplete(command_complete_cb complete_callback,void * context,bluetooth::hci::CommandCompleteView view)155 static void OnTransmitPacketCommandComplete(command_complete_cb complete_callback, void* context,
156 bluetooth::hci::CommandCompleteView view) {
157 log::debug("Received cmd complete for {}", bluetooth::hci::OpCodeText(view.GetCommandOpCode()));
158 BT_HDR* response = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &view);
159 complete_callback(response, context);
160 }
161
OnTransmitPacketStatus(command_status_cb status_callback,void * context,std::unique_ptr<OsiObject> command,bluetooth::hci::CommandStatusView view)162 static void OnTransmitPacketStatus(command_status_cb status_callback, void* context,
163 std::unique_ptr<OsiObject> command,
164 bluetooth::hci::CommandStatusView view) {
165 log::debug("Received cmd status {} for {}", bluetooth::hci::ErrorCodeText(view.GetStatus()),
166 bluetooth::hci::OpCodeText(view.GetCommandOpCode()));
167 uint8_t status = static_cast<uint8_t>(view.GetStatus());
168 status_callback(status, static_cast<BT_HDR*>(command->Release()), context);
169 }
170
transmit_command(const BT_HDR * command,command_complete_cb complete_callback,command_status_cb status_callback,void * context)171 static void transmit_command(const BT_HDR* command, command_complete_cb complete_callback,
172 command_status_cb status_callback, void* context) {
173 log::assert_that(command != nullptr, "assert failed: command != nullptr");
174 const uint8_t* data = command->data + command->offset;
175 size_t len = command->len;
176 log::assert_that(len >= (kCommandOpcodeSize + kCommandLengthSize),
177 "assert failed: len >= (kCommandOpcodeSize + kCommandLengthSize)");
178
179 // little endian command opcode
180 uint16_t command_op_code = (data[1] << 8 | data[0]);
181 // Gd stack API requires opcode specification and calculates length, so
182 // no need to provide opcode or length here.
183 data += (kCommandOpcodeSize + kCommandLengthSize);
184 len -= (kCommandOpcodeSize + kCommandLengthSize);
185
186 auto op_code = static_cast<const bluetooth::hci::OpCode>(command_op_code);
187
188 auto payload = MakeUniquePacket(data, len);
189 auto packet = bluetooth::hci::CommandBuilder::Create(op_code, std::move(payload));
190
191 log::debug("Sending command {}", bluetooth::hci::OpCodeText(op_code));
192
193 if (bluetooth::hci::Checker::IsCommandStatusOpcode(op_code)) {
194 auto command_unique = std::make_unique<OsiObject>(command);
195 bluetooth::shim::GetHciLayer()->EnqueueCommand(
196 std::move(packet),
197 bluetooth::shim::GetGdShimHandler()->BindOnce(OnTransmitPacketStatus, status_callback,
198 context, std::move(command_unique)));
199 } else {
200 bluetooth::shim::GetHciLayer()->EnqueueCommand(
201 std::move(packet),
202 bluetooth::shim::GetGdShimHandler()->BindOnce(OnTransmitPacketCommandComplete,
203 complete_callback, context));
204 osi_free(const_cast<void*>(static_cast<const void*>(command)));
205 }
206 }
207
transmit_iso_fragment(const uint8_t * stream,size_t length)208 static void transmit_iso_fragment(const uint8_t* stream, size_t length) {
209 uint16_t handle_with_flags;
210 STREAM_TO_UINT16(handle_with_flags, stream);
211 auto pb_flag = static_cast<bluetooth::hci::IsoPacketBoundaryFlag>(handle_with_flags >> 12 & 0b11);
212 auto ts_flag = static_cast<bluetooth::hci::TimeStampFlag>(handle_with_flags >> 14);
213 uint16_t handle = HCID_GET_HANDLE(handle_with_flags);
214 log::assert_that(handle <= HCI_HANDLE_MAX, "Require handle <= 0x{:X}, but is 0x{:X}",
215 HCI_HANDLE_MAX, handle);
216 length -= 2;
217 // skip data total length
218 stream += 2;
219 length -= 2;
220 auto payload = MakeUniquePacket(stream, length);
221 auto iso_packet =
222 bluetooth::hci::IsoBuilder::Create(handle, pb_flag, ts_flag, std::move(payload));
223
224 pending_iso_data->Enqueue(std::move(iso_packet), bluetooth::shim::GetGdShimHandler());
225 }
226
register_event(bluetooth::hci::EventCode event_code)227 static void register_event(bluetooth::hci::EventCode event_code) {
228 auto handler = bluetooth::shim::GetGdShimHandler();
229 bluetooth::shim::GetHciLayer()->RegisterEventHandler(event_code, handler->Bind(event_callback));
230 }
231
register_le_event(bluetooth::hci::SubeventCode subevent_code)232 static void register_le_event(bluetooth::hci::SubeventCode subevent_code) {
233 auto handler = bluetooth::shim::GetGdShimHandler();
234 bluetooth::shim::GetHciLayer()->RegisterLeEventHandler(subevent_code,
235 handler->Bind(subevent_callback));
236 }
237
iso_data_callback()238 static void iso_data_callback() {
239 if (hci_iso_queue_end == nullptr) {
240 return;
241 }
242 auto packet = hci_iso_queue_end->TryDequeue();
243 log::assert_that(packet != nullptr, "assert failed: packet != nullptr");
244 if (!packet->IsValid()) {
245 log::info("Dropping invalid packet of size {}", packet->size());
246 return;
247 }
248 if (!send_data_upwards) {
249 return;
250 }
251 auto data = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_ISO, packet.get());
252 packet_fragmenter->reassemble_and_dispatch(data);
253 }
254
register_for_iso()255 static void register_for_iso() {
256 hci_iso_queue_end = bluetooth::shim::GetHciLayer()->GetIsoQueueEnd();
257 hci_iso_queue_end->RegisterDequeue(bluetooth::shim::GetGdShimHandler(),
258 bluetooth::common::Bind(iso_data_callback));
259 pending_iso_data =
260 new bluetooth::os::EnqueueBuffer<bluetooth::hci::IsoBuilder>(hci_iso_queue_end);
261 // Register ISO for disconnect notifications
262 bluetooth::shim::GetHciLayer()->RegisterForDisconnects(
263 get_main_thread()->Bind([](uint16_t handle, bluetooth::hci::ErrorCode error_code) {
264 auto iso = bluetooth::hci::IsoManager::GetInstance();
265 if (iso) {
266 auto reason = static_cast<uint8_t>(error_code);
267 log::info("ISO disconnection from GD, handle: 0x{:02x}, reason: 0x{:02x}", handle,
268 reason);
269 iso->HandleDisconnect(handle, reason);
270 }
271 }));
272 }
273
on_shutting_down()274 static void on_shutting_down() {
275 if (pending_iso_data != nullptr) {
276 pending_iso_data->Clear();
277 delete pending_iso_data;
278 pending_iso_data = nullptr;
279 }
280 if (hci_iso_queue_end != nullptr) {
281 hci_iso_queue_end->UnregisterDequeue();
282 hci_iso_queue_end = nullptr;
283 }
284 }
285
286 } // namespace cpp
287
288 using bluetooth::common::Bind;
289 using bluetooth::common::BindOnce;
290 using bluetooth::common::Unretained;
291
set_data_cb(base::Callback<void (BT_HDR *)> send_data_cb)292 static void set_data_cb(base::Callback<void(BT_HDR*)> send_data_cb) {
293 send_data_upwards = std::move(send_data_cb);
294 }
295
transmit_command(const BT_HDR * command,command_complete_cb complete_callback,command_status_cb status_callback,void * context)296 static void transmit_command(const BT_HDR* command, command_complete_cb complete_callback,
297 command_status_cb status_callback, void* context) {
298 cpp::transmit_command(command, complete_callback, status_callback, context);
299 }
300
transmit_fragment(BT_HDR * packet,bool send_transmit_finished)301 static void transmit_fragment(BT_HDR* packet, bool send_transmit_finished) {
302 uint16_t event = packet->event & MSG_EVT_MASK;
303
304 // HCI command packets are freed on a different thread when the matching
305 // event is received. Check packet->event before sending to avoid a race.
306 bool free_after_transmit = event != MSG_STACK_TO_HC_HCI_CMD && send_transmit_finished;
307
308 if (event == MSG_STACK_TO_HC_HCI_ISO) {
309 const uint8_t* stream = packet->data + packet->offset;
310 size_t length = packet->len;
311 cpp::transmit_iso_fragment(stream, length);
312 }
313
314 if (free_after_transmit) {
315 osi_free(packet);
316 }
317 }
dispatch_reassembled(BT_HDR * packet)318 static void dispatch_reassembled(BT_HDR* packet) {
319 // Only ISO should be handled here
320 log::assert_that((packet->event & MSG_EVT_MASK) == MSG_HC_TO_STACK_HCI_ISO,
321 "assert failed: (packet->event & MSG_EVT_MASK) == "
322 "MSG_HC_TO_STACK_HCI_ISO");
323 log::assert_that(!send_data_upwards.is_null(), "assert failed: !send_data_upwards.is_null()");
324 send_data_upwards.Run(packet);
325 }
326
327 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = {transmit_fragment,
328 dispatch_reassembled};
329
transmit_downward(void * raw_data,uint16_t iso_buffer_size)330 static void transmit_downward(void* raw_data, uint16_t iso_buffer_size) {
331 bluetooth::shim::GetGdShimHandler()->Call(packet_fragmenter->fragment_and_dispatch,
332 static_cast<BT_HDR*>(raw_data), iso_buffer_size);
333 }
334
335 static hci_t interface = {.set_data_cb = set_data_cb,
336 .transmit_command = transmit_command,
337 .transmit_downward = transmit_downward};
338
hci_layer_get_interface()339 const hci_t* bluetooth::shim::hci_layer_get_interface() {
340 packet_fragmenter = packet_fragmenter_get_interface();
341 packet_fragmenter->init(&packet_fragmenter_callbacks);
342 return &interface;
343 }
344
hci_on_reset_complete()345 void bluetooth::shim::hci_on_reset_complete() {
346 log::assert_that(!send_data_upwards.is_null(), "assert failed: !send_data_upwards.is_null()");
347
348 for (uint16_t event_code_raw = 0; event_code_raw < 0x100; event_code_raw++) {
349 auto event_code = static_cast<bluetooth::hci::EventCode>(event_code_raw);
350 if (!register_event_code(event_code)) {
351 continue;
352 }
353 cpp::register_event(event_code);
354 }
355
356 for (uint16_t subevent_code_raw = 0; subevent_code_raw < 0x100; subevent_code_raw++) {
357 auto subevent_code = static_cast<bluetooth::hci::SubeventCode>(subevent_code_raw);
358 if (!register_subevent_code(subevent_code)) {
359 continue;
360 }
361 cpp::register_le_event(subevent_code);
362 }
363
364 cpp::register_for_iso();
365 }
366
hci_on_shutting_down()367 void bluetooth::shim::hci_on_shutting_down() { cpp::on_shutting_down(); }
368