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