1 /*
2  * Copyright (C) 2016 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 "bluetooth_hidl_hal_test"
18 #include <android-base/logging.h>
19 
20 #include <android/hardware/bluetooth/1.0/IBluetoothHci.h>
21 #include <android/hardware/bluetooth/1.0/IBluetoothHciCallbacks.h>
22 #include <android/hardware/bluetooth/1.0/types.h>
23 #include <hardware/bluetooth.h>
24 #include <utils/Log.h>
25 
26 #include <VtsHalHidlTargetCallbackBase.h>
27 #include <gtest/gtest.h>
28 #include <hidl/GtestPrinter.h>
29 #include <hidl/ServiceManagement.h>
30 
31 #include <chrono>
32 #include <queue>
33 #include <thread>
34 
35 using ::android::sp;
36 using ::android::hardware::hidl_death_recipient;
37 using ::android::hardware::hidl_vec;
38 using ::android::hardware::Return;
39 using ::android::hardware::Void;
40 using ::android::hardware::bluetooth::V1_0::IBluetoothHci;
41 using ::android::hardware::bluetooth::V1_0::IBluetoothHciCallbacks;
42 using ::android::hardware::bluetooth::V1_0::Status;
43 
44 #define HCI_MINIMUM_HCI_VERSION 5  // Bluetooth Core Specification 3.0 + HS
45 #define HCI_MINIMUM_LMP_VERSION 5  // Bluetooth Core Specification 3.0 + HS
46 #define NUM_HCI_COMMANDS_BANDWIDTH 1000
47 #define NUM_SCO_PACKETS_BANDWIDTH 1000
48 #define NUM_ACL_PACKETS_BANDWIDTH 1000
49 #define WAIT_FOR_INIT_TIMEOUT std::chrono::milliseconds(2000)
50 #define WAIT_FOR_HCI_EVENT_TIMEOUT std::chrono::milliseconds(2000)
51 #define WAIT_FOR_SCO_DATA_TIMEOUT std::chrono::milliseconds(1000)
52 #define WAIT_FOR_ACL_DATA_TIMEOUT std::chrono::milliseconds(1000)
53 #define INTERFACE_CLOSE_DELAY_MS std::chrono::milliseconds(200)
54 
55 #define COMMAND_HCI_SHOULD_BE_UNKNOWN \
56   { 0xff, 0x3B, 0x08, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }
57 #define COMMAND_HCI_READ_LOCAL_VERSION_INFORMATION \
58   { 0x01, 0x10, 0x00 }
59 #define COMMAND_HCI_READ_BUFFER_SIZE \
60   { 0x05, 0x10, 0x00 }
61 #define COMMAND_HCI_WRITE_LOOPBACK_MODE_LOCAL \
62   { 0x02, 0x18, 0x01, 0x01 }
63 #define COMMAND_HCI_RESET \
64   { 0x03, 0x0c, 0x00 }
65 #define COMMAND_HCI_WRITE_LOCAL_NAME \
66   { 0x13, 0x0c, 0xf8 }
67 #define HCI_STATUS_SUCCESS 0x00
68 #define HCI_STATUS_UNKNOWN_HCI_COMMAND 0x01
69 
70 #define EVENT_CONNECTION_COMPLETE 0x03
71 #define EVENT_COMMAND_COMPLETE 0x0e
72 #define EVENT_COMMAND_STATUS 0x0f
73 #define EVENT_NUMBER_OF_COMPLETED_PACKETS 0x13
74 #define EVENT_LOOPBACK_COMMAND 0x19
75 
76 #define EVENT_CODE_BYTE 0
77 #define EVENT_LENGTH_BYTE 1
78 #define EVENT_FIRST_PAYLOAD_BYTE 2
79 #define EVENT_COMMAND_STATUS_STATUS_BYTE 2
80 #define EVENT_COMMAND_STATUS_ALLOWED_PACKETS_BYTE 3
81 #define EVENT_COMMAND_STATUS_OPCODE_LSBYTE 4  // Bytes 4 and 5
82 #define EVENT_COMMAND_COMPLETE_ALLOWED_PACKETS_BYTE 2
83 #define EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE 3  // Bytes 3 and 4
84 #define EVENT_COMMAND_COMPLETE_STATUS_BYTE 5
85 #define EVENT_COMMAND_COMPLETE_FIRST_PARAM_BYTE 6
86 #define EVENT_LOCAL_HCI_VERSION_BYTE EVENT_COMMAND_COMPLETE_FIRST_PARAM_BYTE
87 #define EVENT_LOCAL_LMP_VERSION_BYTE EVENT_LOCAL_HCI_VERSION_BYTE + 3
88 
89 #define EVENT_CONNECTION_COMPLETE_PARAM_LENGTH 11
90 #define EVENT_CONNECTION_COMPLETE_TYPE 11
91 #define EVENT_CONNECTION_COMPLETE_TYPE_SCO 0
92 #define EVENT_CONNECTION_COMPLETE_TYPE_ACL 1
93 #define EVENT_CONNECTION_COMPLETE_HANDLE_LSBYTE 3
94 #define EVENT_COMMAND_STATUS_LENGTH 4
95 
96 #define EVENT_NUMBER_OF_COMPLETED_PACKETS_NUM_HANDLES 2
97 
98 #define ACL_BROADCAST_FLAG_OFFSET 6
99 #define ACL_BROADCAST_FLAG_POINT_TO_POINT 0x0
100 #define ACL_BROADCAST_POINT_TO_POINT \
101   (ACL_BROADCAST_FLAG_POINT_TO_POINT << ACL_BROADCAST_FLAG_OFFSET)
102 
103 #define ACL_PACKET_BOUNDARY_FLAG_OFFSET 4
104 #define ACL_PACKET_BOUNDARY_FLAG_FIRST_AUTO_FLUSHABLE 0x2
105 #define ACL_PACKET_BOUNDARY_FIRST_AUTO_FLUSHABLE \
106   (ACL_PACKET_BOUNDARY_FLAG_FIRST_AUTO_FLUSHABLE \
107    << ACL_PACKET_BOUNDARY_FLAG_OFFSET)
108 
109 // To be removed in VTS release builds
110 #define ACL_HANDLE_QCA_DEBUG_MESSAGE 0xedc
111 
112 constexpr char kCallbackNameAclEventReceived[] = "aclDataReceived";
113 constexpr char kCallbackNameHciEventReceived[] = "hciEventReceived";
114 constexpr char kCallbackNameInitializationComplete[] = "initializationComplete";
115 constexpr char kCallbackNameScoEventReceived[] = "scoDataReceived";
116 
117 class ThroughputLogger {
118  public:
ThroughputLogger(std::string task)119   ThroughputLogger(std::string task)
120       : task_(task), start_time_(std::chrono::steady_clock::now()) {}
121 
~ThroughputLogger()122   ~ThroughputLogger() {
123     if (total_bytes_ == 0) return;
124     std::chrono::duration<double> duration =
125         std::chrono::steady_clock::now() - start_time_;
126     double s = duration.count();
127     if (s == 0) return;
128     double rate_kb = (static_cast<double>(total_bytes_) / s) / 1024;
129     ALOGD("%s %.1f KB/s (%zu bytes in %.3fs)", task_.c_str(), rate_kb,
130           total_bytes_, s);
131   }
132 
setTotalBytes(size_t total_bytes)133   void setTotalBytes(size_t total_bytes) { total_bytes_ = total_bytes; }
134 
135  private:
136   size_t total_bytes_;
137   std::string task_;
138   std::chrono::steady_clock::time_point start_time_;
139 };
140 
141 // The main test class for Bluetooth HIDL HAL.
142 class BluetoothHidlTest : public ::testing::TestWithParam<std::string> {
143  public:
SetUp()144   virtual void SetUp() override {
145     // currently test passthrough mode only
146     bluetooth = IBluetoothHci::getService(GetParam());
147     ASSERT_NE(bluetooth, nullptr);
148     ALOGI("%s: getService() for bluetooth is %s", __func__,
149           bluetooth->isRemote() ? "remote" : "local");
150 
151     bluetooth_hci_death_recipient = new BluetoothHciDeathRecipient();
152     ASSERT_NE(bluetooth_hci_death_recipient, nullptr);
153     ASSERT_TRUE(
154         bluetooth->linkToDeath(bluetooth_hci_death_recipient, 0).isOk());
155 
156     bluetooth_cb = new BluetoothHciCallbacks(*this);
157     ASSERT_NE(bluetooth_cb, nullptr);
158 
159     max_acl_data_packet_length = 0;
160     max_sco_data_packet_length = 0;
161     max_acl_data_packets = 0;
162     max_sco_data_packets = 0;
163 
164     initialized = false;
165     event_cb_count = 0;
166     acl_cb_count = 0;
167     sco_cb_count = 0;
168 
169     ASSERT_FALSE(initialized);
170     // Should not be checked in production code
171     ASSERT_TRUE(bluetooth->initialize(bluetooth_cb).isOk());
172 
173     bluetooth_cb->SetWaitTimeout(kCallbackNameInitializationComplete,
174                                  WAIT_FOR_INIT_TIMEOUT);
175     bluetooth_cb->SetWaitTimeout(kCallbackNameHciEventReceived,
176                                  WAIT_FOR_HCI_EVENT_TIMEOUT);
177     bluetooth_cb->SetWaitTimeout(kCallbackNameAclEventReceived,
178                                  WAIT_FOR_ACL_DATA_TIMEOUT);
179     bluetooth_cb->SetWaitTimeout(kCallbackNameScoEventReceived,
180                                  WAIT_FOR_SCO_DATA_TIMEOUT);
181 
182     EXPECT_TRUE(
183         bluetooth_cb->WaitForCallback(kCallbackNameInitializationComplete)
184             .no_timeout);
185 
186     ASSERT_TRUE(initialized);
187   }
188 
TearDown()189   virtual void TearDown() override {
190     ALOGI("TearDown");
191     // Should not be checked in production code
192     ASSERT_TRUE(bluetooth->close().isOk());
193     std::this_thread::sleep_for(INTERFACE_CLOSE_DELAY_MS);
194     handle_no_ops();
195     EXPECT_EQ(static_cast<size_t>(0), event_queue.size());
196     EXPECT_EQ(static_cast<size_t>(0), sco_queue.size());
197     EXPECT_EQ(static_cast<size_t>(0), acl_queue.size());
198   }
199 
200   void setBufferSizes();
201 
202   // Functions called from within tests in loopback mode
203   void sendAndCheckHCI(int num_packets);
204   void sendAndCheckSCO(int num_packets, size_t size, uint16_t handle);
205   void sendAndCheckACL(int num_packets, size_t size, uint16_t handle);
206 
207   // Helper functions to try to get a handle on verbosity
208   void enterLoopbackMode(std::vector<uint16_t>& sco_handles,
209                          std::vector<uint16_t>& acl_handles);
210   void handle_no_ops();
211   void wait_for_event(bool timeout_is_error);
212   void wait_for_command_complete_event(hidl_vec<uint8_t> cmd);
213   int wait_for_completed_packets_event(uint16_t handle);
214 
215   class BluetoothHciDeathRecipient : public hidl_death_recipient {
216    public:
serviceDied(uint64_t,const android::wp<::android::hidl::base::V1_0::IBase> &)217     void serviceDied(
218         uint64_t /*cookie*/,
219         const android::wp<::android::hidl::base::V1_0::IBase>& /*who*/)
220         override {
221       FAIL();
222     }
223   };
224 
225   // A simple test implementation of BluetoothHciCallbacks.
226   class BluetoothHciCallbacks
227       : public ::testing::VtsHalHidlTargetCallbackBase<BluetoothHidlTest>,
228         public IBluetoothHciCallbacks {
229     BluetoothHidlTest& parent_;
230 
231    public:
BluetoothHciCallbacks(BluetoothHidlTest & parent)232     BluetoothHciCallbacks(BluetoothHidlTest& parent) : parent_(parent){};
233 
234     virtual ~BluetoothHciCallbacks() = default;
235 
initializationComplete(Status status)236     Return<void> initializationComplete(Status status) override {
237       parent_.initialized = (status == Status::SUCCESS);
238       NotifyFromCallback(kCallbackNameInitializationComplete);
239       ALOGV("%s (status = %d)", __func__, static_cast<int>(status));
240       return Void();
241     };
242 
hciEventReceived(const::android::hardware::hidl_vec<uint8_t> & event)243     Return<void> hciEventReceived(
244         const ::android::hardware::hidl_vec<uint8_t>& event) override {
245       parent_.event_cb_count++;
246       parent_.event_queue.push(event);
247       NotifyFromCallback(kCallbackNameHciEventReceived);
248       ALOGV("Event received (length = %d)", static_cast<int>(event.size()));
249       return Void();
250     };
251 
aclDataReceived(const::android::hardware::hidl_vec<uint8_t> & data)252     Return<void> aclDataReceived(
253         const ::android::hardware::hidl_vec<uint8_t>& data) override {
254       parent_.acl_cb_count++;
255       parent_.acl_queue.push(data);
256       NotifyFromCallback(kCallbackNameAclEventReceived);
257       return Void();
258     };
259 
scoDataReceived(const::android::hardware::hidl_vec<uint8_t> & data)260     Return<void> scoDataReceived(
261         const ::android::hardware::hidl_vec<uint8_t>& data) override {
262       parent_.sco_cb_count++;
263       parent_.sco_queue.push(data);
264       NotifyFromCallback(kCallbackNameScoEventReceived);
265       return Void();
266     };
267   };
268 
269   sp<IBluetoothHci> bluetooth;
270   sp<BluetoothHciCallbacks> bluetooth_cb;
271   sp<BluetoothHciDeathRecipient> bluetooth_hci_death_recipient;
272   std::queue<hidl_vec<uint8_t>> event_queue;
273   std::queue<hidl_vec<uint8_t>> acl_queue;
274   std::queue<hidl_vec<uint8_t>> sco_queue;
275 
276   bool initialized;
277 
278   int event_cb_count;
279   int sco_cb_count;
280   int acl_cb_count;
281 
282   int max_acl_data_packet_length;
283   int max_sco_data_packet_length;
284   int max_acl_data_packets;
285   int max_sco_data_packets;
286 };
287 
288 // Discard NO-OPs from the event queue.
handle_no_ops()289 void BluetoothHidlTest::handle_no_ops() {
290   while (event_queue.size() > 0) {
291     hidl_vec<uint8_t> event = event_queue.front();
292     EXPECT_GE(event.size(),
293               static_cast<size_t>(EVENT_COMMAND_COMPLETE_STATUS_BYTE));
294     bool event_is_no_op =
295         (event[EVENT_CODE_BYTE] == EVENT_COMMAND_COMPLETE) &&
296         (event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE] == 0x00) &&
297         (event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1] == 0x00);
298     event_is_no_op |= (event[EVENT_CODE_BYTE] == EVENT_COMMAND_STATUS) &&
299                       (event[EVENT_COMMAND_STATUS_OPCODE_LSBYTE] == 0x00) &&
300                       (event[EVENT_COMMAND_STATUS_OPCODE_LSBYTE + 1] == 0x00);
301     if (event_is_no_op) {
302       event_queue.pop();
303     } else {
304       break;
305     }
306   }
307   // To be removed in VTS release builds
308   while (acl_queue.size() > 0) {
309     hidl_vec<uint8_t> acl_packet = acl_queue.front();
310     uint16_t connection_handle = acl_packet[1] & 0xF;
311     connection_handle <<= 8;
312     connection_handle |= acl_packet[0];
313     bool packet_is_no_op = connection_handle == ACL_HANDLE_QCA_DEBUG_MESSAGE;
314     if (packet_is_no_op) {
315       acl_queue.pop();
316     } else {
317       break;
318     }
319   }
320 }
321 
322 // Receive an event, discarding NO-OPs.
wait_for_event(bool timeout_is_error=true)323 void BluetoothHidlTest::wait_for_event(bool timeout_is_error = true) {
324   hidl_vec<uint8_t> event;
325   do {
326     bool no_timeout =
327         bluetooth_cb->WaitForCallback(kCallbackNameHciEventReceived).no_timeout;
328     EXPECT_TRUE(no_timeout || !timeout_is_error);
329     if (no_timeout && timeout_is_error) {
330       EXPECT_LT(static_cast<size_t>(0), event_queue.size());
331     }
332     if (event_queue.size() == 0) {
333       // WaitForCallback timed out.
334       return;
335     }
336     handle_no_ops();
337   } while (event_queue.size() == 0);
338 }
339 
340 // Wait until a COMMAND_COMPLETE is received.
wait_for_command_complete_event(hidl_vec<uint8_t> cmd)341 void BluetoothHidlTest::wait_for_command_complete_event(hidl_vec<uint8_t> cmd) {
342   wait_for_event();
343   hidl_vec<uint8_t> event = event_queue.front();
344   event_queue.pop();
345 
346   EXPECT_GT(event.size(),
347             static_cast<size_t>(EVENT_COMMAND_COMPLETE_STATUS_BYTE));
348   EXPECT_EQ(EVENT_COMMAND_COMPLETE, event[EVENT_CODE_BYTE]);
349   EXPECT_EQ(cmd[0], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE]);
350   EXPECT_EQ(cmd[1], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1]);
351   EXPECT_EQ(HCI_STATUS_SUCCESS, event[EVENT_COMMAND_COMPLETE_STATUS_BYTE]);
352 }
353 
354 // Send the command to read the controller's buffer sizes.
setBufferSizes()355 void BluetoothHidlTest::setBufferSizes() {
356   hidl_vec<uint8_t> cmd = COMMAND_HCI_READ_BUFFER_SIZE;
357   bluetooth->sendHciCommand(cmd);
358 
359   wait_for_event();
360   if (event_queue.size() == 0) return;
361 
362   hidl_vec<uint8_t> event = event_queue.front();
363   event_queue.pop();
364 
365   EXPECT_EQ(EVENT_COMMAND_COMPLETE, event[EVENT_CODE_BYTE]);
366   EXPECT_EQ(cmd[0], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE]);
367   EXPECT_EQ(cmd[1], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1]);
368   EXPECT_EQ(HCI_STATUS_SUCCESS, event[EVENT_COMMAND_COMPLETE_STATUS_BYTE]);
369 
370   max_acl_data_packet_length =
371       event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 1] +
372       (event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 2] << 8);
373   max_sco_data_packet_length = event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 3];
374   max_acl_data_packets = event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 4] +
375                          (event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 5] << 8);
376   max_sco_data_packets = event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 6] +
377                          (event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 7] << 8);
378 
379   ALOGD("%s: ACL max %d num %d SCO max %d num %d", __func__,
380         static_cast<int>(max_acl_data_packet_length),
381         static_cast<int>(max_acl_data_packets),
382         static_cast<int>(max_sco_data_packet_length),
383         static_cast<int>(max_sco_data_packets));
384 }
385 
386 // Send an HCI command (in Loopback mode) and check the response.
sendAndCheckHCI(int num_packets)387 void BluetoothHidlTest::sendAndCheckHCI(int num_packets) {
388   ThroughputLogger logger = {__func__};
389   int command_size = 0;
390   for (int n = 0; n < num_packets; n++) {
391     // Send an HCI packet
392     std::vector<uint8_t> write_name = COMMAND_HCI_WRITE_LOCAL_NAME;
393     // With a name
394     char new_name[] = "John Jacob Jingleheimer Schmidt ___________________0";
395     size_t new_name_length = strlen(new_name);
396     for (size_t i = 0; i < new_name_length; i++)
397       write_name.push_back(static_cast<uint8_t>(new_name[i]));
398     // And the packet number
399     size_t i = new_name_length - 1;
400     for (int digits = n; digits > 0; digits = digits / 10, i--)
401       write_name[i] = static_cast<uint8_t>('0' + digits % 10);
402     // And padding
403     for (size_t i = 0; i < 248 - new_name_length; i++)
404       write_name.push_back(static_cast<uint8_t>(0));
405 
406     hidl_vec<uint8_t> cmd = write_name;
407     bluetooth->sendHciCommand(cmd);
408 
409     // Check the loopback of the HCI packet
410     wait_for_event();
411     if (event_queue.size() == 0) return;
412 
413     hidl_vec<uint8_t> event = event_queue.front();
414     event_queue.pop();
415     size_t compare_length =
416         (cmd.size() > static_cast<size_t>(0xff) ? static_cast<size_t>(0xff)
417                                                 : cmd.size());
418     EXPECT_GT(event.size(), compare_length + EVENT_FIRST_PAYLOAD_BYTE - 1);
419 
420     EXPECT_EQ(EVENT_LOOPBACK_COMMAND, event[EVENT_CODE_BYTE]);
421     EXPECT_EQ(compare_length, event[EVENT_LENGTH_BYTE]);
422 
423     // Don't compare past the end of the event.
424     if (compare_length + EVENT_FIRST_PAYLOAD_BYTE > event.size()) {
425       compare_length = event.size() - EVENT_FIRST_PAYLOAD_BYTE;
426       ALOGE("Only comparing %d bytes", static_cast<int>(compare_length));
427     }
428 
429     if (n == num_packets - 1) {
430       command_size = cmd.size();
431     }
432 
433     for (size_t i = 0; i < compare_length; i++)
434       EXPECT_EQ(cmd[i], event[EVENT_FIRST_PAYLOAD_BYTE + i]);
435   }
436   logger.setTotalBytes(command_size * num_packets * 2);
437 }
438 
439 // Send a SCO data packet (in Loopback mode) and check the response.
sendAndCheckSCO(int num_packets,size_t size,uint16_t handle)440 void BluetoothHidlTest::sendAndCheckSCO(int num_packets, size_t size,
441                                         uint16_t handle) {
442   ThroughputLogger logger = {__func__};
443   for (int n = 0; n < num_packets; n++) {
444     // Send a SCO packet
445     hidl_vec<uint8_t> sco_packet;
446     std::vector<uint8_t> sco_vector;
447     sco_vector.push_back(static_cast<uint8_t>(handle & 0xff));
448     sco_vector.push_back(static_cast<uint8_t>((handle & 0x0f00) >> 8));
449     sco_vector.push_back(static_cast<uint8_t>(size & 0xff));
450     sco_vector.push_back(static_cast<uint8_t>((size & 0xff00) >> 8));
451     for (size_t i = 0; i < size; i++) {
452       sco_vector.push_back(static_cast<uint8_t>(i + n));
453     }
454     sco_packet = sco_vector;
455     bluetooth->sendScoData(sco_vector);
456 
457     // Check the loopback of the SCO packet
458     EXPECT_TRUE(bluetooth_cb->WaitForCallback(kCallbackNameScoEventReceived)
459                     .no_timeout);
460     hidl_vec<uint8_t> sco_loopback = sco_queue.front();
461     sco_queue.pop();
462 
463     EXPECT_EQ(sco_packet.size(), sco_loopback.size());
464     size_t successful_bytes = 0;
465 
466     for (size_t i = 0; i < sco_packet.size(); i++) {
467       if (sco_packet[i] == sco_loopback[i]) {
468         successful_bytes = i;
469       } else {
470         ALOGE("Miscompare at %d (expected %x, got %x)", static_cast<int>(i),
471               sco_packet[i], sco_loopback[i]);
472         ALOGE("At %d (expected %x, got %x)", static_cast<int>(i + 1),
473               sco_packet[i + 1], sco_loopback[i + 1]);
474         break;
475       }
476     }
477     EXPECT_EQ(sco_packet.size(), successful_bytes + 1);
478   }
479   logger.setTotalBytes(num_packets * size * 2);
480 }
481 
482 // Send an ACL data packet (in Loopback mode) and check the response.
sendAndCheckACL(int num_packets,size_t size,uint16_t handle)483 void BluetoothHidlTest::sendAndCheckACL(int num_packets, size_t size,
484                                         uint16_t handle) {
485   ThroughputLogger logger = {__func__};
486   for (int n = 0; n < num_packets; n++) {
487     // Send an ACL packet
488     hidl_vec<uint8_t> acl_packet;
489     std::vector<uint8_t> acl_vector;
490     acl_vector.push_back(static_cast<uint8_t>(handle & 0xff));
491     acl_vector.push_back(static_cast<uint8_t>((handle & 0x0f00) >> 8) |
492                          ACL_BROADCAST_POINT_TO_POINT |
493                          ACL_PACKET_BOUNDARY_FIRST_AUTO_FLUSHABLE);
494     acl_vector.push_back(static_cast<uint8_t>(size & 0xff));
495     acl_vector.push_back(static_cast<uint8_t>((size & 0xff00) >> 8));
496     for (size_t i = 0; i < size; i++) {
497       acl_vector.push_back(static_cast<uint8_t>(i + n));
498     }
499     acl_packet = acl_vector;
500     bluetooth->sendAclData(acl_vector);
501 
502     // Check the loopback of the ACL packet
503     EXPECT_TRUE(bluetooth_cb->WaitForCallback(kCallbackNameAclEventReceived)
504                     .no_timeout);
505     hidl_vec<uint8_t> acl_loopback = acl_queue.front();
506     acl_queue.pop();
507 
508     EXPECT_EQ(acl_packet.size(), acl_loopback.size());
509     size_t successful_bytes = 0;
510 
511     for (size_t i = 0; i < acl_packet.size(); i++) {
512       if (acl_packet[i] == acl_loopback[i]) {
513         successful_bytes = i;
514       } else {
515         ALOGE("Miscompare at %d (expected %x, got %x)", static_cast<int>(i),
516               acl_packet[i], acl_loopback[i]);
517         ALOGE("At %d (expected %x, got %x)", static_cast<int>(i + 1),
518               acl_packet[i + 1], acl_loopback[i + 1]);
519         break;
520       }
521     }
522     EXPECT_EQ(acl_packet.size(), successful_bytes + 1);
523   }
524   logger.setTotalBytes(num_packets * size * 2);
525 }
526 
527 // Return the number of completed packets reported by the controller.
wait_for_completed_packets_event(uint16_t handle)528 int BluetoothHidlTest::wait_for_completed_packets_event(uint16_t handle) {
529   int packets_processed = 0;
530   wait_for_event(false);
531   if (event_queue.size() == 0) {
532     ALOGW("%s: WaitForCallback timed out.", __func__);
533     return packets_processed;
534   }
535   while (event_queue.size() > 0) {
536     hidl_vec<uint8_t> event = event_queue.front();
537     event_queue.pop();
538 
539     EXPECT_EQ(EVENT_NUMBER_OF_COMPLETED_PACKETS, event[EVENT_CODE_BYTE]);
540     EXPECT_EQ(1, event[EVENT_NUMBER_OF_COMPLETED_PACKETS_NUM_HANDLES]);
541 
542     uint16_t event_handle = event[3] + (event[4] << 8);
543     EXPECT_EQ(handle, event_handle);
544 
545     packets_processed += event[5] + (event[6] << 8);
546   }
547   return packets_processed;
548 }
549 
550 // Send local loopback command and initialize SCO and ACL handles.
enterLoopbackMode(std::vector<uint16_t> & sco_handles,std::vector<uint16_t> & acl_handles)551 void BluetoothHidlTest::enterLoopbackMode(std::vector<uint16_t>& sco_handles,
552                                           std::vector<uint16_t>& acl_handles) {
553   hidl_vec<uint8_t> cmd = COMMAND_HCI_WRITE_LOOPBACK_MODE_LOCAL;
554   bluetooth->sendHciCommand(cmd);
555 
556   // Receive connection complete events with data channels
557   int connection_event_count = 0;
558   bool command_complete_received = false;
559   while (true) {
560     wait_for_event(false);
561     if (event_queue.size() == 0) {
562       // Fail if there was no event received or no connections completed.
563       EXPECT_TRUE(command_complete_received);
564       EXPECT_LT(0, connection_event_count);
565       return;
566     }
567     hidl_vec<uint8_t> event = event_queue.front();
568     event_queue.pop();
569     EXPECT_GT(event.size(),
570               static_cast<size_t>(EVENT_COMMAND_COMPLETE_STATUS_BYTE));
571     if (event[EVENT_CODE_BYTE] == EVENT_CONNECTION_COMPLETE) {
572       EXPECT_GT(event.size(),
573                 static_cast<size_t>(EVENT_CONNECTION_COMPLETE_TYPE));
574       EXPECT_EQ(event[EVENT_LENGTH_BYTE],
575                 EVENT_CONNECTION_COMPLETE_PARAM_LENGTH);
576       uint8_t connection_type = event[EVENT_CONNECTION_COMPLETE_TYPE];
577 
578       EXPECT_TRUE(connection_type == EVENT_CONNECTION_COMPLETE_TYPE_SCO ||
579                   connection_type == EVENT_CONNECTION_COMPLETE_TYPE_ACL);
580 
581       // Save handles
582       uint16_t handle = event[EVENT_CONNECTION_COMPLETE_HANDLE_LSBYTE] |
583                         event[EVENT_CONNECTION_COMPLETE_HANDLE_LSBYTE + 1] << 8;
584       if (connection_type == EVENT_CONNECTION_COMPLETE_TYPE_SCO)
585         sco_handles.push_back(handle);
586       else
587         acl_handles.push_back(handle);
588 
589       ALOGD("Connect complete type = %d handle = %d",
590             event[EVENT_CONNECTION_COMPLETE_TYPE], handle);
591       connection_event_count++;
592     } else {
593       EXPECT_EQ(EVENT_COMMAND_COMPLETE, event[EVENT_CODE_BYTE]);
594       EXPECT_EQ(cmd[0], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE]);
595       EXPECT_EQ(cmd[1], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1]);
596       EXPECT_EQ(HCI_STATUS_SUCCESS, event[EVENT_COMMAND_COMPLETE_STATUS_BYTE]);
597       command_complete_received = true;
598     }
599   }
600 }
601 
602 // Empty test: Initialize()/Close() are called in SetUp()/TearDown().
TEST_P(BluetoothHidlTest,InitializeAndClose)603 TEST_P(BluetoothHidlTest, InitializeAndClose) {}
604 
605 // Send an HCI Reset with sendHciCommand and wait for a command complete event.
TEST_P(BluetoothHidlTest,HciReset)606 TEST_P(BluetoothHidlTest, HciReset) {
607   hidl_vec<uint8_t> cmd = COMMAND_HCI_RESET;
608   bluetooth->sendHciCommand(cmd);
609 
610   wait_for_command_complete_event(cmd);
611 }
612 
613 // Read and check the HCI version of the controller.
TEST_P(BluetoothHidlTest,HciVersionTest)614 TEST_P(BluetoothHidlTest, HciVersionTest) {
615   hidl_vec<uint8_t> cmd = COMMAND_HCI_READ_LOCAL_VERSION_INFORMATION;
616   bluetooth->sendHciCommand(cmd);
617 
618   wait_for_event();
619   if (event_queue.size() == 0) return;
620 
621   hidl_vec<uint8_t> event = event_queue.front();
622   event_queue.pop();
623   EXPECT_GT(event.size(), static_cast<size_t>(EVENT_LOCAL_LMP_VERSION_BYTE));
624 
625   EXPECT_EQ(EVENT_COMMAND_COMPLETE, event[EVENT_CODE_BYTE]);
626   EXPECT_EQ(cmd[0], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE]);
627   EXPECT_EQ(cmd[1], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1]);
628   EXPECT_EQ(HCI_STATUS_SUCCESS, event[EVENT_COMMAND_COMPLETE_STATUS_BYTE]);
629 
630   EXPECT_LE(HCI_MINIMUM_HCI_VERSION, event[EVENT_LOCAL_HCI_VERSION_BYTE]);
631   EXPECT_LE(HCI_MINIMUM_LMP_VERSION, event[EVENT_LOCAL_LMP_VERSION_BYTE]);
632 }
633 
634 // Send an unknown HCI command and wait for the error message.
TEST_P(BluetoothHidlTest,HciUnknownCommand)635 TEST_P(BluetoothHidlTest, HciUnknownCommand) {
636   hidl_vec<uint8_t> cmd = COMMAND_HCI_SHOULD_BE_UNKNOWN;
637   bluetooth->sendHciCommand(cmd);
638 
639   wait_for_event();
640   if (event_queue.size() == 0) return;
641 
642   hidl_vec<uint8_t> event = event_queue.front();
643   event_queue.pop();
644 
645   EXPECT_GT(event.size(),
646             static_cast<size_t>(EVENT_COMMAND_COMPLETE_STATUS_BYTE));
647   if (event[EVENT_CODE_BYTE] == EVENT_COMMAND_COMPLETE) {
648     EXPECT_EQ(cmd[0], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE]);
649     EXPECT_EQ(cmd[1], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1]);
650     EXPECT_EQ(HCI_STATUS_UNKNOWN_HCI_COMMAND,
651               event[EVENT_COMMAND_COMPLETE_STATUS_BYTE]);
652   } else {
653     EXPECT_EQ(EVENT_COMMAND_STATUS, event[EVENT_CODE_BYTE]);
654     EXPECT_EQ(cmd[0], event[EVENT_COMMAND_STATUS_OPCODE_LSBYTE]);
655     EXPECT_EQ(cmd[1], event[EVENT_COMMAND_STATUS_OPCODE_LSBYTE + 1]);
656     EXPECT_EQ(HCI_STATUS_UNKNOWN_HCI_COMMAND,
657               event[EVENT_COMMAND_STATUS_STATUS_BYTE]);
658   }
659 }
660 
661 // Enter loopback mode, but don't send any packets.
TEST_P(BluetoothHidlTest,WriteLoopbackMode)662 TEST_P(BluetoothHidlTest, WriteLoopbackMode) {
663   std::vector<uint16_t> sco_connection_handles;
664   std::vector<uint16_t> acl_connection_handles;
665   enterLoopbackMode(sco_connection_handles, acl_connection_handles);
666 }
667 
668 // Enter loopback mode and send single packets.
TEST_P(BluetoothHidlTest,LoopbackModeSinglePackets)669 TEST_P(BluetoothHidlTest, LoopbackModeSinglePackets) {
670   setBufferSizes();
671 
672   std::vector<uint16_t> sco_connection_handles;
673   std::vector<uint16_t> acl_connection_handles;
674   enterLoopbackMode(sco_connection_handles, acl_connection_handles);
675 
676   sendAndCheckHCI(1);
677 
678   // This should work, but breaks on some current platforms.  Figure out how to
679   // grandfather older devices but test new ones.
680   if (0 && sco_connection_handles.size() > 0) {
681     EXPECT_LT(0, max_sco_data_packet_length);
682     sendAndCheckSCO(1, max_sco_data_packet_length, sco_connection_handles[0]);
683     int sco_packets_sent = 1;
684     int completed_packets =
685         wait_for_completed_packets_event(sco_connection_handles[0]);
686     if (sco_packets_sent != completed_packets) {
687       ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
688             sco_packets_sent, completed_packets);
689     }
690   }
691 
692   if (acl_connection_handles.size() > 0) {
693     EXPECT_LT(0, max_acl_data_packet_length);
694     sendAndCheckACL(1, max_acl_data_packet_length, acl_connection_handles[0]);
695     int acl_packets_sent = 1;
696     int completed_packets =
697         wait_for_completed_packets_event(acl_connection_handles[0]);
698     if (acl_packets_sent != completed_packets) {
699       ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
700             acl_packets_sent, completed_packets);
701     }
702   }
703 }
704 
705 // Enter loopback mode and send packets for bandwidth measurements.
TEST_P(BluetoothHidlTest,LoopbackModeBandwidth)706 TEST_P(BluetoothHidlTest, LoopbackModeBandwidth) {
707   setBufferSizes();
708 
709   std::vector<uint16_t> sco_connection_handles;
710   std::vector<uint16_t> acl_connection_handles;
711   enterLoopbackMode(sco_connection_handles, acl_connection_handles);
712 
713   sendAndCheckHCI(NUM_HCI_COMMANDS_BANDWIDTH);
714 
715   // This should work, but breaks on some current platforms.  Figure out how to
716   // grandfather older devices but test new ones.
717   if (0 && sco_connection_handles.size() > 0) {
718     EXPECT_LT(0, max_sco_data_packet_length);
719     sendAndCheckSCO(NUM_SCO_PACKETS_BANDWIDTH, max_sco_data_packet_length,
720                     sco_connection_handles[0]);
721     int sco_packets_sent = NUM_SCO_PACKETS_BANDWIDTH;
722     int completed_packets =
723         wait_for_completed_packets_event(sco_connection_handles[0]);
724     if (sco_packets_sent != completed_packets) {
725       ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
726             sco_packets_sent, completed_packets);
727     }
728   }
729 
730   if (acl_connection_handles.size() > 0) {
731     EXPECT_LT(0, max_acl_data_packet_length);
732     sendAndCheckACL(NUM_ACL_PACKETS_BANDWIDTH, max_acl_data_packet_length,
733                     acl_connection_handles[0]);
734     int acl_packets_sent = NUM_ACL_PACKETS_BANDWIDTH;
735     int completed_packets =
736         wait_for_completed_packets_event(acl_connection_handles[0]);
737     if (acl_packets_sent != completed_packets) {
738       ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
739             acl_packets_sent, completed_packets);
740     }
741   }
742 }
743 
744 INSTANTIATE_TEST_SUITE_P(
745     PerInstance, BluetoothHidlTest,
746     testing::ValuesIn(
747         android::hardware::getAllHalInstanceNames(IBluetoothHci::descriptor)),
748     android::hardware::PrintInstanceNameToString);
749