1 /******************************************************************************
2  *
3  *  Copyright 2017 Google, Inc.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #define LOG_TAG "bt_hci"
20 
21 #include "hci_layer.h"
22 
23 #include <iomanip>
24 
25 #include <fcntl.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 
29 #include <android/hardware/bluetooth/1.0/IBluetoothHci.h>
30 #include <android/hardware/bluetooth/1.0/IBluetoothHciCallbacks.h>
31 #include <android/hardware/bluetooth/1.0/types.h>
32 #include <android/hardware/bluetooth/1.1/IBluetoothHci.h>
33 #include <android/hardware/bluetooth/1.1/IBluetoothHciCallbacks.h>
34 
35 #include <base/location.h>
36 #include <base/logging.h>
37 
38 #include "buffer_allocator.h"
39 #include "common/stop_watch_legacy.h"
40 #include "osi/include/log.h"
41 
42 #define LOG_PATH "/data/misc/bluetooth/logs/firmware_events.log"
43 #define LAST_LOG_PATH "/data/misc/bluetooth/logs/firmware_events.log.last"
44 
45 using ::android::hardware::hidl_death_recipient;
46 using ::android::hardware::hidl_vec;
47 using ::android::hardware::Return;
48 using ::android::hardware::Void;
49 using ::android::hardware::bluetooth::V1_0::HciPacket;
50 using ::android::hardware::bluetooth::V1_0::Status;
51 using ::bluetooth::common::StopWatchLegacy;
52 
53 using namespace ::android::hardware::bluetooth;
54 
55 extern void initialization_complete();
56 extern void hci_event_received(const base::Location& from_here, BT_HDR* packet);
57 extern void acl_event_received(BT_HDR* packet);
58 extern void sco_data_received(BT_HDR* packet);
59 extern void iso_data_received(BT_HDR* packet);
60 extern void hal_service_died();
61 extern bool hci_is_root_inflammation_event_received();
62 
63 android::sp<V1_0::IBluetoothHci> btHci;
64 android::sp<V1_1::IBluetoothHci> btHci_1_1;
65 
GetTimerText(std::string func_name,const hidl_vec<uint8_t> & vec)66 std::string GetTimerText(std::string func_name, const hidl_vec<uint8_t>& vec) {
67   std::stringstream ss;
68   const unsigned char* vec_char =
69       reinterpret_cast<const unsigned char*>(vec.data());
70   int length = 5;
71   if ((int)vec.size() < 5) {
72     length = vec.size();
73   }
74   for (int i = 0; i < length; i++) {
75     ss << std::setw(2) << std::setfill('0') << std::hex << (int)vec_char[i];
76   }
77   std::string text = func_name + ": len " + std::to_string(vec.size()) +
78                      ", 1st 5 bytes '" + ss.str() + "'";
79   return text;
80 }
81 
82 class BluetoothHciDeathRecipient : public hidl_death_recipient {
83  public:
serviceDied(uint64_t,const android::wp<::android::hidl::base::V1_0::IBase> &)84   virtual void serviceDied(uint64_t /*cookie*/, const android::wp<::android::hidl::base::V1_0::IBase>& /*who*/) {
85     LOG_ERROR("Bluetooth HAL service died!");
86     StopWatchLegacy::DumpStopWatchLog();
87     hal_service_died();
88   }
89 };
90 android::sp<BluetoothHciDeathRecipient> bluetoothHciDeathRecipient = new BluetoothHciDeathRecipient();
91 
92 class BluetoothHciCallbacks : public V1_1::IBluetoothHciCallbacks {
93  public:
BluetoothHciCallbacks()94   BluetoothHciCallbacks() {
95     buffer_allocator = buffer_allocator_get_interface();
96   }
97 
WrapPacketAndCopy(uint16_t event,const hidl_vec<uint8_t> & data)98   BT_HDR* WrapPacketAndCopy(uint16_t event, const hidl_vec<uint8_t>& data) {
99     size_t packet_size = data.size() + BT_HDR_SIZE;
100     BT_HDR* packet =
101         reinterpret_cast<BT_HDR*>(buffer_allocator->alloc(packet_size));
102     packet->offset = 0;
103     packet->len = data.size();
104     packet->layer_specific = 0;
105     packet->event = event;
106     // TODO(eisenbach): Avoid copy here; if BT_HDR->data can be ensured to
107     // be the only way the data is accessed, a pointer could be passed here...
108     memcpy(packet->data, data.data(), data.size());
109     return packet;
110   }
111 
initializationComplete(Status status)112   Return<void> initializationComplete(Status status) override {
113     StopWatchLegacy(__func__);
114     if (hci_is_root_inflammation_event_received()) {
115       // Ignore the initializationComplete here as we have already received
116       // root inflammation event earlier.
117       LOG_ERROR(
118           "initializationComplete after root inflammation event! status=%d",
119           status);
120       return Void();
121     }
122     CHECK(status == Status::SUCCESS);
123     initialization_complete();
124     return Void();
125   }
126 
hciEventReceived(const hidl_vec<uint8_t> & event)127   Return<void> hciEventReceived(const hidl_vec<uint8_t>& event) override {
128     StopWatchLegacy(GetTimerText(__func__, event));
129     BT_HDR* packet = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, event);
130     hci_event_received(FROM_HERE, packet);
131     return Void();
132   }
133 
aclDataReceived(const hidl_vec<uint8_t> & data)134   Return<void> aclDataReceived(const hidl_vec<uint8_t>& data) override {
135     StopWatchLegacy(GetTimerText(__func__, data));
136     BT_HDR* packet = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_ACL, data);
137     acl_event_received(packet);
138     return Void();
139   }
140 
scoDataReceived(const hidl_vec<uint8_t> & data)141   Return<void> scoDataReceived(const hidl_vec<uint8_t>& data) override {
142     StopWatchLegacy(GetTimerText(__func__, data));
143     BT_HDR* packet = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_SCO, data);
144     sco_data_received(packet);
145     return Void();
146   }
147 
isoDataReceived(const hidl_vec<uint8_t> & data)148   Return<void> isoDataReceived(const hidl_vec<uint8_t>& data) override {
149     StopWatchLegacy(GetTimerText(__func__, data));
150     BT_HDR* packet = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_ISO, data);
151     iso_data_received(packet);
152     return Void();
153   }
154 
155   const allocator_t* buffer_allocator;
156 };
157 
hci_initialize()158 void hci_initialize() {
159   LOG_INFO("%s", __func__);
160 
161   btHci_1_1 = V1_1::IBluetoothHci::getService();
162 
163   if (btHci_1_1 != nullptr) {
164     btHci = btHci_1_1;
165   } else {
166     btHci = V1_0::IBluetoothHci::getService();
167   }
168 
169   // If android.hardware.bluetooth* is not found, Bluetooth can not continue.
170   CHECK(btHci != nullptr);
171   auto death_link = btHci->linkToDeath(bluetoothHciDeathRecipient, 0);
172   if (!death_link.isOk()) {
173     LOG_ERROR("%s: Unable to set the death recipient for the Bluetooth HAL",
174               __func__);
175     abort();
176   }
177   LOG_INFO("%s: IBluetoothHci::getService() returned %p (%s)", __func__,
178            btHci.get(), (btHci->isRemote() ? "remote" : "local"));
179 
180   // Block allows allocation of a variable that might be bypassed by goto.
181   {
182     android::sp<V1_1::IBluetoothHciCallbacks> callbacks =
183         new BluetoothHciCallbacks();
184     if (btHci_1_1 != nullptr) {
185       btHci_1_1->initialize_1_1(callbacks);
186     } else {
187       btHci->initialize(callbacks);
188     }
189   }
190 }
191 
hci_close()192 void hci_close() {
193   if (btHci != nullptr) {
194     auto death_unlink = btHci->unlinkToDeath(bluetoothHciDeathRecipient);
195     if (!death_unlink.isOk()) {
196       LOG_ERROR("%s: Error unlinking death recipient from the Bluetooth HAL",
197                 __func__);
198     }
199     auto close_status = btHci->close();
200     if (!close_status.isOk()) {
201       LOG_ERROR("%s: Error closing the Bluetooth HAL", __func__);
202     }
203     btHci = nullptr;
204   }
205 }
206 
hci_transmit(BT_HDR * packet)207 void hci_transmit(BT_HDR* packet) {
208   HciPacket data;
209   data.setToExternal(packet->data + packet->offset, packet->len);
210 
211   uint16_t event = packet->event & MSG_EVT_MASK;
212   switch (event & MSG_EVT_MASK) {
213     case MSG_STACK_TO_HC_HCI_CMD:
214       btHci->sendHciCommand(data);
215       break;
216     case MSG_STACK_TO_HC_HCI_ACL:
217       btHci->sendAclData(data);
218       break;
219     case MSG_STACK_TO_HC_HCI_SCO:
220       btHci->sendScoData(data);
221       break;
222     case MSG_STACK_TO_HC_HCI_ISO:
223       if (btHci_1_1 != nullptr) {
224         btHci_1_1->sendIsoData(data);
225       } else {
226         LOG_ERROR("ISO is not supported in HAL v1.0");
227       }
228       break;
229     default:
230       LOG_ERROR("Unknown packet type (%d)", event);
231       break;
232   }
233 }
234 
hci_open_firmware_log_file()235 int hci_open_firmware_log_file() {
236   if (rename(LOG_PATH, LAST_LOG_PATH) == -1 && errno != ENOENT) {
237     LOG_ERROR("%s unable to rename '%s' to '%s': %s", __func__, LOG_PATH,
238               LAST_LOG_PATH, strerror(errno));
239   }
240 
241   mode_t prevmask = umask(0);
242   int logfile_fd = open(LOG_PATH, O_WRONLY | O_CREAT | O_TRUNC,
243                         S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
244   umask(prevmask);
245   if (logfile_fd == INVALID_FD) {
246     LOG_ERROR("%s unable to open '%s': %s", __func__, LOG_PATH,
247               strerror(errno));
248   }
249 
250   return logfile_fd;
251 }
252 
hci_close_firmware_log_file(int fd)253 void hci_close_firmware_log_file(int fd) {
254   if (fd != INVALID_FD) close(fd);
255 }
256 
hci_log_firmware_debug_packet(int fd,BT_HDR * packet)257 void hci_log_firmware_debug_packet(int fd, BT_HDR* packet) {
258   TEMP_FAILURE_RETRY(write(fd, packet->data, packet->len));
259 }
260