blob: 57a33616c506bbd21a0db7d43864887373c6abed [file] [log] [blame]
Dylan Tian8a6e09c2022-08-16 07:29:28 +00001/*
2 * Copyright (C) 2023 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 <aidl/Gtest.h>
18#include <aidl/Vintf.h>
19#include <aidl/android/hardware/bluetooth/BnBluetoothHciCallbacks.h>
20#include <aidl/android/hardware/bluetooth/IBluetoothHci.h>
21#include <aidl/android/hardware/bluetooth/IBluetoothHciCallbacks.h>
22#include <aidl/android/hardware/bluetooth/Status.h>
23#include <android/binder_auto_utils.h>
24#include <android/binder_manager.h>
25#include <android/binder_process.h>
26#include <binder/IServiceManager.h>
27#include <binder/ProcessState.h>
28
29#include <atomic>
30#include <chrono>
31#include <condition_variable>
32#include <future>
33#include <mutex>
34#include <queue>
35#include <thread>
36#include <vector>
37
38using aidl::android::hardware::bluetooth::IBluetoothHci;
39using aidl::android::hardware::bluetooth::IBluetoothHciCallbacks;
40using aidl::android::hardware::bluetooth::Status;
41using ndk::ScopedAStatus;
42using ndk::SpAIBinder;
43
44// Bluetooth Core Specification 3.0 + HS
45static constexpr uint8_t kHciMinimumHciVersion = 5;
46// Bluetooth Core Specification 3.0 + HS
47static constexpr uint8_t kHciMinimumLmpVersion = 5;
48
Myles Watsone1708c82023-01-18 17:07:58 -080049static constexpr size_t kNumHciCommandsBandwidth = 100;
50static constexpr size_t kNumScoPacketsBandwidth = 100;
51static constexpr size_t kNumAclPacketsBandwidth = 100;
Dylan Tian8a6e09c2022-08-16 07:29:28 +000052static constexpr std::chrono::milliseconds kWaitForInitTimeout(2000);
53static constexpr std::chrono::milliseconds kWaitForHciEventTimeout(2000);
Myles Watsone1708c82023-01-18 17:07:58 -080054static constexpr std::chrono::milliseconds kWaitForScoDataTimeout(1000);
55static constexpr std::chrono::milliseconds kWaitForAclDataTimeout(1000);
Dylan Tian8a6e09c2022-08-16 07:29:28 +000056static constexpr std::chrono::milliseconds kInterfaceCloseDelayMs(200);
57
58static constexpr uint8_t kCommandHciShouldBeUnknown[] = {
59 0xff, 0x3B, 0x08, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
60static constexpr uint8_t kCommandHciReadLocalVersionInformation[] = {0x01, 0x10,
61 0x00};
62static constexpr uint8_t kCommandHciReadBufferSize[] = {0x05, 0x10, 0x00};
Myles Watsone1708c82023-01-18 17:07:58 -080063static constexpr uint8_t kCommandHciWriteLoopbackModeLocal[] = {0x02, 0x18,
64 0x01, 0x01};
Dylan Tian8a6e09c2022-08-16 07:29:28 +000065static constexpr uint8_t kCommandHciReset[] = {0x03, 0x0c, 0x00};
Myles Watsone1708c82023-01-18 17:07:58 -080066static constexpr uint8_t kCommandHciSynchronousFlowControlEnable[] = {
67 0x2f, 0x0c, 0x01, 0x01};
68static constexpr uint8_t kCommandHciWriteLocalName[] = {0x13, 0x0c, 0xf8};
Dylan Tian8a6e09c2022-08-16 07:29:28 +000069static constexpr uint8_t kHciStatusSuccess = 0x00;
70static constexpr uint8_t kHciStatusUnknownHciCommand = 0x01;
71
Myles Watsone1708c82023-01-18 17:07:58 -080072static constexpr uint8_t kEventConnectionComplete = 0x03;
Dylan Tian8a6e09c2022-08-16 07:29:28 +000073static constexpr uint8_t kEventCommandComplete = 0x0e;
74static constexpr uint8_t kEventCommandStatus = 0x0f;
75static constexpr uint8_t kEventNumberOfCompletedPackets = 0x13;
Myles Watsone1708c82023-01-18 17:07:58 -080076static constexpr uint8_t kEventLoopbackCommand = 0x19;
Dylan Tian8a6e09c2022-08-16 07:29:28 +000077
78static constexpr size_t kEventCodeByte = 0;
Myles Watsone1708c82023-01-18 17:07:58 -080079static constexpr size_t kEventLengthByte = 1;
80static constexpr size_t kEventFirstPayloadByte = 2;
Dylan Tian8a6e09c2022-08-16 07:29:28 +000081static constexpr size_t kEventCommandStatusStatusByte = 2;
82static constexpr size_t kEventCommandStatusOpcodeLsByte = 4; // Bytes 4 and 5
83static constexpr size_t kEventCommandCompleteOpcodeLsByte = 3; // Bytes 3 and 4
84static constexpr size_t kEventCommandCompleteStatusByte = 5;
85static constexpr size_t kEventCommandCompleteFirstParamByte = 6;
86static constexpr size_t kEventLocalHciVersionByte =
87 kEventCommandCompleteFirstParamByte;
88static constexpr size_t kEventLocalLmpVersionByte =
89 kEventLocalHciVersionByte + 3;
90
Myles Watsone1708c82023-01-18 17:07:58 -080091static constexpr size_t kEventConnectionCompleteParamLength = 11;
92static constexpr size_t kEventConnectionCompleteType = 11;
93static constexpr size_t kEventConnectionCompleteTypeSco = 0;
94static constexpr size_t kEventConnectionCompleteTypeAcl = 1;
95static constexpr size_t kEventConnectionCompleteHandleLsByte = 3;
96
Dylan Tian8a6e09c2022-08-16 07:29:28 +000097static constexpr size_t kEventNumberOfCompletedPacketsNumHandles = 2;
98
Myles Watsone1708c82023-01-18 17:07:58 -080099static constexpr size_t kAclBroadcastFlagOffset = 6;
100static constexpr uint8_t kAclBroadcastFlagPointToPoint = 0x0;
101static constexpr uint8_t kAclBroadcastPointToPoint =
102 (kAclBroadcastFlagPointToPoint << kAclBroadcastFlagOffset);
103
104static constexpr uint8_t kAclPacketBoundaryFlagOffset = 4;
105static constexpr uint8_t kAclPacketBoundaryFlagFirstAutoFlushable = 0x2;
106static constexpr uint8_t kAclPacketBoundaryFirstAutoFlushable =
107 kAclPacketBoundaryFlagFirstAutoFlushable << kAclPacketBoundaryFlagOffset;
108
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000109// To discard Qualcomm ACL debugging
110static constexpr uint16_t kAclHandleQcaDebugMessage = 0xedc;
111
112class ThroughputLogger {
113 public:
114 ThroughputLogger(std::string task)
Myles Watsone1708c82023-01-18 17:07:58 -0800115 : total_bytes_(0),
116 task_(task),
117 start_time_(std::chrono::steady_clock::now()) {}
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000118
119 ~ThroughputLogger() {
120 if (total_bytes_ == 0) {
121 return;
122 }
123 std::chrono::duration<double> duration =
124 std::chrono::steady_clock::now() - start_time_;
125 double s = duration.count();
126 if (s == 0) {
127 return;
128 }
129 double rate_kb = (static_cast<double>(total_bytes_) / s) / 1024;
130 ALOGD("%s %.1f KB/s (%zu bytes in %.3fs)", task_.c_str(), rate_kb,
131 total_bytes_, s);
132 }
133
134 void setTotalBytes(size_t total_bytes) { total_bytes_ = total_bytes; }
135
136 private:
137 size_t total_bytes_;
138 std::string task_;
139 std::chrono::steady_clock::time_point start_time_;
140};
141
142// The main test class for Bluetooth HAL.
143class BluetoothAidlTest : public ::testing::TestWithParam<std::string> {
144 public:
145 virtual void SetUp() override {
146 // currently test passthrough mode only
147 hci = IBluetoothHci::fromBinder(
148 SpAIBinder(AServiceManager_waitForService(GetParam().c_str())));
149 ASSERT_NE(hci, nullptr);
150 ALOGI("%s: getService() for bluetooth hci is %s", __func__,
151 hci->isRemote() ? "remote" : "local");
152
153 // Lambda function
154 auto on_binder_death = [](void* /*cookie*/) { FAIL(); };
155
156 bluetooth_hci_death_recipient =
157 AIBinder_DeathRecipient_new(on_binder_death);
158 ASSERT_NE(bluetooth_hci_death_recipient, nullptr);
159 ASSERT_EQ(STATUS_OK,
160 AIBinder_linkToDeath(hci->asBinder().get(),
161 bluetooth_hci_death_recipient, 0));
162
163 hci_cb = ndk::SharedRefBase::make<BluetoothHciCallbacks>(*this);
164 ASSERT_NE(hci_cb, nullptr);
165
166 max_acl_data_packet_length = 0;
167 max_sco_data_packet_length = 0;
168 max_acl_data_packets = 0;
169 max_sco_data_packets = 0;
170
171 event_cb_count = 0;
172 acl_cb_count = 0;
173 sco_cb_count = 0;
174
175 ASSERT_TRUE(hci->initialize(hci_cb).isOk());
176 auto future = initialized_promise.get_future();
177 auto timeout_status = future.wait_for(kWaitForInitTimeout);
178 ASSERT_EQ(timeout_status, std::future_status::ready);
179 ASSERT_TRUE(future.get());
180 }
181
182 virtual void TearDown() override {
183 ALOGI("TearDown");
184 // Should not be checked in production code
185 ASSERT_TRUE(hci->close().isOk());
186 std::this_thread::sleep_for(kInterfaceCloseDelayMs);
187 handle_no_ops();
Myles Watsone1708c82023-01-18 17:07:58 -0800188 discard_qca_debugging();
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000189 EXPECT_EQ(static_cast<size_t>(0), event_queue.size());
190 EXPECT_EQ(static_cast<size_t>(0), sco_queue.size());
191 EXPECT_EQ(static_cast<size_t>(0), acl_queue.size());
192 EXPECT_EQ(static_cast<size_t>(0), iso_queue.size());
193 }
194
195 void setBufferSizes();
Myles Watsone1708c82023-01-18 17:07:58 -0800196 void setSynchronousFlowControlEnable();
197
198 // Functions called from within tests in loopback mode
199 void sendAndCheckHci(int num_packets);
200 void sendAndCheckSco(int num_packets, size_t size, uint16_t handle);
201 void sendAndCheckAcl(int num_packets, size_t size, uint16_t handle);
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000202
203 // Helper functions to try to get a handle on verbosity
Myles Watsone1708c82023-01-18 17:07:58 -0800204 void reset();
205 void enterLoopbackMode();
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000206 void handle_no_ops();
Myles Watsone1708c82023-01-18 17:07:58 -0800207 void discard_qca_debugging();
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000208 void wait_for_event(bool timeout_is_error);
209 void wait_for_command_complete_event(std::vector<uint8_t> cmd);
210 int wait_for_completed_packets_event(uint16_t handle);
211
212 // A simple test implementation of BluetoothHciCallbacks.
213 class BluetoothHciCallbacks
214 : public aidl::android::hardware::bluetooth::BnBluetoothHciCallbacks {
215 BluetoothAidlTest& parent_;
216
217 public:
218 BluetoothHciCallbacks(BluetoothAidlTest& parent) : parent_(parent){};
219
220 virtual ~BluetoothHciCallbacks() = default;
221
222 ndk::ScopedAStatus initializationComplete(Status status) {
223 parent_.initialized_promise.set_value(status == Status::SUCCESS);
224 ALOGV("%s (status = %d)", __func__, static_cast<int>(status));
225 return ScopedAStatus::ok();
226 };
227
228 ndk::ScopedAStatus hciEventReceived(const std::vector<uint8_t>& event) {
229 parent_.event_cb_count++;
230 parent_.event_queue.push(event);
231 ALOGV("Event received (length = %d)", static_cast<int>(event.size()));
232 return ScopedAStatus::ok();
233 };
234
235 ndk::ScopedAStatus aclDataReceived(const std::vector<uint8_t>& data) {
236 parent_.acl_cb_count++;
237 parent_.acl_queue.push(data);
238 return ScopedAStatus::ok();
239 };
240
241 ndk::ScopedAStatus scoDataReceived(const std::vector<uint8_t>& data) {
242 parent_.sco_cb_count++;
243 parent_.sco_queue.push(data);
244 return ScopedAStatus::ok();
245 };
246
247 ndk::ScopedAStatus isoDataReceived(const std::vector<uint8_t>& data) {
248 parent_.iso_cb_count++;
249 parent_.iso_queue.push(data);
250 return ScopedAStatus::ok();
251 };
252 };
253
254 template <class T>
255 class WaitQueue {
256 public:
257 WaitQueue(){};
258
259 virtual ~WaitQueue() = default;
260
261 bool empty() const {
262 std::lock_guard<std::mutex> lock(m_);
263 return q_.empty();
264 };
265
266 size_t size() const {
267 std::lock_guard<std::mutex> lock(m_);
268 return q_.size();
269 };
270
271 void push(const T& v) {
272 std::lock_guard<std::mutex> lock(m_);
273 q_.push(v);
274 ready_.notify_one();
275 };
276
277 bool pop(T& v) {
278 std::lock_guard<std::mutex> lock(m_);
279 if (q_.empty()) {
280 return false;
281 }
282 v = std::move(q_.front());
283 q_.pop();
284 return true;
285 };
286
287 bool front(T& v) {
288 std::lock_guard<std::mutex> lock(m_);
289 if (q_.empty()) {
290 return false;
291 }
292 v = q_.front();
293 return true;
294 };
295
296 void wait() {
297 std::unique_lock<std::mutex> lock(m_);
298 while (q_.empty()) {
299 ready_.wait(lock);
300 }
301 };
302
303 bool waitWithTimeout(std::chrono::milliseconds timeout) {
304 std::unique_lock<std::mutex> lock(m_);
305 while (q_.empty()) {
306 if (ready_.wait_for(lock, timeout) == std::cv_status::timeout) {
307 return false;
308 }
309 }
310 return true;
311 };
312
313 bool tryPopWithTimeout(T& v, std::chrono::milliseconds timeout) {
314 std::unique_lock<std::mutex> lock(m_);
315 while (q_.empty()) {
316 if (ready_.wait_for(lock, timeout) == std::cv_status::timeout) {
317 return false;
318 }
319 }
320 v = std::move(q_.front());
321 q_.pop();
322 return true;
323 };
324
325 private:
326 mutable std::mutex m_;
327 std::queue<T> q_;
328 std::condition_variable_any ready_;
329 };
330
331 std::shared_ptr<IBluetoothHci> hci;
332 std::shared_ptr<BluetoothHciCallbacks> hci_cb;
333 AIBinder_DeathRecipient* bluetooth_hci_death_recipient;
334 WaitQueue<std::vector<uint8_t>> event_queue;
335 WaitQueue<std::vector<uint8_t>> acl_queue;
336 WaitQueue<std::vector<uint8_t>> sco_queue;
337 WaitQueue<std::vector<uint8_t>> iso_queue;
338
339 std::promise<bool> initialized_promise;
340 int event_cb_count;
341 int sco_cb_count;
342 int acl_cb_count;
343 int iso_cb_count;
344
345 int max_acl_data_packet_length;
346 int max_sco_data_packet_length;
347 int max_acl_data_packets;
348 int max_sco_data_packets;
Myles Watsone1708c82023-01-18 17:07:58 -0800349
350 std::vector<uint16_t> sco_connection_handles;
351 std::vector<uint16_t> acl_connection_handles;
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000352};
353
354// Discard NO-OPs from the event queue.
355void BluetoothAidlTest::handle_no_ops() {
356 while (!event_queue.empty()) {
357 std::vector<uint8_t> event;
358 event_queue.front(event);
359 ASSERT_GE(event.size(),
360 static_cast<size_t>(kEventCommandCompleteStatusByte));
361 bool event_is_no_op =
362 (event[kEventCodeByte] == kEventCommandComplete) &&
363 (event[kEventCommandCompleteOpcodeLsByte] == 0x00) &&
364 (event[kEventCommandCompleteOpcodeLsByte + 1] == 0x00);
365 event_is_no_op |= (event[kEventCodeByte] == kEventCommandStatus) &&
366 (event[kEventCommandStatusOpcodeLsByte] == 0x00) &&
367 (event[kEventCommandStatusOpcodeLsByte + 1] == 0x00);
368 if (event_is_no_op) {
369 event_queue.pop(event);
370 } else {
371 break;
372 }
373 }
Myles Watsone1708c82023-01-18 17:07:58 -0800374}
375
376// Discard Qualcomm ACL debugging
377void BluetoothAidlTest::discard_qca_debugging() {
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000378 while (!acl_queue.empty()) {
379 std::vector<uint8_t> acl_packet;
380 acl_queue.front(acl_packet);
381 uint16_t connection_handle = acl_packet[1] & 0xF;
382 connection_handle <<= 8;
383 connection_handle |= acl_packet[0];
384 bool packet_is_no_op = connection_handle == kAclHandleQcaDebugMessage;
385 if (packet_is_no_op) {
386 acl_queue.pop(acl_packet);
387 } else {
388 break;
389 }
390 }
391}
392
393// Receive an event, discarding NO-OPs.
394void BluetoothAidlTest::wait_for_event(bool timeout_is_error = true) {
Myles Watsone1708c82023-01-18 17:07:58 -0800395 // Wait until we get something that's not a no-op.
396 while (true) {
397 bool event_ready = event_queue.waitWithTimeout(kWaitForHciEventTimeout);
398 ASSERT_TRUE(event_ready || !timeout_is_error);
399 if (event_queue.empty()) {
400 // waitWithTimeout timed out
401 return;
402 }
403 handle_no_ops();
404 if (!event_queue.empty()) {
405 // There's an event in the queue that's not a no-op.
406 return;
407 }
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000408 }
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000409}
410
411// Wait until a command complete is received.
412void BluetoothAidlTest::wait_for_command_complete_event(
413 std::vector<uint8_t> cmd) {
Myles Watsone1708c82023-01-18 17:07:58 -0800414 ASSERT_NO_FATAL_FAILURE(wait_for_event());
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000415 std::vector<uint8_t> event;
Myles Watsone1708c82023-01-18 17:07:58 -0800416 ASSERT_FALSE(event_queue.empty());
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000417 ASSERT_TRUE(event_queue.pop(event));
418
419 ASSERT_GT(event.size(), static_cast<size_t>(kEventCommandCompleteStatusByte));
420 ASSERT_EQ(kEventCommandComplete, event[kEventCodeByte]);
421 ASSERT_EQ(cmd[0], event[kEventCommandCompleteOpcodeLsByte]);
422 ASSERT_EQ(cmd[1], event[kEventCommandCompleteOpcodeLsByte + 1]);
423 ASSERT_EQ(kHciStatusSuccess, event[kEventCommandCompleteStatusByte]);
424}
425
426// Send the command to read the controller's buffer sizes.
427void BluetoothAidlTest::setBufferSizes() {
428 std::vector<uint8_t> cmd{
429 kCommandHciReadBufferSize,
430 kCommandHciReadBufferSize + sizeof(kCommandHciReadBufferSize)};
431 hci->sendHciCommand(cmd);
432
Myles Watsone1708c82023-01-18 17:07:58 -0800433 ASSERT_NO_FATAL_FAILURE(wait_for_event());
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000434 if (event_queue.empty()) {
435 return;
436 }
437 std::vector<uint8_t> event;
438 ASSERT_TRUE(event_queue.pop(event));
439
440 ASSERT_EQ(kEventCommandComplete, event[kEventCodeByte]);
441 ASSERT_EQ(cmd[0], event[kEventCommandCompleteOpcodeLsByte]);
442 ASSERT_EQ(cmd[1], event[kEventCommandCompleteOpcodeLsByte + 1]);
443 ASSERT_EQ(kHciStatusSuccess, event[kEventCommandCompleteStatusByte]);
444
445 max_acl_data_packet_length =
446 event[kEventCommandCompleteStatusByte + 1] +
447 (event[kEventCommandCompleteStatusByte + 2] << 8);
448 max_sco_data_packet_length = event[kEventCommandCompleteStatusByte + 3];
449 max_acl_data_packets = event[kEventCommandCompleteStatusByte + 4] +
450 (event[kEventCommandCompleteStatusByte + 5] << 8);
451 max_sco_data_packets = event[kEventCommandCompleteStatusByte + 6] +
452 (event[kEventCommandCompleteStatusByte + 7] << 8);
453
454 ALOGD("%s: ACL max %d num %d SCO max %d num %d", __func__,
455 static_cast<int>(max_acl_data_packet_length),
456 static_cast<int>(max_acl_data_packets),
457 static_cast<int>(max_sco_data_packet_length),
458 static_cast<int>(max_sco_data_packets));
459}
460
Myles Watsone1708c82023-01-18 17:07:58 -0800461// Enable flow control packets for SCO
462void BluetoothAidlTest::setSynchronousFlowControlEnable() {
463 std::vector<uint8_t> cmd{kCommandHciSynchronousFlowControlEnable,
464 kCommandHciSynchronousFlowControlEnable +
465 sizeof(kCommandHciSynchronousFlowControlEnable)};
466 hci->sendHciCommand(cmd);
467
468 wait_for_command_complete_event(cmd);
469}
470
471// Send an HCI command (in Loopback mode) and check the response.
472void BluetoothAidlTest::sendAndCheckHci(int num_packets) {
473 ThroughputLogger logger = {__func__};
474 int command_size = 0;
475 for (int n = 0; n < num_packets; n++) {
476 // Send an HCI packet
477 std::vector<uint8_t> write_name{
478 kCommandHciWriteLocalName,
479 kCommandHciWriteLocalName + sizeof(kCommandHciWriteLocalName)};
480 // With a name
481 char new_name[] = "John Jacob Jingleheimer Schmidt ___________________0";
482 size_t new_name_length = strlen(new_name);
483 for (size_t i = 0; i < new_name_length; i++) {
484 write_name.push_back(static_cast<uint8_t>(new_name[i]));
485 }
486 // And the packet number
487 size_t i = new_name_length - 1;
488 for (int digits = n; digits > 0; digits = digits / 10, i--) {
489 write_name[i] = static_cast<uint8_t>('0' + digits % 10);
490 }
491 // And padding
492 for (size_t i = 0; i < 248 - new_name_length; i++) {
493 write_name.push_back(static_cast<uint8_t>(0));
494 }
495
496 hci->sendHciCommand(write_name);
497
498 // Check the loopback of the HCI packet
499 ASSERT_NO_FATAL_FAILURE(wait_for_event());
500
501 std::vector<uint8_t> event;
502 ASSERT_TRUE(event_queue.pop(event));
503
504 size_t compare_length = (write_name.size() > static_cast<size_t>(0xff)
505 ? static_cast<size_t>(0xff)
506 : write_name.size());
507 ASSERT_GT(event.size(), compare_length + kEventFirstPayloadByte - 1);
508
509 ASSERT_EQ(kEventLoopbackCommand, event[kEventCodeByte]);
510 ASSERT_EQ(compare_length, event[kEventLengthByte]);
511
512 // Don't compare past the end of the event.
513 if (compare_length + kEventFirstPayloadByte > event.size()) {
514 compare_length = event.size() - kEventFirstPayloadByte;
515 ALOGE("Only comparing %d bytes", static_cast<int>(compare_length));
516 }
517
518 if (n == num_packets - 1) {
519 command_size = write_name.size();
520 }
521
522 for (size_t i = 0; i < compare_length; i++) {
523 ASSERT_EQ(write_name[i], event[kEventFirstPayloadByte + i]);
524 }
525 }
526 logger.setTotalBytes(command_size * num_packets * 2);
527}
528
529// Send a SCO data packet (in Loopback mode) and check the response.
530void BluetoothAidlTest::sendAndCheckSco(int num_packets, size_t size,
531 uint16_t handle) {
532 ThroughputLogger logger = {__func__};
533 for (int n = 0; n < num_packets; n++) {
534 // Send a SCO packet
535 std::vector<uint8_t> sco_packet;
536 sco_packet.push_back(static_cast<uint8_t>(handle & 0xff));
537 sco_packet.push_back(static_cast<uint8_t>((handle & 0x0f00) >> 8));
538 sco_packet.push_back(static_cast<uint8_t>(size & 0xff));
539 for (size_t i = 0; i < size; i++) {
540 sco_packet.push_back(static_cast<uint8_t>(i + n));
541 }
542 hci->sendScoData(sco_packet);
543
544 // Check the loopback of the SCO packet
545 std::vector<uint8_t> sco_loopback;
546 ASSERT_TRUE(
547 sco_queue.tryPopWithTimeout(sco_loopback, kWaitForScoDataTimeout));
548
549 ASSERT_EQ(sco_packet.size(), sco_loopback.size());
550 size_t successful_bytes = 0;
551
552 for (size_t i = 0; i < sco_packet.size(); i++) {
553 if (sco_packet[i] == sco_loopback[i]) {
554 successful_bytes = i;
555 } else {
556 ALOGE("Miscompare at %d (expected %x, got %x)", static_cast<int>(i),
557 sco_packet[i], sco_loopback[i]);
558 ALOGE("At %d (expected %x, got %x)", static_cast<int>(i + 1),
559 sco_packet[i + 1], sco_loopback[i + 1]);
560 break;
561 }
562 }
563 ASSERT_EQ(sco_packet.size(), successful_bytes + 1);
564 }
565 logger.setTotalBytes(num_packets * size * 2);
566}
567
568// Send an ACL data packet (in Loopback mode) and check the response.
569void BluetoothAidlTest::sendAndCheckAcl(int num_packets, size_t size,
570 uint16_t handle) {
571 ThroughputLogger logger = {__func__};
572 for (int n = 0; n < num_packets; n++) {
573 // Send an ACL packet
574 std::vector<uint8_t> acl_packet;
575 acl_packet.push_back(static_cast<uint8_t>(handle & 0xff));
576 acl_packet.push_back(static_cast<uint8_t>((handle & 0x0f00) >> 8) |
577 kAclBroadcastPointToPoint |
578 kAclPacketBoundaryFirstAutoFlushable);
579 acl_packet.push_back(static_cast<uint8_t>(size & 0xff));
580 acl_packet.push_back(static_cast<uint8_t>((size & 0xff00) >> 8));
581 for (size_t i = 0; i < size; i++) {
582 acl_packet.push_back(static_cast<uint8_t>(i + n));
583 }
584 hci->sendAclData(acl_packet);
585
586 std::vector<uint8_t> acl_loopback;
587 // Check the loopback of the ACL packet
588 ASSERT_TRUE(
589 acl_queue.tryPopWithTimeout(acl_loopback, kWaitForAclDataTimeout));
590
591 ASSERT_EQ(acl_packet.size(), acl_loopback.size());
592 size_t successful_bytes = 0;
593
594 for (size_t i = 0; i < acl_packet.size(); i++) {
595 if (acl_packet[i] == acl_loopback[i]) {
596 successful_bytes = i;
597 } else {
598 ALOGE("Miscompare at %d (expected %x, got %x)", static_cast<int>(i),
599 acl_packet[i], acl_loopback[i]);
600 ALOGE("At %d (expected %x, got %x)", static_cast<int>(i + 1),
601 acl_packet[i + 1], acl_loopback[i + 1]);
602 break;
603 }
604 }
605 ASSERT_EQ(acl_packet.size(), successful_bytes + 1);
606 }
607 logger.setTotalBytes(num_packets * size * 2);
608}
609
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000610// Return the number of completed packets reported by the controller.
611int BluetoothAidlTest::wait_for_completed_packets_event(uint16_t handle) {
612 int packets_processed = 0;
613 wait_for_event(false);
614 if (event_queue.empty()) {
615 ALOGW("%s: waitForBluetoothCallback timed out.", __func__);
616 return packets_processed;
617 }
618 while (!event_queue.empty()) {
619 std::vector<uint8_t> event;
620 EXPECT_TRUE(event_queue.pop(event));
621
622 EXPECT_EQ(kEventNumberOfCompletedPackets, event[kEventCodeByte]);
623 EXPECT_EQ(1, event[kEventNumberOfCompletedPacketsNumHandles]);
624
625 uint16_t event_handle = event[3] + (event[4] << 8);
626 EXPECT_EQ(handle, event_handle);
627
628 packets_processed += event[5] + (event[6] << 8);
629 }
630 return packets_processed;
631}
632
Myles Watsone1708c82023-01-18 17:07:58 -0800633// Send the reset command and wait for a response.
634void BluetoothAidlTest::reset() {
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000635 std::vector<uint8_t> reset{kCommandHciReset,
636 kCommandHciReset + sizeof(kCommandHciReset)};
637 hci->sendHciCommand(reset);
638
639 wait_for_command_complete_event(reset);
640}
641
Myles Watsone1708c82023-01-18 17:07:58 -0800642// Send local loopback command and initialize SCO and ACL handles.
643void BluetoothAidlTest::enterLoopbackMode() {
644 std::vector<uint8_t> cmd{kCommandHciWriteLoopbackModeLocal,
645 kCommandHciWriteLoopbackModeLocal +
646 sizeof(kCommandHciWriteLoopbackModeLocal)};
647 hci->sendHciCommand(cmd);
648
649 // Receive connection complete events with data channels
650 int connection_event_count = 0;
651 bool command_complete_received = false;
652 while (true) {
653 wait_for_event(false);
654 if (event_queue.empty()) {
655 // Fail if there was no event received or no connections completed.
656 ASSERT_TRUE(command_complete_received);
657 ASSERT_LT(0, connection_event_count);
658 return;
659 }
660 std::vector<uint8_t> event;
661 ASSERT_TRUE(event_queue.pop(event));
662 ASSERT_GT(event.size(),
663 static_cast<size_t>(kEventCommandCompleteStatusByte));
664 if (event[kEventCodeByte] == kEventConnectionComplete) {
665 ASSERT_GT(event.size(),
666 static_cast<size_t>(kEventConnectionCompleteType));
667 ASSERT_EQ(event[kEventLengthByte], kEventConnectionCompleteParamLength);
668 uint8_t connection_type = event[kEventConnectionCompleteType];
669
670 ASSERT_TRUE(connection_type == kEventConnectionCompleteTypeSco ||
671 connection_type == kEventConnectionCompleteTypeAcl);
672
673 // Save handles
674 uint16_t handle = event[kEventConnectionCompleteHandleLsByte] |
675 event[kEventConnectionCompleteHandleLsByte + 1] << 8;
676 if (connection_type == kEventConnectionCompleteTypeSco) {
677 sco_connection_handles.push_back(handle);
678 } else {
679 acl_connection_handles.push_back(handle);
680 }
681
682 ALOGD("Connect complete type = %d handle = %d",
683 event[kEventConnectionCompleteType], handle);
684 connection_event_count++;
685 } else {
686 ASSERT_EQ(kEventCommandComplete, event[kEventCodeByte]);
687 ASSERT_EQ(cmd[0], event[kEventCommandCompleteOpcodeLsByte]);
688 ASSERT_EQ(cmd[1], event[kEventCommandCompleteOpcodeLsByte + 1]);
689 ASSERT_EQ(kHciStatusSuccess, event[kEventCommandCompleteStatusByte]);
690 command_complete_received = true;
691 }
692 }
693}
694
695// Empty test: Initialize()/Close() are called in SetUp()/TearDown().
696TEST_P(BluetoothAidlTest, InitializeAndClose) {}
697
698// Send an HCI Reset with sendHciCommand and wait for a command complete event.
699TEST_P(BluetoothAidlTest, HciReset) { reset(); }
700
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000701// Read and check the HCI version of the controller.
702TEST_P(BluetoothAidlTest, HciVersionTest) {
Myles Watsone1708c82023-01-18 17:07:58 -0800703 reset();
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000704 std::vector<uint8_t> cmd{kCommandHciReadLocalVersionInformation,
705 kCommandHciReadLocalVersionInformation +
706 sizeof(kCommandHciReadLocalVersionInformation)};
707 hci->sendHciCommand(cmd);
708
Myles Watsone1708c82023-01-18 17:07:58 -0800709 ASSERT_NO_FATAL_FAILURE(wait_for_event());
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000710
711 std::vector<uint8_t> event;
712 ASSERT_TRUE(event_queue.pop(event));
713 ASSERT_GT(event.size(), static_cast<size_t>(kEventLocalLmpVersionByte));
714
715 ASSERT_EQ(kEventCommandComplete, event[kEventCodeByte]);
716 ASSERT_EQ(cmd[0], event[kEventCommandCompleteOpcodeLsByte]);
717 ASSERT_EQ(cmd[1], event[kEventCommandCompleteOpcodeLsByte + 1]);
718 ASSERT_EQ(kHciStatusSuccess, event[kEventCommandCompleteStatusByte]);
719
720 ASSERT_LE(kHciMinimumHciVersion, event[kEventLocalHciVersionByte]);
721 ASSERT_LE(kHciMinimumLmpVersion, event[kEventLocalLmpVersionByte]);
722}
723
724// Send an unknown HCI command and wait for the error message.
725TEST_P(BluetoothAidlTest, HciUnknownCommand) {
Myles Watsone1708c82023-01-18 17:07:58 -0800726 reset();
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000727 std::vector<uint8_t> cmd{
728 kCommandHciShouldBeUnknown,
729 kCommandHciShouldBeUnknown + sizeof(kCommandHciShouldBeUnknown)};
730 hci->sendHciCommand(cmd);
731
Myles Watsone1708c82023-01-18 17:07:58 -0800732 ASSERT_NO_FATAL_FAILURE(wait_for_event());
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000733
734 std::vector<uint8_t> event;
735 ASSERT_TRUE(event_queue.pop(event));
736
737 ASSERT_GT(event.size(), static_cast<size_t>(kEventCommandCompleteStatusByte));
738 if (event[kEventCodeByte] == kEventCommandComplete) {
739 ASSERT_EQ(cmd[0], event[kEventCommandCompleteOpcodeLsByte]);
740 ASSERT_EQ(cmd[1], event[kEventCommandCompleteOpcodeLsByte + 1]);
741 ASSERT_EQ(kHciStatusUnknownHciCommand,
742 event[kEventCommandCompleteStatusByte]);
743 } else {
744 ASSERT_EQ(kEventCommandStatus, event[kEventCodeByte]);
745 ASSERT_EQ(cmd[0], event[kEventCommandStatusOpcodeLsByte]);
746 ASSERT_EQ(cmd[1], event[kEventCommandStatusOpcodeLsByte + 1]);
747 ASSERT_EQ(kHciStatusUnknownHciCommand,
748 event[kEventCommandStatusStatusByte]);
749 }
750}
751
Myles Watsone1708c82023-01-18 17:07:58 -0800752// Enter loopback mode, but don't send any packets.
753TEST_P(BluetoothAidlTest, WriteLoopbackMode) {
754 reset();
755 enterLoopbackMode();
756}
757
758// Enter loopback mode and send a single command.
759TEST_P(BluetoothAidlTest, LoopbackModeSingleCommand) {
760 reset();
761 setBufferSizes();
762
763 enterLoopbackMode();
764
765 sendAndCheckHci(1);
766}
767
768// Enter loopback mode and send a single SCO packet.
769TEST_P(BluetoothAidlTest, LoopbackModeSingleSco) {
770 reset();
771 setBufferSizes();
772 setSynchronousFlowControlEnable();
773
774 enterLoopbackMode();
775
776 if (!sco_connection_handles.empty()) {
777 ASSERT_LT(0, max_sco_data_packet_length);
778 sendAndCheckSco(1, max_sco_data_packet_length, sco_connection_handles[0]);
779 int sco_packets_sent = 1;
780 int completed_packets =
781 wait_for_completed_packets_event(sco_connection_handles[0]);
782 if (sco_packets_sent != completed_packets) {
783 ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
784 sco_packets_sent, completed_packets);
785 }
786 }
787}
788
789// Enter loopback mode and send a single ACL packet.
790TEST_P(BluetoothAidlTest, LoopbackModeSingleAcl) {
791 reset();
792 setBufferSizes();
793
794 enterLoopbackMode();
795
796 if (!acl_connection_handles.empty()) {
797 ASSERT_LT(0, max_acl_data_packet_length);
798 sendAndCheckAcl(1, max_acl_data_packet_length - 1,
799 acl_connection_handles[0]);
800 int acl_packets_sent = 1;
801 int completed_packets =
802 wait_for_completed_packets_event(acl_connection_handles[0]);
803 if (acl_packets_sent != completed_packets) {
804 ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
805 acl_packets_sent, completed_packets);
806 }
807 }
808 ASSERT_GE(acl_cb_count, 1);
809}
810
811// Enter loopback mode and send command packets for bandwidth measurements.
812TEST_P(BluetoothAidlTest, LoopbackModeCommandBandwidth) {
813 reset();
814 setBufferSizes();
815
816 enterLoopbackMode();
817
818 sendAndCheckHci(kNumHciCommandsBandwidth);
819}
820
821// Enter loopback mode and send SCO packets for bandwidth measurements.
822TEST_P(BluetoothAidlTest, LoopbackModeScoBandwidth) {
823 reset();
824 setBufferSizes();
825 setSynchronousFlowControlEnable();
826
827 enterLoopbackMode();
828
829 if (!sco_connection_handles.empty()) {
830 ASSERT_LT(0, max_sco_data_packet_length);
831 sendAndCheckSco(kNumScoPacketsBandwidth, max_sco_data_packet_length,
832 sco_connection_handles[0]);
833 int sco_packets_sent = kNumScoPacketsBandwidth;
834 int completed_packets =
835 wait_for_completed_packets_event(sco_connection_handles[0]);
836 if (sco_packets_sent != completed_packets) {
837 ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
838 sco_packets_sent, completed_packets);
839 }
840 }
841}
842
843// Enter loopback mode and send packets for ACL bandwidth measurements.
844TEST_P(BluetoothAidlTest, LoopbackModeAclBandwidth) {
845 reset();
846 setBufferSizes();
847
848 enterLoopbackMode();
849
850 if (!acl_connection_handles.empty()) {
851 ASSERT_LT(0, max_acl_data_packet_length);
852 sendAndCheckAcl(kNumAclPacketsBandwidth, max_acl_data_packet_length - 1,
853 acl_connection_handles[0]);
854 int acl_packets_sent = kNumAclPacketsBandwidth;
855 int completed_packets =
856 wait_for_completed_packets_event(acl_connection_handles[0]);
857 if (acl_packets_sent != completed_packets) {
858 ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
859 acl_packets_sent, completed_packets);
860 }
861 }
862}
863
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000864// Set all bits in the event mask
865TEST_P(BluetoothAidlTest, SetEventMask) {
Myles Watsone1708c82023-01-18 17:07:58 -0800866 reset();
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000867 std::vector<uint8_t> set_event_mask{
868 0x01, 0x0c, 0x08 /*parameter bytes*/, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
869 0xff, 0xff};
870 hci->sendHciCommand({set_event_mask});
871 wait_for_command_complete_event(set_event_mask);
872}
873
874// Set all bits in the LE event mask
875TEST_P(BluetoothAidlTest, SetLeEventMask) {
Myles Watsone1708c82023-01-18 17:07:58 -0800876 reset();
Dylan Tian8a6e09c2022-08-16 07:29:28 +0000877 std::vector<uint8_t> set_event_mask{
878 0x20, 0x0c, 0x08 /*parameter bytes*/, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
879 0xff, 0xff};
880 hci->sendHciCommand({set_event_mask});
881 wait_for_command_complete_event(set_event_mask);
882}
883
884GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(BluetoothAidlTest);
885INSTANTIATE_TEST_SUITE_P(PerInstance, BluetoothAidlTest,
886 testing::ValuesIn(android::getAidlHalInstanceNames(
887 IBluetoothHci::descriptor)),
888 android::PrintInstanceNameToString);
889
890int main(int argc, char** argv) {
891 ABinderProcess_startThreadPool();
892 ::testing::InitGoogleTest(&argc, argv);
893 int status = RUN_ALL_TESTS();
894 ALOGI("Test result = %d", status);
895 return status;
896}