Merge "[sensors] SENSOR_TYPE_DYNAMIC_SENSOR_META should be wake up"
diff --git a/include/hardware/audio.h b/include/hardware/audio.h
index 36bfa86..c95ad09 100644
--- a/include/hardware/audio.h
+++ b/include/hardware/audio.h
@@ -253,7 +253,8 @@
 /* type of asynchronous write callback events. Mutually exclusive */
 typedef enum {
     STREAM_CBK_EVENT_WRITE_READY, /* non blocking write completed */
-    STREAM_CBK_EVENT_DRAIN_READY  /* drain completed */
+    STREAM_CBK_EVENT_DRAIN_READY,  /* drain completed */
+    STREAM_CBK_EVENT_ERROR, /* stream hit some error, let AF take action */
 } stream_callback_event_t;
 
 typedef int (*stream_callback_t)(stream_callback_event_t event, void *param, void *cookie);
@@ -678,7 +679,7 @@
                                        struct audio_hw_device** device)
 {
     return module->methods->open(module, AUDIO_HARDWARE_INTERFACE,
-                                 (struct hw_device_t**)device);
+                                 TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int audio_hw_device_close(struct audio_hw_device* device)
diff --git a/include/hardware/audio_effect.h b/include/hardware/audio_effect.h
index 41cd2e6..e49980d 100644
--- a/include/hardware/audio_effect.h
+++ b/include/hardware/audio_effect.h
@@ -150,6 +150,13 @@
 //  | Effect offload supported  | 22        | 0 The effect cannot be offloaded to an audio DSP
 //  |                           |           | 1 The effect can be offloaded to an audio DSP
 //  +---------------------------+-----------+-----------------------------------
+//  | Process function not      | 23        | 0 The effect implements a process function.
+//  | implemented               |           | 1 The effect does not implement a process function:
+//  |                           |           |   enabling the effect has no impact on latency or
+//  |                           |           |   CPU load.
+//  |                           |           |   Effect implementations setting this flag do not have
+//  |                           |           |   to implement a process function.
+//  +---------------------------+-----------+-----------------------------------
 
 // Insert mode
 #define EFFECT_FLAG_TYPE_SHIFT          0
@@ -240,6 +247,14 @@
                                           << EFFECT_FLAG_OFFLOAD_SHIFT)
 #define EFFECT_FLAG_OFFLOAD_SUPPORTED   (1 << EFFECT_FLAG_OFFLOAD_SHIFT)
 
+// Effect has no process indication
+#define EFFECT_FLAG_NO_PROCESS_SHIFT       (EFFECT_FLAG_OFFLOAD_SHIFT + \
+                                                    EFFECT_FLAG_OFFLOAD_SIZE)
+#define EFFECT_FLAG_NO_PROCESS_SIZE        1
+#define EFFECT_FLAG_NO_PROCESS_MASK        (((1 << EFFECT_FLAG_NO_PROCESS_SIZE) -1) \
+                                          << EFFECT_FLAG_NO_PROCESS_SHIFT)
+#define EFFECT_FLAG_NO_PROCESS          (1 << EFFECT_FLAG_NO_PROCESS_SHIFT)
+
 #define EFFECT_MAKE_API_VERSION(M, m)  (((M)<<16) | ((m) & 0xFFFF))
 #define EFFECT_API_VERSION_MAJOR(v)    ((v)>>16)
 #define EFFECT_API_VERSION_MINOR(v)    ((m) & 0xFFFF)
diff --git a/include/hardware/ble_advertiser.h b/include/hardware/ble_advertiser.h
index 389bdbb..45282aa 100644
--- a/include/hardware/ble_advertiser.h
+++ b/include/hardware/ble_advertiser.h
@@ -14,68 +14,61 @@
  * limitations under the License.
  */
 
-
 #ifndef ANDROID_INCLUDE_BLE_ADVERTISER_H
 #define ANDROID_INCLUDE_BLE_ADVERTISER_H
 
+#include <base/callback_forward.h>
 #include <stdint.h>
 #include <vector>
-#include "bt_gatt_types.h"
 #include "bt_common_types.h"
+#include "bt_gatt_types.h"
 
-using std::vector;
+struct AdvertiseParameters {
+  uint16_t advertising_event_properties;
+  uint32_t min_interval;
+  uint32_t max_interval;
+  uint8_t channel_map;
+  int8_t tx_power;
+  uint8_t primary_advertising_phy;
+  uint8_t secondary_advertising_phy;
+  uint8_t scan_request_notification_enable;
+};
 
-__BEGIN_DECLS
+class BleAdvertiserInterface {
+ public:
+  virtual ~BleAdvertiserInterface() = default;
 
-/** Callback invoked in response to register_advertiser */
-typedef void (*register_advertiser_callback)(int status, int advertiser_id,
-                                             bt_uuid_t *uuid);
+  /** Callback invoked when multi-adv operation has completed */
+  using Callback = base::Callback<void(uint8_t /* status */)>;
 
-/** Callback invoked when multi-adv param set_params operation has completed */
-typedef void (*multi_adv_set_params_callback)(int advertiser_id, int status);
+  /** Registers an advertiser with the stack */
+  virtual void RegisterAdvertiser(
+      base::Callback<void(uint8_t /* advertiser_id */,
+                          uint8_t /* status */)>) = 0;
 
-/** Callback invoked when multi-adv instance data set operation has completed */
-typedef void (*multi_adv_data_callback)(int advertiser_id, int status);
+  /* Set the parameters as per spec, user manual specified values */
+  virtual void SetParameters(
+      uint8_t advertiser_id, uint16_t advertising_event_properties,
+      uint32_t min_interval, uint32_t max_interval, int chnl_map, int tx_power,
+      uint8_t primary_advertising_phy, uint8_t secondary_advertising_phy,
+      uint8_t scan_request_notification_enable, Callback cb) = 0;
 
-/** Callback invoked when multi-adv enable operation has completed */
-typedef void (*multi_adv_enable_callback)(int advertiser_id, int status, bool enable);
+  /* Setup the data */
+  virtual void SetData(int advertiser_id, bool set_scan_rsp,
+                       std::vector<uint8_t> data, Callback cb) = 0;
 
-typedef struct {
-    register_advertiser_callback        register_advertiser_cb;
-    multi_adv_set_params_callback       multi_adv_set_params_cb;
-    multi_adv_data_callback             multi_adv_data_cb;
-    multi_adv_enable_callback           multi_adv_enable_cb;
-} ble_advertiser_callbacks_t;
+  /* Enable the advertising instance */
+  virtual void Enable(uint8_t advertiser_id, bool enable, Callback cb,
+                      int timeout_s, Callback timeout_cb) = 0;
 
-typedef struct {
-    /** Registers an advertiser with the stack */
-    bt_status_t (*register_advertiser)(bt_uuid_t *uuid);
+  /*  Unregisters an advertiser */
+  virtual void Unregister(uint8_t advertiser_id) = 0;
 
-    /** Unregister a advertiser from the stack */
-    bt_status_t (*unregister_advertiser)(int advertiser_id);
-
-    /** Set the advertising data or scan response data */
-    bt_status_t (*set_adv_data)(int advertiser_id, bool set_scan_rsp, bool include_name,
-                    bool include_txpower, int min_interval, int max_interval, int appearance,
-                    vector<uint8_t> manufacturer_data,
-                    vector<uint8_t> service_data,
-                    vector<uint8_t> service_uuid);
-
-    /* Set the parameters as per spec, user manual specified values */
-    bt_status_t (*multi_adv_set_params)(int advertiser_id, int min_interval,int max_interval,int adv_type,
-                 int chnl_map, int tx_power);
-
-
-    /* Setup the data for the specified instance */
-    bt_status_t (*multi_adv_set_inst_data)(int advertiser_id, bool set_scan_rsp, bool include_name,
-                    bool incl_txpower, int appearance, vector<uint8_t> manufacturer_data,
-                    vector<uint8_t> service_data, vector<uint8_t> service_uuid);
-
-    /* Enable the advertising instance as per spec */
-    bt_status_t (*multi_adv_enable)(int advertiser_id, bool enable, int timeout_s);
-
-} ble_advertiser_interface_t;
-
-__END_DECLS
+  virtual void StartAdvertising(uint8_t advertiser_id, Callback cb,
+                                AdvertiseParameters params,
+                                std::vector<uint8_t> advertise_data,
+                                std::vector<uint8_t> scan_response_data,
+                                int timeout_s, Callback timeout_cb) = 0;
+};
 
 #endif /* ANDROID_INCLUDE_BLE_ADVERTISER_H */
diff --git a/include/hardware/ble_scanner.h b/include/hardware/ble_scanner.h
new file mode 100644
index 0000000..20b36fd
--- /dev/null
+++ b/include/hardware/ble_scanner.h
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#ifndef ANDROID_INCLUDE_BLE_SCANNER_H
+#define ANDROID_INCLUDE_BLE_SCANNER_H
+
+#include <stdint.h>
+#include <vector>
+#include "bt_common_types.h"
+#include "bt_gatt_client.h"
+#include "bt_gatt_types.h"
+
+/** Callback invoked when batchscan storage config operation has completed */
+typedef void (*batchscan_cfg_storage_callback)(int client_if, int status);
+
+/** Callback invoked when batchscan enable / disable operation has completed */
+typedef void (*batchscan_enable_disable_callback)(int action, int client_if,
+                                                  int status);
+
+/** Callback invoked when batchscan reports are obtained */
+typedef void (*batchscan_reports_callback)(int client_if, int status,
+                                           int report_format, int num_records,
+                                           std::vector<uint8_t> data);
+
+/** Callback invoked when batchscan storage threshold limit is crossed */
+typedef void (*batchscan_threshold_callback)(int client_if);
+
+/** Track ADV VSE callback invoked when tracked device is found or lost */
+typedef void (*track_adv_event_callback)(
+    btgatt_track_adv_info_t *p_track_adv_info);
+
+/** Callback invoked when scan parameter setup has completed */
+typedef void (*scan_parameter_setup_completed_callback)(int client_if,
+                                                        btgattc_error_t status);
+
+/** Callback for scan results */
+typedef void (*scan_result_callback)(bt_bdaddr_t *bda, int rssi,
+                                     std::vector<uint8_t> adv_data);
+
+/** Callback invoked when a scan filter configuration command has completed */
+typedef void (*scan_filter_cfg_callback)(int action, int client_if, int status,
+                                         int filt_type, int avbl_space);
+
+/** Callback invoked when scan param has been added, cleared, or deleted */
+typedef void (*scan_filter_param_callback)(int action, int client_if,
+                                           int status, int avbl_space);
+
+/** Callback invoked when a scan filter configuration command has completed */
+typedef void (*scan_filter_status_callback)(int enable, int client_if,
+                                            int status);
+
+typedef struct {
+  scan_result_callback scan_result_cb;
+  batchscan_cfg_storage_callback batchscan_cfg_storage_cb;
+  batchscan_enable_disable_callback batchscan_enb_disable_cb;
+  batchscan_reports_callback batchscan_reports_cb;
+  batchscan_threshold_callback batchscan_threshold_cb;
+  track_adv_event_callback track_adv_event_cb;
+  scan_parameter_setup_completed_callback scan_parameter_setup_completed_cb;
+  scan_filter_cfg_callback scan_filter_cfg_cb;
+  scan_filter_param_callback scan_filter_param_cb;
+  scan_filter_status_callback scan_filter_status_cb;
+} btgatt_scanner_callbacks_t;
+
+class BleScannerInterface {
+ public:
+  virtual ~BleScannerInterface() = default;
+
+  using RegisterCallback =
+      base::Callback<void(uint8_t /* scanner_id */, uint8_t /* status */)>;
+
+  /** Registers a scanner with the stack */
+  virtual void RegisterScanner(RegisterCallback) = 0;
+
+  /** Unregister a scanner from the stack */
+  virtual void Unregister(int scanner_id) = 0;
+
+  /** Start or stop LE device scanning */
+  virtual void Scan(bool start) = 0;
+
+  /** Setup scan filter params */
+  virtual void ScanFilterParamSetup(
+      uint8_t client_if, uint8_t action, uint8_t filt_index,
+      std::unique_ptr<btgatt_filt_param_setup_t> filt_param) = 0;
+
+  /** Configure a scan filter condition  */
+  virtual void ScanFilterAddRemove(int client_if, int action, int filt_type,
+                                   int filt_index, int company_id,
+                                   int company_id_mask, const bt_uuid_t *p_uuid,
+                                   const bt_uuid_t *p_uuid_mask,
+                                   const bt_bdaddr_t *bd_addr, char addr_type,
+                                   std::vector<uint8_t> data,
+                                   std::vector<uint8_t> p_mask) = 0;
+
+  /** Clear all scan filter conditions for specific filter index*/
+  virtual void ScanFilterClear(int client_if, int filt_index) = 0;
+
+  /** Enable / disable scan filter feature*/
+  virtual void ScanFilterEnable(int client_if, bool enable) = 0;
+
+  /** Sets the LE scan interval and window in units of N*0.625 msec */
+  virtual void SetScanParameters(int client_if, int scan_interval,
+                                 int scan_window) = 0;
+
+  /* Configure the batchscan storage */
+  virtual void BatchscanConfigStorage(int client_if, int batch_scan_full_max,
+                                      int batch_scan_trunc_max,
+                                      int batch_scan_notify_threshold) = 0;
+
+  /* Enable batchscan */
+  virtual void BatchscanEnable(int client_if, int scan_mode, int scan_interval,
+                               int scan_window, int addr_type,
+                               int discard_rule) = 0;
+
+  /* Disable batchscan */
+  virtual void BatchscanDisable(int client_if) = 0;
+
+  /* Read out batchscan reports */
+  virtual void BatchscanReadReports(int client_if, int scan_mode) = 0;
+};
+
+#endif /* ANDROID_INCLUDE_BLE_SCANNER_H */
\ No newline at end of file
diff --git a/include/hardware/bluetooth.h b/include/hardware/bluetooth.h
index 1fe2596..9870913 100644
--- a/include/hardware/bluetooth.h
+++ b/include/hardware/bluetooth.h
@@ -44,6 +44,7 @@
 #define BT_PROFILE_HEALTH_ID "health"
 #define BT_PROFILE_SOCKETS_ID "socket"
 #define BT_PROFILE_HIDHOST_ID "hidhost"
+#define BT_PROFILE_HIDDEV_ID "hiddev"
 #define BT_PROFILE_PAN_ID "pan"
 #define BT_PROFILE_MAP_CLIENT_ID "map_client"
 #define BT_PROFILE_SDP_CLIENT_ID "sdp"
@@ -267,6 +268,7 @@
 /** Bluetooth Out Of Band data for bonding */
 typedef struct
 {
+   uint8_t le_bt_dev_addr[7]; /* LE Bluetooth Device Address */
    uint8_t c192[16]; /* Simple Pairing Hash C-192 */
    uint8_t r192[16]; /* Simple Pairing Randomizer R-192 */
    uint8_t c256[16]; /* Simple Pairing Hash C-256 */
diff --git a/include/hardware/bt_av.h b/include/hardware/bt_av.h
index 9b32216..e5f7b31 100644
--- a/include/hardware/bt_av.h
+++ b/include/hardware/bt_av.h
@@ -17,6 +17,10 @@
 #ifndef ANDROID_INCLUDE_BT_AV_H
 #define ANDROID_INCLUDE_BT_AV_H
 
+#include <vector>
+
+#include <hardware/bluetooth.h>
+
 __BEGIN_DECLS
 
 /* Bluetooth AV connection states */
@@ -34,6 +38,81 @@
     BTAV_AUDIO_STATE_STARTED,
 } btav_audio_state_t;
 
+/*
+ * Enum values for each A2DP supported codec.
+ * There should be a separate entry for each A2DP codec that is supported
+ * for encoding (SRC), and for decoding purpose (SINK).
+ */
+typedef enum {
+  BTAV_A2DP_CODEC_INDEX_SOURCE_MIN = 0,
+
+  // Add an entry for each source codec here.
+  // NOTE: The values should be same as those listed in the following file:
+  //   BluetoothCodecConfig.java
+  BTAV_A2DP_CODEC_INDEX_SOURCE_SBC = 0,
+  BTAV_A2DP_CODEC_INDEX_SOURCE_APTX,
+  BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD,
+  BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC,
+
+  BTAV_A2DP_CODEC_INDEX_SOURCE_MAX,
+
+  BTAV_A2DP_CODEC_INDEX_SINK_MIN = BTAV_A2DP_CODEC_INDEX_SOURCE_MAX,
+
+  // Add an entry for each sink codec here
+  BTAV_A2DP_CODEC_INDEX_SINK_SBC = BTAV_A2DP_CODEC_INDEX_SINK_MIN,
+
+  BTAV_A2DP_CODEC_INDEX_SINK_MAX,
+
+  BTAV_A2DP_CODEC_INDEX_MIN = BTAV_A2DP_CODEC_INDEX_SOURCE_MIN,
+  BTAV_A2DP_CODEC_INDEX_MAX = BTAV_A2DP_CODEC_INDEX_SINK_MAX
+} btav_a2dp_codec_index_t;
+
+typedef uint32_t btav_a2dp_codec_priority_t;
+
+typedef enum {
+  BTAV_A2DP_CODEC_SAMPLE_RATE_NONE   = 0x0,
+  BTAV_A2DP_CODEC_SAMPLE_RATE_44100  = 0x1 << 0,
+  BTAV_A2DP_CODEC_SAMPLE_RATE_48000  = 0x1 << 1,
+  BTAV_A2DP_CODEC_SAMPLE_RATE_88200  = 0x1 << 2,
+  BTAV_A2DP_CODEC_SAMPLE_RATE_96000  = 0x1 << 3,
+  BTAV_A2DP_CODEC_SAMPLE_RATE_176400 = 0x1 << 4,
+  BTAV_A2DP_CODEC_SAMPLE_RATE_192000 = 0x1 << 5
+} btav_a2dp_codec_sample_rate_t;
+
+typedef enum {
+  BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE = 0x0,
+  BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16   = 0x1 << 0,
+  BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24   = 0x1 << 1,
+  BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32   = 0x1 << 2
+} btav_a2dp_codec_bits_per_sample_t;
+
+typedef enum {
+  BTAV_A2DP_CODEC_CHANNEL_MODE_NONE   = 0x0,
+  BTAV_A2DP_CODEC_CHANNEL_MODE_MONO   = 0x1 << 0,
+  BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO = 0x1 << 1
+} btav_a2dp_codec_channel_mode_t;
+
+/*
+ * Structure for representing codec capability or configuration.
+ * It is used for configuring A2DP codec preference, and for reporting back
+ * current configuration or codec capability.
+ * For codec capability, fields "sample_rate", "bits_per_sample" and
+ * "channel_mode" can contain bit-masks with all supported features.
+ */
+typedef struct {
+  btav_a2dp_codec_index_t codec_type;
+  btav_a2dp_codec_priority_t codec_priority; // Codec selection priority
+                                // relative to other codecs: larger value
+                                // means higher priority. If 0, reset to
+                                // default.
+  btav_a2dp_codec_sample_rate_t sample_rate;
+  btav_a2dp_codec_bits_per_sample_t bits_per_sample;
+  btav_a2dp_codec_channel_mode_t channel_mode;
+  int64_t codec_specific_1;     // Codec-specific value 1
+  int64_t codec_specific_2;     // Codec-specific value 2
+  int64_t codec_specific_3;     // Codec-specific value 3
+  int64_t codec_specific_4;     // Codec-specific value 4
+} btav_a2dp_codec_config_t;
 
 /** Callback for connection state change.
  *  state will have one of the values from btav_connection_state_t
@@ -48,23 +127,38 @@
                                                bt_bdaddr_t *bd_addr);
 
 /** Callback for audio configuration change.
- *  Used only for the A2DP sink interface.
- *  state will have one of the values from btav_audio_state_t
+ *  Used only for the A2DP Source interface.
+ */
+typedef void (* btav_audio_source_config_callback)(
+    btav_a2dp_codec_config_t codec_config,
+    std::vector<btav_a2dp_codec_config_t> codec_capabilities);
+
+/** Callback for audio configuration change.
+ *  Used only for the A2DP Sink interface.
  *  sample_rate: sample rate in Hz
  *  channel_count: number of channels (1 for mono, 2 for stereo)
  */
-typedef void (* btav_audio_config_callback)(bt_bdaddr_t *bd_addr,
-                                                uint32_t sample_rate,
-                                                uint8_t channel_count);
+typedef void (* btav_audio_sink_config_callback)(bt_bdaddr_t *bd_addr,
+                                                 uint32_t sample_rate,
+                                                 uint8_t channel_count);
 
-/** BT-AV callback structure. */
+/** BT-AV A2DP Source callback structure. */
 typedef struct {
-    /** set to sizeof(btav_callbacks_t) */
+    /** set to sizeof(btav_source_callbacks_t) */
     size_t      size;
     btav_connection_state_callback  connection_state_cb;
     btav_audio_state_callback audio_state_cb;
-    btav_audio_config_callback audio_config_cb;
-} btav_callbacks_t;
+    btav_audio_source_config_callback audio_config_cb;
+} btav_source_callbacks_t;
+
+/** BT-AV A2DP Source callback structure. */
+typedef struct {
+    /** set to sizeof(btav_sink_callbacks_t) */
+    size_t      size;
+    btav_connection_state_callback  connection_state_cb;
+    btav_audio_state_callback audio_state_cb;
+    btav_audio_sink_config_callback audio_config_cb;
+} btav_sink_callbacks_t;
 
 /**
  * NOTE:
@@ -76,17 +170,42 @@
  *    android_audio_hw library and the Bluetooth stack.
  *
  */
-/** Represents the standard BT-AV interface.
- *  Used for both the A2DP source and sink interfaces.
+
+/** Represents the standard BT-AV A2DP Source interface.
  */
 typedef struct {
 
-    /** set to sizeof(btav_interface_t) */
+    /** set to sizeof(btav_source_interface_t) */
     size_t          size;
     /**
      * Register the BtAv callbacks
      */
-    bt_status_t (*init)( btav_callbacks_t* callbacks );
+    bt_status_t (*init)( btav_source_callbacks_t* callbacks );
+
+    /** connect to headset */
+    bt_status_t (*connect)( bt_bdaddr_t *bd_addr );
+
+    /** dis-connect from headset */
+    bt_status_t (*disconnect)( bt_bdaddr_t *bd_addr );
+
+    /** configure the codecs settings preferences */
+    bt_status_t (*config_codec)(std::vector<btav_a2dp_codec_config_t> codec_preferences);
+
+    /** Closes the interface. */
+    void  (*cleanup)( void );
+
+} btav_source_interface_t;
+
+/** Represents the standard BT-AV A2DP Sink interface.
+ */
+typedef struct {
+
+    /** set to sizeof(btav_sink_interface_t) */
+    size_t          size;
+    /**
+     * Register the BtAv callbacks
+     */
+    bt_status_t (*init)( btav_sink_callbacks_t* callbacks );
 
     /** connect to headset */
     bt_status_t (*connect)( bt_bdaddr_t *bd_addr );
@@ -102,7 +221,7 @@
 
     /** Sets the audio track gain. */
     void  (*set_audio_track_gain)( float gain );
-} btav_interface_t;
+} btav_sink_interface_t;
 
 __END_DECLS
 
diff --git a/include/hardware/bt_common_types.h b/include/hardware/bt_common_types.h
index 1e6be6b..cff3072 100644
--- a/include/hardware/bt_common_types.h
+++ b/include/hardware/bt_common_types.h
@@ -73,4 +73,19 @@
     uint16_t            permissions;
 } btgatt_db_element_t;
 
+typedef struct
+{
+    uint16_t feat_seln;
+    uint16_t list_logic_type;
+    uint8_t  filt_logic_type;
+    uint8_t  rssi_high_thres;
+    uint8_t  rssi_low_thres;
+    uint8_t  dely_mode;
+    uint16_t found_timeout;
+    uint16_t lost_timeout;
+    uint8_t  found_timeout_cnt;
+    uint16_t  num_of_tracking_entries;
+} btgatt_filt_param_setup_t;
+
+
 #endif  /* ANDROID_INCLUDE_BT_COMMON_TYPES_H */
diff --git a/include/hardware/bt_gatt.h b/include/hardware/bt_gatt.h
index 343e5fa..393d1a5 100644
--- a/include/hardware/bt_gatt.h
+++ b/include/hardware/bt_gatt.h
@@ -20,6 +20,7 @@
 
 #include <stdint.h>
 #include "ble_advertiser.h"
+#include "ble_scanner.h"
 #include "bt_gatt_client.h"
 #include "bt_gatt_server.h"
 
@@ -36,8 +37,8 @@
     /** GATT Server callbacks */
     const btgatt_server_callbacks_t* server;
 
-    /** Advertiser callbacks */
-    const ble_advertiser_callbacks_t* advertiser;
+    /** LE scanner callbacks */
+    const btgatt_scanner_callbacks_t* scanner;
 } btgatt_callbacks_t;
 
 /** Represents the standard Bluetooth GATT interface. */
@@ -59,8 +60,11 @@
     /** Pointer to the GATT server interface methods.*/
     const btgatt_server_interface_t* server;
 
+    /** Pointer to the LE scanner interface methods.*/
+    BleScannerInterface* scanner;
+
     /** Pointer to the advertiser interface methods.*/
-    const ble_advertiser_interface_t* advertiser;
+    BleAdvertiserInterface* advertiser;
 } btgatt_interface_t;
 
 __END_DECLS
diff --git a/include/hardware/bt_gatt_client.h b/include/hardware/bt_gatt_client.h
index 6cd8394..76b52fd 100644
--- a/include/hardware/bt_gatt_client.h
+++ b/include/hardware/bt_gatt_client.h
@@ -23,8 +23,6 @@
 #include "bt_gatt_types.h"
 #include "bt_common_types.h"
 
-using std::vector;
-
 __BEGIN_DECLS
 
 /**
@@ -70,23 +68,6 @@
 
 typedef struct
 {
-    uint8_t  client_if;
-    uint8_t  action;
-    uint8_t  filt_index;
-    uint16_t feat_seln;
-    uint16_t list_logic_type;
-    uint8_t  filt_logic_type;
-    uint8_t  rssi_high_thres;
-    uint8_t  rssi_low_thres;
-    uint8_t  dely_mode;
-    uint16_t found_timeout;
-    uint16_t lost_timeout;
-    uint8_t  found_timeout_cnt;
-    uint16_t  num_of_tracking_entries;
-} btgatt_filt_param_setup_t;
-
-typedef struct
-{
     bt_bdaddr_t        *bda1;
     bt_uuid_t          *uuid1;
     uint16_t            u1;
@@ -121,9 +102,6 @@
 typedef void (*register_client_callback)(int status, int client_if,
                 bt_uuid_t *app_uuid);
 
-/** Callback for scan results */
-typedef void (*scan_result_callback)(bt_bdaddr_t* bda, int rssi, vector<uint8_t> adv_data);
-
 /** GATT open callback invoked in response to open */
 typedef void (*connect_callback)(int conn_id, int status, int client_if, bt_bdaddr_t* bda);
 
@@ -168,24 +146,9 @@
 typedef void (*read_remote_rssi_callback)(int client_if, bt_bdaddr_t* bda,
                                           int rssi, int status);
 
-/**
- * Callback indicating the status of a listen() operation
- */
-typedef void (*listen_callback)(int status, int server_if);
-
 /** Callback invoked when the MTU for a given connection changes */
 typedef void (*configure_mtu_callback)(int conn_id, int status, int mtu);
 
-/** Callback invoked when a scan filter configuration command has completed */
-typedef void (*scan_filter_cfg_callback)(int action, int client_if, int status, int filt_type,
-                                         int avbl_space);
-
-/** Callback invoked when scan param has been added, cleared, or deleted */
-typedef void (*scan_filter_param_callback)(int action, int client_if, int status,
-                                         int avbl_space);
-
-/** Callback invoked when a scan filter configuration command has completed */
-typedef void (*scan_filter_status_callback)(int enable, int client_if, int status);
 
 /**
  * Callback notifying an application that a remote device connection is currently congested
@@ -193,25 +156,6 @@
  * a further callback is received indicating the congestion status has been cleared.
  */
 typedef void (*congestion_callback)(int conn_id, bool congested);
-/** Callback invoked when batchscan storage config operation has completed */
-typedef void (*batchscan_cfg_storage_callback)(int client_if, int status);
-
-/** Callback invoked when batchscan enable / disable operation has completed */
-typedef void (*batchscan_enable_disable_callback)(int action, int client_if, int status);
-
-/** Callback invoked when batchscan reports are obtained */
-typedef void (*batchscan_reports_callback)(int client_if, int status, int report_format,
-                                           int num_records, vector<uint8_t> data);
-
-/** Callback invoked when batchscan storage threshold limit is crossed */
-typedef void (*batchscan_threshold_callback)(int client_if);
-
-/** Track ADV VSE callback invoked when tracked device is found or lost */
-typedef void (*track_adv_event_callback)(btgatt_track_adv_info_t *p_track_adv_info);
-
-/** Callback invoked when scan parameter setup has completed */
-typedef void (*scan_parameter_setup_completed_callback)(int client_if,
-                                                        btgattc_error_t status);
 
 /** GATT get database callback */
 typedef void (*get_gatt_db_callback)(int conn_id, btgatt_db_element_t *db, int count);
@@ -224,7 +168,6 @@
 
 typedef struct {
     register_client_callback            register_client_cb;
-    scan_result_callback                scan_result_cb;
     connect_callback                    open_cb;
     disconnect_callback                 close_cb;
     search_complete_callback            search_complete_cb;
@@ -236,18 +179,8 @@
     write_descriptor_callback           write_descriptor_cb;
     execute_write_callback              execute_write_cb;
     read_remote_rssi_callback           read_remote_rssi_cb;
-    listen_callback                     listen_cb;
     configure_mtu_callback              configure_mtu_cb;
-    scan_filter_cfg_callback            scan_filter_cfg_cb;
-    scan_filter_param_callback          scan_filter_param_cb;
-    scan_filter_status_callback         scan_filter_status_cb;
     congestion_callback                 congestion_cb;
-    batchscan_cfg_storage_callback      batchscan_cfg_storage_cb;
-    batchscan_enable_disable_callback   batchscan_enb_disable_cb;
-    batchscan_reports_callback          batchscan_reports_cb;
-    batchscan_threshold_callback        batchscan_threshold_cb;
-    track_adv_event_callback            track_adv_event_cb;
-    scan_parameter_setup_completed_callback scan_parameter_setup_completed_cb;
     get_gatt_db_callback                get_gatt_db_cb;
     services_removed_callback           services_removed_cb;
     services_added_callback             services_added_cb;
@@ -262,9 +195,6 @@
     /** Unregister a client application from the stack */
     bt_status_t (*unregister_client)(int client_if );
 
-    /** Start or stop LE device scanning */
-    bt_status_t (*scan)( bool start );
-
     /** Create a connection to a remote LE or dual-mode device */
     bt_status_t (*connect)( int client_if, const bt_bdaddr_t *bd_addr,
                          bool is_direct, int transport );
@@ -273,9 +203,6 @@
     bt_status_t (*disconnect)( int client_if, const bt_bdaddr_t *bd_addr,
                     int conn_id);
 
-    /** Start or stop advertisements to listen for incoming connections */
-    bt_status_t (*listen)(int client_if, bool start);
-
     /** Clear the attribute cache for a given device */
     bt_status_t (*refresh)( int client_if, const bt_bdaddr_t *bd_addr );
 
@@ -292,14 +219,14 @@
     /** Write a remote characteristic */
     bt_status_t (*write_characteristic)(int conn_id, uint16_t handle,
                     int write_type, int auth_req,
-                    vector<uint8_t> value);
+                    std::vector<uint8_t> value);
 
     /** Read the descriptor for a given characteristic */
     bt_status_t (*read_descriptor)(int conn_id, uint16_t handle, int auth_req);
 
     /** Write a remote descriptor for a given characteristic */
     bt_status_t (*write_descriptor)( int conn_id, uint16_t handle,
-                    int auth_req, vector<uint8_t> value);
+                                     int auth_req, std::vector<uint8_t> value);
 
     /** Execute a prepared write operation */
     bt_status_t (*execute_write)(int conn_id, int execute);
@@ -318,24 +245,6 @@
     /** Request RSSI for a given remote device */
     bt_status_t (*read_remote_rssi)( int client_if, const bt_bdaddr_t *bd_addr);
 
-    /** Setup scan filter params */
-    bt_status_t (*scan_filter_param_setup)(btgatt_filt_param_setup_t filt_param);
-
-
-    /** Configure a scan filter condition  */
-    bt_status_t (*scan_filter_add_remove)(int client_if, int action, int filt_type,
-                                   int filt_index, int company_id,
-                                   int company_id_mask, const bt_uuid_t *p_uuid,
-                                   const bt_uuid_t *p_uuid_mask, const bt_bdaddr_t *bd_addr,
-                                   char addr_type, vector<uint8_t> data,
-                                   vector<uint8_t> p_mask);
-
-    /** Clear all scan filter conditions for specific filter index*/
-    bt_status_t (*scan_filter_clear)(int client_if, int filt_index);
-
-    /** Enable / disable scan filter feature*/
-    bt_status_t (*scan_filter_enable)(int client_if, bool enable);
-
     /** Determine the type of the remote device (LE, BR/EDR, Dual-mode) */
     int (*get_device_type)( const bt_bdaddr_t *bd_addr );
 
@@ -346,23 +255,6 @@
     bt_status_t (*conn_parameter_update)(const bt_bdaddr_t *bd_addr, int min_interval,
                     int max_interval, int latency, int timeout);
 
-    /** Sets the LE scan interval and window in units of N*0.625 msec */
-    bt_status_t (*set_scan_parameters)(int client_if, int scan_interval, int scan_window);
-
-    /* Configure the batchscan storage */
-    bt_status_t (*batchscan_cfg_storage)(int client_if, int batch_scan_full_max,
-        int batch_scan_trunc_max, int batch_scan_notify_threshold);
-
-    /* Enable batchscan */
-    bt_status_t (*batchscan_enb_batch_scan)(int client_if, int scan_mode,
-        int scan_interval, int scan_window, int addr_type, int discard_rule);
-
-    /* Disable batchscan */
-    bt_status_t (*batchscan_dis_batch_scan)(int client_if);
-
-    /* Read out batchscan reports */
-    bt_status_t (*batchscan_read_reports)(int client_if, int scan_mode);
-
     /** Test mode interface */
     bt_status_t (*test_command)( int command, btgatt_test_params_t* params);
 
diff --git a/include/hardware/bt_gatt_server.h b/include/hardware/bt_gatt_server.h
index 92af285..b105cba 100644
--- a/include/hardware/bt_gatt_server.h
+++ b/include/hardware/bt_gatt_server.h
@@ -23,8 +23,6 @@
 
 #include "bt_gatt_types.h"
 
-using std::vector;
-
 __BEGIN_DECLS
 
 /** GATT value type used in response to remote read requests */
@@ -56,7 +54,7 @@
 
 /** Callback invoked in response to create_service */
 typedef void (*service_added_callback)(int status, int server_if,
-                                       vector<btgatt_db_element_t> service);
+                                       std::vector<btgatt_db_element_t> service);
 
 /** Callback invoked in response to stop_service */
 typedef void (*service_stopped_callback)(int status, int server_if,
@@ -79,7 +77,7 @@
  */
 typedef void (*request_write_callback)(int conn_id, int trans_id, bt_bdaddr_t *bda,
                                        int attr_handle, int offset, bool need_rsp,
-                                       bool is_prep, vector<uint8_t> value);
+                                       bool is_prep, std::vector<uint8_t> value);
 
 /** Callback invoked when a previously prepared write is to be executed */
 typedef void (*request_exec_write_callback)(int conn_id, int trans_id,
@@ -141,7 +139,7 @@
                     int conn_id );
 
     /** Create a new service */
-    bt_status_t (*add_service)(int server_if, vector<btgatt_db_element_t> service);
+    bt_status_t (*add_service)(int server_if, std::vector<btgatt_db_element_t> service);
 
     /** Stops a local service */
     bt_status_t (*stop_service)(int server_if, int service_handle);
@@ -152,7 +150,7 @@
     /** Send value indication to a remote device */
     bt_status_t (*send_indication)(int server_if, int attribute_handle,
                                    int conn_id, int confirm,
-                                   vector<uint8_t> value);
+                                   std::vector<uint8_t> value);
 
     /** Send a response to a read/write operation */
     bt_status_t (*send_response)(int conn_id, int trans_id,
diff --git a/include/hardware/bt_hd.h b/include/hardware/bt_hd.h
new file mode 100644
index 0000000..263f29f
--- /dev/null
+++ b/include/hardware/bt_hd.h
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#ifndef ANDROID_INCLUDE_BT_HD_H
+#define ANDROID_INCLUDE_BT_HD_H
+
+#include <stdint.h>
+
+__BEGIN_DECLS
+
+typedef enum
+{
+    BTHD_REPORT_TYPE_OTHER = 0,
+    BTHD_REPORT_TYPE_INPUT,
+    BTHD_REPORT_TYPE_OUTPUT,
+    BTHD_REPORT_TYPE_FEATURE,
+    BTHD_REPORT_TYPE_INTRDATA // special value for reports to be sent on INTR (INPUT is assumed)
+} bthd_report_type_t;
+
+typedef enum
+{
+    BTHD_APP_STATE_NOT_REGISTERED,
+    BTHD_APP_STATE_REGISTERED
+} bthd_application_state_t;
+
+typedef enum
+{
+    BTHD_CONN_STATE_CONNECTED,
+    BTHD_CONN_STATE_CONNECTING,
+    BTHD_CONN_STATE_DISCONNECTED,
+    BTHD_CONN_STATE_DISCONNECTING,
+    BTHD_CONN_STATE_UNKNOWN
+} bthd_connection_state_t;
+
+typedef struct
+{
+    const char      *name;
+    const char      *description;
+    const char      *provider;
+    uint8_t         subclass;
+    uint8_t         *desc_list;
+    int             desc_list_len;
+} bthd_app_param_t;
+
+typedef struct
+{
+    uint8_t  service_type;
+    uint32_t token_rate;
+    uint32_t token_bucket_size;
+    uint32_t peak_bandwidth;
+    uint32_t access_latency;
+    uint32_t delay_variation;
+} bthd_qos_param_t;
+
+typedef void (* bthd_application_state_callback)(bt_bdaddr_t *bd_addr, bthd_application_state_t state);
+typedef void (* bthd_connection_state_callback)(bt_bdaddr_t *bd_addr, bthd_connection_state_t state);
+typedef void (* bthd_get_report_callback)(uint8_t type, uint8_t id, uint16_t buffer_size);
+typedef void (* bthd_set_report_callback)(uint8_t type, uint8_t id, uint16_t len, uint8_t *p_data);
+typedef void (* bthd_set_protocol_callback)(uint8_t protocol);
+typedef void (* bthd_intr_data_callback)(uint8_t report_id, uint16_t len, uint8_t *p_data);
+typedef void (* bthd_vc_unplug_callback)(void);
+
+/** BT-HD callbacks */
+typedef struct {
+    size_t      size;
+
+    bthd_application_state_callback application_state_cb;
+    bthd_connection_state_callback  connection_state_cb;
+    bthd_get_report_callback        get_report_cb;
+    bthd_set_report_callback        set_report_cb;
+    bthd_set_protocol_callback      set_protocol_cb;
+    bthd_intr_data_callback         intr_data_cb;
+    bthd_vc_unplug_callback         vc_unplug_cb;
+} bthd_callbacks_t;
+
+/** BT-HD interface */
+typedef struct {
+
+    size_t          size;
+
+    /** init interface and register callbacks */
+    bt_status_t (*init)(bthd_callbacks_t* callbacks);
+
+    /** close interface */
+    void  (*cleanup)(void);
+
+    /** register application */
+    bt_status_t (*register_app)(bthd_app_param_t *app_param, bthd_qos_param_t *in_qos,
+                                            bthd_qos_param_t *out_qos);
+
+    /** unregister application */
+    bt_status_t (*unregister_app)(void);
+
+    /** connects to host with virtual cable */
+    bt_status_t (*connect)(bt_bdaddr_t *bd_addr);
+
+    /** disconnects from currently connected host */
+    bt_status_t (*disconnect)(void);
+
+    /** send report */
+    bt_status_t (*send_report)(bthd_report_type_t type, uint8_t id, uint16_t len, uint8_t *p_data);
+
+    /** notifies error for invalid SET_REPORT */
+    bt_status_t (*report_error)(uint8_t error);
+
+    /** send Virtual Cable Unplug  */
+    bt_status_t (*virtual_cable_unplug)(void);
+
+} bthd_interface_t;
+
+__END_DECLS
+
+#endif /* ANDROID_INCLUDE_BT_HD_H */
+
diff --git a/include/hardware/bt_hf_client.h b/include/hardware/bt_hf_client.h
index 8acf1b2..b728be3 100644
--- a/include/hardware/bt_hf_client.h
+++ b/include/hardware/bt_hf_client.h
@@ -167,104 +167,120 @@
  *  state will have one of the values from BtHfConnectionState
  *  peer/chld_features are valid only for BTHF_CLIENT_CONNECTION_STATE_SLC_CONNECTED state
  */
-typedef void (* bthf_client_connection_state_callback)(bthf_client_connection_state_t state,
+typedef void (* bthf_client_connection_state_callback)(const bt_bdaddr_t *bd_addr,
+                                                       bthf_client_connection_state_t state,
                                                        unsigned int peer_feat,
-                                                       unsigned int chld_feat,
-                                                       bt_bdaddr_t *bd_addr);
+                                                       unsigned int chld_feat);
 
 /** Callback for audio connection state change.
  *  state will have one of the values from BtHfAudioState
  */
-typedef void (* bthf_client_audio_state_callback)(bthf_client_audio_state_t state,
-                                                  bt_bdaddr_t *bd_addr);
+typedef void (* bthf_client_audio_state_callback)(const bt_bdaddr_t *bd_addr,
+                                                  bthf_client_audio_state_t state);
 
 /** Callback for VR connection state change.
  *  state will have one of the values from BtHfVRState
  */
-typedef void (* bthf_client_vr_cmd_callback)(bthf_client_vr_state_t state);
+typedef void (* bthf_client_vr_cmd_callback)(const bt_bdaddr_t *bd_addr, bthf_client_vr_state_t state);
 
 /** Callback for network state change
  */
-typedef void (* bthf_client_network_state_callback) (bthf_client_network_state_t state);
+typedef void (* bthf_client_network_state_callback) (const bt_bdaddr_t *bd_addr,
+                                                     bthf_client_network_state_t state);
 
 /** Callback for network roaming status change
  */
-typedef void (* bthf_client_network_roaming_callback) (bthf_client_service_type_t type);
+typedef void (* bthf_client_network_roaming_callback) (const bt_bdaddr_t *bd_addr,
+                                                       bthf_client_service_type_t type);
 
 /** Callback for signal strength indication
  */
-typedef void (* bthf_client_network_signal_callback) (int signal_strength);
+typedef void (* bthf_client_network_signal_callback) (const bt_bdaddr_t *bd_addr,
+                                                      int signal_strength);
 
 /** Callback for battery level indication
  */
-typedef void (* bthf_client_battery_level_callback) (int battery_level);
+typedef void (* bthf_client_battery_level_callback) (const bt_bdaddr_t *bd_addr,
+                                                     int battery_level);
 
 /** Callback for current operator name
  */
-typedef void (* bthf_client_current_operator_callback) (const char *name);
+typedef void (* bthf_client_current_operator_callback) (const bt_bdaddr_t *bd_addr,
+                                                        const char *name);
 
 /** Callback for call indicator
  */
-typedef void (* bthf_client_call_callback) (bthf_client_call_t call);
+typedef void (* bthf_client_call_callback) (const bt_bdaddr_t *bd_addr, bthf_client_call_t call);
 
 /** Callback for callsetup indicator
  */
-typedef void (* bthf_client_callsetup_callback) (bthf_client_callsetup_t callsetup);
+typedef void (* bthf_client_callsetup_callback) (const bt_bdaddr_t *bd_addr,
+                                                 bthf_client_callsetup_t callsetup);
 
 /** Callback for callheld indicator
  */
-typedef void (* bthf_client_callheld_callback) (bthf_client_callheld_t callheld);
+typedef void (* bthf_client_callheld_callback) (const bt_bdaddr_t *bd_addr,
+                                                bthf_client_callheld_t callheld);
 
 /** Callback for response and hold
  */
-typedef void (* bthf_client_resp_and_hold_callback) (bthf_client_resp_and_hold_t resp_and_hold);
+typedef void (* bthf_client_resp_and_hold_callback) (const bt_bdaddr_t *bd_addr,
+                                                     bthf_client_resp_and_hold_t resp_and_hold);
 
 /** Callback for Calling Line Identification notification
  *  Will be called only when there is an incoming call and number is provided.
  */
-typedef void (* bthf_client_clip_callback) (const char *number);
+typedef void (* bthf_client_clip_callback) (const bt_bdaddr_t *bd_addr, const char *number);
 
 /**
  * Callback for Call Waiting notification
  */
-typedef void (* bthf_client_call_waiting_callback) (const char *number);
+typedef void (* bthf_client_call_waiting_callback) (const bt_bdaddr_t *bd_addr, const char *number);
 
 /**
  *  Callback for listing current calls. Can be called multiple time.
  *  If number is unknown NULL is passed.
  */
-typedef void (*bthf_client_current_calls) (int index, bthf_client_call_direction_t dir,
+typedef void (*bthf_client_current_calls) (const bt_bdaddr_t *bd_addr, int index,
+                                           bthf_client_call_direction_t dir,
                                            bthf_client_call_state_t state,
                                            bthf_client_call_mpty_type_t mpty,
                                            const char *number);
 
 /** Callback for audio volume change
  */
-typedef void (*bthf_client_volume_change_callback) (bthf_client_volume_type_t type, int volume);
+typedef void (*bthf_client_volume_change_callback) (const bt_bdaddr_t *bd_addr,
+                                                    bthf_client_volume_type_t type,
+                                                    int volume);
 
 /** Callback for command complete event
  *  cme is valid only for BTHF_CLIENT_CMD_COMPLETE_ERROR_CME type
  */
-typedef void (*bthf_client_cmd_complete_callback) (bthf_client_cmd_complete_t type, int cme);
+typedef void (*bthf_client_cmd_complete_callback) (const bt_bdaddr_t *bd_addr,
+                                                   bthf_client_cmd_complete_t type,
+                                                   int cme);
 
 /** Callback for subscriber information
  */
-typedef void (* bthf_client_subscriber_info_callback) (const char *name,
+typedef void (* bthf_client_subscriber_info_callback) (const bt_bdaddr_t *bd_addr,
+                                                       const char *name,
                                                        bthf_client_subscriber_service_type_t type);
 
 /** Callback for in-band ring tone settings
  */
-typedef void (* bthf_client_in_band_ring_tone_callback) (bthf_client_in_band_ring_state_t state);
+typedef void (* bthf_client_in_band_ring_tone_callback) (const bt_bdaddr_t *bd_addr,
+                                                         bthf_client_in_band_ring_state_t state);
 
 /**
  * Callback for requested number from AG
  */
-typedef void (* bthf_client_last_voice_tag_number_callback) (const char *number);
+typedef void (* bthf_client_last_voice_tag_number_callback) (const bt_bdaddr_t *bd_addr,
+                                                             const char *number);
 
 /**
  * Callback for sending ring indication to app
  */
-typedef void (* bthf_client_ring_indication_callback) (void);
+typedef void (* bthf_client_ring_indication_callback) (const bt_bdaddr_t *bd_addr);
 
 /** BT-HF callback structure. */
 typedef struct {
@@ -307,55 +323,59 @@
     bt_status_t (*connect)(bt_bdaddr_t *bd_addr);
 
     /** disconnect from audio gateway */
-    bt_status_t (*disconnect)(bt_bdaddr_t *bd_addr);
+    bt_status_t (*disconnect)(const bt_bdaddr_t *bd_addr);
 
     /** create an audio connection */
-    bt_status_t (*connect_audio)(bt_bdaddr_t *bd_addr);
+    bt_status_t (*connect_audio)(const bt_bdaddr_t *bd_addr);
 
     /** close the audio connection */
-    bt_status_t (*disconnect_audio)(bt_bdaddr_t *bd_addr);
+    bt_status_t (*disconnect_audio)(const bt_bdaddr_t *bd_addr);
 
     /** start voice recognition */
-    bt_status_t (*start_voice_recognition)(void);
+    bt_status_t (*start_voice_recognition)(const bt_bdaddr_t *bd_addr);
 
     /** stop voice recognition */
-    bt_status_t (*stop_voice_recognition)(void);
+    bt_status_t (*stop_voice_recognition)(const bt_bdaddr_t *bd_addr);
 
     /** volume control */
-    bt_status_t (*volume_control) (bthf_client_volume_type_t type, int volume);
+    bt_status_t (*volume_control) (const bt_bdaddr_t *bd_addr,
+                                   bthf_client_volume_type_t type,
+                                   int volume);
 
     /** place a call with number a number
      * if number is NULL last called number is called (aka re-dial)*/
-    bt_status_t (*dial) (const char *number);
+    bt_status_t (*dial) (const bt_bdaddr_t *bd_addr, const char *number);
 
     /** place a call with number specified by location (speed dial) */
-    bt_status_t (*dial_memory) (int location);
+    bt_status_t (*dial_memory) (const bt_bdaddr_t *bd_addr, int location);
 
     /** perform specified call related action
      * idx is limited only for enhanced call control related action
      */
-    bt_status_t (*handle_call_action) (bthf_client_call_action_t action, int idx);
+    bt_status_t (*handle_call_action) (const bt_bdaddr_t *bd_addr,
+                                       bthf_client_call_action_t action,
+                                       int idx);
 
     /** query list of current calls */
-    bt_status_t (*query_current_calls) (void);
+    bt_status_t (*query_current_calls) (const bt_bdaddr_t *bd_addr);
 
     /** query name of current selected operator */
-    bt_status_t (*query_current_operator_name) (void);
+    bt_status_t (*query_current_operator_name) (const bt_bdaddr_t *bd_addr);
 
     /** Retrieve subscriber information */
-    bt_status_t (*retrieve_subscriber_info) (void);
+    bt_status_t (*retrieve_subscriber_info) (const bt_bdaddr_t *bd_addr);
 
     /** Send DTMF code*/
-    bt_status_t (*send_dtmf) (char code);
+    bt_status_t (*send_dtmf) (const bt_bdaddr_t *bd_addr, char code);
 
     /** Request a phone number from AG corresponding to last voice tag recorded */
-    bt_status_t (*request_last_voice_tag_number) (void);
+    bt_status_t (*request_last_voice_tag_number) (const bt_bdaddr_t *bd_addr);
 
     /** Closes the interface. */
     void (*cleanup)(void);
 
     /** Send AT Command. */
-    bt_status_t (*send_at_cmd) (int cmd, int val1, int val2, const char *arg);
+    bt_status_t (*send_at_cmd) (const bt_bdaddr_t *bd_addr, int cmd, int val1, int val2, const char *arg);
 } bthf_client_interface_t;
 
 __END_DECLS
diff --git a/include/hardware/bt_rc.h b/include/hardware/bt_rc.h
index 4a1a56f..ee99d91 100644
--- a/include/hardware/bt_rc.h
+++ b/include/hardware/bt_rc.h
@@ -23,14 +23,13 @@
 #define BT_RC_NUM_APP 1
 
 /* Macros */
-#define BTRC_MAX_ATTR_STR_LEN       255
+#define BTRC_MAX_ATTR_STR_LEN       (1 << 16)
 #define BTRC_UID_SIZE               8
 #define BTRC_MAX_APP_SETTINGS       8
 #define BTRC_MAX_FOLDER_DEPTH       4
 #define BTRC_MAX_APP_ATTR_SIZE      16
 #define BTRC_MAX_ELEM_ATTR_SIZE     8
-#define BTRC_FEATURE_MASK_SIZE      16
-
+#define BTRC_FEATURE_BIT_MASK_SIZE 16
 
 /* Macros for valid scopes in get_folder_items */
 #define BTRC_SCOPE_PLAYER_LIST  0x00 /* Media Player List */
@@ -46,6 +45,25 @@
 #define BTRC_ITEM_FOLDER  0x02 /* Folder */
 #define BTRC_ITEM_MEDIA   0x03 /* Media File */
 
+/* Macros for media attribute IDs */
+#define BTRC_MEDIA_ATTR_ID_INVALID               -1
+#define BTRC_MEDIA_ATTR_ID_TITLE                 0x00000001
+#define BTRC_MEDIA_ATTR_ID_ARTIST                0x00000002
+#define BTRC_MEDIA_ATTR_ID_ALBUM                 0x00000003
+#define BTRC_MEDIA_ATTR_ID_TRACK_NUM             0x00000004
+#define BTRC_MEDIA_ATTR_ID_NUM_TRACKS            0x00000005
+#define BTRC_MEDIA_ATTR_ID_GENRE                 0x00000006
+#define BTRC_MEDIA_ATTR_ID_PLAYING_TIME          0x00000007        /* in miliseconds */
+
+/* Macros for folder types */
+#define BTRC_FOLDER_TYPE_MIXED      0x00
+#define BTRC_FOLDER_TYPE_TITLES     0x01
+#define BTRC_FOLDER_TYPE_ALBUMS     0x02
+#define BTRC_FOLDER_TYPE_ARTISTS    0x03
+#define BTRC_FOLDER_TYPE_GENRES     0x04
+#define BTRC_FOLDER_TYPE_PLAYLISTS  0x05
+#define BTRC_FOLDER_TYPE_YEARS      0x06
+
 /* Macros for media types */
 #define BTRC_MEDIA_TYPE_AUDIO  0x00 /* audio */
 #define BTRC_MEDIA_TYPE_VIDEO  0x01 /* video */
@@ -231,7 +249,7 @@
     uint8_t   major_type;
     uint32_t  sub_type;
     uint8_t   play_status;
-    uint8_t   features[BTRC_FEATURE_MASK_SIZE];
+    uint8_t   features[BTRC_FEATURE_BIT_MASK_SIZE];
     uint16_t  charset_id;
     uint8_t   name[BTRC_MAX_ATTR_STR_LEN];
 } btrc_item_player_t;
@@ -502,11 +520,12 @@
     void  (*cleanup)( void );
 } btrc_interface_t;
 
-typedef void (* btrc_passthrough_rsp_callback) (int id, int key_state, bt_bdaddr_t *bd_addr);
+typedef void (* btrc_passthrough_rsp_callback) (bt_bdaddr_t *bd_addr, int id, int key_state);
 
 typedef void (* btrc_groupnavigation_rsp_callback) (int id, int key_state);
 
-typedef void (* btrc_connection_state_callback) (bool state, bt_bdaddr_t *bd_addr);
+typedef void (* btrc_connection_state_callback) (
+    bool rc_connect, bool bt_connect, bt_bdaddr_t *bd_addr);
 
 typedef void (* btrc_ctrl_getrcfeatures_callback) (bt_bdaddr_t *bd_addr, int features);
 
@@ -535,6 +554,16 @@
 typedef void (* btrc_ctrl_play_status_changed_callback)(bt_bdaddr_t *bd_addr,
                                                             btrc_play_status_t play_status);
 
+typedef void (* btrc_ctrl_get_folder_items_callback )(bt_bdaddr_t *bd_addr,
+                                                            btrc_status_t status,
+                                                            const btrc_folder_items_t *folder_items,
+                                                            uint8_t count);
+
+typedef void (* btrc_ctrl_change_path_callback)(bt_bdaddr_t *bd_addr, uint8_t count);
+
+typedef void (* btrc_ctrl_set_browsed_player_callback )(
+    bt_bdaddr_t *bd_addr, uint8_t num_items, uint8_t depth);
+typedef void (* btrc_ctrl_set_addressed_player_callback)(bt_bdaddr_t *bd_addr, uint8_t status);
 /** BT-RC Controller callback structure. */
 typedef struct {
     /** set to sizeof(BtRcCallbacks) */
@@ -551,6 +580,10 @@
     btrc_ctrl_track_changed_callback                            track_changed_cb;
     btrc_ctrl_play_position_changed_callback                    play_position_changed_cb;
     btrc_ctrl_play_status_changed_callback                      play_status_changed_cb;
+    btrc_ctrl_get_folder_items_callback                         get_folder_items_cb;
+    btrc_ctrl_change_path_callback                              change_folder_path_cb;
+    btrc_ctrl_set_browsed_player_callback                       set_browsed_player_cb;
+    btrc_ctrl_set_addressed_player_callback                     set_addressed_player_cb;
 } btrc_ctrl_callbacks_t;
 
 /** Represents the standard BT-RC AVRCP Controller interface. */
@@ -575,6 +608,31 @@
     bt_status_t (*set_player_app_setting_cmd) (bt_bdaddr_t *bd_addr, uint8_t num_attrib,
             uint8_t* attrib_ids, uint8_t* attrib_vals);
 
+    /** send command to play a particular item */
+    bt_status_t (*play_item_cmd) (
+        bt_bdaddr_t *bd_addr, uint8_t scope, uint8_t *uid, uint16_t uid_counter);
+
+    /** get the playback state */
+    bt_status_t (*get_playback_state_cmd) (bt_bdaddr_t *bd_addr);
+
+    /** get the now playing list */
+    bt_status_t (*get_now_playing_list_cmd) (bt_bdaddr_t *bd_addr, uint8_t start, uint8_t items);
+
+    /** get the folder list */
+    bt_status_t (*get_folder_list_cmd) (bt_bdaddr_t *bd_addr, uint8_t start, uint8_t items);
+
+    /** get the folder list */
+    bt_status_t (*get_player_list_cmd) (bt_bdaddr_t *bd_addr, uint8_t start, uint8_t items);
+
+    /** get the folder list */
+    bt_status_t (*change_folder_path_cmd) (bt_bdaddr_t *bd_addr, uint8_t direction, uint8_t * uid);
+
+    /** set browsed player */
+    bt_status_t (*set_browsed_player_cmd) (bt_bdaddr_t *bd_addr, uint16_t player_id);
+
+    /** set addressed player */
+    bt_status_t (*set_addressed_player_cmd) (bt_bdaddr_t *bd_addr, uint16_t player_id);
+
     /** send rsp to set_abs_vol received from target */
     bt_status_t (*set_volume_rsp) (bt_bdaddr_t *bd_addr, uint8_t abs_vol, uint8_t label);
 
diff --git a/include/hardware/camera2.h b/include/hardware/camera2.h
index 2b7add0..547a1d7 100644
--- a/include/hardware/camera2.h
+++ b/include/hardware/camera2.h
@@ -146,7 +146,7 @@
 typedef struct camera2_jpeg_blob {
     uint16_t jpeg_blob_id;
     uint32_t jpeg_size;
-};
+} camera2_jpeg_blob_t;
 
 enum {
     CAMERA2_JPEG_BLOB_ID = 0x00FF
diff --git a/include/hardware/context_hub.h b/include/hardware/context_hub.h
index 3004494..aaa4274 100644
--- a/include/hardware/context_hub.h
+++ b/include/hardware/context_hub.h
@@ -358,6 +358,27 @@
  */
 
 /**
+ * CONTEXT_HUB_OS_REBOOT
+ * Reboots context hub OS, restarts all the nanoApps.
+ * No reboot notification is sent to nanoApps; reboot happens immediately and
+ * unconditionally; all volatile FW state and any data is lost as a result
+ *
+ * Payload : none
+ *
+ * Response : status_response_t
+ *            On receipt of a successful response, it is
+ *               expected that
+ *
+ *               i) system reboot has completed;
+ *                  status contains reboot reason code (platform-specific)
+ *
+ * Unsolicited response:
+ *            System may send unsolicited response at any time;
+ *            this should be interpreted as FW reboot, and necessary setup
+ *            has to be done (same or similar to the setup done on system boot)
+ */
+
+/**
  * All communication between the context hubs and the Context Hub Service is in
  * the form of messages. Some message types are distinguished and their
  * Semantics shall be well defined.
@@ -372,6 +393,7 @@
     CONTEXT_HUB_UNLOAD_APP   = 4, // Unload a specified app
     CONTEXT_HUB_QUERY_APPS   = 5, // Query for app(s) info on hub
     CONTEXT_HUB_QUERY_MEMORY = 6, // Query for memory info
+    CONTEXT_HUB_OS_REBOOT    = 7, // Request to reboot context HUB OS
 } hub_messages_e;
 
 #define CONTEXT_HUB_TYPE_PRIVATE_MSG_BASE 0x00400
diff --git a/include/hardware/fb.h b/include/hardware/fb.h
index 9df9416..65720a3 100644
--- a/include/hardware/fb.h
+++ b/include/hardware/fb.h
@@ -160,7 +160,7 @@
 static inline int framebuffer_open(const struct hw_module_t* module,
         struct framebuffer_device_t** device) {
     return module->methods->open(module,
-            GRALLOC_HARDWARE_FB0, (struct hw_device_t**)device);
+            GRALLOC_HARDWARE_FB0, TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int framebuffer_close(struct framebuffer_device_t* device) {
diff --git a/include/hardware/gralloc.h b/include/hardware/gralloc.h
index ef86f90..1b06ebf 100644
--- a/include/hardware/gralloc.h
+++ b/include/hardware/gralloc.h
@@ -68,69 +68,69 @@
 
 enum {
     /* buffer is never read in software */
-    GRALLOC_USAGE_SW_READ_NEVER         = 0x00000000,
+    GRALLOC_USAGE_SW_READ_NEVER         = 0x00000000U,
     /* buffer is rarely read in software */
-    GRALLOC_USAGE_SW_READ_RARELY        = 0x00000002,
+    GRALLOC_USAGE_SW_READ_RARELY        = 0x00000002U,
     /* buffer is often read in software */
-    GRALLOC_USAGE_SW_READ_OFTEN         = 0x00000003,
+    GRALLOC_USAGE_SW_READ_OFTEN         = 0x00000003U,
     /* mask for the software read values */
-    GRALLOC_USAGE_SW_READ_MASK          = 0x0000000F,
+    GRALLOC_USAGE_SW_READ_MASK          = 0x0000000FU,
 
     /* buffer is never written in software */
-    GRALLOC_USAGE_SW_WRITE_NEVER        = 0x00000000,
+    GRALLOC_USAGE_SW_WRITE_NEVER        = 0x00000000U,
     /* buffer is rarely written in software */
-    GRALLOC_USAGE_SW_WRITE_RARELY       = 0x00000020,
+    GRALLOC_USAGE_SW_WRITE_RARELY       = 0x00000020U,
     /* buffer is often written in software */
-    GRALLOC_USAGE_SW_WRITE_OFTEN        = 0x00000030,
+    GRALLOC_USAGE_SW_WRITE_OFTEN        = 0x00000030U,
     /* mask for the software write values */
-    GRALLOC_USAGE_SW_WRITE_MASK         = 0x000000F0,
+    GRALLOC_USAGE_SW_WRITE_MASK         = 0x000000F0U,
 
     /* buffer will be used as an OpenGL ES texture */
-    GRALLOC_USAGE_HW_TEXTURE            = 0x00000100,
+    GRALLOC_USAGE_HW_TEXTURE            = 0x00000100U,
     /* buffer will be used as an OpenGL ES render target */
-    GRALLOC_USAGE_HW_RENDER             = 0x00000200,
+    GRALLOC_USAGE_HW_RENDER             = 0x00000200U,
     /* buffer will be used by the 2D hardware blitter */
-    GRALLOC_USAGE_HW_2D                 = 0x00000400,
+    GRALLOC_USAGE_HW_2D                 = 0x00000400U,
     /* buffer will be used by the HWComposer HAL module */
-    GRALLOC_USAGE_HW_COMPOSER           = 0x00000800,
+    GRALLOC_USAGE_HW_COMPOSER           = 0x00000800U,
     /* buffer will be used with the framebuffer device */
-    GRALLOC_USAGE_HW_FB                 = 0x00001000,
+    GRALLOC_USAGE_HW_FB                 = 0x00001000U,
 
     /* buffer should be displayed full-screen on an external display when
      * possible */
-    GRALLOC_USAGE_EXTERNAL_DISP         = 0x00002000,
+    GRALLOC_USAGE_EXTERNAL_DISP         = 0x00002000U,
 
     /* Must have a hardware-protected path to external display sink for
      * this buffer.  If a hardware-protected path is not available, then
      * either don't composite only this buffer (preferred) to the
      * external sink, or (less desirable) do not route the entire
      * composition to the external sink.  */
-    GRALLOC_USAGE_PROTECTED             = 0x00004000,
+    GRALLOC_USAGE_PROTECTED             = 0x00004000U,
 
     /* buffer may be used as a cursor */
-    GRALLOC_USAGE_CURSOR                = 0x00008000,
+    GRALLOC_USAGE_CURSOR                = 0x00008000U,
 
     /* buffer will be used with the HW video encoder */
-    GRALLOC_USAGE_HW_VIDEO_ENCODER      = 0x00010000,
+    GRALLOC_USAGE_HW_VIDEO_ENCODER      = 0x00010000U,
     /* buffer will be written by the HW camera pipeline */
-    GRALLOC_USAGE_HW_CAMERA_WRITE       = 0x00020000,
+    GRALLOC_USAGE_HW_CAMERA_WRITE       = 0x00020000U,
     /* buffer will be read by the HW camera pipeline */
-    GRALLOC_USAGE_HW_CAMERA_READ        = 0x00040000,
+    GRALLOC_USAGE_HW_CAMERA_READ        = 0x00040000U,
     /* buffer will be used as part of zero-shutter-lag queue */
-    GRALLOC_USAGE_HW_CAMERA_ZSL         = 0x00060000,
+    GRALLOC_USAGE_HW_CAMERA_ZSL         = 0x00060000U,
     /* mask for the camera access values */
-    GRALLOC_USAGE_HW_CAMERA_MASK        = 0x00060000,
+    GRALLOC_USAGE_HW_CAMERA_MASK        = 0x00060000U,
     /* mask for the software usage bit-mask */
-    GRALLOC_USAGE_HW_MASK               = 0x00071F00,
+    GRALLOC_USAGE_HW_MASK               = 0x00071F00U,
 
     /* buffer will be used as a RenderScript Allocation */
-    GRALLOC_USAGE_RENDERSCRIPT          = 0x00100000,
+    GRALLOC_USAGE_RENDERSCRIPT          = 0x00100000U,
 
     /* Set by the consumer to indicate to the producer that they may attach a
      * buffer that they did not detach from the BufferQueue. Will be filtered
      * out by GRALLOC_USAGE_ALLOC_MASK, so gralloc modules will not need to
      * handle this flag. */
-    GRALLOC_USAGE_FOREIGN_BUFFERS       = 0x00200000,
+    GRALLOC_USAGE_FOREIGN_BUFFERS       = 0x00200000U,
 
     /* Mask of all flags which could be passed to a gralloc module for buffer
      * allocation. Any flags not in this mask do not need to be handled by
@@ -138,11 +138,11 @@
     GRALLOC_USAGE_ALLOC_MASK            = ~(GRALLOC_USAGE_FOREIGN_BUFFERS),
 
     /* implementation-specific private usage flags */
-    GRALLOC_USAGE_PRIVATE_0             = 0x10000000,
-    GRALLOC_USAGE_PRIVATE_1             = 0x20000000,
-    GRALLOC_USAGE_PRIVATE_2             = 0x40000000,
-    GRALLOC_USAGE_PRIVATE_3             = 0x80000000,
-    GRALLOC_USAGE_PRIVATE_MASK          = 0xF0000000,
+    GRALLOC_USAGE_PRIVATE_0             = 0x10000000U,
+    GRALLOC_USAGE_PRIVATE_1             = 0x20000000U,
+    GRALLOC_USAGE_PRIVATE_2             = 0x40000000U,
+    GRALLOC_USAGE_PRIVATE_3             = 0x80000000U,
+    GRALLOC_USAGE_PRIVATE_MASK          = 0xF0000000U,
 };
 
 /*****************************************************************************/
@@ -372,13 +372,45 @@
 static inline int gralloc_open(const struct hw_module_t* module, 
         struct alloc_device_t** device) {
     return module->methods->open(module, 
-            GRALLOC_HARDWARE_GPU0, (struct hw_device_t**)device);
+            GRALLOC_HARDWARE_GPU0, TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int gralloc_close(struct alloc_device_t* device) {
     return device->common.close(&device->common);
 }
 
+/**
+ * map_usage_to_memtrack should be called after allocating a gralloc buffer.
+ *
+ * @param usage - it is the flag used when alloc function is called.
+ *
+ * This function maps the gralloc usage flags to appropriate memtrack bucket.
+ * GrallocHAL implementers and users should make an additional ION_IOCTL_TAG
+ * call using the memtrack tag returned by this function. This will help the
+ * in-kernel memtack to categorize the memory allocated by different processes
+ * according to their usage.
+ *
+ */
+static inline const char* map_usage_to_memtrack(uint32_t usage) {
+    usage &= GRALLOC_USAGE_ALLOC_MASK;
+
+    if ((usage & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
+        return "camera";
+    } else if ((usage & GRALLOC_USAGE_HW_VIDEO_ENCODER) != 0 ||
+            (usage & GRALLOC_USAGE_EXTERNAL_DISP) != 0) {
+        return "video";
+    } else if ((usage & GRALLOC_USAGE_HW_RENDER) != 0 ||
+            (usage & GRALLOC_USAGE_HW_TEXTURE) != 0) {
+        return "gl";
+    } else if ((usage & GRALLOC_USAGE_HW_CAMERA_READ) != 0) {
+        return "camera";
+    } else if ((usage & GRALLOC_USAGE_SW_READ_MASK) != 0 ||
+            (usage & GRALLOC_USAGE_SW_WRITE_MASK) != 0) {
+        return "cpu";
+    }
+    return "graphics";
+}
+
 __END_DECLS
 
 #endif  // ANDROID_GRALLOC_INTERFACE_H
diff --git a/include/hardware/gralloc1.h b/include/hardware/gralloc1.h
index 58c0e33..a1a2d69 100644
--- a/include/hardware/gralloc1.h
+++ b/include/hardware/gralloc1.h
@@ -290,7 +290,7 @@
 static inline int gralloc1_open(const struct hw_module_t* module,
         gralloc1_device_t** device) {
     return module->methods->open(module, GRALLOC_HARDWARE_MODULE_ID,
-            (struct hw_device_t**) device);
+            TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int gralloc1_close(gralloc1_device_t* device) {
diff --git a/include/hardware/hardware.h b/include/hardware/hardware.h
index 74f57aa..5ba37e9 100644
--- a/include/hardware/hardware.h
+++ b/include/hardware/hardware.h
@@ -20,8 +20,10 @@
 #include <stdint.h>
 #include <sys/cdefs.h>
 
+#ifndef _HW_DONT_INCLUDE_CORE_
 #include <cutils/native_handle.h>
 #include <system/graphics.h>
+#endif // _HW_DONT_INCLUDE_CORE_
 
 __BEGIN_DECLS
 
@@ -201,6 +203,12 @@
 
 } hw_device_t;
 
+#ifdef __cplusplus
+#define TO_HW_DEVICE_T_OPEN(x) reinterpret_cast<struct hw_device_t**>(x)
+#else
+#define TO_HW_DEVICE_T_OPEN(x) (struct hw_device_t**)(x)
+#endif
+
 /**
  * Name of the hal_module_info
  */
diff --git a/include/hardware/hdmi_cec.h b/include/hardware/hdmi_cec.h
index ab70f92..aa06384 100644
--- a/include/hardware/hdmi_cec.h
+++ b/include/hardware/hdmi_cec.h
@@ -417,7 +417,7 @@
 static inline int hdmi_cec_open(const struct hw_module_t* module,
         struct hdmi_cec_device** device) {
     return module->methods->open(module,
-            HDMI_CEC_HARDWARE_INTERFACE, (struct hw_device_t**)device);
+            HDMI_CEC_HARDWARE_INTERFACE, TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int hdmi_cec_close(struct hdmi_cec_device* device) {
diff --git a/include/hardware/hw_auth_token.h b/include/hardware/hw_auth_token.h
index f471d1a..d84ea48 100644
--- a/include/hardware/hw_auth_token.h
+++ b/include/hardware/hw_auth_token.h
@@ -23,7 +23,7 @@
 extern "C" {
 #endif  // __cplusplus
 
-const uint8_t HW_AUTH_TOKEN_VERSION = 0;
+static const uint8_t HW_AUTH_TOKEN_VERSION = 0;
 
 typedef enum {
     HW_AUTH_NONE = 0,
diff --git a/include/hardware/hwcomposer.h b/include/hardware/hwcomposer.h
index 61218bb..7eca7c1 100644
--- a/include/hardware/hwcomposer.h
+++ b/include/hardware/hwcomposer.h
@@ -783,7 +783,7 @@
 static inline int hwc_open_1(const struct hw_module_t* module,
         hwc_composer_device_1_t** device) {
     return module->methods->open(module,
-            HWC_HARDWARE_COMPOSER, (struct hw_device_t**)device);
+            HWC_HARDWARE_COMPOSER, TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int hwc_close_1(hwc_composer_device_1_t* device) {
diff --git a/include/hardware/hwcomposer2.h b/include/hardware/hwcomposer2.h
index 6973603..35eedb0 100644
--- a/include/hardware/hwcomposer2.h
+++ b/include/hardware/hwcomposer2.h
@@ -17,6 +17,8 @@
 #ifndef ANDROID_HARDWARE_HWCOMPOSER2_H
 #define ANDROID_HARDWARE_HWCOMPOSER2_H
 
+#include <sys/cdefs.h>
+
 #include <hardware/hardware.h>
 
 #include "hwcomposer_defs.h"
@@ -360,7 +362,7 @@
 
 static inline const char* getDisplayRequestName(
         hwc2_display_request_t request) {
-    switch (request) {
+    switch (__BIONIC_CAST(static_cast, int, request)) {
         case 0: return "None";
         case HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET: return "FlipClientTarget";
         case HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT:
@@ -459,7 +461,7 @@
 }
 
 static inline const char* getLayerRequestName(hwc2_layer_request_t request) {
-    switch (request) {
+    switch (__BIONIC_CAST(static_cast, int, request)) {
         case 0: return "None";
         case HWC2_LAYER_REQUEST_CLEAR_CLIENT_TARGET: return "ClearClientTarget";
         default: return "Unknown";
@@ -477,7 +479,7 @@
 }
 
 static inline const char* getTransformName(hwc_transform_t transform) {
-    switch (transform) {
+    switch (__BIONIC_CAST(static_cast, int, transform)) {
         case 0: return "None";
         case HWC_TRANSFORM_FLIP_H: return "FlipH";
         case HWC_TRANSFORM_FLIP_V: return "FlipV";
@@ -738,7 +740,7 @@
 static inline int hwc2_open(const struct hw_module_t* module,
         hwc2_device_t** device) {
     return module->methods->open(module, HWC_HARDWARE_COMPOSER,
-            (struct hw_device_t**) device);
+            TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int hwc2_close(hwc2_device_t* device) {
diff --git a/include/hardware/keymaster0.h b/include/hardware/keymaster0.h
index f020e5b..52ac64b 100644
--- a/include/hardware/keymaster0.h
+++ b/include/hardware/keymaster0.h
@@ -134,7 +134,7 @@
         keymaster0_device_t** device)
 {
     int rc = module->methods->open(module, KEYSTORE_KEYMASTER,
-            (struct hw_device_t**) device);
+            TO_HW_DEVICE_T_OPEN(device));
 
     return rc;
 }
diff --git a/include/hardware/keymaster1.h b/include/hardware/keymaster1.h
index afd202c..9969380 100644
--- a/include/hardware/keymaster1.h
+++ b/include/hardware/keymaster1.h
@@ -536,7 +536,7 @@
 /* Convenience API for opening and closing keymaster devices */
 
 static inline int keymaster1_open(const struct hw_module_t* module, keymaster1_device_t** device) {
-    return module->methods->open(module, KEYSTORE_KEYMASTER, (struct hw_device_t**)device);
+    return module->methods->open(module, KEYSTORE_KEYMASTER, TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int keymaster1_close(keymaster1_device_t* device) {
diff --git a/include/hardware/keymaster2.h b/include/hardware/keymaster2.h
index 565ad2e..f1993f8 100644
--- a/include/hardware/keymaster2.h
+++ b/include/hardware/keymaster2.h
@@ -420,7 +420,7 @@
 /* Convenience API for opening and closing keymaster devices */
 
 static inline int keymaster2_open(const struct hw_module_t* module, keymaster2_device_t** device) {
-    return module->methods->open(module, KEYSTORE_KEYMASTER, (struct hw_device_t**)device);
+    return module->methods->open(module, KEYSTORE_KEYMASTER, TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int keymaster2_close(keymaster2_device_t* device) {
diff --git a/include/hardware/keymaster_defs.h b/include/hardware/keymaster_defs.h
index b45e785..0f9bc27 100644
--- a/include/hardware/keymaster_defs.h
+++ b/include/hardware/keymaster_defs.h
@@ -518,7 +518,7 @@
 
 #define KEYMASTER_SIMPLE_COMPARE(a, b) (a < b) ? -1 : ((a > b) ? 1 : 0)
 inline int keymaster_param_compare(const keymaster_key_param_t* a, const keymaster_key_param_t* b) {
-    int retval = KEYMASTER_SIMPLE_COMPARE(a->tag, b->tag);
+    int retval = KEYMASTER_SIMPLE_COMPARE((uint32_t)a->tag, (uint32_t)b->tag);
     if (retval != 0)
         return retval;
 
diff --git a/include/hardware/local_time_hal.h b/include/hardware/local_time_hal.h
index 946e799..1bbbf11 100644
--- a/include/hardware/local_time_hal.h
+++ b/include/hardware/local_time_hal.h
@@ -109,7 +109,7 @@
         struct local_time_hw_device** device)
 {
     return module->methods->open(module, LOCAL_TIME_HARDWARE_INTERFACE,
-                                 (struct hw_device_t**)device);
+                                 TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int local_time_hw_device_close(struct local_time_hw_device* device)
diff --git a/include/hardware/nfc-base.h b/include/hardware/nfc-base.h
new file mode 100644
index 0000000..d53e759
--- /dev/null
+++ b/include/hardware/nfc-base.h
@@ -0,0 +1,32 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+#ifndef HIDL_GENERATED_android_hardware_nfc_V1_0__EXPORTED_CONSTANTS_H_
+#define HIDL_GENERATED_android_hardware_nfc_V1_0__EXPORTED_CONSTANTS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+enum {
+    HAL_NFC_OPEN_CPLT_EVT = 0,
+    HAL_NFC_CLOSE_CPLT_EVT = 1,
+    HAL_NFC_POST_INIT_CPLT_EVT = 2,
+    HAL_NFC_PRE_DISCOVER_CPLT_EVT = 3,
+    HAL_NFC_REQUEST_CONTROL_EVT = 4,
+    HAL_NFC_RELEASE_CONTROL_EVT = 5,
+    HAL_NFC_ERROR_EVT = 6,
+};
+
+enum {
+    HAL_NFC_STATUS_OK = 0,
+    HAL_NFC_STATUS_FAILED = 1,
+    HAL_NFC_STATUS_ERR_TRANSPORT = 2,
+    HAL_NFC_STATUS_ERR_CMD_TIMEOUT = 3,
+    HAL_NFC_STATUS_REFUSED = 4,
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // HIDL_GENERATED_android_hardware_nfc_V1_0__EXPORTED_CONSTANTS_H_
diff --git a/include/hardware/nfc.h b/include/hardware/nfc.h
index 58d33d9..fdd79a5 100644
--- a/include/hardware/nfc.h
+++ b/include/hardware/nfc.h
@@ -23,6 +23,7 @@
 #include <sys/types.h>
 
 #include <hardware/hardware.h>
+#include "nfc-base.h"
 
 __BEGIN_DECLS
 
@@ -69,34 +70,9 @@
     struct hw_module_t common;
 } nfc_nci_module_t;
 
-/*
- * HAL events that can be passed back to the stack
- */
 typedef uint8_t nfc_event_t;
-
-enum {
-    HAL_NFC_OPEN_CPLT_EVT           = 0x00,
-    HAL_NFC_CLOSE_CPLT_EVT          = 0x01,
-    HAL_NFC_POST_INIT_CPLT_EVT      = 0x02,
-    HAL_NFC_PRE_DISCOVER_CPLT_EVT   = 0x03,
-    HAL_NFC_REQUEST_CONTROL_EVT     = 0x04,
-    HAL_NFC_RELEASE_CONTROL_EVT     = 0x05,
-    HAL_NFC_ERROR_EVT               = 0x06
-};
-
-/*
- * Allowed status return values for each of the HAL methods
- */
 typedef uint8_t nfc_status_t;
 
-enum {
-    HAL_NFC_STATUS_OK               = 0x00,
-    HAL_NFC_STATUS_FAILED           = 0x01,
-    HAL_NFC_STATUS_ERR_TRANSPORT    = 0x02,
-    HAL_NFC_STATUS_ERR_CMD_TIMEOUT  = 0x03,
-    HAL_NFC_STATUS_REFUSED          = 0x04
-};
-
 /*
  * The callback passed in from the NFC stack that the HAL
  * can use to pass events back to the stack.
diff --git a/include/hardware/nvram.h b/include/hardware/nvram.h
index 859ea47..0654afe 100644
--- a/include/hardware/nvram.h
+++ b/include/hardware/nvram.h
@@ -326,7 +326,7 @@
 static inline int nvram_open(const struct hw_module_t* module,
                              nvram_device_t** device) {
     return module->methods->open(module, NVRAM_HARDWARE_DEVICE_ID,
-                                 (struct hw_device_t**)device);
+                                 TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int nvram_close(nvram_device_t* device) {
diff --git a/include/hardware/power.h b/include/hardware/power.h
index c451d67..bd8216e 100644
--- a/include/hardware/power.h
+++ b/include/hardware/power.h
@@ -63,7 +63,9 @@
     POWER_HINT_VIDEO_DECODE = 0x00000004,
     POWER_HINT_LOW_POWER = 0x00000005,
     POWER_HINT_SUSTAINED_PERFORMANCE = 0x00000006,
-    POWER_HINT_VR_MODE = 0x00000007
+    POWER_HINT_VR_MODE = 0x00000007,
+    POWER_HINT_LAUNCH = 0x00000008,
+    POWER_HINT_DISABLE_TOUCH = 0x00000009
 } power_hint_t;
 
 typedef enum {
@@ -247,6 +249,14 @@
      *     device can sustain it. The data parameter is non-zero when the mode
      *     is activated and zero when deactivated.
      *
+     * POWER_HINT_DISABLE_TOUCH
+     *
+     *     When device enters some special modes, e.g. theater mode in Android
+     *     Wear, there is no touch interaction expected between device and user.
+     *     Touch controller could be disabled in those modes to save power.
+     *     The data parameter is non-zero when touch could be disabled, and zero
+     *     when touch needs to be re-enabled.
+     *
      * A particular platform may choose to ignore any hint.
      *
      * availability: version 0.2
diff --git a/include/hardware/radio.h b/include/hardware/radio.h
index 145deb5..413f413 100644
--- a/include/hardware/radio.h
+++ b/include/hardware/radio.h
@@ -285,7 +285,7 @@
                                        struct radio_hw_device** device)
 {
     return module->methods->open(module, RADIO_HARDWARE_DEVICE,
-                                 (struct hw_device_t**)device);
+                                 TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int radio_hw_device_close(const struct radio_hw_device* device)
diff --git a/include/hardware/sensors.h b/include/hardware/sensors.h
index e83f694..322abe6 100644
--- a/include/hardware/sensors.h
+++ b/include/hardware/sensors.h
@@ -1154,7 +1154,7 @@
 
     /**
      * Enumerate all available sensors. The list is returned in "list".
-     * @return number of sensors in the list
+     * return number of sensors in the list
      */
     int (*get_sensors_list)(struct sensors_module_t* module,
             struct sensor_t const** list);
@@ -1165,7 +1165,7 @@
      *  0 - Normal operation. Default state of the module.
      *  1 - Loopback mode. Data is injected for the supported
      *      sensors by the sensor service in this mode.
-     * @return 0 on success
+     * return 0 on success
      *         -EINVAL if requested mode is not supported
      *         -EPERM if operation is not allowed
      */
@@ -1311,11 +1311,16 @@
         struct {
             struct hw_device_t common;
 
-            /* Activate/de-activate one sensor. Return 0 on success, negative
+            /* Activate/de-activate one sensor.
              *
              * sensor_handle is the handle of the sensor to change.
              * enabled set to 1 to enable, or 0 to disable the sensor.
              *
+             * After sensor de-activation, existing sensor events that have not
+             * been picked up by poll() should be abandoned immediately so that
+             * subsequent activation will not get stale sensor events (events
+             * that is generated prior to the latter activation).
+             *
              * Return 0 on success, negative errno code otherwise.
              */
             int (*activate)(struct sensors_poll_device_t *dev,
@@ -1370,7 +1375,7 @@
     /*
      * Inject a single sensor sample to be to this device.
      * data points to the sensor event to be injected
-     * @return 0 on success
+     * return 0 on success
      *         -EPERM if operation is not allowed
      *         -EINVAL if sensor event cannot be injected
      */
@@ -1386,7 +1391,7 @@
 static inline int sensors_open(const struct hw_module_t* module,
         struct sensors_poll_device_t** device) {
     return module->methods->open(module,
-            SENSORS_HARDWARE_POLL, (struct hw_device_t**)device);
+            SENSORS_HARDWARE_POLL, TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int sensors_close(struct sensors_poll_device_t* device) {
@@ -1396,7 +1401,7 @@
 static inline int sensors_open_1(const struct hw_module_t* module,
         sensors_poll_device_1_t** device) {
     return module->methods->open(module,
-            SENSORS_HARDWARE_POLL, (struct hw_device_t**)device);
+            SENSORS_HARDWARE_POLL, TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int sensors_close_1(sensors_poll_device_1_t* device) {
diff --git a/include/hardware/sound_trigger.h b/include/hardware/sound_trigger.h
index e1abbc9..d7828ac 100644
--- a/include/hardware/sound_trigger.h
+++ b/include/hardware/sound_trigger.h
@@ -124,7 +124,7 @@
                                        struct sound_trigger_hw_device** device)
 {
     return module->methods->open(module, SOUND_TRIGGER_HARDWARE_INTERFACE,
-                                 (struct hw_device_t**)device);
+                                 TO_HW_DEVICE_T_OPEN(device));
 }
 
 static inline int sound_trigger_hw_device_close(struct sound_trigger_hw_device* device)
diff --git a/include/hardware/vibrator.h b/include/hardware/vibrator.h
index 200adf0..361085f 100644
--- a/include/hardware/vibrator.h
+++ b/include/hardware/vibrator.h
@@ -65,7 +65,7 @@
 
 static inline int vibrator_open(const struct hw_module_t* module, vibrator_device_t** device)
 {
-    return module->methods->open(module, VIBRATOR_DEVICE_ID_MAIN, (struct hw_device_t**)device);
+    return module->methods->open(module, VIBRATOR_DEVICE_ID_MAIN, TO_HW_DEVICE_T_OPEN(device));
 }
 
 __END_DECLS
diff --git a/modules/audio/audio_hw.c b/modules/audio/audio_hw.c
index a1a322f..35901e4 100644
--- a/modules/audio/audio_hw.c
+++ b/modules/audio/audio_hw.c
@@ -35,10 +35,12 @@
 
 struct stub_stream_out {
     struct audio_stream_out stream;
+    int64_t last_write_time_us;
 };
 
 struct stub_stream_in {
     struct audio_stream_in stream;
+    int64_t last_read_time_us;
 };
 
 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
@@ -79,7 +81,7 @@
 static int out_standby(struct audio_stream *stream)
 {
     ALOGV("out_standby");
-
+    // out->last_write_time_us = 0; unnecessary as a stale write time has same effect
     return 0;
 }
 
@@ -117,10 +119,32 @@
 static ssize_t out_write(struct audio_stream_out *stream, const void* buffer,
                          size_t bytes)
 {
-    ALOGV("out_write: bytes: %d", bytes);
+    ALOGV("out_write: bytes: %zu", bytes);
+
     /* XXX: fake timing for audio output */
-    usleep((int64_t)bytes * 1000000 / audio_stream_out_frame_size(stream) /
-           out_get_sample_rate(&stream->common));
+    struct stub_stream_out *out = (struct stub_stream_out *)stream;
+    struct timespec t = { .tv_sec = 0, .tv_nsec = 0 };
+    clock_gettime(CLOCK_MONOTONIC, &t);
+    const int64_t now = (t.tv_sec * 1000000000LL + t.tv_nsec) / 1000;
+    const int64_t elapsed_time_since_last_write = now - out->last_write_time_us;
+    int64_t sleep_time = bytes * 1000000LL / audio_stream_out_frame_size(stream) /
+               out_get_sample_rate(&stream->common) - elapsed_time_since_last_write;
+    if (sleep_time > 0) {
+        usleep(sleep_time);
+    } else {
+        // we don't sleep when we exit standby (this is typical for a real alsa buffer).
+        sleep_time = 0;
+    }
+    out->last_write_time_us = now + sleep_time;
+    // last_write_time_us is an approximation of when the (simulated) alsa
+    // buffer is believed completely full. The usleep above waits for more space
+    // in the buffer, but by the end of the sleep the buffer is considered
+    // topped-off.
+    //
+    // On the subsequent out_write(), we measure the elapsed time spent in
+    // the mixer. This is subtracted from the sleep estimate based on frames,
+    // thereby accounting for drain in the alsa buffer during mixing.
+    // This is a crude approximation; we don't handle underruns precisely.
     return bytes;
 }
 
@@ -189,6 +213,8 @@
 
 static int in_standby(struct audio_stream *stream)
 {
+    struct stub_stream_in *in = (struct stub_stream_in *)stream;
+    in->last_read_time_us = 0;
     return 0;
 }
 
@@ -216,10 +242,32 @@
 static ssize_t in_read(struct audio_stream_in *stream, void* buffer,
                        size_t bytes)
 {
-    ALOGV("in_read: bytes %d", bytes);
+    ALOGV("in_read: bytes %zu", bytes);
+
     /* XXX: fake timing for audio input */
-    usleep((int64_t)bytes * 1000000 / audio_stream_in_frame_size(stream) /
-           in_get_sample_rate(&stream->common));
+    struct stub_stream_in *in = (struct stub_stream_in *)stream;
+    struct timespec t = { .tv_sec = 0, .tv_nsec = 0 };
+    clock_gettime(CLOCK_MONOTONIC, &t);
+    const int64_t now = (t.tv_sec * 1000000000LL + t.tv_nsec) / 1000;
+
+    // we do a full sleep when exiting standby.
+    const bool standby = in->last_read_time_us == 0;
+    const int64_t elapsed_time_since_last_read = standby ?
+            0 : now - in->last_read_time_us;
+    int64_t sleep_time = bytes * 1000000LL / audio_stream_in_frame_size(stream) /
+            in_get_sample_rate(&stream->common) - elapsed_time_since_last_read;
+    if (sleep_time > 0) {
+        usleep(sleep_time);
+    } else {
+        sleep_time = 0;
+    }
+    in->last_read_time_us = now + sleep_time;
+    // last_read_time_us is an approximation of when the (simulated) alsa
+    // buffer is drained by the read, and is empty.
+    //
+    // On the subsequent in_read(), we measure the elapsed time spent in
+    // the recording thread. This is subtracted from the sleep estimate based on frames,
+    // thereby accounting for fill in the alsa buffer during the interim.
     memset(buffer, 0, bytes);
     return bytes;
 }
diff --git a/modules/sensors/multihal.cpp b/modules/sensors/multihal.cpp
index 0edbc2d..7044551 100644
--- a/modules/sensors/multihal.cpp
+++ b/modules/sensors/multihal.cpp
@@ -155,7 +155,11 @@
         ALOGV("writerTask before poll() - bufferSize = %d", bufferSize);
         eventsPolled = device->poll(device, buffer, bufferSize);
         ALOGV("writerTask poll() got %d events.", eventsPolled);
-        if (eventsPolled == 0) {
+        if (eventsPolled <= 0) {
+            if (eventsPolled < 0) {
+                ALOGV("writerTask ignored error %d from %s", eventsPolled, device->common.module->name);
+                ALOGE("ERROR: Fix %s so it does not return error from poll()", device->common.module->name);
+            }
             continue;
         }
         pthread_mutex_lock(&queue_mutex);
diff --git a/modules/thermal/thermal.c b/modules/thermal/thermal.c
index 6ba5845..7f4de3b 100644
--- a/modules/thermal/thermal.c
+++ b/modules/thermal/thermal.c
@@ -138,8 +138,9 @@
             fclose(file);
             fclose(cpu_file);
             return errno ? -errno : -EIO;
+        } else {
+            fclose(cpu_file);
         }
-        fclose(cpu_file);
 
         if (list != NULL) {
             list[size] = (cpu_usage_t) {
diff --git a/modules/usbaudio/audio_hal.c b/modules/usbaudio/audio_hal.c
index fe4a88e..6a3c5da 100644
--- a/modules/usbaudio/audio_hal.c
+++ b/modules/usbaudio/audio_hal.c
@@ -25,6 +25,7 @@
 #include <sys/time.h>
 
 #include <log/log.h>
+#include <cutils/list.h>
 #include <cutils/str_parms.h>
 #include <cutils/properties.h>
 
@@ -38,17 +39,6 @@
 
 #include <audio_utils/channels.h>
 
-/* FOR TESTING:
- * Set k_force_channels to force the number of channels to present to AudioFlinger.
- *   0 disables (this is default: present the device channels to AudioFlinger).
- *   2 forces to legacy stereo mode.
- *
- * Others values can be tried (up to 8).
- * TODO: AudioFlinger cannot support more than 8 active output channels
- * at this time, so limiting logic needs to be put here or communicated from above.
- */
-static const unsigned k_force_channels = 0;
-
 #include "alsa_device_profile.h"
 #include "alsa_device_proxy.h"
 #include "alsa_logging.h"
@@ -65,9 +55,11 @@
 
     /* output */
     alsa_device_profile out_profile;
+    struct listnode output_stream_list;
 
     /* input */
     alsa_device_profile in_profile;
+    struct listnode input_stream_list;
 
     /* lock input & output sample rates */
     /*FIXME - How do we address multiple output streams? */
@@ -78,14 +70,19 @@
     bool standby;
 };
 
+struct stream_lock {
+    pthread_mutex_t lock;               /* see note below on mutex acquisition order */
+    pthread_mutex_t pre_lock;           /* acquire before lock to avoid DOS by playback thread */
+};
+
 struct stream_out {
     struct audio_stream_out stream;
 
-    pthread_mutex_t lock;               /* see note below on mutex acquisition order */
-    pthread_mutex_t pre_lock;           /* acquire before lock to avoid DOS by playback thread */
+    struct stream_lock  lock;
+
     bool standby;
 
-    struct audio_device *dev;           /* hardware information - only using this for the lock */
+    struct audio_device *adev;           /* hardware information - only using this for the lock */
 
     alsa_device_profile * profile;      /* Points to the alsa_device_profile in the audio_device */
     alsa_device_proxy proxy;            /* state of the stream */
@@ -95,7 +92,13 @@
                                          * the device is not compatible with AudioFlinger
                                          * capabilities, e.g. exposes too many channels or
                                          * too few channels. */
-    audio_channel_mask_t hal_channel_mask;   /* channel mask exposed to AudioFlinger. */
+    audio_channel_mask_t hal_channel_mask;  /* USB devices deal in channel counts, not masks
+                                             * so the proxy doesn't have a channel_mask, but
+                                             * audio HALs need to talk about channel masks
+                                             * so expose the one calculated by
+                                             * adev_open_output_stream */
+
+    struct listnode list_node;
 
     void * conversion_buffer;           /* any conversions are put into here
                                          * they could come from here too if
@@ -106,11 +109,11 @@
 struct stream_in {
     struct audio_stream_in stream;
 
-    pthread_mutex_t lock;               /* see note below on mutex acquisition order */
-    pthread_mutex_t pre_lock;           /* acquire before lock to avoid DOS by capture thread */
+    struct stream_lock  lock;
+
     bool standby;
 
-    struct audio_device *dev;           /* hardware information - only using this for the lock */
+    struct audio_device *adev;           /* hardware information - only using this for the lock */
 
     alsa_device_profile * profile;      /* Points to the alsa_device_profile in the audio_device */
     alsa_device_proxy proxy;            /* state of the stream */
@@ -120,7 +123,13 @@
                                          * the device is not compatible with AudioFlinger
                                          * capabilities, e.g. exposes too many channels or
                                          * too few channels. */
-    audio_channel_mask_t hal_channel_mask;   /* channel mask exposed to AudioFlinger. */
+    audio_channel_mask_t hal_channel_mask;  /* USB devices deal in channel counts, not masks
+                                             * so the proxy doesn't have a channel_mask, but
+                                             * audio HALs need to talk about channel masks
+                                             * so expose the one calculated by
+                                             * adev_open_input_stream */
+
+    struct listnode list_node;
 
     /* We may need to read more data from the device in order to data reduce to 16bit, 4chan */
     void * conversion_buffer;           /* any conversions are put into here
@@ -130,12 +139,63 @@
 };
 
 /*
+ * Locking Helpers
+ */
+/*
  * NOTE: when multiple mutexes have to be acquired, always take the
  * stream_in or stream_out mutex first, followed by the audio_device mutex.
  * stream pre_lock is always acquired before stream lock to prevent starvation of control thread by
  * higher priority playback or capture thread.
  */
 
+static void stream_lock_init(struct stream_lock *lock) {
+    pthread_mutex_init(&lock->lock, (const pthread_mutexattr_t *) NULL);
+    pthread_mutex_init(&lock->pre_lock, (const pthread_mutexattr_t *) NULL);
+}
+
+static void stream_lock(struct stream_lock *lock) {
+    pthread_mutex_lock(&lock->pre_lock);
+    pthread_mutex_lock(&lock->lock);
+    pthread_mutex_unlock(&lock->pre_lock);
+}
+
+static void stream_unlock(struct stream_lock *lock) {
+    pthread_mutex_unlock(&lock->lock);
+}
+
+static void device_lock(struct audio_device *adev) {
+    pthread_mutex_lock(&adev->lock);
+}
+
+static int device_try_lock(struct audio_device *adev) {
+    return pthread_mutex_trylock(&adev->lock);
+}
+
+static void device_unlock(struct audio_device *adev) {
+    pthread_mutex_unlock(&adev->lock);
+}
+
+/*
+ * streams list management
+ */
+static void adev_add_stream_to_list(
+    struct audio_device* adev, struct listnode* list, struct listnode* stream_node) {
+    device_lock(adev);
+
+    list_add_tail(list, stream_node);
+
+    device_unlock(adev);
+}
+
+static void adev_remove_stream_from_list(
+    struct audio_device* adev, struct listnode* stream_node) {
+    device_lock(adev);
+
+    list_remove(stream_node);
+
+    device_unlock(adev);
+}
+
 /*
  * Extract the card and device numbers from the supplied key/value pairs.
  *   kvpairs    A null-terminated string containing the key/value pairs or card and device.
@@ -214,20 +274,6 @@
     return result_str;
 }
 
-void lock_input_stream(struct stream_in *in)
-{
-    pthread_mutex_lock(&in->pre_lock);
-    pthread_mutex_lock(&in->lock);
-    pthread_mutex_unlock(&in->pre_lock);
-}
-
-void lock_output_stream(struct stream_out *out)
-{
-    pthread_mutex_lock(&out->pre_lock);
-    pthread_mutex_lock(&out->lock);
-    pthread_mutex_unlock(&out->pre_lock);
-}
-
 /*
  * HAl Functions
  */
@@ -285,20 +331,28 @@
 {
     struct stream_out *out = (struct stream_out *)stream;
 
-    lock_output_stream(out);
+    stream_lock(&out->lock);
     if (!out->standby) {
-        pthread_mutex_lock(&out->dev->lock);
+        device_lock(out->adev);
         proxy_close(&out->proxy);
-        pthread_mutex_unlock(&out->dev->lock);
+        device_unlock(out->adev);
         out->standby = true;
     }
-    pthread_mutex_unlock(&out->lock);
-
+    stream_unlock(&out->lock);
     return 0;
 }
 
-static int out_dump(const struct audio_stream *stream, int fd)
-{
+static int out_dump(const struct audio_stream *stream, int fd) {
+    const struct stream_out* out_stream = (const struct stream_out*) stream;
+
+    if (out_stream != NULL) {
+        dprintf(fd, "Output Profile:\n");
+        profile_dump(out_stream->profile, fd);
+
+        dprintf(fd, "Output Proxy:\n");
+        proxy_dump(&out_stream->proxy, fd);
+    }
+
     return 0;
 }
 
@@ -318,9 +372,9 @@
         return ret_value;
     }
 
-    lock_output_stream(out);
+    stream_lock(&out->lock);
     /* Lock the device because that is where the profile lives */
-    pthread_mutex_lock(&out->dev->lock);
+    device_lock(out->adev);
 
     if (!profile_is_cached_for(out->profile, card, device)) {
         /* cannot read pcm device info if playback is active */
@@ -339,8 +393,8 @@
         }
     }
 
-    pthread_mutex_unlock(&out->dev->lock);
-    pthread_mutex_unlock(&out->lock);
+    device_unlock(out->adev);
+    stream_unlock(&out->lock);
 
     return ret_value;
 }
@@ -348,14 +402,13 @@
 static char * out_get_parameters(const struct audio_stream *stream, const char *keys)
 {
     struct stream_out *out = (struct stream_out *)stream;
-    lock_output_stream(out);
-    pthread_mutex_lock(&out->dev->lock);
+    stream_lock(&out->lock);
+    device_lock(out->adev);
 
     char * params_str =  device_get_parameters(out->profile, keys);
 
-    pthread_mutex_unlock(&out->lock);
-    pthread_mutex_unlock(&out->dev->lock);
-
+    device_unlock(out->adev);
+    stream_unlock(&out->lock);
     return params_str;
 }
 
@@ -383,11 +436,11 @@
     int ret;
     struct stream_out *out = (struct stream_out *)stream;
 
-    lock_output_stream(out);
+    stream_lock(&out->lock);
     if (out->standby) {
-        pthread_mutex_lock(&out->dev->lock);
+        device_lock(out->adev);
         ret = start_output_stream(out);
-        pthread_mutex_unlock(&out->dev->lock);
+        device_unlock(out->adev);
         if (ret != 0) {
             goto err;
         }
@@ -422,12 +475,12 @@
         proxy_write(&out->proxy, write_buff, num_write_buff_bytes);
     }
 
-    pthread_mutex_unlock(&out->lock);
+    stream_unlock(&out->lock);
 
     return bytes;
 
 err:
-    pthread_mutex_unlock(&out->lock);
+    stream_unlock(&out->lock);
     if (ret != 0) {
         usleep(bytes * 1000000 / audio_stream_out_frame_size(stream) /
                out_get_sample_rate(&stream->common));
@@ -445,12 +498,12 @@
                                          uint64_t *frames, struct timespec *timestamp)
 {
     struct stream_out *out = (struct stream_out *)stream; // discard const qualifier
-    lock_output_stream(out);
+    stream_lock(&out->lock);
 
     const alsa_device_proxy *proxy = &out->proxy;
     const int ret = proxy_get_presentation_position(proxy, frames, timestamp);
 
-    pthread_mutex_unlock(&out->lock);
+    stream_unlock(&out->lock);
     return ret;
 }
 
@@ -469,24 +522,23 @@
     return -EINVAL;
 }
 
-static int adev_open_output_stream(struct audio_hw_device *dev,
+static int adev_open_output_stream(struct audio_hw_device *hw_dev,
                                    audio_io_handle_t handle,
-                                   audio_devices_t devices,
+                                   audio_devices_t devicesSpec __unused,
                                    audio_output_flags_t flags,
                                    struct audio_config *config,
                                    struct audio_stream_out **stream_out,
                                    const char *address /*__unused*/)
 {
-    ALOGV("adev_open_output_stream() handle:0x%X, device:0x%X, flags:0x%X, addr:%s",
-          handle, devices, flags, address);
-
-    struct audio_device *adev = (struct audio_device *)dev;
+    ALOGV("adev_open_output_stream() handle:0x%X, devicesSpec:0x%X, flags:0x%X, addr:%s",
+          handle, devicesSpec, flags, address);
 
     struct stream_out *out;
 
     out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
-    if (!out)
+    if (out == NULL) {
         return -ENOMEM;
+    }
 
     /* setup function pointers */
     out->stream.common.get_sample_rate = out_get_sample_rate;
@@ -508,12 +560,11 @@
     out->stream.get_presentation_position = out_get_presentation_position;
     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
 
-    pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
-    pthread_mutex_init(&out->pre_lock, (const pthread_mutexattr_t *) NULL);
+    stream_lock_init(&out->lock);
 
-    out->dev = adev;
-    pthread_mutex_lock(&adev->lock);
-    out->profile = &adev->out_profile;
+    out->adev = (struct audio_device *)hw_dev;
+    device_lock(out->adev);
+    out->profile = &out->adev->out_profile;
 
     // build this to hand to the alsa_device_proxy
     struct pcm_config proxy_config;
@@ -536,8 +587,8 @@
         ret = -EINVAL;
     }
 
-    out->dev->device_sample_rate = config->sample_rate;
-    pthread_mutex_unlock(&adev->lock);
+    out->adev->device_sample_rate = config->sample_rate;
+    device_unlock(out->adev);
 
     /* Format */
     if (config->format == AUDIO_FORMAT_DEFAULT) {
@@ -555,33 +606,38 @@
     }
 
     /* Channels */
-    unsigned proposed_channel_count = 0;
-    if (k_force_channels) {
-        proposed_channel_count = k_force_channels;
-    } else if (config->channel_mask == AUDIO_CHANNEL_NONE) {
-        proposed_channel_count =  profile_get_default_channel_count(out->profile);
-    }
-
-    if (proposed_channel_count != 0) {
-        if (proposed_channel_count <= FCC_2) {
-            // use channel position mask for mono and stereo
-            config->channel_mask = audio_channel_out_mask_from_count(proposed_channel_count);
-        } else {
-            // use channel index mask for multichannel
-            config->channel_mask =
-                    audio_channel_mask_for_index_assignment_from_count(proposed_channel_count);
-        }
+    bool calc_mask = false;
+    if (config->channel_mask == AUDIO_CHANNEL_NONE) {
+        /* query case */
+        out->hal_channel_count = profile_get_default_channel_count(out->profile);
+        calc_mask = true;
     } else {
-        proposed_channel_count = audio_channel_count_from_out_mask(config->channel_mask);
+        /* explicit case */
+        out->hal_channel_count = audio_channel_count_from_out_mask(config->channel_mask);
     }
-    out->hal_channel_count = proposed_channel_count;
 
-    /* we can expose any channel mask, and emulate internally based on channel count. */
+    /* The Framework is currently limited to no more than this number of channels */
+    if (out->hal_channel_count > FCC_8) {
+        out->hal_channel_count = FCC_8;
+        calc_mask = true;
+    }
+
+    if (calc_mask) {
+        /* need to calculate the mask from channel count either because this is the query case
+         * or the specified mask isn't valid for this device, or is more then the FW can handle */
+        config->channel_mask = out->hal_channel_count <= FCC_2
+            /* position mask for mono and stereo*/
+            ? audio_channel_out_mask_from_count(out->hal_channel_count)
+            /* otherwise indexed */
+            : audio_channel_mask_for_index_assignment_from_count(out->hal_channel_count);
+    }
+
     out->hal_channel_mask = config->channel_mask;
 
-    /* no validity checks are needed as proxy_prepare() forces channel_count to be valid.
-     * and we emulate any channel count discrepancies in out_write(). */
-    proxy_config.channels = out->hal_channel_count;
+    // Validate the "logical" channel count against support in the "actual" profile.
+    // if they differ, choose the "actual" number of channels *closest* to the "logical".
+    // and store THAT in proxy_config.channels
+    proxy_config.channels = profile_get_closest_channel_count(out->profile, out->hal_channel_count);
     proxy_prepare(&out->proxy, out->profile, &proxy_config);
 
     /* TODO The retry mechanism isn't implemented in AudioPolicyManager/AudioFlinger. */
@@ -592,6 +648,9 @@
 
     out->standby = true;
 
+    /* Save the stream for adev_dump() */
+    adev_add_stream_to_list(out->adev, &out->adev->output_stream_list, &out->list_node);
+
     *stream_out = &out->stream;
 
     return ret;
@@ -602,12 +661,14 @@
     return -ENOSYS;
 }
 
-static void adev_close_output_stream(struct audio_hw_device *dev,
+static void adev_close_output_stream(struct audio_hw_device *hw_dev,
                                      struct audio_stream_out *stream)
 {
     struct stream_out *out = (struct stream_out *)stream;
     ALOGV("adev_close_output_stream(c:%d d:%d)", out->profile->card, out->profile->device);
 
+    adev_remove_stream_from_list(out->adev, &out->list_node);
+
     /* Close the pcm device */
     out_standby(&stream->common);
 
@@ -616,14 +677,14 @@
     out->conversion_buffer = NULL;
     out->conversion_buffer_size = 0;
 
-    pthread_mutex_lock(&out->dev->lock);
-    out->dev->device_sample_rate = 0;
-    pthread_mutex_unlock(&out->dev->lock);
+    device_lock(out->adev);
+    out->adev->device_sample_rate = 0;
+    device_unlock(out->adev);
 
     free(stream);
 }
 
-static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
+static size_t adev_get_input_buffer_size(const struct audio_hw_device *hw_dev,
                                          const struct audio_config *config)
 {
     /* TODO This needs to be calculated based on format/channels/rate */
@@ -676,22 +737,31 @@
 {
     struct stream_in *in = (struct stream_in *)stream;
 
-    lock_input_stream(in);
+    stream_lock(&in->lock);
     if (!in->standby) {
-        pthread_mutex_lock(&in->dev->lock);
+        device_lock(in->adev);
         proxy_close(&in->proxy);
-        pthread_mutex_unlock(&in->dev->lock);
+        device_unlock(in->adev);
         in->standby = true;
     }
 
-    pthread_mutex_unlock(&in->lock);
+    stream_unlock(&in->lock);
 
     return 0;
 }
 
 static int in_dump(const struct audio_stream *stream, int fd)
 {
-    return 0;
+  const struct stream_in* in_stream = (const struct stream_in*)stream;
+  if (in_stream != NULL) {
+      dprintf(fd, "Input Profile:\n");
+      profile_dump(in_stream->profile, fd);
+
+      dprintf(fd, "Input Proxy:\n");
+      proxy_dump(&in_stream->proxy, fd);
+  }
+
+  return 0;
 }
 
 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
@@ -712,8 +782,8 @@
         return ret_value;
     }
 
-    lock_input_stream(in);
-    pthread_mutex_lock(&in->dev->lock);
+    stream_lock(&in->lock);
+    device_lock(in->adev);
 
     if (card >= 0 && device >= 0 && !profile_is_cached_for(in->profile, card, device)) {
         /* cannot read pcm device info if playback is active */
@@ -732,8 +802,8 @@
         }
     }
 
-    pthread_mutex_unlock(&in->dev->lock);
-    pthread_mutex_unlock(&in->lock);
+    device_unlock(in->adev);
+    stream_unlock(&in->lock);
 
     return ret_value;
 }
@@ -742,13 +812,13 @@
 {
     struct stream_in *in = (struct stream_in *)stream;
 
-    lock_input_stream(in);
-    pthread_mutex_lock(&in->dev->lock);
+    stream_lock(&in->lock);
+    device_lock(in->adev);
 
     char * params_str =  device_get_parameters(in->profile, keys);
 
-    pthread_mutex_unlock(&in->dev->lock);
-    pthread_mutex_unlock(&in->lock);
+    device_unlock(in->adev);
+    stream_unlock(&in->lock);
 
     return params_str;
 }
@@ -786,11 +856,11 @@
 
     struct stream_in * in = (struct stream_in *)stream;
 
-    lock_input_stream(in);
+    stream_lock(&in->lock);
     if (in->standby) {
-        pthread_mutex_lock(&in->dev->lock);
+        device_lock(in->adev);
         ret = start_input_stream(in);
-        pthread_mutex_unlock(&in->dev->lock);
+        device_unlock(in->adev);
         if (ret != 0) {
             goto err;
         }
@@ -840,16 +910,15 @@
             }
         }
 
-        /* no need to acquire in->dev->lock to read mic_muted here as we don't change its state */
-        if (num_read_buff_bytes > 0 && in->dev->mic_muted)
+        /* no need to acquire in->adev->lock to read mic_muted here as we don't change its state */
+        if (num_read_buff_bytes > 0 && in->adev->mic_muted)
             memset(buffer, 0, num_read_buff_bytes);
     } else {
         num_read_buff_bytes = 0; // reset the value after USB headset is unplugged
     }
 
 err:
-    pthread_mutex_unlock(&in->lock);
-
+    stream_unlock(&in->lock);
     return num_read_buff_bytes;
 }
 
@@ -858,9 +927,9 @@
     return 0;
 }
 
-static int adev_open_input_stream(struct audio_hw_device *dev,
+static int adev_open_input_stream(struct audio_hw_device *hw_dev,
                                   audio_io_handle_t handle,
-                                  audio_devices_t devices,
+                                  audio_devices_t devicesSpec __unused,
                                   struct audio_config *config,
                                   struct audio_stream_in **stream_in,
                                   audio_input_flags_t flags __unused,
@@ -873,8 +942,9 @@
     struct stream_in *in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
     int ret = 0;
 
-    if (in == NULL)
+    if (in == NULL) {
         return -ENOMEM;
+    }
 
     /* setup function pointers */
     in->stream.common.get_sample_rate = in_get_sample_rate;
@@ -894,13 +964,12 @@
     in->stream.read = in_read;
     in->stream.get_input_frames_lost = in_get_input_frames_lost;
 
-    pthread_mutex_init(&in->lock, (const pthread_mutexattr_t *) NULL);
-    pthread_mutex_init(&in->pre_lock, (const pthread_mutexattr_t *) NULL);
+    stream_lock_init(&in->lock);
 
-    in->dev = (struct audio_device *)dev;
-    pthread_mutex_lock(&in->dev->lock);
+    in->adev = (struct audio_device *)hw_dev;
+    device_lock(in->adev);
 
-    in->profile = &in->dev->in_profile;
+    in->profile = &in->adev->in_profile;
 
     struct pcm_config proxy_config;
     memset(&proxy_config, 0, sizeof(proxy_config));
@@ -915,17 +984,17 @@
         config->sample_rate = profile_get_default_sample_rate(in->profile);
     }
 
-    if (in->dev->device_sample_rate != 0 &&                 /* we are playing, so lock the rate */
-        in->dev->device_sample_rate >= RATELOCK_THRESHOLD) {/* but only for high sample rates */
-        ret = config->sample_rate != in->dev->device_sample_rate ? -EINVAL : 0;
-        proxy_config.rate = config->sample_rate = in->dev->device_sample_rate;
+    if (in->adev->device_sample_rate != 0 &&                 /* we are playing, so lock the rate */
+        in->adev->device_sample_rate >= RATELOCK_THRESHOLD) {/* but only for high sample rates */
+        ret = config->sample_rate != in->adev->device_sample_rate ? -EINVAL : 0;
+        proxy_config.rate = config->sample_rate = in->adev->device_sample_rate;
     } else if (profile_is_sample_rate_valid(in->profile, config->sample_rate)) {
-        in->dev->device_sample_rate = proxy_config.rate = config->sample_rate;
+        in->adev->device_sample_rate = proxy_config.rate = config->sample_rate;
     } else {
         proxy_config.rate = config->sample_rate = profile_get_default_sample_rate(in->profile);
         ret = -EINVAL;
     }
-    pthread_mutex_unlock(&in->dev->lock);
+    device_unlock(in->adev);
 
     /* Format */
     if (config->format == AUDIO_FORMAT_DEFAULT) {
@@ -943,40 +1012,75 @@
     }
 
     /* Channels */
-    unsigned proposed_channel_count = 0;
-    if (k_force_channels) {
-        proposed_channel_count = k_force_channels;
-    } else if (config->channel_mask == AUDIO_CHANNEL_NONE) {
-        proposed_channel_count = profile_get_default_channel_count(in->profile);
-    }
-    if (proposed_channel_count != 0) {
-        config->channel_mask = audio_channel_in_mask_from_count(proposed_channel_count);
-        if (config->channel_mask == AUDIO_CHANNEL_INVALID)
-            config->channel_mask =
-                    audio_channel_mask_for_index_assignment_from_count(proposed_channel_count);
-        in->hal_channel_count = proposed_channel_count;
+    bool calc_mask = false;
+    if (config->channel_mask == AUDIO_CHANNEL_NONE) {
+        /* query case */
+        in->hal_channel_count = profile_get_default_channel_count(in->profile);
+        calc_mask = true;
     } else {
+        /* explicit case */
         in->hal_channel_count = audio_channel_count_from_in_mask(config->channel_mask);
     }
-    /* we can expose any channel mask, and emulate internally based on channel count. */
-    in->hal_channel_mask = config->channel_mask;
 
-    proxy_config.channels = profile_get_default_channel_count(in->profile);
-    proxy_prepare(&in->proxy, in->profile, &proxy_config);
+    /* The Framework is currently limited to no more than this number of channels */
+    if (in->hal_channel_count > FCC_8) {
+        in->hal_channel_count = FCC_8;
+        calc_mask = true;
+    }
 
-    in->standby = true;
+    if (calc_mask) {
+        /* need to calculate the mask from channel count either because this is the query case
+         * or the specified mask isn't valid for this device, or is more then the FW can handle */
+        in->hal_channel_mask = in->hal_channel_count <= FCC_2
+            /* position mask for mono & stereo */
+            ? audio_channel_in_mask_from_count(in->hal_channel_count)
+            /* otherwise indexed */
+            : audio_channel_mask_for_index_assignment_from_count(in->hal_channel_count);
 
-    in->conversion_buffer = NULL;
-    in->conversion_buffer_size = 0;
+        // if we change the mask...
+        if (in->hal_channel_mask != config->channel_mask &&
+            config->channel_mask != AUDIO_CHANNEL_NONE) {
+            config->channel_mask = in->hal_channel_mask;
+            ret = -EINVAL;
+        }
+    } else {
+        in->hal_channel_mask = config->channel_mask;
+    }
 
-    *stream_in = &in->stream;
+    if (ret == 0) {
+        // Validate the "logical" channel count against support in the "actual" profile.
+        // if they differ, choose the "actual" number of channels *closest* to the "logical".
+        // and store THAT in proxy_config.channels
+        proxy_config.channels =
+                profile_get_closest_channel_count(in->profile, in->hal_channel_count);
+        proxy_prepare(&in->proxy, in->profile, &proxy_config);
+
+        in->standby = true;
+
+        in->conversion_buffer = NULL;
+        in->conversion_buffer_size = 0;
+
+        *stream_in = &in->stream;
+
+        /* Save this for adev_dump() */
+        adev_add_stream_to_list(in->adev, &in->adev->input_stream_list, &in->list_node);
+    } else {
+        // Deallocate this stream on error, because AudioFlinger won't call
+        // adev_close_input_stream() in this case.
+        *stream_in = NULL;
+        free(in);
+    }
 
     return ret;
 }
 
-static void adev_close_input_stream(struct audio_hw_device *dev, struct audio_stream_in *stream)
+static void adev_close_input_stream(struct audio_hw_device *hw_dev,
+                                    struct audio_stream_in *stream)
 {
     struct stream_in *in = (struct stream_in *)stream;
+    ALOGV("adev_close_input_stream(c:%d d:%d)", in->profile->card, in->profile->device);
+
+    adev_remove_stream_from_list(in->adev, &in->list_node);
 
     /* Close the pcm device */
     in_standby(&stream->common);
@@ -989,52 +1093,94 @@
 /*
  * ADEV Functions
  */
-static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
+static int adev_set_parameters(struct audio_hw_device *hw_dev, const char *kvpairs)
 {
     return 0;
 }
 
-static char * adev_get_parameters(const struct audio_hw_device *dev, const char *keys)
+static char * adev_get_parameters(const struct audio_hw_device *hw_dev, const char *keys)
 {
     return strdup("");
 }
 
-static int adev_init_check(const struct audio_hw_device *dev)
+static int adev_init_check(const struct audio_hw_device *hw_dev)
 {
     return 0;
 }
 
-static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
+static int adev_set_voice_volume(struct audio_hw_device *hw_dev, float volume)
 {
     return -ENOSYS;
 }
 
-static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
+static int adev_set_master_volume(struct audio_hw_device *hw_dev, float volume)
 {
     return -ENOSYS;
 }
 
-static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
+static int adev_set_mode(struct audio_hw_device *hw_dev, audio_mode_t mode)
 {
     return 0;
 }
 
-static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
+static int adev_set_mic_mute(struct audio_hw_device *hw_dev, bool state)
 {
-    struct audio_device * adev = (struct audio_device *)dev;
-    pthread_mutex_lock(&adev->lock);
+    struct audio_device * adev = (struct audio_device *)hw_dev;
+    device_lock(adev);
     adev->mic_muted = state;
-    pthread_mutex_unlock(&adev->lock);
+    device_unlock(adev);
     return -ENOSYS;
 }
 
-static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
+static int adev_get_mic_mute(const struct audio_hw_device *hw_dev, bool *state)
 {
     return -ENOSYS;
 }
 
-static int adev_dump(const audio_hw_device_t *device, int fd)
+static int adev_dump(const struct audio_hw_device *device, int fd)
 {
+    dprintf(fd, "\nUSB audio module:\n");
+
+    struct audio_device* adev = (struct audio_device*)device;
+    const int kNumRetries = 3;
+    const int kSleepTimeMS = 500;
+
+    // use device_try_lock() in case we dumpsys during a deadlock
+    int retry = kNumRetries;
+    while (retry > 0 && device_try_lock(adev) != 0) {
+      sleep(kSleepTimeMS);
+      retry--;
+    }
+
+    if (retry > 0) {
+        if (list_empty(&adev->output_stream_list)) {
+            dprintf(fd, "  No output streams.\n");
+        } else {
+            struct listnode* node;
+            list_for_each(node, &adev->output_stream_list) {
+                struct audio_stream* stream =
+                        (struct audio_stream *)node_to_item(node, struct stream_out, list_node);
+                out_dump(stream, fd);
+            }
+        }
+
+        if (list_empty(&adev->input_stream_list)) {
+            dprintf(fd, "\n  No input streams.\n");
+        } else {
+            struct listnode* node;
+            list_for_each(node, &adev->input_stream_list) {
+                struct audio_stream* stream =
+                        (struct audio_stream *)node_to_item(node, struct stream_in, list_node);
+                in_dump(stream, fd);
+            }
+        }
+
+        device_unlock(adev);
+    } else {
+        // Couldn't lock
+        dprintf(fd, "  Could not obtain device lock.\n");
+    }
+
     return 0;
 }
 
@@ -1058,6 +1204,9 @@
     profile_init(&adev->out_profile, PCM_OUT);
     profile_init(&adev->in_profile, PCM_IN);
 
+    list_init(&adev->output_stream_list);
+    list_init(&adev->input_stream_list);
+
     adev->hw_device.common.tag = HARDWARE_DEVICE_TAG;
     adev->hw_device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
     adev->hw_device.common.module = (struct hw_module_t *)module;
diff --git a/tests/vehicle/vehicle-hal-tool.c b/tests/vehicle/vehicle-hal-tool.c
index c93790a..e85df62 100755
--- a/tests/vehicle/vehicle-hal-tool.c
+++ b/tests/vehicle/vehicle-hal-tool.c
@@ -98,6 +98,7 @@
             memcpy(ascii_out, data->value.str_value.data, data->value.str_value.len);
             ascii_out[data->value.str_value.len] = '\0';
             printf("Value Type: STRING %s\n", ascii_out);
+            free(ascii_out);
             break;
         case VEHICLE_VALUE_TYPE_BYTES:
             printf("Value type: BYTES\n Size: %d", data->value.bytes_value.len);