OSDN Git Service

Replace Bluetooth HAL by Intel's implementation
authorChih-Wei Huang <cwhuang@linux.org.tw>
Wed, 29 May 2019 03:56:16 +0000 (11:56 +0800)
committerChih-Wei Huang <cwhuang@linux.org.tw>
Thu, 14 Nov 2019 04:21:27 +0000 (12:21 +0800)
Linaro's implementation is buggy.

18 files changed:
vendor_libs/linux/interface/Android.bp
vendor_libs/linux/interface/android.hardware.bluetooth@1.0-service.btlinux.rc
vendor_libs/linux/interface/async_fd_watcher.cc
vendor_libs/linux/interface/bluetooth_address.cc [new file with mode: 0644]
vendor_libs/linux/interface/bluetooth_address.h [new file with mode: 0644]
vendor_libs/linux/interface/bluetooth_hci.cc
vendor_libs/linux/interface/bluetooth_hci.h
vendor_libs/linux/interface/bt_vendor_lib.h [new file with mode: 0644]
vendor_libs/linux/interface/h4_protocol.cc
vendor_libs/linux/interface/h4_protocol.h
vendor_libs/linux/interface/hci_packetizer.cc
vendor_libs/linux/interface/hci_protocol.cc [new file with mode: 0644]
vendor_libs/linux/interface/hci_protocol.h [new file with mode: 0644]
vendor_libs/linux/interface/mct_protocol.cc [new file with mode: 0644]
vendor_libs/linux/interface/mct_protocol.h [new file with mode: 0644]
vendor_libs/linux/interface/service.cc
vendor_libs/linux/interface/vendor_interface.cc [new file with mode: 0644]
vendor_libs/linux/interface/vendor_interface.h [new file with mode: 0644]

index 8d6caa4..2b2af74 100644 (file)
@@ -17,27 +17,36 @@ cc_binary {
     name: "android.hardware.bluetooth@1.0-service.btlinux",
     proprietary: true,
     relative_install_path: "hw",
+    include_dirs: [
+        "system/bt/device/include",
+        "system/bt/stack/include"
+    ],
     srcs: [
+        "async_fd_watcher.cc",
+        "bluetooth_hci.cc",
+        "bluetooth_address.cc",
+        "vendor_interface.cc",
         "hci_packetizer.cc",
+        "hci_protocol.cc",
         "h4_protocol.cc",
-        "bluetooth_hci.cc",
-        "async_fd_watcher.cc",
+        "mct_protocol.cc",
         "service.cc"
     ],
-    cflags: ["-Wall", "-Werror"],
+    cflags: ["-Wall", "-Werror", "-Wno-unused-result"],
     header_libs: ["libbluetooth_headers"],
     shared_libs: [
         "android.hardware.bluetooth@1.0",
         "libbase",
         "libcutils",
+        "libhwbinder",
         "libhidlbase",
         "libhidltransport",
         "liblog",
         "libutils",
+        "libusb",
     ],
-    conlyflags: [
-        "-std=c99",
+    required: [
+        "libbt-vendor",
     ],
     init_rc: ["android.hardware.bluetooth@1.0-service.btlinux.rc"],
 }
-
index 36fbc2c..f992c45 100644 (file)
@@ -1,5 +1,15 @@
-service btlinux-1.0 /vendor/bin/hw/android.hardware.bluetooth@1.0-service.btlinux
+service vendor.bluetooth-1-0 /vendor/bin/hw/android.hardware.bluetooth@1.0-service.btlinux
     class hal
+    capabilities BLOCK_SUSPEND NET_ADMIN SYS_NICE
     user bluetooth
-    group bluetooth net_admin net_bt_admin
-    capabilities NET_ADMIN
+    group bluetooth
+    writepid /dev/stune/foreground/tasks
+
+on property:vts.native_server.on=1 && property:ro.build.type=userdebug
+    stop vendor.bluetooth-1-0
+on property:vts.native_server.on=1 && property:ro.build.type=eng
+    stop vendor.bluetooth-1-0
+on property:vts.native_server.on=0 && property:ro.build.type=userdebug
+    start vendor.bluetooth-1-0
+on property:vts.native_server.on=0 && property:ro.build.type=eng
+    start vendor.bluetooth-1-0
index ef4a959..bcacc4e 100644 (file)
 // limitations under the License.
 //
 
+#define LOG_TAG "android.hardware.bluetooth@1.0-service.btlinux"
+
 #include "async_fd_watcher.h"
 
 #include <algorithm>
 #include <atomic>
 #include <condition_variable>
-#include <log/log.h>
 #include <map>
 #include <mutex>
 #include <thread>
+#include <log/log.h>
 #include <vector>
 #include "fcntl.h"
 #include "sys/select.h"
 #include "unistd.h"
 
 static const int INVALID_FD = -1;
+
 static const int BT_RT_PRIORITY = 1;
 
 namespace android {
@@ -102,6 +105,9 @@ int AsyncFdWatcher::stopThread() {
     timeout_cb_ = nullptr;
   }
 
+  close(notification_listen_fd_);
+  close(notification_write_fd_);
+
   return 0;
 }
 
@@ -114,7 +120,6 @@ int AsyncFdWatcher::notifyThread() {
 }
 
 void AsyncFdWatcher::ThreadRoutine() {
-
   // Make watching thread RT.
   struct sched_param rt_params;
   rt_params.sched_priority = BT_RT_PRIORITY;
diff --git a/vendor_libs/linux/interface/bluetooth_address.cc b/vendor_libs/linux/interface/bluetooth_address.cc
new file mode 100644 (file)
index 0000000..fd53e78
--- /dev/null
@@ -0,0 +1,128 @@
+//
+// Copyright 2016 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "bluetooth_address.h"
+
+#include <cutils/properties.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <utils/Log.h>
+
+namespace android {
+namespace hardware {
+namespace bluetooth {
+namespace V1_0 {
+namespace implementation {
+
+void BluetoothAddress::bytes_to_string(const uint8_t* addr, char* addr_str) {
+  sprintf(addr_str, "%02x:%02x:%02x:%02x:%02x:%02x", addr[0], addr[1], addr[2],
+          addr[3], addr[4], addr[5]);
+}
+
+bool BluetoothAddress::string_to_bytes(const char* addr_str, uint8_t* addr) {
+  if (addr_str == NULL) return false;
+  if (strnlen(addr_str, kStringLength) != kStringLength) return false;
+  unsigned char trailing_char = '\0';
+
+  return (sscanf(addr_str, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx%1c",
+                 &addr[0], &addr[1], &addr[2], &addr[3], &addr[4], &addr[5],
+                 &trailing_char) == kBytes);
+}
+
+bool BluetoothAddress::get_local_address(uint8_t* local_addr) {
+  char property[PROPERTY_VALUE_MAX] = {0};
+  bool valid_bda = false;
+
+  // Get local bdaddr storage path from a system property.
+  if (property_get(PROPERTY_BT_BDADDR_PATH, property, NULL)) {
+    int addr_fd;
+
+    ALOGD("%s: Trying %s", __func__, property);
+
+    addr_fd = open(property, O_RDONLY);
+    if (addr_fd != -1) {
+      char address[kStringLength + 1] = {0};
+      int bytes_read = read(addr_fd, address, kStringLength);
+      if (bytes_read == -1) {
+        ALOGE("%s: Error reading address from %s: %s", __func__, property,
+              strerror(errno));
+      }
+      close(addr_fd);
+
+      // Null terminate the string.
+      address[kStringLength] = '\0';
+
+      // If the address is not all zeros, then use it.
+      const uint8_t zero_bdaddr[kBytes] = {0, 0, 0, 0, 0, 0};
+      if ((string_to_bytes(address, local_addr)) &&
+          (memcmp(local_addr, zero_bdaddr, kBytes) != 0)) {
+        valid_bda = true;
+        ALOGD("%s: Got Factory BDA %s", __func__, address);
+      } else {
+        ALOGE("%s: Got Invalid BDA '%s' from %s", __func__, address, property);
+      }
+    }
+  }
+
+  // No BDADDR found in the file. Look for BDA in a factory property.
+  if (!valid_bda && property_get(FACTORY_BDADDR_PROPERTY, property, NULL) &&
+      string_to_bytes(property, local_addr)) {
+    valid_bda = true;
+  }
+
+  // No factory BDADDR found. Look for a previously stored BDA.
+  if (!valid_bda && property_get(PERSIST_BDADDR_PROPERTY, property, NULL) &&
+      string_to_bytes(property, local_addr)) {
+    valid_bda = true;
+  }
+
+  /* Generate new BDA if necessary */
+  if (!valid_bda) {
+    char bdstr[kStringLength + 1];
+
+    /* No autogen BDA. Generate one now. */
+    local_addr[0] = 0x22;
+    local_addr[1] = 0x22;
+    local_addr[2] = (uint8_t)rand();
+    local_addr[3] = (uint8_t)rand();
+    local_addr[4] = (uint8_t)rand();
+    local_addr[5] = (uint8_t)rand();
+
+    /* Convert to ascii, and store as a persistent property */
+    bytes_to_string(local_addr, bdstr);
+
+    ALOGE("%s: No preset BDA! Generating BDA: %s for prop %s", __func__,
+          (char*)bdstr, PERSIST_BDADDR_PROPERTY);
+    ALOGE("%s: This is a bug in the platform!  Please fix!", __func__);
+
+    if (property_set(PERSIST_BDADDR_PROPERTY, (char*)bdstr) < 0) {
+      ALOGE("%s: Failed to set random BDA in prop %s", __func__,
+            PERSIST_BDADDR_PROPERTY);
+      valid_bda = false;
+    } else {
+      valid_bda = true;
+    }
+  }
+
+  return valid_bda;
+}
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace bluetooth
+}  // namespace hardware
+}  // namespace android
diff --git a/vendor_libs/linux/interface/bluetooth_address.h b/vendor_libs/linux/interface/bluetooth_address.h
new file mode 100644 (file)
index 0000000..94bf616
--- /dev/null
@@ -0,0 +1,61 @@
+//
+// Copyright 2016 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#pragma once
+
+#include <fcntl.h>
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace android {
+namespace hardware {
+namespace bluetooth {
+namespace V1_0 {
+namespace implementation {
+
+// The property key stores the storage location of Bluetooth Device Address
+static constexpr char PROPERTY_BT_BDADDR_PATH[] = "ro.bt.bdaddr_path";
+
+// Check for a legacy address stored as a property.
+static constexpr char PERSIST_BDADDR_PROPERTY[] =
+    "persist.service.bdroid.bdaddr";
+
+// If there is no valid bdaddr available from PROPERTY_BT_BDADDR_PATH and there
+// is no available persistent bdaddr available from PERSIST_BDADDR_PROPERTY,
+// use a factory set address.
+static constexpr char FACTORY_BDADDR_PROPERTY[] = "ro.boot.btmacaddr";
+
+// Encapsulate handling for Bluetooth Addresses:
+class BluetoothAddress {
+ public:
+  // Conversion constants
+  static constexpr size_t kStringLength = sizeof("XX:XX:XX:XX:XX:XX") - 1;
+  static constexpr size_t kBytes = (kStringLength + 1) / 3;
+
+  static void bytes_to_string(const uint8_t* addr, char* addr_str);
+
+  static bool string_to_bytes(const char* addr_str, uint8_t* addr);
+
+  static bool get_local_address(uint8_t* addr);
+};
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace bluetooth
+} // namespace hardware
+} // namespace android
index 8507f7a..dfc48b7 100644 (file)
 // limitations under the License.
 //
 
-#define LOG_TAG "android.hardware.bluetooth@1.0-btlinux"
-#include <errno.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <sys/socket.h>
-
-#include <utils/Log.h>
-
+#define LOG_TAG "android.hardware.bluetooth@1.0-service.btlinux"
 #include "bluetooth_hci.h"
 
-#define BTPROTO_HCI 1
-
-#define HCI_CHANNEL_USER 1
-#define HCI_CHANNEL_CONTROL 3
-#define HCI_DEV_NONE 0xffff
-
-/* reference from <kernel>/include/net/bluetooth/mgmt.h */
-#define MGMT_OP_INDEX_LIST 0x0003
-#define MGMT_EV_INDEX_ADDED 0x0004
-#define MGMT_EV_COMMAND_COMP 0x0001
-#define MGMT_EV_SIZE_MAX 1024
-#define MGMT_EV_POLL_TIMEOUT 3000 /* 3000ms */
-#define WRITE_NO_INTR(fn) \
-  do {                  \
-  } while ((fn) == -1 && errno == EINTR)
-
-struct sockaddr_hci {
-    sa_family_t hci_family;
-    unsigned short hci_dev;
-    unsigned short hci_channel;
-};
-
-struct mgmt_pkt {
-    uint16_t opcode;
-    uint16_t index;
-    uint16_t len;
-    uint8_t data[MGMT_EV_SIZE_MAX];
-} __attribute__((packed));
+#include <log/log.h>
 
-struct mgmt_event_read_index {
-    uint16_t cc_opcode;
-    uint8_t status;
-    uint16_t num_intf;
-    uint16_t index[0];
-  } __attribute__((packed));
+#include "vendor_interface.h"
 
 namespace android {
 namespace hardware {
 namespace bluetooth {
 namespace V1_0 {
-namespace btlinux {
-
-int BluetoothHci::openBtHci() {
-
-  ALOGI( "%s", __func__);
-
-  int hci_interface = 0;
-  rfkill_state_ = NULL;
-  rfKill(1);
-
-  int fd = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
-  if (fd < 0) {
-    ALOGE( "Bluetooth socket error: %s", strerror(errno));
-    return -1;
-  }
-  bt_soc_fd_ = fd;
-
-  if (waitHciDev(hci_interface)) {
-    ALOGE( "HCI interface (%d) not found", hci_interface);
-    ::close(fd);
-    return -1;
-  }
-  struct sockaddr_hci addr;
-  memset(&addr, 0, sizeof(addr));
-  addr.hci_family = AF_BLUETOOTH;
-  addr.hci_dev = hci_interface;
-  addr.hci_channel = HCI_CHANNEL_USER;
-  if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
-    ALOGE( "HCI Channel Control: %s", strerror(errno));
-    ::close(fd);
-    return -1;
-  }
-  ALOGI( "HCI device ready");
-  return fd;
-}
-
-void BluetoothHci::closeBtHci() {
-  if (bt_soc_fd_ != -1) {
-    ::close(bt_soc_fd_);
-    bt_soc_fd_ = -1;
-  }
-  rfKill(0);
-  free(rfkill_state_);
-}
-
-int BluetoothHci::waitHciDev(int hci_interface) {
-  struct sockaddr_hci addr;
-  struct pollfd fds[1];
-  struct mgmt_pkt ev;
-  int fd;
-  int ret = 0;
-
-  ALOGI( "%s", __func__);
-  fd = socket(PF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
-  if (fd < 0) {
-    ALOGE( "Bluetooth socket error: %s", strerror(errno));
-    return -1;
-  }
-  memset(&addr, 0, sizeof(addr));
-  addr.hci_family = AF_BLUETOOTH;
-  addr.hci_dev = HCI_DEV_NONE;
-  addr.hci_channel = HCI_CHANNEL_CONTROL;
-  if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
-    ALOGE( "HCI Channel Control: %s", strerror(errno));
-    ret = -1;
-    goto end;
-  }
-
-  fds[0].fd = fd;
-  fds[0].events = POLLIN;
-
-  /* Read Controller Index List Command */
-  ev.opcode = MGMT_OP_INDEX_LIST;
-  ev.index = HCI_DEV_NONE;
-  ev.len = 0;
-
-  ssize_t wrote;
-  WRITE_NO_INTR(wrote = write(fd, &ev, 6));
-  if (wrote != 6) {
-    ALOGE( "Unable to write mgmt command: %s", strerror(errno));
-    ret = -1;
-    goto end;
-  }
-  /* validate mentioned hci interface is present and registered with sock system */
-  while (1) {
-    int n;
-    WRITE_NO_INTR(n = poll(fds, 1, MGMT_EV_POLL_TIMEOUT));
-    if (n == -1) {
-      ALOGE( "Poll error: %s", strerror(errno));
-      ret = -1;
-      break;
-    } else if (n == 0) {
-      ALOGE( "Timeout, no HCI device detected");
-      ret = -1;
-      break;
-    }
-
-    if (fds[0].revents & POLLIN) {
-      WRITE_NO_INTR(n = read(fd, &ev, sizeof(struct mgmt_pkt)));
-      if (n < 0) {
-        ALOGE( "Error reading control channel: %s",
-                  strerror(errno));
-        ret = -1;
-        break;
-      }
+namespace implementation {
 
-      if (ev.opcode == MGMT_EV_INDEX_ADDED && ev.index == hci_interface) {
-        goto end;
-      } else if (ev.opcode == MGMT_EV_COMMAND_COMP) {
-        struct mgmt_event_read_index* cc;
-        int i;
-
-        cc = (struct mgmt_event_read_index*)ev.data;
-
-        if (cc->cc_opcode != MGMT_OP_INDEX_LIST || cc->status != 0) continue;
-
-        for (i = 0; i < cc->num_intf; i++) {
-          if (cc->index[i] == hci_interface) goto end;
-        }
-      }
-    }
-  }
-
-end:
-  ::close(fd);
-  return ret;
-}
-
-int BluetoothHci::findRfKill() {
-    char rfkill_type[64];
-    char type[16];
-    int fd, size, i;
-    for(i = 0; rfkill_state_ == NULL; i++)
-    {
-        snprintf(rfkill_type, sizeof(rfkill_type), "/sys/class/rfkill/rfkill%d/type", i);
-        if ((fd = open(rfkill_type, O_RDONLY)) < 0)
-        {
-            ALOGE("open(%s) failed: %s (%d)\n", rfkill_type, strerror(errno), errno);
-            return -1;
-        }
-
-        size = read(fd, &type, sizeof(type));
-        ::close(fd);
-
-        if ((size >= 9) && !memcmp(type, "bluetooth", 9))
-        {
-            ::asprintf(&rfkill_state_, "/sys/class/rfkill/rfkill%d/state", i);
-            break;
-        }
-    }
-    return 0;
-}
-
-int BluetoothHci::rfKill(int block) {
-  int fd;
-  char on = (block)?'1':'0';
-  if (findRfKill() != 0) return 0;
-
-  fd = open(rfkill_state_, O_WRONLY);
-  if (fd < 0) {
-    ALOGE( "Unable to open /dev/rfkill");
-    return -1;
-  }
-  ssize_t len;
-  WRITE_NO_INTR(len = write(fd, &on, 1));
-  if (len < 0) {
-    ALOGE( "Failed to change rfkill state");
-    ::close(fd);
-    return -1;
-  }
-  ::close(fd);
-  return 0;
-}
+static const uint8_t HCI_DATA_TYPE_COMMAND = 1;
+static const uint8_t HCI_DATA_TYPE_ACL = 2;
+static const uint8_t HCI_DATA_TYPE_SCO = 3;
 
 class BluetoothDeathRecipient : public hidl_death_recipient {
  public:
@@ -274,21 +63,39 @@ Return<void> BluetoothHci::initialize(
 
   death_recipient_->setHasDied(false);
   cb->linkToDeath(death_recipient_, 0);
-  int hci_fd = openBtHci();
-  auto hidl_status = cb->initializationComplete(
-          hci_fd > 0 ? Status::SUCCESS : Status::INITIALIZATION_ERROR);
-  if (!hidl_status.isOk()) {
+
+  bool rc = VendorInterface::Initialize(
+      [cb](bool status) {
+        auto hidl_status = cb->initializationComplete(
+            status ? Status::SUCCESS : Status::INITIALIZATION_ERROR);
+        if (!hidl_status.isOk()) {
+          ALOGE("VendorInterface -> Unable to call initializationComplete()");
+        }
+      },
+      [cb](const hidl_vec<uint8_t>& packet) {
+        auto hidl_status = cb->hciEventReceived(packet);
+        if (!hidl_status.isOk()) {
+          ALOGE("VendorInterface -> Unable to call hciEventReceived()");
+        }
+      },
+      [cb](const hidl_vec<uint8_t>& packet) {
+        auto hidl_status = cb->aclDataReceived(packet);
+        if (!hidl_status.isOk()) {
+          ALOGE("VendorInterface -> Unable to call aclDataReceived()");
+        }
+      },
+      [cb](const hidl_vec<uint8_t>& packet) {
+        auto hidl_status = cb->scoDataReceived(packet);
+        if (!hidl_status.isOk()) {
+          ALOGE("VendorInterface -> Unable to call scoDataReceived()");
+        }
+      });
+  if (!rc) {
+    auto hidl_status = cb->initializationComplete(Status::INITIALIZATION_ERROR);
+    if (!hidl_status.isOk()) {
       ALOGE("VendorInterface -> Unable to call initializationComplete(ERR)");
+    }
   }
-  hci::H4Protocol* h4_hci = new hci::H4Protocol(
-      hci_fd,
-      [cb](const hidl_vec<uint8_t>& packet) { cb->hciEventReceived(packet); },
-      [cb](const hidl_vec<uint8_t>& packet) { cb->aclDataReceived(packet); },
-      [cb](const hidl_vec<uint8_t>& packet) { cb->scoDataReceived(packet); });
-
-  fd_watcher_.WatchFdForNonBlockingReads(
-          hci_fd, [h4_hci](int fd) { h4_hci->OnDataReady(fd); });
-  hci_handle_ = h4_hci;
 
   unlink_cb_ = [cb](sp<BluetoothDeathRecipient>& death_recipient) {
     if (death_recipient->getHasDied())
@@ -303,13 +110,7 @@ Return<void> BluetoothHci::initialize(
 Return<void> BluetoothHci::close() {
   ALOGI("BluetoothHci::close()");
   unlink_cb_(death_recipient_);
-  fd_watcher_.StopWatchingFileDescriptors();
-
-  if (hci_handle_ != nullptr) {
-    delete hci_handle_;
-    hci_handle_ = nullptr;
-  }
-  closeBtHci();
+  VendorInterface::Shutdown();
   return Void();
 }
 
@@ -330,14 +131,14 @@ Return<void> BluetoothHci::sendScoData(const hidl_vec<uint8_t>& data) {
 
 void BluetoothHci::sendDataToController(const uint8_t type,
                                         const hidl_vec<uint8_t>& data) {
-  hci_handle_->Send(type, data.data(), data.size());
+  VendorInterface::get()->Send(type, data.data(), data.size());
 }
 
 IBluetoothHci* HIDL_FETCH_IBluetoothHci(const char* /* name */) {
   return new BluetoothHci();
 }
 
-}  // namespace btlinux
+}  // namespace implementation
 }  // namespace V1_0
 }  // namespace bluetooth
 }  // namespace hardware
index 5dc1c0a..e2797b1 100644 (file)
 
 #include <hidl/MQDescriptor.h>
 
-#include "async_fd_watcher.h"
-#include "h4_protocol.h"
-#include "hci_internals.h"
+#include <functional>
 
 namespace android {
 namespace hardware {
 namespace bluetooth {
 namespace V1_0 {
-namespace btlinux {
+namespace implementation {
 
 using ::android::hardware::Return;
 using ::android::hardware::hidl_vec;
@@ -47,21 +45,6 @@ class BluetoothHci : public IBluetoothHci {
   Return<void> close() override;
 
  private:
-  async::AsyncFdWatcher fd_watcher_;
-  hci::H4Protocol* hci_handle_;
-  int bt_soc_fd_;
-  char *rfkill_state_;
-
-  const uint8_t HCI_DATA_TYPE_COMMAND = 1;
-  const uint8_t HCI_DATA_TYPE_ACL = 2;
-  const uint8_t HCI_DATA_TYPE_SCO = 3;
-
-  int waitHciDev(int hci_interface);
-  int findRfKill(void);
-  int rfKill(int block);
-  int openBtHci(void);
-  void closeBtHci(void);
-
   void sendDataToController(const uint8_t type, const hidl_vec<uint8_t>& data);
   ::android::sp<BluetoothDeathRecipient> death_recipient_;
   std::function<void(sp<BluetoothDeathRecipient>&)> unlink_cb_;
@@ -69,7 +52,7 @@ class BluetoothHci : public IBluetoothHci {
 
 extern "C" IBluetoothHci* HIDL_FETCH_IBluetoothHci(const char* name);
 
-}  // namespace btlinux
+}  // namespace implementation
 }  // namespace V1_0
 }  // namespace bluetooth
 }  // namespace hardware
diff --git a/vendor_libs/linux/interface/bt_vendor_lib.h b/vendor_libs/linux/interface/bt_vendor_lib.h
new file mode 100644 (file)
index 0000000..c140e52
--- /dev/null
@@ -0,0 +1,435 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2009-2012 Broadcom Corporation
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#ifndef BT_VENDOR_LIB_H
+#define BT_VENDOR_LIB_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Struct types */
+
+/** Typedefs and defines */
+
+/** Vendor specific operations OPCODE */
+typedef enum {
+  /*  [operation]
+   *      Power on or off the BT Controller.
+   *  [input param]
+   *      A pointer to int type with content of bt_vendor_power_state_t.
+   *      Typecasting conversion: (int *) param.
+   *  [return]
+   *      0 - default, don't care.
+   *  [callback]
+   *      None.
+   */
+  BT_VND_OP_POWER_CTRL,
+
+  /*  [operation]
+   *      Perform any vendor specific initialization or configuration
+   *      on the BT Controller. This is called before stack initialization.
+   *  [input param]
+   *      None.
+   *  [return]
+   *      0 - default, don't care.
+   *  [callback]
+   *      Must call fwcfg_cb to notify the stack of the completion of vendor
+   *      specific initialization once it has been done.
+   */
+  BT_VND_OP_FW_CFG,
+
+  /*  [operation]
+   *      Perform any vendor specific SCO/PCM configuration on the BT
+   * Controller.
+   *      This is called after stack initialization.
+   *  [input param]
+   *      None.
+   *  [return]
+   *      0 - default, don't care.
+   *  [callback]
+   *      Must call scocfg_cb to notify the stack of the completion of vendor
+   *      specific SCO configuration once it has been done.
+   */
+  BT_VND_OP_SCO_CFG,
+
+  /*  [operation]
+   *      Open UART port on where the BT Controller is attached.
+   *      This is called before stack initialization.
+   *  [input param]
+   *      A pointer to int array type for open file descriptors.
+   *      The mapping of HCI channel to fd slot in the int array is given in
+   *      bt_vendor_hci_channels_t.
+   *      And, it requires the vendor lib to fill up the content before
+   * returning
+   *      the call.
+   *      Typecasting conversion: (int (*)[]) param.
+   *  [return]
+   *      Numbers of opened file descriptors.
+   *      Valid number:
+   *          1 - CMD/EVT/ACL-In/ACL-Out via the same fd (e.g. UART)
+   *          2 - CMD/EVT on one fd, and ACL-In/ACL-Out on the other fd
+   *          4 - CMD, EVT, ACL-In, ACL-Out are on their individual fd
+   *  [callback]
+   *      None.
+   */
+  BT_VND_OP_USERIAL_OPEN,
+
+  /*  [operation]
+   *      Close the previously opened UART port.
+   *  [input param]
+   *      None.
+   *  [return]
+   *      0 - default, don't care.
+   *  [callback]
+   *      None.
+   */
+  BT_VND_OP_USERIAL_CLOSE,
+
+  /*  [operation]
+   *      Get the LPM idle timeout in milliseconds.
+   *      The stack uses this information to launch a timer delay before it
+   *      attempts to de-assert LPM WAKE signal once downstream HCI packet
+   *      has been delivered.
+   *  [input param]
+   *      A pointer to uint32_t type which is passed in by the stack. And, it
+   *      requires the vendor lib to fill up the content before returning
+   *      the call.
+   *      Typecasting conversion: (uint32_t *) param.
+   *  [return]
+   *      0 - default, don't care.
+   *  [callback]
+   *      None.
+   */
+  BT_VND_OP_GET_LPM_IDLE_TIMEOUT,
+
+  /*  [operation]
+   *      Enable or disable LPM mode on BT Controller.
+   *  [input param]
+   *      A pointer to uint8_t type with content of bt_vendor_lpm_mode_t.
+   *      Typecasting conversion: (uint8_t *) param.
+   *  [return]
+   *      0 - default, don't care.
+   *  [callback]
+   *      Must call lpm_cb to notify the stack of the completion of LPM
+   *      disable/enable process once it has been done.
+   */
+  BT_VND_OP_LPM_SET_MODE,
+
+  /*  [operation]
+   *      Assert or Deassert LPM WAKE on BT Controller.
+   *  [input param]
+   *      A pointer to uint8_t type with content of bt_vendor_lpm_wake_state_t.
+   *      Typecasting conversion: (uint8_t *) param.
+   *  [return]
+   *      0 - default, don't care.
+   *  [callback]
+   *      None.
+   */
+  BT_VND_OP_LPM_WAKE_SET_STATE,
+
+  /*  [operation]
+   *      Perform any vendor specific commands related to audio state changes.
+   *  [input param]
+   *      a pointer to bt_vendor_op_audio_state_t indicating what audio state is
+   *      set.
+   *  [return]
+   *      0 - default, don't care.
+   *  [callback]
+   *      None.
+   */
+  BT_VND_OP_SET_AUDIO_STATE,
+
+  /*  [operation]
+   *      The epilog call to the vendor module so that it can perform any
+   *      vendor-specific processes (e.g. send a HCI_RESET to BT Controller)
+   *      before the caller calls for cleanup().
+   *  [input param]
+   *      None.
+   *  [return]
+   *      0 - default, don't care.
+   *  [callback]
+   *      Must call epilog_cb to notify the stack of the completion of vendor
+   *      specific epilog process once it has been done.
+   */
+  BT_VND_OP_EPILOG,
+
+  /*  [operation]
+   *      Call to the vendor module so that it can perform all vendor-specific
+   *      operations to start offloading a2dp media encode & tx.
+   *  [input param]
+   *      pointer to bt_vendor_op_a2dp_offload_start_t containing elements
+   *      required for VND FW to setup a2dp offload.
+   *  [return]
+   *      0  - default, dont care.
+   *  [callback]
+   *      Must call a2dp_offload_start_cb to notify the stack of the
+   *      completion of vendor specific setup process once it has been done.
+   */
+  BT_VND_OP_A2DP_OFFLOAD_START,
+
+  /*  [operation]
+   *      Call to the vendor module so that it can perform all vendor-specific
+   *      operations to suspend offloading a2dp media encode & tx.
+   *  [input param]
+   *      pointer to bt_vendor_op_a2dp_offload_t containing elements
+   *      required for VND FW to setup a2dp offload.
+   *  [return]
+   *      0  - default, dont care.
+   *  [callback]
+   *      Must call a2dp_offload_cb to notify the stack of the
+   *      completion of vendor specific setup process once it has been done.
+   */
+  BT_VND_OP_A2DP_OFFLOAD_STOP,
+
+} bt_vendor_opcode_t;
+
+/** Power on/off control states */
+typedef enum {
+  BT_VND_PWR_OFF,
+  BT_VND_PWR_ON,
+} bt_vendor_power_state_t;
+
+/** Define HCI channel identifier in the file descriptors array
+    used in BT_VND_OP_USERIAL_OPEN operation.
+ */
+typedef enum {
+  CH_CMD,      // HCI Command channel
+  CH_EVT,      // HCI Event channel
+  CH_ACL_OUT,  // HCI ACL downstream channel
+  CH_ACL_IN,   // HCI ACL upstream channel
+
+  CH_MAX  // Total channels
+} bt_vendor_hci_channels_t;
+
+/** LPM disable/enable request */
+typedef enum {
+  BT_VND_LPM_DISABLE,
+  BT_VND_LPM_ENABLE,
+} bt_vendor_lpm_mode_t;
+
+/** LPM WAKE set state request */
+typedef enum {
+  BT_VND_LPM_WAKE_ASSERT,
+  BT_VND_LPM_WAKE_DEASSERT,
+} bt_vendor_lpm_wake_state_t;
+
+/** Callback result values */
+typedef enum {
+  BT_VND_OP_RESULT_SUCCESS,
+  BT_VND_OP_RESULT_FAIL,
+} bt_vendor_op_result_t;
+
+/** audio (SCO) state changes triggering VS commands for configuration */
+typedef struct {
+  uint16_t handle;
+  uint16_t peer_codec;
+  uint16_t state;
+} bt_vendor_op_audio_state_t;
+
+/*
+ * Bluetooth Host/Controller Vendor callback structure.
+ */
+
+/* vendor initialization/configuration callback */
+typedef void (*cfg_result_cb)(bt_vendor_op_result_t result);
+
+/* datapath buffer allocation callback (callout)
+ *
+ *  Vendor lib needs to request a buffer through the alloc callout function
+ *  from HCI lib if the buffer is for constructing a HCI Command packet which
+ *  will be sent through xmit_cb to BT Controller.
+ *
+ *  For each buffer allocation, the requested size needs to be big enough to
+ *  accommodate the below header plus a complete HCI packet --
+ *      typedef struct
+ *      {
+ *          uint16_t          event;
+ *          uint16_t          len;
+ *          uint16_t          offset;
+ *          uint16_t          layer_specific;
+ *      } HC_BT_HDR;
+ *
+ *  HCI lib returns a pointer to the buffer where Vendor lib should use to
+ *  construct a HCI command packet as below format:
+ *
+ *  --------------------------------------------
+ *  |  HC_BT_HDR  |  HCI command               |
+ *  --------------------------------------------
+ *  where
+ *      HC_BT_HDR.event = 0x2000;
+ *      HC_BT_HDR.len = Length of HCI command;
+ *      HC_BT_HDR.offset = 0;
+ *      HC_BT_HDR.layer_specific = 0;
+ *
+ *  For example, a HCI_RESET Command will be formed as
+ *  ------------------------
+ *  |  HC_BT_HDR  |03|0c|00|
+ *  ------------------------
+ *  with
+ *      HC_BT_HDR.event = 0x2000;
+ *      HC_BT_HDR.len = 3;
+ *      HC_BT_HDR.offset = 0;
+ *      HC_BT_HDR.layer_specific = 0;
+ */
+typedef void* (*malloc_cb)(int size);
+
+/* datapath buffer deallocation callback (callout) */
+typedef void (*mdealloc_cb)(void* p_buf);
+
+/* define callback of the cmd_xmit_cb
+ *
+ *  The callback function which HCI lib will call with the return of command
+ *  complete packet. Vendor lib is responsible for releasing the buffer passed
+ *  in at the p_mem parameter by calling dealloc callout function.
+ */
+typedef void (*tINT_CMD_CBACK)(void* p_mem);
+
+/* hci command packet transmit callback (callout)
+ *
+ *  Vendor lib calls xmit_cb callout function in order to send a HCI Command
+ *  packet to BT Controller. The buffer carrying HCI Command packet content
+ *  needs to be first allocated through the alloc callout function.
+ *  HCI lib will release the buffer for Vendor lib once it has delivered the
+ *  packet content to BT Controller.
+ *
+ *  Vendor lib needs also provide a callback function (p_cback) which HCI lib
+ *  will call with the return of command complete packet.
+ *
+ *  The opcode parameter gives the HCI OpCode (combination of OGF and OCF) of
+ *  HCI Command packet. For example, opcode = 0x0c03 for the HCI_RESET command
+ *  packet.
+ */
+typedef uint8_t (*cmd_xmit_cb)(uint16_t opcode, void* p_buf,
+                               tINT_CMD_CBACK p_cback);
+
+typedef void (*cfg_a2dp_cb)(bt_vendor_op_result_t result, bt_vendor_opcode_t op,
+                            uint8_t bta_av_handle);
+
+typedef struct {
+  /** set to sizeof(bt_vendor_callbacks_t) */
+  size_t size;
+
+  /*
+   * Callback and callout functions have implemented in HCI libray
+   * (libbt-hci.so).
+   */
+
+  /* notifies caller result of firmware configuration request */
+  cfg_result_cb fwcfg_cb;
+
+  /* notifies caller result of sco configuration request */
+  cfg_result_cb scocfg_cb;
+
+  /* notifies caller result of lpm enable/disable */
+  cfg_result_cb lpm_cb;
+
+  /* notifies the result of codec setting */
+  cfg_result_cb audio_state_cb;
+
+  /* buffer allocation request */
+  malloc_cb alloc;
+
+  /* buffer deallocation request */
+  mdealloc_cb dealloc;
+
+  /* hci command packet transmit request */
+  cmd_xmit_cb xmit_cb;
+
+  /* notifies caller completion of epilog process */
+  cfg_result_cb epilog_cb;
+
+  /* notifies status of a2dp offload cmd's */
+  cfg_a2dp_cb a2dp_offload_cb;
+} bt_vendor_callbacks_t;
+
+/** A2DP offload request */
+typedef struct {
+  uint8_t bta_av_handle;  /* BTA_AV Handle for callbacks */
+  uint16_t xmit_quota;    /* Total ACL quota for light stack */
+  uint16_t acl_data_size; /* Max ACL data size across HCI transport */
+  uint16_t stream_mtu;
+  uint16_t local_cid;
+  uint16_t remote_cid;
+  uint16_t lm_handle;
+  uint8_t is_flushable; /* true if flushable channel */
+  uint32_t stream_source;
+  uint8_t codec_info[10]; /* Codec capabilities array */
+} bt_vendor_op_a2dp_offload_t;
+
+/*
+ * Bluetooth Host/Controller VENDOR Interface
+ */
+typedef struct {
+  /** Set to sizeof(bt_vndor_interface_t) */
+  size_t size;
+
+  /*
+   * Functions need to be implemented in Vendor libray (libbt-vendor.so).
+   */
+
+  /**
+   * Caller will open the interface and pass in the callback routines
+   * to the implemenation of this interface.
+   */
+  int (*init)(const bt_vendor_callbacks_t* p_cb, unsigned char* local_bdaddr);
+
+  /**  Vendor specific operations */
+  int (*op)(bt_vendor_opcode_t opcode, void* param);
+
+  /** Closes the interface */
+  void (*cleanup)(void);
+} bt_vendor_interface_t;
+
+/*
+ * External shared lib functions/data
+ */
+
+/* Entry point of DLib --
+ *      Vendor library needs to implement the body of bt_vendor_interface_t
+ *      structure and uses the below name as the variable name. HCI library
+ *      will use this symbol name to get address of the object through the
+ *      dlsym call.
+ */
+extern const bt_vendor_interface_t BLUETOOTH_VENDOR_LIB_INTERFACE;
+
+// MODIFICATION FOR NEW HAL/HIDL IMPLEMENTATION:
+// EXPOSE THE BT_HDR STRUCT HERE FOR THE VENDOR INTERFACE
+// ONLY, WITHOUT REQUIRING INCLUDES FROM system/bt OR OTHER
+// DIRECTORIES.
+// ONLY USED INSIDE transmit_cb.
+// DO NOT USE IN NEW HAL IMPLEMENTATIONS GOING FORWARD
+typedef struct
+{
+    uint16_t          event;
+    uint16_t          len;
+    uint16_t          offset;
+    uint16_t          layer_specific;
+    uint8_t           data[];
+} HC_BT_HDR;
+// /MODIFICATION
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* BT_VENDOR_LIB_H */
index e7acff4..0a7a524 100644 (file)
 //
 
 #include "h4_protocol.h"
+#include "esco_parameters.h"
+#include "hcidefs.h"
 
 #define LOG_TAG "android.hardware.bluetooth-hci-h4"
-#include <android-base/logging.h>
-#include <assert.h>
+
+#include <sys/ioctl.h>
+#include <linux/usbdevice_fs.h>
+#include <asm/byteorder.h>
+#include <linux/usb/ch9.h>
+#include <libusb/libusb.h>
+
+typedef uint8_t UINT8;
+typedef uint16_t UINT16;
+
+#define UINT16_TO_STREAM(p, u16) {*(p)++ = (UINT8)(u16); *(p)++ = (UINT8)((u16) >> 8);}
+#define UINT8_TO_STREAM(p, u8)   {*(p)++ = (UINT8)(u8);}
+#define STREAM_TO_UINT8(u8, p)   {u8 = (UINT8)(*(p)); (p) += 1;}
+#define STREAM_TO_UINT16(u16, p) {u16 = ((UINT16)(*(p)) + (((UINT16)(*((p) + 1))) << 8)); (p) += 2;}
+
+#define T2_MAXIMUM_LATENCY                        0x000D
+#define HCIC_PARAM_SIZE_ENH_ACC_ESCO_CONN         63
+
+#define INTEL_VID 0x8087
+#define INTEL_PID_8265 0x0a2b // Windstorm peak
+#define INTEL_PID_3168 0x0aa7 //SandyPeak (SdP)
+#define INTEL_PID_9260 0x0025 // 9160/9260 (also known as ThunderPeak)
+#define INTEL_PID_9560 0x0aaa // 9460/9560 also know as Jefferson Peak (JfP)
+
+#include <errno.h>
 #include <fcntl.h>
+#include <log/log.h>
 #include <sys/uio.h>
-#include <utils/Log.h>
+#include <unistd.h>
+#include <string.h>
 
 namespace android {
 namespace hardware {
@@ -39,6 +66,68 @@ size_t H4Protocol::Send(uint8_t type, const uint8_t* data, size_t length) {
     iov[0].iov_len = sizeof(type);
     iov[1].iov_base = (void *)data;
     iov[1].iov_len = length;
+
+    if (type == HCI_PACKET_TYPE_COMMAND) {
+        uint8_t* p;
+        void* r;
+        uint8_t* q;
+        uint16_t command;
+        uint8_t coding_format;
+        /* Marvell specific  Configuration */
+        const uint16_t input_coded_data_size = 8;
+        const uint16_t output_coded_data_size = 8;
+        const uint8_t input_transport_unit_size = 16;
+        const uint8_t output_transport_unit_size = 16;
+        const uint8_t packet_size = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_ENH_ACC_ESCO_CONN;
+        const uint16_t max_latency_ms = 13;
+
+        p = (uint8_t*)data;
+        STREAM_TO_UINT16(command, p);
+        p += 15; // Increment stream pinter to point coding format byte
+        STREAM_TO_UINT8(coding_format, p);
+
+        if ((command == HCI_ENH_ACCEPT_ESCO_CONNECTION) &&
+                                           (coding_format == ESCO_CODING_FORMAT_MSBC)) {
+            ALOGV("%s accept esco", __func__);
+            q = (uint8_t*)malloc(packet_size);
+
+            if (q == NULL) {
+                ALOGE("%s Memory allocation for SCO config parameters failed", __func__);
+            } else {
+                r = q;
+                memcpy(q, data, packet_size);
+                q += 49; // Increment stream pointer to point to input_coded_data_size
+                UINT16_TO_STREAM(q, input_coded_data_size);
+                UINT16_TO_STREAM(q, output_coded_data_size);
+                q += 6; // Increment stream pointer to point to input_transport_unit_size
+                UINT8_TO_STREAM(q, input_transport_unit_size);
+                UINT8_TO_STREAM(q, output_transport_unit_size);
+                UINT16_TO_STREAM(q, max_latency_ms);
+                /* Write T2 specific Settings */
+                UINT16_TO_STREAM(q, (ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 |
+                      ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5));
+
+                iov[1].iov_base = r;
+            }
+            while (1) {
+                ret = TEMP_FAILURE_RETRY(writev(uart_fd_, iov, 2));
+                if (ret == -1) {
+                    if (errno == EAGAIN) {
+                        ALOGE("%s error writing to UART (%s)", __func__, strerror(errno));
+                        continue;
+                    }
+                } else if (ret == 0) {
+                    ALOGE("%s zero bytes written - something went wrong...", __func__);
+                    break;
+                }
+                break;
+            }
+            free (q);
+            return ret;
+        }
+    }
+
+    ALOGV("%x %x %x", data[0],data[1],data[2]);
     while (1) {
         ret = TEMP_FAILURE_RETRY(writev(uart_fd_, iov, 2));
         if (ret == -1) {
@@ -47,7 +136,6 @@ size_t H4Protocol::Send(uint8_t type, const uint8_t* data, size_t length) {
                 continue;
             }
         } else if (ret == 0) {
-            // Nothing written :(
             ALOGE("%s zero bytes written - something went wrong...", __func__);
             break;
         }
@@ -56,9 +144,97 @@ size_t H4Protocol::Send(uint8_t type, const uint8_t* data, size_t length) {
     return ret;
 }
 
+bool H4Protocol::IsIntelController(uint16_t vid, uint16_t pid) {
+    if ((vid == INTEL_VID) && ((pid == INTEL_PID_8265) ||
+                                (pid == INTEL_PID_3168)||
+                                (pid == INTEL_PID_9260)||
+                                (pid == INTEL_PID_9560)))
+        return true;
+    else
+        return false;
+}
+
+void H4Protocol::GetUsbpath(void) {
+    size_t count, i;
+    int ret, busnum, devnum;
+    struct libusb_device **dev_list = NULL;
+    struct libusb_context *ctx;
+    uint16_t vid = 0, pid = 0;
+    ALOGD(" Initializing GenericUSB (libusb-1.0)...\n");
+    ret = libusb_init(&ctx);
+    if (ret < 0) {
+        ALOGE("libusb failed to initialize: %d\n", ret);
+        return;
+    }
+    count = libusb_get_device_list(ctx, &dev_list);
+    if (count <= 0) {
+        ALOGE("Error getting USB device list: %s\n", strerror(count));
+        libusb_exit(ctx);
+        return;
+    }
+    for (i = 0; i < count; ++i) {
+        struct libusb_device* dev = dev_list[i];
+        busnum = libusb_get_bus_number(dev);
+        devnum = libusb_get_device_address(dev);
+        struct libusb_device_descriptor descriptor;
+        ret = libusb_get_device_descriptor(dev, &descriptor);
+        if (ret < 0)  {
+            ALOGE("Error getting device descriptor %d ", ret);
+            goto exit;
+        }
+        vid = descriptor.idVendor;
+        pid = descriptor.idProduct;
+        if (H4Protocol::IsIntelController(vid, pid)) {
+            snprintf(dev_address, sizeof(dev_address), "/dev/bus/usb/%03d/%03d",
+                                                       busnum, devnum);
+            ALOGV("Value of BT device address = %s", dev_address);
+            goto exit;
+        }
+    }
+exit:
+    libusb_free_device_list(dev_list, count);
+    libusb_exit(ctx);
+}
+
+void H4Protocol::SendHandle(void) {
+    int fd,ret;
+    fd = open(dev_address,O_WRONLY|O_NONBLOCK);
+    if (fd < 0) {
+        ALOGE("Fail to open USB device %s, value of fd= %d", dev_address, fd);
+    } else {
+        struct usbdevfs_ioctl   wrapper;
+        wrapper.ifno = 1;
+        wrapper.ioctl_code = USBDEVFS_IOCTL;
+        wrapper.data = sco_handle;
+        ret = ioctl(fd, USBDEVFS_IOCTL, &wrapper);
+        if (ret < 0)
+            ALOGE("Failed to send SCO handle err = %d", ret);
+        close(fd);
+    }
+}
+
 void H4Protocol::OnPacketReady() {
   switch (hci_packet_type_) {
     case HCI_PACKET_TYPE_EVENT:
+        if ((hci_packetizer_.GetPacket())[0] == HCI_COMMAND_COMPLETE_EVT) {
+                unsigned int cmd, lsb, msb;
+                msb = hci_packetizer_.GetPacket()[4] ;
+                lsb = hci_packetizer_.GetPacket()[3];
+                cmd = msb << 8 | lsb ;
+
+                if (cmd == HCI_RESET) {
+                    event_cb_(hci_packetizer_.GetPacket());
+                    hci_packet_type_ = HCI_PACKET_TYPE_UNKNOWN;
+                    H4Protocol::GetUsbpath();
+                    return;
+                }
+        } else if ((hci_packetizer_.GetPacket())[0] == HCI_ESCO_CONNECTION_COMP_EVT) {
+             const unsigned char *handle = hci_packetizer_.GetPacket().data() + 3;
+             memcpy(sco_handle, handle, 2);
+             ALOGI("Value of SCO handle = %x, %x", handle[0], handle[1]);
+             H4Protocol::SendHandle();
+        }
+
       event_cb_(hci_packetizer_.GetPacket());
       break;
     case HCI_PACKET_TYPE_ACL_DATA:
@@ -67,18 +243,27 @@ void H4Protocol::OnPacketReady() {
     case HCI_PACKET_TYPE_SCO_DATA:
       sco_cb_(hci_packetizer_.GetPacket());
       break;
-    default: {
-      bool bad_packet_type = true;
-      CHECK(!bad_packet_type);
-    }
+    default:
+      LOG_ALWAYS_FATAL("%s: Unimplemented packet type %d", __func__,
+                       static_cast<int>(hci_packet_type_));
   }
   // Get ready for the next type byte.
   hci_packet_type_ = HCI_PACKET_TYPE_UNKNOWN;
 }
 
+
+typedef struct
+{
+    uint8_t         type;
+    uint8_t         event;
+    uint8_t         len;
+    uint8_t         offset;
+    uint16_t        layer_specific;
+} BT_EVENT_HDR;
+
 void H4Protocol::OnDataReady(int fd) {
     if (hci_packet_type_ == HCI_PACKET_TYPE_UNKNOWN) {
-        /**
+        /*
          * read full buffer. ACL max length is 2 bytes, and SCO max length is 2
          * byte. so taking 64K as buffer length.
          * Question : Why to read in single chunk rather than multiple reads,
@@ -94,9 +279,39 @@ void H4Protocol::OnDataReady(int fd) {
         const size_t max_plen = 64*1024;
         hidl_vec<uint8_t> tpkt;
         tpkt.resize(max_plen);
-        size_t bytes_read = TEMP_FAILURE_RETRY(read(fd, tpkt.data(), max_plen));
+        ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, tpkt.data(), max_plen));
+        if (bytes_read == 0) {
+            // This is only expected if the UART got closed when shutting down.
+            ALOGE("%s: Unexpected EOF reading the packet type!", __func__);
+            sleep(5);  // Expect to be shut down within 5 seconds.
+            return;
+        } else if (bytes_read < 0) {
+            LOG_ALWAYS_FATAL("%s: Read packet type error: %s", __func__,
+                         strerror(errno));
+        }
         hci_packet_type_ = static_cast<HciPacketType>(tpkt.data()[0]);
-        hci_packetizer_.CbHciPacket(tpkt.data()+1, bytes_read-1);
+        if (hci_packet_type_ != HCI_PACKET_TYPE_ACL_DATA &&
+            hci_packet_type_ != HCI_PACKET_TYPE_SCO_DATA &&
+            hci_packet_type_ != HCI_PACKET_TYPE_EVENT) {
+          LOG_ALWAYS_FATAL("%s: Unimplemented packet type %d", __func__,
+                           static_cast<int>(hci_packet_type_));
+        } else {
+            if (tpkt.data()[1] == HCI_COMMAND_COMPLETE_EVT) {
+                ALOGD("%s Command complete event ncmds = %d",
+                                                     __func__, tpkt.data()[3]);
+                tpkt.data()[3] = 1;
+               /* Disable Enhance setup synchronous connections*/
+                BT_EVENT_HDR* hdr  = (BT_EVENT_HDR*)(tpkt.data());
+                if (hdr->layer_specific == HCI_READ_LOCAL_SUPPORTED_CMDS)
+                        tpkt.data()[36] &= ~((uint8_t)0x1 << 3);
+
+            } else if (tpkt.data()[1] ==  HCI_COMMAND_STATUS_EVT) {
+                ALOGV("%s Command status event ncmd = %d", __func__, tpkt.data()[4]);
+                tpkt.data()[4] = 1;
+            }
+
+            hci_packetizer_.CbHciPacket(tpkt.data() + 1, bytes_read - 1);
+        }
     }
 }
 
index 612b0db..e2c350b 100644 (file)
 #include <hidl/HidlSupport.h>
 
 #include "async_fd_watcher.h"
+#include "bt_vendor_lib.h"
 #include "hci_internals.h"
-#include "hci_packetizer.h"
+#include "hci_protocol.h"
 
 namespace android {
 namespace hardware {
 namespace bluetooth {
 namespace hci {
 
-using ::android::hardware::hidl_vec;
-using PacketReadCallback = std::function<void(const hidl_vec<uint8_t>&)>;
-
-class H4Protocol {
+class H4Protocol : public HciProtocol {
  public:
   H4Protocol(int fd, PacketReadCallback event_cb, PacketReadCallback acl_cb,
              PacketReadCallback sco_cb)
@@ -46,15 +44,25 @@ class H4Protocol {
 
   void OnDataReady(int fd);
 
+  bool IsIntelController(uint16_t vid, uint16_t pid);
+
+  void GetUsbpath(void);
+
+  void SendHandle(void);
+
  private:
   int uart_fd_;
 
+  uint8_t sco_handle[2];
+
+  char dev_address[32];
+
   PacketReadCallback event_cb_;
   PacketReadCallback acl_cb_;
   PacketReadCallback sco_cb_;
 
   HciPacketType hci_packet_type_{HCI_PACKET_TYPE_UNKNOWN};
-  HciPacketizer hci_packetizer_;
+  hci::HciPacketizer hci_packetizer_;
 };
 
 }  // namespace hci
index 6016cad..8c970c2 100644 (file)
 #include "hci_packetizer.h"
 
 #define LOG_TAG "android.hardware.bluetooth.hci_packetizer"
-#include <android-base/logging.h>
-#include <utils/Log.h>
 
 #include <dlfcn.h>
+#include <errno.h>
 #include <fcntl.h>
+#include <unistd.h>
+#include <utils/Log.h>
 
 namespace {
 
@@ -45,21 +46,31 @@ namespace hardware {
 namespace bluetooth {
 namespace hci {
 
-const hidl_vec<uint8_t>& HciPacketizer::GetPacket() const { return packet_; }
+const hidl_vec<uint8_t>& HciPacketizer::GetPacket() const {
+  return packet_;
+}
 
 void HciPacketizer::CbHciPacket(uint8_t *data, size_t len) {
     packet_.setToExternal(data, len);
     packet_ready_cb_();
 }
 
-#if 0
 void HciPacketizer::OnDataReady(int fd, HciPacketType packet_type) {
   switch (state_) {
     case HCI_PREAMBLE: {
-      size_t bytes_read = TEMP_FAILURE_RETRY(
+      ssize_t bytes_read = TEMP_FAILURE_RETRY(
           read(fd, preamble_ + bytes_read_,
                preamble_size_for_type[packet_type] - bytes_read_));
-      CHECK(bytes_read > 0);
+      if (bytes_read == 0) {
+        // This is only expected if the UART got closed when shutting down.
+        ALOGE("%s: Unexpected EOF reading the header!", __func__);
+        sleep(5);  // Expect to be shut down within 5 seconds.
+        return;
+      }
+      if (bytes_read < 0) {
+        LOG_ALWAYS_FATAL("%s: Read header error: %s", __func__,
+                         strerror(errno));
+      }
       bytes_read_ += bytes_read;
       if (bytes_read_ == preamble_size_for_type[packet_type]) {
         size_t packet_length =
@@ -74,11 +85,20 @@ void HciPacketizer::OnDataReady(int fd, HciPacketType packet_type) {
     }
 
     case HCI_PAYLOAD: {
-      size_t bytes_read = TEMP_FAILURE_RETRY(read(
+      ssize_t bytes_read = TEMP_FAILURE_RETRY(read(
           fd,
           packet_.data() + preamble_size_for_type[packet_type] + bytes_read_,
           bytes_remaining_));
-      CHECK(bytes_read > 0);
+      if (bytes_read == 0) {
+        // This is only expected if the UART got closed when shutting down.
+        ALOGE("%s: Unexpected EOF reading the payload!", __func__);
+        sleep(5);  // Expect to be shut down within 5 seconds.
+        return;
+      }
+      if (bytes_read < 0) {
+        LOG_ALWAYS_FATAL("%s: Read payload error: %s", __func__,
+                         strerror(errno));
+      }
       bytes_remaining_ -= bytes_read;
       bytes_read_ += bytes_read;
       if (bytes_remaining_ == 0) {
@@ -90,7 +110,6 @@ void HciPacketizer::OnDataReady(int fd, HciPacketType packet_type) {
     }
   }
 }
-#endif
 
 }  // namespace hci
 }  // namespace bluetooth
diff --git a/vendor_libs/linux/interface/hci_protocol.cc b/vendor_libs/linux/interface/hci_protocol.cc
new file mode 100644 (file)
index 0000000..bf94dfe
--- /dev/null
@@ -0,0 +1,58 @@
+//
+// Copyright 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "hci_protocol.h"
+
+#define LOG_TAG "android.hardware.bluetooth-hci-hci_protocol"
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <log/log.h>
+
+namespace android {
+namespace hardware {
+namespace bluetooth {
+namespace hci {
+
+size_t HciProtocol::WriteSafely(int fd, const uint8_t* data, size_t length) {
+  size_t transmitted_length = 0;
+  while (length > 0) {
+    ssize_t ret =
+        TEMP_FAILURE_RETRY(write(fd, data + transmitted_length, length));
+
+    if (ret == -1) {
+      if (errno == EAGAIN) continue;
+      ALOGE("%s error writing to UART (%s)", __func__, strerror(errno));
+      break;
+
+    } else if (ret == 0) {
+      // Nothing written :(
+      ALOGE("%s zero bytes written - something went wrong...", __func__);
+      break;
+    }
+
+    transmitted_length += ret;
+    length -= ret;
+  }
+
+  return transmitted_length;
+}
+
+}  // namespace hci
+}  // namespace bluetooth
+}  // namespace hardware
+}  // namespace android
diff --git a/vendor_libs/linux/interface/hci_protocol.h b/vendor_libs/linux/interface/hci_protocol.h
new file mode 100644 (file)
index 0000000..6821107
--- /dev/null
@@ -0,0 +1,49 @@
+//
+// Copyright 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#pragma once
+
+#include <hidl/HidlSupport.h>
+
+#include "bt_vendor_lib.h"
+#include "hci_internals.h"
+#include "hci_packetizer.h"
+
+namespace android {
+namespace hardware {
+namespace bluetooth {
+namespace hci {
+
+using ::android::hardware::hidl_vec;
+using PacketReadCallback = std::function<void(const hidl_vec<uint8_t>&)>;
+
+// Implementation of HCI protocol bits common to different transports
+class HciProtocol {
+ public:
+  HciProtocol() = default;
+  virtual ~HciProtocol(){};
+
+  // Protocol-specific implementation of sending packets.
+  virtual size_t Send(uint8_t type, const uint8_t* data, size_t length) = 0;
+
+ protected:
+  static size_t WriteSafely(int fd, const uint8_t* data, size_t length);
+};
+
+}  // namespace hci
+}  // namespace bluetooth
+}  // namespace hardware
+}  // namespace android
diff --git a/vendor_libs/linux/interface/mct_protocol.cc b/vendor_libs/linux/interface/mct_protocol.cc
new file mode 100644 (file)
index 0000000..2a59187
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// Copyright 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "mct_protocol.h"
+
+#include <assert.h>
+
+#define LOG_TAG "android.hardware.bluetooth-hci-mct"
+#include <utils/Log.h>
+
+#include <fcntl.h>
+
+namespace android {
+namespace hardware {
+namespace bluetooth {
+namespace hci {
+
+MctProtocol::MctProtocol(int* fds, PacketReadCallback event_cb,
+                         PacketReadCallback acl_cb)
+    : event_cb_(event_cb),
+      acl_cb_(acl_cb),
+      event_packetizer_([this]() { OnEventPacketReady(); }),
+      acl_packetizer_([this]() { OnAclDataPacketReady(); }) {
+  for (int i = 0; i < CH_MAX; i++) {
+    uart_fds_[i] = fds[i];
+  }
+}
+
+size_t MctProtocol::Send(uint8_t type, const uint8_t* data, size_t length) {
+  if (type == HCI_PACKET_TYPE_COMMAND)
+    return WriteSafely(uart_fds_[CH_CMD], data, length);
+  if (type == HCI_PACKET_TYPE_ACL_DATA)
+    return WriteSafely(uart_fds_[CH_ACL_OUT], data, length);
+  LOG_ALWAYS_FATAL("%s: Unimplemented packet type = %d", __func__, type);
+  return 0;
+}
+
+void MctProtocol::OnEventPacketReady() {
+  event_cb_(event_packetizer_.GetPacket());
+}
+
+void MctProtocol::OnAclDataPacketReady() {
+  acl_cb_(acl_packetizer_.GetPacket());
+}
+
+void MctProtocol::OnEventDataReady(int fd) {
+  event_packetizer_.OnDataReady(fd, HCI_PACKET_TYPE_EVENT);
+}
+
+void MctProtocol::OnAclDataReady(int fd) {
+  acl_packetizer_.OnDataReady(fd, HCI_PACKET_TYPE_ACL_DATA);
+}
+
+}  // namespace hci
+}  // namespace bluetooth
+}  // namespace hardware
+}  // namespace android
diff --git a/vendor_libs/linux/interface/mct_protocol.h b/vendor_libs/linux/interface/mct_protocol.h
new file mode 100644 (file)
index 0000000..6991746
--- /dev/null
@@ -0,0 +1,56 @@
+//
+// Copyright 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#pragma once
+
+#include <hidl/HidlSupport.h>
+
+#include "async_fd_watcher.h"
+#include "bt_vendor_lib.h"
+#include "hci_internals.h"
+#include "hci_protocol.h"
+
+namespace android {
+namespace hardware {
+namespace bluetooth {
+namespace hci {
+
+class MctProtocol : public HciProtocol {
+ public:
+  MctProtocol(int* fds, PacketReadCallback event_cb, PacketReadCallback acl_cb);
+
+  size_t Send(uint8_t type, const uint8_t* data, size_t length);
+
+  void OnEventPacketReady();
+  void OnAclDataPacketReady();
+
+  void OnEventDataReady(int fd);
+  void OnAclDataReady(int fd);
+
+ private:
+  int uart_fds_[CH_MAX];
+
+  PacketReadCallback event_cb_;
+  PacketReadCallback acl_cb_;
+
+  hci::HciPacketizer event_packetizer_;
+  hci::HciPacketizer acl_packetizer_;
+};
+
+}  // namespace hci
+}  // namespace bluetooth
+}  // namespace hardware
+}  // namespace android
index fac9ce0..6019d75 100644 (file)
@@ -1,5 +1,5 @@
 //
-// Copyright 2017 The Android Open Source Project
+// Copyright 2016 The Android Open Source Project
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 #include <android/hardware/bluetooth/1.0/IBluetoothHci.h>
 #include <hidl/HidlSupport.h>
 #include <hidl/HidlTransportSupport.h>
-#include <utils/Log.h>
+
 
 #include "bluetooth_hci.h"
 
 using ::android::hardware::configureRpcThreadpool;
 using ::android::hardware::bluetooth::V1_0::IBluetoothHci;
-using ::android::hardware::bluetooth::V1_0::btlinux::BluetoothHci;
+using ::android::hardware::bluetooth::V1_0::implementation::BluetoothHci;
 using ::android::hardware::joinRpcThreadpool;
 using ::android::sp;
 
 int main(int /* argc */, char** /* argv */) {
   sp<IBluetoothHci> bluetooth = new BluetoothHci;
   configureRpcThreadpool(1, true);
-  android::status_t status = bluetooth->registerAsService();
-  if (status == android::OK)
-    joinRpcThreadpool();
-  else
-    ALOGE("Could not register as a service!");
+  bluetooth->registerAsService();
+  joinRpcThreadpool();
 }
diff --git a/vendor_libs/linux/interface/vendor_interface.cc b/vendor_libs/linux/interface/vendor_interface.cc
new file mode 100644 (file)
index 0000000..41c7541
--- /dev/null
@@ -0,0 +1,426 @@
+//
+// Copyright 2016 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "vendor_interface.h"
+
+#define LOG_TAG "android.hardware.bluetooth@1.0-service.btlinux"
+#include <cutils/properties.h>
+#include <utils/Log.h>
+
+#include <dlfcn.h>
+#include <fcntl.h>
+
+#include "esco_parameters.h"
+#include "hcidefs.h"
+
+#include "bluetooth_address.h"
+#include "h4_protocol.h"
+#include "mct_protocol.h"
+
+typedef uint8_t UINT8;
+typedef uint16_t UINT16;
+
+#define STREAM_TO_UINT8(u8, p)   {u8 = (UINT8)(*(p)); (p) += 1;}
+#define STREAM_TO_UINT16(u16, p) {u16 = ((UINT16)(*(p)) + (((UINT16)(*((p) + 1))) << 8)); (p) += 2;}
+
+static const char* VENDOR_LIBRARY_NAME = "libbt-vendor.so";
+static const char* VENDOR_LIBRARY_SYMBOL_NAME =
+    "BLUETOOTH_VENDOR_LIB_INTERFACE";
+
+static const int INVALID_FD = -1;
+
+namespace {
+
+using android::hardware::bluetooth::V1_0::implementation::VendorInterface;
+using android::hardware::hidl_vec;
+
+struct {
+  tINT_CMD_CBACK cb;
+  uint16_t opcode;
+} internal_command;
+
+// True when LPM is not enabled yet or wake is not asserted.
+bool lpm_wake_deasserted;
+uint32_t lpm_timeout_ms;
+bool recent_activity_flag;
+
+VendorInterface* g_vendor_interface = nullptr;
+std::mutex wakeup_mutex_;
+
+HC_BT_HDR* WrapPacketAndCopy(uint16_t event, const hidl_vec<uint8_t>& data) {
+  size_t packet_size = data.size() + sizeof(HC_BT_HDR);
+  HC_BT_HDR* packet = reinterpret_cast<HC_BT_HDR*>(new uint8_t[packet_size]);
+  packet->offset = 0;
+  packet->len = data.size();
+  packet->layer_specific = 0;
+  packet->event = event;
+  // TODO(eisenbach): Avoid copy here; if BT_HDR->data can be ensured to
+  // be the only way the data is accessed, a pointer could be passed here...
+  memcpy(packet->data, data.data(), data.size());
+  return packet;
+}
+
+bool internal_command_event_match(const hidl_vec<uint8_t>& packet) {
+  uint8_t event_code = packet[0];
+  if (event_code != HCI_COMMAND_COMPLETE_EVENT) {
+    ALOGE("%s: Unhandled event type %02X", __func__, event_code);
+    return false;
+  }
+
+  size_t opcode_offset = HCI_EVENT_PREAMBLE_SIZE + 1;  // Skip num packets.
+
+  uint16_t opcode = packet[opcode_offset] | (packet[opcode_offset + 1] << 8);
+
+  ALOGV("%s internal_command.opcode = %04X opcode = %04x", __func__,
+        internal_command.opcode, opcode);
+  return opcode == internal_command.opcode;
+}
+
+uint8_t transmit_cb(uint16_t opcode, void* buffer, tINT_CMD_CBACK callback) {
+  ALOGV("%s opcode: 0x%04x, ptr: %p, cb: %p", __func__, opcode, buffer,
+        callback);
+  internal_command.cb = callback;
+  internal_command.opcode = opcode;
+  uint8_t type = HCI_PACKET_TYPE_COMMAND;
+  HC_BT_HDR* bt_hdr = reinterpret_cast<HC_BT_HDR*>(buffer);
+  VendorInterface::get()->Send(type, bt_hdr->data, bt_hdr->len);
+  delete[] reinterpret_cast<uint8_t*>(buffer);
+  return true;
+}
+
+void firmware_config_cb(bt_vendor_op_result_t result) {
+  ALOGV("%s result: %d", __func__, result);
+  VendorInterface::get()->OnFirmwareConfigured(result);
+}
+
+void sco_config_cb(bt_vendor_op_result_t result) {
+  ALOGD("%s result: %d", __func__, result);
+}
+
+void low_power_mode_cb(bt_vendor_op_result_t result) {
+  ALOGD("%s result: %d", __func__, result);
+}
+
+void sco_audiostate_cb(bt_vendor_op_result_t result) {
+  ALOGD("%s result: %d", __func__, result);
+}
+
+void* buffer_alloc_cb(int size) {
+  void* p = new uint8_t[size];
+  ALOGV("%s pts: %p, size: %d", __func__, p, size);
+  return p;
+}
+
+void buffer_free_cb(void* buffer) {
+  ALOGV("%s ptr: %p", __func__, buffer);
+  delete[] reinterpret_cast<uint8_t*>(buffer);
+}
+
+void epilog_cb(bt_vendor_op_result_t result) {
+  ALOGD("%s result: %d", __func__, result);
+}
+
+void a2dp_offload_cb(bt_vendor_op_result_t result, bt_vendor_opcode_t op,
+                     uint8_t av_handle) {
+  ALOGD("%s result: %d, op: %d, handle: %d", __func__, result, op, av_handle);
+}
+
+const bt_vendor_callbacks_t lib_callbacks = {
+    sizeof(lib_callbacks), firmware_config_cb, sco_config_cb,
+    low_power_mode_cb,     sco_audiostate_cb,  buffer_alloc_cb,
+    buffer_free_cb,        transmit_cb,        epilog_cb,
+    a2dp_offload_cb};
+
+}  // namespace
+
+namespace android {
+namespace hardware {
+namespace bluetooth {
+namespace V1_0 {
+namespace implementation {
+
+class FirmwareStartupTimer {
+ public:
+  FirmwareStartupTimer() : start_time_(std::chrono::steady_clock::now()) {}
+
+  ~FirmwareStartupTimer() {
+    std::chrono::duration<double> duration =
+        std::chrono::steady_clock::now() - start_time_;
+    double s = duration.count();
+    if (s == 0) return;
+    ALOGI("Firmware configured in %.3fs", s);
+  }
+
+ private:
+  std::chrono::steady_clock::time_point start_time_;
+};
+
+bool VendorInterface::Initialize(
+    InitializeCompleteCallback initialize_complete_cb,
+    PacketReadCallback event_cb, PacketReadCallback acl_cb,
+    PacketReadCallback sco_cb) {
+  if (g_vendor_interface) {
+    ALOGE("%s: No previous Shutdown()?", __func__);
+    return false;
+  }
+  g_vendor_interface = new VendorInterface();
+  return g_vendor_interface->Open(initialize_complete_cb, event_cb, acl_cb,
+                                  sco_cb);
+}
+
+void VendorInterface::Shutdown() {
+  LOG_ALWAYS_FATAL_IF(!g_vendor_interface, "%s: No Vendor interface!",
+                      __func__);
+  g_vendor_interface->Close();
+  delete g_vendor_interface;
+  g_vendor_interface = nullptr;
+}
+
+VendorInterface* VendorInterface::get() { return g_vendor_interface; }
+
+bool VendorInterface::Open(InitializeCompleteCallback initialize_complete_cb,
+                           PacketReadCallback event_cb,
+                           PacketReadCallback acl_cb,
+                           PacketReadCallback sco_cb) {
+  initialize_complete_cb_ = initialize_complete_cb;
+
+  // Initialize vendor interface
+
+  lib_handle_ = dlopen(VENDOR_LIBRARY_NAME, RTLD_NOW);
+  if (!lib_handle_) {
+    ALOGE("%s unable to open %s (%s)", __func__, VENDOR_LIBRARY_NAME,
+          dlerror());
+    return false;
+  }
+
+  lib_interface_ = reinterpret_cast<bt_vendor_interface_t*>(
+      dlsym(lib_handle_, VENDOR_LIBRARY_SYMBOL_NAME));
+  if (!lib_interface_) {
+    ALOGE("%s unable to find symbol %s in %s (%s)", __func__,
+          VENDOR_LIBRARY_SYMBOL_NAME, VENDOR_LIBRARY_NAME, dlerror());
+    return false;
+  }
+
+  old_coding_format = ESCO_CODING_FORMAT_MSBC;
+
+  // Get the local BD address
+
+  uint8_t local_bda[BluetoothAddress::kBytes];
+  if (!BluetoothAddress::get_local_address(local_bda)) {
+    LOG_ALWAYS_FATAL("%s: No Bluetooth Address!", __func__);
+  }
+  int status = lib_interface_->init(&lib_callbacks, (unsigned char*)local_bda);
+  if (status) {
+    ALOGE("%s unable to initialize vendor library: %d", __func__, status);
+    return false;
+  }
+
+  ALOGD("%s vendor library loaded", __func__);
+
+  // Power on the controller
+
+  int power_state = BT_VND_PWR_ON;
+  lib_interface_->op(BT_VND_OP_POWER_CTRL, &power_state);
+
+  // Get the UART socket(s)
+
+  int fd_list[CH_MAX] = {0};
+  int fd_count = lib_interface_->op(BT_VND_OP_USERIAL_OPEN, &fd_list);
+
+  if (fd_count < 1 || fd_count > CH_MAX - 1) {
+    ALOGE("%s: fd_count %d is invalid!", __func__, fd_count);
+    return false;
+  }
+
+  for (int i = 0; i < fd_count; i++) {
+    if (fd_list[i] == INVALID_FD) {
+      ALOGE("%s: fd %d is invalid!", __func__, fd_list[i]);
+      return false;
+    }
+  }
+
+  event_cb_ = event_cb;
+  PacketReadCallback intercept_events = [this](const hidl_vec<uint8_t>& event) {
+    HandleIncomingEvent(event);
+  };
+
+  if (fd_count == 1) {
+    hci::H4Protocol* h4_hci =
+        new hci::H4Protocol(fd_list[0], intercept_events, acl_cb, sco_cb);
+    fd_watcher_.WatchFdForNonBlockingReads(
+        fd_list[0], [h4_hci](int fd) { h4_hci->OnDataReady(fd); });
+    hci_ = h4_hci;
+  } else {
+    hci::MctProtocol* mct_hci =
+        new hci::MctProtocol(fd_list, intercept_events, acl_cb);
+    fd_watcher_.WatchFdForNonBlockingReads(
+        fd_list[CH_EVT], [mct_hci](int fd) { mct_hci->OnEventDataReady(fd); });
+    fd_watcher_.WatchFdForNonBlockingReads(
+        fd_list[CH_ACL_IN],
+        [mct_hci](int fd) { mct_hci->OnAclDataReady(fd); });
+    hci_ = mct_hci;
+  }
+
+  // Initially, the power management is off.
+  lpm_wake_deasserted = true;
+
+  // Start configuring the firmware
+  firmware_startup_timer_ = new FirmwareStartupTimer();
+  lib_interface_->op(BT_VND_OP_FW_CFG, nullptr);
+
+  return true;
+}
+
+void VendorInterface::Close() {
+  // These callbacks may send HCI events (vendor-dependent), so make sure to
+  // StopWatching the file descriptor after this.
+  if (lib_interface_ != nullptr) {
+    bt_vendor_lpm_mode_t mode = BT_VND_LPM_DISABLE;
+    lib_interface_->op(BT_VND_OP_LPM_SET_MODE, &mode);
+  }
+
+  fd_watcher_.StopWatchingFileDescriptors();
+
+  if (hci_ != nullptr) {
+    delete hci_;
+    hci_ = nullptr;
+  }
+
+  if (lib_interface_ != nullptr) {
+    lib_interface_->op(BT_VND_OP_USERIAL_CLOSE, nullptr);
+
+    int power_state = BT_VND_PWR_OFF;
+    lib_interface_->op(BT_VND_OP_POWER_CTRL, &power_state);
+
+    lib_interface_->cleanup();
+  }
+
+  if (lib_handle_ != nullptr) {
+    dlclose(lib_handle_);
+    lib_handle_ = nullptr;
+  }
+
+  if (firmware_startup_timer_ != nullptr) {
+    delete firmware_startup_timer_;
+    firmware_startup_timer_ = nullptr;
+  }
+}
+
+size_t VendorInterface::Send(uint8_t type, const uint8_t* data, size_t length) {
+  std::unique_lock<std::mutex> lock(wakeup_mutex_);
+  recent_activity_flag = true;
+
+  if (lpm_wake_deasserted == true) {
+    // Restart the timer.
+    fd_watcher_.ConfigureTimeout(std::chrono::milliseconds(lpm_timeout_ms),
+                                 [this]() { OnTimeout(); });
+    // Assert wake.
+    lpm_wake_deasserted = false;
+    bt_vendor_lpm_wake_state_t wakeState = BT_VND_LPM_WAKE_ASSERT;
+    lib_interface_->op(BT_VND_OP_LPM_WAKE_SET_STATE, &wakeState);
+    ALOGV("%s: Sent wake before (%02x)", __func__, data[0] | (data[1] << 8));
+  }
+  if (type == HCI_PACKET_TYPE_COMMAND) {
+      uint8_t* p;
+      uint16_t command;
+      uint8_t coding_format = 0;
+      int codec = 0x02;
+      p = (uint8_t*)data;
+      STREAM_TO_UINT16(command, p);
+
+      if (command == HCI_ENH_ACCEPT_ESCO_CONNECTION) {
+          p += 15; // Increment stream pointer to point to the coding format byte
+          STREAM_TO_UINT8(coding_format, p);
+      } else if (command == HCI_ENH_SETUP_ESCO_CONNECTION) {
+          p += 11; // Increment stream pointer to point to the coding format byte
+          STREAM_TO_UINT8(coding_format, p);
+      }
+      if (coding_format != 0 && coding_format != old_coding_format) {
+          if (coding_format == ESCO_CODING_FORMAT_MSBC) {
+              codec = 0x02;
+          } else if (coding_format == ESCO_CODING_FORMAT_CVSD) {
+              codec = 0x01;
+          }
+
+          old_coding_format = coding_format;
+          lib_interface_->op(BT_VND_OP_SET_AUDIO_STATE, (int*)&codec);
+      }
+  }
+
+  return hci_->Send(type, data, length);
+}
+
+void VendorInterface::OnFirmwareConfigured(uint8_t result) {
+  ALOGD("%s result: %d", __func__, result);
+
+  if (firmware_startup_timer_ != nullptr) {
+    delete firmware_startup_timer_;
+    firmware_startup_timer_ = nullptr;
+  }
+
+  if (initialize_complete_cb_ != nullptr) {
+    initialize_complete_cb_(result == 0);
+    initialize_complete_cb_ = nullptr;
+  }
+
+  // Post load
+  lib_interface_->op(BT_VND_OP_SCO_CFG, NULL);
+  ALOGI("%s: SCO configuration initiated ", __func__);
+
+  lib_interface_->op(BT_VND_OP_GET_LPM_IDLE_TIMEOUT, &lpm_timeout_ms);
+  ALOGI("%s: lpm_timeout_ms %d", __func__, lpm_timeout_ms);
+
+  bt_vendor_lpm_mode_t mode = BT_VND_LPM_ENABLE;
+  lib_interface_->op(BT_VND_OP_LPM_SET_MODE, &mode);
+
+  ALOGD("%s Calling StartLowPowerWatchdog()", __func__);
+  fd_watcher_.ConfigureTimeout(std::chrono::milliseconds(lpm_timeout_ms),
+                               [this]() { OnTimeout(); });
+}
+
+void VendorInterface::OnTimeout() {
+  ALOGV("%s", __func__);
+  std::unique_lock<std::mutex> lock(wakeup_mutex_);
+  if (recent_activity_flag == false) {
+    lpm_wake_deasserted = true;
+    bt_vendor_lpm_wake_state_t wakeState = BT_VND_LPM_WAKE_DEASSERT;
+    lib_interface_->op(BT_VND_OP_LPM_WAKE_SET_STATE, &wakeState);
+    fd_watcher_.ConfigureTimeout(std::chrono::seconds(0), []() {
+      ALOGE("Zero timeout! Should never happen.");
+    });
+  }
+  recent_activity_flag = false;
+}
+
+void VendorInterface::HandleIncomingEvent(const hidl_vec<uint8_t>& hci_packet) {
+  if (internal_command.cb != nullptr &&
+      internal_command_event_match(hci_packet)) {
+    HC_BT_HDR* bt_hdr = WrapPacketAndCopy(HCI_PACKET_TYPE_EVENT, hci_packet);
+
+    // The callbacks can send new commands, so don't zero after calling.
+    tINT_CMD_CBACK saved_cb = internal_command.cb;
+    internal_command.cb = nullptr;
+    saved_cb(bt_hdr);
+  } else {
+    event_cb_(hci_packet);
+  }
+}
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace bluetooth
+}  // namespace hardware
+}  // namespace android
diff --git a/vendor_libs/linux/interface/vendor_interface.h b/vendor_libs/linux/interface/vendor_interface.h
new file mode 100644 (file)
index 0000000..17f68db
--- /dev/null
@@ -0,0 +1,77 @@
+//
+// Copyright 2016 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#pragma once
+
+#include <hidl/HidlSupport.h>
+
+#include "async_fd_watcher.h"
+#include "bt_vendor_lib.h"
+#include "hci_protocol.h"
+
+namespace android {
+namespace hardware {
+namespace bluetooth {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::hidl_vec;
+using InitializeCompleteCallback = std::function<void(bool success)>;
+using PacketReadCallback = std::function<void(const hidl_vec<uint8_t>&)>;
+
+class FirmwareStartupTimer;
+
+class VendorInterface {
+ public:
+  static bool Initialize(InitializeCompleteCallback initialize_complete_cb,
+                         PacketReadCallback event_cb, PacketReadCallback acl_cb,
+                         PacketReadCallback sco_cb);
+  static void Shutdown();
+  static VendorInterface *get();
+
+  size_t Send(uint8_t type, const uint8_t *data, size_t length);
+
+  void OnFirmwareConfigured(uint8_t result);
+
+ private:
+  virtual ~VendorInterface() = default;
+
+  bool Open(InitializeCompleteCallback initialize_complete_cb,
+            PacketReadCallback event_cb, PacketReadCallback acl_cb,
+            PacketReadCallback sco_cb);
+  void Close();
+
+  void OnTimeout();
+
+  void HandleIncomingEvent(const hidl_vec<uint8_t>& hci_packet);
+
+  void *lib_handle_;
+  bt_vendor_interface_t *lib_interface_;
+  async::AsyncFdWatcher fd_watcher_;
+  InitializeCompleteCallback initialize_complete_cb_;
+  hci::HciProtocol* hci_;
+
+  PacketReadCallback event_cb_;
+
+  FirmwareStartupTimer *firmware_startup_timer_;
+  uint8_t old_coding_format;
+};
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace bluetooth
+}  // namespace hardware
+}  // namespace android