Merge commit 'f7f839985b3931682363d2ef3b7c5cae55a842ee' into merge

Change-Id: Iaaec1ea0bf3009b7e32a9a60f697631a3f56e889
diff --git a/Android.mk b/Android.mk
index a8c40c8..6f27d9b 100644
--- a/Android.mk
+++ b/Android.mk
@@ -1,7 +1,5 @@
 LOCAL_PATH := $(call my-dir)
 
-bdroid_CFLAGS := -Wno-unused-parameter -Wno-missing-field-initializers
-
 # Setup bdroid local make variables for handling configuration
 ifneq ($(BOARD_BLUETOOTH_BDROID_BUILDCFG_INCLUDE_DIR),)
   bdroid_C_INCLUDES := $(BOARD_BLUETOOTH_BDROID_BUILDCFG_INCLUDE_DIR)
@@ -11,15 +9,22 @@
   bdroid_CFLAGS += -DHAS_NO_BDROID_BUILDCFG
 endif
 
-bdroid_CFLAGS += -Wall -Werror
-
-# Temporary, remove after cleanup. b/18632512
-bdroid_CFLAGS += -Wno-unused
-
 ifneq ($(BOARD_BLUETOOTH_BDROID_HCILP_INCLUDED),)
   bdroid_CFLAGS += -DHCILP_INCLUDED=$(BOARD_BLUETOOTH_BDROID_HCILP_INCLUDED)
 endif
 
+ifneq ($(TARGET_BUILD_VARIANT),user)
+bdroid_CFLAGS += -DBLUEDROID_DEBUG
+endif
+
+bdroid_CFLAGS += \
+  -Wall \
+  -Werror \
+  -Wno-unused-parameter \
+  -Wunused-but-set-variable \
+  -UNDEBUG \
+  -DLOG_NDEBUG=1
+
 include $(call all-subdir-makefiles)
 
 # Cleanup our locals
diff --git a/audio_a2dp_hw/Android.mk b/audio_a2dp_hw/Android.mk
index 6fb83cb..959c255 100644
--- a/audio_a2dp_hw/Android.mk
+++ b/audio_a2dp_hw/Android.mk
@@ -7,9 +7,10 @@
 
 LOCAL_C_INCLUDES += \
 	. \
+	$(LOCAL_PATH)/../ \
 	$(LOCAL_PATH)/../utils/include
 
-LOCAL_CFLAGS += -std=c99
+LOCAL_CFLAGS += -std=c99 $(bdroid_CFLAGS)
 
 LOCAL_MODULE := audio.a2dp.default
 LOCAL_MODULE_RELATIVE_PATH := hw
diff --git a/audio_a2dp_hw/audio_a2dp_hw.c b/audio_a2dp_hw/audio_a2dp_hw.c
index 88ac8d6..5b194b4 100644
--- a/audio_a2dp_hw/audio_a2dp_hw.c
+++ b/audio_a2dp_hw/audio_a2dp_hw.c
@@ -46,9 +46,8 @@
 #include "audio_a2dp_hw.h"
 #include "bt_utils.h"
 
-#define LOG_TAG "audio_a2dp_hw"
-/* #define LOG_NDEBUG 0 */
-#include <log/log.h>
+#define LOG_TAG "bt_a2dp_hw"
+#include "osi/include/log.h"
 
 /*****************************************************************************
 **  Constants & Macros
@@ -59,10 +58,10 @@
 
 #define CASE_RETURN_STR(const) case const: return #const;
 
-#define FNLOG()             ALOGV("%s", __FUNCTION__);
-#define DEBUG(fmt, ...)     ALOGV("%s: " fmt,__FUNCTION__, ## __VA_ARGS__)
-#define INFO(fmt, ...)      ALOGI("%s: " fmt,__FUNCTION__, ## __VA_ARGS__)
-#define ERROR(fmt, ...)     ALOGE("%s: " fmt,__FUNCTION__, ## __VA_ARGS__)
+#define FNLOG()             LOG_VERBOSE("%s", __FUNCTION__);
+#define DEBUG(fmt, ...)     LOG_VERBOSE("%s: " fmt,__FUNCTION__, ## __VA_ARGS__)
+#define INFO(fmt, ...)      LOG_INFO("%s: " fmt,__FUNCTION__, ## __VA_ARGS__)
+#define ERROR(fmt, ...)     LOG_ERROR("%s: " fmt,__FUNCTION__, ## __VA_ARGS__)
 
 #define ASSERTC(cond, msg, val) if (!(cond)) {ERROR("### ASSERT : %s line %d %s (%d) ###", __FILE__, __LINE__, msg, val);}
 
diff --git a/bta/Android.mk b/bta/Android.mk
index 7df6715..d41ae75 100644
--- a/bta/Android.mk
+++ b/bta/Android.mk
@@ -51,9 +51,6 @@
     ./hh/bta_hh_le.c \
     ./hh/bta_hh_utils.c \
     ./hh/bta_hh_main.c \
-    ./pb/bta_pbs_cfg.c \
-    ./fs/bta_fs_ci.c \
-    ./fs/bta_fs_cfg.c \
     ./pan/bta_pan_main.c \
     ./pan/bta_pan_ci.c \
     ./pan/bta_pan_act.c \
@@ -78,11 +75,7 @@
     ./mce/bta_mce_act.c \
     ./mce/bta_mce_cfg.c \
     ./sys/bta_sys_main.c \
-    ./sys/bta_sys_ci.c \
     ./sys/bta_sys_conn.c \
-    ./sys/bta_sys_cfg.c \
-    ./sys/ptim.c \
-    ./sys/bd.c \
     ./sys/utl.c \
     ./jv/bta_jv_act.c \
     ./jv/bta_jv_cfg.c \
@@ -100,13 +93,15 @@
                    $(LOCAL_PATH)/sys \
                    $(LOCAL_PATH)/dm \
                    $(LOCAL_PATH)/hh \
+                   $(LOCAL_PATH)/../ \
+                   $(LOCAL_PATH)/../btcore/include \
                    $(LOCAL_PATH)/../gki/common \
                    $(LOCAL_PATH)/../gki/ulinux \
+                   $(LOCAL_PATH)/../hci/include \
                    $(LOCAL_PATH)/../include \
                    $(LOCAL_PATH)/../stack/include \
                    $(LOCAL_PATH)/../stack/btm \
-                   $(LOCAL_PATH)/../hcis \
-                   $(LOCAL_PATH)/../hcis/patchram \
+                   $(LOCAL_PATH)/../osi/include \
                    $(LOCAL_PATH)/../udrv/include \
                    $(LOCAL_PATH)/../vnd/include \
                    $(LOCAL_PATH)/../utils/include \
diff --git a/bta/ag/bta_ag_act.c b/bta/ag/bta_ag_act.c
index ca4f8eb..f661a19 100644
--- a/bta/ag/bta_ag_act.c
+++ b/bta/ag/bta_ag_act.c
@@ -23,7 +23,6 @@
  ******************************************************************************/
 
 #include "bta_api.h"
-#include "bd.h"
 #include "bta_sys.h"
 #include "bta_ag_api.h"
 #include "bta_ag_co.h"
@@ -411,12 +410,6 @@
     int i, num_active_conn = 0;
     UNUSED(p_data);
 
-#ifdef  _WIN32_WCE
-    /* The BTE RFCOMM automatically removes the connection when closed, but BTW does not */
-    if (p_scb->conn_handle != 0)
-        RFCOMM_RemoveConnection (p_scb->conn_handle);
-#endif
-
     /* reinitialize stuff */
     p_scb->conn_service = 0;
     p_scb->peer_features = 0;
diff --git a/bta/ag/bta_ag_api.c b/bta/ag/bta_ag_api.c
index 5bfa492..dabfd44 100644
--- a/bta/ag/bta_ag_api.c
+++ b/bta/ag/bta_ag_api.c
@@ -25,7 +25,6 @@
  ******************************************************************************/
 
 #include "bta_api.h"
-#include "bd.h"
 #include "bta_sys.h"
 #include "bta_ag_api.h"
 #include "bta_ag_int.h"
diff --git a/bta/ag/bta_ag_cmd.c b/bta/ag/bta_ag_cmd.c
index fd30247..7ea5790 100755
--- a/bta/ag/bta_ag_cmd.c
+++ b/bta/ag/bta_ag_cmd.c
@@ -24,7 +24,6 @@
 #include "bt_target.h"
 #include "bt_types.h"
 #include "gki.h"
-#include "bd.h"
 #include "bta_api.h"
 #include "bta_sys.h"
 #include "bta_ag_api.h"
diff --git a/bta/ag/bta_ag_main.c b/bta/ag/bta_ag_main.c
index 3a32a9d..97faafd 100644
--- a/bta/ag/bta_ag_main.c
+++ b/bta/ag/bta_ag_main.c
@@ -27,7 +27,6 @@
 #include "bta_sys.h"
 #include "bta_ag_co.h"
 #include "bta_ag_int.h"
-#include "bd.h"
 #include "utl.h"
 
 /*****************************************************************************
diff --git a/bta/ag/bta_ag_rfc.c b/bta/ag/bta_ag_rfc.c
index c0a9d3b..9018b75 100644
--- a/bta/ag/bta_ag_rfc.c
+++ b/bta/ag/bta_ag_rfc.c
@@ -33,7 +33,6 @@
 #include "port_api.h"
 #include "rfcdefs.h"
 #include "gki.h"
-#include "bd.h"
 #include "utl.h"
 
 /* Event mask for RfCOMM port callback */
@@ -430,17 +429,5 @@
         }
         */
     }
-
-#ifdef _WIN32_WCE
-    {
-        /* Windows versions of RFCOMM does NOT generate a closed callback when we close */
-        tPORT_CALLBACK *rfc_mgmt_cback = bta_ag_mgmt_cback_tbl[bta_ag_scb_to_idx(p_scb) - 1];
-
-        if (rfc_mgmt_cback)
-        {
-            (rfc_mgmt_cback)(PORT_CLOSED, p_scb->conn_handle);
-        }
-    }
-#endif
 }
 
diff --git a/bta/ag/bta_ag_sco.c b/bta/ag/bta_ag_sco.c
index a698da4..a9f6d37 100644
--- a/bta/ag/bta_ag_sco.c
+++ b/bta/ag/bta_ag_sco.c
@@ -561,8 +561,8 @@
 
 #if (BTM_WBS_INCLUDED == TRUE )
         /* Allow any platform specific pre-SCO set up to take place */
-        bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, BTA_AG_CO_AUD_STATE_SETUP,\
-        esco_codec);
+        bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, SCO_STATE_SETUP,
+                esco_codec);
 
         /* This setting may not be necessary */
         /* To be verified with stable 2049 boards */
@@ -574,7 +574,7 @@
         p_scb->inuse_codec = esco_codec;
 #else
         /* Allow any platform specific pre-SCO set up to take place */
-        bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, BTA_AG_CO_AUD_STATE_SETUP);
+        bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, SCO_STATE_SETUP);
 #endif
 
 #if (BTM_SCO_HCI_INCLUDED == TRUE )
@@ -1458,10 +1458,10 @@
     bta_sys_sco_open(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr);
 
 #if (BTM_WBS_INCLUDED == TRUE)
-    bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, BTA_AG_CO_AUD_STATE_ON,
+    bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, SCO_STATE_ON,
                           p_scb->inuse_codec);
 #else
-    bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, BTA_AG_CO_AUD_STATE_ON);
+    bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, SCO_STATE_ON);
 #endif
 
 #if (BTM_SCO_HCI_INCLUDED == TRUE )
@@ -1521,14 +1521,13 @@
 #endif
     else
     {
+        sco_state_t sco_state = bta_ag_cb.sco.p_xfer_scb ? SCO_STATE_OFF_TRANSFER : SCO_STATE_OFF;
 #if (BTM_WBS_INCLUDED == TRUE)
         /* Indicate if the closing of audio is because of transfer */
-        bta_ag_co_audio_state(handle, p_scb->app_id,(bta_ag_cb.sco.p_xfer_scb)?\
-        BTA_AG_CO_AUD_STATE_OFF_XFER:BTA_AG_CO_AUD_STATE_OFF,p_scb->inuse_codec);
+        bta_ag_co_audio_state(handle, p_scb->app_id, sco_state, p_scb->inuse_codec);
 #else
         /* Indicate if the closing of audio is because of transfer */
-        bta_ag_co_audio_state(handle, p_scb->app_id,(bta_ag_cb.sco.p_xfer_scb)?\
-        BTA_AG_CO_AUD_STATE_OFF_XFER:BTA_AG_CO_AUD_STATE_OFF);
+        bta_ag_co_audio_state(handle, p_scb->app_id, sco_state);
 #endif
         bta_ag_sco_event(p_scb, BTA_AG_SCO_CONN_CLOSE_E);
 
@@ -1608,11 +1607,11 @@
 
 #if (BTM_WBS_INCLUDED == FALSE )
         /* Allow any platform specific pre-SCO set up to take place */
-        bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, BTA_AG_CO_AUD_STATE_SETUP);
+        bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, SCO_STATE_SETUP);
 #else
         /* When HS initiated SCO, it cannot be WBS. */
         /* Allow any platform specific pre-SCO set up to take place */
-        bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, BTA_AG_CO_AUD_STATE_SETUP,
+        bta_ag_co_audio_state(bta_ag_scb_to_idx(p_scb), p_scb->app_id, SCO_STATE_SETUP,
                               BTA_AG_CODEC_CVSD);
 #endif
 
diff --git a/bta/ar/bta_ar.c b/bta/ar/bta_ar.c
index 25b27d3..d58fe7b 100644
--- a/bta/ar/bta_ar.c
+++ b/bta/ar/bta_ar.c
@@ -258,9 +258,7 @@
             bta_ar_cb.tg_registered = mask;
             bta_ar_cb.sdp_tg_handle = SDP_CreateRecord();
             AVRC_AddRecord(service_uuid, service_name, provider_name, categories, bta_ar_cb.sdp_tg_handle);
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&(BTA_EIR_CANNED_UUID_LIST != TRUE)
             bta_sys_add_uuid(service_uuid);
-#endif
         }
         /* only one TG is allowed (first-come, first-served).
          * If sdp_tg_handle is non-0, ignore this request */
@@ -273,9 +271,7 @@
         {
             bta_ar_cb.sdp_ct_handle = SDP_CreateRecord();
             AVRC_AddRecord(service_uuid, service_name, provider_name, categories, bta_ar_cb.sdp_ct_handle);
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&(BTA_EIR_CANNED_UUID_LIST != TRUE)
             bta_sys_add_uuid(service_uuid);
-#endif
         }
         else
         {
@@ -314,9 +310,7 @@
             bta_ar_cb.tg_registered = 0;
             SDP_DeleteRecord(bta_ar_cb.sdp_tg_handle);
             bta_ar_cb.sdp_tg_handle = 0;
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&(BTA_EIR_CANNED_UUID_LIST != TRUE)
             bta_sys_remove_uuid(service_uuid);
-#endif
         }
     }
     else if (service_uuid == UUID_SERVCLASS_AV_REMOTE_CONTROL)
@@ -330,9 +324,7 @@
                 /* no CT is still registered - cleaup */
                 SDP_DeleteRecord(bta_ar_cb.sdp_ct_handle);
                 bta_ar_cb.sdp_ct_handle = 0;
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&(BTA_EIR_CANNED_UUID_LIST != TRUE)
                 bta_sys_remove_uuid(service_uuid);
-#endif
             }
             else
             {
diff --git a/bta/av/bta_av_aact.c b/bta/av/bta_av_aact.c
index f1aa795..fd57523 100644
--- a/bta/av/bta_av_aact.c
+++ b/bta/av/bta_av_aact.c
@@ -27,10 +27,10 @@
 #include "bt_target.h"
 #if defined(BTA_AV_INCLUDED) && (BTA_AV_INCLUDED == TRUE)
 
+#include <assert.h>
 #include <string.h>
 #include "bta_av_int.h"
 #include "avdt_api.h"
-#include "bd.h"
 #include "utl.h"
 #include "l2c_api.h"
 #include "l2cdefs.h"
@@ -57,6 +57,8 @@
 #define BTA_AV_RECONFIG_RETRY       6
 #endif
 
+static void bta_av_st_rc_timer(tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data);
+
 /* state machine states */
 enum
 {
@@ -235,7 +237,7 @@
 **
 ** Returns          void
 ***********************************************/
-UINT8  bta_av_get_scb_handle ( tBTA_AV_SCB *p_scb, UINT8 local_sep )
+static UINT8 bta_av_get_scb_handle(tBTA_AV_SCB *p_scb, UINT8 local_sep)
 {
     UINT8 xx =0;
     for (xx = 0; xx<BTA_AV_MAX_SEPS; xx++)
@@ -257,7 +259,7 @@
 **
 ** Returns          void
 ***********************************************/
-UINT8  bta_av_get_scb_sep_type ( tBTA_AV_SCB *p_scb, UINT8 tavdt_handle)
+static UINT8 bta_av_get_scb_sep_type(tBTA_AV_SCB *p_scb, UINT8 tavdt_handle)
 {
     UINT8 xx =0;
     for (xx = 0; xx<BTA_AV_MAX_SEPS; xx++)
@@ -329,7 +331,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-void bta_av_st_rc_timer(tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data)
+static void bta_av_st_rc_timer(tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data)
 {
     UNUSED(p_data);
 
@@ -425,7 +427,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-void bta_av_proc_stream_evt(UINT8 handle, BD_ADDR bd_addr, UINT8 event, tAVDT_CTRL *p_data, int index)
+static void bta_av_proc_stream_evt(UINT8 handle, BD_ADDR bd_addr, UINT8 event, tAVDT_CTRL *p_data, int index)
 {
     tBTA_AV_STR_MSG     *p_msg;
     UINT16              sec_len = 0;
@@ -2038,7 +2040,7 @@
         policy |= HCI_ENABLE_MASTER_SLAVE_SWITCH;
     bta_sys_set_policy(BTA_ID_AV, policy, p_scb->peer_addr);
 
-    if(p_scb->co_started)
+    if (p_scb->co_started)
     {
         bta_av_stream_chg(p_scb, FALSE);
         p_scb->co_started = FALSE;
@@ -2047,14 +2049,17 @@
         L2CA_SetFlushTimeout(p_scb->peer_addr, L2CAP_DEFAULT_FLUSH_TO);
     }
 
-    /* if q_info.a2d is not empty, drop it now */
-    if(BTA_AV_CHNL_AUDIO == p_scb->chnl)
-    {
-        while((p_buf = (BT_HDR*)GKI_dequeue (&p_scb->q_info.a2d)) != NULL)
-        GKI_freebuf(p_buf);
+    /* if q_info.a2d_list is not empty, drop it now */
+    if (BTA_AV_CHNL_AUDIO == p_scb->chnl) {
+        while (!list_is_empty(p_scb->a2d_list))
+        {
+            p_buf = (BT_HDR *)list_front(p_scb->a2d_list);
+            list_remove(p_scb->a2d_list, p_buf);
+            GKI_freebuf(p_buf);
+        }
 
     /* drop the audio buffers queued in L2CAP */
-        if(p_data && p_data->api_stop.flush)
+        if (p_data && p_data->api_stop.flush)
             L2CA_FlushChannel (p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL);
     }
 
@@ -2189,7 +2194,7 @@
 *******************************************************************************/
 void bta_av_data_path (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data)
 {
-    BT_HDR  *p_buf;
+    BT_HDR  *p_buf = NULL;
     UINT32  data_len;
     UINT32  timestamp;
     BOOLEAN new_buf = FALSE;
@@ -2197,81 +2202,82 @@
     tAVDT_DATA_OPT_MASK     opt;
     UNUSED(p_data);
 
-    if (!p_scb->cong)
+    if (p_scb->cong)
     {
-        /*
-        APPL_TRACE_ERROR("q: %d", p_scb->l2c_bufs);
-        */
-        //Always get the current number of bufs que'd up
-        p_scb->l2c_bufs = (UINT8)L2CA_FlushChannel (p_scb->l2c_cid, L2CAP_FLUSH_CHANS_GET);
+        return;
+    }
 
-        p_buf = (BT_HDR *)GKI_dequeue (&p_scb->q_info.a2d);
-        if(p_buf)
+    /*
+    APPL_TRACE_ERROR("q: %d", p_scb->l2c_bufs);
+    */
+    //Always get the current number of bufs que'd up
+    p_scb->l2c_bufs = (UINT8)L2CA_FlushChannel (p_scb->l2c_cid, L2CAP_FLUSH_CHANS_GET);
+
+    if (!list_is_empty(p_scb->a2d_list)) {
+        p_buf = (BT_HDR *)list_front(p_scb->a2d_list);
+        list_remove(p_scb->a2d_list, p_buf);
+         /* use q_info.a2d data, read the timestamp */
+        timestamp = *(UINT32 *)(p_buf + 1);
+    }
+    else
+    {
+        new_buf = TRUE;
+        /* a2d_list empty, call co_data, dup data to other channels */
+        p_buf = (BT_HDR *)p_scb->p_cos->data(p_scb->codec_type, &data_len,
+                                         &timestamp);
+
+        if (p_buf)
         {
-            /* use q_info.a2d data, read the timestamp */
-            timestamp = *(UINT32 *)(p_buf + 1);
+            /* use the offset area for the time stamp */
+            *(UINT32 *)(p_buf + 1) = timestamp;
+
+            /* dup the data to other channels */
+            bta_av_dup_audio_buf(p_scb, p_buf);
+        }
+    }
+
+    if(p_buf)
+    {
+        if(p_scb->l2c_bufs < (BTA_AV_QUEUE_DATA_CHK_NUM))
+        {
+            /* there's a buffer, just queue it to L2CAP */
+            /*  There's no need to increment it here, it is always read from L2CAP see above */
+            /* p_scb->l2c_bufs++; */
+            /*
+            APPL_TRACE_ERROR("qw: %d", p_scb->l2c_bufs);
+            */
+
+            /* opt is a bit mask, it could have several options set */
+            opt = AVDT_DATA_OPT_NONE;
+            if (p_scb->no_rtp_hdr)
+            {
+                opt |= AVDT_DATA_OPT_NO_RTP;
+            }
+
+            AVDT_WriteReqOpt(p_scb->avdt_handle, p_buf, timestamp, m_pt, opt);
+            p_scb->cong = TRUE;
         }
         else
         {
-            new_buf = TRUE;
-            /* q_info.a2d empty, call co_data, dup data to other channels */
-            p_buf = (BT_HDR *)p_scb->p_cos->data(p_scb->codec_type, &data_len,
-                                             &timestamp);
-
-            if (p_buf)
+            /* there's a buffer, but L2CAP does not seem to be moving data */
+            if(new_buf)
             {
-                /* use the offset area for the time stamp */
-                *(UINT32 *)(p_buf + 1) = timestamp;
-
-                /* dup the data to other channels */
-                bta_av_dup_audio_buf(p_scb, p_buf);
-            }
-        }
-
-        if(p_buf)
-        {
-            if(p_scb->l2c_bufs < (BTA_AV_QUEUE_DATA_CHK_NUM))
-            {
-                /* there's a buffer, just queue it to L2CAP */
-                /*  There's no need to increment it here, it is always read from L2CAP see above */
-                /* p_scb->l2c_bufs++; */
-                /*
-                APPL_TRACE_ERROR("qw: %d", p_scb->l2c_bufs);
-                */
-
-                /* opt is a bit mask, it could have several options set */
-                opt = AVDT_DATA_OPT_NONE;
-                if (p_scb->no_rtp_hdr)
-                {
-                    opt |= AVDT_DATA_OPT_NO_RTP;
-                }
-
-                AVDT_WriteReqOpt(p_scb->avdt_handle, p_buf, timestamp, m_pt, opt);
-                p_scb->cong = TRUE;
+                /* just got this buffer from co_data,
+                 * put it in queue */
+                list_append(p_scb->a2d_list, p_buf);
             }
             else
             {
-                /* there's a buffer, but L2CAP does not seem to be moving data */
-                if(new_buf)
-                {
-                    /* just got this buffer from co_data,
-                     * put it in queue */
-                    GKI_enqueue(&p_scb->q_info.a2d, p_buf);
+                /* just dequeue it from the a2d_list */
+                if (list_length(p_scb->a2d_list) < 3) {
+                    /* put it back to the queue */
+                    list_prepend(p_scb->a2d_list, p_buf);
                 }
                 else
                 {
-                    /* just dequeue it from the q_info.a2d */
-                    if(p_scb->q_info.a2d.count < 3)
-                    {
-                        /* put it back to the queue */
-                        GKI_enqueue_head (&p_scb->q_info.a2d, p_buf);
-                    }
-                    else
-                    {
-                        /* too many buffers in q_info.a2d, drop it. */
-                        bta_av_co_audio_drop(p_scb->hndl);
-                        GKI_freebuf(p_buf);
-                    }
+                    /* too many buffers in a2d_list, drop it. */
+                    bta_av_co_audio_drop(p_scb->hndl);
+                    GKI_freebuf(p_buf);
                 }
             }
         }
diff --git a/bta/av/bta_av_act.c b/bta/av/bta_av_act.c
index dfd3662..89e6fd8 100644
--- a/bta/av/bta_av_act.c
+++ b/bta/av/bta_av_act.c
@@ -30,13 +30,16 @@
 #include "bta_av_api.h"
 #include "bta_av_int.h"
 #include "avdt_api.h"
-#include "bd.h"
 #include "utl.h"
 #include "l2c_api.h"
+#include "osi/include/list.h"
 #if( defined BTA_AR_INCLUDED ) && (BTA_AR_INCLUDED == TRUE)
 #include "bta_ar_api.h"
 #endif
 
+#define LOG_TAG "bt_bta_av"
+#include "osi/include/log.h"
+
 /*****************************************************************************
 **  Constants
 *****************************************************************************/
@@ -500,7 +503,7 @@
             p_scb->rc_handle = p_data->rc_conn_chg.handle;
             APPL_TRACE_DEBUG("bta_av_rc_opened shdl:%d, srch %d", i + 1, p_scb->rc_handle);
             shdl = i+1;
-            APPL_TRACE_ERROR("use_rc:%d", p_scb->use_rc);
+            LOG_INFO("%s allow incoming AVRCP connections:%d", __func__, p_scb->use_rc);
             bta_sys_stop_timer(&p_scb->timer);
             disc = p_scb->hndl;
             break;
@@ -869,7 +872,6 @@
     tAVRC_MSG_VENDOR    *p_vendor = &p_data->rc_msg.msg.vendor;
     BOOLEAN is_inquiry = ((p_data->rc_msg.msg.hdr.ctype == AVRC_CMD_SPEC_INQ) || p_data->rc_msg.msg.hdr.ctype == AVRC_CMD_GEN_INQ);
 #if (AVRC_METADATA_INCLUDED == TRUE)
-    tAVRC_STS   res;
     UINT8       ctype = 0;
     tAVRC_RESPONSE  rc_rsp;
 
@@ -997,7 +999,7 @@
         if (!p_pkt)
         {
             rc_rsp.rsp.opcode = p_data->rc_msg.opcode;
-            res = AVRC_BldResponse (0, &rc_rsp, &p_pkt);
+            AVRC_BldResponse (0, &rc_rsp, &p_pkt);
         }
         if (p_pkt)
             AVRC_MsgReq (p_data->rc_msg.handle, p_data->rc_msg.label, ctype, p_pkt);
@@ -1981,11 +1983,13 @@
             }
             p_cb->conn_audio &= ~mask;
 
-            if (p_scb->q_tag == BTA_AV_Q_TAG_STREAM)
-            {
-            /* make sure no buffers are in q_info.a2d */
-            while((p_buf = (BT_HDR*)GKI_dequeue (&p_scb->q_info.a2d)) != NULL)
-                GKI_freebuf(p_buf);
+            if (p_scb->q_tag == BTA_AV_Q_TAG_STREAM && p_scb->a2d_list) {
+                /* make sure no buffers are in a2d_list */
+                while (!list_is_empty(p_scb->a2d_list)) {
+                    p_buf = (BT_HDR*)list_front(p_scb->a2d_list);
+                    list_remove(p_scb->a2d_list, p_buf);
+                    GKI_freebuf(p_buf);
+                }
             }
 
             /* remove the A2DP SDP record, if no more audio stream is left */
diff --git a/bta/av/bta_av_api.c b/bta/av/bta_av_api.c
index 154855a..ecc05e1 100644
--- a/bta/av/bta_av_api.c
+++ b/bta/av/bta_av_api.c
@@ -28,7 +28,6 @@
 #if defined(BTA_AV_INCLUDED) && (BTA_AV_INCLUDED == TRUE)
 
 #include "bta_api.h"
-#include "bd.h"
 #include "bta_sys.h"
 #include "bta_av_api.h"
 #include "bta_av_int.h"
diff --git a/bta/av/bta_av_cfg.c b/bta/av/bta_av_cfg.c
index 48a67f0..d3776f4 100644
--- a/bta/av/bta_av_cfg.c
+++ b/bta/av/bta_av_cfg.c
@@ -48,7 +48,6 @@
 **	3. GetCapabilities supported event_ids list
 **	4. GetCapabilities supported event_ids count
 */
-#ifdef ANDROID_APP_INCLUDED
 /* Flushing partial avdtp packets can cause some headsets to disconnect the link
    if receiving partial a2dp frames */
 const UINT16  bta_av_audio_flush_to[] = {
@@ -82,8 +81,6 @@
 #define BTA_AV_NUM_RC_EVT_IDS   (sizeof(bta_av_meta_caps_evt_ids) / sizeof(bta_av_meta_caps_evt_ids[0]))
 #endif /* BTA_AV_NUM_RC_EVT_IDS */
 
-#endif /* ANDROID_APP_INCLUDED */
-
 /* the MTU for the AVRCP browsing channel */
 #ifndef BTA_AV_MAX_RC_BR_MTU
 #define BTA_AV_MAX_RC_BR_MTU      1008
diff --git a/bta/av/bta_av_int.h b/bta/av/bta_av_int.h
index 5deed76..6764e94 100644
--- a/bta/av/bta_av_int.h
+++ b/bta/av/bta_av_int.h
@@ -29,6 +29,7 @@
 #include "bta_av_api.h"
 #include "avdt_api.h"
 #include "bta_av_co.h"
+#include "list.h"
 
 #define BTA_AV_DEBUG TRUE
 /*****************************************************************************
@@ -437,7 +438,6 @@
 
 typedef union
 {
-    BUFFER_Q            a2d;            /* used for audio channels only */
     tBTA_AV_VF_INFO     vdp;            /* used for video channels only */
     tBTA_AV_API_OPEN    open;           /* used only before open and role switch
                                            is needed on another AV channel */
@@ -470,6 +470,7 @@
     tSDP_DISCOVERY_DB   *p_disc_db;     /* pointer to discovery database */
     tBTA_AV_SEP         seps[BTA_AV_MAX_SEPS];
     tAVDT_CFG           *p_cap;         /* buffer used for get capabilities */
+    list_t              *a2d_list;      /* used for audio channels only */
     tBTA_AV_Q_INFO      q_info;
     tAVDT_SEP_INFO      sep_info[BTA_AV_NUM_SEPS];      /* stream discovery results */
     tAVDT_CFG           cfg;            /* local SEP configuration */
@@ -625,7 +626,6 @@
 extern UINT16 bta_av_chk_mtu(tBTA_AV_SCB *p_scb, UINT16 mtu);
 extern void bta_av_conn_cback(UINT8 handle, BD_ADDR bd_addr, UINT8 event, tAVDT_CTRL *p_data);
 extern UINT8 bta_av_rc_create(tBTA_AV_CB *p_cb, UINT8 role, UINT8 shdl, UINT8 lidx);
-extern void bta_av_proc_stream_evt(UINT8 handle, BD_ADDR bd_addr, UINT8 event, tAVDT_CTRL *p_data, int index);
 extern void bta_av_stream_chg(tBTA_AV_SCB *p_scb, BOOLEAN started);
 extern BOOLEAN bta_av_is_scb_opening (tBTA_AV_SCB *p_scb);
 extern BOOLEAN bta_av_is_scb_incoming (tBTA_AV_SCB *p_scb);
@@ -682,7 +682,6 @@
 extern void bta_av_security_req (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data);
 extern void bta_av_security_rsp (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data);
 extern void bta_av_setconfig_rsp (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data);
-extern void bta_av_st_rc_timer(tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data);
 extern void bta_av_str_opened (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data);
 extern void bta_av_security_ind (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data);
 extern void bta_av_security_cfm (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data);
diff --git a/bta/av/bta_av_main.c b/bta/av/bta_av_main.c
index a8544c4..849dd1e 100644
--- a/bta/av/bta_av_main.c
+++ b/bta/av/bta_av_main.c
@@ -22,13 +22,15 @@
  *
  ******************************************************************************/
 
-#include "bt_target.h"
-#if defined(BTA_AV_INCLUDED) && (BTA_AV_INCLUDED == TRUE)
-
+#include <assert.h>
 #include <string.h>
+
+#include "bt_target.h"
+#include "osi/include/log.h"
+
+#if defined(BTA_AV_INCLUDED) && (BTA_AV_INCLUDED == TRUE)
 #include "bta_av_int.h"
 #include "utl.h"
-#include "bd.h"
 #include "l2c_api.h"
 #include "l2cdefs.h"
 #include "bta_av_co.h"
@@ -384,6 +386,7 @@
                     p_ret->chnl = chnl;
                     p_ret->hndl = (tBTA_AV_HNDL)((xx + 1) | chnl);
                     p_ret->hdi  = xx;
+                    p_ret->a2d_list = list_new(NULL);
                     bta_av_cb.p_scb[xx] = p_ret;
                 }
                 break;
@@ -394,6 +397,25 @@
 }
 
 /*******************************************************************************
+**
+** Function         bta_av_free_scb
+**
+** Description      free stream control block,
+**
+**
+** Returns          void
+**
+*******************************************************************************/
+static void bta_av_free_scb(tBTA_AV_SCB *p_scb)
+{
+    // NOTE(google) This free currently is not called
+    assert(p_scb != NULL);
+
+    list_free(p_scb->a2d_list);
+    GKI_freebuf(p_scb);
+}
+
+/*******************************************************************************
 *******************************************************************************/
 void bta_av_conn_cback(UINT8 handle, BD_ADDR bd_addr, UINT8 event, tAVDT_CTRL *p_data)
 {
@@ -1097,11 +1119,12 @@
 {
     UINT8 role;
     BOOLEAN is_ok = TRUE;
-    BOOLEAN need_timer = FALSE;
 
     if (BTM_GetRole(p_scb->peer_addr, &role) == BTM_SUCCESS)
     {
-        APPL_TRACE_ERROR("bta_av_link_role_ok hndl:x%x role:%d, conn_audio:x%x, bits:%d, features:x%x", p_scb->hndl, role, bta_av_cb.conn_audio, bits, bta_av_cb.features);
+        LOG_INFO("%s hndl:x%x role:%d conn_audio:x%x bits:%d features:x%x",
+                __func__, p_scb->hndl, role, bta_av_cb.conn_audio, bits,
+                bta_av_cb.features);
         if (BTM_ROLE_MASTER != role && (A2D_BitsSet(bta_av_cb.conn_audio) > bits || (bta_av_cb.features & BTA_AV_FEAT_MASTER)))
         {
             if (bta_av_cb.features & BTA_AV_FEAT_MASTER)
@@ -1110,7 +1133,6 @@
             if (BTM_CMD_STARTED != BTM_SwitchRole(p_scb->peer_addr, BTM_ROLE_MASTER, NULL))
             {
                 /* can not switch role on SCB - start the timer on SCB */
-                need_timer = TRUE;
             }
             is_ok = FALSE;
             p_scb->wait |= BTA_AV_WAIT_ROLE_SW_RES_START;
@@ -1179,7 +1201,6 @@
 void bta_av_dup_audio_buf(tBTA_AV_SCB *p_scb, BT_HDR *p_buf)
 {
     tBTA_AV_SCB *p_scbi;
-    BUFFER_Q    *pq;
     int     i;
     UINT16  size, copy_size;
     BT_HDR *p_new;
@@ -1204,12 +1225,13 @@
                 if(p_new)
                 {
                     memcpy(p_new, p_buf, copy_size);
-                    pq = &p_scbi->q_info.a2d;
-                    GKI_enqueue(pq, p_new);
-                    if(pq->count > p_bta_av_cfg->audio_mqs)
-                    {
+                    list_append(p_scbi->a2d_list, p_new);
+                    if (list_length(p_scbi->a2d_list) >  p_bta_av_cfg->audio_mqs) {
+                        // Drop the oldest packet
                         bta_av_co_audio_drop(p_scbi->hndl);
-                        GKI_freebuf(GKI_dequeue(pq));
+                        BT_HDR *p_buf = list_front(p_scbi->a2d_list);
+                        list_remove(p_scbi->a2d_list, p_buf);
+                        GKI_freebuf(p_buf);
                     }
                 }
             }
diff --git a/bta/dm/bta_dm_act.c b/bta/dm/bta_dm_act.c
index 7213866..ee3ba8f 100644
--- a/bta/dm/bta_dm_act.c
+++ b/bta/dm/bta_dm_act.c
@@ -26,7 +26,6 @@
 #include "bt_target.h"
 #include "bt_types.h"
 #include "gki.h"
-#include "bd.h"
 #include "bta_sys.h"
 #include "bta_api.h"
 #include "bta_dm_int.h"
@@ -36,11 +35,13 @@
 #include "btu.h"
 #include "sdp_api.h"
 #include "l2c_api.h"
-#include "wbt_api.h"
 #include "utl.h"
 #include "gap_api.h"    /* For GAP_BleReadPeerPrefConnParams */
 #include <string.h>
 
+#define LOG_TAG "bt_bta_dm"
+#include "osi/include/log.h"
+
 #if (GAP_INCLUDED == TRUE)
 #include "gap_api.h"
 #endif
@@ -54,34 +55,22 @@
 static void bta_dm_sdp_callback (UINT16 sdp_status);
 static UINT8 bta_dm_authorize_cback (BD_ADDR bd_addr, DEV_CLASS dev_class, BD_NAME bd_name, UINT8 *service_name, UINT8 service_id, BOOLEAN is_originator);
 static UINT8 bta_dm_pin_cback (BD_ADDR bd_addr, DEV_CLASS dev_class, BD_NAME bd_name);
-static UINT8 bta_dm_link_key_request_cback (BD_ADDR bd_addr, LINK_KEY key);
 static UINT8 bta_dm_new_link_key_cback(BD_ADDR bd_addr, DEV_CLASS dev_class, BD_NAME bd_name, LINK_KEY key, UINT8 key_type);
 static UINT8 bta_dm_authentication_complete_cback(BD_ADDR bd_addr, DEV_CLASS dev_class,BD_NAME bd_name, int result);
 static void bta_dm_local_name_cback(BD_ADDR bd_addr);
 static BOOLEAN bta_dm_check_av(UINT16 event);
-#if (BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
 static void bta_dm_bl_change_cback (tBTM_BL_EVENT_DATA *p_data);
-#else
-static void bta_dm_acl_change_cback (BD_ADDR p_bda, DEV_CLASS p_dc, BD_NAME p_bdn, UINT8 *features, BOOLEAN is_new);
-#endif
 static void bta_dm_policy_cback(tBTA_SYS_CONN_STATUS status, UINT8 id, UINT8 app_id, BD_ADDR peer_addr);
 
 /* Extended Inquiry Response */
 static UINT8 bta_dm_sp_cback (tBTM_SP_EVT event, tBTM_SP_EVT_DATA *p_data);
 
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
 static void bta_dm_set_eir (char *local_name);
-#endif /* BTM_EIR_SERVER_INCLUDED */
 
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
 static void bta_dm_eir_search_services( tBTM_INQ_RESULTS  *p_result,
                                         tBTA_SERVICE_MASK *p_services_to_search,
                                         tBTA_SERVICE_MASK *p_services_found);
-#endif /* BTM_EIR_CLIENT_INCLUDED */
 
-static void bta_dm_rssi_cback (tBTM_RSSI_RESULTS *p_result);
-static void bta_dm_signal_strength_timer_cback (TIMER_LIST_ENT *p_tle);
-static void bta_dm_link_quality_cback (tBTM_LINK_QUALITY_RESULTS *p_result);
 static void bta_dm_search_timer_cback (TIMER_LIST_ENT *p_tle);
 static void bta_dm_disable_timer_cback (TIMER_LIST_ENT *p_tle);
 static void bta_dm_disable_conn_down_timer_cback (TIMER_LIST_ENT *p_tle);
@@ -212,9 +201,7 @@
     &bta_dm_authorize_cback,
     &bta_dm_pin_cback,
     &bta_dm_new_link_key_cback,
-    &bta_dm_link_key_request_cback,
     &bta_dm_authentication_complete_cback,
-    NULL,
     &bta_dm_bond_cancel_complete_cback,
 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
     &bta_dm_sp_cback
@@ -382,11 +369,7 @@
         BTM_WritePageTimeout(bta_dm_cfg.page_timeout);
         bta_dm_cb.cur_policy = bta_dm_cfg.policy_settings;
         BTM_SetDefaultLinkPolicy(bta_dm_cb.cur_policy);
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
         BTM_RegBusyLevelNotif (bta_dm_bl_change_cback, NULL, BTM_BL_UPDATE_MASK|BTM_BL_ROLE_CHG_MASK);
-#else
-        BTM_AclRegisterForChanges(bta_dm_acl_change_cback);
-#endif
 
 #if BLE_VND_INCLUDED == TRUE
         BTM_BleReadControllerFeatures (bta_dm_ctrl_features_rd_cmpl_cback);
@@ -541,9 +524,7 @@
 {
 
     BTM_SetLocalDeviceName((char*)p_data->set_name.name);
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
     bta_dm_set_eir ((char*)p_data->set_name.name);
-#endif
 }
 
 /*******************************************************************************
@@ -599,64 +580,6 @@
 
 }
 
-
-/*******************************************************************************
-**
-** Function         bta_dm_set_afhchannels
-**
-** Description      This function sets the AFH first and
-**                  last disable channel, so channels within
-**                  that range are disabled.
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_dm_set_afhchannels (tBTA_DM_MSG *p_data)
-{
-    BTM_SetAfhChannels(p_data->set_afhchannels.first,p_data->set_afhchannels.last);
-
-}
-
-
-/*******************************************************************************
-**
-** Function         bta_dm_vendor_spec_command
-**
-** Description      Send a vendor specific command to the controller
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_dm_vendor_spec_command (tBTA_DM_MSG *p_data)
-{
-    tBTM_STATUS status;
-
-    status = BTM_VendorSpecificCommand(p_data->vendor_command.opcode,p_data->vendor_command.param_len,p_data->vendor_command.p_param_buf, p_data->vendor_command.p_cback);
-
-}
-
-
-/*******************************************************************************
-**
-** Function         bta_dm_tx_inqpower
-**
-** Description      write inquiry tx power.
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_dm_tx_inqpower(tBTA_DM_MSG *p_data)
-{
-    if (BTM_WriteInquiryTxPower (p_data->tx_inq_pwr.tx_power) == BTM_ILLEGAL_VALUE)
-    {
-        APPL_TRACE_ERROR("Invalid Inquiry Tx Power: %d", p_data->tx_inq_pwr.tx_power);
-    }
-    return;
-}
-
 /*******************************************************************************
 **
 ** Function         bta_dm_remove_device
@@ -946,46 +869,6 @@
 
 /*******************************************************************************
 **
-** Function         bta_dm_link_policy
-**
-** Description      remove/set link policy mask.
-**                  wake the link, is sniff/park is removed
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_dm_link_policy (tBTA_DM_MSG *p_data)
-{
-    tBTA_DM_PEER_DEVICE *p_dev;
-
-    p_dev = bta_dm_find_peer_device(p_data->link_policy.bd_addr);
-    if(!p_dev)
-        return;
-
-    APPL_TRACE_DEBUG(" bta_dm_link_policy set:%d, policy:0x%x",
-        p_data->link_policy.set, p_data->link_policy.policy_mask);
-    if(p_data->link_policy.set)
-    {
-        /* restore the default link policy */
-        p_dev->link_policy |= p_data->link_policy.policy_mask;
-        BTM_SetLinkPolicy(p_dev->peer_bdaddr, &(p_dev->link_policy));
-    }
-    else
-    {
-        /* clear the policy from the default link policy */
-        p_dev->link_policy &= (~p_data->link_policy.policy_mask);
-        BTM_SetLinkPolicy(p_dev->peer_bdaddr, &(p_dev->link_policy));
-
-        if(p_data->link_policy.policy_mask & (HCI_ENABLE_SNIFF_MODE | HCI_ENABLE_PARK_MODE))
-        {
-            /* if clearing sniff/park, wake the link */
-            bta_dm_pm_active(p_dev->peer_bdaddr);
-        }
-    }
-}
-
-/*******************************************************************************
-**
 ** Function         bta_dm_policy_cback
 **
 ** Description      process the link policy changes
@@ -1048,56 +931,6 @@
     }
 }
 
-
-/*******************************************************************************
-**
-** Function         bta_dm_auth_reply
-**
-** Description      Send the authorization reply to a request from BTM
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_dm_auth_reply (tBTA_DM_MSG *p_data)
-{
-
-    UINT32  trusted_mask[BTM_SEC_SERVICE_ARRAY_SIZE];
-    UINT8   btm_mask_index = 0;
-    UINT32  * current_trusted_mask;
-
-    current_trusted_mask = BTM_ReadTrustedMask(p_data->auth_reply.bd_addr);
-
-    if(current_trusted_mask)
-    {
-        memcpy(trusted_mask, current_trusted_mask, sizeof(trusted_mask));
-    }
-    else
-    {
-        memset(trusted_mask, 0, sizeof(trusted_mask));
-    }
-
-    if(p_data->auth_reply.response != BTA_DM_NOT_AUTH)
-    {
-        if(p_data->auth_reply.response == BTA_DM_AUTH_PERM)
-        {
-            if(p_data->auth_reply.service < BTA_MAX_SERVICE_ID)
-            {
-                /* convert BTA service id to BTM mask */
-                btm_mask_index =  bta_service_id_to_btm_srv_id_lkup_tbl[p_data->auth_reply.service] / 32;
-                trusted_mask[btm_mask_index] |= (UINT32)(1 << (bta_service_id_to_btm_srv_id_lkup_tbl[p_data->auth_reply.service] - (UINT32)(btm_mask_index * 32)));
-
-            }
-        }
-        BTM_DeviceAuthorized (p_data->auth_reply.bd_addr, BTM_SUCCESS,trusted_mask);
-    }
-    else
-    {
-        BTM_DeviceAuthorized (p_data->auth_reply.bd_addr, BTM_NOT_AUTHORIZED,trusted_mask);
-    }
-
-}
-
 /*******************************************************************************
 **
 ** Function         bta_dm_confirm
@@ -1119,22 +952,6 @@
 
 /*******************************************************************************
 **
-** Function         bta_dm_passkey_cancel
-**
-** Description      Send the passkey cancel from SP initiator by sending a negative
-**                  passkey request replyreply.
-** Returns          void
-**
-*******************************************************************************/
-#if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
-void bta_dm_passkey_cancel(tBTA_DM_MSG *p_data)
-{
-    BTM_PasskeyReqReply(BTM_NOT_AUTHORIZED, p_data->passkey_cancel.bd_addr, 0);
-}
-#endif
-
-/*******************************************************************************
-**
 ** Function         bta_dm_loc_oob
 **
 ** Description      Retrieve the OOB data from the local LM
@@ -1322,7 +1139,7 @@
 #if BLE_INCLUDED == TRUE && BTA_GATT_INCLUDED == TRUE
     UINT16 len = (UINT16)(sizeof(tBT_UUID) * p_data->discover.num_uuid);
 #endif
-    APPL_TRACE_EVENT("bta_dm_discover services_to_search=0x%04X, sdp_search=%d",
+    APPL_TRACE_EVENT("%s services_to_search=0x%04X, sdp_search=%d", __func__,
                       p_data->discover.services, p_data->discover.sdp_search);
 
     /* save the search condition */
@@ -1659,7 +1476,6 @@
 
     tSDP_DISC_REC   *p_sdp_rec = NULL;
     tBTA_DM_MSG     *p_msg;
-    BOOLEAN          service_found = FALSE;
     BOOLEAN          scn_found = FALSE;
     UINT16           service = 0xFFFF;
     tSDP_PROTOCOL_ELEM  pe;
@@ -1681,7 +1497,6 @@
         do
         {
 
-            service_found = FALSE;
             p_sdp_rec = NULL;
             if( bta_dm_search_cb.service_index == (BTA_USER_SERVICE_ID+1) )
             {
@@ -1744,23 +1559,7 @@
                     bta_dm_search_cb.services != BTA_ALL_SERVICE_MASK) ||
                     (p_sdp_rec  != NULL))
             {
-                /* If Plug and Play service record, check to see if Broadcom stack */
-                if (service == UUID_SERVCLASS_PNP_INFORMATION)
-                {
-                    if (p_sdp_rec)
-                    {
-                        if (SDP_FindAttributeInRec (p_sdp_rec, ATTR_ID_EXT_BRCM_VERSION))
-                        {
-                            service_found = TRUE;
-                        }
-                    }
-                }
-                else
-                {
-                    service_found = TRUE;
-                }
-
-                if (service_found)
+                if (service != UUID_SERVCLASS_PNP_INFORMATION)
                 {
                     UINT16 tmp_svc = 0xFFFF;
                     bta_dm_search_cb.services_found |=
@@ -2009,10 +1808,8 @@
     /* if searching did not initiate to create link */
     if(!bta_dm_search_cb.wait_disc )
     {
-#if ( BTM_EIR_CLIENT_INCLUDED == TRUE )
         /* if service searching is done with EIR, don't search next device */
         if( bta_dm_search_cb.p_btm_inq_info )
-#endif
         bta_dm_discover_next_device();
     }
     else
@@ -2216,6 +2013,7 @@
 {
 
     tSDP_UUID    uuid;
+    UINT16       num_attrs = 1;
     tBTA_DM_MSG *p_msg;
 
     memset (&uuid, 0, sizeof(tSDP_UUID));
@@ -2231,7 +2029,7 @@
                 /* try to search all services by search based on L2CAP UUID */
                 if(bta_dm_search_cb.services == BTA_ALL_SERVICE_MASK )
                 {
-                    APPL_TRACE_ERROR("services_to_search = %08x",bta_dm_search_cb.services_to_search);
+                    LOG_INFO("%s services_to_search=%08x", __func__, bta_dm_search_cb.services_to_search);
                     if (bta_dm_search_cb.services_to_search & BTA_RES_SERVICE_MASK)
                     {
                         uuid.uu.uuid16 = bta_service_id_to_uuid_lkup_tbl[0];
@@ -2278,26 +2076,16 @@
                 }
 
                 if (uuid.len == 0)
-                uuid.len = LEN_UUID_16;
-
-#if 0
-                if (uuid.uu.uuid16 == UUID_SERVCLASS_PNP_INFORMATION)
-                {
-                    num_attrs = 2;
-                }
-#endif
+                    uuid.len = LEN_UUID_16;
 
                 if (bta_dm_search_cb.service_index == BTA_USER_SERVICE_ID)
                 {
                     memcpy(&uuid, &bta_dm_search_cb.uuid, sizeof(tSDP_UUID));
                 }
 
-
-                APPL_TRACE_ERROR("****************search UUID = %04x***********", uuid.uu.uuid16);
-                //SDP_InitDiscoveryDb (bta_dm_search_cb.p_sdp_db, BTA_DM_SDP_DB_SIZE, 1, &uuid, num_attrs, attr_list);
+                LOG_INFO("%s search UUID = %04x", __func__, uuid.uu.uuid16);
                 SDP_InitDiscoveryDb (bta_dm_search_cb.p_sdp_db, BTA_DM_SDP_DB_SIZE, 1, &uuid, 0, NULL);
 
-
                 memset(g_disc_raw_data_buf, 0, sizeof(g_disc_raw_data_buf));
                 bta_dm_search_cb.p_sdp_db->raw_data = g_disc_raw_data_buf;
 
@@ -2460,7 +2248,6 @@
 #if BLE_INCLUDED == TRUE && BTA_GATT_INCLUDED == TRUE
         bta_dm_search_cb.uuid_to_search     = bta_dm_search_cb.num_uuid;
 #endif
-#if ( BTM_EIR_CLIENT_INCLUDED == TRUE )
         if ((bta_dm_search_cb.p_btm_inq_info != NULL) &&
 			bta_dm_search_cb.services != BTA_USER_SERVICE_MASK
             &&(bta_dm_search_cb.sdp_search == FALSE))
@@ -2473,7 +2260,6 @@
 
         /* if seaching with EIR is not completed */
         if(bta_dm_search_cb.services_to_search)
-#endif
         {
             /* check whether connection already exists to the device
                if connection exists, we don't have to wait for ACL
@@ -2906,34 +2692,6 @@
     return BTM_CMD_STARTED;
 }
 
-
-
-/*******************************************************************************
-**
-** Function         bta_dm_link_key_request_cback
-**
-** Description      Callback requesting linkkey
-**
-** Returns          void
-**
-*******************************************************************************/
-static UINT8  bta_dm_link_key_request_cback (BD_ADDR bd_addr, LINK_KEY key)
-{
-    /* Application passes all link key to
-    BTM during initialization using add_device
-    API. If BTM doesn't have the link key in it's
-    data base, that's because application doesn't
-    it */
-    UNUSED(bd_addr);
-    UNUSED(key);
-
-    return BTM_NOT_AUTHORIZED;
-}
-
-
-
-
-
 /*******************************************************************************
 **
 ** Function         bta_dm_new_link_key_cback
@@ -3199,7 +2957,6 @@
     tBTA_DM_SEC sec_event;
     UNUSED(p_name);
 
-    BTM_GetLocalDeviceAddr(sec_event.enable.bd_addr);
     sec_event.enable.status = BTA_SUCCESS;
 
     if(bta_dm_cb.p_sec_cback)
@@ -3209,73 +2966,6 @@
 
 /*******************************************************************************
 **
-** Function         bta_dm_signal_strength
-**
-** Description      Callback from btm after local bdaddr is read
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_dm_signal_strength(tBTA_DM_MSG *p_data)
-{
-
-    if(p_data->sig_strength.start)
-    {
-        bta_dm_cb.signal_strength_mask = p_data->sig_strength.mask;
-        bta_dm_cb.signal_strength_period = p_data->sig_strength.period;
-        bta_dm_signal_strength_timer_cback(NULL);
-    }
-    else
-    {
-        bta_sys_stop_timer(&bta_dm_cb.signal_strength_timer);
-    }
-
-}
-/*******************************************************************************
-**
-** Function         bta_dm_signal_strength_timer_cback
-**
-** Description      Periodic timer callback to read signal strength
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-static void bta_dm_signal_strength_timer_cback (TIMER_LIST_ENT *p_tle)
-{
-    UNUSED(p_tle);
-    UINT8 i;
-
-    if(bta_dm_cb.signal_strength_mask & BTA_SIG_STRENGTH_RSSI_MASK)
-    {
-        for(i=0; i<bta_dm_cb.device_list.count; i++)
-        {
-            BTM_ReadRSSI (bta_dm_cb.device_list.peer_device[i].peer_bdaddr, (tBTM_CMPL_CB *)bta_dm_rssi_cback);
-
-        }
-    }
-    if(bta_dm_cb.signal_strength_mask & BTA_SIG_STRENGTH_LINK_QUALITY_MASK)
-    {
-
-        for(i=0; i<bta_dm_cb.device_list.count; i++)
-        {
-            BTM_ReadLinkQuality (bta_dm_cb.device_list.peer_device[i].peer_bdaddr, (tBTM_CMPL_CB *)bta_dm_link_quality_cback);
-        }
-
-    }
-
-    if(bta_dm_cb.signal_strength_period)
-    {
-        bta_dm_cb.signal_strength_timer.p_cback = (TIMER_CBACK*)&bta_dm_signal_strength_timer_cback;
-        bta_sys_start_timer(&bta_dm_cb.signal_strength_timer, 0, (UINT32)1000*bta_dm_cb.signal_strength_period);
-    }
-}
-
-
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
-/*******************************************************************************
-**
 ** Function         bta_dm_bl_change_cback
 **
 ** Description      Callback from btm when acl connection goes up or down
@@ -3330,47 +3020,6 @@
     }
 
 }
-#else
-
-/*******************************************************************************
-**
-** Function         bta_dm_acl_change_cback
-**
-** Description      Callback from btm when acl connection goes up or down
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-static void bta_dm_acl_change_cback (BD_ADDR p_bda, DEV_CLASS p_dc, BD_NAME p_bdn,
-                                     UINT8 *features, BOOLEAN is_new,UINT16 handle,
-                                     tBT_TRANSPORT transport)
-{
-
-    tBTA_DM_ACL_CHANGE * p_msg;
-
-    if ((p_msg = (tBTA_DM_ACL_CHANGE *) GKI_getbuf(sizeof(tBTA_DM_ACL_CHANGE))) != NULL)
-    {
-        bdcpy (p_msg->bd_addr, p_bda);
-        p_msg->is_new = is_new;
-#if BLE_INCLUDED == TRUE
-        p_msg->handle   = handle;
-        p_msg->transport = transport;
-#endif
-        /* This is collision case */
-        if (features != NULL)
-        {
-            if ((features[0] == 0xFF) && !is_new)
-                p_msg->event = BTM_BL_COLLISION_EVT;
-        }
-
-        p_msg->hdr.event = BTA_DM_ACL_CHANGE_EVT;
-        bta_sys_sendmsg(p_msg);
-
-    }
-
-}
-#endif
 /*******************************************************************************
 **
 ** Function         bta_dm_rs_cback
@@ -3467,7 +3116,6 @@
     BOOLEAN         need_policy_change = FALSE;
     BOOLEAN         issue_unpair_cb = FALSE;
 
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     tBTA_DM_PEER_DEVICE *p_dev;
     memset(&conn, 0, sizeof(tBTA_DM_SEC));
 
@@ -3525,7 +3173,6 @@
         }
         return;
     }
-#endif
 
     /* Collision report from Stack: Notify profiles */
     if (p_data->acl_change.event == BTM_BL_COLLISION_EVT)
@@ -3701,59 +3348,6 @@
 
 /*******************************************************************************
 **
-** Function         bta_dm_rssi_cback
-**
-** Description      Callback from btm with rssi values
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-static void bta_dm_rssi_cback (tBTM_RSSI_RESULTS *p_result)
-{
-    tBTA_DM_SEC sec_event;
-
-    if(p_result->status == BTM_SUCCESS)
-    {
-
-        bdcpy(sec_event.sig_strength.bd_addr, p_result->rem_bda);
-        sec_event.sig_strength.mask = BTA_SIG_STRENGTH_RSSI_MASK;
-        sec_event.sig_strength.rssi_value = p_result->rssi;
-        if( bta_dm_cb.p_sec_cback!= NULL )
-            bta_dm_cb.p_sec_cback(BTA_DM_SIG_STRENGTH_EVT, &sec_event);
-
-    }
-}
-
-/*******************************************************************************
-**
-** Function         bta_dm_link_quality_cback
-**
-** Description      Callback from btm with link quality value
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-static void bta_dm_link_quality_cback (tBTM_LINK_QUALITY_RESULTS *p_result)
-{
-
-    tBTA_DM_SEC sec_event;
-
-    if(p_result->status == BTM_SUCCESS)
-    {
-
-        bdcpy(sec_event.sig_strength.bd_addr, p_result->rem_bda);
-        sec_event.sig_strength.mask = BTA_SIG_STRENGTH_LINK_QUALITY_MASK;
-        sec_event.sig_strength.link_quality_value = p_result->link_quality;
-        if( bta_dm_cb.p_sec_cback!= NULL )
-            bta_dm_cb.p_sec_cback(BTA_DM_SIG_STRENGTH_EVT, &sec_event);
-
-    }
-}
-
-/*******************************************************************************
-**
 ** Function         bta_dm_rm_cback
 **
 ** Description      Role management callback from sys
@@ -4068,100 +3662,6 @@
     }
 }
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )
-    #if ( BTA_EIR_CANNED_UUID_LIST != TRUE )&&(BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
-/*******************************************************************************
-**
-** Function         bta_dm_update_eir_uuid
-**
-** Description
-**
-**
-*******************************************************************************/
-void bta_dm_update_eir_uuid (tBTA_DM_MSG *p_data)
-{
-    tBTA_DM_API_UPDATE_EIR_UUID *p_msg = (tBTA_DM_API_UPDATE_EIR_UUID *)p_data;
-    UINT8 xx;
-    UINT8 empty_slot = BTA_EIR_SERVER_NUM_CUSTOM_UUID;
-    UINT8 match_slot = BTA_EIR_SERVER_NUM_CUSTOM_UUID;
-
-    for (xx = 0; xx < BTA_EIR_SERVER_NUM_CUSTOM_UUID; xx++)
-    {
-        if (bta_dm_cb.custom_uuid[xx].len == 0)
-        {
-            if (empty_slot == BTA_EIR_SERVER_NUM_CUSTOM_UUID)
-                empty_slot = xx;
-        }
-        else if (match_slot == BTA_EIR_SERVER_NUM_CUSTOM_UUID)
-        {
-            if (!memcmp (bta_dm_cb.custom_uuid[xx].uu.uuid128, p_msg->uuid.uu.uuid128, p_msg->uuid.len))
-            {
-                match_slot = xx;;
-            }
-        }
-    }
-
-    if (p_msg->is_add)
-    {
-        if (match_slot == BTA_EIR_SERVER_NUM_CUSTOM_UUID)
-        {
-            if (empty_slot == BTA_EIR_SERVER_NUM_CUSTOM_UUID)
-            {
-                APPL_TRACE_ERROR("No space to add UUID for EIR");
-                return;
-            }
-            else
-            {
-                memcpy (&(bta_dm_cb.custom_uuid[empty_slot]), &(p_msg->uuid), sizeof(tBT_UUID));
-            }
-        }
-        else
-        {
-            APPL_TRACE_ERROR("UUID is already added for EIR");
-            return;
-        }
-    }
-    else
-    {
-        if (match_slot == BTA_EIR_SERVER_NUM_CUSTOM_UUID)
-        {
-            APPL_TRACE_ERROR("UUID is not found for EIR");
-            return;
-        }
-        else
-        {
-            memset (&(bta_dm_cb.custom_uuid[match_slot]), 0, sizeof(tBT_UUID));
-        }
-    }
-
-    bta_dm_set_eir (NULL);
-}
-    #endif
-
-/*******************************************************************************
-**
-** Function         bta_dm_set_eir_config
-**
-** Description
-**
-**
-*******************************************************************************/
-void bta_dm_set_eir_config (tBTA_DM_MSG *p_data)
-{
-    if (p_data->set_eir_cfg.p_eir_cfg)
-    {
-        /* User defined config */
-        p_bta_dm_eir_cfg = p_data->set_eir_cfg.p_eir_cfg;
-    }
-    else
-    {
-        /* Back to default config */
-        p_bta_dm_eir_cfg = (tBTA_DM_EIR_CONF*)&bta_dm_eir_cfg;
-    }
-
-    bta_dm_set_eir (NULL);
-}
-
 /*******************************************************************************
 **
 ** Function         bta_dm_set_eir
@@ -4181,13 +3681,13 @@
     UINT8    max_num_uuid;
 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
     UINT8    custom_uuid_idx;
-#endif
-#endif
+#endif  // BTA_EIR_SERVER_NUM_CUSTOM_UUID
+#endif  // BTA_EIR_CANNED_UUID_LIST
 #if (BTM_EIR_DEFAULT_FEC_REQUIRED == FALSE)
     UINT8    free_eir_length = HCI_EXT_INQ_RESPONSE_LEN;
-#else
+#else  // BTM_EIR_DEFAULT_FEC_REQUIRED
     UINT8    free_eir_length = HCI_DM5_PACKET_SIZE;
-#endif
+#endif  // BTM_EIR_DEFAULT_FEC_REQUIRED 
     UINT8    num_uuid;
     UINT8    data_type;
     UINT8    local_name_len;
@@ -4209,7 +3709,7 @@
             APPL_TRACE_ERROR("Fail to read local device name for EIR");
         }
     }
-#endif
+#endif  // BTA_EIR_CANNED_UUID_LIST
 
     /* Allocate a buffer to hold HCI command */
     if ((p_buf = (BT_HDR *)GKI_getpoolbuf(BTM_CMD_POOL_ID)) == NULL)
@@ -4236,12 +3736,12 @@
         /* get number of UUID 16-bit list */
 #if (BTA_EIR_CANNED_UUID_LIST == TRUE)
         num_uuid = p_bta_dm_eir_cfg->bta_dm_eir_uuid16_len/LEN_UUID_16;
-#else
+#else  // BTA_EIR_CANNED_UUID_LIST
         max_num_uuid = (free_eir_length - 2)/LEN_UUID_16;
         data_type = BTM_GetEirSupportedServices( bta_dm_cb.eir_uuid, &p,
                                                  max_num_uuid, &num_uuid );
         p = (UINT8 *)p_buf + BTM_HCI_EIR_OFFSET; /* reset p */
-#endif
+#endif  // BTA_EIR_CANNED_UUID_LIST
 
         /* if UUID doesn't fit remaing space, shorten local name */
         if ( local_name_len > (free_eir_length - 4 - num_uuid*LEN_UUID_16))
@@ -4452,9 +3952,7 @@
     BTM_WriteEIR( p_buf );
 
 }
-#endif
 
-#if ( BTM_EIR_CLIENT_INCLUDED == TRUE )
 /*******************************************************************************
 **
 ** Function         bta_dm_eir_search_services
@@ -4528,9 +4026,8 @@
     APPL_TRACE_ERROR("BTA EIR search result, services_to_search=0x%08X, services_found=0x%08X",
                         *p_services_to_search, *p_services_found);
 }
-#endif
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&(BTA_EIR_CANNED_UUID_LIST != TRUE)
+#if (BTA_EIR_CANNED_UUID_LIST != TRUE)
 /*******************************************************************************
 **
 ** Function         bta_dm_eir_update_uuid
@@ -4723,38 +4220,6 @@
     }
 }
 
-/*******************************************************************************
-**
-** Function         bta_dm_set_afh_channels
-**
-** Description      set afh channels
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_dm_set_afh_channels(tBTA_DM_MSG * p_data)
-{
-
-    BTM_SetAfhChannels(p_data->set_afhchannels.first,p_data->set_afhchannels.last);
-}
-
-/*******************************************************************************
-**
-** Function         bta_dm_set_afh_channel_assesment
-**
-** Description      set afh channel assesment
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-
-void bta_dm_set_afh_channel_assesment (tBTA_DM_MSG * p_data)
-{
-    BTM_SetAfhChannelAssessment(p_data->set_afh_channel_assessment.enable_or_disable);
-}
-
 #if (BLE_INCLUDED == TRUE)
 /*******************************************************************************
 **
@@ -5857,7 +5322,7 @@
         APPL_TRACE_ERROR("%s out of room to accomodate more service ids ble_raw_size = %d ble_raw_used = %d", __FUNCTION__,bta_dm_search_cb.ble_raw_size, bta_dm_search_cb.ble_raw_used );
     }
 
-    APPL_TRACE_ERROR("bta_dm_gatt_disc_result serivce_id len=%d ", service_id.uuid.len);
+    LOG_INFO("%s service_id_uuid_len=%d ", __func__, service_id.uuid.len);
     if ( bta_dm_search_cb.state != BTA_DM_SEARCH_IDLE)
     {
 
@@ -6093,6 +5558,7 @@
             APPL_TRACE_DEBUG("BTA_GATTC_CLOSE_EVT reason = %d", p_data->close.reason);
             /* in case of disconnect before search is completed */
             if ( (bta_dm_search_cb.state != BTA_DM_SEARCH_IDLE) &&
+                 (bta_dm_search_cb.state != BTA_DM_SEARCH_ACTIVE) &&
                  !memcmp(p_data->close.remote_bda, bta_dm_search_cb.peer_bdaddr, BD_ADDR_LEN))
             {
                 bta_dm_gatt_disc_complete((UINT16)BTA_GATT_INVALID_CONN_ID,  (tBTA_GATT_STATUS) BTA_GATT_ERROR);
diff --git a/bta/dm/bta_dm_api.c b/bta/dm/bta_dm_api.c
index 9000207..92ab0a8 100644
--- a/bta/dm/bta_dm_api.c
+++ b/bta/dm/bta_dm_api.c
@@ -23,7 +23,6 @@
  ******************************************************************************/
 
 #include "gki.h"
-#include "bd.h"
 #include "bta_sys.h"
 #include "bta_api.h"
 #include "bta_dm_int.h"
@@ -167,21 +166,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_DmIsDeviceUp
-**
-** Description      Called during startup to check whether the bluetooth module
-**                  is up and ready
-**
-** Returns          BOOLEAN
-**
-*******************************************************************************/
-BOOLEAN BTA_DmIsDeviceUp(void)
-{
-    return BTM_IsDeviceUp();
-}
-
-/*******************************************************************************
-**
 ** Function         BTA_DmSetDeviceName
 **
 ** Description      This function sets the Bluetooth name of local device
@@ -241,129 +225,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_DmSetScanParam
-**
-** Description      This function sets the parameters for page scan and
-**                  inquiry scan.
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTA_DmSetScanParam (UINT16 page_scan_interval, UINT16 page_scan_window,
-                                  UINT16 inquiry_scan_interval, UINT16 inquiry_scan_window)
-{
-    APPL_TRACE_API ("BTA_DmSetScanParam: %d, %d, %d, %d",
-            page_scan_interval, page_scan_window,
-            inquiry_scan_interval, inquiry_scan_window);
-
-    bta_dm_cb.page_scan_interval = page_scan_interval;
-    bta_dm_cb.page_scan_window = page_scan_window;
-    bta_dm_cb.inquiry_scan_interval = inquiry_scan_interval;
-    bta_dm_cb.inquiry_scan_window = inquiry_scan_window;
-}
-
-/*******************************************************************************
-**
-** Function         BTA_DmSetAfhChannels
-**
-** Description      This function sets the AFH first and
-**                  last disable channel, so channels within
-**                  that range are disabled.
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTA_DmSetAfhChannels(UINT8 first, UINT8 last)
-{
-
-    tBTA_DM_API_SET_AFH_CHANNELS_EVT    *p_msg;
-
-    if ((p_msg = (tBTA_DM_API_SET_AFH_CHANNELS_EVT *) GKI_getbuf(sizeof(tBTA_DM_MSG))) != NULL)
-    {
-        p_msg->hdr.event = BTA_DM_API_SET_AFH_CHANNELS_EVT;
-        p_msg->first = first;
-        p_msg->last = last;
-        bta_sys_sendmsg(p_msg);
-    }
-
-
-}
-
-/*******************************************************************************
-**
-** Function         BTA_SetAfhChannelAssessment
-**
-** Description      This function is called to set the channel assessment mode on or off
-**
-** Returns          status
-**
-*******************************************************************************/
-void BTA_DmSetAfhChannelAssessment (BOOLEAN enable_or_disable)
-{
-    tBTA_DM_API_SET_AFH_CHANNEL_ASSESSMENT *p_msg;
-
-    if ((p_msg = (tBTA_DM_API_SET_AFH_CHANNEL_ASSESSMENT *) GKI_getbuf(sizeof(tBTA_DM_API_SET_AFH_CHANNEL_ASSESSMENT))) != NULL)
-    {
-        p_msg->hdr.event    = BTA_DM_API_SET_AFH_CHANNEL_ASSESMENT_EVT;
-        p_msg->enable_or_disable = enable_or_disable;
-        bta_sys_sendmsg(p_msg);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         BTA_DmVendorSpecificCommand
-**
-** Description      This function sends the vendor specific command
-**                  to the controller
-**
-**
-** Returns          tBTA_STATUS
-**
-*******************************************************************************/
-tBTA_STATUS BTA_DmVendorSpecificCommand (UINT16 opcode, UINT8 param_len,
-                                         UINT8 *p_param_buf,
-                                         tBTA_VENDOR_CMPL_CBACK *p_cback)
-{
-
-    tBTA_DM_API_VENDOR_SPECIFIC_COMMAND    *p_msg;
-    UINT16 size;
-
-    /* If p_cback is NULL, Notify application */
-    if (p_cback == NULL)
-    {
-        return (BTA_FAILURE);
-    }
-    else
-    {
-        size = sizeof (tBTA_DM_API_VENDOR_SPECIFIC_COMMAND) + param_len;
-        if ((p_msg = (tBTA_DM_API_VENDOR_SPECIFIC_COMMAND *) GKI_getbuf(size)) != NULL)
-        {
-            p_msg->hdr.event = BTA_DM_API_VENDOR_SPECIFIC_COMMAND_EVT;
-            p_msg->opcode = opcode;
-            p_msg->p_param_buf = (UINT8 *)(p_msg + 1);
-            p_msg->p_cback = p_cback;
-
-            if (p_param_buf && param_len)
-            {
-                memcpy (p_msg->p_param_buf, p_param_buf, param_len);
-                p_msg->param_len = param_len;
-            }
-            else
-            {
-                p_msg->param_len = 0;
-                p_msg->p_param_buf = NULL;
-
-            }
-
-            bta_sys_sendmsg(p_msg);
-        }
-        return (BTA_SUCCESS);
-    }
-}
-/*******************************************************************************
-**
 ** Function         BTA_DmSearch
 **
 ** Description      This function searches for peer Bluetooth devices. It performs
@@ -479,30 +340,6 @@
     }
 
 }
-/*******************************************************************************
-**
-** Function         BTA_DmIsMaster
-**
-** Description      This function checks if the local device is the master of
-**                  the link to the given device
-**
-** Returns          TRUE if master.
-**                  FALSE if not.
-**
-*******************************************************************************/
-BOOLEAN BTA_DmIsMaster(BD_ADDR bd_addr)
-{
-    BOOLEAN is_master = FALSE;
-    UINT8 link_role;
-
-    BTM_GetRole(bd_addr, &link_role);
-    APPL_TRACE_API("BTA_DmIsMaster role:x%x", link_role);
-    if(link_role == BTM_ROLE_MASTER)
-    {
-        is_master = TRUE;
-    }
-    return is_master;
-}
 
 /*******************************************************************************
 **
@@ -602,34 +439,6 @@
 
 }
 
-/*******************************************************************************
-**
-** Function         BTA_DmLinkPolicy
-**
-** Description      This function sets/clears the link policy mask to the given
-**                  bd_addr.
-**                  If clearing the sniff or park mode mask, the link is put
-**                  in active mode.
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTA_DmLinkPolicy(BD_ADDR bd_addr, tBTA_DM_LP_MASK policy_mask,
-                      BOOLEAN set)
-{
-    tBTA_DM_API_LINK_POLICY    *p_msg;
-
-    if ((p_msg = (tBTA_DM_API_LINK_POLICY *) GKI_getbuf(sizeof(tBTA_DM_API_LINK_POLICY))) != NULL)
-    {
-        p_msg->hdr.event = BTA_DM_API_LINK_POLICY_EVT;
-        bdcpy(p_msg->bd_addr, bd_addr);
-        p_msg->policy_mask = policy_mask;
-        p_msg->set = set;
-        bta_sys_sendmsg(p_msg);
-    }
-}
-
-
 #if (BTM_OOB_INCLUDED == TRUE)
 /*******************************************************************************
 **
@@ -677,32 +486,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_DmPasskeyCancel
-**
-** Description      This function is called to cancel the simple pairing process
-**                  reported by BTA_DM_SP_KEY_NOTIF_EVT
-**
-** Returns          void
-**
-*******************************************************************************/
-#if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
-void BTA_DmPasskeyCancel(BD_ADDR bd_addr)
-{
-    tBTA_DM_API_PASKY_CANCEL    *p_msg;
-
-    if ((p_msg = (tBTA_DM_API_PASKY_CANCEL *) \
-        GKI_getbuf(sizeof(tBTA_DM_API_PASKY_CANCEL))) != NULL)
-    {
-        p_msg->hdr.event = BTA_DM_API_PASKY_CANCEL_EVT;
-        bdcpy(p_msg->bd_addr, bd_addr);
-        bta_sys_sendmsg(p_msg);
-    }
-}
-#endif
-
-
-/*******************************************************************************
-**
 ** Function         BTA_DmAddDevice
 **
 ** Description      This function adds a device to the security database list of
@@ -784,248 +567,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_DmAddDevWithName
-**
-** Description      This function is newer version of  BTA_DmAddDevice()
-**                  which added bd_name and features as input parameters.
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTA_DmAddDevWithName (BD_ADDR bd_addr, DEV_CLASS dev_class,
-                                      BD_NAME bd_name, UINT8 *features,
-                                      LINK_KEY link_key, tBTA_SERVICE_MASK trusted_mask,
-                                      BOOLEAN is_trusted, UINT8 key_type, tBTA_IO_CAP io_cap)
-{
-    tBTA_DM_API_ADD_DEVICE *p_msg;
-
-    if ((p_msg = (tBTA_DM_API_ADD_DEVICE *) GKI_getbuf(sizeof(tBTA_DM_API_ADD_DEVICE))) != NULL)
-    {
-        memset (p_msg, 0, sizeof(tBTA_DM_API_ADD_DEVICE));
-
-        p_msg->hdr.event = BTA_DM_API_ADD_DEVICE_EVT;
-        bdcpy(p_msg->bd_addr, bd_addr);
-        p_msg->tm = trusted_mask;
-        p_msg->is_trusted = is_trusted;
-        p_msg->io_cap = io_cap;
-
-        if (link_key)
-        {
-            p_msg->link_key_known = TRUE;
-            p_msg->key_type = key_type;
-            memcpy(p_msg->link_key, link_key, LINK_KEY_LEN);
-        }
-
-        /* Load device class if specified */
-        if (dev_class)
-        {
-            p_msg->dc_known = TRUE;
-            memcpy (p_msg->dc, dev_class, DEV_CLASS_LEN);
-        }
-
-        if (bd_name)
-            memcpy(p_msg->bd_name, bd_name, BD_NAME_LEN);
-
-        if (features)
-            memcpy(p_msg->features, features, sizeof(p_msg->features));
-
-        bta_sys_sendmsg(p_msg);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         BTA_DmAuthorizeReply
-**
-** Description      This function provides an authorization reply when authorization
-**                  is requested by BTA through BTA_DM_AUTHORIZE_EVT
-**
-**
-** Returns          tBTA_STATUS
-**
-*******************************************************************************/
-void BTA_DmAuthorizeReply(BD_ADDR bd_addr, tBTA_SERVICE_ID service, tBTA_AUTH_RESP response)
-{
-
-    tBTA_DM_API_AUTH_REPLY    *p_msg;
-
-    if ((p_msg = (tBTA_DM_API_AUTH_REPLY *) GKI_getbuf(sizeof(tBTA_DM_API_AUTH_REPLY))) != NULL)
-    {
-        p_msg->hdr.event = BTA_DM_API_AUTH_REPLY_EVT;
-        bdcpy(p_msg->bd_addr, bd_addr);
-        p_msg->service = service;
-        p_msg->response = response;
-
-        bta_sys_sendmsg(p_msg);
-    }
-
-}
-
-/*******************************************************************************
-**
-** Function         BTA_DmSignalStrength
-**
-** Description      This function initiates RSSI and channnel quality
-**                  measurments. BTA_DM_SIG_STRENGTH_EVT is sent to
-**                  application with the values of RSSI and channel
-**                  quality
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTA_DmSignalStrength(tBTA_SIG_STRENGTH_MASK mask, UINT16 period, BOOLEAN start)
-{
-
-    tBTA_API_DM_SIG_STRENGTH    *p_msg;
-
-    if ((p_msg = (tBTA_API_DM_SIG_STRENGTH *) GKI_getbuf(sizeof(tBTA_API_DM_SIG_STRENGTH))) != NULL)
-    {
-        p_msg->hdr.event = BTA_API_DM_SIG_STRENGTH_EVT;
-        p_msg->mask = mask;
-        p_msg->period = period;
-        p_msg->start = start;
-
-        bta_sys_sendmsg(p_msg);
-    }
-
-
-}
-
-/*******************************************************************************
-**
-** Function         BTA_DmWriteInqTxPower
-**
-** Description      This command is used to write the inquiry transmit power level
-**                  used to transmit the inquiry (ID) data packets.
-**
-** Parameters       tx_power - tx inquiry power to use, valid value is -70 ~ 20
-
-** Returns          void
-**
-*******************************************************************************/
-void BTA_DmWriteInqTxPower(INT8 tx_power)
-{
-
-    tBTA_API_DM_TX_INQPWR    *p_msg;
-
-    if ((p_msg = (tBTA_API_DM_TX_INQPWR *) GKI_getbuf(sizeof(tBTA_API_DM_TX_INQPWR))) != NULL)
-    {
-        p_msg->hdr.event = BTA_DM_API_TX_INQPWR_EVT;
-        p_msg->tx_power = tx_power;
-
-        bta_sys_sendmsg(p_msg);
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         BTA_DmEirAddUUID
-**
-** Description      This function is called to add UUID into EIR.
-**
-** Parameters       tBT_UUID - UUID
-**
-** Returns          None
-**
-*******************************************************************************/
-void BTA_DmEirAddUUID (tBT_UUID *p_uuid)
-{
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&( BTA_EIR_CANNED_UUID_LIST != TRUE )&&(BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
-    tBTA_DM_API_UPDATE_EIR_UUID    *p_msg;
-
-    if ((p_msg = (tBTA_DM_API_UPDATE_EIR_UUID *) GKI_getbuf(sizeof(tBTA_DM_API_UPDATE_EIR_UUID))) != NULL)
-    {
-        p_msg->hdr.event = BTA_DM_API_UPDATE_EIR_UUID_EVT;
-        p_msg->is_add    = TRUE;
-        memcpy (&(p_msg->uuid), p_uuid, sizeof(tBT_UUID));
-
-        bta_sys_sendmsg(p_msg);
-    }
-#endif
-}
-
-/*******************************************************************************
-**
-** Function         BTA_DmEirRemoveUUID
-**
-** Description      This function is called to remove UUID from EIR.
-**
-** Parameters       tBT_UUID - UUID
-**
-** Returns          None
-**
-*******************************************************************************/
-void BTA_DmEirRemoveUUID (tBT_UUID *p_uuid)
-{
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&( BTA_EIR_CANNED_UUID_LIST != TRUE )&&(BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
-    tBTA_DM_API_UPDATE_EIR_UUID    *p_msg;
-
-    if ((p_msg = (tBTA_DM_API_UPDATE_EIR_UUID *) GKI_getbuf(sizeof(tBTA_DM_API_UPDATE_EIR_UUID))) != NULL)
-    {
-        p_msg->hdr.event = BTA_DM_API_UPDATE_EIR_UUID_EVT;
-        p_msg->is_add    = FALSE;
-        memcpy (&(p_msg->uuid), p_uuid, sizeof(tBT_UUID));
-
-        bta_sys_sendmsg(p_msg);
-    }
-#endif
-}
-
-/*******************************************************************************
-**
-** Function         BTA_DmSetEIRConfig
-**
-** Description      This function is called to override the BTA default EIR parameters.
-**                  This funciton is only valid in a system where BTU & App task
-**                  are in the same memory space.
-**
-** Parameters       Pointer to User defined EIR config
-**
-** Returns          None
-**
-*******************************************************************************/
-void BTA_DmSetEIRConfig (tBTA_DM_EIR_CONF *p_eir_cfg)
-{
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
-    tBTA_DM_API_SET_EIR_CONFIG  *p_msg;
-
-    if ((p_msg = (tBTA_DM_API_SET_EIR_CONFIG *) GKI_getbuf(sizeof(tBTA_DM_API_SET_EIR_CONFIG))) != NULL)
-    {
-        p_msg->hdr.event = BTA_DM_API_SET_EIR_CONFIG_EVT;
-        p_msg->p_eir_cfg = p_eir_cfg;
-
-        bta_sys_sendmsg(p_msg);
-    }
-#endif
-}
-
-/*******************************************************************************
-**
-** Function         BTA_CheckEirData
-**
-** Description      This function is called to get EIR data from significant part.
-**
-** Parameters       p_eir - pointer of EIR significant part
-**                  type   - finding EIR data type
-**                  p_length - return the length of EIR data
-**
-** Returns          pointer of EIR data
-**
-*******************************************************************************/
-UINT8 *BTA_CheckEirData( UINT8 *p_eir, UINT8 type, UINT8 *p_length )
-{
-#if ( BTM_EIR_CLIENT_INCLUDED == TRUE )
-    return BTM_CheckEirData( p_eir, type, p_length );
-#else
-    return NULL;
-#endif
-}
-
-/*******************************************************************************
-**
 ** Function         BTA_GetEirService
 **
 ** Description      This function is called to get BTA service mask from EIR.
@@ -1039,7 +580,6 @@
 extern const UINT16 bta_service_id_to_uuid_lkup_tbl [];
 void BTA_GetEirService( UINT8 *p_eir, tBTA_SERVICE_MASK *p_services )
 {
-#if ( BTM_EIR_CLIENT_INCLUDED == TRUE )
     UINT8 xx, yy;
     UINT8 num_uuid, max_num_uuid = 32;
     UINT8 uuid_list[32*LEN_UUID_16];
@@ -1070,26 +610,6 @@
         if (*(p_uuid16 + xx) == UUID_SERVCLASS_HDP_SINK)
             *p_services |= BTA_HL_SERVICE_MASK;
     }
-#endif
-}
-
-/*******************************************************************************
-**
-** Function         BTA_DmUseSsr
-**
-** Description      This function is called to check if the connected peer device
-**                  supports SSR or not.
-**
-** Returns          TRUE, if SSR is supported
-**
-*******************************************************************************/
-BOOLEAN BTA_DmUseSsr( BD_ADDR bd_addr )
-{
-    BOOLEAN use_ssr = FALSE;
-    tBTA_DM_PEER_DEVICE * p_dev = bta_dm_find_peer_device(bd_addr);
-    if(p_dev && (p_dev->info & BTA_DM_DI_USE_SSR) )
-        use_ssr = TRUE;
-    return use_ssr;
 }
 
 /*******************************************************************************
@@ -1145,100 +665,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_DmGetLocalDiRecord
-**
-** Description      Get a specified DI record to the local SDP database. If no
-**                  record handle is provided, the primary DI record will be
-**                  returned.
-**
-**                  Fills in the device information of the record
-**                  p_handle - if p_handle == 0, the primary record is returned
-**
-** Returns          BTA_SUCCESS if record set sucessfully, otherwise error code.
-**
-*******************************************************************************/
-tBTA_STATUS BTA_DmGetLocalDiRecord( tBTA_DI_GET_RECORD *p_device_info,
-                              UINT32 *p_handle )
-{
-    UINT16  status;
-
-    status = SDP_GetLocalDiRecord(p_device_info, p_handle);
-
-    if (status == SDP_SUCCESS)
-        return BTA_SUCCESS;
-    else
-        return BTA_FAILURE;
-
-}
-
-/*******************************************************************************
-**                   Device Identification (DI) Client Functions
-*******************************************************************************/
-/*******************************************************************************
-**
-** Function         BTA_DmDiDiscover
-**
-** Description      This function queries a remote device for DI information.
-**
-**
-** Returns          None.
-**
-*******************************************************************************/
-void BTA_DmDiDiscover( BD_ADDR remote_device, tBTA_DISCOVERY_DB *p_db,
-                       UINT32 len, tBTA_DM_SEARCH_CBACK *p_cback )
-{
-    tBTA_DM_API_DI_DISC    *p_msg;
-
-    if ((p_msg = (tBTA_DM_API_DI_DISC *) GKI_getbuf(sizeof(tBTA_DM_API_DI_DISC))) != NULL)
-    {
-        bdcpy(p_msg->bd_addr, remote_device);
-        p_msg->hdr.event    = BTA_DM_API_DI_DISCOVER_EVT;
-        p_msg->p_sdp_db     = p_db;
-        p_msg->len          = len;
-        p_msg->p_cback      = p_cback;
-
-        bta_sys_sendmsg(p_msg);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         BTA_DmGetDiRecord
-**
-** Description      This function retrieves a remote device's DI record from
-**                  the specified database.
-**
-** Returns          BTA_SUCCESS if Get DI record is succeed.
-**                  BTA_FAILURE if Get DI record failed.
-**
-*******************************************************************************/
-tBTA_STATUS BTA_DmGetDiRecord( UINT8 get_record_index, tBTA_DI_GET_RECORD *p_device_info,
-                        tBTA_DISCOVERY_DB *p_db )
-{
-    if (SDP_GetDiRecord(get_record_index, p_device_info, p_db) != SDP_SUCCESS)
-        return BTA_FAILURE;
-    else
-        return BTA_SUCCESS;
-}
-
-/*******************************************************************************
-**
-** Function         BTA_SysFeatures
-**
-** Description      This function is called to set system features.
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTA_SysFeatures (UINT16 sys_features)
-{
-    bta_sys_cb.sys_features = sys_features;
-
-    APPL_TRACE_API("BTA_SysFeatures: sys_features = %d", sys_features);
-}
-
-/*******************************************************************************
-**
 ** Function         bta_dmexecutecallback
 **
 ** Description      This function will request BTA to execute a call back in the context of BTU task
@@ -1557,8 +983,8 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleSetScanRsp (tBTA_BLE_AD_MASK data_mask, tBTA_BLE_ADV_DATA *p_adv_cfg,
-                        tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback)
+extern void BTA_DmBleSetScanRsp (tBTA_BLE_AD_MASK data_mask, tBTA_BLE_ADV_DATA *p_adv_cfg,
+                                 tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback)
 {
     tBTA_DM_API_SET_ADV_CONFIG  *p_msg;
 
@@ -1591,7 +1017,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleSetStorageParams(UINT8 batch_scan_full_max,
+extern void BTA_DmBleSetStorageParams(UINT8 batch_scan_full_max,
                                          UINT8 batch_scan_trunc_max,
                                          UINT8 batch_scan_notify_threshold,
                                          tBTA_BLE_SCAN_SETUP_CBACK *p_setup_cback,
@@ -1632,7 +1058,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleEnableBatchScan(tBTA_BLE_SCAN_MODE scan_mode,
+extern void BTA_DmBleEnableBatchScan(tBTA_BLE_SCAN_MODE scan_mode,
                                          UINT32 scan_interval, UINT32 scan_window,
                                          tBTA_BLE_DISCARD_RULE discard_rule,
                                          tBLE_ADDR_TYPE        addr_type,
@@ -1664,7 +1090,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleDisableBatchScan(tBTA_DM_BLE_REF_VALUE ref_value)
+extern void BTA_DmBleDisableBatchScan(tBTA_DM_BLE_REF_VALUE ref_value)
 {
     tBTA_DM_API_DISABLE_SCAN  *p_msg;
 
@@ -1689,7 +1115,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleReadScanReports(tBTA_BLE_SCAN_MODE scan_type,
+extern void BTA_DmBleReadScanReports(tBTA_BLE_SCAN_MODE scan_type,
                                              tBTA_DM_BLE_REF_VALUE ref_value)
 {
     tBTA_DM_API_READ_SCAN_REPORTS  *p_msg;
@@ -1716,7 +1142,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleTrackAdvertiser(tBTA_DM_BLE_REF_VALUE ref_value,
+extern void BTA_DmBleTrackAdvertiser(tBTA_DM_BLE_REF_VALUE ref_value,
                             tBTA_BLE_TRACK_ADV_CBACK *p_track_adv_cback)
 {
     tBTA_DM_API_TRACK_ADVERTISER  *p_msg;
@@ -1742,7 +1168,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleBroadcast (BOOLEAN start)
+extern void BTA_DmBleBroadcast (BOOLEAN start)
 {
     tBTA_DM_API_BLE_OBSERVE   *p_msg;
 
@@ -2526,8 +1952,8 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleObserve(BOOLEAN start, UINT8 duration,
-                                     tBTA_DM_SEARCH_CBACK *p_results_cb)
+extern void BTA_DmBleObserve(BOOLEAN start, UINT8 duration,
+                             tBTA_DM_SEARCH_CBACK *p_results_cb)
 {
     tBTA_DM_API_BLE_OBSERVE   *p_msg;
 
diff --git a/bta/dm/bta_dm_cfg.c b/bta/dm/bta_dm_cfg.c
index 606435b..e16b9f3 100644
--- a/bta/dm/bta_dm_cfg.c
+++ b/bta/dm/bta_dm_cfg.c
@@ -513,7 +513,6 @@
 ** 184 to 240 bytes, DH5 is used but it not recommended.
 */
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )
 #if (BTA_EIR_CANNED_UUID_LIST == TRUE)
                                             /* for example */
 const UINT8 bta_dm_eir_uuid16_list[] = {    0x08, 0x11, /* Headset */
@@ -521,7 +520,7 @@
                                             0x0E, 0x11, /* AV Remote Control */
                                             0x0B, 0x11, /* Audio Sink */
 };
-#endif
+#endif  // BTA_EIR_CANNED_UUID_LIST
 
 /* Extended Inquiry Response */
 const tBTA_DM_EIR_CONF bta_dm_eir_cfg =
@@ -532,13 +531,13 @@
 #if (BTA_EIR_CANNED_UUID_LIST == TRUE)
     8,
     (UINT8 *)bta_dm_eir_uuid16_list,
-#else
+#else // BTA_EIR_CANNED_UUID_LIST
     {   /* mask of UUID list in EIR */
         0xFFFFFFFF, /* LSB is the first UUID of the first 32 UUIDs in BTM_EIR_UUID_LKUP_TBL */
         0xFFFFFFFF  /* LSB is the first UUID of the next 32 UUIDs in BTM_EIR_UUID_LKUP_TBL */
         /* BTM_EIR_UUID_LKUP_TBL can be overrided */
     },
-#endif
+#endif  // BTA_EIR_CANNED_UUID_LIST
     NULL,   /* Inquiry TX power         */
     0,      /* length of flags in bytes */
     NULL,   /* flags for EIR */
@@ -548,4 +547,3 @@
     NULL    /* additional data */
 };
 tBTA_DM_EIR_CONF *p_bta_dm_eir_cfg = (tBTA_DM_EIR_CONF*)&bta_dm_eir_cfg;
-#endif
diff --git a/bta/dm/bta_dm_ci.c b/bta/dm/bta_dm_ci.c
index 5e2e312..11ef0b2 100644
--- a/bta/dm/bta_dm_ci.c
+++ b/bta/dm/bta_dm_ci.c
@@ -23,7 +23,6 @@
  ******************************************************************************/
 
 #include "gki.h"
-#include "bd.h"
 #include "bta_sys.h"
 #include "bta_api.h"
 #include "bta_dm_int.h"
diff --git a/bta/dm/bta_dm_int.h b/bta/dm/bta_dm_int.h
index 66bc5a3..4ab8497 100644
--- a/bta/dm/bta_dm_int.h
+++ b/bta/dm/bta_dm_int.h
@@ -54,10 +54,6 @@
     BTA_DM_API_DISABLE_EVT,
     BTA_DM_API_SET_NAME_EVT,
     BTA_DM_API_SET_VISIBILITY_EVT,
-    BTA_DM_API_SET_AFH_CHANNELS_EVT,
-    BTA_API_DM_SIG_STRENGTH_EVT,
-    BTA_DM_API_VENDOR_SPECIFIC_COMMAND_EVT,
-    BTA_DM_API_TX_INQPWR_EVT,
     BTA_DM_ACL_CHANGE_EVT,
     BTA_DM_API_ADD_DEVICE_EVT,
     BTA_DM_API_REMOVE_ACL_EVT,
@@ -66,8 +62,6 @@
     BTA_DM_API_BOND_EVT,
     BTA_DM_API_BOND_CANCEL_EVT,
     BTA_DM_API_PIN_REPLY_EVT,
-    BTA_DM_API_LINK_POLICY_EVT,
-    BTA_DM_API_AUTH_REPLY_EVT,
 
     /* power manger events */
     BTA_DM_PM_BTM_STATUS_EVT,
@@ -79,9 +73,6 @@
     BTA_DM_API_SET_ENCRYPTION_EVT,
 
 
-#if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
-    BTA_DM_API_PASKY_CANCEL_EVT,
-#endif
 #if (BTM_OOB_INCLUDED == TRUE)
     BTA_DM_API_LOC_OOB_EVT,
     BTA_DM_CI_IO_REQ_EVT,
@@ -125,17 +116,9 @@
     BTA_DM_API_BLE_ENERGY_INFO_EVT,
 #endif
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&( BTA_EIR_CANNED_UUID_LIST != TRUE )&&(BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
-    BTA_DM_API_UPDATE_EIR_UUID_EVT,
-#endif
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
-    BTA_DM_API_SET_EIR_CONFIG_EVT,
-#endif
-
     BTA_DM_API_ENABLE_TEST_MODE_EVT,
     BTA_DM_API_DISABLE_TEST_MODE_EVT,
     BTA_DM_API_EXECUTE_CBACK_EVT,
-    BTA_DM_API_SET_AFH_CHANNEL_ASSESMENT_EVT,
     BTA_DM_MAX_EVT
 };
 
@@ -180,25 +163,6 @@
     UINT8           conn_paired_only;
 } tBTA_DM_API_SET_VISIBILITY;
 
-/* data type for BTA_DM_API_SET_AFH_CHANNELS_EVT */
-typedef struct
-{
-    BT_HDR              hdr;
-    UINT8           first;
-    UINT8           last;
-} tBTA_DM_API_SET_AFH_CHANNELS_EVT;
-
-/* data type for BTA_DM_API_VENDOR_SPECIFIC_COMMAND_EVT */
-typedef struct
-{
-    BT_HDR              hdr;
-    UINT16              opcode;
-    UINT8               param_len;
-    UINT8               *p_param_buf;
-    tBTA_VENDOR_CMPL_CBACK *p_cback;
-
-} tBTA_DM_API_VENDOR_SPECIFIC_COMMAND;
-
 enum
 {
     BTA_DM_RS_NONE,     /* straight API call */
@@ -273,24 +237,6 @@
     UINT8 p_pin[PIN_CODE_LEN];
 } tBTA_DM_API_PIN_REPLY;
 
-/* data type for BTA_DM_API_LINK_POLICY_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    BD_ADDR     bd_addr;
-    UINT16      policy_mask;
-    BOOLEAN     set;
-} tBTA_DM_API_LINK_POLICY;
-
-/* data type for BTA_DM_API_AUTH_REPLY_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    BD_ADDR bd_addr;
-    tBTA_SERVICE_ID service;
-    tBTA_AUTH_RESP response;
-} tBTA_DM_API_AUTH_REPLY;
-
 /* data type for BTA_DM_API_LOC_OOB_EVT */
 typedef struct
 {
@@ -305,13 +251,6 @@
     BOOLEAN     accept;
 } tBTA_DM_API_CONFIRM;
 
-/* data type for BTA_DM_API_PASKY_CANCEL_EVT*/
-typedef struct
-{
-    BT_HDR      hdr;
-    BD_ADDR     bd_addr;
-} tBTA_DM_API_PASKY_CANCEL;
-
 /* data type for BTA_DM_CI_IO_REQ_EVT */
 typedef struct
 {
@@ -361,22 +300,6 @@
     UINT16 sdp_result;
 } tBTA_DM_SDP_RESULT;
 
-/* data type for BTA_API_DM_SIG_STRENGTH_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    tBTA_SIG_STRENGTH_MASK mask;
-    UINT16 period;
-    BOOLEAN start;
-} tBTA_API_DM_SIG_STRENGTH;
-
-/* data type for tBTA_API_DM_TX_INQPWR */
-typedef struct
-{
-    BT_HDR      hdr;
-    INT8        tx_power;
-}tBTA_API_DM_TX_INQPWR;
-
 /* data type for BTA_DM_ACL_CHANGE_EVT */
 typedef struct
 {
@@ -648,31 +571,6 @@
 
 #endif /* BLE_INCLUDED */
 
-typedef struct
-{
-    BT_HDR                  hdr;
-    BOOLEAN                 enable_or_disable;
-}tBTA_DM_API_SET_AFH_CHANNEL_ASSESSMENT;
-
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&( BTA_EIR_CANNED_UUID_LIST != TRUE )&&(BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
-/* data type for BTA_DM_API_UPDATE_EIR_UUID_EVT */
-typedef struct
-{
-    BT_HDR          hdr;
-    BOOLEAN         is_add;
-    tBT_UUID        uuid;
-}tBTA_DM_API_UPDATE_EIR_UUID;
-#endif
-
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
-/* data type for BTA_DM_API_SET_EIR_CONFIG_EVT */
-typedef struct
-{
-    BT_HDR              hdr;
-    tBTA_DM_EIR_CONF    *p_eir_cfg;
-}tBTA_DM_API_SET_EIR_CONFIG;
-#endif
-
 /* data type for BTA_DM_API_REMOVE_ACL_EVT */
 typedef struct
 {
@@ -735,10 +633,6 @@
 
     tBTA_DM_API_SET_VISIBILITY set_visibility;
 
-    tBTA_DM_API_SET_AFH_CHANNELS_EVT set_afhchannels;
-
-    tBTA_DM_API_VENDOR_SPECIFIC_COMMAND vendor_command;
-
     tBTA_DM_API_ADD_DEVICE  add_dev;
 
     tBTA_DM_API_REMOVE_DEVICE remove_dev;
@@ -752,16 +646,12 @@
     tBTA_DM_API_BOND_CANCEL bond_cancel;
 
     tBTA_DM_API_PIN_REPLY pin_reply;
-    tBTA_DM_API_LINK_POLICY link_policy;
 
     tBTA_DM_API_LOC_OOB     loc_oob;
     tBTA_DM_API_CONFIRM     confirm;
-    tBTA_DM_API_PASKY_CANCEL passkey_cancel;
     tBTA_DM_CI_IO_REQ       ci_io_req;
     tBTA_DM_CI_RMT_OOB      ci_rmt_oob;
 
-    tBTA_DM_API_AUTH_REPLY auth_reply;
-
     tBTA_DM_REM_NAME rem_name;
 
     tBTA_DM_DISC_RESULT disc_result;
@@ -770,10 +660,6 @@
 
     tBTA_DM_SDP_RESULT sdp_event;
 
-    tBTA_API_DM_SIG_STRENGTH sig_strength;
-
-    tBTA_API_DM_TX_INQPWR   tx_inq_pwr;
-
     tBTA_DM_ACL_CHANGE  acl_change;
 
     tBTA_DM_PM_BTM_STATUS pm_status;
@@ -818,14 +704,6 @@
     tBTA_DM_API_ENERGY_INFO             ble_energy_info;
 #endif
 
-    tBTA_DM_API_SET_AFH_CHANNEL_ASSESSMENT set_afh_channel_assessment;
-
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&( BTA_EIR_CANNED_UUID_LIST != TRUE )&&(BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
-    tBTA_DM_API_UPDATE_EIR_UUID     update_eir_uuid;
-#endif
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
-    tBTA_DM_API_SET_EIR_CONFIG          set_eir_cfg;
-#endif
     tBTA_DM_API_REMOVE_ACL              remove_acl;
 
 } tBTA_DM_MSG;
@@ -926,10 +804,7 @@
     tBTA_BLE_MULTI_ADV_CBACK     *p_multi_adv_cback;
     tBTA_BLE_ENERGY_INFO_CBACK   *p_energy_info_cback;
 #endif
-    TIMER_LIST_ENT              signal_strength_timer;
-    tBTA_SIG_STRENGTH_MASK      signal_strength_mask;
     UINT16                      state;
-    UINT16                      signal_strength_period;
     BOOLEAN                     disabling;
     TIMER_LIST_ENT              disable_timer;
     UINT32                      wbt_sdp_handle;          /* WIDCOMM Extensions SDP record handle */
@@ -955,7 +830,7 @@
     tBTA_DM_SEC_EVT             pin_evt;
     UINT32          num_val;        /* the numeric value for comparison. If just_works, do not show this number to UI */
     BOOLEAN         just_works;     /* TRUE, if "Just Works" association model */
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&( BTA_EIR_CANNED_UUID_LIST != TRUE )
+#if ( BTA_EIR_CANNED_UUID_LIST != TRUE )
     /* store UUID list for EIR */
     TIMER_LIST_ENT              app_ready_timer;
     UINT32                      eir_uuid[BTM_EIR_SERVICE_ARRAY_SIZE];
@@ -1113,11 +988,9 @@
 extern tBTA_DM_SSR_SPEC *p_bta_dm_ssr_spec;
 #endif
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )
 /* update dynamic BRCM Aware EIR data */
 extern const tBTA_DM_EIR_CONF bta_dm_eir_cfg;
 extern tBTA_DM_EIR_CONF *p_bta_dm_eir_cfg;
-#endif
 
 /* DM control block */
 #if BTA_DYNAMIC_MEMORY == FALSE
@@ -1153,15 +1026,9 @@
 extern void bta_dm_disable (tBTA_DM_MSG *p_data);
 extern void bta_dm_set_dev_name (tBTA_DM_MSG *p_data);
 extern void bta_dm_set_visibility (tBTA_DM_MSG *p_data);
-extern void bta_dm_set_afhchannels (tBTA_DM_MSG *p_data);
-extern void bta_dm_vendor_spec_command(tBTA_DM_MSG *p_data);
 extern void bta_dm_bond (tBTA_DM_MSG *p_data);
 extern void bta_dm_bond_cancel (tBTA_DM_MSG *p_data);
 extern void bta_dm_pin_reply (tBTA_DM_MSG *p_data);
-extern void bta_dm_link_policy (tBTA_DM_MSG *p_data);
-extern void bta_dm_auth_reply (tBTA_DM_MSG *p_data);
-extern void bta_dm_signal_strength(tBTA_DM_MSG *p_data);
-extern void bta_dm_tx_inqpower(tBTA_DM_MSG *p_data);
 extern void bta_dm_acl_change(tBTA_DM_MSG *p_data);
 extern void bta_dm_add_device (tBTA_DM_MSG *p_data);
 extern void bta_dm_remove_device (tBTA_DM_MSG *p_data);
@@ -1209,7 +1076,6 @@
 #endif
 extern void bta_dm_set_encryption(tBTA_DM_MSG *p_data);
 extern void bta_dm_confirm(tBTA_DM_MSG *p_data);
-extern void bta_dm_passkey_cancel(tBTA_DM_MSG *p_data);
 #if (BTM_OOB_INCLUDED == TRUE)
 extern void bta_dm_loc_oob(tBTA_DM_MSG *p_data);
 extern void bta_dm_ci_io_req_act(tBTA_DM_MSG *p_data);
@@ -1244,22 +1110,10 @@
 
 extern void bta_dm_pm_active(BD_ADDR peer_addr);
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )
 void bta_dm_eir_update_uuid(UINT16 uuid16, BOOLEAN adding);
-#else
-#define bta_dm_eir_update_uuid(x, y)
-#endif
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&( BTA_EIR_CANNED_UUID_LIST != TRUE )&&(BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
-extern void bta_dm_update_eir_uuid (tBTA_DM_MSG *p_data);
-#endif
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
-extern void bta_dm_set_eir_config (tBTA_DM_MSG *p_data);
-#endif
 extern void bta_dm_enable_test_mode(tBTA_DM_MSG *p_data);
 extern void bta_dm_disable_test_mode(tBTA_DM_MSG *p_data);
 extern void bta_dm_execute_callback(tBTA_DM_MSG *p_data);
 
-extern void bta_dm_set_afh_channel_assesment(tBTA_DM_MSG *p_data);
-
 #endif /* BTA_DM_INT_H */
diff --git a/bta/dm/bta_dm_main.c b/bta/dm/bta_dm_main.c
index 35835c7..cf810a4 100644
--- a/bta/dm/bta_dm_main.c
+++ b/bta/dm/bta_dm_main.c
@@ -52,10 +52,6 @@
     bta_dm_disable,           /* 1  BTA_DM_API_DISABLE_EVT */
     bta_dm_set_dev_name,      /* 2  BTA_DM_API_SET_NAME_EVT */
     bta_dm_set_visibility,    /* 3  BTA_DM_API_SET_VISIBILITY_EVT */
-    bta_dm_set_afhchannels,   /* 4  BTA_DM_API_SET_AFH_CHANNELS_EVT */
-    bta_dm_signal_strength,   /* 5  BTA_API_DM_SIG_STRENGTH_EVT */
-    bta_dm_vendor_spec_command,/* 6  BTA_DM_API_VENDOR_SPECIFIC_COMMAND_EVT */
-    bta_dm_tx_inqpower,       /* 7  BTA_DM_API_SIG_STRENGTH_EVT */
     bta_dm_acl_change,        /* 8  BTA_DM_ACL_CHANGE_EVT */
     bta_dm_add_device,        /* 9  BTA_DM_API_ADD_DEVICE_EVT */
     bta_dm_close_acl,         /* 10 BTA_DM_API_ADD_DEVICE_EVT */
@@ -64,8 +60,6 @@
     bta_dm_bond,              /* 11  BTA_DM_API_BOND_EVT */
     bta_dm_bond_cancel,       /* 12  BTA_DM_API_BOND_CANCEL_EVT */
     bta_dm_pin_reply,         /* 13 BTA_DM_API_PIN_REPLY_EVT */
-    bta_dm_link_policy,       /* 14 BTA_DM_API_LINK_POLICY_EVT */
-    bta_dm_auth_reply,        /* 15 BTA_DM_API_AUTH_REPLY_EVT */
 
     /* power manger events */
     bta_dm_pm_btm_status,     /* 16 BTA_DM_PM_BTM_STATUS_EVT */
@@ -76,9 +70,6 @@
 
     bta_dm_set_encryption,    /* BTA_DM_API_SET_ENCRYPTION_EVT */
 
-#if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
-    bta_dm_passkey_cancel,    /* 19 BTA_DM_API_PASKY_CANCEL_EVT */
-#endif
 #if (BTM_OOB_INCLUDED == TRUE)
     bta_dm_loc_oob,           /* 20 BTA_DM_API_LOC_OOB_EVT */
     bta_dm_ci_io_req_act,     /* 21 BTA_DM_CI_IO_REQ_EVT */
@@ -121,17 +112,9 @@
     bta_dm_ble_get_energy_info,    /* BTA_DM_API_BLE_ENERGY_INFO_EVT */
 #endif
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&( BTA_EIR_CANNED_UUID_LIST != TRUE )&&(BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
-    bta_dm_update_eir_uuid,     /*  BTA_DM_API_UPDATE_EIR_UUID_EVT      */
-#endif
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
-    bta_dm_set_eir_config,      /*  BTA_DM_API_SET_EIR_CONFIG_EVT       */
-#endif
-
     bta_dm_enable_test_mode,    /*  BTA_DM_API_ENABLE_TEST_MODE_EVT     */
     bta_dm_disable_test_mode,   /*  BTA_DM_API_DISABLE_TEST_MODE_EVT    */
     bta_dm_execute_callback,     /*  BTA_DM_API_EXECUTE_CBACK_EVT        */
-    bta_dm_set_afh_channel_assesment      /* BTA_DM_API_SET_AFH_CHANNEL_ASSESMENT_EVT */
 };
 
 
diff --git a/bta/dm/bta_dm_pm.c b/bta/dm/bta_dm_pm.c
index e1826d8..c3c05de 100644
--- a/bta/dm/bta_dm_pm.c
+++ b/bta/dm/bta_dm_pm.c
@@ -24,7 +24,6 @@
  ******************************************************************************/
 
 #include "gki.h"
-#include "bd.h"
 #include "bta_sys.h"
 #include "bta_api.h"
 #include "bta_dm_int.h"
@@ -154,8 +153,7 @@
 {
 
     UINT8 i,j;
-    tBTM_STATUS btm_status;
-    tBTM_VERSION_INFO vers;
+    UINT16 policy_setting;
 #if (BTM_SSR_INCLUDED == TRUE)
     int               index = BTA_DM_PM_SSR0;
 #endif
@@ -163,21 +161,8 @@
 
     APPL_TRACE_DEBUG("bta_dm_pm_cback: st(%d), id(%d), app(%d)", status, id, app_id);
 
-    btm_status = BTM_ReadLocalVersion (&vers);
     p_dev = bta_dm_find_peer_device(peer_addr);
 
-    /* Disable/Enable sniff policy on the SCO link if sco Up/Down. Will be removed in 2.2*/
-    if ((p_dev) &&
-        ((status == BTA_SYS_SCO_OPEN) || (status == BTA_SYS_SCO_CLOSE)) )
-    {
-        if ((btm_status == BTM_SUCCESS) &&
-            (vers.manufacturer ==  LMP_COMPID_BROADCOM) &&
-            (vers.hci_version < HCI_PROTO_VERSION_2_0))
-        {
-            bta_dm_pm_set_sniff_policy(p_dev, (status == BTA_SYS_SCO_OPEN));
-        }
-    }
-
     /* find if there is an power mode entry for the service */
     for(i=1; i<=p_bta_dm_pm_cfg[0].app_id; i++)
     {
@@ -293,7 +278,7 @@
     ** 2. If HID connection open is received and SCO is already active.
     **     This will handle the case where HID connects when SCO already active
     */
-    if ( (btm_status == BTM_SUCCESS) &&
+    if ( BTM_IsDeviceUp() &&
          ( ((status == BTA_SYS_SCO_OPEN) || (status == BTA_SYS_SCO_CLOSE)) ||
            ((status == BTA_SYS_CONN_OPEN) && (id == BTA_ID_HH) && bta_dm_pm_is_sco_active()) ) )
     {
diff --git a/bta/fs/bta_fs_cfg.c b/bta/fs/bta_fs_cfg.c
deleted file mode 100644
index 0bfffcd..0000000
--- a/bta/fs/bta_fs_cfg.c
+++ /dev/null
@@ -1,51 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains compile-time configurable constants for the BTA File
- *  System.
- *
- ******************************************************************************/
-
-#include "bt_target.h"
-#include "bta_fs_api.h"
-
-/* Character used as path separator */
-#ifndef BTA_FS_PATH_SEPARATOR
-#define BTA_FS_PATH_SEPARATOR   ((char) 0x2f)   /* 0x2f ('/'), or 0x5c ('\') */
-#endif
-
-/* Maximum path length supported by MMI */
-#ifndef BTA_FS_PATH_LEN
-#define BTA_FS_PATH_LEN         294
-#endif
-
-#ifndef BTA_FS_FILE_LEN
-#define BTA_FS_FILE_LEN         256
-#endif
-
-const tBTA_FS_CFG bta_fs_cfg =
-{
-    BTA_FS_FILE_LEN,
-    BTA_FS_PATH_LEN,
-    BTA_FS_PATH_SEPARATOR
-};
-
-tBTA_FS_CFG *p_bta_fs_cfg = (tBTA_FS_CFG *)&bta_fs_cfg;
-
diff --git a/bta/fs/bta_fs_ci.c b/bta/fs/bta_fs_ci.c
deleted file mode 100644
index 589a591..0000000
--- a/bta/fs/bta_fs_ci.c
+++ /dev/null
@@ -1,280 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This is the implementation file for the file system call-in functions.
- *
- ******************************************************************************/
-#include <string.h>
-
-#include "bta_api.h"
-#include "bta_sys.h"
-#include "bta_fs_ci.h"
-#include "gki.h"
-#include "bd.h"
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_write
-**
-** Description      This function sends an event to IO indicating the phone
-**                  has written the number of bytes specified in the call-out
-**                  function, bta_fs_co_write(), and is ready for more data.
-**                  This function is used to control the TX data flow.
-**                  Note: The data buffer is released by the stack after
-**                        calling this function.
-**
-** Parameters       fd - file descriptor passed to the stack in the
-**                       bta_fs_ci_open call-in function.
-**                  status - BTA_FS_CO_OK or BTA_FS_CO_FAIL
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_ci_write(int fd, tBTA_FS_CO_STATUS status, UINT16 evt)
-{
-    tBTA_FS_CI_WRITE_EVT  *p_evt;
-
-    if ((p_evt = (tBTA_FS_CI_WRITE_EVT *) GKI_getbuf(sizeof(tBTA_FS_CI_WRITE_EVT))) != NULL)
-    {
-        p_evt->hdr.event = evt;
-        p_evt->fd = fd;
-        p_evt->status = status;
-
-        bta_sys_sendmsg(p_evt);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_read
-**
-** Description      This function sends an event to BTA indicating the phone has
-**                  read in the requested amount of data specified in the
-**                  bta_fs_co_read() call-out function.  It should only be called
-**                  when the requested number of bytes has been read in, or after
-**                  the end of the file has been detected.
-**
-** Parameters       fd - file descriptor passed to the stack in the
-**                       bta_fs_ci_open call-in function.
-**                  num_bytes_read - number of bytes read into the buffer
-**                      specified in the read callout-function.
-**                  status - BTA_FS_CO_OK if full buffer of data,
-**                           BTA_FS_CO_EOF if the end of file has been reached,
-**                           BTA_FS_CO_FAIL if an error has occurred.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_ci_read(int fd, UINT16 num_bytes_read, tBTA_FS_CO_STATUS status, UINT16 evt)
-{
-    tBTA_FS_CI_READ_EVT  *p_evt;
-
-    if ((p_evt = (tBTA_FS_CI_READ_EVT *) GKI_getbuf(sizeof(tBTA_FS_CI_READ_EVT))) != NULL)
-    {
-        p_evt->hdr.event = evt;
-        p_evt->fd        = fd;
-        p_evt->status    = status;
-        p_evt->num_read  = num_bytes_read;
-
-        bta_sys_sendmsg(p_evt);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_open
-**
-** Description      This function sends an event to BTA indicating the phone has
-**                  finished opening a file for reading or writing.
-**
-** Parameters       fd - file descriptor passed to the stack in the
-**                       bta_fs_ci_open call-in function.
-**                  status - BTA_FS_CO_OK if file was opened in mode specified
-**                                          in the call-out function.
-**                           BTA_FS_CO_EACCES if the file exists, but contains
-**                                          the wrong access permissions.
-**                           BTA_FS_CO_FAIL if any other error has occurred.
-**                  file_size - The total size of the file
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_ci_open(int fd, tBTA_FS_CO_STATUS status, UINT32 file_size, UINT16 evt)
-{
-    tBTA_FS_CI_OPEN_EVT  *p_evt;
-
-    if ((p_evt = (tBTA_FS_CI_OPEN_EVT *) GKI_getbuf(sizeof(tBTA_FS_CI_OPEN_EVT))) != NULL)
-    {
-        p_evt->hdr.event = evt;
-        p_evt->fd        = fd;
-        p_evt->status    = status;
-        p_evt->file_size = file_size;
-        p_evt->p_file    = NULL;
-
-        bta_sys_sendmsg(p_evt);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_direntry
-**
-** Description      This function is called in response to the
-**                  bta_fs_co_getdirentry call-out function.
-**
-** Parameters       status - BTA_FS_CO_OK if p_entry points to a valid entry.
-**                           BTA_FS_CO_EODIR if no more entries (p_entry is ignored).
-**                           BTA_FS_CO_FAIL if any errors have occurred.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_ci_direntry(tBTA_FS_CO_STATUS status, UINT16 evt)
-{
-    tBTA_FS_CI_GETDIR_EVT  *p_evt;
-
-    if ((p_evt = (tBTA_FS_CI_GETDIR_EVT *)GKI_getbuf(sizeof(tBTA_FS_CI_GETDIR_EVT))) != NULL)
-    {
-        p_evt->hdr.event = evt;
-        p_evt->status = status;
-        bta_sys_sendmsg(p_evt);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_resume
-**
-** Description      This function is called in response to the
-**                  bta_fs_co_resume call-out function.
-**
-** Parameters       p_sess_info - the stored session ID and related information.
-**                  timeout - the timeout for this suspended session.
-**                  ssn     - the stored session sequence number.
-**                  info    - the stored BTA specific information (like last active operation).
-**                  status  - BTA_FS_CO_OK if p_entry points to a valid entry.
-**                            BTA_FS_CO_FAIL if any errors have occurred.
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_ci_resume (BD_ADDR_PTR p_addr, UINT8 *p_sess_info,
-                       UINT32 timeout, UINT32 offset, UINT8 ssn, UINT8 info,
-                       tBTA_FS_CO_STATUS status, UINT16 evt)
-{
-    tBTA_FS_CI_RESUME_EVT  *p_evt;
-    UINT16  size = sizeof(tBTA_FS_CI_RESUME_EVT) + sizeof(BD_ADDR);
-
-    if ((p_evt = (tBTA_FS_CI_RESUME_EVT *)GKI_getbuf(size)) != NULL)
-    {
-        p_evt->p_addr       = NULL;
-        if (p_addr != NULL)
-        {
-            p_evt->p_addr   = (BD_ADDR_PTR)(p_evt + 1);
-            bdcpy(p_evt->p_addr, p_addr);
-        }
-        p_evt->hdr.event    = evt;
-        p_evt->p_sess_info  = p_sess_info;
-        p_evt->timeout      = timeout;
-        p_evt->offset       = offset;
-        p_evt->ssn          = ssn;
-        p_evt->info         = info;
-        p_evt->status       = status;
-        bta_sys_sendmsg(p_evt);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_action
-**
-** Description      This function is called in response to one of the action
-**                  call-out functions: bta_fs_co_copy, bta_fs_co_rename or
-**                  bta_fs_co_set_perms.
-**
-** Parameters       status  - BTA_FS_CO_OK if the action is succession.
-**                            BTA_FS_CO_FAIL if any errors have occurred.
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_ci_action(tBTA_FS_CO_STATUS status, UINT16 evt)
-{
-    tBTA_FS_CI_ACTION_EVT  *p_evt;
-
-    if ((p_evt = (tBTA_FS_CI_ACTION_EVT *) GKI_getbuf(sizeof(tBTA_FS_CI_ACTION_EVT))) != NULL)
-    {
-        p_evt->hdr.event = evt;
-        p_evt->status    = status;
-
-        bta_sys_sendmsg(p_evt);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_resume_op
-**
-** Description      This function sends an event to BTA indicating the phone has
-**                  finished opening a file for reading or writing on resume.
-**
-** Parameters       fd - file descriptor passed to the stack in the
-**                       bta_fs_ci_open call-in function.
-**                  status - BTA_FS_CO_OK if file was opened in mode specified
-**                                          in the call-out function.
-**                           BTA_FS_CO_EACCES if the file exists, but contains
-**                                          the wrong access permissions.
-**                           BTA_FS_CO_FAIL if any other error has occurred.
-**                  p_file - The file name associated with fd
-**                  file_size - The total size of the file
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_ci_resume_op(int fd, tBTA_FS_CO_STATUS status, const char *p_file,
-                         UINT32 file_size, UINT16 evt)
-{
-    tBTA_FS_CI_OPEN_EVT  *p_evt;
-    UINT16  file_len = strlen(p_file) + 1;
-    UINT16  size = sizeof(tBTA_FS_CI_OPEN_EVT) + file_len;
-    char *p;
-
-    if ((p_evt = (tBTA_FS_CI_OPEN_EVT *) GKI_getbuf(size)) != NULL)
-    {
-        p_evt->hdr.event = evt;
-        p_evt->fd        = fd;
-        p_evt->status    = status;
-        p_evt->file_size = file_size;
-        p   = (char *)(p_evt + 1);
-        BCM_STRNCPY_S (p, file_len, p_file, file_len-1);
-        p[file_len] = '\0';
-        p_evt->p_file    = (const char *)p;
-
-        bta_sys_sendmsg(p_evt);
-    }
-}
diff --git a/bta/gatt/bta_gattc_act.c b/bta/gatt/bta_gattc_act.c
index 546a56f..38d05a4 100755
--- a/bta/gatt/bta_gattc_act.c
+++ b/bta/gatt/bta_gattc_act.c
@@ -22,12 +22,12 @@
  *  machine.
  *
  ******************************************************************************/
+#define LOG_TAG "bt_bta_gattc"
 
 #include "bt_target.h"
 
 #include "utl.h"
 #include "gki.h"
-#include "bd.h"
 #include "bta_sys.h"
 
 #include "bta_gattc_int.h"
@@ -39,6 +39,8 @@
 
 #include <string.h>
 
+#include "osi/include/log.h"
+
 #if BTA_GATT_INCLUDED && BLE_INCLUDED == TRUE
 
 /*****************************************************************************
@@ -563,8 +565,11 @@
         /* always call open to hold a connection */
         if (!GATT_Connect(p_data->client_if, p_data->remote_bda, FALSE, p_data->transport))
         {
+            uint8_t *bda = (uint8_t *)p_data->remote_bda;
             status = BTA_GATT_ERROR;
-            APPL_TRACE_ERROR("bta_gattc_init_bk_conn failed");
+            APPL_TRACE_ERROR("%s unable to connect to remote bd_addr:%02x:%02x:%02x:%02x:%02x:%02x",
+                __func__, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
+
         }
         else
         {
@@ -1025,7 +1030,7 @@
         /* clean up cache */
         if(p_clcb->p_srcb && p_clcb->p_srcb->p_srvc_cache)
         {
-            while (p_clcb->p_srcb->cache_buffer.p_first)
+            while (!GKI_queue_is_empty(&p_clcb->p_srcb->cache_buffer))
             {
                 GKI_freebuf (GKI_dequeue (&p_clcb->p_srcb->cache_buffer));
             }
@@ -1898,7 +1903,7 @@
         /* in all other cases, mark it and delete the cache */
         if (p_srvc_cb->p_srvc_cache != NULL)
         {
-            while (p_srvc_cb->cache_buffer.p_first)
+            while (!GKI_queue_is_empty(&p_srvc_cb->cache_buffer))
                 GKI_freebuf (GKI_dequeue (&p_srvc_cb->cache_buffer));
 
             p_srvc_cb->p_srvc_cache = NULL;
@@ -2304,7 +2309,7 @@
                 /* if listen to all */
                 else
                 {
-                    APPL_TRACE_ERROR("Listen For All now");
+                    LOG_DEBUG("Listen For All now");
                     /* go through all connected device and send
                     callback for all connected slave connection */
                     bta_gattc_process_listen_all(p_msg->api_listen.client_if);
diff --git a/bta/gatt/bta_gattc_api.c b/bta/gatt/bta_gattc_api.c
index a91b20e..36e7b7d 100644
--- a/bta/gatt/bta_gattc_api.c
+++ b/bta/gatt/bta_gattc_api.c
@@ -976,7 +976,7 @@
 
     if (!p_char_id)
     {
-        APPL_TRACE_ERROR("deregistration failed, unknow char id");
+        APPL_TRACE_ERROR("%s deregistration failed, unknown char id", __func__);
         return status;
     }
 
@@ -988,7 +988,8 @@
                 !memcmp(p_clreg->notif_reg[i].remote_bda, bda, BD_ADDR_LEN) &&
                 bta_gattc_charid_compare(&p_clreg->notif_reg[i].char_id, p_char_id))
             {
-                APPL_TRACE_DEBUG("Deregistered.");
+                APPL_TRACE_DEBUG("%s deregistered bd_addr:%02x:%02x:%02x:%02x:%02x:%02x",
+                    __func__, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
                 memset(&p_clreg->notif_reg[i], 0, sizeof(tBTA_GATTC_NOTIF_REG));
                 status = BTA_GATT_OK;
                 break;
@@ -997,13 +998,14 @@
         if (i == BTA_GATTC_NOTIF_REG_MAX)
         {
             status = BTA_GATT_ERROR;
-
-            APPL_TRACE_ERROR("registration not found");
+            APPL_TRACE_ERROR("%s registration not found bd_addr:%02x:%02x:%02x:%02x:%02x:%02x",
+                __func__, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
         }
     }
     else
     {
-        APPL_TRACE_ERROR("Client_if: %d Not Registered", client_if);
+        APPL_TRACE_ERROR("%s client_if: %d not registered bd_addr:%02x:%02x:%02x:%02x:%02x:%02x",
+            __func__, client_if, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
     }
 
     return status;
diff --git a/bta/gatt/bta_gattc_cache.c b/bta/gatt/bta_gattc_cache.c
index db9ebb6..0f41f7f 100644
--- a/bta/gatt/bta_gattc_cache.c
+++ b/bta/gatt/bta_gattc_cache.c
@@ -37,6 +37,9 @@
 #include "btm_api.h"
 #include "btm_ble_api.h"
 
+#define LOG_TAG "bt_bta_gattc"
+#include "osi/include/log.h"
+
 static void bta_gattc_char_dscpt_disc_cmpl(UINT16 conn_id, tBTA_GATTC_SERV *p_srvc_cb);
 static tBTA_GATT_STATUS bta_gattc_sdp_service_disc(UINT16 conn_id, tBTA_GATTC_SERV *p_server_cb);
 
@@ -171,7 +174,7 @@
 {
     tBTA_GATT_STATUS    status = BTA_GATT_OK;
 
-    while (p_srvc_cb->cache_buffer.p_first)
+    while (!GKI_queue_is_empty(&p_srvc_cb->cache_buffer))
         GKI_freebuf (GKI_dequeue (&p_srvc_cb->cache_buffer));
 
     utl_freebuf((void **)&p_srvc_cb->p_srvc_list);
@@ -598,7 +601,7 @@
         }
     }
     /* no service found at all, the end of server discovery*/
-    APPL_TRACE_ERROR("No More Service found");
+    LOG_WARN("%s no more services found", __func__);
 
 #if (defined BTA_GATT_DEBUG && BTA_GATT_DEBUG == TRUE)
     bta_gattc_display_cache_server(p_srvc_cb->p_srvc_cache);
@@ -1495,7 +1498,7 @@
     APPL_TRACE_ERROR("bta_gattc_rebuild_cache");
     if (attr_index == 0)
     {
-        while (p_srvc_cb->cache_buffer.p_first)
+        while (!GKI_queue_is_empty(&p_srvc_cb->cache_buffer))
             GKI_freebuf (GKI_dequeue (&p_srvc_cb->cache_buffer));
 
         if (bta_gattc_alloc_cache_buf(p_srvc_cb) == NULL)
diff --git a/bta/gatt/bta_gattc_ci.c b/bta/gatt/bta_gattc_ci.c
index 533955a..f6d9347 100644
--- a/bta/gatt/bta_gattc_ci.c
+++ b/bta/gatt/bta_gattc_ci.c
@@ -32,7 +32,6 @@
 #include "bta_sys.h"
 #include "bta_gattc_ci.h"
 #include "gki.h"
-#include "bd.h"
 #include "utl.h"
 
 /*******************************************************************************
diff --git a/bta/gatt/bta_gattc_utils.c b/bta/gatt/bta_gattc_utils.c
index db4b6a3..bffbc4c 100644
--- a/bta/gatt/bta_gattc_utils.c
+++ b/bta/gatt/bta_gattc_utils.c
@@ -32,8 +32,8 @@
 #include "bta_sys.h"
 #include "bta_gattc_int.h"
 #include "l2c_api.h"
-#include "bd.h"
 
+#define LOG_TAG "bt_bta_gattc"
 /*****************************************************************************
 **  Constants
 *****************************************************************************/
@@ -410,7 +410,7 @@
 
     if (p_tcb != NULL)
     {
-        while (p_tcb->cache_buffer.p_first)
+        while (!GKI_queue_is_empty(&p_tcb->cache_buffer))
             GKI_freebuf (GKI_dequeue (&p_tcb->cache_buffer));
 
         utl_freebuf((void **)&p_tcb->p_srvc_list);
@@ -710,7 +710,10 @@
     }
     if (!add)
     {
-        APPL_TRACE_ERROR("Do not find the bg connection mask for the remote device");
+        uint8_t *bda = (uint8_t *)remote_bda_ptr;
+        APPL_TRACE_ERROR("%s unable to find the bg connection mask for"
+            " bd_addr:%02x:%02x:%02x:%02x:%02x:%02x", __func__,
+            bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
         return FALSE;
     }
     else /* adding a new device mask */
diff --git a/bta/gatt/bta_gatts_act.c b/bta/gatt/bta_gatts_act.c
index 7dd3581..bdd7f29 100644
--- a/bta/gatt/bta_gatts_act.c
+++ b/bta/gatt/bta_gatts_act.c
@@ -113,7 +113,6 @@
 {
     UINT8 index=0;
     tBTA_GATTS_HNDL_RANGE handle_range;
-    tBTA_GATT_STATUS    status = BTA_GATT_OK;
 
     if (p_cb->enabled)
     {
@@ -137,7 +136,6 @@
         if (!GATTS_NVRegister(&bta_gatts_nv_cback))
         {
             APPL_TRACE_ERROR("BTA GATTS NV register failed.");
-            status = BTA_GATT_ERROR;
         }
     }
 }
diff --git a/bta/gatt/bta_gatts_utils.c b/bta/gatt/bta_gatts_utils.c
index e7ac1e3..c5deef3 100644
--- a/bta/gatt/bta_gatts_utils.c
+++ b/bta/gatt/bta_gatts_utils.c
@@ -31,7 +31,6 @@
 #include "gki.h"
 #include "bta_sys.h"
 #include "bta_gatts_int.h"
-#include "bd.h"
 
 static const UINT8  base_uuid[LEN_UUID_128] = {0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80,
     0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
diff --git a/bta/hf_client/bta_hf_client_act.c b/bta/hf_client/bta_hf_client_act.c
index 5b70db2..880baca 100644
--- a/bta/hf_client/bta_hf_client_act.c
+++ b/bta/hf_client/bta_hf_client_act.c
@@ -24,7 +24,6 @@
  ******************************************************************************/
 
 #include "bta_api.h"
-#include "bd.h"
 #include "bta_hf_client_api.h"
 #include "bta_hf_client_int.h"
 #include "bta_dm_int.h"
diff --git a/bta/hf_client/bta_hf_client_api.c b/bta/hf_client/bta_hf_client_api.c
index 2365e9d..2d95ca3 100644
--- a/bta/hf_client/bta_hf_client_api.c
+++ b/bta/hf_client/bta_hf_client_api.c
@@ -27,7 +27,6 @@
 #include <string.h>
 #include "bta_hf_client_api.h"
 #include "bta_hf_client_int.h"
-#include "bd.h"
 
 /*****************************************************************************
 **  Constants and data types
@@ -56,7 +55,7 @@
 ** Returns          BTA_SUCCESS if OK, BTA_FAILURE otherwise.
 **
 *******************************************************************************/
-BTA_API tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK *p_cback)
+tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK *p_cback)
 {
     tBTA_HF_CLIENT_API_ENABLE  *p_buf;
 
@@ -89,7 +88,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientDisable(void)
+void BTA_HfClientDisable(void)
 {
     BT_HDR  *p_buf;
 
@@ -110,8 +109,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientRegister(tBTA_SEC sec_mask, tBTA_HF_CLIENT_FEAT features,
-                                                        char *p_service_name)
+void BTA_HfClientRegister(tBTA_SEC sec_mask, tBTA_HF_CLIENT_FEAT features,
+                          char *p_service_name)
 {
     tBTA_HF_CLIENT_API_REGISTER    *p_buf;
 
@@ -143,7 +142,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientDeregister(UINT16 handle)
+void BTA_HfClientDeregister(UINT16 handle)
 {
     BT_HDR  *p_buf;
 
@@ -168,7 +167,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientOpen(UINT16 handle, BD_ADDR bd_addr, tBTA_SEC sec_mask)
+void BTA_HfClientOpen(UINT16 handle, BD_ADDR bd_addr, tBTA_SEC sec_mask)
 {
     tBTA_HF_CLIENT_API_OPEN  *p_buf;
 
@@ -193,7 +192,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientClose(UINT16 handle)
+void BTA_HfClientClose(UINT16 handle)
 {
     BT_HDR  *p_buf;
 
@@ -216,7 +215,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientAudioOpen(UINT16 handle)
+void BTA_HfClientAudioOpen(UINT16 handle)
 {
     BT_HDR  *p_buf;
 
@@ -239,7 +238,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientAudioClose(UINT16 handle)
+void BTA_HfClientAudioClose(UINT16 handle)
 {
     BT_HDR  *p_buf;
 
@@ -261,7 +260,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientSendAT(UINT16 handle, tBTA_HF_CLIENT_AT_CMD_TYPE at, UINT32 val1, UINT32 val2, const char *str)
+void BTA_HfClientSendAT(UINT16 handle, tBTA_HF_CLIENT_AT_CMD_TYPE at, UINT32 val1, UINT32 val2, const char *str)
 {
     tBTA_HF_CLIENT_DATA_VAL  *p_buf;
 
diff --git a/bta/hf_client/bta_hf_client_rfc.c b/bta/hf_client/bta_hf_client_rfc.c
index 43a3e0c..829c3a5 100644
--- a/bta/hf_client/bta_hf_client_rfc.c
+++ b/bta/hf_client/bta_hf_client_rfc.c
@@ -28,7 +28,6 @@
 #include "bta_api.h"
 #include "bta_hf_client_int.h"
 #include "port_api.h"
-#include "bd.h"
 #include "bt_utils.h"
 
 /*******************************************************************************
diff --git a/bta/hf_client/bta_hf_client_sco.c b/bta/hf_client/bta_hf_client_sco.c
index eb0929c..b0b74b7 100644
--- a/bta/hf_client/bta_hf_client_sco.c
+++ b/bta/hf_client/bta_hf_client_sco.c
@@ -19,7 +19,6 @@
 
 #include "bta_hf_client_int.h"
 #include <bt_trace.h>
-#include <bd.h>
 #include <string.h>
 #include "bt_utils.h"
 
diff --git a/bta/hh/bta_hh_api.c b/bta/hh/bta_hh_api.c
index 58090f6..1fdbc29 100644
--- a/bta/hh/bta_hh_api.c
+++ b/bta/hh/bta_hh_api.c
@@ -35,6 +35,9 @@
 #include "l2c_api.h"
 #include "utl.h"
 
+#define LOG_TAG "bt_bta_hh"
+#include "osi/include/log.h"
+
 /*****************************************************************************
 **  Constants
 *****************************************************************************/
@@ -65,7 +68,7 @@
     /* register with BTA system manager */
     bta_sys_register(BTA_ID_HH, &bta_hh_reg);
 
-    APPL_TRACE_ERROR("Calling BTA_HhEnable");
+    LOG_INFO("%s sec_mask:0x%x p_cback:%p", __func__, sec_mask, p_cback);
     p_buf = (tBTA_HH_API_ENABLE *)GKI_getbuf((UINT16)sizeof(tBTA_HH_API_ENABLE));
 
     if (p_buf != NULL)
diff --git a/bta/hh/bta_hh_int.h b/bta/hh/bta_hh_int.h
index ac9bb61..2db0cf1 100644
--- a/bta/hh/bta_hh_int.h
+++ b/bta/hh/bta_hh_int.h
@@ -26,7 +26,6 @@
 #define BTA_HH_INT_H
 
 #include "bta_sys.h"
-#include "bd.h"
 #include "utl.h"
 #include "bta_hh_api.h"
 
@@ -234,7 +233,7 @@
 #define BTA_HH_GET_LE_DEV_HDL(x)        (UINT8)(((x)  + 1) << 4)
 /* check to see if th edevice handle is a LE device handle */
 #define BTA_HH_IS_LE_DEV_HDL(x)        ((x) & 0xf0)
-#define BTA_HH_IS_LE_DEV_HDL_VALID(x)  (((x)>>4) < BTA_HH_LE_MAX_KNOWN)
+#define BTA_HH_IS_LE_DEV_HDL_VALID(x)  (((x)>>4) <= BTA_HH_LE_MAX_KNOWN)
 #endif
 
 /* device control block */
diff --git a/bta/hh/bta_hh_le.c b/bta/hh/bta_hh_le.c
index df541af..99a5627 100644
--- a/bta/hh/bta_hh_le.c
+++ b/bta/hh/bta_hh_le.c
@@ -31,6 +31,9 @@
 #include "btm_int.h"
 #include "utl.h"
 
+#define LOG_TAG "bt_bta_hh"
+#include "osi/include/log.h"
+
 #ifndef BTA_HH_LE_RECONN
 #define BTA_HH_LE_RECONN    TRUE
 #endif
@@ -594,7 +597,7 @@
 **
 ** Function         bta_hh_le_read_char_dscrpt
 **
-** Description      read cahracteristic descriptor
+** Description      read characteristic descriptor
 **
 *******************************************************************************/
 tBTA_HH_STATUS bta_hh_le_read_char_dscrpt(tBTA_HH_DEV_CB *p_cb, UINT16 srvc_uuid, UINT8 srvc_inst_id,
@@ -626,8 +629,8 @@
     else
     {
 #if BTA_HH_DEBUG == TRUE
-        APPL_TRACE_ERROR("bta_hh_le_read_char_dscrpt: No such descrpt exists: %s(0x%04x)",
-            bta_hh_uuid_to_str(char_descp_uuid), char_descp_uuid);
+      LOG_WARN("%s No descriptor exists: %s(0x%04x)", __func__,
+          bta_hh_uuid_to_str(char_descp_uuid), char_descp_uuid);
 #endif
     }
     return status;
@@ -1139,7 +1142,7 @@
     }
     while (1);
 
-    APPL_TRACE_ERROR("all report searched");
+    LOG_INFO("%s all BLE reports searched", __func__);
     bta_hh_le_read_rpt_ref_descr(p_dev_cb,
                                  &p_dev_cb->hid_srvc[p_dev_cb->cur_srvc_index].report[0]);
 
@@ -2666,7 +2669,8 @@
             break;
 
         default:
-            APPL_TRACE_ERROR("unsupported trsanction for LE HID device: %d", p_data->api_sndcmd.t_type);
+            APPL_TRACE_ERROR("%s unsupported transaction for BLE HID device: %d",
+                __func__, p_data->api_sndcmd.t_type);
             break;
     }
 }
diff --git a/bta/hl/bta_hl_act.c b/bta/hl/bta_hl_act.c
index b4c65c3..f9408eb 100644
--- a/bta/hl/bta_hl_act.c
+++ b/bta/hl/bta_hl_act.c
@@ -36,7 +36,6 @@
 #include "bta_hl_api.h"
 #include "bta_hl_int.h"
 #include "utl.h"
-#include "bd.h"
 #include "mca_defs.h"
 #include "mca_api.h"
 
diff --git a/bta/hl/bta_hl_api.c b/bta/hl/bta_hl_api.c
index 86cb17f..917d816 100644
--- a/bta/hl/bta_hl_api.c
+++ b/bta/hl/bta_hl_api.c
@@ -30,7 +30,6 @@
 #if defined(HL_INCLUDED) && (HL_INCLUDED == TRUE)
 
 #include "gki.h"
-#include "bd.h"
 #include "bta_hl_api.h"
 #include "bta_hl_int.h"
 
diff --git a/bta/hl/bta_hl_ci.c b/bta/hl/bta_hl_ci.c
index 7226b8b..792b08f 100644
--- a/bta/hl/bta_hl_ci.c
+++ b/bta/hl/bta_hl_ci.c
@@ -47,9 +47,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_ci_get_tx_data(  tBTA_HL_MDL_HANDLE mdl_handle,
-                                            tBTA_HL_STATUS status,
-                                            UINT16 evt )
+extern void bta_hl_ci_get_tx_data(  tBTA_HL_MDL_HANDLE mdl_handle,
+                                    tBTA_HL_STATUS status,
+                                    UINT16 evt )
 {
     tBTA_HL_CI_GET_PUT_DATA  *p_evt;
 
@@ -82,9 +82,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_ci_put_rx_data(  tBTA_HL_MDL_HANDLE mdl_handle,
-                                            tBTA_HL_STATUS status,
-                                            UINT16 evt )
+extern void bta_hl_ci_put_rx_data(  tBTA_HL_MDL_HANDLE mdl_handle,
+                                    tBTA_HL_STATUS status,
+                                    UINT16 evt )
 {
     tBTA_HL_CI_GET_PUT_DATA  *p_evt;
 #if  (BTA_HL_DEBUG == TRUE)
@@ -117,9 +117,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_ci_get_echo_data(  tBTA_HL_MCL_HANDLE mcl_handle,
-                                              tBTA_HL_STATUS status,
-                                              UINT16 evt )
+extern void bta_hl_ci_get_echo_data(  tBTA_HL_MCL_HANDLE mcl_handle,
+                                      tBTA_HL_STATUS status,
+                                      UINT16 evt )
 {
     tBTA_HL_CI_ECHO_DATA  *p_evt;
 
@@ -152,9 +152,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_ci_put_echo_data(  tBTA_HL_MCL_HANDLE mcl_handle,
-                                              tBTA_HL_STATUS status,
-                                              UINT16 evt )
+extern void bta_hl_ci_put_echo_data(  tBTA_HL_MCL_HANDLE mcl_handle,
+                                      tBTA_HL_STATUS status,
+                                      UINT16 evt )
 {
     tBTA_HL_CI_ECHO_DATA  *p_evt;
 
@@ -171,4 +171,3 @@
         bta_sys_sendmsg(p_evt);
     }
 }
-
diff --git a/bta/hl/bta_hl_int.h b/bta/hl/bta_hl_int.h
index 2b5c914..32c2a7d 100644
--- a/bta/hl/bta_hl_int.h
+++ b/bta/hl/bta_hl_int.h
@@ -27,7 +27,6 @@
 
 #include "bt_target.h"
 #include "bta_sys.h"
-#include "obx_api.h"
 #include "bta_hl_api.h"
 #include "bta_hl_co.h"
 #include "l2cdefs.h"
diff --git a/bta/hl/bta_hl_main.c b/bta/hl/bta_hl_main.c
index 7f08752..7d7cc83 100644
--- a/bta/hl/bta_hl_main.c
+++ b/bta/hl/bta_hl_main.c
@@ -33,7 +33,6 @@
 #include "bta_hl_int.h"
 #include "gki.h"
 #include "utl.h"
-#include "bd.h"
 #include "l2c_api.h"
 #include "mca_defs.h"
 
@@ -1565,13 +1564,11 @@
     tBTA_HL_APP_CB      *p_acb = BTA_HL_GET_APP_CB_PTR( app_idx);
     tBTA_HL_MCL_CB      *p_mcb =  BTA_HL_GET_MCL_CB_PTR( app_idx,  mcl_idx);
     tBTA_HL_SDP         *p_sdp=NULL;
-    tBTA_HL_SDP_OPER    sdp_oper;
     UINT16              event;
     BOOLEAN             release_sdp_buf=FALSE;
     UNUSED(p_cb);
 
     event = p_data->hdr.event;
-    sdp_oper = p_mcb->sdp_oper;
 
     if ( event == BTA_HL_SDP_QUERY_OK_EVT)
     {
diff --git a/bta/hl/bta_hl_sdp.c b/bta/hl/bta_hl_sdp.c
index 14171fa..f5b3fd1 100644
--- a/bta/hl/bta_hl_sdp.c
+++ b/bta/hl/bta_hl_sdp.c
@@ -39,7 +39,7 @@
                                       tBTA_HL_SUP_FEATURE_LIST_ELEM *p_list)
 {
     tSDP_DISC_ATTR  *p_sattr;
-    UINT8           seq_len, item_cnt;
+    UINT8           item_cnt;
     UINT8           list_cnt=0;
     BOOLEAN         status=TRUE;
 
@@ -50,7 +50,7 @@
         {
             return(FALSE);
         }
-        seq_len =SDP_DISC_ATTR_LEN(p_attr->attr_len_type);
+        SDP_DISC_ATTR_LEN(p_attr->attr_len_type);
         item_cnt=0;
 
         for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr && (item_cnt < 4) ; p_sattr = p_sattr->p_next_attr)
diff --git a/bta/hl/bta_hl_utils.c b/bta/hl/bta_hl_utils.c
index 6c67e2f..0a0f326 100644
--- a/bta/hl/bta_hl_utils.c
+++ b/bta/hl/bta_hl_utils.c
@@ -32,8 +32,6 @@
 
 #include "gki.h"
 #include "utl.h"
-#include "bd.h"
-#include "bta_fs_api.h"
 #include "bta_hl_int.h"
 #include "bta_hl_co.h"
 #include "mca_defs.h"
@@ -147,7 +145,7 @@
 {
     UINT8 pool_id;
 
-    if (max_tx_size > GKI_get_pool_bufsize (OBX_FCR_TX_POOL_ID))
+    if (max_tx_size > GKI_get_pool_bufsize (HCI_ACL_POOL_ID))
     {
         pool_id = BTA_HL_LRG_DATA_POOL_ID;
     }
@@ -158,7 +156,7 @@
 
 #if BTA_HL_DEBUG == TRUE
     APPL_TRACE_DEBUG("bta_hl_set_user_rx_pool_id pool_id=%d max_tx_size=%d default_ertm_pool_size=%d",
-                      pool_id, max_tx_size, GKI_get_pool_bufsize (OBX_FCR_TX_POOL_ID));
+                      pool_id, max_tx_size, GKI_get_pool_bufsize (HCI_ACL_POOL_ID));
 #endif
 
     return pool_id;
@@ -178,7 +176,7 @@
 {
     UINT8 pool_id;
 
-    if (mtu > GKI_get_pool_bufsize (OBX_FCR_RX_POOL_ID))
+    if (mtu > GKI_get_pool_bufsize (HCI_ACL_POOL_ID))
     {
         pool_id = BTA_HL_LRG_DATA_POOL_ID;
     }
@@ -189,7 +187,7 @@
 
 #if BTA_HL_DEBUG == TRUE
     APPL_TRACE_DEBUG("bta_hl_set_user_rx_pool_id pool_id=%d mtu=%d default_ertm_pool_size=%d",
-                      pool_id, mtu, GKI_get_pool_bufsize (OBX_FCR_RX_POOL_ID));
+                      pool_id, mtu, GKI_get_pool_bufsize (HCI_ACL_POOL_ID));
 #endif
 
     return pool_id;
@@ -1169,11 +1167,10 @@
 {
     BOOLEAN found=FALSE;
     UINT8 i;
-    tBTA_HL_MCL_CB  *p_mcb;
 
     for (i=0; i < BTA_HL_NUM_MCLS ; i ++)
     {
-        p_mcb = BTA_HL_GET_MCL_CB_PTR(app_idx, i);
+        BTA_HL_GET_MCL_CB_PTR(app_idx, i);
 
         if (bta_hl_cb.acb[app_idx].mcb[i].in_use &&
             (!memcmp (bta_hl_cb.acb[app_idx].mcb[i].bd_addr, p_bd_addr, BD_ADDR_LEN)))
diff --git a/bta/include/bd.h b/bta/include/bd.h
deleted file mode 100644
index 33c3de1..0000000
--- a/bta/include/bd.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  BD address services.
- *
- ******************************************************************************/
-#ifndef BD_H
-#define BD_H
-
-/*****************************************************************************
-**  Constants and data types
-*****************************************************************************/
-
-/* bd addr length and type */
-#ifndef BD_ADDR_LEN
-#define BD_ADDR_LEN     6
-typedef UINT8 BD_ADDR[BD_ADDR_LEN];
-#endif
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/* global constant for "any" bd addr */
-extern const BD_ADDR bd_addr_any;
-extern const BD_ADDR bd_addr_null;
-/*****************************************************************************
-**  Function Declarations
-*****************************************************************************/
-
-/*******************************************************************************
-**
-** Function         bdcpy
-**
-** Description      Copy bd addr b to a.
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-extern void bdcpy(BD_ADDR a, const BD_ADDR b);
-
-/*******************************************************************************
-**
-** Function         bdcmp
-**
-** Description      Compare bd addr b to a.
-**
-**
-** Returns          Zero if b==a, nonzero otherwise (like memcmp).
-**
-*******************************************************************************/
-extern int bdcmp(const BD_ADDR a, const BD_ADDR b);
-
-/*******************************************************************************
-**
-** Function         bdcmpany
-**
-** Description      Compare bd addr to "any" bd addr.
-**
-**
-** Returns          Zero if a equals bd_addr_any.
-**
-*******************************************************************************/
-extern int bdcmpany(const BD_ADDR a);
-
-/*******************************************************************************
-**
-** Function         bdsetany
-**
-** Description      Set bd addr to "any" bd addr.
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-extern void bdsetany(BD_ADDR a);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* BD_H */
-
diff --git a/bta/include/bta_ag_api.h b/bta/include/bta_ag_api.h
index 62342cb..24bbc87 100644
--- a/bta/include/bta_ag_api.h
+++ b/bta/include/bta_ag_api.h
@@ -114,6 +114,8 @@
 typedef UINT16 tBTA_AG_PEER_FEAT;
 
 /* HFP peer supported codec masks */
+// TODO(google) This should use common definitions
+// in hci/include/hci_audio.h
 #define BTA_AG_CODEC_NONE           BTM_SCO_CODEC_NONE
 #define BTA_AG_CODEC_CVSD           BTM_SCO_CODEC_CVSD      /* CVSD */
 #define BTA_AG_CODEC_MSBC           BTM_SCO_CODEC_MSBC      /* mSBC */
@@ -397,7 +399,7 @@
 ** Returns          BTA_SUCCESS if OK, BTA_FAILURE otherwise.
 **
 *******************************************************************************/
-BTA_API tBTA_STATUS BTA_AgEnable(tBTA_AG_PARSE_MODE parse_mode, tBTA_AG_CBACK *p_cback);
+tBTA_STATUS BTA_AgEnable(tBTA_AG_PARSE_MODE parse_mode, tBTA_AG_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -409,7 +411,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AgDisable(void);
+void BTA_AgDisable(void);
 
 /*******************************************************************************
 **
@@ -421,8 +423,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AgRegister(tBTA_SERVICE_MASK services, tBTA_SEC sec_mask,
-                tBTA_AG_FEAT features, char *p_service_names[], UINT8 app_id);
+void BTA_AgRegister(tBTA_SERVICE_MASK services, tBTA_SEC sec_mask,
+                    tBTA_AG_FEAT features, char *p_service_names[], UINT8 app_id);
 
 /*******************************************************************************
 **
@@ -434,7 +436,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AgDeregister(UINT16 handle);
+void BTA_AgDeregister(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -449,7 +451,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AgOpen(UINT16 handle, BD_ADDR bd_addr, tBTA_SEC sec_mask, tBTA_SERVICE_MASK services);
+void BTA_AgOpen(UINT16 handle, BD_ADDR bd_addr, tBTA_SEC sec_mask, tBTA_SERVICE_MASK services);
 
 /*******************************************************************************
 **
@@ -462,7 +464,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AgClose(UINT16 handle);
+void BTA_AgClose(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -475,7 +477,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AgAudioOpen(UINT16 handle);
+void BTA_AgAudioOpen(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -488,7 +490,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AgAudioClose(UINT16 handle);
+void BTA_AgAudioClose(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -502,7 +504,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AgResult(UINT16 handle, tBTA_AG_RES result, tBTA_AG_RES_DATA *p_data);
+void BTA_AgResult(UINT16 handle, tBTA_AG_RES result, tBTA_AG_RES_DATA *p_data);
 
 /*******************************************************************************
 **
@@ -516,12 +518,10 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AgSetCodec(UINT16 handle, tBTA_AG_PEER_CODEC codec);
+void BTA_AgSetCodec(UINT16 handle, tBTA_AG_PEER_CODEC codec);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif /* BTA_AG_API_H */
-
-
diff --git a/bta/include/bta_ag_ci.h b/bta/include/bta_ag_ci.h
index 3bc0e53..5ce2e55 100644
--- a/bta/include/bta_ag_ci.h
+++ b/bta/include/bta_ag_ci.h
@@ -45,7 +45,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_ag_ci_rx_write(UINT16 handle, char *p_data, UINT16 len);
+extern void bta_ag_ci_rx_write(UINT16 handle, char *p_data, UINT16 len);
 
 /******************************************************************************
 **
@@ -58,7 +58,7 @@
 ** Returns          void
 **
 ******************************************************************************/
-BTA_API extern void bta_ag_ci_slc_ready(UINT16 handle);
+extern void bta_ag_ci_slc_ready(UINT16 handle);
 
 // btla-specific ++
 /******************************************************************************
@@ -71,7 +71,7 @@
 ** Returns          void
 **
 ******************************************************************************/
-BTA_API extern void bta_ag_ci_wbs_command (UINT16 handle, char *p_data, UINT16 len);
+extern void bta_ag_ci_wbs_command (UINT16 handle, char *p_data, UINT16 len);
 // btla-specific --
 
 #ifdef __cplusplus
@@ -79,4 +79,3 @@
 #endif
 
 #endif /* BTA_AG_CI_H */
-
diff --git a/bta/include/bta_ag_co.h b/bta/include/bta_ag_co.h
index 4ef3ce7..2f52581 100644
--- a/bta/include/bta_ag_co.h
+++ b/bta/include/bta_ag_co.h
@@ -25,12 +25,7 @@
 #define BTA_AG_CO_H
 
 #include "bta_ag_api.h"
-
-/* Definitions for audio state callout function "state" parameter */
-#define BTA_AG_CO_AUD_STATE_OFF         0
-#define BTA_AG_CO_AUD_STATE_OFF_XFER    1   /* Closed pending transfer of audio */
-#define BTA_AG_CO_AUD_STATE_ON          2
-#define BTA_AG_CO_AUD_STATE_SETUP       3
+#include "hci/include/hci_audio.h"
 
 /*******************************************************************************
 **
@@ -45,7 +40,7 @@
 ** Returns          Void.
 **
 *******************************************************************************/
-BTA_API extern void bta_ag_co_init(void);
+extern void bta_ag_co_init(void);
 
 /*******************************************************************************
 **
@@ -56,12 +51,8 @@
 **
 ** Parameters       handle - handle of the AG instance
 **                  state - Audio state
-**                      BTA_AG_CO_AUD_STATE_OFF      - Audio has been turned off
-**                      BTA_AG_CO_AUD_STATE_OFF_XFER - Audio is closed pending transfer
-**                      BTA_AG_CO_AUD_STATE_ON       - Audio has been turned on
-**                      BTA_AG_CO_AUD_STATE_SETUP    - Audio is about to be turned on
 **                  codec - if WBS support is compiled in, codec to going to be used is provided
-**                      and when in BTA_AG_CO_AUD_STATE_SETUP, BTM_I2SPCMConfig() must be called with
+**                      and when in SCO_STATE_SETUP, BTM_I2SPCMConfig() must be called with
 **                      the correct platform parameters.
 **                      in the other states codec type should not be ignored
 **
@@ -69,11 +60,11 @@
 **
 *******************************************************************************/
 #if (BTM_WBS_INCLUDED == TRUE )
-BTA_API extern void bta_ag_co_audio_state(UINT16 handle, UINT8 app_id, UINT8 state,
+extern void bta_ag_co_audio_state(UINT16 handle, UINT8 app_id, UINT8 state,
                                           tBTA_AG_PEER_CODEC codec);
 
 #else
-BTA_API extern void bta_ag_co_audio_state(UINT16 handle, UINT8 app_id, UINT8 state);
+extern void bta_ag_co_audio_state(UINT16 handle, UINT8 app_id, UINT8 state);
 #endif
 
 /*******************************************************************************
@@ -89,7 +80,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_ag_co_data_open(UINT16 handle, tBTA_SERVICE_ID service);
+extern void bta_ag_co_data_open(UINT16 handle, tBTA_SERVICE_ID service);
 
 /*******************************************************************************
 **
@@ -102,7 +93,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_ag_co_data_close(UINT16 handle);
+extern void bta_ag_co_data_close(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -116,7 +107,6 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_ag_co_tx_write(UINT16 handle, UINT8 *p_data, UINT16 len);
+extern void bta_ag_co_tx_write(UINT16 handle, UINT8 *p_data, UINT16 len);
 
 #endif /* BTA_AG_CO_H */
-
diff --git a/bta/include/bta_api.h b/bta/include/bta_api.h
index aef2606..f4fc9f2 100644
--- a/bta/include/bta_api.h
+++ b/bta/include/bta_api.h
@@ -25,7 +25,6 @@
 #ifndef BTA_API_H
 #define BTA_API_H
 
-#include "data_types.h"
 #include "bt_target.h"
 #include "bt_types.h"
 #include "btm_api.h"
@@ -601,10 +600,6 @@
 typedef UINT8 tBTA_DM_LINK_QUALITY_VALUE;
 
 
-/* signal strength mask */
-#define BTA_SIG_STRENGTH_RSSI_MASK          1
-#define BTA_SIG_STRENGTH_LINK_QUALITY_MASK  2
-
 typedef UINT8 tBTA_SIG_STRENGTH_MASK;
 
 
@@ -643,7 +638,6 @@
 /* Structure associated with BTA_DM_ENABLE_EVT */
 typedef struct
 {
-    BD_ADDR         bd_addr;            /* BD address of local device. */
     tBTA_STATUS    status;
 } tBTA_DM_ENABLE;
 
@@ -804,16 +798,6 @@
     UINT8           new_role;           /* the new connection role */
 } tBTA_DM_ROLE_CHG;
 
-/* Structure associated with BTA_DM_SIG_STRENGTH_EVT */
-typedef struct
-{
-    BD_ADDR         bd_addr;            /* BD address peer device. */
-    tBTA_SIG_STRENGTH_MASK mask;        /* mask for the values that are valid */
-    tBTA_DM_RSSI_VALUE  rssi_value;
-    tBTA_DM_LINK_QUALITY_VALUE link_quality_value;
-
-} tBTA_DM_SIG_STRENGTH;
-
 /* Structure associated with BTA_DM_BUSY_LEVEL_EVT */
 typedef struct
 {
@@ -924,7 +908,6 @@
     tBTA_DM_AUTHORIZE   authorize;      /* Authorization request. */
     tBTA_DM_LINK_UP     link_up;       /* ACL connection down event */
     tBTA_DM_LINK_DOWN   link_down;       /* ACL connection down event */
-    tBTA_DM_SIG_STRENGTH sig_strength;  /* rssi and link quality value */
     tBTA_DM_BUSY_LEVEL  busy_level;     /* System busy level */
     tBTA_DM_SP_CFM_REQ  cfm_req;        /* user confirm request */
     tBTA_DM_SP_KEY_NOTIF key_notif;     /* passkey notification */
@@ -1013,9 +996,6 @@
     tBTA_DM_BLE_PF_TIMEOUT_CNT found_timeout_cnt;
 } tBTA_DM_BLE_PF_FILT_PARAMS;
 
-/* Vendor Specific Command Callback */
-typedef tBTM_VSC_CMPL_CB        tBTA_VENDOR_CMPL_CBACK;
-
 /* Search callback events */
 #define BTA_DM_INQ_RES_EVT              0       /* Inquiry result for a peer device. */
 #define BTA_DM_INQ_CMPL_EVT             1       /* Inquiry complete. */
@@ -1366,7 +1346,7 @@
 **                  BTA_FAIL if internal failure.
 **
 *******************************************************************************/
-BTA_API extern tBTA_STATUS BTA_EnableBluetooth(tBTA_DM_SEC_CBACK *p_cback);
+extern tBTA_STATUS BTA_EnableBluetooth(tBTA_DM_SEC_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -1380,7 +1360,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern tBTA_STATUS BTA_DisableBluetooth(void);
+extern tBTA_STATUS BTA_DisableBluetooth(void);
 
 /*******************************************************************************
 **
@@ -1392,7 +1372,7 @@
 ** Returns          tBTA_STATUS
 **
 *******************************************************************************/
-BTA_API extern tBTA_STATUS BTA_EnableTestMode(void);
+extern tBTA_STATUS BTA_EnableTestMode(void);
 
 /*******************************************************************************
 **
@@ -1404,22 +1384,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DisableTestMode(void);
-
-/*******************************************************************************
-**
-** Function         BTA_DmIsDeviceUp
-**
-** Description      This function tests whether the Bluetooth module is up
-**                  and ready.  This is a direct execution function that
-**                  may lock task scheduling on some platforms.
-**
-**
-** Returns          TRUE if the module is ready.
-**                  FALSE if the module is not ready.
-**
-*******************************************************************************/
-BTA_API extern BOOLEAN BTA_DmIsDeviceUp(void);
+extern void BTA_DisableTestMode(void);
 
 /*******************************************************************************
 **
@@ -1431,7 +1396,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmSetDeviceName(char *p_name);
+extern void BTA_DmSetDeviceName(char *p_name);
 
 /*******************************************************************************
 **
@@ -1446,51 +1411,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmSetVisibility(tBTA_DM_DISC disc_mode, tBTA_DM_CONN conn_mode, UINT8 pairable_mode, UINT8 conn_filter);
-
-/*******************************************************************************
-**
-** Function         BTA_DmSetScanParam
-**
-** Description      This function sets the parameters for page scan and
-**                  inquiry scan.
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmSetScanParam (UINT16 page_scan_interval, UINT16 page_scan_window,
-                                  UINT16 inquiry_scan_interval, UINT16 inquiry_scan_window);
-
-/*******************************************************************************
-**
-** Function         BTA_DmSetAfhChannels
-**
-** Description      This function sets the AFH first and
-**                  last disable channel, so channels within
-**                  that range are disabled.
-**                  In order to use this API, BTM_BYPASS_AMP_AUTO_AFH must be set
-**                  to be TRUE
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmSetAfhChannels(UINT8 first, UINT8 last);
-
-
-/*******************************************************************************
-**
-** Function         BTA_DmVendorSpecificCommand
-**
-** Description      This function sends the vendor specific command
-**                  to the controller
-**
-**
-** Returns          tBTA_STATUS
-**
-*******************************************************************************/
-BTA_API extern tBTA_STATUS BTA_DmVendorSpecificCommand (UINT16 opcode, UINT8 param_len,UINT8 *p_param_buf, tBTA_VENDOR_CMPL_CBACK *p_cback);
-
+extern void BTA_DmSetVisibility(tBTA_DM_DISC disc_mode, tBTA_DM_CONN conn_mode, UINT8 pairable_mode, UINT8 conn_filter);
 
 /*******************************************************************************
 **
@@ -1506,8 +1427,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmSearch(tBTA_DM_INQ *p_dm_inq, tBTA_SERVICE_MASK services,
-                                 tBTA_DM_SEARCH_CBACK *p_cback);
+extern void BTA_DmSearch(tBTA_DM_INQ *p_dm_inq, tBTA_SERVICE_MASK services,
+                         tBTA_DM_SEARCH_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -1520,7 +1441,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmSearchCancel(void);
+extern void BTA_DmSearchCancel(void);
 
 /*******************************************************************************
 **
@@ -1533,8 +1454,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmDiscover(BD_ADDR bd_addr, tBTA_SERVICE_MASK services,
-                                   tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search);
+extern void BTA_DmDiscover(BD_ADDR bd_addr, tBTA_SERVICE_MASK services,
+                           tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search);
 
 // btla-specific ++
 /*******************************************************************************
@@ -1548,8 +1469,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmDiscoverUUID(BD_ADDR bd_addr, tSDP_UUID *uuid,
-                    tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search);
+extern void BTA_DmDiscoverUUID(BD_ADDR bd_addr, tSDP_UUID *uuid,
+                               tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search);
 
 /*******************************************************************************
 **
@@ -1566,19 +1487,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_DmIsMaster
-**
-** Description      This function checks if the local device is the master of
-**                  the link to the given device
-**
-** Returns          TRUE if master.
-**                  FALSE if not.
-**
-*******************************************************************************/
-BTA_API extern BOOLEAN BTA_DmIsMaster(BD_ADDR bd_addr);
-
-/*******************************************************************************
-**
 ** Function         BTA_DmBond
 **
 ** Description      This function initiates a bonding procedure with a peer
@@ -1589,7 +1497,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBond(BD_ADDR bd_addr);
+extern void BTA_DmBond(BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -1603,7 +1511,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBondByTransport(BD_ADDR bd_addr, tBTA_TRANSPORT transport);
+extern void BTA_DmBondByTransport(BD_ADDR bd_addr, tBTA_TRANSPORT transport);
 
 
 /*******************************************************************************
@@ -1617,7 +1525,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBondCancel(BD_ADDR bd_addr);
+extern void BTA_DmBondCancel(BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -1632,23 +1540,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmPinReply(BD_ADDR bd_addr, BOOLEAN accept, UINT8 pin_len,
-                                   UINT8 *p_pin);
-
-/*******************************************************************************
-**
-** Function         BTA_DmLinkPolicy
-**
-** Description      This function sets/clears the link policy mask to the given
-**                  bd_addr.
-**                  If clearing the sniff or park mode mask, the link is put
-**                  in active mode.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmLinkPolicy(BD_ADDR bd_addr, tBTA_DM_LP_MASK policy_mask,
-                                     BOOLEAN set);
+extern void BTA_DmPinReply(BD_ADDR bd_addr, BOOLEAN accept, UINT8 pin_len,
+                           UINT8 *p_pin);
 
 #if (BTM_OOB_INCLUDED == TRUE)
 /*******************************************************************************
@@ -1661,7 +1554,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmLocalOob(void);
+extern void BTA_DmLocalOob(void);
 #endif /* BTM_OOB_INCLUDED */
 
 /*******************************************************************************
@@ -1674,19 +1567,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmConfirm(BD_ADDR bd_addr, BOOLEAN accept);
-
-/*******************************************************************************
-**
-** Function         BTA_DmPasskeyCancel
-**
-** Description      This function is called to cancel the simple pairing process
-**                  reported by BTA_DM_SP_KEY_NOTIF_EVT
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmPasskeyCancel(BD_ADDR bd_addr);
+extern void BTA_DmConfirm(BD_ADDR bd_addr, BOOLEAN accept);
 
 /*******************************************************************************
 **
@@ -1701,30 +1582,10 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmAddDevice(BD_ADDR bd_addr, DEV_CLASS dev_class,
-                                    LINK_KEY link_key, tBTA_SERVICE_MASK trusted_mask,
-                                    BOOLEAN is_trusted, UINT8 key_type,
-                                    tBTA_IO_CAP io_cap);
-
-/*******************************************************************************
-**
-** Function         BTA_DmAddDevWithName
-**
-** Description      This function is newer version of  BTA_DmAddDevice()
-**                  which added bd_name and features as input parameters.
-**
-**
-** Returns          void
-**
-** Note:            features points to the remote device features array.
-**                  The array size is
-**                  BTA_FEATURE_BYTES_PER_PAGE * (BTA_EXT_FEATURES_PAGE_MAX + 1)
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmAddDevWithName (BD_ADDR bd_addr, DEV_CLASS dev_class,
-                                      BD_NAME bd_name, UINT8 *features,
-                                      LINK_KEY link_key, tBTA_SERVICE_MASK trusted_mask,
-                                      BOOLEAN is_trusted, UINT8 key_type, tBTA_IO_CAP io_cap);
+extern void BTA_DmAddDevice(BD_ADDR bd_addr, DEV_CLASS dev_class,
+                            LINK_KEY link_key, tBTA_SERVICE_MASK trusted_mask,
+                            BOOLEAN is_trusted, UINT8 key_type,
+                            tBTA_IO_CAP io_cap);
 
 /*******************************************************************************
 **
@@ -1739,108 +1600,7 @@
 **                  BTA_FAIL if operation failed.
 **
 *******************************************************************************/
-BTA_API extern tBTA_STATUS BTA_DmRemoveDevice(BD_ADDR bd_addr);
-
-/*******************************************************************************
-**
-** Function         BTA_DmAuthorizeReply
-**
-** Description      This function provides an authorization reply when
-**                  authorization is requested by BTA.  The application calls
-**                  this function after the security callback is called with
-**                  a BTA_DM_AUTHORIZE_EVT.
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmAuthorizeReply(BD_ADDR bd_addr, tBTA_SERVICE_ID service,
-                                         tBTA_AUTH_RESP response);
-
-/*******************************************************************************
-**
-** Function         BTA_DmSignalStrength
-**
-** Description      This function initiates RSSI and channnel quality
-**                  measurments. BTA_DM_SIG_STRENGTH_EVT is sent to
-**                  application with the values of RSSI and channel
-**                  quality
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmSignalStrength(tBTA_SIG_STRENGTH_MASK mask, UINT16 period, BOOLEAN start);
-
-/*******************************************************************************
-**
-** Function         BTA_DmWriteInqTxPower
-**
-** Description      This command is used to write the inquiry transmit power level
-**                  used to transmit the inquiry (ID) data packets.
-**
-** Parameters       tx_power - tx inquiry power to use, valid value is -70 ~ 20
-
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmWriteInqTxPower(INT8 tx_power);
-
-/*******************************************************************************
-**
-** Function         BTA_DmEirAddUUID
-**
-** Description      This function is called to add UUID into EIR.
-**
-** Parameters       tBT_UUID - UUID
-**
-** Returns          None
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmEirAddUUID (tBT_UUID *p_uuid);
-
-/*******************************************************************************
-**
-** Function         BTA_DmEirRemoveUUID
-**
-** Description      This function is called to remove UUID from EIR.
-**
-** Parameters       tBT_UUID - UUID
-**
-** Returns          None
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmEirRemoveUUID (tBT_UUID *p_uuid);
-
-/*******************************************************************************
-**
-** Function         BTA_DmSetEIRConfig
-**
-** Description      This function is called to override the BTA default EIR parameters.
-**                  This funciton is only valid in a system where BTU & App task
-**                  are in the same memory space.
-**
-** Parameters       Pointer to User defined EIR config
-**
-** Returns          None
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmSetEIRConfig (tBTA_DM_EIR_CONF *p_eir_cfg);
-
-/*******************************************************************************
-**
-** Function         BTA_CheckEirData
-**
-** Description      This function is called to get EIR data from significant part.
-**
-** Parameters       p_eir - pointer of EIR significant part
-**                  type   - finding EIR data type
-**                  p_length - return the length of EIR data
-**
-** Returns          pointer of EIR data
-**
-*******************************************************************************/
-BTA_API extern UINT8 *BTA_CheckEirData( UINT8 *p_eir, UINT8 tag, UINT8 *p_length );
+extern tBTA_STATUS BTA_DmRemoveDevice(BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -1854,19 +1614,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GetEirService( UINT8 *p_eir, tBTA_SERVICE_MASK *p_services );
-
-/*******************************************************************************
-**
-** Function         BTA_DmUseSsr
-**
-** Description      This function is called to check if the connected peer device
-**                  supports SSR or not.
-**
-** Returns          TRUE, if SSR is supported
-**
-*******************************************************************************/
-BTA_API extern BOOLEAN BTA_DmUseSsr( BD_ADDR bd_addr );
+extern void BTA_GetEirService( UINT8 *p_eir, tBTA_SERVICE_MASK *p_services );
 
 /*******************************************************************************
 **
@@ -1877,7 +1625,7 @@
 ** Returns          0 if the device is NOT connected.
 **
 *******************************************************************************/
-BTA_API extern UINT16 BTA_DmGetConnectionState( BD_ADDR bd_addr );
+extern UINT16 BTA_DmGetConnectionState( BD_ADDR bd_addr );
 
 
 /*******************************************************************************
@@ -1889,47 +1637,8 @@
 ** Returns          BTA_SUCCESS if record set sucessfully, otherwise error code.
 **
 *******************************************************************************/
-BTA_API extern tBTA_STATUS BTA_DmSetLocalDiRecord( tBTA_DI_RECORD *p_device_info,
-	                          UINT32 *p_handle );
-
-/*******************************************************************************
-**
-** Function         BTA_DmGetLocalDiRecord
-**
-** Description      Get a specified DI record to the local SDP database. If no
-**                  record handle is provided, the primary DI record will be
-**                  returned.
-**
-** Returns          BTA_SUCCESS if record set sucessfully, otherwise error code.
-**
-*******************************************************************************/
-BTA_API extern tBTA_STATUS BTA_DmGetLocalDiRecord( tBTA_DI_GET_RECORD *p_device_info,
-	                          UINT32 *p_handle );
-
-/*******************************************************************************
-**
-** Function         BTA_DmDiDiscover
-**
-** Description      This function queries a remote device for DI information.
-**
-** Returns          None.
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmDiDiscover( BD_ADDR remote_device, tBTA_DISCOVERY_DB *p_db,
-                       UINT32 len, tBTA_DM_SEARCH_CBACK *p_cback );
-
-/*******************************************************************************
-**
-** Function         BTA_DmGetDiRecord
-**
-** Description      This function retrieves a remote device's DI record from
-**                  the specified database.
-**
-** Returns          None.
-**
-*******************************************************************************/
-BTA_API extern tBTA_STATUS BTA_DmGetDiRecord( UINT8 get_record_index, tBTA_DI_GET_RECORD *p_device_info,
-                        tBTA_DISCOVERY_DB *p_db );
+extern tBTA_STATUS BTA_DmSetLocalDiRecord( tBTA_DI_RECORD *p_device_info,
+                                           UINT32 *p_handle );
 
 /*******************************************************************************
 **
@@ -1947,18 +1656,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmCloseACL(BD_ADDR bd_addr, BOOLEAN remove_dev, tBTA_TRANSPORT transport);
-
-/*******************************************************************************
-**
-** Function         BTA_SysFeatures
-**
-** Description      This function is called to set system features.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void BTA_SysFeatures (UINT16 sys_features);
+extern void BTA_DmCloseACL(BD_ADDR bd_addr, BOOLEAN remove_dev, tBTA_TRANSPORT transport);
 
 /*******************************************************************************
 **
@@ -1971,7 +1669,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_dmexecutecallback (tBTA_DM_EXEC_CBACK* p_callback, void * p_param);
+extern void bta_dmexecutecallback (tBTA_DM_EXEC_CBACK* p_callback, void * p_param);
 
 #if (BTM_SCO_HCI_INCLUDED == TRUE)
 /*******************************************************************************
@@ -1988,7 +1686,7 @@
 ** Returns          none
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmPcmInitSamples (UINT32 src_sps, UINT32 bits, UINT32 n_channels);
+extern void BTA_DmPcmInitSamples (UINT32 src_sps, UINT32 bits, UINT32 n_channels);
 
 /**************************************************************************************
 ** Function         BTA_DmPcmResample
@@ -2006,7 +1704,7 @@
 ** Returns          INT32: number of samples converted.
 **
 **************************************************************************************/
-BTA_API extern INT32 BTA_DmPcmResample (void *p_src, UINT32 in_bytes, void *p_dst);
+extern INT32 BTA_DmPcmResample (void *p_src, UINT32 in_bytes, void *p_dst);
 #endif
 
 #if ((defined BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
@@ -2023,7 +1721,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleSecurityGrant(BD_ADDR bd_addr, tBTA_DM_BLE_SEC_GRANT res);
+extern void BTA_DmBleSecurityGrant(BD_ADDR bd_addr, tBTA_DM_BLE_SEC_GRANT res);
 
 
 
@@ -2041,7 +1739,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleSetBgConnType(tBTA_DM_BLE_CONN_TYPE bg_conn_type, tBTA_DM_BLE_SEL_CBACK *p_select_cback);
+extern void BTA_DmBleSetBgConnType(tBTA_DM_BLE_CONN_TYPE bg_conn_type, tBTA_DM_BLE_SEL_CBACK *p_select_cback);
 
 /*******************************************************************************
 **
@@ -2057,7 +1755,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBlePasskeyReply(BD_ADDR bd_addr, BOOLEAN accept, UINT32 passkey);
+extern void BTA_DmBlePasskeyReply(BD_ADDR bd_addr, BOOLEAN accept, UINT32 passkey);
 
 /*******************************************************************************
 **
@@ -2074,8 +1772,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmAddBleDevice(BD_ADDR bd_addr, tBLE_ADDR_TYPE addr_type,
-                                       tBT_DEVICE_TYPE dev_type);
+extern void BTA_DmAddBleDevice(BD_ADDR bd_addr, tBLE_ADDR_TYPE addr_type,
+                               tBT_DEVICE_TYPE dev_type);
 
 
 /*******************************************************************************
@@ -2093,9 +1791,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmAddBleKey (BD_ADDR bd_addr,
-                                     tBTA_LE_KEY_VALUE *p_le_key,
-                                     tBTA_LE_KEY_TYPE key_type);
+extern void BTA_DmAddBleKey (BD_ADDR bd_addr,
+                             tBTA_LE_KEY_VALUE *p_le_key,
+                             tBTA_LE_KEY_TYPE key_type);
 
 /*******************************************************************************
 **
@@ -2114,9 +1812,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmSetBlePrefConnParams(BD_ADDR bd_addr,
-                               UINT16 min_conn_int, UINT16 max_conn_int,
-                               UINT16 slave_latency, UINT16 supervision_tout );
+extern void BTA_DmSetBlePrefConnParams(BD_ADDR bd_addr,
+                                       UINT16 min_conn_int, UINT16 max_conn_int,
+                                       UINT16 slave_latency, UINT16 supervision_tout );
 
 /*******************************************************************************
 **
@@ -2132,8 +1830,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmSetBleConnScanParams(UINT16 scan_interval,
-                                               UINT16 scan_window );
+extern void BTA_DmSetBleConnScanParams(UINT16 scan_interval,
+                                       UINT16 scan_window );
 
 /*******************************************************************************
 **
@@ -2150,8 +1848,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmSetBleAdvParams (UINT16 adv_int_min, UINT16 adv_int_max,
-                                           tBLE_BD_ADDR *p_dir_bda);
+extern void BTA_DmSetBleAdvParams (UINT16 adv_int_min, UINT16 adv_int_max,
+                                   tBLE_BD_ADDR *p_dir_bda);
 /*******************************************************************************
 **
 ** Function         BTA_DmSearchExt
@@ -2171,8 +1869,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmSearchExt(tBTA_DM_INQ *p_dm_inq, tBTA_SERVICE_MASK_EXT *p_services,
-                                    tBTA_DM_SEARCH_CBACK *p_cback);
+extern void BTA_DmSearchExt(tBTA_DM_INQ *p_dm_inq, tBTA_SERVICE_MASK_EXT *p_services,
+                            tBTA_DM_SEARCH_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -2189,8 +1887,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmDiscoverExt(BD_ADDR bd_addr, tBTA_SERVICE_MASK_EXT *p_services,
-                                    tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search);
+extern void BTA_DmDiscoverExt(BD_ADDR bd_addr, tBTA_SERVICE_MASK_EXT *p_services,
+                              tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search);
 
 /*******************************************************************************
 **
@@ -2208,9 +1906,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmDiscoverByTransport(BD_ADDR bd_addr, tBTA_SERVICE_MASK_EXT *p_services,
-                                              tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search,
-                                              tBTA_TRANSPORT transport);
+extern void BTA_DmDiscoverByTransport(BD_ADDR bd_addr, tBTA_SERVICE_MASK_EXT *p_services,
+                                      tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search,
+                                      tBTA_TRANSPORT transport);
 
 /*******************************************************************************
 **
@@ -2235,9 +1933,9 @@
 **
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmSetEncryption(BD_ADDR bd_addr, tBTA_TRANSPORT transport,
-                                        tBTA_DM_ENCRYPT_CBACK *p_callback,
-                                         tBTA_DM_BLE_SEC_ACT sec_act);
+extern void BTA_DmSetEncryption(BD_ADDR bd_addr, tBTA_TRANSPORT transport,
+                                tBTA_DM_ENCRYPT_CBACK *p_callback,
+                                tBTA_DM_BLE_SEC_ACT sec_act);
 
 
 /*******************************************************************************
@@ -2254,24 +1952,12 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleObserve(BOOLEAN start, UINT8 duration,
-                                           tBTA_DM_SEARCH_CBACK *p_results_cb);
+extern void BTA_DmBleObserve(BOOLEAN start, UINT8 duration,
+                             tBTA_DM_SEARCH_CBACK *p_results_cb);
 
 
 #endif
 
-// btla-specific ++
-/*******************************************************************************
-**
-** Function         BTA_DmSetAfhChannelAssessment
-**
-** Description      This function is called to set the channel assessment mode on or off
-**
-** Returns          status
-**
-*******************************************************************************/
-BTA_API extern void BTA_DmSetAfhChannelAssessment (BOOLEAN enable_or_disable);
-
 #if BLE_INCLUDED == TRUE
 // btla-specific --
 /*******************************************************************************
@@ -2285,7 +1971,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleConfigLocalPrivacy(BOOLEAN privacy_enable);
+extern void BTA_DmBleConfigLocalPrivacy(BOOLEAN privacy_enable);
 
 /*******************************************************************************
 **
@@ -2299,7 +1985,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleEnableRemotePrivacy(BD_ADDR bd_addr, BOOLEAN privacy_enable);
+extern void BTA_DmBleEnableRemotePrivacy(BD_ADDR bd_addr, BOOLEAN privacy_enable);
 
 
 /*******************************************************************************
@@ -2313,9 +1999,9 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleSetAdvConfig (tBTA_BLE_AD_MASK data_mask,
-                                           tBTA_BLE_ADV_DATA *p_adv_cfg,
-                                           tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback);
+extern void BTA_DmBleSetAdvConfig (tBTA_BLE_AD_MASK data_mask,
+                                   tBTA_BLE_ADV_DATA *p_adv_cfg,
+                                   tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback);
 
 /*******************************************************************************
 **
@@ -2328,9 +2014,9 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleSetScanRsp (tBTA_BLE_AD_MASK data_mask,
-                                         tBTA_BLE_ADV_DATA *p_adv_cfg,
-                                         tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback);
+extern void BTA_DmBleSetScanRsp (tBTA_BLE_AD_MASK data_mask,
+                                 tBTA_BLE_ADV_DATA *p_adv_cfg,
+                                 tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback);
 
 /*******************************************************************************
 **
@@ -2343,7 +2029,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleBroadcast (BOOLEAN start);
+extern void BTA_DmBleBroadcast (BOOLEAN start);
 
 
 /*******************************************************************************
@@ -2359,7 +2045,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_BleEnableAdvInstance (tBTA_BLE_ADV_PARAMS *p_params,
+extern void BTA_BleEnableAdvInstance (tBTA_BLE_ADV_PARAMS *p_params,
                                 tBTA_BLE_MULTI_ADV_CBACK *p_cback,void *p_ref);
 
 /*******************************************************************************
@@ -2374,7 +2060,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_BleUpdateAdvInstParam (UINT8 inst_id,
+extern void BTA_BleUpdateAdvInstParam (UINT8 inst_id,
                                 tBTA_BLE_ADV_PARAMS *p_params);
 
 /*******************************************************************************
@@ -2389,7 +2075,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_BleCfgAdvInstData (UINT8 inst_id, BOOLEAN is_scan_rsp,
+extern void BTA_BleCfgAdvInstData (UINT8 inst_id, BOOLEAN is_scan_rsp,
                                 tBTA_BLE_AD_MASK data_mask, tBTA_BLE_ADV_DATA *p_data);
 
 /*******************************************************************************
@@ -2403,7 +2089,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_BleDisableAdvInstance(UINT8 inst_id);
+extern void BTA_BleDisableAdvInstance(UINT8 inst_id);
 
 /*******************************************************************************
 **
@@ -2420,7 +2106,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleUpdateConnectionParams(BD_ADDR bd_addr, UINT16 min_int,
+extern void BTA_DmBleUpdateConnectionParams(BD_ADDR bd_addr, UINT16 min_int,
                                    UINT16 max_int, UINT16 latency, UINT16 timeout);
 
 /*******************************************************************************
@@ -2441,7 +2127,7 @@
 ** Returns           None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleSetStorageParams(UINT8 batch_scan_full_max,
+extern void BTA_DmBleSetStorageParams(UINT8 batch_scan_full_max,
                                          UINT8 batch_scan_trunc_max,
                                          UINT8 batch_scan_notify_threshold,
                                          tBTA_BLE_SCAN_SETUP_CBACK *p_setup_cback,
@@ -2465,7 +2151,7 @@
 ** Returns           None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleEnableBatchScan(tBTA_BLE_SCAN_MODE scan_mode,
+extern void BTA_DmBleEnableBatchScan(tBTA_BLE_SCAN_MODE scan_mode,
                                          UINT32 scan_interval, UINT32 scan_window,
                                          tBTA_BLE_DISCARD_RULE discard_rule,
                                          tBLE_ADDR_TYPE        addr_type,
@@ -2483,7 +2169,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleReadScanReports(tBTA_BLE_SCAN_MODE scan_type,
+extern void BTA_DmBleReadScanReports(tBTA_BLE_SCAN_MODE scan_type,
                                              tBTA_DM_BLE_REF_VALUE ref_value);
 
 /*******************************************************************************
@@ -2497,7 +2183,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleDisableBatchScan(tBTA_DM_BLE_REF_VALUE ref_value);
+extern void BTA_DmBleDisableBatchScan(tBTA_DM_BLE_REF_VALUE ref_value);
 
 /*******************************************************************************
 **
@@ -2512,7 +2198,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmEnableScanFilter(UINT8 action,
+extern void BTA_DmEnableScanFilter(UINT8 action,
                                         tBTA_DM_BLE_PF_STATUS_CBACK *p_cmpl_cback,
                                         tBTA_DM_BLE_REF_VALUE ref_value);
 
@@ -2532,7 +2218,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleScanFilterSetup(UINT8 action,
+extern void BTA_DmBleScanFilterSetup(UINT8 action,
                                                    tBTA_DM_BLE_PF_FILT_INDEX filt_index,
                                                    tBTA_DM_BLE_PF_FILT_PARAMS *p_filt_params,
                                                    tBLE_BD_ADDR *p_target,
@@ -2556,7 +2242,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleCfgFilterCondition(tBTA_DM_BLE_SCAN_COND_OP action,
+extern void BTA_DmBleCfgFilterCondition(tBTA_DM_BLE_SCAN_COND_OP action,
                                                  tBTA_DM_BLE_PF_COND_TYPE cond_type,
                                                  tBTA_DM_BLE_PF_FILT_INDEX filt_index,
                                                  tBTA_DM_BLE_PF_COND_PARAM *p_cond,
@@ -2576,7 +2262,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleTrackAdvertiser(tBTA_DM_BLE_REF_VALUE ref_value,
+extern void BTA_DmBleTrackAdvertiser(tBTA_DM_BLE_REF_VALUE ref_value,
                             tBTA_BLE_TRACK_ADV_CBACK *p_track_adv_cback);
 
 /*******************************************************************************
@@ -2590,7 +2276,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_DmBleGetEnergyInfo(tBTA_BLE_ENERGY_INFO_CBACK *p_cmpl_cback);
+extern void BTA_DmBleGetEnergyInfo(tBTA_BLE_ENERGY_INFO_CBACK *p_cmpl_cback);
 
 /*******************************************************************************
 **
@@ -2601,7 +2287,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_VendorInit  (void);
+extern void BTA_VendorInit  (void);
 
 /*******************************************************************************
 **
@@ -2612,7 +2298,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_VendorCleanup (void);
+extern void BTA_VendorCleanup (void);
 
 #endif
 
@@ -2621,4 +2307,3 @@
 #endif
 
 #endif /* BTA_API_H */
-
diff --git a/bta/include/bta_av_api.h b/bta/include/bta_av_api.h
index 22ee91c..e0e356f 100644
--- a/bta/include/bta_av_api.h
+++ b/bta/include/bta_av_api.h
@@ -531,7 +531,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvEnable(tBTA_SEC sec_mask, tBTA_AV_FEAT features,
+void BTA_AvEnable(tBTA_SEC sec_mask, tBTA_AV_FEAT features,
                           tBTA_AV_CBACK *p_cback);
 
 /*******************************************************************************
@@ -544,7 +544,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvDisable(void);
+void BTA_AvDisable(void);
 
 /*******************************************************************************
 **
@@ -559,7 +559,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvRegister(tBTA_AV_CHNL chnl, const char *p_service_name,
+void BTA_AvRegister(tBTA_AV_CHNL chnl, const char *p_service_name,
                             UINT8 app_id, tBTA_AV_DATA_CBACK  *p_data_cback);
 
 /*******************************************************************************
@@ -571,7 +571,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvDeregister(tBTA_AV_HNDL hndl);
+void BTA_AvDeregister(tBTA_AV_HNDL hndl);
 
 /*******************************************************************************
 **
@@ -584,7 +584,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvOpen(BD_ADDR bd_addr, tBTA_AV_HNDL handle,
+void BTA_AvOpen(BD_ADDR bd_addr, tBTA_AV_HNDL handle,
                         BOOLEAN use_rc, tBTA_SEC sec_mask, UINT16 uuid);
 
 /*******************************************************************************
@@ -596,7 +596,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvClose(tBTA_AV_HNDL handle);
+void BTA_AvClose(tBTA_AV_HNDL handle);
 
 /*******************************************************************************
 **
@@ -607,7 +607,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvDisconnect(BD_ADDR bd_addr);
+void BTA_AvDisconnect(BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -629,7 +629,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvStart(void);
+void BTA_AvStart(void);
 
 /*******************************************************************************
 **
@@ -642,7 +642,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvStop(BOOLEAN suspend);
+void BTA_AvStop(BOOLEAN suspend);
 
 /*******************************************************************************
 **
@@ -657,7 +657,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvReconfig(tBTA_AV_HNDL hndl, BOOLEAN suspend, UINT8 sep_info_idx,
+void BTA_AvReconfig(tBTA_AV_HNDL hndl, BOOLEAN suspend, UINT8 sep_info_idx,
                             UINT8 *p_codec_info, UINT8 num_protect, UINT8 *p_protect_info);
 
 /*******************************************************************************
@@ -670,7 +670,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvProtectReq(tBTA_AV_HNDL hndl, UINT8 *p_data, UINT16 len);
+void BTA_AvProtectReq(tBTA_AV_HNDL hndl, UINT8 *p_data, UINT16 len);
 
 /*******************************************************************************
 **
@@ -684,7 +684,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, UINT8 error_code, UINT8 *p_data,
+void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, UINT8 error_code, UINT8 *p_data,
                               UINT16 len);
 
 /*******************************************************************************
@@ -697,7 +697,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvRemoteCmd(UINT8 rc_handle, UINT8 label, tBTA_AV_RC rc_id,
+void BTA_AvRemoteCmd(UINT8 rc_handle, UINT8 label, tBTA_AV_RC rc_id,
                              tBTA_AV_STATE key_state);
 
 /*******************************************************************************
@@ -711,7 +711,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvVendorCmd(UINT8 rc_handle, UINT8 label, tBTA_AV_CODE cmd_code,
+void BTA_AvVendorCmd(UINT8 rc_handle, UINT8 label, tBTA_AV_CODE cmd_code,
                              UINT8 *p_data, UINT16 len);
 
 /*******************************************************************************
@@ -726,7 +726,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvVendorRsp(UINT8 rc_handle, UINT8 label, tBTA_AV_CODE rsp_code,
+void BTA_AvVendorRsp(UINT8 rc_handle, UINT8 label, tBTA_AV_CODE rsp_code,
                              UINT8 *p_data, UINT16 len, UINT32 company_id);
 
 
@@ -740,7 +740,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvOpenRc(tBTA_AV_HNDL handle);
+void BTA_AvOpenRc(tBTA_AV_HNDL handle);
 
 /*******************************************************************************
 **
@@ -751,7 +751,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvCloseRc(UINT8 rc_handle);
+void BTA_AvCloseRc(UINT8 rc_handle);
 
 /*******************************************************************************
 **
@@ -765,7 +765,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvMetaRsp(UINT8 rc_handle, UINT8 label, tBTA_AV_CODE rsp_code,
+void BTA_AvMetaRsp(UINT8 rc_handle, UINT8 label, tBTA_AV_CODE rsp_code,
                                BT_HDR *p_pkt);
 
 /*******************************************************************************
@@ -782,7 +782,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_AvMetaCmd(UINT8 rc_handle, UINT8 label, tBTA_AV_CMD cmd_code, BT_HDR *p_pkt);
+void BTA_AvMetaCmd(UINT8 rc_handle, UINT8 label, tBTA_AV_CMD cmd_code, BT_HDR *p_pkt);
 
 #ifdef __cplusplus
 }
diff --git a/bta/include/bta_av_ci.h b/bta/include/bta_av_ci.h
index faad260..9e2c62c 100644
--- a/bta/include/bta_av_ci.h
+++ b/bta/include/bta_av_ci.h
@@ -46,7 +46,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_ci_src_data_ready(tBTA_AV_CHNL chnl);
+extern void bta_av_ci_src_data_ready(tBTA_AV_CHNL chnl);
 
 /*******************************************************************************
 **
@@ -61,7 +61,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_ci_setconfig(tBTA_AV_HNDL hndl, UINT8 err_code,
+extern void bta_av_ci_setconfig(tBTA_AV_HNDL hndl, UINT8 err_code,
                                         UINT8 category, UINT8 num_seid, UINT8 *p_seid,
                                         BOOLEAN recfg_needed, UINT8 avdt_handle);
 
@@ -71,4 +71,3 @@
 #endif
 
 #endif /* BTA_AV_CI_H */
-
diff --git a/bta/include/bta_av_co.h b/bta/include/bta_av_co.h
index ed11c50..ad8e697 100644
--- a/bta/include/bta_av_co.h
+++ b/bta/include/bta_av_co.h
@@ -84,8 +84,8 @@
 ** Returns          Stream codec and content protection capabilities info.
 **
 *******************************************************************************/
-BTA_API extern BOOLEAN bta_av_co_audio_init(UINT8 *p_codec_type, UINT8 *p_codec_info,
-                                   UINT8 *p_num_protect, UINT8 *p_protect_info, UINT8 index);
+extern BOOLEAN bta_av_co_audio_init(UINT8 *p_codec_type, UINT8 *p_codec_info,
+                                    UINT8 *p_num_protect, UINT8 *p_protect_info, UINT8 index);
 
 /*******************************************************************************
 **
@@ -99,7 +99,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_audio_disc_res(tBTA_AV_HNDL hndl, UINT8 num_seps,
+extern void bta_av_co_audio_disc_res(tBTA_AV_HNDL hndl, UINT8 num_seps,
                     UINT8 num_snk, UINT8 num_src, BD_ADDR addr, UINT16 uuid_local);
 
 /*******************************************************************************
@@ -114,8 +114,8 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_video_disc_res(tBTA_AV_HNDL hndl, UINT8 num_seps,
-                                             UINT8 num_snk, BD_ADDR addr);
+extern void bta_av_co_video_disc_res(tBTA_AV_HNDL hndl, UINT8 num_seps,
+                                     UINT8 num_snk, BD_ADDR addr);
 
 /*******************************************************************************
 **
@@ -129,9 +129,9 @@
 ** Returns          Stream codec and content protection configuration info.
 **
 *******************************************************************************/
-BTA_API extern UINT8 bta_av_co_audio_getconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
-                                         UINT8 *p_codec_info, UINT8 *p_sep_info_idx, UINT8 seid,
-                                         UINT8 *p_num_protect, UINT8 *p_protect_info);
+extern UINT8 bta_av_co_audio_getconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+                                       UINT8 *p_codec_info, UINT8 *p_sep_info_idx, UINT8 seid,
+                                       UINT8 *p_num_protect, UINT8 *p_protect_info);
 
 /*******************************************************************************
 **
@@ -145,9 +145,9 @@
 ** Returns          Stream codec and content protection configuration info.
 **
 *******************************************************************************/
-BTA_API extern UINT8 bta_av_co_video_getconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
-                                         UINT8 *p_codec_info, UINT8 *p_sep_info_idx, UINT8 seid,
-                                         UINT8 *p_num_protect, UINT8 *p_protect_info);
+extern UINT8 bta_av_co_video_getconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+                                       UINT8 *p_codec_info, UINT8 *p_sep_info_idx, UINT8 seid,
+                                       UINT8 *p_num_protect, UINT8 *p_protect_info);
 
 /*******************************************************************************
 **
@@ -160,7 +160,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_audio_setconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+extern void bta_av_co_audio_setconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
                                         UINT8 *p_codec_info, UINT8 seid, BD_ADDR addr,
                                         UINT8 num_protect, UINT8 *p_protect_info,UINT8 t_local_sep, UINT8 avdt_handle);
 
@@ -175,9 +175,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_video_setconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
-                                        UINT8 *p_codec_info, UINT8 seid, BD_ADDR addr,
-                                        UINT8 num_protect, UINT8 *p_protect_info);
+extern void bta_av_co_video_setconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+                                      UINT8 *p_codec_info, UINT8 seid, BD_ADDR addr,
+                                      UINT8 num_protect, UINT8 *p_protect_info);
 
 /*******************************************************************************
 **
@@ -192,9 +192,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_audio_open(tBTA_AV_HNDL hndl,
-                                         tBTA_AV_CODEC codec_type, UINT8 *p_codec_info,
-                                         UINT16 mtu);
+extern void bta_av_co_audio_open(tBTA_AV_HNDL hndl,
+                                 tBTA_AV_CODEC codec_type, UINT8 *p_codec_info,
+                                 UINT16 mtu);
 
 /*******************************************************************************
 **
@@ -207,9 +207,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_video_open(tBTA_AV_HNDL hndl,
-                                         tBTA_AV_CODEC codec_type, UINT8 *p_codec_info,
-                                         UINT16 mtu);
+extern void bta_av_co_video_open(tBTA_AV_HNDL hndl,
+                                 tBTA_AV_CODEC codec_type, UINT8 *p_codec_info,
+                                 UINT16 mtu);
 
 /*******************************************************************************
 **
@@ -225,8 +225,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_audio_close(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
-                                          UINT16 mtu);
+extern void bta_av_co_audio_close(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+                                  UINT16 mtu);
 
 /*******************************************************************************
 **
@@ -239,8 +239,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_video_close(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
-                                          UINT16 mtu);
+extern void bta_av_co_video_close(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+                                  UINT16 mtu);
 
 /*******************************************************************************
 **
@@ -253,8 +253,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_audio_start(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
-        UINT8 *p_codec_info, BOOLEAN *p_no_rtp_hdr);
+extern void bta_av_co_audio_start(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+                                  UINT8 *p_codec_info, BOOLEAN *p_no_rtp_hdr);
 
 /*******************************************************************************
 **
@@ -267,8 +267,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_video_start(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
-        UINT8 *p_codec_info, BOOLEAN *p_no_rtp_hdr);
+extern void bta_av_co_video_start(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+                                  UINT8 *p_codec_info, BOOLEAN *p_no_rtp_hdr);
 
 /*******************************************************************************
 **
@@ -281,7 +281,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_audio_stop(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type);
+extern void bta_av_co_audio_stop(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type);
 
 /*******************************************************************************
 **
@@ -294,7 +294,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_video_stop(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type);
+extern void bta_av_co_video_stop(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type);
 
 /*******************************************************************************
 **
@@ -307,8 +307,8 @@
 **                  Otherwise, a GKI buffer (BT_HDR*) containing the audio data.
 **
 *******************************************************************************/
-BTA_API extern void * bta_av_co_audio_src_data_path(tBTA_AV_CODEC codec_type,
-                                                    UINT32 *p_len, UINT32 *p_timestamp);
+extern void * bta_av_co_audio_src_data_path(tBTA_AV_CODEC codec_type,
+                                            UINT32 *p_len, UINT32 *p_timestamp);
 
 /*******************************************************************************
 **
@@ -321,8 +321,8 @@
 **                  Otherwise, a video data buffer (UINT8*).
 **
 *******************************************************************************/
-BTA_API extern void * bta_av_co_video_src_data_path(tBTA_AV_CODEC codec_type,
-                                                    UINT32 *p_len, UINT32 *p_timestamp);
+extern void * bta_av_co_video_src_data_path(tBTA_AV_CODEC codec_type,
+                                            UINT32 *p_len, UINT32 *p_timestamp);
 
 /*******************************************************************************
 **
@@ -336,7 +336,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_audio_drop(tBTA_AV_HNDL hndl);
+extern void bta_av_co_audio_drop(tBTA_AV_HNDL hndl);
 
 /*******************************************************************************
 **
@@ -348,7 +348,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_video_report_conn (BOOLEAN open, UINT8 avdt_handle);
+extern void bta_av_co_video_report_conn (BOOLEAN open, UINT8 avdt_handle);
 
 /*******************************************************************************
 **
@@ -360,7 +360,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_video_report_rr (UINT32 packet_lost);
+extern void bta_av_co_video_report_rr (UINT32 packet_lost);
 
 /*******************************************************************************
 **
@@ -373,7 +373,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_audio_delay(tBTA_AV_HNDL hndl, UINT16 delay);
+extern void bta_av_co_audio_delay(tBTA_AV_HNDL hndl, UINT16 delay);
 
 /*******************************************************************************
 **
@@ -386,7 +386,6 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_av_co_video_delay(tBTA_AV_HNDL hndl, UINT16 delay);
+extern void bta_av_co_video_delay(tBTA_AV_HNDL hndl, UINT16 delay);
 
 #endif /* BTA_AV_CO_H */
-
diff --git a/bta/include/bta_dm_ci.h b/bta/include/bta_dm_ci.h
index bf0983e..5593b9e 100644
--- a/bta/include/bta_dm_ci.h
+++ b/bta/include/bta_dm_ci.h
@@ -45,7 +45,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_ci_io_req(BD_ADDR bd_addr, tBTA_IO_CAP io_cap,
+extern void bta_dm_ci_io_req(BD_ADDR bd_addr, tBTA_IO_CAP io_cap,
                                      tBTA_OOB_DATA oob_data, tBTA_AUTH_REQ auth_req);
 
 /*******************************************************************************
@@ -59,8 +59,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_ci_rmt_oob(BOOLEAN accept, BD_ADDR bd_addr,
-                                      BT_OCTET16 c, BT_OCTET16 r);
+extern void bta_dm_ci_rmt_oob(BOOLEAN accept, BD_ADDR bd_addr,
+                              BT_OCTET16 c, BT_OCTET16 r);
 /*******************************************************************************
 **
 ** Function         bta_dm_sco_ci_data_ready
@@ -71,11 +71,10 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_sco_ci_data_ready(UINT16 event, UINT16 sco_handle);
+extern void bta_dm_sco_ci_data_ready(UINT16 event, UINT16 sco_handle);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif
-
diff --git a/bta/include/bta_dm_co.h b/bta/include/bta_dm_co.h
index 864104e..c00a59c 100644
--- a/bta/include/bta_dm_co.h
+++ b/bta/include/bta_dm_co.h
@@ -69,9 +69,9 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_co_io_req(BD_ADDR bd_addr, tBTA_IO_CAP *p_io_cap,
-                                     tBTA_OOB_DATA *p_oob_data, tBTA_AUTH_REQ *p_auth_req,
-                                     BOOLEAN is_orig);
+extern void bta_dm_co_io_req(BD_ADDR bd_addr, tBTA_IO_CAP *p_io_cap,
+                             tBTA_OOB_DATA *p_oob_data, tBTA_AUTH_REQ *p_auth_req,
+                             BOOLEAN is_orig);
 
 /*******************************************************************************
 **
@@ -88,8 +88,8 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_co_io_rsp(BD_ADDR bd_addr, tBTA_IO_CAP io_cap,
-                                     tBTA_OOB_DATA oob_data, tBTA_AUTH_REQ auth_req);
+extern void bta_dm_co_io_rsp(BD_ADDR bd_addr, tBTA_IO_CAP io_cap,
+                             tBTA_OOB_DATA oob_data, tBTA_AUTH_REQ auth_req);
 
 /*******************************************************************************
 **
@@ -104,7 +104,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void  bta_dm_co_lk_upgrade(BD_ADDR bd_addr, BOOLEAN *p_upgrade );
+extern void  bta_dm_co_lk_upgrade(BD_ADDR bd_addr, BOOLEAN *p_upgrade );
 
 /*******************************************************************************
 **
@@ -120,7 +120,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_co_loc_oob(BOOLEAN valid, BT_OCTET16 c, BT_OCTET16 r);
+extern void bta_dm_co_loc_oob(BOOLEAN valid, BT_OCTET16 c, BT_OCTET16 r);
 
 /*******************************************************************************
 **
@@ -134,7 +134,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_co_rmt_oob(BD_ADDR bd_addr);
+extern void bta_dm_co_rmt_oob(BD_ADDR bd_addr);
 
 /*****************************************************************************
 **  SCO over HCI Function Declarations
@@ -151,8 +151,8 @@
 ** Returns          Void.
 **
 *******************************************************************************/
-BTA_API extern tBTA_DM_SCO_ROUTE_TYPE bta_dm_sco_co_init(UINT32 rx_bw, UINT32 tx_bw,
-                                                         tBTA_CODEC_INFO *p_codec_info, UINT8 app_id);
+extern tBTA_DM_SCO_ROUTE_TYPE bta_dm_sco_co_init(UINT32 rx_bw, UINT32 tx_bw,
+                                                 tBTA_CODEC_INFO *p_codec_info, UINT8 app_id);
 
 
 /*******************************************************************************
@@ -165,7 +165,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_sco_co_open(UINT16 handle, UINT8 pkt_size, UINT16 event);
+extern void bta_dm_sco_co_open(UINT16 handle, UINT8 pkt_size, UINT16 event);
 
 /*******************************************************************************
 **
@@ -177,7 +177,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_sco_co_close(void);
+extern void bta_dm_sco_co_close(void);
 
 /*******************************************************************************
 **
@@ -188,7 +188,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_sco_co_out_data(BT_HDR  **p_buf);
+extern void bta_dm_sco_co_out_data(BT_HDR  **p_buf);
 
 /*******************************************************************************
 **
@@ -199,7 +199,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_sco_co_in_data(BT_HDR  *p_buf, tBTM_SCO_DATA_FLAG status);
+extern void bta_dm_sco_co_in_data(BT_HDR  *p_buf, tBTM_SCO_DATA_FLAG status);
 
 
 
@@ -221,12 +221,12 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_co_ble_io_req(BD_ADDR bd_addr,  tBTA_IO_CAP *p_io_cap,
-                                        tBTA_OOB_DATA *p_oob_data,
-                                        tBTA_LE_AUTH_REQ *p_auth_req,
-                                        UINT8 *p_max_key_size,
-                                        tBTA_LE_KEY_TYPE *p_init_key,
-                                        tBTA_LE_KEY_TYPE  *p_resp_key );
+extern void bta_dm_co_ble_io_req(BD_ADDR bd_addr,  tBTA_IO_CAP *p_io_cap,
+                                 tBTA_OOB_DATA *p_oob_data,
+                                 tBTA_LE_AUTH_REQ *p_auth_req,
+                                 UINT8 *p_max_key_size,
+                                 tBTA_LE_KEY_TYPE *p_init_key,
+                                 tBTA_LE_KEY_TYPE  *p_resp_key );
 
 
 /*******************************************************************************
@@ -241,8 +241,8 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_co_ble_load_local_keys (tBTA_DM_BLE_LOCAL_KEY_MASK *p_key_mask, BT_OCTET16 er,
-                                                   tBTA_BLE_LOCAL_ID_KEYS *p_id_keys);
+extern void bta_dm_co_ble_load_local_keys (tBTA_DM_BLE_LOCAL_KEY_MASK *p_key_mask, BT_OCTET16 er,
+                                           tBTA_BLE_LOCAL_ID_KEYS *p_id_keys);
 
 // btla-specific ++
 /*******************************************************************************
@@ -263,12 +263,12 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_dm_co_ble_io_req(BD_ADDR bd_addr,  tBTA_IO_CAP *p_io_cap,
-                         tBTA_OOB_DATA *p_oob_data,
-                         tBTA_LE_AUTH_REQ *p_auth_req,
-                         UINT8 *p_max_key_size,
-                         tBTA_LE_KEY_TYPE *p_init_key,
-                         tBTA_LE_KEY_TYPE  *p_resp_key );
+extern void bta_dm_co_ble_io_req(BD_ADDR bd_addr,  tBTA_IO_CAP *p_io_cap,
+                                 tBTA_OOB_DATA *p_oob_data,
+                                 tBTA_LE_AUTH_REQ *p_auth_req,
+                                 UINT8 *p_max_key_size,
+                                 tBTA_LE_KEY_TYPE *p_init_key,
+                                 tBTA_LE_KEY_TYPE  *p_resp_key );
 // btla-specific --
 
 #endif
diff --git a/bta/include/bta_fs_api.h b/bta/include/bta_fs_api.h
deleted file mode 100644
index a3c34e0..0000000
--- a/bta/include/bta_fs_api.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This is the public interface file for the file system of BTA, Broadcom's
- *  Bluetooth application layer for mobile phones.
- *
- ******************************************************************************/
-#ifndef BTA_FS_API_H
-#define BTA_FS_API_H
-
-#include "bta_api.h"
-
-/*****************************************************************************
-**  Constants and data types
-*****************************************************************************/
-
-/* Configuration structure */
-typedef struct
-{
-    UINT16  max_file_len;           /* Maximum size file name */
-    UINT16  max_path_len;           /* Maximum path length (includes appended file name) */
-    char    path_separator;         /* 0x2f ('/'), or 0x5c ('\') */
-} tBTA_FS_CFG;
-
-extern tBTA_FS_CFG * p_bta_fs_cfg;
-
-#endif /* BTA_FS_API_H */
diff --git a/bta/include/bta_fs_ci.h b/bta/include/bta_fs_ci.h
deleted file mode 100644
index e2b5093..0000000
--- a/bta/include/bta_fs_ci.h
+++ /dev/null
@@ -1,256 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This is the interface file for file system call-in functions.
- *
- ******************************************************************************/
-#ifndef BTA_FS_CI_H
-#define BTA_FS_CI_H
-
-#include "bta_fs_co.h"
-
-/*****************************************************************************
-**  Constants and data types
-*****************************************************************************/
-
-/* Open Complete Event */
-typedef struct
-{
-    BT_HDR            hdr;
-    tBTA_FS_CO_STATUS status;
-    UINT32            file_size;
-    int               fd;
-    const char        *p_file;
-} tBTA_FS_CI_OPEN_EVT;
-
-/* Read Ready Event */
-typedef struct
-{
-    BT_HDR            hdr;
-    tBTA_FS_CO_STATUS status;
-    int               fd;
-    UINT16            num_read;
-} tBTA_FS_CI_READ_EVT;
-
-/* Write Ready Event */
-typedef struct
-{
-    BT_HDR            hdr;
-    tBTA_FS_CO_STATUS status;
-    int               fd;
-} tBTA_FS_CI_WRITE_EVT;
-
-/* Get Directory Entry Event */
-typedef struct
-{
-    BT_HDR            hdr;
-    tBTA_FS_CO_STATUS status;
-} tBTA_FS_CI_GETDIR_EVT;
-
-/* Resume Information Event */
-typedef struct
-{
-    BT_HDR            hdr;
-    tBTA_FS_CO_STATUS status;
-    BD_ADDR_PTR       p_addr;
-    UINT8             *p_sess_info;
-    UINT32            timeout;
-    UINT32            offset;
-    UINT8             ssn;
-    UINT8             info;
-} tBTA_FS_CI_RESUME_EVT;
-
-/* Action Complete Event */
-typedef struct
-{
-    BT_HDR            hdr;
-    tBTA_FS_CO_STATUS status;
-} tBTA_FS_CI_ACTION_EVT;
-
-
-/*****************************************************************************
-**  Function Declarations
-*****************************************************************************/
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_write
-**
-** Description      This function sends an event to BTA indicating the phone
-**                  has written the number of bytes specified in the call-out
-**                  function, bta_fs_co_write(), and is ready for more data.
-**                  This function is used to control the TX data flow.
-**                  Note: The data buffer is released by the stack aioer
-**                        calling this function.
-**
-** Parameters       fd - file descriptor passed to the stack in the
-**                       bta_fs_ci_open call-in function.
-**                  status - BTA_FS_CO_OK, BTA_FS_CO_NOSPACE, or BTA_FS_CO_FAIL
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_ci_write(int fd, tBTA_FS_CO_STATUS status, UINT16 evt);
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_read
-**
-** Description      This function sends an event to BTA indicating the phone has
-**                  read in the requested amount of data specified in the
-**                  bta_fs_co_read() call-out function.  It should only be called
-**                  when the requested number of bytes has been read in, or aioer
-**                  the end of the file has been detected.
-**
-** Parameters       fd - file descriptor passed to the stack in the
-**                       bta_fs_ci_open call-in function.
-**                  num_bytes_read - number of bytes read into the buffer
-**                      specified in the read callout-function.
-**                  status - BTA_FS_CO_OK if full buffer of data,
-**                           BTA_FS_CO_EOF if the end of file has been reached,
-**                           BTA_FS_CO_FAIL if an error has occurred.
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_ci_read(int fd, UINT16 num_bytes_read,
-                                   tBTA_FS_CO_STATUS status, UINT16 evt);
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_open
-**
-** Description      This function sends an event to BTA indicating the phone has
-**                  finished opening a file for reading or writing.
-**
-** Parameters       fd - file descriptor passed to the stack in the
-**                       bta_fs_ci_open call-in function.
-**                  status - BTA_FS_CO_OK if file was opened in mode specified
-**                                          in the call-out function.
-**                           BTA_FS_CO_EACCES if the file exists, but contains
-**                                          the wrong access permissions.
-**                           BTA_FS_CO_FAIL if any other error has occurred.
-**                  file_size - The total size of the file
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_ci_open(int fd, tBTA_FS_CO_STATUS status,
-                                   UINT32 file_size, UINT16 evt);
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_direntry
-**
-** Description      This function is called in response to the
-**                  bta_fs_co_getdirentry call-out function.
-**
-** Parameters       status - BTA_FS_CO_OK if p_entry points to a valid entry.
-**                           BTA_FS_CO_EODIR if no more entries (p_entry is ignored).
-**                           BTA_FS_CO_FAIL if any errors have occurred.
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_ci_direntry(tBTA_FS_CO_STATUS status, UINT16 evt);
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_resume
-**
-** Description      This function is called in response to the
-**                  bta_fs_co_resume call-out function.
-**
-** Parameters       p_sess_info - the stored session ID and related information.
-**                  ssn     - the stored session sequence number.
-**                  info    - the stored BTA specific information (like last active operation).
-**                  status  - BTA_FS_CO_OK if p_entry points to a valid entry.
-**                            BTA_FS_CO_FAIL if any errors have occurred.
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_ci_resume (BD_ADDR_PTR p_addr, UINT8 *p_sess_info,
-                                      UINT32 timeout, UINT32 offset, UINT8 ssn, UINT8 info,
-                                      tBTA_FS_CO_STATUS status, UINT16 evt);
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_action
-**
-** Description      This function is called in response to one of the action
-**                  call-out functions: bta_fs_co_copy, bta_fs_co_rename or
-**                  bta_fs_co_set_perms.
-**
-** Parameters       status  - BTA_FS_CO_OK if the action is succession.
-**                            BTA_FS_CO_FAIL if any errors have occurred.
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_ci_action(tBTA_FS_CO_STATUS status, UINT16 evt);
-
-/*******************************************************************************
-**
-** Function         bta_fs_ci_resume_op
-**
-** Description      This function sends an event to BTA indicating the phone has
-**                  finished opening a file for reading or writing on resume.
-**
-** Parameters       fd - file descriptor passed to the stack in the
-**                       bta_fs_ci_open call-in function.
-**                  status - BTA_FS_CO_OK if file was opened in mode specified
-**                                          in the call-out function.
-**                           BTA_FS_CO_EACCES if the file exists, but contains
-**                                          the wrong access permissions.
-**                           BTA_FS_CO_FAIL if any other error has occurred.
-**                  p_file - The file name associated with fd
-**                  file_size - The total size of the file
-**                  evt - Used Internally by BTA -> MUST be same value passed
-**                       in call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_ci_resume_op(int fd, tBTA_FS_CO_STATUS status, const char *p_file,
-                                        UINT32 file_size, UINT16 evt);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* BTA_FS_CI_H */
-
diff --git a/bta/include/bta_fs_co.h b/bta/include/bta_fs_co.h
deleted file mode 100644
index 7ab16fa..0000000
--- a/bta/include/bta_fs_co.h
+++ /dev/null
@@ -1,703 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This is the interface file for the synchronization server call-out
- *  functions.
- *
- ******************************************************************************/
-#ifndef BTA_FS_CO_H
-#define BTA_FS_CO_H
-
-#include <time.h>
-
-#include "bta_api.h"
-#include "goep_fs.h"
-#include "obx_api.h"
-
-/*****************************************************************************
-**  Constants and Data Types
-*****************************************************************************/
-
-#ifndef BTA_FS_CO_MAX_SSN_ENTRIES
-#define BTA_FS_CO_MAX_SSN_ENTRIES   10
-#endif
-
-/* Maximum path length supported by FS_CO */
-#ifndef BTA_FS_CO_PATH_LEN
-#define BTA_FS_CO_PATH_LEN          294
-#endif
-
-#ifndef BTA_FS_CO_TEST_ROOT
-#define BTA_FS_CO_TEST_ROOT         "test_files"
-#endif
-
-#define BTA_FS_CO_TEST_TYPE_NONE    0
-#define BTA_FS_CO_TEST_TYPE_REJECT  1
-#define BTA_FS_CO_TEST_TYPE_SUSPEND 2
-
-#ifndef BTA_FS_CO_TEST_AB_END
-#define BTA_FS_CO_TEST_AB_END   BTA_FS_CO_TEST_TYPE_NONE
-#endif
-
-/**************************
-**  Common Definitions
-***************************/
-
-/* Status codes returned by call-out functions, or in call-in functions as status */
-#define BTA_FS_CO_OK            GOEP_OK
-#define BTA_FS_CO_FAIL          GOEP_FAIL   /* Used to pass all other errors */
-#define BTA_FS_CO_EACCES        GOEP_EACCES
-#define BTA_FS_CO_ENOTEMPTY     GOEP_ENOTEMPTY
-#define BTA_FS_CO_EOF           GOEP_EOF
-#define BTA_FS_CO_EODIR         GOEP_EODIR
-#define BTA_FS_CO_ENOSPACE      GOEP_ENOSPACE/* Returned in bta_fs_ci_open if no room */
-#define BTA_FS_CO_EIS_DIR       GOEP_EIS_DIR
-#define BTA_FS_CO_RESUME        GOEP_RESUME /* used in ci_open, on resume */
-#define BTA_FS_CO_NONE          GOEP_NONE /* used in ci_open, on resume (no file to resume) */
-
-typedef UINT16 tBTA_FS_CO_STATUS;
-
-/* the index to the permission flags */
-#define BTA_FS_PERM_USER    0
-#define BTA_FS_PERM_GROUP   1
-#define BTA_FS_PERM_OTHER   2
-/* max number of the permission flags */
-#define BTA_FS_PERM_SIZE    3
-
-/* Flags passed to the open function (bta_fs_co_open)
-**      Values are OR'd together. (First 3 are
-**      mutually exclusive.
-*/
-#define BTA_FS_O_RDONLY         GOEP_O_RDONLY
-#define BTA_FS_O_WRONLY         GOEP_O_WRONLY
-#define BTA_FS_O_RDWR           GOEP_O_RDWR
-
-#define BTA_FS_O_CREAT          GOEP_O_CREAT
-#define BTA_FS_O_EXCL           GOEP_O_EXCL
-#define BTA_FS_O_TRUNC          GOEP_O_TRUNC
-
-#define BTA_FS_O_MODE_MASK(x)      (((UINT16)(x)) & 0x0003)
-
-/* Origin for the bta_fs_co_seek function  */
-#define BTA_FS_SEEK_SET         GOEP_SEEK_SET
-#define BTA_FS_SEEK_CUR         GOEP_SEEK_CUR
-#define BTA_FS_SEEK_END         GOEP_SEEK_END
-
-/* mode field in bta_fs_co_access callout */
-#define BTA_FS_ACC_EXIST        GOEP_ACC_EXIST
-#define BTA_FS_ACC_READ         GOEP_ACC_READ
-#define BTA_FS_ACC_RDWR         GOEP_ACC_RDWR
-
-#define BTA_FS_LEN_UNKNOWN      GOEP_LEN_UNKNOWN
-#define BTA_FS_INVALID_FD       GOEP_INVALID_FD
-#define BTA_FS_INVALID_APP_ID   (0xFF)  /* this app_id is reserved */
-
-/* mode field in tBTA_FS_DIRENTRY (OR'd together) */
-#define BTA_FS_A_RDONLY         GOEP_A_RDONLY
-#define BTA_FS_A_DIR            GOEP_A_DIR      /* Entry is a sub directory */
-
-#define BTA_FS_CTIME_LEN        GOEP_CTIME_LEN  /* Creation time "yyyymmddTHHMMSSZ" */
-
-/* Return structure type for a directory entry */
-typedef struct
-{
-    UINT32  refdata;            /* holder for OS specific data used to get next entry */
-    UINT32  filesize;
-    char    crtime[BTA_FS_CTIME_LEN]; /* "yyyymmddTHHMMSSZ", or "" if none */
-    char    *p_name;            /* Contains the addr of memory to copy name into */
-    UINT8   mode;               /* BTA_FS_A_RDONLY and/or BTA_FS_A_DIR */
-} tBTA_FS_DIRENTRY;
-
-/* session state */
-enum
-{
-    BTA_FS_CO_SESS_ST_NONE,
-    BTA_FS_CO_SESS_ST_ACTIVE,
-    BTA_FS_CO_SESS_ST_SUSPEND,
-    BTA_FS_CO_SESS_ST_RESUMING
-};
-typedef UINT8   tBTA_FS_CO_SESS_ST;
-
-
-
-/* a data type to keep an array of ssn/file offset - the info can be saved to NV */
-typedef struct
-{
-    char        path[BTA_FS_CO_PATH_LEN + 1];   /* the "current path". path[0]==0-> root */
-    char        file[BTA_FS_CO_PATH_LEN + 1];   /* file[0] !=0 on resume -> the previous suspended session had opened files */
-    int         oflags;  /* the flag to open the file */
-    BD_ADDR     bd_addr;
-    UINT8       sess_info[OBX_SESSION_INFO_SIZE];
-    UINT32      offset;         /* last file offset */
-    UINT32      timeout;        /* the timeout value on suspend */
-    time_t      suspend_time;   /* the time of suspend */
-    UINT16      nbytes;         /* number of bytes for last read/write */
-    UINT8       ssn;
-    UINT8       info;           /* info for BTA on the client side */
-    UINT8       app_id;
-    tBTA_FS_CO_SESS_ST  sess_st;
-} tBTA_FS_CO_SESSION;
-
-/*****************************************************************************
-**  Function Declarations
-*****************************************************************************/
-/**************************
-**  Common Functions
-***************************/
-/*******************************************************************************
-**
-** Function         bta_fs_co_init
-**
-** Description      This function is executed as a part of the start up sequence
-**                  to make sure the control block is initialized.
-**
-** Parameters       void.
-**
-** Returns          void
-**
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_init(void);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_open
-**
-** Description      This function is executed by BTA when a file is opened.
-**                  The phone uses this function to open
-**                  a file for reading or writing.
-**
-** Parameters       p_path  - Fully qualified path and file name.
-**                  oflags  - permissions and mode (see constants above)
-**                  size    - size of file to put (0 if unavailable or not applicable)
-**                  evt     - event that must be passed into the call-in function.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-**                  Note: Upon completion of the request, a file descriptor (int),
-**                        if successful, and an error code (tBTA_FS_CO_STATUS)
-**                        are returned in the call-in function, bta_fs_ci_open().
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_open(const char *p_path, int oflags, UINT32 size,
-                           UINT16 evt, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_session_info
-**
-** Description      This function is executed by BTA when a reliable session is
-**                  established (p_sess_info != NULL) or ended (p_sess_info == NULL).
-**
-** Parameters       bd_addr     - the peer address
-**                  p_sess_info - the session ID and related information.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_session_info(BD_ADDR bd_addr, UINT8 *p_sess_info, UINT8 ssn,
-                                           tBTA_FS_CO_SESS_ST new_st, char *p_path, UINT8 *p_info, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_resume_op
-**
-** Description      This function is executed by BTA when a reliable session is
-**                  resumed and there was an interrupted operation.
-**
-** Parameters       offset  - the session ID and related information.
-**                  evt     - event that must be passed into the call-in function.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_resume_op(UINT32 offset, UINT16 evt, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_suspend
-**
-** Description      This function is executed by BTA when a reliable session is
-**                  suspended.
-**
-** Parameters       bd_addr - the peer address
-**                  ssn     - the session sequence number.
-**                  info    - the BTA specific information (like last active operation).
-**                  p_offset- the location to receive object offset of the suspended session
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_suspend(BD_ADDR bd_addr, UINT8 *p_sess_info, UINT8 ssn,
-                                      UINT32 *p_timeout, UINT32 *p_offset, UINT8 info, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_resume
-**
-** Description      This function is executed by BTA when resuming a session.
-**                  This is used to retrieve the session ID and related information
-**
-** Parameters       evt     - event that must be passed into the call-in function.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-**                  Note: Upon completion of the request, the related session information,
-**                        if successful, and an error code (tBTA_FS_CO_STATUS)
-**                        are returned in the call-in function, bta_fs_ci_resume().
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_resume(UINT16 evt, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_sess_ssn
-**
-** Description      This function is executed by BTA when resuming a session.
-**                  This is used to inform call-out module if the ssn/file offset
-**                  needs to be adjusted.
-**
-** Parameters       ssn     - the session sequence number of the first request
-**                            after resume.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_sess_ssn(int fd, UINT8 ssn, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_setdir
-**
-** Description      This function is executed by BTA when the server changes the
-**                  local path
-**
-** Parameters       p_path  - the new path.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_setdir(const char *p_path, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_close
-**
-** Description      This function is called by BTA when a connection to a
-**                  client is closed.
-**
-** Parameters       fd      - file descriptor of file to close.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful],
-**                      [BTA_FS_CO_FAIL if failed  ]
-**
-*******************************************************************************/
-BTA_API extern tBTA_FS_CO_STATUS bta_fs_co_close(int fd, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_read
-**
-** Description      This function is called by BTA to read in data from the
-**                  previously opened file on the phone.
-**
-** Parameters       fd      - file descriptor of file to read from.
-**                  p_buf   - buffer to read the data into.
-**                  nbytes  - number of bytes to read into the buffer.
-**                  evt     - event that must be passed into the call-in function.
-**                  ssn     - session sequence number. Ignored, if bta_fs_co_open
-**							  was not called with BTA_FS_CO_RELIABLE.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-**                  Note: Upon completion of the request, bta_fs_ci_read() is
-**                        called with the buffer of data, along with the number
-**                        of bytes read into the buffer, and a status.  The
-**                        call-in function should only be called when ALL requested
-**                        bytes have been read, the end of file has been detected,
-**                        or an error has occurred.
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_read(int fd, UINT8 *p_buf, UINT16 nbytes, UINT16 evt,
-                           UINT8 ssn, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_write
-**
-** Description      This function is called by io to send file data to the
-**                  phone.
-**
-** Parameters       fd      - file descriptor of file to write to.
-**                  p_buf   - buffer to read the data from.
-**                  nbytes  - number of bytes to write out to the file.
-**                  evt     - event that must be passed into the call-in function.
-**                  ssn     - session sequence number. Ignored, if bta_fs_co_open
-**							  was not called with BTA_FS_CO_RELIABLE.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-**                  Note: Upon completion of the request, bta_fs_ci_write() is
-**                        called with the file descriptor and the status.  The
-**                        call-in function should only be called when ALL requested
-**                        bytes have been written, or an error has been detected,
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_write(int fd, const UINT8 *p_buf, UINT16 nbytes, UINT16 evt,
-                            UINT8 ssn, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_seek
-**
-** Description      This function is called by io to move the file pointer
-**                  of a previously opened file to the specified location for
-**                  the next read or write operation.
-**
-** Parameters       fd      - file descriptor of file.
-**                  offset  - Number of bytes from origin.
-**                  origin  - Initial position: BTA_FS_SEEK_SET, BTA_FS_SEEK_CUR,
-**                            or BTA_FS_SEEK_END.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_seek (int fd, INT32 offset, INT16 origin, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_access
-**
-** Description      This function is called to check the existence of a file or
-**                  directory.
-**
-** Parameters       p_path   - (input) file or directory to access (fully qualified path).
-**                  mode     - (input) [BTA_FS_ACC_EXIST, BTA_FS_ACC_READ, or BTA_FS_ACC_RDWR]
-**                  p_is_dir - (output) returns TRUE if p_path specifies a directory.
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                   [BTA_FS_CO_OK if it exists]
-**                   [BTA_FS_CO_EACCES if permissions are wrong]
-**                   [BTA_FS_CO_FAIL if it does not exist]
-**
-*******************************************************************************/
-BTA_API extern tBTA_FS_CO_STATUS bta_fs_co_access(const char *p_path, int mode,
-                                          BOOLEAN *p_is_dir, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_mkdir
-**
-** Description      This function is called to create a directory with
-**                  the pathname given by path. The pathname is a null terminated
-**                  string. All components of the path must already exist.
-**
-** Parameters       p_path   - (input) name of directory to create (fully qualified path).
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                  [BTA_FS_CO_OK if successful]
-**                  [BTA_FS_CO_FAIL if unsuccessful]
-**
-*******************************************************************************/
-BTA_API extern tBTA_FS_CO_STATUS bta_fs_co_mkdir(const char *p_path, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_rmdir
-**
-** Description      This function is called to remove a directory whose
-**                  name is given by path. The directory must be empty.
-**
-** Parameters       p_path   - (input) name of directory to remove (fully qualified path).
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful]
-**                      [BTA_FS_CO_EACCES if read-only]
-**                      [BTA_FS_CO_ENOTEMPTY if directory is not empty]
-**                      [BTA_FS_CO_FAIL otherwise]
-**
-*******************************************************************************/
-BTA_API extern tBTA_FS_CO_STATUS bta_fs_co_rmdir(const char *p_path, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_unlink
-**
-** Description      This function is called by to remove a file whose name
-**                  is given by p_path.
-**
-** Parameters       p_path   - (input) name of file to remove (fully qualified path).
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful]
-**                      [BTA_FS_CO_EACCES if read-only]
-**                      [BTA_FS_CO_FAIL otherwise]
-**
-*******************************************************************************/
-BTA_API extern tBTA_FS_CO_STATUS bta_fs_co_unlink(const char *p_path, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_getdirentry
-**
-** Description      This function is called to retrieve a directory entry for the
-**                  specified path.  The first/next directory should be filled
-**                  into the location specified by p_entry.
-**
-** Parameters       p_path      - directory to search (Fully qualified path)
-**                  first_item  - TRUE if first search, FALSE if next search
-**                                      (p_cur contains previous)
-**                  p_entry (input/output) - Points to last entry data (valid when
-**                                           first_item is FALSE)
-**                  evt     - event that must be passed into the call-in function.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-**                  Note: Upon completion of the request, the status is passed
-**                        in the bta_fs_ci_direntry() call-in function.
-**                        BTA_FS_CO_OK is returned when p_entry is valid,
-**                        BTA_FS_CO_EODIR is returned when no more entries [finished]
-**                        BTA_FS_CO_FAIL is returned if an error occurred
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_getdirentry(const char *p_path, BOOLEAN first_item,
-                                   tBTA_FS_DIRENTRY *p_entry, UINT16 evt,
-                                   UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_copy
-**
-** Description      This function is called to copy a file/directory whose
-**                  name is given by p_src_path to p_dest_path.
-**
-** Parameters       p_src_path  - (input) name of file/directory to be copied (fully qualified path).
-**                  p_dest_path - (input) new name of file/directory(fully qualified path).
-**                  p_perms     - the permission of the new object.
-**                  evt     - event that must be passed into the call-in function.
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful]
-**                      [BTA_FS_CO_EIS_DIR if p_src_path is a folder]
-**                      [BTA_FS_CO_EACCES if p_dest_path already exists or could not be created (invalid path);
-**                                        or p_src_path is a directory and p_dest_path specifies a different path. ]
-**                      [BTA_FS_CO_FAIL otherwise]
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_copy(const char *p_src_path, const char *p_dest_path, UINT8 *p_perms, UINT16 evt, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_rename
-**
-** Description      This function is called to move a file/directory whose
-**                  name is given by p_src_path to p_dest_path.
-**
-** Parameters       p_src_path  - (input) name of file/directory to be moved (fully qualified path).
-**                  p_dest_path - (input) new name of file/directory(fully qualified path).
-**                  p_perms     - the permission of the new object.
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful]
-**                      [BTA_FS_CO_EACCES if p_dest_path already exists or could not be created (invalid path);
-**                                        or p_src_path is a directory and p_dest_path specifies a different path. ]
-**                      [BTA_FS_CO_FAIL otherwise]
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_rename(const char *p_src_path, const char *p_dest_path, UINT8 *p_perms, UINT16 evt, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_set_perms
-**
-** Description      This function is called to set the permission a file/directory
-**                  with name as p_src_path.
-**
-** Parameters       p_src_path  - (input) name of file/directory to set permission (fully qualified path).
-**                  p_perms     - the permission .
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful]
-**                      [BTA_FS_CO_EACCES if p_dest_path already exists or could not be created (invalid path);
-**                                        or p_src_path is a directory and p_dest_path specifies a different path. ]
-**                      [BTA_FS_CO_FAIL otherwise]
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_set_perms(const char *p_src_path,  UINT8 *p_perms, UINT16 evt, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_sess_fopen
-**
-** Description      This function is called by bta_fs_co_open to keep track of
-**                  the opened file (for reliable session suspend/resume.)
-**
-** Parameters       p_path  - Fully qualified path and file name.
-**                  oflags  - permissions and mode (see constants above)
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_sess_fopen(const char *p_path, int oflags, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_sess_fclose
-**
-** Description      This function is called by bta_fs_co_close
-**
-** Parameters       app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_sess_fclose(UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_sess_offset
-**
-** Description      This function is called by bta_fs_co_write to keep track of
-**                  the last file offset (Only the receiving side needs to keep
-**                  track of the file offset)
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_sess_offset(UINT8 ssn, INT32 pos, UINT16 nbytes, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_suspended_addr
-**
-** Description      find the peer address of the suspended session control block
-**                  for the given an app_id.
-**
-** Returns          the control block found.
-**
-*******************************************************************************/
-BTA_API extern UINT8 *bta_fs_co_suspended_addr(UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_num_suspended_session
-**
-** Description      find the number of suspended session control blocks for the
-**                  given an app_id.
-**
-** Returns          the number of control blocks found.
-**
-*******************************************************************************/
-BTA_API extern UINT8 bta_fs_co_num_suspended_session(UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_get_active_session
-**
-** Description      find the active session control block for the given an app_id.
-**
-** Returns          the control block found.
-**
-*******************************************************************************/
-BTA_API extern tBTA_FS_CO_SESSION *bta_fs_co_get_active_session(UINT8 app_id);
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_init_db
-**
-** Description      Initialize the session control blocks for platform.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API extern void bta_fs_co_init_db (tBTA_FS_CO_SESSION *p_first);
-
-/*******************************************************************************
-**
-** Function         bta_fs_convert_oflags
-**
-** Description      This function converts the open flags from BTA into MFS.
-**
-** Returns          BTA FS status value.
-**
-*******************************************************************************/
-BTA_API extern int bta_fs_convert_bta_oflags(int bta_oflags);
-
-#endif /* BTA_FS_CO_H */
diff --git a/bta/include/bta_gatt_api.h b/bta/include/bta_gatt_api.h
index 9e75eef..5ef9ad7 100644
--- a/bta/include/bta_gatt_api.h
+++ b/bta/include/bta_gatt_api.h
@@ -648,7 +648,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_Disable(void);
+extern void BTA_GATTC_Disable(void);
 
 /*******************************************************************************
 **
@@ -663,7 +663,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_AppRegister(tBT_UUID *p_app_uuid, tBTA_GATTC_CBACK *p_client_cb);
+extern void BTA_GATTC_AppRegister(tBT_UUID *p_app_uuid, tBTA_GATTC_CBACK *p_client_cb);
 
 /*******************************************************************************
 **
@@ -677,7 +677,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_AppDeregister (tBTA_GATTC_IF client_if);
+extern void BTA_GATTC_AppDeregister (tBTA_GATTC_IF client_if);
 
 /*******************************************************************************
 **
@@ -693,8 +693,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_Open(tBTA_GATTC_IF client_if, BD_ADDR remote_bda,
-                                   BOOLEAN is_direct, tBTA_GATT_TRANSPORT transport);
+extern void BTA_GATTC_Open(tBTA_GATTC_IF client_if, BD_ADDR remote_bda,
+                           BOOLEAN is_direct, tBTA_GATT_TRANSPORT transport);
 
 /*******************************************************************************
 **
@@ -710,7 +710,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_CancelOpen(tBTA_GATTC_IF client_if, BD_ADDR remote_bda, BOOLEAN is_direct);
+extern void BTA_GATTC_CancelOpen(tBTA_GATTC_IF client_if, BD_ADDR remote_bda, BOOLEAN is_direct);
 
 /*******************************************************************************
 **
@@ -723,7 +723,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_Close(UINT16 conn_id);
+extern void BTA_GATTC_Close(UINT16 conn_id);
 
 /*******************************************************************************
 **
@@ -741,7 +741,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_ServiceSearchRequest(UINT16 conn_id, tBT_UUID *p_srvc_uuid);
+extern void BTA_GATTC_ServiceSearchRequest(UINT16 conn_id, tBT_UUID *p_srvc_uuid);
 
 /*******************************************************************************
 **
@@ -761,11 +761,11 @@
 ** Returns          returns status.
 **
 *******************************************************************************/
-BTA_API extern tBTA_GATT_STATUS  BTA_GATTC_GetFirstChar (UINT16              conn_id,
-                                                         tBTA_GATT_SRVC_ID   *p_srvc_id,
-                                                         tBT_UUID            *p_char_uuid_cond,
-                                                         tBTA_GATTC_CHAR_ID  *p_char_result,
-                                                         tBTA_GATT_CHAR_PROP *p_property);
+extern tBTA_GATT_STATUS  BTA_GATTC_GetFirstChar (UINT16              conn_id,
+                                                 tBTA_GATT_SRVC_ID   *p_srvc_id,
+                                                 tBT_UUID            *p_char_uuid_cond,
+                                                 tBTA_GATTC_CHAR_ID  *p_char_result,
+                                                 tBTA_GATT_CHAR_PROP *p_property);
 
 /*******************************************************************************
 **
@@ -786,11 +786,11 @@
 ** Returns          returns status.
 **
 *******************************************************************************/
-BTA_API extern tBTA_GATT_STATUS  BTA_GATTC_GetNextChar (UINT16 conn_id,
-                                                        tBTA_GATTC_CHAR_ID  *p_start_char_id,
-                                                        tBT_UUID            *p_char_uuid_cond,
-                                                        tBTA_GATTC_CHAR_ID  *p_char_result,
-                                                        tBTA_GATT_CHAR_PROP *p_property);
+extern tBTA_GATT_STATUS  BTA_GATTC_GetNextChar (UINT16 conn_id,
+                                                tBTA_GATTC_CHAR_ID  *p_start_char_id,
+                                                tBT_UUID            *p_char_uuid_cond,
+                                                tBTA_GATTC_CHAR_ID  *p_char_result,
+                                                tBTA_GATT_CHAR_PROP *p_property);
 
 /*******************************************************************************
 **
@@ -809,9 +809,9 @@
 ** Returns          returns status.
 **
 *******************************************************************************/
-BTA_API extern tBTA_GATT_STATUS  BTA_GATTC_GetFirstCharDescr (UINT16 conn_id, tBTA_GATTC_CHAR_ID *p_char_id,
-                                                tBT_UUID *p_descr_uuid_cond,
-                                                tBTA_GATTC_CHAR_DESCR_ID *p_descr_result);
+extern tBTA_GATT_STATUS  BTA_GATTC_GetFirstCharDescr (UINT16 conn_id, tBTA_GATTC_CHAR_ID *p_char_id,
+                                                      tBT_UUID *p_descr_uuid_cond,
+                                                      tBTA_GATTC_CHAR_DESCR_ID *p_descr_result);
 
 /*******************************************************************************
 **
@@ -831,10 +831,10 @@
 ** Returns          returns status.
 **
 *******************************************************************************/
-BTA_API extern tBTA_GATT_STATUS  BTA_GATTC_GetNextCharDescr (UINT16 conn_id,
-                                             tBTA_GATTC_CHAR_DESCR_ID *p_start_descr_id,
-                                             tBT_UUID           *p_descr_uuid_cond,
-                                             tBTA_GATTC_CHAR_DESCR_ID *p_descr_result);
+extern tBTA_GATT_STATUS  BTA_GATTC_GetNextCharDescr (UINT16 conn_id,
+                                                     tBTA_GATTC_CHAR_DESCR_ID *p_start_descr_id,
+                                                     tBT_UUID           *p_descr_uuid_cond,
+                                                     tBTA_GATTC_CHAR_DESCR_ID *p_descr_result);
 
 
 /*******************************************************************************
@@ -854,10 +854,10 @@
 ** Returns          returns status.
 **
 *******************************************************************************/
-BTA_API extern tBTA_GATT_STATUS  BTA_GATTC_GetFirstIncludedService(UINT16 conn_id,
-                                                                   tBTA_GATT_SRVC_ID    *p_srvc_id,
-                                                                   tBT_UUID               *p_uuid_cond,
-                                                                   tBTA_GATTC_INCL_SVC_ID *p_result);
+extern tBTA_GATT_STATUS  BTA_GATTC_GetFirstIncludedService(UINT16 conn_id,
+                                                           tBTA_GATT_SRVC_ID    *p_srvc_id,
+                                                           tBT_UUID               *p_uuid_cond,
+                                                           tBTA_GATTC_INCL_SVC_ID *p_result);
 
 /*******************************************************************************
 **
@@ -877,10 +877,10 @@
 ** Returns          returns status.
 **
 *******************************************************************************/
-BTA_API extern tBTA_GATT_STATUS  BTA_GATTC_GetNextIncludedService(UINT16 conn_id,
-                                                                  tBTA_GATTC_INCL_SVC_ID *p_start_id,
-                                                                  tBT_UUID             *p_uuid_cond,
-                                                                  tBTA_GATTC_INCL_SVC_ID *p_result);
+extern tBTA_GATT_STATUS  BTA_GATTC_GetNextIncludedService(UINT16 conn_id,
+                                                          tBTA_GATTC_INCL_SVC_ID *p_start_id,
+                                                          tBT_UUID             *p_uuid_cond,
+                                                          tBTA_GATTC_INCL_SVC_ID *p_result);
 
 /*******************************************************************************
 **
@@ -895,9 +895,9 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_ReadCharacteristic (UINT16 conn_id,
-                                                  tBTA_GATTC_CHAR_ID *p_char_id,
-                                                  tBTA_GATT_AUTH_REQ auth_req);
+extern void BTA_GATTC_ReadCharacteristic (UINT16 conn_id,
+                                          tBTA_GATTC_CHAR_ID *p_char_id,
+                                          tBTA_GATT_AUTH_REQ auth_req);
 
 /*******************************************************************************
 **
@@ -911,9 +911,9 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_ReadCharDescr (UINT16 conn_id,
-                                             tBTA_GATTC_CHAR_DESCR_ID *p_char_descr_id,
-                                             tBTA_GATT_AUTH_REQ auth_req);
+extern void BTA_GATTC_ReadCharDescr (UINT16 conn_id,
+                                     tBTA_GATTC_CHAR_DESCR_ID *p_char_descr_id,
+                                     tBTA_GATT_AUTH_REQ auth_req);
 
 /*******************************************************************************
 **
@@ -930,12 +930,12 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_WriteCharValue (UINT16 conn_id,
-                                              tBTA_GATTC_CHAR_ID *p_char_id,
-                                              tBTA_GATTC_WRITE_TYPE  write_type,
-                                              UINT16 len,
-                                              UINT8 *p_value,
-                                              tBTA_GATT_AUTH_REQ auth_req);
+extern void BTA_GATTC_WriteCharValue (UINT16 conn_id,
+                                      tBTA_GATTC_CHAR_ID *p_char_id,
+                                      tBTA_GATTC_WRITE_TYPE  write_type,
+                                      UINT16 len,
+                                      UINT8 *p_value,
+                                      tBTA_GATT_AUTH_REQ auth_req);
 
 /*******************************************************************************
 **
@@ -951,11 +951,11 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_WriteCharDescr (UINT16 conn_id,
-                                              tBTA_GATTC_CHAR_DESCR_ID *p_char_descr_id,
-                                              tBTA_GATTC_WRITE_TYPE  write_type,
-                                              tBTA_GATT_UNFMT   *p_data,
-                                              tBTA_GATT_AUTH_REQ auth_req);
+extern void BTA_GATTC_WriteCharDescr (UINT16 conn_id,
+                                      tBTA_GATTC_CHAR_DESCR_ID *p_char_descr_id,
+                                      tBTA_GATTC_WRITE_TYPE  write_type,
+                                      tBTA_GATT_UNFMT   *p_data,
+                                      tBTA_GATT_AUTH_REQ auth_req);
 
 /*******************************************************************************
 **
@@ -969,7 +969,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_SendIndConfirm (UINT16 conn_id, tBTA_GATTC_CHAR_ID *p_char_id);
+extern void BTA_GATTC_SendIndConfirm (UINT16 conn_id, tBTA_GATTC_CHAR_ID *p_char_id);
 
 /*******************************************************************************
 **
@@ -984,9 +984,9 @@
 ** Returns          OK if registration succeed, otherwise failed.
 **
 *******************************************************************************/
-BTA_API extern tBTA_GATT_STATUS BTA_GATTC_RegisterForNotifications (tBTA_GATTC_IF      client_if,
-                                                                    BD_ADDR            remote_bda,
-                                                                    tBTA_GATTC_CHAR_ID *p_char_id);
+extern tBTA_GATT_STATUS BTA_GATTC_RegisterForNotifications (tBTA_GATTC_IF      client_if,
+                                                            BD_ADDR            remote_bda,
+                                                            tBTA_GATTC_CHAR_ID *p_char_id);
 
 
 /*******************************************************************************
@@ -1002,9 +1002,9 @@
 ** Returns          OK if deregistration succeed, otherwise failed.
 **
 *******************************************************************************/
-BTA_API extern tBTA_GATT_STATUS BTA_GATTC_DeregisterForNotifications (tBTA_GATTC_IF      client_if,
-                                                                      BD_ADDR            remote_bda,
-                                                                      tBTA_GATTC_CHAR_ID *p_char_id);
+extern tBTA_GATT_STATUS BTA_GATTC_DeregisterForNotifications (tBTA_GATTC_IF      client_if,
+                                                              BD_ADDR            remote_bda,
+                                                              tBTA_GATTC_CHAR_ID *p_char_id);
 
 /*******************************************************************************
 **
@@ -1021,12 +1021,12 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_PrepareWrite  (UINT16 conn_id,
-                                             tBTA_GATTC_CHAR_ID *p_char_id,
-                                             UINT16 offset,
-                                             UINT16 len,
-                                             UINT8 *p_value,
-                                             tBTA_GATT_AUTH_REQ auth_req);
+extern void BTA_GATTC_PrepareWrite  (UINT16 conn_id,
+                                     tBTA_GATTC_CHAR_ID *p_char_id,
+                                     UINT16 offset,
+                                     UINT16 len,
+                                     UINT8 *p_value,
+                                     tBTA_GATT_AUTH_REQ auth_req);
 
 /*******************************************************************************
 **
@@ -1040,7 +1040,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_ExecuteWrite  (UINT16 conn_id, BOOLEAN is_execute);
+extern void BTA_GATTC_ExecuteWrite  (UINT16 conn_id, BOOLEAN is_execute);
 
 /*******************************************************************************
 **
@@ -1055,8 +1055,8 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_ReadMultiple(UINT16 conn_id, tBTA_GATTC_MULTI *p_read_multi,
-                                           tBTA_GATT_AUTH_REQ auth_req);
+extern void BTA_GATTC_ReadMultiple(UINT16 conn_id, tBTA_GATTC_MULTI *p_read_multi,
+                                   tBTA_GATT_AUTH_REQ auth_req);
 
 
 /*******************************************************************************
@@ -1070,7 +1070,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_Refresh(BD_ADDR remote_bda);
+extern void BTA_GATTC_Refresh(BD_ADDR remote_bda);
 
 
 /*******************************************************************************
@@ -1087,7 +1087,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_Listen(tBTA_GATTC_IF client_if, BOOLEAN start, BD_ADDR_PTR target_bda);
+extern void BTA_GATTC_Listen(tBTA_GATTC_IF client_if, BOOLEAN start, BD_ADDR_PTR target_bda);
 
 /*******************************************************************************
 **
@@ -1101,7 +1101,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_Broadcast(tBTA_GATTC_IF client_if, BOOLEAN start);
+extern void BTA_GATTC_Broadcast(tBTA_GATTC_IF client_if, BOOLEAN start);
 
 
 /*******************************************************************************
@@ -1117,7 +1117,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_GATTC_ConfigureMTU (UINT16 conn_id, UINT16 mtu);
+extern void BTA_GATTC_ConfigureMTU (UINT16 conn_id, UINT16 mtu);
 
 /*******************************************************************************
 **  BTA GATT Server API
@@ -1134,7 +1134,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_Init();
+extern void BTA_GATTS_Init();
 
 /*******************************************************************************
 **
@@ -1147,7 +1147,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_Disable(void);
+extern void BTA_GATTS_Disable(void);
 
 /*******************************************************************************
 **
@@ -1162,7 +1162,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_AppRegister(tBT_UUID *p_app_uuid, tBTA_GATTS_CBACK *p_cback);
+extern void BTA_GATTS_AppRegister(tBT_UUID *p_app_uuid, tBTA_GATTS_CBACK *p_cback);
 
 
 /*******************************************************************************
@@ -1176,7 +1176,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_AppDeregister(tBTA_GATTS_IF server_if);
+extern void BTA_GATTS_AppDeregister(tBTA_GATTS_IF server_if);
 
 /*******************************************************************************
 **
@@ -1197,8 +1197,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_CreateService(tBTA_GATTS_IF server_if, tBT_UUID *p_service_uuid,
-                                                UINT8 inst, UINT16 num_handle, BOOLEAN is_primary);
+extern void BTA_GATTS_CreateService(tBTA_GATTS_IF server_if, tBT_UUID *p_service_uuid,
+                                    UINT8 inst, UINT16 num_handle, BOOLEAN is_primary);
 
 /*******************************************************************************
 **
@@ -1215,7 +1215,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_AddIncludeService(UINT16 service_id, UINT16 included_service_id);
+extern void BTA_GATTS_AddIncludeService(UINT16 service_id, UINT16 included_service_id);
 
 /*******************************************************************************
 **
@@ -1232,8 +1232,8 @@
 ** Returns          None
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_AddCharacteristic (UINT16 service_id,  tBT_UUID   *p_char_uuid,
-                                                     tBTA_GATT_PERM perm, tBTA_GATT_CHAR_PROP property);
+extern void BTA_GATTS_AddCharacteristic (UINT16 service_id,  tBT_UUID   *p_char_uuid,
+                                         tBTA_GATT_PERM perm, tBTA_GATT_CHAR_PROP property);
 
 /*******************************************************************************
 **
@@ -1252,9 +1252,9 @@
 ** Returns          returns status.
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_AddCharDescriptor (UINT16 service_id,
-                                                     tBTA_GATT_PERM perm,
-                                                     tBT_UUID  * p_descr_uuid);
+extern void BTA_GATTS_AddCharDescriptor (UINT16 service_id,
+                                         tBTA_GATT_PERM perm,
+                                         tBT_UUID  * p_descr_uuid);
 
 /*******************************************************************************
 **
@@ -1268,7 +1268,7 @@
 ** Returns          returns none.
 **
 *******************************************************************************/
-    BTA_API extern void  BTA_GATTS_DeleteService(UINT16 service_id);
+extern void  BTA_GATTS_DeleteService(UINT16 service_id);
 
 /*******************************************************************************
 **
@@ -1282,7 +1282,7 @@
 ** Returns          None.
 **
 *******************************************************************************/
-    BTA_API extern void  BTA_GATTS_StartService(UINT16 service_id, tBTA_GATT_TRANSPORT sup_transport);
+extern void  BTA_GATTS_StartService(UINT16 service_id, tBTA_GATT_TRANSPORT sup_transport);
 
 /*******************************************************************************
 **
@@ -1295,7 +1295,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_StopService(UINT16 service_id);
+extern void BTA_GATTS_StopService(UINT16 service_id);
 
 /*******************************************************************************
 **
@@ -1312,10 +1312,10 @@
 ** Returns          None
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_HandleValueIndication (UINT16 conn_id, UINT16 attr_id,
-                                                         UINT16 data_len,
-                                                         UINT8 *p_data,
-                                                         BOOLEAN need_confirm);
+extern void BTA_GATTS_HandleValueIndication (UINT16 conn_id, UINT16 attr_id,
+                                             UINT16 data_len,
+                                             UINT8 *p_data,
+                                             BOOLEAN need_confirm);
 
 /*******************************************************************************
 **
@@ -1331,10 +1331,8 @@
 ** Returns          None
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_SendRsp (UINT16 conn_id, UINT32 trans_id,
-                                           tBTA_GATT_STATUS status, tBTA_GATTS_RSP *p_msg);
-
-
+extern void BTA_GATTS_SendRsp (UINT16 conn_id, UINT32 trans_id,
+                               tBTA_GATT_STATUS status, tBTA_GATTS_RSP *p_msg);
 
 
 /*******************************************************************************
@@ -1351,8 +1349,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_Open(tBTA_GATTS_IF server_if, BD_ADDR remote_bda,
-                                        BOOLEAN is_direct, tBTA_GATT_TRANSPORT transport);
+extern void BTA_GATTS_Open(tBTA_GATTS_IF server_if, BD_ADDR remote_bda,
+                           BOOLEAN is_direct, tBTA_GATT_TRANSPORT transport);
 
 
 /*******************************************************************************
@@ -1369,7 +1367,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_CancelOpen(tBTA_GATTS_IF server_if, BD_ADDR remote_bda, BOOLEAN is_direct);
+extern void BTA_GATTS_CancelOpen(tBTA_GATTS_IF server_if, BD_ADDR remote_bda, BOOLEAN is_direct);
 
 
 /*******************************************************************************
@@ -1383,7 +1381,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_Close(UINT16 conn_id);
+extern void BTA_GATTS_Close(UINT16 conn_id);
 
 /*******************************************************************************
 **
@@ -1400,8 +1398,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_GATTS_Listen(tBTA_GATTS_IF server_if, BOOLEAN start,
-                                        BD_ADDR_PTR target_bda);
+extern void BTA_GATTS_Listen(tBTA_GATTS_IF server_if, BOOLEAN start,
+                             BD_ADDR_PTR target_bda);
 
 
 #ifdef __cplusplus
@@ -1411,4 +1409,3 @@
 
 
 #endif /* BTA_GATT_API_H */
-
diff --git a/bta/include/bta_gattc_ci.h b/bta/include/bta_gattc_ci.h
index 1525e3e..a64bf89 100644
--- a/bta/include/bta_gattc_ci.h
+++ b/bta/include/bta_gattc_ci.h
@@ -71,7 +71,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_gattc_ci_cache_open(BD_ADDR server_bda, UINT16 evt,
+extern void bta_gattc_ci_cache_open(BD_ADDR server_bda, UINT16 evt,
                                             tBTA_GATT_STATUS status, UINT16 conn_id);
 
 /*******************************************************************************
@@ -90,9 +90,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_gattc_ci_cache_load(BD_ADDR server_bda, UINT16 evt,
-                                            UINT16 num_attr, tBTA_GATTC_NV_ATTR *p_atrr,
-                                            tBTA_GATT_STATUS status, UINT16 conn_id);
+extern void bta_gattc_ci_cache_load(BD_ADDR server_bda, UINT16 evt,
+                                    UINT16 num_attr, tBTA_GATTC_NV_ATTR *p_atrr,
+                                    tBTA_GATT_STATUS status, UINT16 conn_id);
 
 /*******************************************************************************
 **
@@ -108,8 +108,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_gattc_ci_cache_save(BD_ADDR server_bda, UINT16 evt,
-                                            tBTA_GATT_STATUS status, UINT16 conn_id);
+extern void bta_gattc_ci_cache_save(BD_ADDR server_bda, UINT16 evt,
+                                    tBTA_GATT_STATUS status, UINT16 conn_id);
 
 
 #ifdef __cplusplus
@@ -117,4 +117,3 @@
 #endif
 
 #endif /* BTA_GATTC_CI_H */
-
diff --git a/bta/include/bta_gattc_co.h b/bta/include/bta_gattc_co.h
index fa882ec..b96ebf3 100644
--- a/bta/include/bta_gattc_co.h
+++ b/bta/include/bta_gattc_co.h
@@ -41,7 +41,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_gattc_co_cache_open(BD_ADDR server_bda, UINT16 evt,
+extern void bta_gattc_co_cache_open(BD_ADDR server_bda, UINT16 evt,
                                             UINT16 conn_id, BOOLEAN to_save);
 
 /*******************************************************************************
@@ -57,7 +57,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_gattc_co_cache_close(BD_ADDR server_bda, UINT16 conn_id);
+extern void bta_gattc_co_cache_close(BD_ADDR server_bda, UINT16 conn_id);
 
 /*******************************************************************************
 **
@@ -75,9 +75,9 @@
 ** Returns
 **
 *******************************************************************************/
-BTA_API extern void bta_gattc_co_cache_save(BD_ADDR server_bda, UINT16 evt,
-                                          UINT16 num_attr, tBTA_GATTC_NV_ATTR *p_attr,
-                                          UINT16 attr_index, UINT16 conn_id);
+extern void bta_gattc_co_cache_save(BD_ADDR server_bda, UINT16 evt,
+                                    UINT16 num_attr, tBTA_GATTC_NV_ATTR *p_attr,
+                                    UINT16 attr_index, UINT16 conn_id);
 
 /*******************************************************************************
 **
@@ -94,8 +94,8 @@
 ** Returns
 **
 *******************************************************************************/
-BTA_API extern void bta_gattc_co_cache_load(BD_ADDR server_bda, UINT16 evt,
-                                            UINT16 start_index, UINT16 conn_id);
+extern void bta_gattc_co_cache_load(BD_ADDR server_bda, UINT16 evt,
+                                    UINT16 start_index, UINT16 conn_id);
 
 /*******************************************************************************
 **
@@ -109,7 +109,6 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_gattc_co_cache_reset(BD_ADDR server_bda);
+extern void bta_gattc_co_cache_reset(BD_ADDR server_bda);
 
 #endif /* BTA_GATT_CO_H */
-
diff --git a/bta/include/bta_gatts_co.h b/bta/include/bta_gatts_co.h
index 86f65dc..b3ee99b 100644
--- a/bta/include/bta_gatts_co.h
+++ b/bta/include/bta_gatts_co.h
@@ -39,7 +39,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_gatts_co_update_handle_range(BOOLEAN is_add, tBTA_GATTS_HNDL_RANGE *p_hndl_range);
+extern void bta_gatts_co_update_handle_range(BOOLEAN is_add, tBTA_GATTS_HNDL_RANGE *p_hndl_range);
 
 /*******************************************************************************
 **
@@ -58,9 +58,9 @@
 **                  FASLE - if the request can not be processed
 **
 *******************************************************************************/
-BTA_API extern BOOLEAN bta_gatts_co_srv_chg(tBTA_GATTS_SRV_CHG_CMD cmd,
-                                            tBTA_GATTS_SRV_CHG_REQ *p_req,
-                                            tBTA_GATTS_SRV_CHG_RSP *p_rsp);
+extern BOOLEAN bta_gatts_co_srv_chg(tBTA_GATTS_SRV_CHG_CMD cmd,
+                                    tBTA_GATTS_SRV_CHG_REQ *p_req,
+                                    tBTA_GATTS_SRV_CHG_RSP *p_rsp);
 
 /*******************************************************************************
 **
@@ -74,9 +74,8 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern  BOOLEAN bta_gatts_co_load_handle_range(UINT8 index,
-                                                       tBTA_GATTS_HNDL_RANGE *p_handle);
+extern  BOOLEAN bta_gatts_co_load_handle_range(UINT8 index,
+                                               tBTA_GATTS_HNDL_RANGE *p_handle);
 
 
 #endif /* BTA_GATTS_CO_H */
-
diff --git a/bta/include/bta_hf_client_api.h b/bta/include/bta_hf_client_api.h
index 8ef42f4..82235fa 100644
--- a/bta/include/bta_hf_client_api.h
+++ b/bta/include/bta_hf_client_api.h
@@ -270,7 +270,7 @@
 ** Returns          BTA_SUCCESS if OK, BTA_FAILURE otherwise.
 **
 *******************************************************************************/
-BTA_API tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK *p_cback);
+tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -282,7 +282,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientDisable(void);
+void BTA_HfClientDisable(void);
 
 /*******************************************************************************
 **
@@ -294,8 +294,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientRegister(tBTA_SEC sec_mask, tBTA_HF_CLIENT_FEAT features,
-                                                        char *p_service_name);
+void BTA_HfClientRegister(tBTA_SEC sec_mask, tBTA_HF_CLIENT_FEAT features,
+                          char *p_service_name);
 
 /*******************************************************************************
 **
@@ -307,7 +307,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientDeregister(UINT16 handle);
+void BTA_HfClientDeregister(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -322,7 +322,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientOpen(UINT16 handle, BD_ADDR bd_addr, tBTA_SEC sec_mask);
+void BTA_HfClientOpen(UINT16 handle, BD_ADDR bd_addr, tBTA_SEC sec_mask);
 
 /*******************************************************************************
 **
@@ -335,7 +335,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientClose(UINT16 handle);
+void BTA_HfClientClose(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -348,7 +348,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientAudioOpen(UINT16 handle);
+void BTA_HfClientAudioOpen(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -361,7 +361,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientAudioClose(UINT16 handle);
+void BTA_HfClientAudioClose(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -373,7 +373,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_HfClientSendAT(UINT16 handle, tBTA_HF_CLIENT_AT_CMD_TYPE at, UINT32 val1, UINT32 val2, const char *str);
+void BTA_HfClientSendAT(UINT16 handle, tBTA_HF_CLIENT_AT_CMD_TYPE at, UINT32 val1, UINT32 val2, const char *str);
 
 #ifdef __cplusplus
 }
diff --git a/bta/include/bta_hh_api.h b/bta/include/bta_hh_api.h
index 893cac5..d43e492 100644
--- a/bta/include/bta_hh_api.h
+++ b/bta/include/bta_hh_api.h
@@ -330,7 +330,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhEnable(tBTA_SEC sec_mask, tBTA_HH_CBACK *p_cback);
+extern void BTA_HhEnable(tBTA_SEC sec_mask, tBTA_HH_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -341,7 +341,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhDisable(void);
+extern void BTA_HhDisable(void);
 
 /*******************************************************************************
 **
@@ -354,8 +354,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhOpen (BD_ADDR dev_bda, tBTA_HH_PROTO_MODE mode,
-                                tBTA_SEC sec_mask);
+extern void BTA_HhOpen (BD_ADDR dev_bda, tBTA_HH_PROTO_MODE mode,
+                        tBTA_SEC sec_mask);
 
 /*******************************************************************************
 **
@@ -366,7 +366,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhClose(UINT8 dev_handle);
+extern void BTA_HhClose(UINT8 dev_handle);
 
 /*******************************************************************************
 **
@@ -377,7 +377,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhSetProtoMode(UINT8 handle, tBTA_HH_PROTO_MODE t_type);
+extern void BTA_HhSetProtoMode(UINT8 handle, tBTA_HH_PROTO_MODE t_type);
 
 /*******************************************************************************
 **
@@ -388,7 +388,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhGetProtoMode(UINT8 dev_handle);
+extern void BTA_HhGetProtoMode(UINT8 dev_handle);
 /*******************************************************************************
 **
 ** Function         BTA_HhSetReport
@@ -398,8 +398,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhSetReport(UINT8 dev_handle, tBTA_HH_RPT_TYPE r_type,
-                                        BT_HDR *p_data);
+extern void BTA_HhSetReport(UINT8 dev_handle, tBTA_HH_RPT_TYPE r_type,
+                            BT_HDR *p_data);
 
 /*******************************************************************************
 **
@@ -410,8 +410,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhGetReport(UINT8 dev_handle, tBTA_HH_RPT_TYPE r_type,
-                                    UINT8 rpt_id, UINT16 buf_size);
+extern void BTA_HhGetReport(UINT8 dev_handle, tBTA_HH_RPT_TYPE r_type,
+                            UINT8 rpt_id, UINT16 buf_size);
 /*******************************************************************************
 **
 ** Function         BTA_HhSetIdle
@@ -421,7 +421,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhSetIdle(UINT8 dev_handle, UINT16 idle_rate);
+extern void BTA_HhSetIdle(UINT8 dev_handle, UINT16 idle_rate);
 
 /*******************************************************************************
 **
@@ -432,7 +432,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhGetIdle(UINT8 dev_handle);
+extern void BTA_HhGetIdle(UINT8 dev_handle);
 
 /*******************************************************************************
 **
@@ -443,8 +443,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhSendCtrl(UINT8 dev_handle,
-                                   tBTA_HH_TRANS_CTRL_TYPE c_type);
+extern void BTA_HhSendCtrl(UINT8 dev_handle,
+                           tBTA_HH_TRANS_CTRL_TYPE c_type);
 
 /*******************************************************************************
 **
@@ -455,7 +455,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhSetIdle(UINT8 dev_handle, UINT16 idle_rate);
+extern void BTA_HhSetIdle(UINT8 dev_handle, UINT16 idle_rate);
 
 
 /*******************************************************************************
@@ -467,7 +467,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhGetIdle(UINT8 dev_handle);
+extern void BTA_HhGetIdle(UINT8 dev_handle);
 
 /*******************************************************************************
 **
@@ -478,7 +478,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhSendData(UINT8 dev_handle, BD_ADDR dev_bda, BT_HDR  *p_buf);
+extern void BTA_HhSendData(UINT8 dev_handle, BD_ADDR dev_bda, BT_HDR  *p_buf);
 
 /*******************************************************************************
 **
@@ -489,7 +489,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhGetDscpInfo(UINT8 dev_handle);
+extern void BTA_HhGetDscpInfo(UINT8 dev_handle);
 
 /*******************************************************************************
 ** Function         BTA_HhAddDev
@@ -502,9 +502,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhAddDev(BD_ADDR bda, tBTA_HH_ATTR_MASK attr_mask,
-                                 UINT8 sub_class, UINT8 app_id,
-                                 tBTA_HH_DEV_DSCP_INFO dscp_info);
+extern void BTA_HhAddDev(BD_ADDR bda, tBTA_HH_ATTR_MASK attr_mask,
+                         UINT8 sub_class, UINT8 app_id,
+                         tBTA_HH_DEV_DSCP_INFO dscp_info);
 /*******************************************************************************
 **
 ** Function         BTA_HhRemoveDev
@@ -514,7 +514,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhRemoveDev(UINT8 dev_handle );
+extern void BTA_HhRemoveDev(UINT8 dev_handle );
 
 /*******************************************************************************
 **
@@ -530,8 +530,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhParseBootRpt(tBTA_HH_BOOT_RPT *p_data, UINT8 *p_report,
-                                       UINT16 report_len);
+extern void BTA_HhParseBootRpt(tBTA_HH_BOOT_RPT *p_data, UINT8 *p_report,
+                               UINT16 report_len);
 
 #if BTA_HH_LE_INCLUDED == TRUE
 /*******************************************************************************
@@ -544,10 +544,10 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_HhUpdateLeScanParam(UINT8 dev_handle, UINT16 scan_int, UINT16 scan_win);
+extern void BTA_HhUpdateLeScanParam(UINT8 dev_handle, UINT16 scan_int, UINT16 scan_win);
 #endif
 /* test commands */
-BTA_API extern void bta_hh_le_hid_read_rpt_clt_cfg(BD_ADDR bd_addr, UINT8 rpt_id);
+extern void bta_hh_le_hid_read_rpt_clt_cfg(BD_ADDR bd_addr, UINT8 rpt_id);
 
 
 
diff --git a/bta/include/bta_hh_co.h b/bta/include/bta_hh_co.h
index bf73b46..09cb565 100755
--- a/bta/include/bta_hh_co.h
+++ b/bta/include/bta_hh_co.h
@@ -46,9 +46,9 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_hh_co_data(UINT8 dev_handle, UINT8 *p_rpt, UINT16 len,
-                                   tBTA_HH_PROTO_MODE  mode, UINT8 sub_class,
-                                   UINT8 ctry_code, BD_ADDR peer_addr, UINT8 app_id);
+extern void bta_hh_co_data(UINT8 dev_handle, UINT8 *p_rpt, UINT16 len,
+                           tBTA_HH_PROTO_MODE  mode, UINT8 sub_class,
+                           UINT8 ctry_code, BD_ADDR peer_addr, UINT8 app_id);
 
 /*******************************************************************************
 **
@@ -61,8 +61,8 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_hh_co_open(UINT8 dev_handle, UINT8 sub_class,
-                                   UINT16 attr_mask, UINT8 app_id);
+extern void bta_hh_co_open(UINT8 dev_handle, UINT8 sub_class,
+                           UINT16 attr_mask, UINT8 app_id);
 
 /*******************************************************************************
 **
@@ -74,7 +74,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_hh_co_close(UINT8 dev_handle, UINT8 app_id);
+extern void bta_hh_co_close(UINT8 dev_handle, UINT8 app_id);
 
 #if (BLE_INCLUDED == TRUE && BTA_HH_LE_INCLUDED == TRUE)
 /*******************************************************************************
@@ -93,7 +93,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-BTA_API extern void bta_hh_le_co_rpt_info(BD_ADDR remote_bda,
+extern void bta_hh_le_co_rpt_info(BD_ADDR remote_bda,
                                           tBTA_HH_RPT_CACHE_ENTRY *p_entry,
                                           UINT8 app_id);
 
@@ -112,7 +112,7 @@
 ** Returns          the acched report array
 **
 *******************************************************************************/
-BTA_API extern tBTA_HH_RPT_CACHE_ENTRY *bta_hh_le_co_cache_load (BD_ADDR remote_bda,
+extern tBTA_HH_RPT_CACHE_ENTRY *bta_hh_le_co_cache_load (BD_ADDR remote_bda,
                                                                  UINT8 *p_num_rpt,
                                                                  UINT8 app_id);
 
@@ -127,8 +127,7 @@
 ** Returns          none
 **
 *******************************************************************************/
-BTA_API extern void bta_hh_le_co_reset_rpt_cache (BD_ADDR remote_bda, UINT8 app_id);
+extern void bta_hh_le_co_reset_rpt_cache (BD_ADDR remote_bda, UINT8 app_id);
 
 #endif /* #if (BLE_INCLUDED == TRUE && BTA_HH_LE_INCLUDED == TRUE) */
 #endif /* BTA_HH_CO_H */
-
diff --git a/bta/include/bta_hl_api.h b/bta/include/bta_hl_api.h
index f9f6be7..3a154a5 100644
--- a/bta/include/bta_hl_api.h
+++ b/bta/include/bta_hl_api.h
@@ -650,7 +650,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlEnable(tBTA_HL_CTRL_CBACK *p_ctrl_cback);
+extern void BTA_HlEnable(tBTA_HL_CTRL_CBACK *p_ctrl_cback);
 /*******************************************************************************
 **
 ** Function         BTA_HlDisable
@@ -660,7 +660,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlDisable(void);
+extern void BTA_HlDisable(void);
 
 /*******************************************************************************
 **
@@ -676,9 +676,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlUpdate(UINT8  app_id,
-                    tBTA_HL_REG_PARAM *p_reg_param, BOOLEAN is_register,
-                    tBTA_HL_CBACK *p_cback);
+extern void BTA_HlUpdate(UINT8  app_id,
+                         tBTA_HL_REG_PARAM *p_reg_param, BOOLEAN is_register,
+                         tBTA_HL_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -695,9 +695,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlRegister(UINT8  app_id,
-                                       tBTA_HL_REG_PARAM *p_reg_param,
-                                       tBTA_HL_CBACK *p_cback);
+extern void BTA_HlRegister(UINT8  app_id,
+                           tBTA_HL_REG_PARAM *p_reg_param,
+                           tBTA_HL_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -710,7 +710,7 @@
 ** Returns         void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlDeregister(UINT8 app_id,tBTA_HL_APP_HANDLE app_handle);
+extern void BTA_HlDeregister(UINT8 app_id,tBTA_HL_APP_HANDLE app_handle);
 
 /*******************************************************************************
 **
@@ -730,8 +730,8 @@
 **                  Note: If the control PSM value is zero then the first HDP
 **                        instance is used for the control channel setup
 *******************************************************************************/
-    BTA_API extern void BTA_HlCchOpen(UINT8 app_id, tBTA_HL_APP_HANDLE app_handle,
-                                      tBTA_HL_CCH_OPEN_PARAM *p_open_param);
+extern void BTA_HlCchOpen(UINT8 app_id, tBTA_HL_APP_HANDLE app_handle,
+                          tBTA_HL_CCH_OPEN_PARAM *p_open_param);
 
 /*******************************************************************************
 **
@@ -745,7 +745,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern  void BTA_HlCchClose(tBTA_HL_MCL_HANDLE mcl_handle);
+extern  void BTA_HlCchClose(tBTA_HL_MCL_HANDLE mcl_handle);
 
 /*******************************************************************************
 **
@@ -759,8 +759,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern  void BTA_HlDchOpen(tBTA_HL_MCL_HANDLE mcl_handle,
-                                       tBTA_HL_DCH_OPEN_PARAM *p_open_param);
+extern  void BTA_HlDchOpen(tBTA_HL_MCL_HANDLE mcl_handle,
+                           tBTA_HL_DCH_OPEN_PARAM *p_open_param);
 /*******************************************************************************
 **
 ** Function         BTA_HlDchReconnect
@@ -773,8 +773,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlDchReconnect(tBTA_HL_MCL_HANDLE mcl_handle,
-                                            tBTA_HL_DCH_RECONNECT_PARAM *p_recon_param);
+extern void BTA_HlDchReconnect(tBTA_HL_MCL_HANDLE mcl_handle,
+                               tBTA_HL_DCH_RECONNECT_PARAM *p_recon_param);
 /*******************************************************************************
 **
 ** Function         BTA_HlDchClose
@@ -786,7 +786,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlDchClose(tBTA_HL_MDL_HANDLE mdl_handle);
+extern void BTA_HlDchClose(tBTA_HL_MDL_HANDLE mdl_handle);
 
 /*******************************************************************************
 **
@@ -801,7 +801,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlDchAbort(tBTA_HL_MCL_HANDLE mcl_handle);
+extern void BTA_HlDchAbort(tBTA_HL_MCL_HANDLE mcl_handle);
 
 /*******************************************************************************
 **
@@ -815,8 +815,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlSendData(tBTA_HL_MDL_HANDLE mdl_handle,
-                                       UINT16           pkt_size);
+extern void BTA_HlSendData(tBTA_HL_MDL_HANDLE mdl_handle,
+                           UINT16           pkt_size);
 
 /*******************************************************************************
 **
@@ -834,8 +834,8 @@
 **                        not other requests
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlDeleteMdl(tBTA_HL_MCL_HANDLE mcl_handle,
-                                        tBTA_HL_MDL_ID mdl_id );
+extern void BTA_HlDeleteMdl(tBTA_HL_MCL_HANDLE mcl_handle,
+                            tBTA_HL_MDL_ID mdl_id );
 
 /*******************************************************************************
 **
@@ -849,8 +849,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlDchEchoTest( tBTA_HL_MCL_HANDLE  mcl_handle,
-                                           tBTA_HL_DCH_ECHO_TEST_PARAM *p_echo_test_param);
+extern void BTA_HlDchEchoTest( tBTA_HL_MCL_HANDLE  mcl_handle,
+                               tBTA_HL_DCH_ECHO_TEST_PARAM *p_echo_test_param);
 
 /*******************************************************************************
 **
@@ -865,8 +865,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern  void BTA_HlSdpQuery(UINT8  app_id,tBTA_HL_APP_HANDLE app_handle,
-                                        BD_ADDR bd_addr);
+extern  void BTA_HlSdpQuery(UINT8  app_id,tBTA_HL_APP_HANDLE app_handle,
+                            BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -884,8 +884,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTA_API extern void BTA_HlDchCreateRsp(tBTA_HL_MCL_HANDLE mcl_handle,
-                                           tBTA_HL_DCH_CREATE_RSP_PARAM *p_rsp_param);
+extern void BTA_HlDchCreateRsp(tBTA_HL_MCL_HANDLE mcl_handle,
+                               tBTA_HL_DCH_CREATE_RSP_PARAM *p_rsp_param);
 
 
 
@@ -895,41 +895,3 @@
 #endif
 
 #endif /* BTA_HL_API_H */
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/bta/include/bta_hl_ci.h b/bta/include/bta_hl_ci.h
index 4d3951c..c808938 100644
--- a/bta/include/bta_hl_ci.h
+++ b/bta/include/bta_hl_ci.h
@@ -57,9 +57,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern  void bta_hl_ci_get_tx_data(  tBTA_HL_MDL_HANDLE mdl_handle,
-                                             tBTA_HL_STATUS status,
-                                             UINT16 evt );
+extern  void bta_hl_ci_get_tx_data(  tBTA_HL_MDL_HANDLE mdl_handle,
+                                     tBTA_HL_STATUS status,
+                                     UINT16 evt );
 
 /*******************************************************************************
 **
@@ -76,9 +76,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern  void bta_hl_ci_put_rx_data(  tBTA_HL_MDL_HANDLE mdl_handle,
-                                             tBTA_HL_STATUS status,
-                                             UINT16 evt );
+extern  void bta_hl_ci_put_rx_data(  tBTA_HL_MDL_HANDLE mdl_handle,
+                                     tBTA_HL_STATUS status,
+                                     UINT16 evt );
 
 
 
@@ -97,9 +97,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern  void bta_hl_ci_get_echo_data(  tBTA_HL_MCL_HANDLE mcl_handle,
-                                               tBTA_HL_STATUS status,
-                                               UINT16 evt );
+extern  void bta_hl_ci_get_echo_data(  tBTA_HL_MCL_HANDLE mcl_handle,
+                                       tBTA_HL_STATUS status,
+                                       UINT16 evt );
 
 
 /*******************************************************************************
@@ -117,9 +117,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_ci_put_echo_data(  tBTA_HL_MCL_HANDLE mcl_handle,
-                                              tBTA_HL_STATUS status,
-                                              UINT16 evt );
+extern void bta_hl_ci_put_echo_data(  tBTA_HL_MCL_HANDLE mcl_handle,
+                                      tBTA_HL_STATUS status,
+                                      UINT16 evt );
 #endif /* BTA_HL_CI_H */
-
-
diff --git a/bta/include/bta_hl_co.h b/bta/include/bta_hl_co.h
index 2a188db..05b37c7 100644
--- a/bta/include/bta_hl_co.h
+++ b/bta/include/bta_hl_co.h
@@ -50,7 +50,7 @@
 ** Returns         Bloolean - TRUE success
 **
 *******************************************************************************/
-BTA_API extern BOOLEAN bta_hl_co_get_num_of_mdep(UINT8 app_id, UINT8 *p_num_of_mdep);
+extern BOOLEAN bta_hl_co_get_num_of_mdep(UINT8 app_id, UINT8 *p_num_of_mdep);
 /*******************************************************************************
 **
 ** Function        bta_hl_co_advrtise_source_sdp
@@ -64,7 +64,7 @@
 **                            information
 **
 *******************************************************************************/
-BTA_API extern BOOLEAN bta_hl_co_advrtise_source_sdp(UINT8 app_id);
+extern BOOLEAN bta_hl_co_advrtise_source_sdp(UINT8 app_id);
 /*******************************************************************************
 **
 ** Function        bta_hl_co_get_mdep_config
@@ -82,11 +82,11 @@
 **
 ** Returns         Bloolean - TRUE success
 *******************************************************************************/
-BTA_API extern BOOLEAN bta_hl_co_get_mdep_config(UINT8 app_id,
-                                                 UINT8 mdep_idx,
-                                                 UINT8 mdep_counter,
-                                                 tBTA_HL_MDEP_ID mdep_id,
-                                                 tBTA_HL_MDEP_CFG *p_mdep_cfg);
+extern BOOLEAN bta_hl_co_get_mdep_config(UINT8 app_id,
+                                         UINT8 mdep_idx,
+                                         UINT8 mdep_counter,
+                                         tBTA_HL_MDEP_ID mdep_id,
+                                         tBTA_HL_MDEP_CFG *p_mdep_cfg);
 
 
 /*******************************************************************************
@@ -102,8 +102,8 @@
 **
 ** Returns         Bloolean - TRUE success
 *******************************************************************************/
-BTA_API extern BOOLEAN bta_hl_co_get_echo_config(UINT8  app_id,
-                                                 tBTA_HL_ECHO_CFG *p_echo_cfg);
+extern BOOLEAN bta_hl_co_get_echo_config(UINT8  app_id,
+                                         tBTA_HL_ECHO_CFG *p_echo_cfg);
 
 
 /*******************************************************************************
@@ -120,7 +120,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_co_save_mdl(UINT8 app_id, UINT8 item_idx, tBTA_HL_MDL_CFG *p_mdl_cfg );
+extern void bta_hl_co_save_mdl(UINT8 app_id, UINT8 item_idx, tBTA_HL_MDL_CFG *p_mdl_cfg );
 /*******************************************************************************
 **
 ** Function        bta_hl_co_delete_mdl
@@ -134,7 +134,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_co_delete_mdl(UINT8 app_id, UINT8 item_idx);
+extern void bta_hl_co_delete_mdl(UINT8 app_id, UINT8 item_idx);
 /*******************************************************************************
 **
 ** Function         bta_hl_co_get_mdl_config
@@ -151,8 +151,8 @@
 **
 **
 *******************************************************************************/
-BTA_API extern BOOLEAN bta_hl_co_load_mdl_config (UINT8 app_id, UINT8 buffer_size,
-                                                  tBTA_HL_MDL_CFG *p_mdl_buf );
+extern BOOLEAN bta_hl_co_load_mdl_config (UINT8 app_id, UINT8 buffer_size,
+                                          tBTA_HL_MDL_CFG *p_mdl_buf );
 
 
 /*******************************************************************************
@@ -171,8 +171,8 @@
 ** Returns        Void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_co_get_tx_data (UINT8 app_id, tBTA_HL_MDL_HANDLE mdl_handle,
-                                           UINT16 buf_size, UINT8 *p_buf, UINT16 evt);
+extern void bta_hl_co_get_tx_data (UINT8 app_id, tBTA_HL_MDL_HANDLE mdl_handle,
+                                   UINT16 buf_size, UINT8 *p_buf, UINT16 evt);
 
 
 /*******************************************************************************
@@ -191,8 +191,8 @@
 ** Returns        Void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_co_put_rx_data (UINT8 app_id, tBTA_HL_MDL_HANDLE mdl_handle,
-                                           UINT16 data_size, UINT8 *p_data, UINT16 evt);
+extern void bta_hl_co_put_rx_data (UINT8 app_id, tBTA_HL_MDL_HANDLE mdl_handle,
+                                   UINT16 data_size, UINT8 *p_data, UINT16 evt);
 /*******************************************************************************
 **
 ** Function         bta_hl_co_get_tx_data
@@ -209,8 +209,8 @@
 ** Returns        Void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_co_get_echo_data (UINT8 app_id, tBTA_HL_MCL_HANDLE mcl_handle,
-                                             UINT16 buf_size, UINT8 *p_buf, UINT16 evt);
+extern void bta_hl_co_get_echo_data (UINT8 app_id, tBTA_HL_MCL_HANDLE mcl_handle,
+                                     UINT16 buf_size, UINT8 *p_buf, UINT16 evt);
 
 /*******************************************************************************
 **
@@ -228,7 +228,7 @@
 ** Returns        Void
 **
 *******************************************************************************/
-BTA_API extern void bta_hl_co_put_echo_data (UINT8 app_id, tBTA_HL_MCL_HANDLE mcl_handle,
-                                             UINT16 data_size, UINT8 *p_data, UINT16 evt);
+extern void bta_hl_co_put_echo_data (UINT8 app_id, tBTA_HL_MCL_HANDLE mcl_handle,
+                                     UINT16 data_size, UINT8 *p_data, UINT16 evt);
 
 #endif /* BTA_HL_CO_H */
diff --git a/bta/include/bta_jv_api.h b/bta/include/bta_jv_api.h
index 7e53ab6..a61588a 100644
--- a/bta/include/bta_jv_api.h
+++ b/bta/include/bta_jv_api.h
@@ -24,7 +24,6 @@
 #ifndef BTA_JV_API_H
 #define BTA_JV_API_H
 
-#include "data_types.h"
 #include "bt_target.h"
 #include "bt_types.h"
 #include "bta_api.h"
@@ -45,11 +44,6 @@
 #define BTA_JV_MAX_UUIDS        SDP_MAX_UUID_FILTERS
 #define BTA_JV_MAX_ATTRS        SDP_MAX_ATTR_FILTERS
 #define BTA_JV_MAX_SDP_REC      SDP_MAX_RECORDS
-#if SDP_FOR_JV_INCLUDED == TRUE
-#define BTA_JV_MAX_L2C_CONN     (GAP_MAX_CONNECTIONS + 1)
-#else
-#define BTA_JV_MAX_L2C_CONN     GAP_MAX_CONNECTIONS
-#endif
 #define BTA_JV_MAX_SCN          PORT_MAX_RFC_PORTS /* same as BTM_MAX_SCN (in btm_int.h) */
 #define BTA_JV_MAX_RFC_CONN     MAX_RFC_PORTS
 
@@ -81,15 +75,6 @@
 };
 typedef UINT16 tBTA_JV_DISC;
 
-/* Security Mode (BTA_JvGetSecurityMode) */
-#define BTA_JV_SEC_MODE_UNDEFINED   BTM_SEC_MODE_UNDEFINED  /* 0 */
-#define BTA_JV_SEC_MODE_NONE        BTM_SEC_MODE_NONE       /* 1 */
-#define BTA_JV_SEC_MODE_SERVICE     BTM_SEC_MODE_SERVICE    /* 2 */
-#define BTA_JV_SEC_MODE_LINK        BTM_SEC_MODE_LINK       /* 3 */
-#define BTA_JV_SEC_MODE_SP          BTM_SEC_MODE_SP         /* 4 */
-#define BTA_JV_SEC_MODE_SP_DEBUG    BTM_SEC_MODE_SP_DEBUG   /* 5 */
-typedef UINT8 tBTA_JV_SEC_MODE;
-
 #define BTA_JV_ROLE_SLAVE       BTM_ROLE_SLAVE
 #define BTA_JV_ROLE_MASTER      BTM_ROLE_MASTER
 typedef UINT32 tBTA_JV_ROLE;
@@ -136,32 +121,8 @@
 /* Java I/F callback events */
 /* events received by tBTA_JV_DM_CBACK */
 #define BTA_JV_ENABLE_EVT           0  /* JV enabled */
-#define BTA_JV_SET_DISCOVER_EVT     1  /* the result for BTA_JvSetDiscoverability */
-#define BTA_JV_LOCAL_ADDR_EVT       2  /* Local device address */
-#define BTA_JV_LOCAL_NAME_EVT       3  /* Local device name */
-#define BTA_JV_REMOTE_NAME_EVT      4  /* Remote device name */
-#define BTA_JV_SET_ENCRYPTION_EVT   5  /* Set Encryption */
-#define BTA_JV_GET_SCN_EVT          6  /* Reserved an SCN */
-#define BTA_JV_GET_PSM_EVT          7  /* Reserved a PSM */
 #define BTA_JV_DISCOVERY_COMP_EVT   8  /* SDP discovery complete */
-#define BTA_JV_SERVICES_LEN_EVT     9  /* the result for BTA_JvGetServicesLength */
-#define BTA_JV_SERVICE_SEL_EVT      10 /* the result for BTA_JvServiceSelect */
 #define BTA_JV_CREATE_RECORD_EVT    11 /* the result for BTA_JvCreateRecord */
-#define BTA_JV_UPDATE_RECORD_EVT    12 /* the result for BTA_JvUpdateRecord */
-#define BTA_JV_ADD_ATTR_EVT         13 /* the result for BTA_JvAddAttribute */
-#define BTA_JV_DELETE_ATTR_EVT      14 /* the result for BTA_JvDeleteAttribute */
-#define BTA_JV_CANCEL_DISCVRY_EVT   15 /* the result for BTA_JvCancelDiscovery */
-
-/* events received by tBTA_JV_L2CAP_CBACK */
-#define BTA_JV_L2CAP_OPEN_EVT       16 /* open status of L2CAP connection */
-#define BTA_JV_L2CAP_CLOSE_EVT      17 /* L2CAP connection closed */
-#define BTA_JV_L2CAP_START_EVT      18 /* L2CAP server started */
-#define BTA_JV_L2CAP_CL_INIT_EVT    19 /* L2CAP client initiated a connection */
-#define BTA_JV_L2CAP_DATA_IND_EVT   20 /* L2CAP connection received data */
-#define BTA_JV_L2CAP_CONG_EVT       21 /* L2CAP connection congestion status changed */
-#define BTA_JV_L2CAP_READ_EVT       22 /* the result for BTA_JvL2capRead */
-#define BTA_JV_L2CAP_RECEIVE_EVT    23 /* the result for BTA_JvL2capReceive*/
-#define BTA_JV_L2CAP_WRITE_EVT      24 /* the result for BTA_JvL2capWrite*/
 
 /* events received by tBTA_JV_RFCOMM_CBACK */
 #define BTA_JV_RFCOMM_OPEN_EVT      25 /* open status of RFCOMM Client connection */
@@ -191,129 +152,12 @@
     int scn;                    /* channel # */
 } tBTA_JV_DISCOVERY_COMP;
 
-/* data associated with BTA_JV_SET_ENCRYPTION_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    BD_ADDR     bd_addr;        /* The peer address */
-} tBTA_JV_SET_ENCRYPTION;
-
-/* data associated with BTA_JV_SERVICES_LEN_EVT */
-typedef struct
-{
-    INT32       num_services;       /* -1, if error. Otherwise, the number of
-                                     * services collected from peer */
-    UINT16      *p_services_len;    /* this points the same location as the
-                                     * parameter in BTA_JvGetServicesLength() */
-} tBTA_JV_SERVICES_LEN;
-
-/* data associated with BTA_JV_SERVICE_SEL_EVT */
-typedef struct
-{
-    BD_ADDR     bd_addr;            /* The peer address */
-    UINT16      service_len;        /* the length of this record */
-} tBTA_JV_SERVICE_SEL;
-
 /* data associated with BTA_JV_CREATE_RECORD_EVT */
 typedef struct
 {
    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
 } tBTA_JV_CREATE_RECORD;
 
-/* data associated with BTA_JV_UPDATE_RECORD_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The SDP record handle was updated */
-} tBTA_JV_UPDATE_RECORD;
-
-/* data associated with BTA_JV_ADD_ATTR_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The SDP record handle was updated */
-} tBTA_JV_ADD_ATTR;
-
-/* data associated with BTA_JV_DELETE_ATTR_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The SDP record handle was updated */
-} tBTA_JV_DELETE_ATTR;
-
-/* data associated with BTA_JV_L2CAP_OPEN_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The connection handle */
-    BD_ADDR         rem_bda;    /* The peer address */
-    INT32           tx_mtu;     /* The transmit MTU */
-} tBTA_JV_L2CAP_OPEN;
-
-/* data associated with BTA_JV_L2CAP_CLOSE_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The connection handle */
-    BOOLEAN         async;      /* FALSE, if local initiates disconnect */
-} tBTA_JV_L2CAP_CLOSE;
-
-/* data associated with BTA_JV_L2CAP_START_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The connection handle */
-    UINT8           sec_id;     /* security ID used by this server */
-} tBTA_JV_L2CAP_START;
-
-/* data associated with BTA_JV_L2CAP_CL_INIT_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The connection handle */
-    UINT8           sec_id;     /* security ID used by this client */
-} tBTA_JV_L2CAP_CL_INIT;
-
-/* data associated with BTA_JV_L2CAP_CONG_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The connection handle */
-    BOOLEAN         cong;       /* TRUE, congested. FALSE, uncongested */
-} tBTA_JV_L2CAP_CONG;
-
-/* data associated with BTA_JV_L2CAP_READ_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The connection handle */
-    UINT32          req_id;     /* The req_id in the associated BTA_JvL2capRead() */
-    UINT8           *p_data;    /* This points the same location as the p_data
-                                 * parameter in BTA_JvL2capRead () */
-    UINT16          len;        /* The length of the data read. */
-} tBTA_JV_L2CAP_READ;
-
-/* data associated with BTA_JV_L2CAP_RECEIVE_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The connection handle */
-    UINT32          req_id;     /* The req_id in the associated BTA_JvL2capReceive() */
-    UINT8           *p_data;    /* This points the same location as the p_data
-                                 * parameter in BTA_JvL2capReceive () */
-    UINT16          len;        /* The length of the data read. */
-} tBTA_JV_L2CAP_RECEIVE;
-
-/* data associated with BTA_JV_L2CAP_WRITE_EVT */
-typedef struct
-{
-    tBTA_JV_STATUS  status;     /* Whether the operation succeeded or failed. */
-    UINT32          handle;     /* The connection handle */
-    UINT32          req_id;     /* The req_id in the associated BTA_JvL2capWrite() */
-    UINT16          len;        /* The length of the data written. */
-    BOOLEAN         cong;       /* congestion status */
-} tBTA_JV_L2CAP_WRITE;
-
 /* data associated with BTA_JV_RFCOMM_OPEN_EVT */
 typedef struct
 {
@@ -414,25 +258,7 @@
     tBTA_JV_STATUS          status;         /* BTA_JV_ENABLE_EVT */
     tBTA_JV_DISCOVERY_COMP  disc_comp;      /* BTA_JV_DISCOVERY_COMP_EVT */
     tBTA_JV_SET_DISCOVER    set_discover;   /* BTA_JV_SET_DISCOVER_EVT */
-    tBTA_JV_SET_ENCRYPTION  set_encrypt;    /* BTA_JV_SET_ENCRYPTION_EVT */
-    BD_ADDR                 bd_addr;        /* BTA_JV_LOCAL_ADDR_EVT */
-    UINT8                   *p_name;        /* BTA_JV_LOCAL_NAME_EVT,
-                                               BTA_JV_REMOTE_NAME_EVT */
-    UINT8                   scn;            /* BTA_JV_GET_SCN_EVT */
-    UINT16                  psm;            /* BTA_JV_GET_PSM_EVT */
-    tBTA_JV_SERVICES_LEN    servs_len;      /* BTA_JV_SERVICES_LEN_EVT */
-    tBTA_JV_SERVICE_SEL     serv_sel;       /* BTA_JV_SERVICE_SEL_EVT */
     tBTA_JV_CREATE_RECORD   create_rec;     /* BTA_JV_CREATE_RECORD_EVT */
-    tBTA_JV_UPDATE_RECORD   update_rec;     /* BTA_JV_UPDATE_RECORD_EVT */
-    tBTA_JV_ADD_ATTR        add_attr;       /* BTA_JV_ADD_ATTR_EVT */
-    tBTA_JV_DELETE_ATTR     del_attr;       /* BTA_JV_DELETE_ATTR_EVT */
-    tBTA_JV_L2CAP_OPEN      l2c_open;       /* BTA_JV_L2CAP_OPEN_EVT */
-    tBTA_JV_L2CAP_CLOSE     l2c_close;      /* BTA_JV_L2CAP_CLOSE_EVT */
-    tBTA_JV_L2CAP_START     l2c_start;      /* BTA_JV_L2CAP_START_EVT */
-    tBTA_JV_L2CAP_CL_INIT   l2c_cl_init;    /* BTA_JV_L2CAP_CL_INIT_EVT */
-    tBTA_JV_L2CAP_CONG      l2c_cong;       /* BTA_JV_L2CAP_CONG_EVT */
-    tBTA_JV_L2CAP_READ      l2c_read;       /* BTA_JV_L2CAP_READ_EVT */
-    tBTA_JV_L2CAP_WRITE     l2c_write;      /* BTA_JV_L2CAP_WRITE_EVT */
     tBTA_JV_RFCOMM_OPEN     rfc_open;       /* BTA_JV_RFCOMM_OPEN_EVT */
     tBTA_JV_RFCOMM_SRV_OPEN rfc_srv_open;   /* BTA_JV_RFCOMM_SRV_OPEN_EVT */
     tBTA_JV_RFCOMM_CLOSE    rfc_close;      /* BTA_JV_RFCOMM_CLOSE_EVT */
@@ -451,9 +277,6 @@
 /* JAVA RFCOMM interface callback */
 typedef void* (tBTA_JV_RFCOMM_CBACK)(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
 
-/* JAVA L2CAP interface callback */
-typedef void (tBTA_JV_L2CAP_CBACK)(tBTA_JV_EVT event, tBTA_JV *p_data);
-
 /* JV configuration structure */
 typedef struct
 {
@@ -463,14 +286,6 @@
     tSDP_DISCOVERY_DB   *p_sdp_db;  /* The data buffer to keep SDP database */
 } tBTA_JV_CFG;
 
-/*****************************************************************************
-**  External Function Declarations
-*****************************************************************************/
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
 /*******************************************************************************
 **
 ** Function         BTA_JvEnable
@@ -485,7 +300,7 @@
 **                  BTA_JV_FAIL if internal failure.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvEnable(tBTA_JV_DM_CBACK *p_cback);
+extern tBTA_JV_STATUS BTA_JvEnable(tBTA_JV_DM_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -496,7 +311,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_JvDisable(void);
+extern void BTA_JvDisable(void);
 
 /*******************************************************************************
 **
@@ -507,169 +322,7 @@
 ** Returns          TRUE, if registered
 **
 *******************************************************************************/
-BTA_API extern BOOLEAN BTA_JvIsEnable(void);
-
-/*******************************************************************************
-**
-** Function         BTA_JvSetDiscoverability
-**
-** Description      This function sets the Bluetooth  discoverable modes
-**                  of the local device.  This controls whether other
-**                  Bluetooth devices can find the local device.
-**
-**                  When the operation is complete the tBTA_JV_DM_CBACK callback
-**                  function will be called with a BTA_JV_SET_DISCOVER_EVT.
-**
-** Returns          BTA_JV_SUCCESS if successful.
-**                  BTA_JV_FAIL if internal failure.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvSetDiscoverability(tBTA_JV_DISC disc_mode);
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetDiscoverability
-**
-** Description      This function gets the Bluetooth
-**                  discoverable modes of local device
-**
-** Returns          The current Bluetooth discoverable mode.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_DISC BTA_JvGetDiscoverability(void);
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetLocalDeviceAddr
-**
-** Description      This function obtains the local Bluetooth device address.
-**                  The local Bluetooth device address is reported by the
-**                  tBTA_JV_DM_CBACK callback with a BTA_JV_LOCAL_ADDR_EVT.
-**
-** Returns          BTA_JV_SUCCESS if successful.
-**                  BTA_JV_FAIL if internal failure.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvGetLocalDeviceAddr(void);
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetLocalDeviceName
-**
-** Description      This function obtains the name of the local device
-**                  The local Bluetooth device name is reported by the
-**                  tBTA_JV_DM_CBACK callback with a BTA_JV_LOCAL_NAME_EVT.
-**
-** Returns          BTA_JV_SUCCESS if successful.
-**                  BTA_JV_FAIL if internal failure.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvGetLocalDeviceName(void);
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetRemoteDeviceName
-**
-** Description      This function obtains the name of the specified device.
-**                  The Bluetooth device name is reported by the
-**                  tBTA_JV_DM_CBACK callback with a BTA_JV_REMOTE_NAME_EVT.
-**
-** Returns          BTA_JV_SUCCESS if successful.
-**                  BTA_JV_FAIL if internal failure.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvGetRemoteDeviceName(BD_ADDR bd_addr);
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetPreknownDevice
-**
-** Description      This function obtains the Bluetooth address in the inquiry
-**                  database collected via the previous call to BTA_DmSearch().
-**
-** Returns          The number of preknown devices if p_bd_addr is NULL
-**                  BTA_JV_SUCCESS if successful.
-**                  BTA_JV_INTERNAL_ERR(-1) if internal failure.
-**
-*******************************************************************************/
-BTA_API extern INT32 BTA_JvGetPreknownDevice(UINT8 * p_bd_addr, UINT32 index);
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetDeviceClass
-**
-** Description      This function obtains the local Class of Device.
-**
-** Returns          DEV_CLASS, A three-byte array of UINT8 that contains the
-**                  Class of Device information. The definitions are in the
-**                  "Bluetooth Assigned Numbers".
-**
-*******************************************************************************/
-BTA_API extern UINT8 * BTA_JvGetDeviceClass(void);
-
-/*******************************************************************************
-**
-** Function         BTA_JvSetServiceClass
-**
-** Description      This function sets the service class of local Class of Device
-**
-** Returns          BTA_JV_SUCCESS if successful.
-**                  BTA_JV_FAIL if internal failure.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvSetServiceClass(UINT32 service);
-
-/*******************************************************************************
-**
-** Function         BTA_JvSetEncryption
-**
-** Description      This function ensures that the connection to the given device
-**                  is encrypted.
-**                  When the operation is complete the tBTA_JV_DM_CBACK callback
-**                  function will be called with a BTA_JV_SET_ENCRYPTION_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvSetEncryption(BD_ADDR bd_addr);
-
-/*******************************************************************************
-**
-** Function         BTA_JvIsAuthenticated
-**
-** Description      This function checks if the peer device is authenticated
-**
-** Returns          TRUE if authenticated.
-**                  FALSE if not.
-**
-*******************************************************************************/
-BTA_API extern BOOLEAN BTA_JvIsAuthenticated(BD_ADDR bd_addr);
-
-/*******************************************************************************
-**
-** Function         BTA_JvIsTrusted
-**
-** Description      This function checks if the peer device is trusted
-**                  (previously paired)
-**
-** Returns          TRUE if trusted.
-**                  FALSE if not.
-**
-*******************************************************************************/
-BTA_API extern BOOLEAN BTA_JvIsTrusted(BD_ADDR bd_addr);
-
-/*******************************************************************************
-**
-** Function         BTA_JvIsAuthorized
-**
-** Description      This function checks if the peer device is authorized
-**
-** Returns          TRUE if authorized.
-**                  FALSE if not.
-**
-*******************************************************************************/
-BTA_API extern BOOLEAN BTA_JvIsAuthorized(BD_ADDR bd_addr);
+extern BOOLEAN BTA_JvIsEnable(void);
 
 /*******************************************************************************
 **
@@ -681,66 +334,7 @@
 **                  FALSE if not.
 **
 *******************************************************************************/
-BTA_API extern BOOLEAN BTA_JvIsEncrypted(BD_ADDR bd_addr);
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetSecurityMode
-**
-** Description      This function returns the current Bluetooth security mode
-**                  of the local device
-**
-** Returns          The current Bluetooth security mode.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_SEC_MODE BTA_JvGetSecurityMode(void);
-
-/* BTA_JvIsMaster is replaced by BTA_DmIsMaster */
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetSCN
-**
-** Description      This function reserves a SCN (server channel number) for
-**                  applications running over RFCOMM. It is primarily called by
-**                  server profiles/applications to register their SCN into the
-**                  SDP database. The SCN is reported by the tBTA_JV_DM_CBACK
-**                  callback with a BTA_JV_GET_SCN_EVT.
-**                  If the SCN reported is 0, that means all SCN resources are
-**                  exhausted.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvGetSCN(void);
-
-/*******************************************************************************
-**
-** Function         BTA_JvFreeSCN
-**
-** Description      This function frees a server channel number that was used
-**                  by an application running over RFCOMM.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvFreeSCN(UINT8 scn);
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetPSM
-**
-** Description      This function reserves a PSM (Protocol Service Multiplexer)
-**                  applications running over L2CAP. It is primarily called by
-**                  server profiles/applications to register their PSM into the
-**                  SDP database.
-**
-** Returns          The next free PSM
-**
-*******************************************************************************/
-BTA_API extern UINT16 BTA_JvGetPSM(void);
+extern BOOLEAN BTA_JvIsEncrypted(BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -755,85 +349,8 @@
 **                  BTA_JV_FAILURE, otherwise.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvStartDiscovery(BD_ADDR bd_addr, UINT16 num_uuid,
-                           tSDP_UUID *p_uuid_list, void* user_data);
-
-/*******************************************************************************
-**
-** Function         BTA_JvCancelDiscovery
-**
-** Description      This function cancels an active service discovery.
-**                  When the operation is
-**                  complete the tBTA_JV_DM_CBACK callback function will be
-**                  called with a BTA_JV_CANCEL_DISCVRY_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvCancelDiscovery(void * user_data);
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetServicesLength
-**
-** Description      This function obtains the number of services and the length
-**                  of each service found in the SDP database (result of last
-**                  BTA_JvStartDiscovery().When the operation is complete the
-**                  tBTA_JV_DM_CBACK callback function will be called with a
-**                  BTA_JV_SERVICES_LEN_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvGetServicesLength(BOOLEAN inc_hdr, UINT16 *p_services_len);
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetServicesResult
-**
-** Description      This function returns a number of service records found
-**                  during current service search, equals to the number returned
-**                  by previous call to BTA_JvGetServicesLength.
-**                  The contents of each SDP record will be returned under a
-**                  TLV (type, len, value) representation in the data buffer
-**                  provided by the caller.
-**
-** Returns          -1, if error. Otherwise, the number of services
-**
-*******************************************************************************/
-BTA_API extern INT32 BTA_JvGetServicesResult(BOOLEAN inc_hdr, UINT8 **TLVs);
-
-/*******************************************************************************
-**
-** Function         BTA_JvServiceSelect
-**
-** Description      This function checks if the SDP database contains the given
-**                  service UUID. When the operation is complete the
-**                  tBTA_JV_DM_CBACK callback function will be called with a
-**                  BTA_JV_SERVICE_SEL_EVT with the length of the service record.
-**                  If the service is not found or error, -1 is reported.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvServiceSelect(UINT16 uuid);
-
-/*******************************************************************************
-**
-** Function         BTA_JvServiceResult
-**
-** Description      This function returns the contents of the SDP record from
-**                  last BTA_JvServiceSelect. The contents will be returned under
-**                  a TLV (type, len, value) representation in the data buffer
-**                  provided by the caller.
-**
-** Returns          -1, if error. Otherwise, the length of service record.
-**
-*******************************************************************************/
-BTA_API extern INT32 BTA_JvServiceResult(UINT8 *TLV);
+extern tBTA_JV_STATUS BTA_JvStartDiscovery(BD_ADDR bd_addr, UINT16 num_uuid,
+                                           tSDP_UUID *p_uuid_list, void* user_data);
 
 /*******************************************************************************
 **
@@ -846,51 +363,7 @@
 **                  BTA_JV_FAILURE, otherwise.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvCreateRecordByUser(void* user_data);
-
-/*******************************************************************************
-**
-** Function         BTA_JvUpdateRecord
-**
-** Description      Update a service record in the local SDP database.
-**                  When the operation is complete the tBTA_JV_DM_CBACK callback
-**                  function will be called with a BTA_JV_UPDATE_RECORD_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvUpdateRecord(UINT32 handle, UINT16 *p_ids,
-                           UINT8 **p_values, INT32 *p_value_sizes, INT32 array_len);
-
-/*******************************************************************************
-**
-** Function         BTA_JvAddAttribute
-**
-** Description      Add an attribute to a service record in the local SDP database.
-**                  When the operation is complete the tBTA_JV_DM_CBACK callback
-**                  function will be called with a BTA_JV_ADD_ATTR_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvAddAttribute(UINT32 handle, UINT16 attr_id,
-                           UINT8 *p_value, INT32 value_size);
-
-/*******************************************************************************
-**
-** Function         BTA_JvDeleteAttribute
-**
-** Description      Delete an attribute from a service record in the local SDP database.
-**                  When the operation is complete the tBTA_JV_DM_CBACK callback
-**                  function will be called with a BTA_JV_DELETE_ATTR_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvDeleteAttribute(UINT32 handle, UINT16 attr_id);
+extern tBTA_JV_STATUS BTA_JvCreateRecordByUser(void* user_data);
 
 /*******************************************************************************
 **
@@ -902,142 +375,7 @@
 **                  BTA_JV_FAILURE, otherwise.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvDeleteRecord(UINT32 handle);
-
-/*******************************************************************************
-**
-** Function         BTA_JvReadRecord
-**
-** Description      Read a service record in the local SDP database.
-**
-** Returns          -1, if the record is not found.
-**                  Otherwise, the offset (0 or 1) to start of data in p_data.
-**
-**                  The size of data copied into p_data is in *p_data_len.
-**
-*******************************************************************************/
-BTA_API extern INT32 BTA_JvReadRecord(UINT32 handle, UINT8 *p_data, INT32 *p_data_len);
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capConnect
-**
-** Description      Initiate a connection as a L2CAP client to the given BD
-**                  Address.
-**                  When the connection is initiated or failed to initiate,
-**                  tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_CL_INIT_EVT
-**                  When the connection is established or failed,
-**                  tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_OPEN_EVT
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvL2capConnect(tBTA_SEC sec_mask,
-                           tBTA_JV_ROLE role,  UINT16 remote_psm, UINT16 rx_mtu,
-                           BD_ADDR peer_bd_addr, tBTA_JV_L2CAP_CBACK *p_cback);
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capClose
-**
-** Description      This function closes an L2CAP client connection
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvL2capClose(UINT32 handle);
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capStartServer
-**
-** Description      This function starts an L2CAP server and listens for an L2CAP
-**                  connection from a remote Bluetooth device.  When the server
-**                  is started successfully, tBTA_JV_L2CAP_CBACK is called with
-**                  BTA_JV_L2CAP_START_EVT.  When the connection is established,
-**                  tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_OPEN_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvL2capStartServer(tBTA_SEC sec_mask, tBTA_JV_ROLE role,
-                           UINT16 local_psm, UINT16 rx_mtu,
-                           tBTA_JV_L2CAP_CBACK *p_cback);
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capStopServer
-**
-** Description      This function stops the L2CAP server. If the server has an
-**                  active connection, it would be closed.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvL2capStopServer(UINT16 local_psm);
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capRead
-**
-** Description      This function reads data from an L2CAP connection
-**                  When the operation is complete, tBTA_JV_L2CAP_CBACK is
-**                  called with BTA_JV_L2CAP_READ_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvL2capRead(UINT32 handle, UINT32 req_id,
-                                              UINT8 *p_data, UINT16 len);
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capReceive
-**
-** Description      This function reads data from an L2CAP connection
-**                  When the operation is complete, tBTA_JV_L2CAP_CBACK is
-**                  called with BTA_JV_L2CAP_RECEIVE_EVT.
-**                  If there are more data queued in L2CAP than len, the extra data will be discarded.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvL2capReceive(UINT32 handle, UINT32 req_id,
-                                              UINT8 *p_data, UINT16 len);
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capReady
-**
-** Description      This function determined if there is data to read from
-**                  an L2CAP connection
-**
-** Returns          BTA_JV_SUCCESS, if data queue size is in *p_data_size.
-**                  BTA_JV_FAILURE, if error.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvL2capReady(UINT32 handle, UINT32 *p_data_size);
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capWrite
-**
-** Description      This function writes data to an L2CAP connection
-**                  When the operation is complete, tBTA_JV_L2CAP_CBACK is
-**                  called with BTA_JV_L2CAP_WRITE_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvL2capWrite(UINT32 handle, UINT32 req_id,
-                                               UINT8 *p_data, UINT16 len);
+extern tBTA_JV_STATUS BTA_JvDeleteRecord(UINT32 handle);
 
 /*******************************************************************************
 **
@@ -1054,9 +392,9 @@
 **                  BTA_JV_FAILURE, otherwise.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvRfcommConnect(tBTA_SEC sec_mask,
-                           tBTA_JV_ROLE role, UINT8 remote_scn, BD_ADDR peer_bd_addr,
-                           tBTA_JV_RFCOMM_CBACK *p_cback, void *user_data);
+extern tBTA_JV_STATUS BTA_JvRfcommConnect(tBTA_SEC sec_mask,
+                                          tBTA_JV_ROLE role, UINT8 remote_scn, BD_ADDR peer_bd_addr,
+                                          tBTA_JV_RFCOMM_CBACK *p_cback, void *user_data);
 
 /*******************************************************************************
 **
@@ -1068,7 +406,7 @@
 **                  BTA_JV_FAILURE, otherwise.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvRfcommClose(UINT32 handle, void* user_data);
+extern tBTA_JV_STATUS BTA_JvRfcommClose(UINT32 handle, void* user_data);
 
 /*******************************************************************************
 **
@@ -1085,9 +423,9 @@
 **                  BTA_JV_FAILURE, otherwise.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC sec_mask,
-                           tBTA_JV_ROLE role, UINT8 local_scn, UINT8 max_session,
-                           tBTA_JV_RFCOMM_CBACK *p_cback, void *user_data);
+extern tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC sec_mask,
+                                              tBTA_JV_ROLE role, UINT8 local_scn, UINT8 max_session,
+                                              tBTA_JV_RFCOMM_CBACK *p_cback, void *user_data);
 
 /*******************************************************************************
 **
@@ -1100,7 +438,7 @@
 **                  BTA_JV_FAILURE, otherwise.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvRfcommStopServer(UINT32 handle, void* user_data);
+extern tBTA_JV_STATUS BTA_JvRfcommStopServer(UINT32 handle, void* user_data);
 
 /*******************************************************************************
 **
@@ -1114,8 +452,8 @@
 **                  BTA_JV_FAILURE, otherwise.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvRfcommRead(UINT32 handle, UINT32 req_id,
-                                               UINT8 *p_data, UINT16 len);
+extern tBTA_JV_STATUS BTA_JvRfcommRead(UINT32 handle, UINT32 req_id,
+                                       UINT8 *p_data, UINT16 len);
 
 /*******************************************************************************
 **
@@ -1128,7 +466,7 @@
 **                  BTA_JV_FAILURE, if error.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvRfcommReady(UINT32 handle, UINT32 *p_data_size);
+extern tBTA_JV_STATUS BTA_JvRfcommReady(UINT32 handle, UINT32 *p_data_size);
 
 /*******************************************************************************
 **
@@ -1142,7 +480,7 @@
 **                  BTA_JV_FAILURE, otherwise.
 **
 *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvRfcommWrite(UINT32 handle, UINT32 req_id);
+extern tBTA_JV_STATUS BTA_JvRfcommWrite(UINT32 handle, UINT32 req_id);
 
 /*******************************************************************************
  **
@@ -1163,8 +501,8 @@
  **              BTA_JV_CONN_CLOSE to remove in case of connection close!
  **
  *******************************************************************************/
-BTA_API extern tBTA_JV_STATUS BTA_JvSetPmProfile(UINT32 handle, tBTA_JV_PM_ID app_id,
-                                                 tBTA_JV_CONN_STATE init_st);
+extern tBTA_JV_STATUS BTA_JvSetPmProfile(UINT32 handle, tBTA_JV_PM_ID app_id,
+                                         tBTA_JV_CONN_STATE init_st);
 
 /*******************************************************************************
 **
@@ -1178,9 +516,4 @@
 *******************************************************************************/
 UINT16 BTA_JvRfcommGetPortHdl(UINT32 handle);
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* BTA_JV_API_H */
-
diff --git a/bta/include/bta_jv_co.h b/bta/include/bta_jv_co.h
index 098766c..24315c2 100644
--- a/bta/include/bta_jv_co.h
+++ b/bta/include/bta_jv_co.h
@@ -42,9 +42,8 @@
 **
 *******************************************************************************/
 
-BTA_API extern int bta_co_rfc_data_incoming(void *user_data, BT_HDR *p_buf);
-BTA_API extern int bta_co_rfc_data_outgoing_size(void *user_data, int *size);
-BTA_API extern int bta_co_rfc_data_outgoing(void *user_data, UINT8* buf, UINT16 size);
+extern int bta_co_rfc_data_incoming(void *user_data, BT_HDR *p_buf);
+extern int bta_co_rfc_data_outgoing_size(void *user_data, int *size);
+extern int bta_co_rfc_data_outgoing(void *user_data, UINT8* buf, UINT16 size);
 
 #endif /* BTA_DG_CO_H */
-
diff --git a/bta/include/bta_mce_api.h b/bta/include/bta_mce_api.h
index b9fbf6a..c978115 100644
--- a/bta/include/bta_mce_api.h
+++ b/bta/include/bta_mce_api.h
@@ -25,7 +25,6 @@
 #ifndef BTA_MCE_API_H
 #define BTA_MCE_API_H
 
-#include "data_types.h"
 #include "bt_target.h"
 #include "bt_types.h"
 #include "bta_api.h"
@@ -108,7 +107,7 @@
 **                  BTA_MCE_FAIL if internal failure.
 **
 *******************************************************************************/
-BTA_API extern tBTA_MCE_STATUS BTA_MceEnable(tBTA_MCE_DM_CBACK *p_cback);
+extern tBTA_MCE_STATUS BTA_MceEnable(tBTA_MCE_DM_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -123,7 +122,7 @@
 **                  BTA_MCE_FAILURE, otherwise.
 **
 *******************************************************************************/
-BTA_API extern tBTA_MCE_STATUS BTA_MceGetRemoteMasInstances(BD_ADDR bd_addr);
+extern tBTA_MCE_STATUS BTA_MceGetRemoteMasInstances(BD_ADDR bd_addr);
 
 #ifdef __cplusplus
 }
diff --git a/bta/include/bta_pan_api.h b/bta/include/bta_pan_api.h
index 2166766..a6fd9aa 100644
--- a/bta/include/bta_pan_api.h
+++ b/bta/include/bta_pan_api.h
@@ -136,7 +136,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_PanEnable(tBTA_PAN_CBACK p_cback);
+extern void BTA_PanEnable(tBTA_PAN_CBACK p_cback);
 
 /*******************************************************************************
 **
@@ -147,7 +147,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_PanDisable(void);
+extern void BTA_PanDisable(void);
 
 
 /*******************************************************************************
@@ -160,8 +160,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_PanSetRole(tBTA_PAN_ROLE role, tBTA_PAN_ROLE_INFO *p_user_info, tBTA_PAN_ROLE_INFO *p_gn_info,
-                                        tBTA_PAN_ROLE_INFO *p_nap_info);
+void BTA_PanSetRole(tBTA_PAN_ROLE role, tBTA_PAN_ROLE_INFO *p_user_info, tBTA_PAN_ROLE_INFO *p_gn_info,
+                    tBTA_PAN_ROLE_INFO *p_nap_info);
 
 
 /*******************************************************************************
@@ -176,7 +176,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_PanOpen(BD_ADDR bd_addr, tBTA_PAN_ROLE    local_role, tBTA_PAN_ROLE  peer_role);
+void BTA_PanOpen(BD_ADDR bd_addr, tBTA_PAN_ROLE    local_role, tBTA_PAN_ROLE  peer_role);
 
 
 
@@ -190,7 +190,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void BTA_PanClose(UINT16 handle);
+extern void BTA_PanClose(UINT16 handle);
 
 
 #ifdef __cplusplus
@@ -198,4 +198,3 @@
 #endif
 
 #endif /* BTA_PAN_API_H */
-
diff --git a/bta/include/bta_pan_ci.h b/bta/include/bta_pan_ci.h
index faeef54..4f314fd 100644
--- a/bta/include/bta_pan_ci.h
+++ b/bta/include/bta_pan_ci.h
@@ -47,7 +47,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_ci_tx_ready(UINT16 handle);
+extern void bta_pan_ci_tx_ready(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -62,7 +62,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_ci_rx_ready(UINT16 handle);
+extern void bta_pan_ci_rx_ready(UINT16 handle);
 
 /*******************************************************************************
 **
@@ -79,7 +79,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_ci_tx_flow(UINT16 handle, BOOLEAN enable);
+extern void bta_pan_ci_tx_flow(UINT16 handle, BOOLEAN enable);
 
 /*******************************************************************************
 **
@@ -96,7 +96,7 @@
 ** Returns          TRUE if flow enabled
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_ci_rx_writebuf(UINT16 handle, BD_ADDR src, BD_ADDR dst, UINT16 protocol, BT_HDR *p_buf, BOOLEAN ext);
+extern void bta_pan_ci_rx_writebuf(UINT16 handle, BD_ADDR src, BD_ADDR dst, UINT16 protocol, BT_HDR *p_buf, BOOLEAN ext);
 
 /*******************************************************************************
 **
@@ -111,8 +111,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern BT_HDR * bta_pan_ci_readbuf(UINT16 handle, BD_ADDR src, BD_ADDR dst, UINT16 *p_protocol,
-                                 BOOLEAN* p_ext, BOOLEAN* p_forward);
+extern BT_HDR * bta_pan_ci_readbuf(UINT16 handle, BD_ADDR src, BD_ADDR dst, UINT16 *p_protocol,
+                                   BOOLEAN* p_ext, BOOLEAN* p_forward);
 
 /*******************************************************************************
 **
@@ -124,7 +124,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_ci_set_pfilters(UINT16 handle, UINT16 num_filters, UINT16 *p_start_array, UINT16 *p_end_array);
+extern void bta_pan_ci_set_pfilters(UINT16 handle, UINT16 num_filters, UINT16 *p_start_array, UINT16 *p_end_array);
 
 
 /*******************************************************************************
@@ -137,15 +137,11 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_ci_set_mfilters(UINT16 handle, UINT16 num_mcast_filters, UINT8 *p_start_array,
-                                                    UINT8 *p_end_array);
-
-
-
+extern void bta_pan_ci_set_mfilters(UINT16 handle, UINT16 num_mcast_filters, UINT8 *p_start_array,
+                                    UINT8 *p_end_array);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif /* BTA_PAN_CI_H */
-
diff --git a/bta/include/bta_pan_co.h b/bta/include/bta_pan_co.h
index 5b20fad..5f3baed 100644
--- a/bta/include/bta_pan_co.h
+++ b/bta/include/bta_pan_co.h
@@ -64,7 +64,7 @@
 ** Returns          Data flow mask.
 **
 *******************************************************************************/
-BTA_API extern UINT8 bta_pan_co_init(UINT8 *q_level);
+extern UINT8 bta_pan_co_init(UINT8 *q_level);
 
 /*******************************************************************************
 **
@@ -78,7 +78,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_co_open(UINT16 handle, UINT8 app_id, tBTA_PAN_ROLE local_role, tBTA_PAN_ROLE peer_role, BD_ADDR peer_addr);
+extern void bta_pan_co_open(UINT16 handle, UINT8 app_id, tBTA_PAN_ROLE local_role, tBTA_PAN_ROLE peer_role, BD_ADDR peer_addr);
 
 /*******************************************************************************
 **
@@ -91,7 +91,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_co_close(UINT16 handle, UINT8 app_id);
+extern void bta_pan_co_close(UINT16 handle, UINT8 app_id);
 
 /*******************************************************************************
 **
@@ -106,7 +106,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_co_tx_path(UINT16 handle, UINT8 app_id);
+extern void bta_pan_co_tx_path(UINT16 handle, UINT8 app_id);
 
 /*******************************************************************************
 **
@@ -121,7 +121,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_co_rx_path(UINT16 handle, UINT8 app_id);
+extern void bta_pan_co_rx_path(UINT16 handle, UINT8 app_id);
 
 /*******************************************************************************
 **
@@ -136,7 +136,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_co_tx_write(UINT16 handle, UINT8 app_id, BD_ADDR src, BD_ADDR dst, UINT16 protocol, UINT8 *p_data,
+extern void bta_pan_co_tx_write(UINT16 handle, UINT8 app_id, BD_ADDR src, BD_ADDR dst, UINT16 protocol, UINT8 *p_data,
                                 UINT16 len, BOOLEAN ext, BOOLEAN forward);
 
 /*******************************************************************************
@@ -152,7 +152,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_co_tx_writebuf(UINT16 handle, UINT8 app_id, BD_ADDR src, BD_ADDR dst, UINT16 protocol, BT_HDR *p_buf,
+extern void bta_pan_co_tx_writebuf(UINT16 handle, UINT8 app_id, BD_ADDR src, BD_ADDR dst, UINT16 protocol, BT_HDR *p_buf,
                                    BOOLEAN ext, BOOLEAN forward);
 
 
@@ -170,7 +170,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_co_rx_flow(UINT16 handle, UINT8 app_id, BOOLEAN enable);
+extern void bta_pan_co_rx_flow(UINT16 handle, UINT8 app_id, BOOLEAN enable);
 
 
 /*******************************************************************************
@@ -182,8 +182,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_co_pfilt_ind(UINT16 handle, BOOLEAN indication, tBTA_PAN_STATUS result,
-                                    UINT16 len, UINT8 *p_filters);
+extern void bta_pan_co_pfilt_ind(UINT16 handle, BOOLEAN indication, tBTA_PAN_STATUS result,
+                                 UINT16 len, UINT8 *p_filters);
 
 /*******************************************************************************
 **
@@ -194,8 +194,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API extern void bta_pan_co_mfilt_ind(UINT16 handle,  BOOLEAN indication, tBTA_PAN_STATUS result,
-                                    UINT16 len, UINT8 *p_filters);
+extern void bta_pan_co_mfilt_ind(UINT16 handle,  BOOLEAN indication, tBTA_PAN_STATUS result,
+                                 UINT16 len, UINT8 *p_filters);
 
 #endif /* BTA_PAN_CO_H */
-
diff --git a/bta/include/bta_pbs_api.h b/bta/include/bta_pbs_api.h
deleted file mode 100644
index c3563c2..0000000
--- a/bta/include/bta_pbs_api.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This is the public interface file for the phone book access (PB) server
- *  subsystem of BTA, Broadcom's Bluetooth application layer for mobile
- *  phones.
- *
- ******************************************************************************/
-#ifndef BTA_PB_API_H
-#define BTA_PB_API_H
-
-#include "bta_api.h"
-#include "btm_api.h"
-#include "bta_sys.h"
-
-/*****************************************************************************
-**  Constants and data types
-*****************************************************************************/
-
-/**************************
-**  Common Definitions
-***************************/
-
-/* Profile supported features */
-#define BTA_PBS_SUPF_DOWNLOAD     0x0001
-#define BTA_PBS_SURF_BROWSE       0x0002
-
-/* Profile supported repositories */
-#define BTA_PBS_REPOSIT_LOCAL      0x01    /* Local PhoneBook */
-#define BTA_PBS_REPOSIT_SIM        0x02    /* SIM card PhoneBook */
-
-#endif
diff --git a/bta/include/bta_sys_ci.h b/bta/include/bta_sys_ci.h
deleted file mode 100644
index 4818386..0000000
--- a/bta/include/bta_sys_ci.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2010-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This is the interface file for system call-in functions.
- *
- ******************************************************************************/
-#ifndef BTA_SYS_CI_H
-#define BTA_SYS_CI_H
-
-#include "bta_api.h"
-
-/*****************************************************************************
-**  Function Declarations
-*****************************************************************************/
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/*******************************************************************************
-**
-** Function         bta_sys_hw_ci_enabled
-**
-** Description      This function must be called in response to function
-**                  bta_sys_hw_co_enable(), when HW is indeed enabled
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API  void bta_sys_hw_ci_enabled(tBTA_SYS_HW_MODULE module );
-
-
-/*******************************************************************************
-**
-** Function         bta_sys_hw_ci_disabled
-**
-** Description      This function must be called in response to function
-**                  bta_sys_hw_co_disable() when HW is really OFF
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API void bta_sys_hw_ci_disabled( tBTA_SYS_HW_MODULE module  );
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
diff --git a/bta/include/bta_sys_co.h b/bta/include/bta_sys_co.h
deleted file mode 100644
index 92118a3..0000000
--- a/bta/include/bta_sys_co.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2010-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This is the interface file for system callout functions.
- *
- ******************************************************************************/
-#ifndef BTA_SYS_CO_H
-#define BTA_SYS_CO_H
-
-#include "bta_sys.h"
-
-
-
-/*****************************************************************************
-**  Function Declarations
-*****************************************************************************/
-
-
-/*******************************************************************************
-**
-** Function         bta_sys_hw_co_enable
-**
-** Description      This function is called by the stack to power up the HW
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API void bta_sys_hw_co_enable( tBTA_SYS_HW_MODULE module );
-
-/*******************************************************************************
-**
-** Function         bta_sys_hw_co_disable
-**
-** Description     This function is called by the stack to power down the HW
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API void bta_sys_hw_co_disable( tBTA_SYS_HW_MODULE module );
-
-
-#endif
diff --git a/bta/include/ptim.h b/bta/include/ptim.h
deleted file mode 100644
index 80e50bd..0000000
--- a/bta/include/ptim.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Protocol timer services.
- *
- ******************************************************************************/
-#ifndef PTIM_H
-#define PTIM_H
-
-#include "gki.h"
-
-/*****************************************************************************
-**  Constants and data types
-*****************************************************************************/
-
-typedef struct
-{
-    TIMER_LIST_Q        timer_queue;        /* GKI timer queue */
-    INT32               period;             /* Timer period in milliseconds */
-    UINT32              last_gki_ticks;     /* GKI ticks since last time update called */
-    UINT8               timer_id;           /* GKI timer id */
-} tPTIM_CB;
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/*****************************************************************************
-**  Function Declarations
-*****************************************************************************/
-
-/*******************************************************************************
-**
-** Function         ptim_init
-**
-** Description      Initialize a protocol timer service control block.
-**
-** Returns          void
-**
-*******************************************************************************/
-extern void ptim_init(tPTIM_CB *p_cb, UINT16 period, UINT8 timer_id);
-
-/*******************************************************************************
-**
-** Function         ptim_timer_update
-**
-** Description      Update the protocol timer list and handle expired timers.
-**
-** Returns          void
-**
-*******************************************************************************/
-extern void ptim_timer_update(tPTIM_CB *p_cb);
-
-/*******************************************************************************
-**
-** Function         ptim_start_timer
-**
-** Description      Start a protocol timer for the specified amount
-**                  of time in milliseconds.
-**
-** Returns          void
-**
-*******************************************************************************/
-extern void ptim_start_timer(tPTIM_CB *p_cb, TIMER_LIST_ENT *p_tle, UINT16 type, INT32 timeout);
-
-/*******************************************************************************
-**
-** Function         ptim_stop_timer
-**
-** Description      Stop a protocol timer.
-**
-** Returns          void
-**
-*******************************************************************************/
-extern void ptim_stop_timer(tPTIM_CB *p_cb, TIMER_LIST_ENT *p_tle);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* PTIM_H */
diff --git a/bta/include/utl.h b/bta/include/utl.h
index e26cded..ff8591f 100644
--- a/bta/include/utl.h
+++ b/bta/include/utl.h
@@ -24,7 +24,7 @@
 #ifndef UTL_H
 #define UTL_H
 
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_utils.h"
 
 /*****************************************************************************
diff --git a/bta/jv/bta_jv_act.c b/bta/jv/bta_jv_act.c
index 8bcb7c6..c9299e8 100644
--- a/bta/jv/bta_jv_act.c
+++ b/bta/jv/bta_jv_act.c
@@ -26,7 +26,6 @@
 
 #include "bt_types.h"
 #include "gki.h"
-#include "bd.h"
 #include "utl.h"
 #include "bta_sys.h"
 #include "bta_api.h"
@@ -45,17 +44,11 @@
 #include "gap_api.h"
 
 
-#define HDL2CB(handle) \
-    UINT32  __hi = ((handle) & BTA_JV_RFC_HDL_MASK) - 1; \
-    UINT32  __si = BTA_JV_RFC_HDL_TO_SIDX(handle); \
-    tBTA_JV_RFC_CB  *p_cb = &bta_jv_cb.rfc_cb[__hi]; \
-    tBTA_JV_PCB   *p_pcb = &bta_jv_cb.port_cb[p_cb->rfc_hdl[__si] - 1]
-
-extern void uuid_to_string(bt_uuid_t *p_uuid, char *str);
+extern void uuid_to_string_legacy(bt_uuid_t *p_uuid, char *str);
 static inline void logu(const char* title, const uint8_t * p_uuid)
 {
     char uuids[128];
-    uuid_to_string((bt_uuid_t*)p_uuid, uuids);
+    uuid_to_string_legacy((bt_uuid_t*)p_uuid, uuids);
     APPL_TRACE_DEBUG("%s: %s", title, uuids);
 }
 
@@ -70,38 +63,6 @@
 
 /*******************************************************************************
 **
-** Function     bta_jv_get_local_device_addr_cback
-**
-** Description  Callback from btm after local bdaddr is read
-**
-** Returns      void
-**
-*******************************************************************************/
-static void bta_jv_get_local_device_addr_cback(BD_ADDR bd_addr)
-{
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_LOCAL_ADDR_EVT, (tBTA_JV *)bd_addr, 0);
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_get_remote_device_name_cback
-**
-** Description  Callback from btm after remote name is read
-**
-** Returns      void
-**
-*******************************************************************************/
-static void bta_jv_get_remote_device_name_cback(tBTM_REMOTE_DEV_NAME *p_name)
-{
-    tBTA_JV evt_data;
-    evt_data.p_name = p_name->remote_bd_name;
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_REMOTE_NAME_EVT, &evt_data, 0);
-}
-
-/*******************************************************************************
-**
 ** Function     bta_jv_alloc_sec_id
 **
 ** Description  allocate a security id
@@ -369,51 +330,6 @@
 }
 
 /*******************************************************************************
-**
-** Function     bta_jv_free_l2c_cb
-**
-** Description  free the given L2CAP control block
-**
-** Returns
-**
-*******************************************************************************/
-tBTA_JV_STATUS bta_jv_free_l2c_cb(tBTA_JV_L2C_CB *p_cb)
-{
-    UNUSED(p_cb);
-#if 0
-    tBTA_JV_STATUS status = BTA_JV_SUCCESS;
-
-    if(BTA_JV_ST_NONE != p_cb->state)
-    {
-#if SDP_FOR_JV_INCLUDED == TRUE
-        if(BTA_JV_L2C_FOR_SDP_HDL == p_cb->handle)
-        {
-            bta_jv_cb.sdp_data_size = 0;
-            if(SDP_ConnClose(bta_jv_cb.sdp_for_jv))
-            {
-                bta_jv_cb.sdp_for_jv = 0;
-            }
-            else
-                status = BTA_JV_FAILURE;
-        }
-        else
-#endif
-        {
-            bta_jv_free_set_pm_profile_cb((UINT32)p_cb->handle);
-            if (GAP_ConnClose(p_cb->handle) != BT_PASS)
-                status = BTA_JV_FAILURE;
-        }
-    }
-    p_cb->psm = 0;
-    p_cb->state = BTA_JV_ST_NONE;
-    bta_jv_free_sec_id(&p_cb->sec_id);
-    p_cb->p_cback = NULL;
-    return status;
-#endif
-    return 0;
-}
-
-/*******************************************************************************
  **
  ** Function    bta_jv_clear_pm_cb
  **
@@ -501,17 +417,7 @@
                     }
                 }
             }
-            else
-            {
-                if (jv_handle < BTA_JV_MAX_L2C_CONN)
-                {
-                    tBTA_JV_L2C_CB *p_l2c_cb = &bta_jv_cb.l2c_cb[jv_handle];
-                    if (NULL == p_l2c_cb->p_pm_cb)
-                        APPL_TRACE_WARNING("bta_jv_free_set_pm_profile_cb(jv_handle: "
-                                "0x%x): p_pm_cb: %d: no link to pm_cb?", jv_handle, i);
-                    p_cb = &p_l2c_cb->p_pm_cb;
-                }
-            }
+
             if (p_cb)
             {
                 *p_cb = NULL;
@@ -546,6 +452,8 @@
             /* rfc handle bd addr retrieval requires core stack handle */
             if (bRfcHandle)
             {
+                UINT32 hi = ((jv_handle & BTA_JV_RFC_HDL_MASK) & ~BTA_JV_RFCOMM_MASK) - 1;
+                UINT32 si = BTA_JV_RFC_HDL_TO_SIDX(jv_handle);
                 for (j = 0; j < BTA_JV_MAX_RFC_CONN; j++)
                 {
                     if (jv_handle == bta_jv_cb.port_cb[j].handle)
@@ -558,23 +466,6 @@
                     }
                 }
             }
-            else
-            {
-                /* use jv handle for l2cap bd address retrieval */
-                for (j = 0; j < BTA_JV_MAX_L2C_CONN; j++)
-                {
-                    if (jv_handle == bta_jv_cb.l2c_cb[j].handle)
-                    {
-                        pp_cb = &bta_jv_cb.l2c_cb[j].p_pm_cb;
-                        UINT8 *p_bd_addr = GAP_ConnGetRemoteAddr((UINT16)jv_handle);
-                        if (NULL != p_bd_addr)
-                            bdcpy(peer_bd_addr, p_bd_addr);
-                        else
-                            i = BTA_JV_PM_MAX_NUM;
-                        break;
-                    }
-                }
-            }
             APPL_TRACE_API("bta_jv_alloc_set_pm_profile_cb(handle 0x%2x, app_id %d): "
                     "idx: %d, (BTA_JV_PM_MAX_NUM: %d), pp_cb: 0x%x", jv_handle, app_id,
                     i, BTA_JV_PM_MAX_NUM, pp_cb);
@@ -597,135 +488,6 @@
 }
 
 /*******************************************************************************
- **
- ** Function     bta_jv_alloc_sdp_id
- **
- ** Description  allocate a SDP id for the given SDP record handle
- **
- ** Returns
- **
- *******************************************************************************/
-UINT32 bta_jv_alloc_sdp_id(UINT32 sdp_handle)
-{
-    int j;
-    UINT32 id = 0;
-
-    /* find a free entry */
-    for (j = 0; j < BTA_JV_MAX_SDP_REC; j++)
-    {
-        if (bta_jv_cb.sdp_handle[j] == 0)
-        {
-            bta_jv_cb.sdp_handle[j] = sdp_handle;
-            id = (UINT32)(j + 1);
-            break;
-        }
-    }
-    /* the SDP record handle reported is the (index + 1) to control block */
-    return id;
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_free_sdp_id
-**
-** Description  free the sdp id
-**
-** Returns
-**
-*******************************************************************************/
-void bta_jv_free_sdp_id(UINT32 sdp_id)
-{
-    if(sdp_id > 0 && sdp_id <= BTA_JV_MAX_SDP_REC)
-    {
-        bta_jv_cb.sdp_handle[sdp_id - 1] = 0;
-    }
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_get_sdp_handle
-**
-** Description  find the SDP handle associated with the given sdp id
-**
-** Returns
-**
-*******************************************************************************/
-UINT32 bta_jv_get_sdp_handle(UINT32 sdp_id)
-{
-    UINT32 sdp_handle = 0;
-
-    if(sdp_id > 0 && sdp_id <= BTA_JV_MAX_SDP_REC)
-    {
-        sdp_handle = bta_jv_cb.sdp_handle[sdp_id - 1];
-    }
-    return sdp_handle;
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_check_psm
-**
-** Description  for now use only the legal PSM per JSR82 spec
-**
-** Returns      TRUE, if allowed
-**
-*******************************************************************************/
-BOOLEAN bta_jv_check_psm(UINT16 psm)
-{
-    BOOLEAN ret = FALSE;
-
-    if(L2C_IS_VALID_PSM(psm) )
-    {
-        if(psm < 0x1001)
-        {
-            /* see if this is defined by spec */
-            switch(psm)
-            {
-            case SDP_PSM:           /* 1 */
-            case BT_PSM_RFCOMM:     /* 3 */
-                /* do not allow java app to use these 2 PSMs */
-                break;
-
-            case TCS_PSM_INTERCOM:  /* 5 */
-            case TCS_PSM_CORDLESS:  /* 7 */
-                if( FALSE == bta_sys_is_register(BTA_ID_CT) &&
-                    FALSE == bta_sys_is_register(BTA_ID_CG) )
-                    ret = TRUE;
-                break;
-
-            case BT_PSM_BNEP:       /* F */
-                if(FALSE == bta_sys_is_register(BTA_ID_PAN))
-                    ret = TRUE;
-                break;
-
-            case HID_PSM_CONTROL:   /* 0x11 */
-            case HID_PSM_INTERRUPT: /* 0x13 */
-                //FIX: allow HID Device and HID Host to coexist
-                if( FALSE == bta_sys_is_register(BTA_ID_HD) ||
-                    FALSE == bta_sys_is_register(BTA_ID_HH) )
-                    ret = TRUE;
-                break;
-
-            case AVCT_PSM:          /* 0x17 */
-            case AVDT_PSM:          /* 0x19 */
-                if ((FALSE == bta_sys_is_register(BTA_ID_AV)) &&
-                   (FALSE == bta_sys_is_register(BTA_ID_AVK)))
-                    ret = TRUE;
-                break;
-
-            default:
-                ret = TRUE;
-                break;
-            }
-        }
-        else
-            ret = TRUE;
-    }
-    return ret;
-
-}
-
-/*******************************************************************************
 **
 ** Function     bta_jv_enable
 **
@@ -756,247 +518,8 @@
     UNUSED(p_data);
 
     APPL_TRACE_ERROR("bta_jv_disable not used");
-#if 0
-    int i;
-
-    bta_jv_cb.p_dm_cback = NULL;
-    /* delete the SDP records created by java apps */
-    for(i=0; i<BTA_JV_MAX_SDP_REC; i++)
-    {
-        if(bta_jv_cb.sdp_handle[i])
-        {
-            APPL_TRACE_DEBUG( "delete SDP record: %d", bta_jv_cb.sdp_handle[i]);
-            SDP_DeleteRecord(bta_jv_cb.sdp_handle[i]);
-            bta_jv_cb.sdp_handle[i] = 0;
-        }
-    }
-
-    /* free the SCNs allocated by java apps */
-    for(i=0; i<BTA_JV_MAX_SCN; i++)
-    {
-        if(bta_jv_cb.scn[i])
-        {
-            APPL_TRACE_DEBUG( "free scn: %d", (i+1));
-            BTM_FreeSCN((UINT8)(i+1));
-            bta_jv_cb.scn[i] = FALSE;
-        }
-    }
-
-    /* disconnect L2CAP connections */
-    for(i=0; i<BTA_JV_MAX_L2C_CONN; i++)
-    {
-        bta_jv_free_l2c_cb(&bta_jv_cb.l2c_cb[i]);
-    }
-
-    /* disconnect RFCOMM connections */
-    for(i=0; i<BTA_JV_MAX_RFC_CONN; i++)
-    {
-        bta_jv_free_rfc_cb(&bta_jv_cb.rfc_cb[i]);
-    }
-
-    /* free the service records allocated by java apps */
-    for(i=0; i<BTA_JV_NUM_SERVICE_ID; i++)
-    {
-        if(bta_jv_cb.sec_id[i])
-        {
-            BTM_SecClrService(bta_jv_cb.sec_id[i]);
-            bta_jv_cb.sec_id[i] = 0;
-        }
-    }
-#endif
 }
 
-/*******************************************************************************
-**
-** Function     bta_jv_set_discoverability
-**
-** Description  Sets discoverability
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_set_discoverability (tBTA_JV_MSG *p_data)
-{
-    tBTA_JV     evt_data;
-
-    evt_data.set_discover.status = BTA_JV_FAILURE;
-    /* initialize the default value for the event as the current mode */
-    evt_data.set_discover.disc_mode = BTM_ReadDiscoverability(NULL, NULL);
-
-    if(BTM_SUCCESS == BTM_SetDiscoverability((UINT8)p_data->set_discoverability.disc_mode, 0, 0))
-    {
-        evt_data.set_discover.status     = BTA_JV_SUCCESS;
-        /* update the mode, after BTM_SetDiscoverability() is successful */
-        evt_data.set_discover.disc_mode  = p_data->set_discoverability.disc_mode;
-    }
-
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_SET_DISCOVER_EVT, &evt_data, 0);
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_get_local_device_addr
-**
-** Description  Reads the local Bluetooth device address
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_get_local_device_addr(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-
-    BTM_ReadLocalDeviceAddr((tBTM_CMPL_CB *)bta_jv_get_local_device_addr_cback);
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_get_local_device_name
-**
-** Description  Reads the local Bluetooth device name
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_get_local_device_name(tBTA_JV_MSG *p_data)
-{
-    tBTA_JV evt_data;
-    char *name;
-    UNUSED(p_data);
-
-    BTM_ReadLocalDeviceName(&name);
-    evt_data.p_name = (UINT8*)name;
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_LOCAL_NAME_EVT, &evt_data, 0);
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_get_remote_device_name
-**
-** Description  Reads the local Bluetooth device name
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_get_remote_device_name(tBTA_JV_MSG *p_data)
-{
-
-    BTM_ReadRemoteDeviceName(p_data->get_rmt_name.bd_addr,
-        (tBTM_CMPL_CB *)bta_jv_get_remote_device_name_cback, BT_TRANSPORT_BR_EDR);
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_set_service_class
-**
-** Description  update the service class field of device class
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_set_service_class (tBTA_JV_MSG *p_data)
-{
-    tBTA_UTL_COD cod;
-
-    /* set class of device */
-    /* 
-    BTA_JvSetServiceClass(UINT32 service) assumes that the service class passed to the
-    API function as defined in the assigned number page.
-    For example: the object transfer bit is bit 20 of the 24-bit Class of device;
-    the value of this bit is 0x00100000 (value 1)
-    Our btm_api.h defines this bit as #define BTM_COD_SERVICE_OBJ_TRANSFER        0x1000  (value 2)
-    This reflects that the service class defined at btm is UINT16,
-    which starts at bit 8 of the 24 bit Class of Device
-    The following statement converts from (value 1) into (value 2)
-    */
-    cod.service = (p_data->set_service.service >> 8);
-    utl_set_device_class(&cod, BTA_UTL_SET_COD_SERVICE_CLASS);
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_sec_cback
-**
-** Description  callback function to handle set encryption complete event
-**
-** Returns      void
-**
-*******************************************************************************/
-static void bta_jv_sec_cback (BD_ADDR bd_addr, tBTA_TRANSPORT transport,
-                                    void *p_ref_data, tBTM_STATUS result)
-{
-    UNUSED(p_ref_data);
-    UNUSED(transport);
-
-    tBTA_JV_SET_ENCRYPTION  set_enc;
-    if(bta_jv_cb.p_dm_cback)
-    {
-        bdcpy(set_enc.bd_addr, bd_addr);
-        set_enc.status = result;
-        if (result > BTA_JV_BUSY)
-            set_enc.status = BTA_JV_FAILURE;
-        bta_jv_cb.p_dm_cback(BTA_JV_SET_ENCRYPTION_EVT, (tBTA_JV *)&set_enc, 0);
-    }
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_set_encryption
-**
-** Description  Reads the local Bluetooth device name
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_set_encryption(tBTA_JV_MSG *p_data)
-{
-    BTM_SetEncryption(p_data->set_encrypt.bd_addr, BTA_TRANSPORT_BR_EDR, bta_jv_sec_cback, NULL);
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_get_scn
-**
-** Description  obtain a free SCN
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_get_scn(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    UINT8   scn;
-    scn = BTM_AllocateSCN();
-    if(scn)
-        bta_jv_cb.scn[scn-1] = TRUE;
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_GET_SCN_EVT, (tBTA_JV *)&scn);
-#endif
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_free_scn
-**
-** Description  free a SCN
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_free_scn(tBTA_JV_MSG *p_data)
-{
-    UINT8   scn = p_data->free_scn.scn;
-
-    if (scn > 0 && scn <= BTA_JV_MAX_SCN && bta_jv_cb.scn[scn-1])
-    {
-        /* this scn is used by JV */
-        bta_jv_cb.scn[scn-1] = FALSE;
-        BTM_FreeSCN(scn);
-    }
-}
 static inline tBT_UUID shorten_sdp_uuid(const tBT_UUID* u)
 {
     static uint8_t bt_base_uuid[] =
@@ -1052,38 +575,27 @@
     bta_jv_cb.sdp_active = BTA_JV_SDP_ACT_NONE;
     if(bta_jv_cb.p_dm_cback)
     {
-        if (old_sdp_act == BTA_JV_SDP_ACT_CANCEL)
+        tBTA_JV_DISCOVERY_COMP dcomp;
+        dcomp.scn = 0;
+        status = BTA_JV_FAILURE;
+        if (result == SDP_SUCCESS || result == SDP_DB_FULL)
         {
-            APPL_TRACE_DEBUG("BTA_JV_SDP_ACT_CANCEL");
-            status = BTA_JV_SUCCESS;
-            bta_jv_cb.p_dm_cback(BTA_JV_CANCEL_DISCVRY_EVT, (tBTA_JV *)&status, user_data);
-        }
-        else
-        {
-            tBTA_JV_DISCOVERY_COMP dcomp;
-            dcomp.scn = 0;
-            status = BTA_JV_FAILURE;
-            if (result == SDP_SUCCESS || result == SDP_DB_FULL)
+            tSDP_DISC_REC       *p_sdp_rec = NULL;
+            tSDP_PROTOCOL_ELEM  pe;
+            logu("bta_jv_cb.uuid", bta_jv_cb.uuid.uu.uuid128);
+            tBT_UUID su = shorten_sdp_uuid(&bta_jv_cb.uuid);
+            logu("shorten uuid:", su.uu.uuid128);
+            p_sdp_rec = SDP_FindServiceUUIDInDb(p_bta_jv_cfg->p_sdp_db, &su, p_sdp_rec);
+            APPL_TRACE_DEBUG("p_sdp_rec:%p", p_sdp_rec);
+            if(p_sdp_rec && SDP_FindProtocolListElemInRec(p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe))
             {
-                tSDP_DISC_REC       *p_sdp_rec = NULL;
-                tSDP_PROTOCOL_ELEM  pe;
-                logu("bta_jv_cb.uuid", bta_jv_cb.uuid.uu.uuid128);
-                tBT_UUID su = shorten_sdp_uuid(&bta_jv_cb.uuid);
-                logu("shorten uuid:", su.uu.uuid128);
-                p_sdp_rec = SDP_FindServiceUUIDInDb(p_bta_jv_cfg->p_sdp_db, &su, p_sdp_rec);
-                APPL_TRACE_DEBUG("p_sdp_rec:%p", p_sdp_rec);
-                if(p_sdp_rec && SDP_FindProtocolListElemInRec(p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe))
-                {
-                    dcomp.scn = (UINT8) pe.params[0];
-                    status = BTA_JV_SUCCESS;
-                }
+                dcomp.scn = (UINT8) pe.params[0];
+                status = BTA_JV_SUCCESS;
             }
-
-            dcomp.status = status;
-            bta_jv_cb.p_dm_cback(BTA_JV_DISCOVERY_COMP_EVT, (tBTA_JV *)&dcomp, user_data);
         }
-        //free sdp db
-        //utl_freebuf(&(p_bta_jv_cfg->p_sdp_db));
+
+        dcomp.status = status;
+        bta_jv_cb.p_dm_cback(BTA_JV_DISCOVERY_COMP_EVT, (tBTA_JV *)&dcomp, user_data);
     }
 }
 
@@ -1108,14 +620,7 @@
             bta_jv_cb.p_dm_cback(BTA_JV_DISCOVERY_COMP_EVT, (tBTA_JV *)&status, p_data->start_discovery.user_data);
         return;
     }
-/*
-    if(p_data->start_discovery.num_uuid == 0)
-    {
-        p_data->start_discovery.num_uuid = 1;
-        p_data->start_discovery.uuid_list[0].len       = 2;
-        p_data->start_discovery.uuid_list[0].uu.uuid16 = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP;
-    }
-*/
+
     /* init the database/set up the filter */
     APPL_TRACE_DEBUG("call SDP_InitDiscoveryDb, p_data->start_discovery.num_uuid:%d",
         p_data->start_discovery.num_uuid);
@@ -1146,152 +651,6 @@
 
 /*******************************************************************************
 **
-** Function     bta_jv_cancel_discovery
-**
-** Description  Cancels an active discovery
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_cancel_discovery(tBTA_JV_MSG *p_data)
-{
-    tBTA_JV_STATUS status = BTA_JV_SUCCESS;
-    if (bta_jv_cb.sdp_active == BTA_JV_SDP_ACT_YES)
-    {
-        if (SDP_CancelServiceSearch (p_bta_jv_cfg->p_sdp_db))
-        {
-            bta_jv_cb.sdp_active = BTA_JV_SDP_ACT_CANCEL;
-            return;
-        }
-    }
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_CANCEL_DISCVRY_EVT, (tBTA_JV *)&status, p_data->cancel_discovery.user_data);
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_get_services_length
-**
-** Description  Obtain the length of each record in the SDP DB.
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_get_services_length(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_SERVICES_LEN    evt_data;
-    UINT8   *p, *np, *op, type;
-    UINT32  raw_used, raw_cur;
-    UINT32  len;
-
-    evt_data.num_services = -1;
-    evt_data.p_services_len = p_data->get_services_length.p_services_len;
-    if(p_bta_jv_cfg->p_sdp_db->p_first_rec)
-    {
-        /* the database is valid */
-        evt_data.num_services = 0;
-        p = p_bta_jv_cfg->p_sdp_db->raw_data;
-        raw_used = p_bta_jv_cfg->p_sdp_db->raw_used;
-        while(raw_used && p)
-        {
-            op = p;
-            type = *p++;
-            np = sdpu_get_len_from_type(p, type, &len);
-            p = np + len;
-            raw_cur = p - op;
-            if(raw_used >= raw_cur)
-            {
-                raw_used -= raw_cur;
-            }
-            else
-            {
-                /* error. can not continue */
-                break;
-            }
-            if(p_data->get_services_length.inc_hdr)
-            {
-                evt_data.p_services_len[evt_data.num_services++] = len + np - op;
-            }
-            else
-            {
-                evt_data.p_services_len[evt_data.num_services++] = len;
-            }
-        } /* end of while */
-    }
-
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_SERVICES_LEN_EVT, (tBTA_JV *)&evt_data);
-#endif
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_service_select
-**
-** Description  Obtain the length of given UUID in the SDP DB.
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_service_select(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_SERVICE_SEL     serv_sel;
-    tSDP_DISC_REC *p_rec, *p_tmp;
-    UINT8   *p, *np, *op, type;
-    UINT32  raw_used, raw_cur;
-    UINT32  len;
-
-    serv_sel.service_len = 0;
-    bta_jv_cb.p_sel_raw_data     = 0;
-    p_rec = SDP_FindServiceInDb (p_bta_jv_cfg->p_sdp_db, p_data->service_select.uuid, NULL);
-    if(p_rec)
-    {
-        /* found the record in the database */
-        /* the database must be valid */
-        p = p_bta_jv_cfg->p_sdp_db->raw_data;
-        raw_used = p_bta_jv_cfg->p_sdp_db->raw_used;
-        p_tmp = p_bta_jv_cfg->p_sdp_db->p_first_rec;
-        while(raw_used && p && p_tmp)
-        {
-            op = p;
-            type = *p++;
-            np = sdpu_get_len_from_type(p, type, &len);
-            if(p_tmp == p_rec)
-            {
-                bta_jv_cb.p_sel_raw_data = op;
-                bta_jv_cb.sel_len = len;
-                serv_sel.service_len = len;
-                bdcpy(serv_sel.bd_addr, p_rec->remote_bd_addr);
-                APPL_TRACE_DEBUG( "bta_jv_service_select found uuid: 0x%x",
-                    p_data->service_select.uuid);
-                break;
-            }
-            p = np + len;
-            raw_cur = p - op;
-            if(raw_used >= raw_cur)
-            {
-                raw_used -= raw_cur;
-            }
-            else
-            {
-                /* error. can not continue */
-                break;
-            }
-            p_tmp = p_tmp->p_next_rec;
-        } /* end of while */
-    }
-    APPL_TRACE_DEBUG( "service_len: %d", serv_sel.service_len);
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_SERVICE_SEL_EVT, (tBTA_JV *)&serv_sel);
-#endif
-}
-
-/*******************************************************************************
-**
 ** Function     bta_jv_create_record
 **
 ** Description  Create an SDP record with the given attributes
@@ -1311,150 +670,6 @@
 
 /*******************************************************************************
 **
-** Function     bta_jv_update_record
-**
-** Description  Update an SDP record with the given attributes
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_update_record(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_API_UPDATE_RECORD *ur = &(p_data->update_record);
-    tBTA_JV_UPDATE_RECORD   evt_data;
-    UINT32 handle;
-    INT32 i;
-    UINT8 *ptr;
-    UINT8 *next_ptr;
-    UINT8 *end;
-    UINT32 len;
-    UINT8 type;
-
-    evt_data.status = BTA_JV_FAILURE;
-    evt_data.handle = ur->handle;
-
-    handle = bta_jv_get_sdp_handle(ur->handle);
-
-    if(handle)
-    {
-        /* this is a record created by JV */
-        for (i = 0; i < ur->array_len; i++)
-        {
-            ptr = ur->p_values[i];
-            end = ptr + ur->p_value_sizes[i];
-
-            while (ptr < end)
-            {
-                type = *ptr;
-                next_ptr = sdpu_get_len_from_type(ptr + 1, *ptr, &len);
-
-                if(ATTR_ID_SERVICE_RECORD_HDL != ur->p_ids[i])
-                {
-                if (!SDP_AddAttribute(handle, ur->p_ids[i], (UINT8)((type >> 3) & 0x1f),
-                    len, next_ptr))
-                {
-                    /* failed on updating attributes.  */
-                    if(bta_jv_cb.p_dm_cback)
-                        bta_jv_cb.p_dm_cback(BTA_JV_UPDATE_RECORD_EVT, (tBTA_JV *)&evt_data);
-                    return;
-                }
-                }
-
-                ptr = next_ptr + len;
-            } /* end of while */
-        } /* end of for */
-        evt_data.status = BTA_JV_SUCCESS;
-    }
-
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_UPDATE_RECORD_EVT, (tBTA_JV *)&evt_data);
-#endif
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_add_attribute
-**
-** Description  Add an attribute to an SDP record
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_add_attribute(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_API_ADD_ATTRIBUTE *aa = &(p_data->add_attr);
-    tBTA_JV_ADD_ATTR   evt_data;
-    UINT32 handle;
-    UINT8 type;
-    UINT32 len;
-    UINT8 *ptr;
-    UINT8 *next_ptr;
-
-    evt_data.status = BTA_JV_FAILURE;
-    evt_data.handle = aa->handle;
-    handle = bta_jv_get_sdp_handle(aa->handle);
-
-    if(handle)
-    {
-        /* this is a record created by JV */
-        ptr = aa->p_value;
-        type = *ptr;
-        next_ptr = sdpu_get_len_from_type(ptr + 1, *ptr, &len);
-        APPL_TRACE_DEBUG( "bta_jv_add_attribute: ptr chg:%d len:%d, size:%d",
-            (next_ptr - ptr), len, aa->value_size);
-        if(ATTR_ID_SERVICE_RECORD_HDL != aa->attr_id && /* do not allow the SDP record handle to be updated */
-            ((INT32)(next_ptr - ptr + len) == aa->value_size) && /* double check data size */
-            SDP_AddAttribute(handle, aa->attr_id, (UINT8)((type >> 3) & 0x1f),
-                    len, next_ptr))
-        {
-            evt_data.status = BTA_JV_SUCCESS;
-        }
-    }
-
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_ADD_ATTR_EVT, (tBTA_JV *)&evt_data);
-#endif
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_delete_attribute
-**
-** Description  Delete an attribute from the given SDP record
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_delete_attribute(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_API_ADD_ATTRIBUTE *da = &(p_data->add_attr);
-    tBTA_JV_DELETE_ATTR   evt_data;
-    UINT32 handle;
-
-    evt_data.status = BTA_JV_FAILURE;
-    evt_data.handle = da->handle;
-    handle = bta_jv_get_sdp_handle(da->handle);
-
-    if(handle)
-    {
-        /* this is a record created by JV */
-        if(SDP_DeleteAttribute(handle, da->attr_id))
-            evt_data.status = BTA_JV_SUCCESS;
-    }
-
-    if(bta_jv_cb.p_dm_cback)
-        bta_jv_cb.p_dm_cback(BTA_JV_DELETE_ATTR_EVT, (tBTA_JV *)&evt_data);
-#endif
-}
-
-/*******************************************************************************
-**
 ** Function     bta_jv_delete_record
 **
 ** Description  Delete an SDP record
@@ -1473,383 +688,6 @@
     }
 }
 
-#if SDP_FOR_JV_INCLUDED == TRUE
-/*******************************************************************************
-**
-** Function     bta_jv_sdp_res_cback
-**
-** Description  Callback for Start Discovery
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_sdp_res_cback (UINT16 event, tSDP_DATA *p_data)
-{
-    tBTA_JV evt_data;
-    tBTA_JV_L2C_CB  *p_cb = &bta_jv_cb.l2c_cb[BTA_JV_L2C_FOR_SDP_HDL];
-
-    APPL_TRACE_DEBUG( "bta_jv_sdp_res_cback: %d evt:x%x",
-        bta_jv_cb.sdp_for_jv, event);
-
-    if(!bta_jv_cb.sdp_for_jv)
-        return;
-
-    evt_data.l2c_open.status = BTA_JV_SUCCESS;
-    evt_data.l2c_open.handle = BTA_JV_L2C_FOR_SDP_HDL;
-
-    switch(event)
-    {
-    case SDP_EVT_OPEN:
-        bdcpy(evt_data.l2c_open.rem_bda, p_data->open.peer_addr);
-        evt_data.l2c_open.tx_mtu = p_data->open.peer_mtu;
-        p_cb->state = BTA_JV_ST_SR_OPEN;
-        p_cb->p_cback(BTA_JV_L2CAP_OPEN_EVT, &evt_data);
-        break;
-    case SDP_EVT_DATA_IND:
-        evt_data.handle = BTA_JV_L2C_FOR_SDP_HDL;
-        memcpy(p_bta_jv_cfg->p_sdp_raw_data, p_data->data.p_data, p_data->data.data_len);
-        APPL_TRACE_DEBUG( "data size: %d/%d ", bta_jv_cb.sdp_data_size, p_data->data.data_len);
-        bta_jv_cb.sdp_data_size = p_data->data.data_len;
-        p_cb->p_cback(BTA_JV_L2CAP_DATA_IND_EVT, &evt_data);
-        break;
-    }
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_sdp_cback
-**
-** Description  Callback for Start Discovery
-**
-** Returns      void
-**
-*******************************************************************************/
-static void bta_jv_sdp_cback(UINT16 result)
-{
-    tBTA_JV_L2CAP_CLOSE close;
-    tBTA_JV_L2C_CB  *p_cb = &bta_jv_cb.l2c_cb[BTA_JV_L2C_FOR_SDP_HDL];
-    APPL_TRACE_DEBUG( "bta_jv_sdp_cback: result:x%x", result);
-
-    if(p_cb->p_cback)
-    {
-        close.handle    = BTA_JV_L2C_FOR_SDP_HDL;
-        close.async     = FALSE;
-        close.status    = BTA_JV_SUCCESS;
-        bta_jv_free_sec_id(&p_cb->sec_id);
-        p_cb->p_cback(BTA_JV_L2CAP_CLOSE_EVT, (tBTA_JV *)&close);
-    }
-
-    bta_jv_cb.sdp_for_jv = 0;
-    p_cb->p_cback = NULL;
-
-}
-#endif
-
-/*******************************************************************************
-**
-** Function     bta_jv_l2cap_connect
-**
-** Description  makes an l2cap client connection
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_l2cap_connect(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_L2C_CB      *p_cb;
-    tBTA_JV_L2CAP_CL_INIT  evt_data;
-    UINT16  handle=GAP_INVALID_HANDLE;
-    UINT8   sec_id;
-    tL2CAP_CFG_INFO cfg;
-    tBTA_JV_API_L2CAP_CONNECT *cc = &(p_data->l2cap_connect);
-
-    memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
-    cfg.mtu_present = TRUE;
-    cfg.mtu = cc->rx_mtu;
-    /* TODO: DM role manager
-    L2CA_SetDesireRole(cc->role);
-    */
-
-    sec_id = bta_jv_alloc_sec_id();
-    evt_data.sec_id = sec_id;
-    evt_data.status = BTA_JV_FAILURE;
-    if (sec_id)
-    {
-#if SDP_FOR_JV_INCLUDED == TRUE
-        if(SDP_PSM == cc->remote_psm && 0 == bta_jv_cb.sdp_for_jv)
-        {
-            bta_jv_cb.sdp_for_jv = SDP_ConnOpen(cc->peer_bd_addr,
-                                       bta_jv_sdp_res_cback,
-                                       bta_jv_sdp_cback);
-            if(bta_jv_cb.sdp_for_jv)
-            {
-                bta_jv_cb.sdp_data_size = 0;
-                handle = BTA_JV_L2C_FOR_SDP_HDL;
-                evt_data.status = BTA_JV_SUCCESS;
-            }
-        }
-        else
-#endif
-        if(bta_jv_check_psm(cc->remote_psm)) /* allowed */
-        {
-            if( (handle = GAP_ConnOpen("", sec_id, 0, cc->peer_bd_addr, cc->remote_psm,
-                &cfg, cc->sec_mask, GAP_FCR_CHAN_OPT_BASIC,
-                bta_jv_l2cap_client_cback)) != GAP_INVALID_HANDLE )
-            {
-                evt_data.status = BTA_JV_SUCCESS;
-            }
-        }
-    }
-
-    if (evt_data.status == BTA_JV_SUCCESS)
-    {
-        p_cb = &bta_jv_cb.l2c_cb[handle];
-        p_cb->handle = handle;
-        p_cb->p_cback = cc->p_cback;
-        p_cb->psm = 0;  /* not a server */
-        p_cb->sec_id = sec_id;
-        p_cb->state = BTA_JV_ST_CL_OPENING;
-    }
-    else
-    {
-        bta_jv_free_sec_id(&sec_id);
-    }
-    evt_data.handle = handle;
-    cc->p_cback(BTA_JV_L2CAP_CL_INIT_EVT, (tBTA_JV *)&evt_data);
-#endif
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_l2cap_close
-**
-** Description  Close an L2CAP client connection
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_l2cap_close(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_L2CAP_CLOSE  evt_data;
-    tBTA_JV_API_L2CAP_CLOSE *cc = &(p_data->l2cap_close);
-    tBTA_JV_L2CAP_CBACK *p_cback = cc->p_cb->p_cback;
-
-    evt_data.handle = cc->handle;
-    evt_data.status = bta_jv_free_l2c_cb(cc->p_cb);
-    evt_data.async = FALSE;
-
-    if (p_cback)
-        p_cback(BTA_JV_L2CAP_CLOSE_EVT, (tBTA_JV *)&evt_data);
-    else
-        APPL_TRACE_ERROR("### NO CALLBACK SET !!! ###");
-#endif
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_l2cap_start_server
-**
-** Description  starts an L2CAP server
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_l2cap_start_server(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_L2C_CB      *p_cb;
-    UINT8   sec_id;
-    UINT16  handle;
-    tL2CAP_CFG_INFO cfg;
-    tBTA_JV_L2CAP_START evt_data;
-    tBTA_JV_API_L2CAP_SERVER *ls = &(p_data->l2cap_server);
-
-    memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
-
-    //FIX: MTU=0 means not present
-    if (ls->rx_mtu >0)
-    {
-        cfg.mtu_present = TRUE;
-        cfg.mtu = ls->rx_mtu;
-    }
-    else
-    {
-        cfg.mtu_present = FALSE;
-        cfg.mtu = 0;
-    }
-
-    /* TODO DM role manager
-    L2CA_SetDesireRole(ls->role);
-    */
-
-    sec_id = bta_jv_alloc_sec_id();
-    if (0 == sec_id || (FALSE == bta_jv_check_psm(ls->local_psm)) ||
-        (handle = GAP_ConnOpen("JV L2CAP", sec_id, 1, 0, ls->local_psm, &cfg,
-            ls->sec_mask, GAP_FCR_CHAN_OPT_BASIC, bta_jv_l2cap_server_cback)) == GAP_INVALID_HANDLE)
-    {
-        bta_jv_free_sec_id(&sec_id);
-        evt_data.status = BTA_JV_FAILURE;
-    }
-    else
-    {
-        /* default JV implementation requires explicit call
-           to allow incoming connections when ready*/
-
-        GAP_SetAcceptReady(handle, FALSE);
-
-        p_cb = &bta_jv_cb.l2c_cb[handle];
-        evt_data.status = BTA_JV_SUCCESS;
-        evt_data.handle = handle;
-        evt_data.sec_id = sec_id;
-        p_cb->p_cback = ls->p_cback;
-        p_cb->handle = handle;
-        p_cb->sec_id = sec_id;
-        p_cb->state = BTA_JV_ST_SR_LISTEN;
-        p_cb->psm = ls->local_psm;
-    }
-    ls->p_cback(BTA_JV_L2CAP_START_EVT, (tBTA_JV *)&evt_data);
-#endif
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_l2cap_stop_server
-**
-** Description  stops an L2CAP server
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_l2cap_stop_server(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_L2C_CB      *p_cb;
-    tBTA_JV_L2CAP_CLOSE  evt_data;
-    tBTA_JV_API_L2CAP_SERVER *ls = &(p_data->l2cap_server);
-    tBTA_JV_L2CAP_CBACK *p_cback;
-    int i;
-
-    for(i=0; i<BTA_JV_MAX_L2C_CONN; i++)
-    {
-        if(bta_jv_cb.l2c_cb[i].psm == ls->local_psm)
-        {
-            p_cb = &bta_jv_cb.l2c_cb[i];
-            p_cback = p_cb->p_cback;
-            evt_data.handle = p_cb->handle;
-            evt_data.status = bta_jv_free_l2c_cb(p_cb);
-            evt_data.async = FALSE;
-            p_cback(BTA_JV_L2CAP_CLOSE_EVT, (tBTA_JV *)&evt_data);
-            break;
-        }
-    }
-#endif
-}
-
-/*******************************************************************************
-**
-** Function     bta_jv_l2cap_read
-**
-** Description  Read data from an L2CAP connection
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_l2cap_read(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_L2CAP_READ evt_data;
-    tBTA_JV_API_L2CAP_READ *rc = &(p_data->l2cap_read);
-
-    evt_data.status = BTA_JV_FAILURE;
-    evt_data.handle = rc->handle;
-    evt_data.req_id = rc->req_id;
-    evt_data.p_data = rc->p_data;
-    evt_data.len    = 0;
-#if SDP_FOR_JV_INCLUDED == TRUE
-    if(BTA_JV_L2C_FOR_SDP_HDL == rc->handle)
-    {
-        evt_data.len = rc->len;
-        if(evt_data.len > bta_jv_cb.sdp_data_size)
-            evt_data.len = bta_jv_cb.sdp_data_size;
-
-        memcpy(rc->p_data, p_bta_jv_cfg->p_sdp_raw_data, evt_data.len);
-        bta_jv_cb.sdp_data_size = 0;
-        evt_data.status = BTA_JV_SUCCESS;
-    }
-    else
-#endif
-    if (BT_PASS == GAP_ConnReadData(rc->handle, rc->p_data, rc->len, &evt_data.len))
-    {
-        evt_data.status = BTA_JV_SUCCESS;
-    }
-
-    rc->p_cback(BTA_JV_L2CAP_READ_EVT, (tBTA_JV *)&evt_data);
-#endif
-}
-
-
-/*******************************************************************************
-**
-** Function     bta_jv_l2cap_write
-**
-** Description  Write data to an L2CAP connection
-**
-** Returns      void
-**
-*******************************************************************************/
-void bta_jv_l2cap_write(tBTA_JV_MSG *p_data)
-{
-    UNUSED(p_data);
-#if 0
-    tBTA_JV_L2CAP_WRITE evt_data;
-    tBTA_JV_API_L2CAP_WRITE *ls = &(p_data->l2cap_write);
-
-    evt_data.status = BTA_JV_FAILURE;
-    evt_data.handle = ls->handle;
-    evt_data.req_id = ls->req_id;
-    evt_data.cong   = ls->p_cb->cong;
-    evt_data.len    = 0;
-#if SDP_FOR_JV_INCLUDED == TRUE
-    if(BTA_JV_L2C_FOR_SDP_HDL == ls->handle)
-    {
-        UINT8   *p;
-        BT_HDR  *p_msg = (BT_HDR *) GKI_getbuf ((UINT16)(ls->len + BT_HDR_SIZE + L2CAP_MIN_OFFSET));
-        if(p_msg)
-        {
-            p_msg->offset = L2CAP_MIN_OFFSET;
-            p = (UINT8 *)(p_msg + 1) + L2CAP_MIN_OFFSET;
-            p_msg->len = ls->len;
-            memcpy(p, ls->p_data, p_msg->len);
-            bta_jv_pm_conn_busy(ls->p_cb->p_pm_cb);
-            if(SDP_WriteData (bta_jv_cb.sdp_for_jv, p_msg))
-            {
-                evt_data.len    = ls->len;
-                evt_data.status = BTA_JV_SUCCESS;
-            }
-        }
-    }
-    else
-#endif
-    {
-        bta_jv_pm_conn_busy(ls->p_cb->p_pm_cb);
-        if (!evt_data.cong &&
-           BT_PASS == GAP_ConnWriteData(ls->handle, ls->p_data, ls->len, &evt_data.len))
-        {
-           evt_data.status = BTA_JV_SUCCESS;
-        }
-    }
-    ls->p_cb->p_cback(BTA_JV_L2CAP_WRITE_EVT, (tBTA_JV *)&evt_data);
-	bta_jv_set_pm_conn_state(ls->p_cb->p_pm_cb, BTA_JV_CONN_IDLE);
-#endif
-}
-
 /*******************************************************************************
 **
 ** Function     bta_jv_port_data_co_cback
@@ -1860,11 +698,6 @@
 ** Returns      void
 **
 *******************************************************************************/
-/*
-#define DATA_CO_CALLBACK_TYPE_INCOMING          1
-#define DATA_CO_CALLBACK_TYPE_OUTGOING_SIZE     2
-#define DATA_CO_CALLBACK_TYPE_OUTGOING          3
-*/
 static int bta_jv_port_data_co_cback(UINT16 port_handle, UINT8 *buf, UINT16 len, int type)
 {
     tBTA_JV_RFC_CB  *p_cb = bta_jv_rfc_port_to_cb(port_handle);
@@ -2311,8 +1144,6 @@
 
                 port_state.fc_type = (PORT_FC_CTS_ON_INPUT | PORT_FC_CTS_ON_OUTPUT);
 
-/* coverity[uninit_use_in_call]
-FALSE-POSITIVE: port_state is initialized at PORT_GetState() */
                 PORT_SetState(p_pcb->port_handle, &port_state);
                 p_pcb->handle = BTA_JV_RFC_H_S_TO_HDL(p_cb->handle, si);
                 APPL_TRACE_DEBUG("bta_jv_add_rfc_port: p_pcb->handle:0x%x, curr_sess:%d",
@@ -2390,7 +1221,7 @@
         evt_data.status = BTA_JV_SUCCESS;
         evt_data.handle = p_cb->handle;
         evt_data.sec_id = sec_id;
-        evt_data.use_co = TRUE; //FALSE;
+        evt_data.use_co = TRUE;
 
         PORT_ClearKeepHandleFlag(handle);
         PORT_SetEventCallback(handle, bta_jv_port_event_sr_cback);
@@ -2399,10 +1230,9 @@
 
         port_state.fc_type = (PORT_FC_CTS_ON_INPUT | PORT_FC_CTS_ON_OUTPUT);
 
-/* coverity[uninit_use_in_call]
-FALSE-POSITIVE: port_state is initialized at PORT_GetState() */
         PORT_SetState(handle, &port_state);
     } while (0);
+
     rs->p_cback(BTA_JV_RFCOMM_START_EVT, (tBTA_JV *)&evt_data, rs->user_data);
     if(evt_data.status == BTA_JV_SUCCESS)
     {
diff --git a/bta/jv/bta_jv_api.c b/bta/jv/bta_jv_api.c
index e0d100d..a242f45 100644
--- a/bta/jv/bta_jv_api.c
+++ b/bta/jv/bta_jv_api.c
@@ -23,7 +23,6 @@
  *
  ******************************************************************************/
 #include "bta_api.h"
-#include "bd.h"
 #include "bta_sys.h"
 #include "bta_jv_api.h"
 #include "bta_jv_int.h"
@@ -129,359 +128,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_JvSetDiscoverability
-**
-** Description      This function sets the Bluetooth  discoverable modes
-**                  of the local device.  This controls whether other
-**                  Bluetooth devices can find the local device.
-**
-**                  When the operation is complete the tBTA_JV_DM_CBACK callback
-**                  function will be called with a BTA_JV_SET_DISCOVER_EVT.
-**
-** Returns          BTA_JV_SUCCESS if successful.
-**                  BTA_JV_FAIL if internal failure.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvSetDiscoverability(tBTA_JV_DISC disc_mode)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_SET_DISCOVERABILITY *p_msg;
-
-    APPL_TRACE_API( "BTA_JvSetDiscoverability");
-    if ((p_msg = (tBTA_JV_API_SET_DISCOVERABILITY *)GKI_getbuf(sizeof(tBTA_JV_MSG))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_SET_DISCOVERABILITY_EVT;
-        p_msg->disc_mode = disc_mode;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetDiscoverability
-**
-** Description      This function gets the Bluetooth
-**                  discoverable modes of local device
-**
-** Returns          The current Bluetooth discoverable mode.
-**
-*******************************************************************************/
-tBTA_JV_DISC BTA_JvGetDiscoverability(void)
-{
-    APPL_TRACE_API( "BTA_JvGetDiscoverability");
-    return BTM_ReadDiscoverability(0, 0);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetLocalDeviceAddr
-**
-** Description      This function obtains the local Bluetooth device address.
-**                  The local Bluetooth device address is reported by the
-**                  tBTA_JV_DM_CBACK callback with a BTA_JV_LOCAL_ADDR_EVT.
-**
-** Returns          BTA_JV_SUCCESS if successful.
-**                  BTA_JV_FAIL if internal failure.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvGetLocalDeviceAddr(void)
-{
-    tBTA_JV_STATUS ret = BTA_JV_FAILURE;
-    BT_HDR *p_msg;
-
-    APPL_TRACE_API( "BTA_JvGetLocalDeviceAddr");
-    if ((p_msg = (BT_HDR *)GKI_getbuf(sizeof(BT_HDR))) != NULL)
-    {
-        p_msg->event = BTA_JV_API_GET_LOCAL_DEVICE_ADDR_EVT;
-        bta_sys_sendmsg(p_msg);
-        ret = BTA_JV_SUCCESS;
-    }
-
-    return(ret);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetLocalDeviceName
-**
-** Description      This function obtains the name of the local device
-**                  The local Bluetooth device name is reported by the
-**                  tBTA_JV_DM_CBACK callback with a BTA_JV_LOCAL_NAME_EVT.
-**
-** Returns          BTA_JV_SUCCESS if successful.
-**                  BTA_JV_FAIL if internal failure.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvGetLocalDeviceName(void)
-{
-    tBTA_JV_STATUS ret = BTA_JV_FAILURE;
-    BT_HDR *p_msg;
-
-    APPL_TRACE_API( "BTA_JvGetLocalDeviceName");
-    if ((p_msg = (BT_HDR *)GKI_getbuf(sizeof(BT_HDR))) != NULL)
-    {
-        p_msg->event = BTA_JV_API_GET_LOCAL_DEVICE_NAME_EVT;
-        bta_sys_sendmsg(p_msg);
-        ret = BTA_JV_SUCCESS;
-    }
-
-    return(ret);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetRemoteDeviceName
-**
-** Description      This function obtains the name of the specified device.
-**                  The Bluetooth device name is reported by the
-**                  tBTA_JV_DM_CBACK callback with a BTA_JV_REMOTE_NAME_EVT.
-**
-** Returns          BTA_JV_SUCCESS if successful.
-**                  BTA_JV_FAIL if internal failure.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvGetRemoteDeviceName(BD_ADDR bd_addr)
-{
-    tBTA_JV_STATUS ret = BTA_JV_FAILURE;
-    tBTA_JV_API_GET_REMOTE_NAME *p_msg;
-
-    APPL_TRACE_API( "BTA_JvGetRemoteDeviceName");
-    if ((p_msg = (tBTA_JV_API_GET_REMOTE_NAME *)GKI_getbuf(sizeof(tBTA_JV_API_GET_REMOTE_NAME))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_GET_REMOTE_DEVICE_NAME_EVT;
-        bdcpy(p_msg->bd_addr, bd_addr);
-        bta_sys_sendmsg(p_msg);
-        ret = BTA_JV_SUCCESS;
-    }
-
-    return(ret);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetPreknownDevice
-**
-** Description      This function obtains the Bluetooth address in the inquiry
-**                  database collected via the previous call to BTA_DmSearch().
-**
-** Returns          The number of preknown devices if p_bd_addr is NULL
-**                  BTA_JV_SUCCESS if successful.
-**                  BTA_JV_INTERNAL_ERR(-1) if internal failure.
-**
-*******************************************************************************/
-INT32 BTA_JvGetPreknownDevice(UINT8 * p_bd_addr, UINT32 index)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTM_INQ_INFO *p_info;
-    UINT32  count = 0;
-    INT32   ret = BTA_JV_INTERNAL_ERR;
-
-    APPL_TRACE_API( "BTA_JvGetPreknownDevice");
-    p_info = BTM_InqFirstResult();
-    if(p_info)
-    {
-        status = BTA_JV_SUCCESS;
-        /* the database is valid */
-        if(NULL == p_bd_addr)
-        {
-            /* p_bd_addr is NULL: count the number of preknown devices */
-            /* set the index to an invalid size (too big) */
-            index = BTM_INQ_DB_SIZE;
-        }
-        else if(index >= BTM_INQ_DB_SIZE)
-        {
-            /* invalid index - error */
-            status = (tBTA_JV_STATUS)BTA_JV_INTERNAL_ERR;
-        }
-
-        if(BTA_JV_SUCCESS == status)
-        {
-            while(p_info && index > count)
-            {
-                count++;
-                p_info = BTM_InqNextResult(p_info);
-            }
-
-            if(p_bd_addr)
-            {
-                if(index == count && p_info)
-                {
-                    count = BTA_JV_SUCCESS;
-                    bdcpy(p_bd_addr, p_info->results.remote_bd_addr);
-                }
-                else
-                    status = (tBTA_JV_STATUS)BTA_JV_INTERNAL_ERR;
-            }
-            /*
-            else report the count
-            */
-        }
-        /*
-        else error had happened.
-        */
-    }
-
-    if(BTA_JV_SUCCESS == status)
-    {
-        ret = count;
-    }
-    return ret;
-}
-
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetDeviceClass
-**
-** Description      This function obtains the local Class of Device. This
-**                  function executes in place. The result is returned right away.
-**
-** Returns          DEV_CLASS, A three-byte array of UINT8 that contains the
-**                  Class of Device information. The definitions are in the
-**                  "Bluetooth Assigned Numbers".
-**
-*******************************************************************************/
-UINT8 * BTA_JvGetDeviceClass(void)
-{
-    APPL_TRACE_API( "BTA_JvGetDeviceClass");
-    return BTM_ReadDeviceClass();
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvSetServiceClass
-**
-** Description      This function sets the service class of local Class of Device
-**
-** Returns          BTA_JV_SUCCESS if successful.
-**                  BTA_JV_FAIL if internal failure.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvSetServiceClass(UINT32 service)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_SET_SERVICE_CLASS *p_msg;
-
-    APPL_TRACE_API( "BTA_JvSetServiceClass");
-    if ((p_msg = (tBTA_JV_API_SET_SERVICE_CLASS *)GKI_getbuf(sizeof(tBTA_JV_API_SET_SERVICE_CLASS))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_SET_SERVICE_CLASS_EVT;
-        p_msg->service = service;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvSetEncryption
-**
-** Description      This function ensures that the connection to the given device
-**                  is encrypted.
-**                  When the operation is complete the tBTA_JV_DM_CBACK callback
-**                  function will be called with a BTA_JV_SET_ENCRYPTION_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvSetEncryption(BD_ADDR bd_addr)
-{
-    tBTA_JV_STATUS ret = BTA_JV_FAILURE;
-    tBTA_JV_API_SET_ENCRYPTION *p_msg;
-
-    APPL_TRACE_API( "BTA_JvSetEncryption");
-    if ((p_msg = (tBTA_JV_API_SET_ENCRYPTION *)GKI_getbuf(sizeof(tBTA_JV_API_SET_ENCRYPTION))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_SET_ENCRYPTION_EVT;
-        bdcpy(p_msg->bd_addr, bd_addr);
-        bta_sys_sendmsg(p_msg);
-        ret = BTA_JV_SUCCESS;
-    }
-
-    return(ret);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvIsAuthenticated
-**
-** Description      This function checks if the peer device is authenticated
-**
-** Returns          TRUE if authenticated.
-**                  FALSE if not.
-**
-*******************************************************************************/
-BOOLEAN BTA_JvIsAuthenticated(BD_ADDR bd_addr)
-{
-    BOOLEAN is_authenticated = FALSE;
-    UINT8 sec_flags;
-
-    if(BTM_GetSecurityFlags(bd_addr, &sec_flags))
-    {
-        if(sec_flags&BTM_SEC_FLAG_AUTHENTICATED)
-            is_authenticated = TRUE;
-    }
-    return is_authenticated;
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvIsTrusted
-**
-** Description      This function checks if the peer device is trusted
-**                  (previously paired)
-**
-** Returns          TRUE if trusted.
-**                  FALSE if not.
-**
-*******************************************************************************/
-BOOLEAN BTA_JvIsTrusted(BD_ADDR bd_addr)
-{
-    BOOLEAN is_trusted = FALSE;
-    UINT8 sec_flags;
-
-    if(BTM_GetSecurityFlags(bd_addr, &sec_flags))
-    {
-        if ((sec_flags&BTM_SEC_FLAG_AUTHENTICATED) ||
-            (sec_flags&BTM_SEC_FLAG_LKEY_KNOWN))
-        {
-            is_trusted = TRUE;
-        }
-    }
-    return is_trusted;
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvIsAuthorized
-**
-** Description      This function checks if the peer device is authorized
-**
-** Returns          TRUE if authorized.
-**                  FALSE if not.
-**
-*******************************************************************************/
-BOOLEAN BTA_JvIsAuthorized(BD_ADDR bd_addr)
-{
-    BOOLEAN is_authorized = FALSE;
-    UINT8 sec_flags;
-
-    if(BTM_GetSecurityFlags(bd_addr, &sec_flags))
-    {
-        if(sec_flags&BTM_SEC_FLAG_AUTHORIZED)
-            is_authorized = TRUE;
-    }
-    return is_authorized;
-}
-
-/*******************************************************************************
-**
 ** Function         BTA_JvIsEncrypted
 **
 ** Description      This function checks if the link to peer device is encrypted
@@ -507,104 +153,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_JvGetSecurityMode
-**
-** Description      This function returns the current Bluetooth security mode
-**                  of the local device
-**
-** Returns          The current Bluetooth security mode.
-**
-*******************************************************************************/
-tBTA_JV_SEC_MODE BTA_JvGetSecurityMode(void)
-{
-   return BTM_GetSecurityMode();
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetSCN
-**
-** Description      This function reserves a SCN (server channel number) for
-**                  applications running over RFCOMM. It is primarily called by
-**                  server profiles/applications to register their SCN into the
-**                  SDP database. The SCN is reported by the tBTA_JV_DM_CBACK
-**                  callback with a BTA_JV_GET_SCN_EVT.
-**                  If the SCN reported is 0, that means all SCN resources are
-**                  exhausted.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvGetSCN(void)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    BT_HDR *p_msg;
-
-    APPL_TRACE_API( "BTA_JvGetSCN");
-    if ((p_msg = (BT_HDR *)GKI_getbuf(sizeof(BT_HDR))) != NULL)
-    {
-        p_msg->event = BTA_JV_API_GET_SCN_EVT;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvFreeSCN
-**
-** Description      This function frees a server channel number that was used
-**                  by an application running over RFCOMM.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvFreeSCN(UINT8 scn)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_FREE_SCN *p_msg;
-
-    APPL_TRACE_API( "BTA_JvFreeSCN");
-    if ((p_msg = (tBTA_JV_API_FREE_SCN *)GKI_getbuf(sizeof(tBTA_JV_API_FREE_SCN))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_FREE_SCN_EVT;
-        p_msg->scn       = scn;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetPSM
-**
-** Description      This function reserves a PSM (Protocol Service Multiplexer)
-**                  applications running over L2CAP. It is primarily called by
-**                  server profiles/applications to register their PSM into the
-**                  SDP database.
-**
-** Returns          The next free PSM
-**
-*******************************************************************************/
-UINT16 BTA_JvGetPSM(void)
-{
-#if 0
-    APPL_TRACE_API( "BTA_JvGetPSM");
-
-    return (L2CA_AllocatePSM());
-#endif
-    return 0;
-}
-
-
-/*******************************************************************************
-**
 ** Function         BTA_JvStartDiscovery
 **
 ** Description      This function performs service discovery for the services
@@ -640,187 +188,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_JvCancelDiscovery
-**
-** Description      This function cancels an active service discovery.
-**                  When the operation is
-**                  complete the tBTA_JV_DM_CBACK callback function will be
-**                  called with a BTA_JV_CANCEL_DISCVRY_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvCancelDiscovery(void * user_data)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_CANCEL_DISCOVERY *p_msg;
-
-    APPL_TRACE_API( "BTA_JvCancelDiscovery");
-    if ((p_msg = (tBTA_JV_API_CANCEL_DISCOVERY *)GKI_getbuf(sizeof(tBTA_JV_API_CANCEL_DISCOVERY))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_CANCEL_DISCOVERY_EVT;
-        p_msg->user_data = user_data;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvGetServicesLength
-**
-** Description      This function obtains the number of services and the length
-**                  of each service found in the SDP database (result of last
-**                  BTA_JvStartDiscovery().When the operation is complete the
-**                  tBTA_JV_DM_CBACK callback function will be called with a
-**                  BTA_JV_SERVICES_LEN_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvGetServicesLength(BOOLEAN inc_hdr, UINT16 *p_services_len)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_GET_SERVICES_LENGTH *p_msg;
-
-    APPL_TRACE_API( "BTA_JvGetServicesLength");
-    if ((p_msg = (tBTA_JV_API_GET_SERVICES_LENGTH *)GKI_getbuf(sizeof(tBTA_JV_API_GET_SERVICES_LENGTH))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_GET_SERVICES_LENGTH_EVT;
-        p_msg->p_services_len = p_services_len;
-        p_msg->inc_hdr = inc_hdr;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-/*******************************************************************************
-**
-** Function         BTA_JvGetServicesResult
-**
-** Description      This function returns a number of service records found
-**                  during current service search, equals to the number returned
-**                  by previous call to BTA_JvGetServicesLength.
-**                  The contents of each SDP record will be returned under a
-**                  TLV (type, len, value) representation in the data buffer
-**                  provided by the caller.
-**
-** Returns          -1, if error. Otherwise, the number of services
-**
-*******************************************************************************/
-INT32 BTA_JvGetServicesResult(BOOLEAN inc_hdr, UINT8 **TLVs)
-{
-    UNUSED(inc_hdr);
-    UNUSED(TLVs);
-#if 0
-    INT32 num_services = -1;
-    UINT8   *p, *np, *op, type;
-    UINT32  raw_used, raw_cur;
-    UINT32  len;
-    UINT32  hdr_len;
-
-    APPL_TRACE_API( "BTA_JvGetServicesResult");
-    if(p_bta_jv_cfg->p_sdp_db->p_first_rec)
-    {
-        /* the database is valid */
-        num_services = 0;
-        p = p_bta_jv_cfg->p_sdp_db->raw_data;
-        raw_used = p_bta_jv_cfg->p_sdp_db->raw_used;
-        while(raw_used && p)
-        {
-            op = p;
-            type = *p++;
-            np = sdpu_get_len_from_type(p, type, &len);
-            p = np + len;
-            raw_cur = p - op;
-            if(raw_used >= raw_cur)
-            {
-                raw_used -= raw_cur;
-            }
-            else
-            {
-                /* error. can not continue */
-                break;
-            }
-            if(inc_hdr)
-            {
-                hdr_len = np - op;
-                memcpy(TLVs[num_services++], op, len+hdr_len);
-            }
-            else
-            {
-                memcpy(TLVs[num_services++], np, len);
-            }
-        } /* end of while */
-    }
-    return(num_services);
-#endif
-    return 0;
-}
-/*******************************************************************************
-**
-** Function         BTA_JvServiceSelect
-**
-** Description      This function checks if the SDP database contains the given
-**                  service UUID. When the operation is complete the
-**                  tBTA_JV_DM_CBACK callback function will be called with a
-**                  BTA_JV_SERVICE_SEL_EVT with the length of the service record.
-**                  If the service is not found or error, -1 is reported.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvServiceSelect(UINT16 uuid)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_SERVICE_SELECT *p_msg;
-
-    APPL_TRACE_API( "BTA_JvServiceSelect");
-    if ((p_msg = (tBTA_JV_API_SERVICE_SELECT *)GKI_getbuf(sizeof(tBTA_JV_API_SERVICE_SELECT))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_SERVICE_SELECT_EVT;
-        p_msg->uuid = uuid;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvServiceResult
-**
-** Description      This function returns the contents of the SDP record from
-**                  last BTA_JvServiceSelect. The contents will be returned under
-**                  a TLV (type, len, value) representation in the data buffer
-**                  provided by the caller.
-**
-** Returns          -1, if error. Otherwise, the length of service record.
-**
-*******************************************************************************/
-INT32 BTA_JvServiceResult(UINT8 *TLV)
-{
-    INT32   serv_sel = -1;
-
-    APPL_TRACE_API( "BTA_JvServiceResult");
-    if(bta_jv_cb.p_sel_raw_data)
-    {
-        serv_sel = bta_jv_cb.sel_len;
-        memcpy(TLV, bta_jv_cb.p_sel_raw_data, serv_sel);
-    }
-
-    return serv_sel;
-}
-
-
-/*******************************************************************************
-**
 ** Function         BTA_JvCreateRecord
 **
 ** Description      Create a service record in the local SDP database.
@@ -850,108 +217,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_JvUpdateRecord
-**
-** Description      Update a service record in the local SDP database.
-**                  When the operation is complete the tBTA_JV_DM_CBACK callback
-**                  function will be called with a BTA_JV_UPDATE_RECORD_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvUpdateRecord(UINT32 handle, UINT16 *p_ids,
-    UINT8 **p_values, INT32 *p_value_sizes, INT32 array_len)
-{
-    UNUSED(handle);
-    UNUSED(p_ids);
-    UNUSED(p_values);
-    UNUSED(p_value_sizes);
-    UNUSED(array_len);
-#if 0
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_UPDATE_RECORD *p_msg;
-
-    APPL_TRACE_API( "BTA_JvUpdateRecord");
-    if ((p_msg = (tBTA_JV_API_UPDATE_RECORD *)GKI_getbuf(sizeof(tBTA_JV_API_UPDATE_RECORD))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_UPDATE_RECORD_EVT;
-        p_msg->handle = handle;
-        p_msg->p_ids = p_ids;
-        p_msg->p_values = p_values;
-        p_msg->p_value_sizes = p_value_sizes;
-        p_msg->array_len = array_len;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-    return(status);
-#endif
-    return -1;
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvAddAttribute
-**
-** Description      Add an attribute to a service record in the local SDP database.
-**                  When the operation is complete the tBTA_JV_DM_CBACK callback
-**                  function will be called with a BTA_JV_ADD_ATTR_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvAddAttribute(UINT32 handle, UINT16 attr_id,
-    UINT8 *p_value, INT32 value_size)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_ADD_ATTRIBUTE *p_msg;
-
-    APPL_TRACE_API( "BTA_JvAddAttribute");
-    if ((p_msg = (tBTA_JV_API_ADD_ATTRIBUTE *)GKI_getbuf(sizeof(tBTA_JV_API_ADD_ATTRIBUTE))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_ADD_ATTRIBUTE_EVT;
-        p_msg->handle = handle;
-        p_msg->attr_id = attr_id;
-        p_msg->p_value = p_value;
-        p_msg->value_size = value_size;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvDeleteAttribute
-**
-** Description      Delete an attribute from a service record in the local SDP database.
-**                  When the operation is complete the tBTA_JV_DM_CBACK callback
-**                  function will be called with a BTA_JV_DELETE_ATTR_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvDeleteAttribute(UINT32 handle, UINT16 attr_id)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_ADD_ATTRIBUTE *p_msg;
-
-    APPL_TRACE_API( "BTA_JvDeleteAttribute");
-    if ((p_msg = (tBTA_JV_API_ADD_ATTRIBUTE *)GKI_getbuf(sizeof(tBTA_JV_API_ADD_ATTRIBUTE))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_DELETE_ATTRIBUTE_EVT;
-        p_msg->handle = handle;
-        p_msg->attr_id = attr_id;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-    return(status);
-}
-
-/*******************************************************************************
-**
 ** Function         BTA_JvDeleteRecord
 **
 ** Description      Delete a service record in the local SDP database.
@@ -978,366 +243,6 @@
 
 /*******************************************************************************
 **
-** Function         BTA_JvReadRecord
-**
-** Description      Read a service record in the local SDP database.
-**
-** Returns          -1, if the record is not found.
-**                  Otherwise, the offset (0 or 1) to start of data in p_data.
-**
-**                  The size of data copied into p_data is in *p_data_len.
-**
-*******************************************************************************/
-INT32 BTA_JvReadRecord(UINT32 handle, UINT8 *p_data, INT32 *p_data_len)
-{
-    UINT32 sdp_handle;
-
-    sdp_handle = bta_jv_get_sdp_handle(handle);
-
-    if(sdp_handle)
-    {
-        return SDP_ReadRecord(sdp_handle, p_data, p_data_len);
-    }
-
-    return -1;
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capConnect
-**
-** Description      Initiate a connection as a L2CAP client to the given BD
-**                  Address.
-**                  When the connection is initiated or failed to initiate,
-**                  tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_CL_INIT_EVT
-**                  When the connection is established or failed,
-**                  tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_OPEN_EVT
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvL2capConnect(tBTA_SEC sec_mask,
-                           tBTA_JV_ROLE role, UINT16 remote_psm, UINT16 rx_mtu,
-                           BD_ADDR peer_bd_addr, tBTA_JV_L2CAP_CBACK *p_cback)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_L2CAP_CONNECT *p_msg;
-
-    APPL_TRACE_API( "BTA_JvL2capConnect");
-    if (p_cback &&
-        (p_msg = (tBTA_JV_API_L2CAP_CONNECT *)GKI_getbuf(sizeof(tBTA_JV_API_L2CAP_CONNECT))) != NULL)
-    {
-        p_msg->hdr.event    = BTA_JV_API_L2CAP_CONNECT_EVT;
-        p_msg->sec_mask     = sec_mask;
-        p_msg->role         = role;
-        p_msg->remote_psm   = remote_psm;
-        p_msg->rx_mtu       = rx_mtu;
-        memcpy(p_msg->peer_bd_addr, peer_bd_addr, sizeof(BD_ADDR));
-        p_msg->p_cback      = p_cback;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capClose
-**
-** Description      This function closes an L2CAP client connection
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvL2capClose(UINT32 handle)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_L2CAP_CLOSE *p_msg;
-
-    APPL_TRACE_API( "BTA_JvL2capClose");
-    if (handle < BTA_JV_MAX_L2C_CONN && bta_jv_cb.l2c_cb[handle].p_cback &&
-        (p_msg = (tBTA_JV_API_L2CAP_CLOSE *)GKI_getbuf(sizeof(tBTA_JV_API_L2CAP_CLOSE))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_L2CAP_CLOSE_EVT;
-        p_msg->handle = handle;
-        p_msg->p_cb = &bta_jv_cb.l2c_cb[handle];
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capStartServer
-**
-** Description      This function starts an L2CAP server and listens for an L2CAP
-**                  connection from a remote Bluetooth device.  When the server
-**                  is started successfully, tBTA_JV_L2CAP_CBACK is called with
-**                  BTA_JV_L2CAP_START_EVT.  When the connection is established,
-**                  tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_OPEN_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvL2capStartServer(tBTA_SEC sec_mask, tBTA_JV_ROLE role,
-                           UINT16 local_psm, UINT16 rx_mtu,
-                           tBTA_JV_L2CAP_CBACK *p_cback)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_L2CAP_SERVER *p_msg;
-
-    APPL_TRACE_API( "BTA_JvL2capStartServer");
-    if (p_cback &&
-        (p_msg = (tBTA_JV_API_L2CAP_SERVER *)GKI_getbuf(sizeof(tBTA_JV_API_L2CAP_SERVER))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_L2CAP_START_SERVER_EVT;
-        p_msg->sec_mask = sec_mask;
-        p_msg->role = role;
-        p_msg->local_psm = local_psm;
-        p_msg->rx_mtu = rx_mtu;
-        p_msg->p_cback = p_cback;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capStopServer
-**
-** Description      This function stops the L2CAP server. If the server has an
-**                  active connection, it would be closed.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvL2capStopServer(UINT16 local_psm)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_L2CAP_SERVER *p_msg;
-
-    APPL_TRACE_API( "BTA_JvL2capStopServer");
-    if ((p_msg = (tBTA_JV_API_L2CAP_SERVER *)GKI_getbuf(sizeof(tBTA_JV_API_L2CAP_SERVER))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_L2CAP_STOP_SERVER_EVT;
-        p_msg->local_psm = local_psm;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capRead
-**
-** Description      This function reads data from an L2CAP connecti;
-    tBTA_JV_RFC_CB  *p_cb = rc->p_cb;
-on
-**                  When the operation is complete, tBTA_JV_L2CAP_CBACK is
-**                  called with BTA_JV_L2CAP_READ_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvL2capRead(UINT32 handle, UINT32 req_id, UINT8 *p_data, UINT16 len)
-{
-    UNUSED(handle);
-    UNUSED(req_id);
-    UNUSED(p_data);
-    UNUSED(len);
-
-#if 0
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-#if SDP_FOR_JV_INCLUDED == TRUE
-    tBTA_JV_API_L2CAP_READ *p_msg;
-#endif
-    tBTA_JV_L2CAP_READ evt_data;
-
-    APPL_TRACE_API( "BTA_JvL2capRead");
-
-#if SDP_FOR_JV_INCLUDED == TRUE
-    if(BTA_JV_L2C_FOR_SDP_HDL == handle)
-    {
-        if (bta_jv_cb.l2c_cb[handle].p_cback &&
-            (p_msg = (tBTA_JV_API_L2CAP_READ *)GKI_getbuf(sizeof(tBTA_JV_API_L2CAP_READ))) != NULL)
-        {
-            p_msg->hdr.event = BTA_JV_API_L2CAP_READ_EVT;
-            p_msg->handle = handle;
-            p_msg->req_id = req_id;
-            p_msg->p_data = p_data;
-            p_msg->len = len;
-            p_msg->p_cback = bta_jv_cb.l2c_cb[handle].p_cback;
-            bta_sys_sendmsg(p_msg);
-            status = BTA_JV_SUCCESS;
-        }
-    }
-    else
-#endif
-    if (handle < BTA_JV_MAX_L2C_CONN && bta_jv_cb.l2c_cb[handle].p_cback)
-    {
-        status = BTA_JV_SUCCESS;
-        evt_data.status = BTA_JV_FAILURE;
-        evt_data.handle = handle;
-        evt_data.req_id = req_id;
-        evt_data.p_data = p_data;
-        evt_data.len    = 0;
-
-        if (BT_PASS == GAP_ConnReadData((UINT16)handle, p_data, len, &evt_data.len))
-        {
-            evt_data.status = BTA_JV_SUCCESS;
-        }
-        bta_jv_cb.l2c_cb[handle].p_cback(BTA_JV_L2CAP_READ_EVT, (tBTA_JV *)&evt_data);
-    }
-
-    return(status);
-#endif
-    return -1;
-}
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capReceive
-**
-** Description      This function reads data from an L2CAP connection
-**                  When the operation is complete, tBTA_JV_L2CAP_CBACK is
-**                  called with BTA_JV_L2CAP_RECEIVE_EVT.
-**                  If there are more data queued in L2CAP than len, the extra data will be discarded.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvL2capReceive(UINT32 handle, UINT32 req_id, UINT8 *p_data, UINT16 len)
-{
-    UNUSED(handle);
-    UNUSED(req_id);
-    UNUSED(p_data);
-    UNUSED(len);
-#if 0
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_L2CAP_RECEIVE evt_data;
-    UINT32  left_over = 0;
-    UINT16  max_len, read_len;
-
-    APPL_TRACE_API( "BTA_JvL2capReceive");
-
-    if (handle < BTA_JV_MAX_L2C_CONN && bta_jv_cb.l2c_cb[handle].p_cback)
-    {
-        status = BTA_JV_SUCCESS;
-        evt_data.status = BTA_JV_FAILURE;
-        evt_data.handle = handle;
-        evt_data.req_id = req_id;
-        evt_data.p_data = p_data;
-        evt_data.len    = 0;
-
-        if (BT_PASS == GAP_ConnReadData((UINT16)handle, p_data, len, &evt_data.len))
-        {
-            evt_data.status = BTA_JV_SUCCESS;
-            GAP_GetRxQueueCnt ((UINT16)handle, &left_over);
-            while (left_over)
-            {
-                max_len = (left_over > 0xFFFF)?0xFFFF:left_over;
-                GAP_ConnReadData ((UINT16)handle, NULL, max_len, &read_len);
-                left_over -= read_len;
-            }
-        }
-        bta_jv_cb.l2c_cb[handle].p_cback(BTA_JV_L2CAP_RECEIVE_EVT, (tBTA_JV *)&evt_data);
-    }
-
-    return(status);
-#endif
-    return -1;
-}
-/*******************************************************************************
-**
-** Function         BTA_JvL2capReady
-**
-** Description      This function determined if there is data to read from
-**                    an L2CAP connection
-**
-** Returns          BTA_JV_SUCCESS, if data queue size is in *p_data_size.
-**                  BTA_JV_FAILURE, if error.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvL2capReady(UINT32 handle, UINT32 *p_data_size)
-{
-    UNUSED(handle);
-    UNUSED(p_data_size);
-#if 0
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-
-    APPL_TRACE_API( "BTA_JvL2capReady: %d", handle);
-    if (p_data_size && handle < BTA_JV_MAX_L2C_CONN && bta_jv_cb.l2c_cb[handle].p_cback)
-    {
-        *p_data_size = 0;
-#if SDP_FOR_JV_INCLUDED == TRUE
-        if(BTA_JV_L2C_FOR_SDP_HDL == handle)
-        {
-            *p_data_size = bta_jv_cb.sdp_data_size;
-            status = BTA_JV_SUCCESS;
-        }
-        else
-#endif
-        if(BT_PASS == GAP_GetRxQueueCnt((UINT16)handle, p_data_size) )
-        {
-            status = BTA_JV_SUCCESS;
-        }
-    }
-
-    return(status);
-#endif
-    return -1;
-}
-
-
-/*******************************************************************************
-**
-** Function         BTA_JvL2capWrite
-**
-** Description      This function writes data to an L2CAP connection
-**                  When the operation is complete, tBTA_JV_L2CAP_CBACK is
-**                  called with BTA_JV_L2CAP_WRITE_EVT.
-**
-** Returns          BTA_JV_SUCCESS, if the request is being processed.
-**                  BTA_JV_FAILURE, otherwise.
-**
-*******************************************************************************/
-tBTA_JV_STATUS BTA_JvL2capWrite(UINT32 handle, UINT32 req_id, UINT8 *p_data, UINT16 len)
-{
-    tBTA_JV_STATUS status = BTA_JV_FAILURE;
-    tBTA_JV_API_L2CAP_WRITE *p_msg;
-
-    APPL_TRACE_API( "BTA_JvL2capWrite");
-    if (handle < BTA_JV_MAX_L2C_CONN && bta_jv_cb.l2c_cb[handle].p_cback &&
-        (p_msg = (tBTA_JV_API_L2CAP_WRITE *)GKI_getbuf(sizeof(tBTA_JV_API_L2CAP_WRITE))) != NULL)
-    {
-        p_msg->hdr.event = BTA_JV_API_L2CAP_WRITE_EVT;
-        p_msg->handle = handle;
-        p_msg->req_id = req_id;
-        p_msg->p_data = p_data;
-        p_msg->p_cb = &bta_jv_cb.l2c_cb[handle];
-        p_msg->len = len;
-        bta_sys_sendmsg(p_msg);
-        status = BTA_JV_SUCCESS;
-    }
-
-    return(status);
-}
-
-/*******************************************************************************
-**
 ** Function         BTA_JvRfcommConnect
 **
 ** Description      This function makes an RFCOMM conection to a remote BD
diff --git a/bta/jv/bta_jv_cfg.c b/bta/jv/bta_jv_cfg.c
index 21bd2a8..26671ea 100644
--- a/bta/jv/bta_jv_cfg.c
+++ b/bta/jv/bta_jv_cfg.c
@@ -26,7 +26,6 @@
 
 #include "gki.h"
 #include "bta_api.h"
-#include "bd.h"
 #include "bta_jv_api.h"
 
 #ifndef BTA_JV_SDP_DB_SIZE
diff --git a/bta/jv/bta_jv_int.h b/bta/jv/bta_jv_int.h
index 436c0a5..a766647 100644
--- a/bta/jv/bta_jv_int.h
+++ b/bta/jv/bta_jv_int.h
@@ -39,29 +39,9 @@
     /* these events are handled by the state machine */
     BTA_JV_API_ENABLE_EVT = BTA_SYS_EVT_START(BTA_ID_JV),
     BTA_JV_API_DISABLE_EVT,
-    BTA_JV_API_SET_DISCOVERABILITY_EVT,
-    BTA_JV_API_GET_LOCAL_DEVICE_ADDR_EVT,
-    BTA_JV_API_GET_LOCAL_DEVICE_NAME_EVT,
-    BTA_JV_API_GET_REMOTE_DEVICE_NAME_EVT,
-    BTA_JV_API_SET_SERVICE_CLASS_EVT,
-    BTA_JV_API_SET_ENCRYPTION_EVT,
-    BTA_JV_API_GET_SCN_EVT,
-    BTA_JV_API_FREE_SCN_EVT,
     BTA_JV_API_START_DISCOVERY_EVT,
-    BTA_JV_API_CANCEL_DISCOVERY_EVT,
-    BTA_JV_API_GET_SERVICES_LENGTH_EVT,
-    BTA_JV_API_SERVICE_SELECT_EVT,
     BTA_JV_API_CREATE_RECORD_EVT,
-    BTA_JV_API_UPDATE_RECORD_EVT,
-    BTA_JV_API_ADD_ATTRIBUTE_EVT,
-    BTA_JV_API_DELETE_ATTRIBUTE_EVT,
     BTA_JV_API_DELETE_RECORD_EVT,
-    BTA_JV_API_L2CAP_CONNECT_EVT,
-    BTA_JV_API_L2CAP_CLOSE_EVT,
-    BTA_JV_API_L2CAP_START_SERVER_EVT,
-    BTA_JV_API_L2CAP_STOP_SERVER_EVT,
-    BTA_JV_API_L2CAP_READ_EVT,
-    BTA_JV_API_L2CAP_WRITE_EVT,
     BTA_JV_API_RFCOMM_CONNECT_EVT,
     BTA_JV_API_RFCOMM_CLOSE_EVT,
     BTA_JV_API_RFCOMM_START_SERVER_EVT,
@@ -84,35 +64,6 @@
     tBTA_JV_DM_CBACK   *p_cback;
 } tBTA_JV_API_ENABLE;
 
-/* data type for BTA_JV_API_SET_DISCOVERABILITY_EVT */
-typedef struct
-{
-    BT_HDR              hdr;
-    tBTA_JV_DISC    disc_mode;
-} tBTA_JV_API_SET_DISCOVERABILITY;
-
-
-/* data type for BTA_JV_API_SET_SERVICE_CLASS_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    UINT32      service;
-} tBTA_JV_API_SET_SERVICE_CLASS;
-
-/* data type for BTA_JV_API_SET_ENCRYPTION_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    BD_ADDR     bd_addr;
-} tBTA_JV_API_SET_ENCRYPTION;
-
-/* data type for BTA_JV_API_GET_REMOTE_DEVICE_NAME_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    BD_ADDR     bd_addr;
-} tBTA_JV_API_GET_REMOTE_NAME;
-
 /* data type for BTA_JV_API_START_DISCOVERY_EVT */
 typedef struct
 {
@@ -125,36 +76,6 @@
     void            *user_data;      /* piggyback caller's private data*/
 } tBTA_JV_API_START_DISCOVERY;
 
-/* data type for BTA_JV_API_CANCEL_DISCOVERY_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    void        *user_data;      /* piggyback caller's private data*/
-} tBTA_JV_API_CANCEL_DISCOVERY;
-
-
-/* data type for BTA_JV_API_GET_SERVICES_LENGTH_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    UINT16      *p_services_len;
-    BOOLEAN     inc_hdr;
-} tBTA_JV_API_GET_SERVICES_LENGTH;
-
-/* data type for BTA_JV_API_GET_SERVICE_RESULT_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    UINT8        **TLVs;
-} tBTA_JV_API_GET_SERVICE_RESULT;
-
-/* data type for BTA_JV_API_SERVICE_SELECT_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    UINT16        uuid;
-} tBTA_JV_API_SERVICE_SELECT;
-
 enum
 {
     BTA_JV_PM_FREE_ST = 0, /* empty PM slot */
@@ -184,18 +105,6 @@
 typedef UINT8  tBTA_JV_STATE;
 #define BTA_JV_ST_CL_MAX    BTA_JV_ST_CL_CLOSING
 
-/* JV L2CAP control block */
-typedef struct
-{
-    tBTA_JV_L2CAP_CBACK *p_cback;   /* the callback function */
-    UINT16              psm;        /* the psm used for this server connection */
-    tBTA_JV_STATE       state;      /* the state of this control block */
-    tBTA_SERVICE_ID     sec_id;     /* service id */
-    UINT32              handle;     /* the handle reported to java app (same as gap handle) */
-    BOOLEAN             cong;       /* TRUE, if congested */
-    tBTA_JV_PM_CB      *p_pm_cb;    /* ptr to pm control block, NULL: unused */
-} tBTA_JV_L2C_CB;
-
 #define BTA_JV_RFC_HDL_MASK         0xFF
 #define BTA_JV_RFCOMM_MASK          0x80
 #define BTA_JV_ALL_APP_ID           0xFF
@@ -226,59 +135,6 @@
     int                 curr_sess;   /* current sessions count*/
 } tBTA_JV_RFC_CB;
 
-/* data type for BTA_JV_API_L2CAP_CONNECT_EVT */
-typedef struct
-{
-    BT_HDR          hdr;
-    tBTA_SEC        sec_mask;
-    tBTA_JV_ROLE    role;
-    UINT16          remote_psm;
-    UINT16          rx_mtu;
-    BD_ADDR         peer_bd_addr;
-    tBTA_JV_L2CAP_CBACK *p_cback;
-} tBTA_JV_API_L2CAP_CONNECT;
-
-/* data type for BTA_JV_API_L2CAP_SERVER_EVT */
-typedef struct
-{
-    BT_HDR              hdr;
-    tBTA_SEC            sec_mask;
-    tBTA_JV_ROLE        role;
-    UINT16              local_psm;
-    UINT16              rx_mtu;
-    tBTA_JV_L2CAP_CBACK *p_cback;
-} tBTA_JV_API_L2CAP_SERVER;
-
-/* data type for BTA_JV_API_L2CAP_CLOSE_EVT */
-typedef struct
-{
-    BT_HDR          hdr;
-    UINT32          handle;
-    tBTA_JV_L2C_CB  *p_cb;
-} tBTA_JV_API_L2CAP_CLOSE;
-
-/* data type for BTA_JV_API_L2CAP_READ_EVT */
-typedef struct
-{
-    BT_HDR              hdr;
-    UINT32              handle;
-    UINT32              req_id;
-    tBTA_JV_L2CAP_CBACK *p_cback;
-    UINT8*              p_data;
-    UINT16              len;
-} tBTA_JV_API_L2CAP_READ;
-
-/* data type for BTA_JV_API_L2CAP_WRITE_EVT */
-typedef struct
-{
-    BT_HDR              hdr;
-    UINT32              handle;
-    UINT32              req_id;
-    tBTA_JV_L2C_CB      *p_cb;
-    UINT8               *p_data;
-    UINT16              len;
-} tBTA_JV_API_L2CAP_WRITE;
-
 /* data type for BTA_JV_API_RFCOMM_CONNECT_EVT */
 typedef struct
 {
@@ -362,17 +218,6 @@
     void        *user_data;
 } tBTA_JV_API_CREATE_RECORD;
 
-/* data type for BTA_JV_API_UPDATE_RECORD_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    UINT32      handle;
-    UINT16      *p_ids;
-    UINT8       **p_values;
-    INT32       *p_value_sizes;
-    INT32       array_len;
-} tBTA_JV_API_UPDATE_RECORD;
-
 /* data type for BTA_JV_API_ADD_ATTRIBUTE_EVT */
 typedef struct
 {
@@ -383,36 +228,15 @@
     INT32       value_size;
 } tBTA_JV_API_ADD_ATTRIBUTE;
 
-/* data type for BTA_JV_API_FREE_SCN_EVT */
-typedef struct
-{
-    BT_HDR      hdr;
-    UINT8       scn;
-} tBTA_JV_API_FREE_SCN;
 /* union of all data types */
 typedef union
 {
     /* GKI event buffer header */
     BT_HDR                          hdr;
     tBTA_JV_API_ENABLE              enable;
-    tBTA_JV_API_SET_DISCOVERABILITY set_discoverability;
-    tBTA_JV_API_GET_REMOTE_NAME     get_rmt_name;
-    tBTA_JV_API_SET_SERVICE_CLASS   set_service;
-    tBTA_JV_API_SET_ENCRYPTION      set_encrypt;
     tBTA_JV_API_START_DISCOVERY     start_discovery;
-    tBTA_JV_API_CANCEL_DISCOVERY    cancel_discovery;
-    tBTA_JV_API_GET_SERVICES_LENGTH get_services_length;
-    tBTA_JV_API_GET_SERVICE_RESULT  get_service_result;
-    tBTA_JV_API_SERVICE_SELECT      service_select;
-    tBTA_JV_API_FREE_SCN            free_scn;
     tBTA_JV_API_CREATE_RECORD       create_record;
-    tBTA_JV_API_UPDATE_RECORD       update_record;
     tBTA_JV_API_ADD_ATTRIBUTE       add_attr;
-    tBTA_JV_API_L2CAP_CONNECT       l2cap_connect;
-    tBTA_JV_API_L2CAP_READ          l2cap_read;
-    tBTA_JV_API_L2CAP_WRITE         l2cap_write;
-    tBTA_JV_API_L2CAP_CLOSE         l2cap_close;
-    tBTA_JV_API_L2CAP_SERVER        l2cap_server;
     tBTA_JV_API_RFCOMM_CONNECT      rfcomm_connect;
     tBTA_JV_API_RFCOMM_READ         rfcomm_read;
     tBTA_JV_API_RFCOMM_WRITE        rfcomm_write;
@@ -422,32 +246,20 @@
     tBTA_JV_API_RFCOMM_SERVER       rfcomm_server;
 } tBTA_JV_MSG;
 
-#if SDP_FOR_JV_INCLUDED == TRUE
-#define BTA_JV_L2C_FOR_SDP_HDL     GAP_MAX_CONNECTIONS
-#endif
-
 /* JV control block */
 typedef struct
 {
-#if SDP_FOR_JV_INCLUDED == TRUE
-    UINT32                  sdp_for_jv;     /* The SDP client connection handle */
-    UINT32                  sdp_data_size;  /* the data len */
-#endif
     /* the SDP handle reported to JV user is the (index + 1) to sdp_handle[].
      * if sdp_handle[i]==0, it's not used.
      * otherwise sdp_handle[i] is the stack SDP handle. */
     UINT32                  sdp_handle[BTA_JV_MAX_SDP_REC]; /* SDP records created */
     UINT8                   *p_sel_raw_data;/* the raw data of last service select */
-    INT32                   sel_len;        /* the SDP record size of last service select */
     tBTA_JV_DM_CBACK        *p_dm_cback;
-    tBTA_JV_L2C_CB          l2c_cb[BTA_JV_MAX_L2C_CONN];    /* index is GAP handle (index) */
     tBTA_JV_RFC_CB          rfc_cb[BTA_JV_MAX_RFC_CONN];
     tBTA_JV_PCB             port_cb[MAX_RFC_PORTS];         /* index of this array is the port_handle, */
     UINT8                   sec_id[BTA_JV_NUM_SERVICE_ID];  /* service ID */
-    BOOLEAN                 scn[BTA_JV_MAX_SCN];            /* SCN allocated by java */
     UINT8                   sdp_active;                     /* see BTA_JV_SDP_ACT_* */
     tSDP_UUID               uuid;                           /* current uuid of sdp discovery*/
-    void                    *user_data;                     /* piggyback user data*/
     tBTA_JV_PM_CB           pm_cb[BTA_JV_PM_MAX_NUM];       /* PM on a per JV handle bases */
 } tBTA_JV_CB;
 
@@ -469,37 +281,13 @@
 /* config struct */
 extern tBTA_JV_CFG *p_bta_jv_cfg;
 
-/* this is defined in stack/sdp. used by bta jv */
-extern UINT8 *sdpu_get_len_from_type (UINT8 *p, UINT8 type, UINT32 *p_len);
-
 extern BOOLEAN bta_jv_sm_execute(BT_HDR *p_msg);
 
-extern UINT32 bta_jv_get_sdp_handle(UINT32 sdp_id);
 extern void bta_jv_enable (tBTA_JV_MSG *p_data);
 extern void bta_jv_disable (tBTA_JV_MSG *p_data);
-extern void bta_jv_set_discoverability (tBTA_JV_MSG *p_data);
-extern void bta_jv_get_local_device_addr (tBTA_JV_MSG *p_data);
-extern void bta_jv_get_local_device_name (tBTA_JV_MSG *p_data);
-extern void bta_jv_get_remote_device_name (tBTA_JV_MSG *p_data);
-extern void bta_jv_set_service_class (tBTA_JV_MSG *p_data);
-extern void bta_jv_set_encryption (tBTA_JV_MSG *p_data);
-extern void bta_jv_get_scn (tBTA_JV_MSG *p_data);
-extern void bta_jv_free_scn (tBTA_JV_MSG *p_data);
 extern void bta_jv_start_discovery (tBTA_JV_MSG *p_data);
-extern void bta_jv_cancel_discovery (tBTA_JV_MSG *p_data);
-extern void bta_jv_get_services_length (tBTA_JV_MSG *p_data);
-extern void bta_jv_service_select (tBTA_JV_MSG *p_data);
 extern void bta_jv_create_record (tBTA_JV_MSG *p_data);
-extern void bta_jv_update_record (tBTA_JV_MSG *p_data);
-extern void bta_jv_add_attribute (tBTA_JV_MSG *p_data);
-extern void bta_jv_delete_attribute (tBTA_JV_MSG *p_data);
 extern void bta_jv_delete_record (tBTA_JV_MSG *p_data);
-extern void bta_jv_l2cap_connect (tBTA_JV_MSG *p_data);
-extern void bta_jv_l2cap_close (tBTA_JV_MSG *p_data);
-extern void bta_jv_l2cap_start_server (tBTA_JV_MSG *p_data);
-extern void bta_jv_l2cap_stop_server (tBTA_JV_MSG *p_data);
-extern void bta_jv_l2cap_read (tBTA_JV_MSG *p_data);
-extern void bta_jv_l2cap_write (tBTA_JV_MSG *p_data);
 extern void bta_jv_rfcomm_connect (tBTA_JV_MSG *p_data);
 extern void bta_jv_rfcomm_close (tBTA_JV_MSG *p_data);
 extern void bta_jv_rfcomm_start_server (tBTA_JV_MSG *p_data);
diff --git a/bta/jv/bta_jv_main.c b/bta/jv/bta_jv_main.c
index 686ff17..97e2b81 100644
--- a/bta/jv/bta_jv_main.c
+++ b/bta/jv/bta_jv_main.c
@@ -46,29 +46,9 @@
 {
     bta_jv_enable,                  /* BTA_JV_API_ENABLE_EVT */
     bta_jv_disable,                 /* BTA_JV_API_DISABLE_EVT */
-    bta_jv_set_discoverability,     /* BTA_JV_API_SET_DISCOVERABILITY_EVT */
-    bta_jv_get_local_device_addr,   /* BTA_JV_API_GET_LOCAL_DEVICE_ADDR_EVT */
-    bta_jv_get_local_device_name,   /* BTA_JV_API_GET_LOCAL_DEVICE_NAME_EVT */
-    bta_jv_get_remote_device_name,  /* BTA_JV_API_GET_REMOTE_DEVICE_NAME_EVT */
-    bta_jv_set_service_class,       /* BTA_JV_API_SET_SERVICE_CLASS_EVT */
-    bta_jv_set_encryption,          /* BTA_JV_API_SET_ENCRYPTION_EVT */
-    bta_jv_get_scn,                 /* BTA_JV_API_GET_SCN_EVT */
-    bta_jv_free_scn,                /* BTA_JV_API_FREE_SCN_EVT */
     bta_jv_start_discovery,         /* BTA_JV_API_START_DISCOVERY_EVT */
-    bta_jv_cancel_discovery,        /* BTA_JV_API_CANCEL_DISCOVERY_EVT */
-    bta_jv_get_services_length,     /* BTA_JV_API_GET_SERVICES_LENGTH_EVT */
-    bta_jv_service_select,          /* BTA_JV_API_SERVICE_SELECT_EVT */
     bta_jv_create_record,           /* BTA_JV_API_CREATE_RECORD_EVT */
-    bta_jv_update_record,           /* BTA_JV_API_UPDATE_RECORD_EVT */
-    bta_jv_add_attribute,           /* BTA_JV_API_ADD_ATTRIBUTE_EVT */
-    bta_jv_delete_attribute,        /* BTA_JV_API_DELETE_ATTRIBUTE_EVT */
     bta_jv_delete_record,           /* BTA_JV_API_DELETE_RECORD_EVT */
-    bta_jv_l2cap_connect,           /* BTA_JV_API_L2CAP_CONNECT_EVT */
-    bta_jv_l2cap_close,             /* BTA_JV_API_L2CAP_CLOSE_EVT */
-    bta_jv_l2cap_start_server,      /* BTA_JV_API_L2CAP_START_SERVER_EVT */
-    bta_jv_l2cap_stop_server,       /* BTA_JV_API_L2CAP_STOP_SERVER_EVT */
-    bta_jv_l2cap_read,              /* BTA_JV_API_L2CAP_READ_EVT */
-    bta_jv_l2cap_write,             /* BTA_JV_API_L2CAP_WRITE_EVT */
     bta_jv_rfcomm_connect,          /* BTA_JV_API_RFCOMM_CONNECT_EVT */
     bta_jv_rfcomm_close,            /* BTA_JV_API_RFCOMM_CLOSE_EVT */
     bta_jv_rfcomm_start_server,     /* BTA_JV_API_RFCOMM_START_SERVER_EVT */
diff --git a/bta/mce/bta_mce_act.c b/bta/mce/bta_mce_act.c
index 652254f..fcd014c 100644
--- a/bta/mce/bta_mce_act.c
+++ b/bta/mce/bta_mce_act.c
@@ -28,7 +28,6 @@
 
 #include "bt_types.h"
 #include "gki.h"
-#include "bd.h"
 #include "utl.h"
 #include "bta_sys.h"
 #include "bta_api.h"
diff --git a/bta/mce/bta_mce_api.c b/bta/mce/bta_mce_api.c
index ff2713c..dfb3c5c 100644
--- a/bta/mce/bta_mce_api.c
+++ b/bta/mce/bta_mce_api.c
@@ -24,7 +24,7 @@
  ******************************************************************************/
 
 #include "bta_api.h"
-#include "bd.h"
+#include "bt_types.h"
 #include "bta_sys.h"
 #include "bta_mce_api.h"
 #include "bta_mce_int.h"
diff --git a/bta/mce/bta_mce_cfg.c b/bta/mce/bta_mce_cfg.c
index db9fe66..931dab5 100644
--- a/bta/mce/bta_mce_cfg.c
+++ b/bta/mce/bta_mce_cfg.c
@@ -25,7 +25,7 @@
 
 #include "gki.h"
 #include "bta_api.h"
-#include "bd.h"
+#include "bt_types.h"
 #include "bta_mce_api.h"
 
 #ifndef BTA_MCE_SDP_DB_SIZE
diff --git a/bta/pan/bta_pan_act.c b/bta/pan/bta_pan_act.c
index ca3567c..ef7bee7 100644
--- a/bta/pan/bta_pan_act.c
+++ b/bta/pan/bta_pan_act.c
@@ -28,7 +28,6 @@
 
 #include "bta_api.h"
 #include "bta_sys.h"
-#include "bd.h"
 #include "gki.h"
 #include "pan_api.h"
 #include "bta_pan_api.h"
@@ -430,11 +429,11 @@
     /* close all connections */
     PAN_SetRole (0, NULL, NULL, NULL, NULL);
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&(BTA_EIR_CANNED_UUID_LIST != TRUE)
+#if (BTA_EIR_CANNED_UUID_LIST != TRUE)
     bta_sys_remove_uuid(UUID_SERVCLASS_NAP);
     bta_sys_remove_uuid(UUID_SERVCLASS_GN);
     bta_sys_remove_uuid(UUID_SERVCLASS_PANU);
-#endif
+#endif // BTA_EIR_CANNED_UUID_LIST
     /* free all queued up data buffers */
     for (i = 0; i < BTA_PAN_NUM_CONN; i++, p_scb++)
     {
@@ -665,7 +664,7 @@
         bta_pan_co_tx_path(p_scb->handle, p_scb->app_id);
 
         /* free data that exceeds queue level */
-        while(p_scb->data_queue.count > bta_pan_cb.q_level)
+        while(GKI_queue_length(&p_scb->data_queue) > bta_pan_cb.q_level)
             GKI_freebuf(GKI_dequeue(&p_scb->data_queue));
         bta_pan_pm_conn_idle(p_scb);
     }
@@ -690,12 +689,12 @@
 
             }
             /* free data that exceeds queue level  */
-            while(p_scb->data_queue.count > bta_pan_cb.q_level)
+            while(GKI_queue_length(&p_scb->data_queue) > bta_pan_cb.q_level)
                 GKI_freebuf(GKI_dequeue(&p_scb->data_queue));
 
             /* if there is more data to be passed to
             upper layer */
-            if(p_scb->data_queue.count)
+            if(!GKI_queue_is_empty(&p_scb->data_queue))
             {
                 if ((p_buf = (BT_HDR *) GKI_getbuf(sizeof(BT_HDR))) != NULL)
                 {
diff --git a/bta/pan/bta_pan_api.c b/bta/pan/bta_pan_api.c
index 0a69b0f..b273e95 100644
--- a/bta/pan/bta_pan_api.c
+++ b/bta/pan/bta_pan_api.c
@@ -31,7 +31,6 @@
 #include "gki.h"
 #include "bta_pan_api.h"
 #include "bta_pan_int.h"
-#include "bd.h"
 #include <string.h>
 #include "bt_utils.h"
 
@@ -173,7 +172,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_PanOpen(BD_ADDR bd_addr, tBTA_PAN_ROLE    local_role, tBTA_PAN_ROLE    peer_role)
+void BTA_PanOpen(BD_ADDR bd_addr, tBTA_PAN_ROLE    local_role, tBTA_PAN_ROLE    peer_role)
 {
 
     tBTA_PAN_API_OPEN  *p_buf;
@@ -199,7 +198,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void BTA_PanClose(UINT16 handle)
+void BTA_PanClose(UINT16 handle)
 {
     BT_HDR  *p_buf;
 
diff --git a/bta/pan/bta_pan_ci.c b/bta/pan/bta_pan_ci.c
index 7e67477..653c643 100644
--- a/bta/pan/bta_pan_ci.c
+++ b/bta/pan/bta_pan_ci.c
@@ -28,7 +28,6 @@
 
 #include "gki.h"
 #include "pan_api.h"
-#include "bd.h"
 #include "bta_api.h"
 #include "bta_pan_api.h"
 #include "bta_pan_ci.h"
diff --git a/bta/pan/bta_pan_main.c b/bta/pan/bta_pan_main.c
index 3a69994..2228870 100644
--- a/bta/pan/bta_pan_main.c
+++ b/bta/pan/bta_pan_main.c
@@ -33,7 +33,6 @@
 #include "pan_api.h"
 #include "bta_pan_api.h"
 #include "bta_pan_int.h"
-#include "bd.h"
 #include "utl.h"
 
 /*****************************************************************************
diff --git a/bta/pb/bta_pbs_cfg.c b/bta/pb/bta_pbs_cfg.c
deleted file mode 100644
index b2782fb..0000000
--- a/bta/pb/bta_pbs_cfg.c
+++ /dev/null
@@ -1,51 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains compile-time configurable constants for the BTA Phone
- *  Book Access Server.
- *
- ******************************************************************************/
-
-#include "bt_target.h"
-
-#if defined(BTA_PBS_INCLUDED) && (BTA_PBS_INCLUDED == TRUE)
-
-#include "bta_pbs_int.h"
-
-/* Realm Character Set */
-#ifndef BTA_PBS_REALM_CHARSET
-#define BTA_PBS_REALM_CHARSET   0       /* ASCII */
-#endif
-
-/* Specifies whether or not client's user id is required during obex authentication */
-#ifndef BTA_PBS_USERID_REQ
-#define BTA_PBS_USERID_REQ      FALSE
-#endif
-
-const tBTA_PBS_CFG bta_pbs_cfg =
-{
-    BTA_PBS_REALM_CHARSET,      /* Server only */
-    BTA_PBS_USERID_REQ,         /* Server only */
-    (BTA_PBS_SUPF_DOWNLOAD | BTA_PBS_SURF_BROWSE),
-    BTA_PBS_REPOSIT_LOCAL,
-};
-
-tBTA_PBS_CFG *p_bta_pbs_cfg = (tBTA_PBS_CFG *)&bta_pbs_cfg;
-#endif /* BTA_PBS_INCLUDED */
diff --git a/bta/pb/bta_pbs_int.h b/bta/pb/bta_pbs_int.h
index a4fce2b..fb78842 100644
--- a/bta/pb/bta_pbs_int.h
+++ b/bta/pb/bta_pbs_int.h
@@ -25,12 +25,20 @@
 #define BTA_PBS_INT_H
 
 #include "bt_target.h"
-#include "bta_pbs_api.h"
+#include "bta_sys.h"
 
 /*****************************************************************************
 **  Constants and data types
 *****************************************************************************/
 
+/* Profile supported features */
+#define BTA_PBS_SUPF_DOWNLOAD     0x0001
+#define BTA_PBS_SURF_BROWSE       0x0002
+
+/* Profile supported repositories */
+#define BTA_PBS_REPOSIT_LOCAL      0x01    /* Local PhoneBook */
+#define BTA_PBS_REPOSIT_SIM        0x02    /* SIM card PhoneBook */
+
 #define BTA_PBS_TARGET_UUID "\x79\x61\x35\xf0\xf0\xc5\x11\xd8\x09\x66\x08\x00\x20\x0c\x9a\x66"
 #define BTA_PBS_UUID_LENGTH                 16
 #define BTA_PBS_MAX_AUTH_KEY_SIZE           16  /* Must not be greater than OBX_MAX_AUTH_KEY_SIZE */
@@ -48,10 +56,4 @@
 
 } tBTA_PBS_CFG;
 
-
-/*****************************************************************************
-**  Global data
-*****************************************************************************/
-
-
 #endif /* BTA_PBS_INT_H */
diff --git a/bta/sys/bd.c b/bta/sys/bd.c
deleted file mode 100644
index 052f9b9..0000000
--- a/bta/sys/bd.c
+++ /dev/null
@@ -1,112 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  BD address services.
- *
- ******************************************************************************/
-
-#include "data_types.h"
-#include "bd.h"
-
-/*****************************************************************************
-**  Constants
-*****************************************************************************/
-
-/* global constant for "any" bd addr */
-const BD_ADDR bd_addr_any = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
-const BD_ADDR bd_addr_null= {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-
-/*****************************************************************************
-**  Functions
-*****************************************************************************/
-
-/*******************************************************************************
-**
-** Function         bdcpy
-**
-** Description      Copy bd addr b to a.
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void bdcpy(BD_ADDR a, const BD_ADDR b)
-{
-    int i;
-
-    for (i = BD_ADDR_LEN; i != 0; i--)
-    {
-        *a++ = *b++;
-    }
-}
-
-/*******************************************************************************
-**
-** Function         bdcmp
-**
-** Description      Compare bd addr b to a.
-**
-**
-** Returns          Zero if b==a, nonzero otherwise (like memcmp).
-**
-*******************************************************************************/
-int bdcmp(const BD_ADDR a, const BD_ADDR b)
-{
-    int i;
-
-    for (i = BD_ADDR_LEN; i != 0; i--)
-    {
-        if (*a++ != *b++)
-        {
-            return -1;
-        }
-    }
-    return 0;
-}
-
-/*******************************************************************************
-**
-** Function         bdcmpany
-**
-** Description      Compare bd addr to "any" bd addr.
-**
-**
-** Returns          Zero if a equals bd_addr_any.
-**
-*******************************************************************************/
-int bdcmpany(const BD_ADDR a)
-{
-    return bdcmp(a, bd_addr_any);
-}
-
-/*******************************************************************************
-**
-** Function         bdsetany
-**
-** Description      Set bd addr to "any" bd addr.
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void bdsetany(BD_ADDR a)
-{
-    bdcpy(a, bd_addr_any);
-}
diff --git a/bta/sys/bta_sys.h b/bta/sys/bta_sys.h
index 7b60b1f..f42ee0a 100644
--- a/bta/sys/bta_sys.h
+++ b/bta/sys/bta_sys.h
@@ -45,11 +45,6 @@
 enum
 {
     BTA_SYS_HW_BLUETOOTH,
-    BTA_SYS_HW_FMRX,
-    BTA_SYS_HW_FMTX,
-    BTA_SYS_HW_GPS,
-    BTA_SYS_HW_SENSOR,
-    BTA_SYS_HW_NFC,
     BTA_SYS_HW_RT,
 
     BTA_SYS_MAX_HW_MODULES
@@ -98,16 +93,6 @@
 #define BTA_ID_GATTS        32           /* GATT Client */
 #define BTA_ID_BLUETOOTH_MAX   33        /* last BT profile */
 
-/* FM */
-#define BTA_ID_FM           34           /* FM  */
-#define BTA_ID_FMTX         35           /* FM TX */
-
-/* SENSOR */
-#define BTA_ID_SSR          36           /* Sensor  */
-
-/* GPS */
-#define BTA_ID_GPS          37           /* GPS  */
-
 /* GENERIC */
 #define BTA_ID_PRM          38
 #define BTA_ID_SYSTEM       39           /* platform-specific */
@@ -156,7 +141,7 @@
 /* conn callback for role / low power manager*/
 typedef void (tBTA_SYS_SSR_CFG_CBACK)(UINT8 id, UINT8 app_id, UINT16 latency, UINT16 tout);
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&(BTA_EIR_CANNED_UUID_LIST != TRUE)
+#if (BTA_EIR_CANNED_UUID_LIST != TRUE)
 /* eir callback for adding/removeing UUID */
 typedef void (tBTA_SYS_EIR_CBACK)(UINT16 uuid16, BOOLEAN adding);
 #endif
@@ -168,15 +153,6 @@
     tBTA_SYS_DISABLE    *disable;
 } tBTA_SYS_REG;
 
-/* system manager configuration structure */
-typedef struct
-{
-    UINT16          mbox_evt;                       /* GKI mailbox event */
-    UINT8           mbox;                           /* GKI mailbox id */
-    UINT8           timer;                          /* GKI timer id */
-    UINT8           trace_level;                    /* initial trace level */
-} tBTA_SYS_CFG;
-
 /* data type to send events to BTA SYS HW manager */
 typedef struct
 {
@@ -184,8 +160,6 @@
     tBTA_SYS_HW_MODULE   hw_module;
 } tBTA_SYS_HW_MSG;
 
-
-
 /*****************************************************************************
 **  Global data
 *****************************************************************************/
@@ -243,17 +217,16 @@
 extern "C" {
 #endif
 
-BTA_API extern void bta_sys_init(void);
-BTA_API extern void bta_sys_event(BT_HDR *p_msg);
-BTA_API extern void bta_sys_timer_update(void);
-BTA_API extern void bta_sys_disable_timers(void);
-BTA_API extern void bta_sys_set_trace_level(UINT8 level);
+extern void bta_sys_init(void);
+extern void bta_sys_free(void);
+extern void bta_sys_event(BT_HDR *p_msg);
+extern void bta_sys_set_trace_level(UINT8 level);
 extern void bta_sys_register(UINT8 id, const tBTA_SYS_REG *p_reg);
 extern void bta_sys_deregister(UINT8 id);
 extern BOOLEAN bta_sys_is_register(UINT8 id);
 extern UINT16 bta_sys_get_sys_features(void);
 extern void bta_sys_sendmsg(void *p_msg);
-extern void bta_sys_start_timer(TIMER_LIST_ENT *p_tle, UINT16 type, INT32 timeout);
+extern void bta_sys_start_timer(TIMER_LIST_ENT *p_tle, UINT16 type, INT32 timeout_ms);
 extern void bta_sys_stop_timer(TIMER_LIST_ENT *p_tle);
 extern void bta_sys_disable(tBTA_SYS_HW_MODULE module);
 
@@ -289,7 +262,7 @@
 extern void bta_sys_collision_register(UINT8 bta_id, tBTA_SYS_CONN_CBACK *p_cback);
 extern void bta_sys_notify_collision (BD_ADDR_PTR p_bda);
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&(BTA_EIR_CANNED_UUID_LIST != TRUE)
+#if (BTA_EIR_CANNED_UUID_LIST != TRUE)
 extern void bta_sys_eir_register(tBTA_SYS_EIR_CBACK * p_cback);
 extern void bta_sys_add_uuid(UINT16 uuid16);
 extern void bta_sys_remove_uuid(UINT16 uuid16);
diff --git a/bta/sys/bta_sys_cfg.c b/bta/sys/bta_sys_cfg.c
deleted file mode 100644
index bcc7e40..0000000
--- a/bta/sys/bta_sys_cfg.c
+++ /dev/null
@@ -1,55 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains compile-time configurable constants for the BTA
- *  system manager.
- *
- ******************************************************************************/
-
-#include "bt_target.h"
-#include "gki.h"
-#include "bta_sys.h"
-
-/* GKI task mailbox event for BTA. */
-#ifndef BTA_MBOX_EVT
-#define BTA_MBOX_EVT                TASK_MBOX_2_EVT_MASK
-#endif
-
-/* GKI task mailbox for BTA. */
-#ifndef BTA_MBOX
-#define BTA_MBOX                    TASK_MBOX_2
-#endif
-
-/* GKI timer id used for protocol timer for BTA. */
-#ifndef BTA_TIMER
-#define BTA_TIMER                   TIMER_1
-#endif
-
-const tBTA_SYS_CFG bta_sys_cfg =
-{
-    BTA_MBOX_EVT,               /* GKI mailbox event */
-    BTA_MBOX,                   /* GKI mailbox id */
-    BTA_TIMER,                  /* GKI timer id */
-    APPL_INITIAL_TRACE_LEVEL    /* initial trace level */
-};
-
-tBTA_SYS_CFG *p_bta_sys_cfg = (tBTA_SYS_CFG *)&bta_sys_cfg;
-
-
diff --git a/bta/sys/bta_sys_ci.c b/bta/sys/bta_sys_ci.c
deleted file mode 100644
index a30763c..0000000
--- a/bta/sys/bta_sys_ci.c
+++ /dev/null
@@ -1,79 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2010-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This is the implementation file for BTA system call-in functions.
- *
- ******************************************************************************/
-
-#include <stddef.h>
-
-#include "bta_sys.h"
-#include "bta_sys_ci.h"
-
-
-/*******************************************************************************
-**
-** Function         bta_sys_hw_ci_enabled
-**
-** Description      This function must be called in response to function
-**                  bta_sys_hw_enable_co(), when HW is indeed enabled
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-  void bta_sys_hw_ci_enabled(tBTA_SYS_HW_MODULE module )
-
-{
-    tBTA_SYS_HW_MSG *p_msg;
-
-    if ((p_msg = (tBTA_SYS_HW_MSG *) GKI_getbuf(sizeof(tBTA_SYS_HW_MSG))) != NULL)
-    {
-        p_msg->hdr.event = BTA_SYS_EVT_ENABLED_EVT;
-        p_msg->hw_module = module;
-
-        bta_sys_sendmsg(p_msg);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         bta_sys_hw_ci_disabled
-**
-** Description      This function must be called in response to function
-**                  bta_sys_hw_disable_co() when HW is really OFF
-**
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_sys_hw_ci_disabled( tBTA_SYS_HW_MODULE module  )
-{
-    tBTA_SYS_HW_MSG *p_msg;
-
-    if ((p_msg = (tBTA_SYS_HW_MSG *) GKI_getbuf(sizeof(tBTA_SYS_HW_MSG))) != NULL)
-    {
-        p_msg->hdr.event = BTA_SYS_EVT_DISABLED_EVT;
-        p_msg->hw_module = module;
-
-        bta_sys_sendmsg(p_msg);
-    }
-}
-
diff --git a/bta/sys/bta_sys_conn.c b/bta/sys/bta_sys_conn.c
index c58b001..accff7c 100644
--- a/bta/sys/bta_sys_conn.c
+++ b/bta/sys/bta_sys_conn.c
@@ -527,7 +527,7 @@
     }
 }
 
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&(BTA_EIR_CANNED_UUID_LIST != TRUE)
+#if (BTA_EIR_CANNED_UUID_LIST != TRUE)
 /*******************************************************************************
 **
 ** Function         bta_sys_eir_register
diff --git a/bta/sys/bta_sys_int.h b/bta/sys/bta_sys_int.h
index 32101a5..e9c1929 100644
--- a/bta/sys/bta_sys_int.h
+++ b/bta/sys/bta_sys_int.h
@@ -24,8 +24,6 @@
 #ifndef BTA_SYS_INT_H
 #define BTA_SYS_INT_H
 
-#include "ptim.h"
-
 /*****************************************************************************
 **  Constants and data types
 *****************************************************************************/
@@ -58,9 +56,6 @@
 {
     tBTA_SYS_REG            *reg[BTA_ID_MAX];       /* registration structures */
     BOOLEAN                 is_reg[BTA_ID_MAX];     /* registration structures */
-    tPTIM_CB                ptim_cb;                /* protocol timer list */
-    BOOLEAN                 timers_disabled;        /* TRUE if sys timers disabled */
-    UINT8                   task_id;                /* GKI task id */
     tBTA_SYS_HW_STATE state;
     tBTA_SYS_HW_CBACK *sys_hw_cback[BTA_SYS_MAX_HW_MODULES];    /* enable callback for each HW modules */
     UINT32                  sys_hw_module_active;   /* bitmask of all active modules */
@@ -72,7 +67,7 @@
     tBTA_SYS_CONN_CBACK     *p_sco_cb;               /* SCO connection change callback registered by AV */
     tBTA_SYS_CONN_CBACK     *p_role_cb;              /* role change callback registered by AV */
     tBTA_SYS_COLLISION      colli_reg;               /* collision handling module */
-#if ( BTM_EIR_SERVER_INCLUDED == TRUE )&&(BTA_EIR_CANNED_UUID_LIST != TRUE)
+#if (BTA_EIR_CANNED_UUID_LIST != TRUE)
     tBTA_SYS_EIR_CBACK      *eir_cb;                /* add/remove UUID into EIR */
 #endif
 #if (BTM_SSR_INCLUDED == TRUE)
@@ -83,9 +78,6 @@
 
 } tBTA_SYS_CB;
 
-
-
-
 /*****************************************************************************
 **  Global variables
 *****************************************************************************/
@@ -98,12 +90,6 @@
 #define bta_sys_cb (*bta_sys_cb_ptr)
 #endif
 
-
-/* system manager configuration structure */
-extern tBTA_SYS_CFG *p_bta_sys_cfg;
-
-
-
 /* functions used for BTA SYS HW state machine */
 void bta_sys_hw_btm_cback( tBTM_DEV_STATUS status );
 void bta_sys_hw_error(tBTA_SYS_HW_MSG *p_sys_hw_msg);
@@ -115,8 +101,4 @@
 
 BOOLEAN bta_sys_sm_execute(BT_HDR *p_msg);
 
-
-
-
-
 #endif /* BTA_SYS_INT_H */
diff --git a/bta/sys/bta_sys_main.c b/bta/sys/bta_sys_main.c
index 0219290..b03c2d1 100644
--- a/bta/sys/bta_sys_main.c
+++ b/bta/sys/bta_sys_main.c
@@ -21,46 +21,49 @@
  *  This is the main implementation file for the BTA system manager.
  *
  ******************************************************************************/
+#define LOG_TAG "bt_bta_sys_main"
 
+#include <assert.h>
+#include <string.h>
+
+#include "osi/include/alarm.h"
 #include "btm_api.h"
 #include "bta_api.h"
 #include "bta_sys.h"
 #include "bta_sys_int.h"
-#include "bta_sys_ci.h"
-#include "bta_sys_co.h"
-#if BTA_FM_INCLUDED == TRUE
-#include "bta_fm_api.h"
-#endif
-#if BTA_FMTX_INCLUDED == TRUE
-#include "bta_fmtx_api.h"
-#endif
-#if GPS_INCLUDED == TRUE
-#include "bta_gps_api.h"
-#endif
 
+#include "osi/include/fixed_queue.h"
 #include "gki.h"
-#include "ptim.h"
-#include <string.h>
+#include "osi/include/hash_map.h"
+#include "osi/include/osi.h"
+#include "osi/include/hash_functions.h"
+#include "osi/include/log.h"
+#include "osi/include/thread.h"
 #if( defined BTA_AR_INCLUDED ) && (BTA_AR_INCLUDED == TRUE)
 #include "bta_ar_api.h"
 #endif
 #include "utl.h"
 
-/* protocol timer update period, in milliseconds */
-#ifndef BTA_SYS_TIMER_PERIOD
-#define BTA_SYS_TIMER_PERIOD            1000
-#endif
-
 /* system manager control block definition */
 #if BTA_DYNAMIC_MEMORY == FALSE
 tBTA_SYS_CB bta_sys_cb;
 #endif
 
+fixed_queue_t *btu_bta_alarm_queue;
+static hash_map_t *bta_alarm_hash_map;
+static const size_t BTA_ALARM_HASH_MAP_SIZE = 17;
+static pthread_mutex_t bta_alarm_lock;
+extern thread_t *bt_workqueue_thread;
+
 /* trace level */
 /* TODO Bluedroid - Hard-coded trace levels -  Needs to be configurable */
 UINT8 appl_trace_level = BT_TRACE_LEVEL_WARNING; //APPL_INITIAL_TRACE_LEVEL;
 UINT8 btif_trace_level = BT_TRACE_LEVEL_WARNING;
 
+// Communication queue between btu_task and bta.
+extern fixed_queue_t *btu_bta_msg_queue;
+void btu_bta_alarm_ready(fixed_queue_t *queue, UNUSED_ATTR void *context);
+
 static const tBTA_SYS_REG bta_sys_hw_reg =
 {
     bta_sys_sm_execute,
@@ -169,12 +172,22 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void bta_sys_init(void)
+void bta_sys_init(void)
 {
     memset(&bta_sys_cb, 0, sizeof(tBTA_SYS_CB));
-    ptim_init(&bta_sys_cb.ptim_cb, BTA_SYS_TIMER_PERIOD, p_bta_sys_cfg->timer);
-    bta_sys_cb.task_id = GKI_get_taskid();
-    appl_trace_level = p_bta_sys_cfg->trace_level;
+
+    pthread_mutex_init(&bta_alarm_lock, NULL);
+
+    bta_alarm_hash_map = hash_map_new(BTA_ALARM_HASH_MAP_SIZE,
+            hash_function_pointer, NULL, (data_free_fn)alarm_free, NULL);
+    btu_bta_alarm_queue = fixed_queue_new(SIZE_MAX);
+
+    fixed_queue_register_dequeue(btu_bta_alarm_queue,
+        thread_get_reactor(bt_workqueue_thread),
+        btu_bta_alarm_ready,
+        NULL);
+
+    appl_trace_level = APPL_INITIAL_TRACE_LEVEL;
 
     /* register BTA SYS message handler */
     bta_sys_register( BTA_ID_SYS,  &bta_sys_hw_reg);
@@ -188,6 +201,12 @@
 
 }
 
+void bta_sys_free(void) {
+    fixed_queue_free(btu_bta_alarm_queue, NULL);
+    hash_map_free(bta_alarm_hash_map);
+    pthread_mutex_destroy(&bta_alarm_lock);
+}
+
 /*******************************************************************************
 **
 ** Function         bta_dm_sm_execute
@@ -339,8 +358,14 @@
         /* register which HW module was turned on */
         bta_sys_cb.sys_hw_module_active |=  ((UINT32)1 << p_sys_hw_msg->hw_module );
 
-        /* use call-out to power-up HW */
-        bta_sys_hw_co_enable(p_sys_hw_msg->hw_module);
+        tBTA_SYS_HW_MSG *p_msg;
+        if ((p_msg = (tBTA_SYS_HW_MSG *) GKI_getbuf(sizeof(tBTA_SYS_HW_MSG))) != NULL)
+        {
+            p_msg->hdr.event = BTA_SYS_EVT_ENABLED_EVT;
+            p_msg->hw_module = p_sys_hw_msg->hw_module;
+
+            bta_sys_sendmsg(p_msg);
+        }
     }
     else
     {
@@ -391,8 +416,15 @@
     {
         /* manually update the state of our system */
         bta_sys_cb.state = BTA_SYS_HW_STOPPING;
-        /* and use the call-out to disable HW */
-        bta_sys_hw_co_disable(p_sys_hw_msg->hw_module);
+
+        tBTA_SYS_HW_MSG *p_msg;
+        if ((p_msg = (tBTA_SYS_HW_MSG *) GKI_getbuf(sizeof(tBTA_SYS_HW_MSG))) != NULL)
+        {
+            p_msg->hdr.event = BTA_SYS_EVT_DISABLED_EVT;
+            p_msg->hw_module = p_sys_hw_msg->hw_module;
+
+            bta_sys_sendmsg(p_msg);
+        }
     }
 
 }
@@ -411,21 +443,7 @@
 void bta_sys_hw_evt_enabled(tBTA_SYS_HW_MSG *p_sys_hw_msg)
 {
     APPL_TRACE_EVENT("bta_sys_hw_evt_enabled for %i", p_sys_hw_msg->hw_module);
-
-#if ( defined BTM_AUTOMATIC_HCI_RESET && BTM_AUTOMATIC_HCI_RESET == TRUE )
-    /* If device is already up, send a fake "BTM DEVICE UP" using BTA SYS state machine */
-    /* If we are in the middle device initialization, BTM_DEVICE_UP will be issued      */
-    /* by BTM once initialization is done.                                              */
-    if (BTA_DmIsDeviceUp())
-    {
-        bta_sys_hw_btm_cback (BTM_DEV_STATUS_UP);
-    }
-#else
-
-    /* if HCI reset was not sent during stack start-up */
     BTM_DeviceReset( NULL );
-
-#endif
 }
 
 
@@ -489,7 +507,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTA_API void bta_sys_event(BT_HDR *p_msg)
+void bta_sys_event(BT_HDR *p_msg)
 {
     UINT8       id;
     BOOLEAN     freebuf = TRUE;
@@ -518,23 +536,6 @@
 
 /*******************************************************************************
 **
-** Function         bta_sys_timer_update
-**
-** Description      Update the BTA timer list and handle expired timers.
-**
-** Returns          void
-**
-*******************************************************************************/
-BTA_API void bta_sys_timer_update(void)
-{
-    if (!bta_sys_cb.timers_disabled)
-    {
-        ptim_timer_update(&bta_sys_cb.ptim_cb);
-    }
-}
-
-/*******************************************************************************
-**
 ** Function         bta_sys_register
 **
 ** Description      Called by other BTA subsystems to register their event
@@ -596,7 +597,7 @@
 *******************************************************************************/
 void bta_sys_sendmsg(void *p_msg)
 {
-    GKI_send_msg(bta_sys_cb.task_id, p_bta_sys_cfg->mbox, p_msg);
+    fixed_queue_enqueue(btu_bta_msg_queue, p_msg);
 }
 
 /*******************************************************************************
@@ -609,9 +610,32 @@
 ** Returns          void
 **
 *******************************************************************************/
-void bta_sys_start_timer(TIMER_LIST_ENT *p_tle, UINT16 type, INT32 timeout)
-{
-    ptim_start_timer(&bta_sys_cb.ptim_cb, p_tle, type, timeout);
+void bta_alarm_cb(void *data) {
+  assert(data != NULL);
+  TIMER_LIST_ENT *p_tle = (TIMER_LIST_ENT *)data;
+
+  fixed_queue_enqueue(btu_bta_alarm_queue, p_tle);
+}
+
+void bta_sys_start_timer(TIMER_LIST_ENT *p_tle, UINT16 type, INT32 timeout_ms) {
+  assert(p_tle != NULL);
+
+  // Get the alarm for this p_tle.
+  pthread_mutex_lock(&bta_alarm_lock);
+  if (!hash_map_has_key(bta_alarm_hash_map, p_tle)) {
+    hash_map_set(bta_alarm_hash_map, p_tle, alarm_new());
+  }
+  pthread_mutex_unlock(&bta_alarm_lock);
+
+  alarm_t *alarm = hash_map_get(bta_alarm_hash_map, p_tle);
+  if (alarm == NULL) {
+    LOG_ERROR("%s unable to create alarm.", __func__);
+    return;
+  }
+
+  p_tle->event = type;
+  p_tle->ticks = timeout_ms;
+  alarm_set(alarm, (period_ms_t)timeout_ms, bta_alarm_cb, p_tle);
 }
 
 /*******************************************************************************
@@ -623,9 +647,15 @@
 ** Returns          void
 **
 *******************************************************************************/
-void bta_sys_stop_timer(TIMER_LIST_ENT *p_tle)
-{
-    ptim_stop_timer(&bta_sys_cb.ptim_cb, p_tle);
+void bta_sys_stop_timer(TIMER_LIST_ENT *p_tle) {
+  assert(p_tle != NULL);
+
+  alarm_t *alarm = hash_map_get(bta_alarm_hash_map, p_tle);
+  if (alarm == NULL) {
+    LOG_DEBUG("%s expected alarm was not in bta alarm hash map.", __func__);
+    return;
+  }
+  alarm_cancel(alarm);
 }
 
 /*******************************************************************************
@@ -650,18 +680,6 @@
             bta_id = BTA_ID_DM;
             bta_id_max = BTA_ID_BLUETOOTH_MAX;
             break;
-        case BTA_SYS_HW_FMRX:
-            bta_id = BTA_ID_FM;
-            bta_id_max = BTA_ID_FM;
-            break;
-        case BTA_SYS_HW_FMTX:
-            bta_id = BTA_ID_FMTX;
-            bta_id_max = BTA_ID_FMTX;
-            break;
-        case BTA_SYS_HW_GPS:
-            bta_id = BTA_ID_GPS;
-            bta_id_max = BTA_ID_GPS;
-            break;
         default:
             APPL_TRACE_WARNING("bta_sys_disable: unkown module");
             return;
@@ -681,20 +699,6 @@
 
 /*******************************************************************************
 **
-** Function         bta_sys_disable_timers
-**
-** Description      Disable sys timer event handling
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_sys_disable_timers(void)
-{
-    bta_sys_cb.timers_disabled = TRUE;
-}
-
-/*******************************************************************************
-**
 ** Function         bta_sys_set_trace_level
 **
 ** Description      Set trace level for BTA
@@ -720,5 +724,3 @@
 {
     return bta_sys_cb.sys_features;
 }
-
-
diff --git a/bta/sys/ptim.c b/bta/sys/ptim.c
deleted file mode 100644
index 2e1ce20..0000000
--- a/bta/sys/ptim.c
+++ /dev/null
@@ -1,165 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Protocol timer services.
- *
- ******************************************************************************/
-
-#include <stddef.h>
-
-#include "bt_target.h"
-#include "gki.h"
-#include "ptim.h"
-#include "bta_sys.h"
-
-/*******************************************************************************
-**
-** Function         ptim_init
-**
-** Description      Initialize a protocol timer control block.  Parameter
-**                  period is the GKI timer period in milliseconds.  Parameter
-**                  timer_id is the GKI timer id.
-**
-** Returns          void
-**
-*******************************************************************************/
-void ptim_init(tPTIM_CB *p_cb, UINT16 period, UINT8 timer_id)
-{
-    GKI_init_timer_list(&p_cb->timer_queue);
-    p_cb->period = period;
-    p_cb->timer_id = timer_id;
-}
-
-/*******************************************************************************
-**
-** Function         ptim_timer_update
-**
-** Description      Update the protocol timer list and handle expired timers.
-**                  This function is called from the task running the protocol
-**                  timers when the periodic GKI timer expires.
-**
-** Returns          void
-**
-*******************************************************************************/
-void ptim_timer_update(tPTIM_CB *p_cb)
-{
-    TIMER_LIST_ENT *p_tle;
-    BT_HDR *p_msg;
-    UINT32 new_ticks_count;
-    INT32  period_in_ticks;
-
-    /* To handle the case when the function is called less frequently than the period
-       we must convert determine the number of ticks since the last update, then
-       convert back to milliseconds before updating timer list */
-    new_ticks_count = GKI_get_tick_count();
-
-    /* Check for wrapped condition */
-    if (new_ticks_count >= p_cb->last_gki_ticks)
-    {
-        period_in_ticks = (INT32)(new_ticks_count - p_cb->last_gki_ticks);
-    }
-    else
-    {
-        period_in_ticks = (INT32)(((UINT32)0xffffffff - p_cb->last_gki_ticks)
-                            + new_ticks_count + 1);
-    }
-
-    /* update timer list */
-    GKI_update_timer_list(&p_cb->timer_queue, GKI_TICKS_TO_MS(period_in_ticks));
-
-    p_cb->last_gki_ticks = new_ticks_count;
-
-    /* while there are expired timers */
-    while((p_cb->timer_queue.p_first) && (p_cb->timer_queue.p_first->ticks <= 0))
-    {
-        /* removed expired timer from list */
-        p_tle = p_cb->timer_queue.p_first;
-        GKI_remove_from_timer_list(&p_cb->timer_queue, p_tle);
-
-        /* call timer callback */
-        if(p_tle->p_cback)
-        {
-            (*p_tle->p_cback)(p_tle);
-        }
-        else if(p_tle->event)
-        {
-            if ((p_msg = (BT_HDR *) GKI_getbuf(sizeof(BT_HDR))) != NULL)
-            {
-                p_msg->event = p_tle->event;
-                p_msg->layer_specific = 0;
-                bta_sys_sendmsg(p_msg);
-            }
-        }
-    }
-
-    /* if timer list is empty stop periodic GKI timer */
-    if (p_cb->timer_queue.p_first == NULL)
-    {
-        GKI_stop_timer(p_cb->timer_id);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         ptim_start_timer
-**
-** Description      Start a protocol timer for the specified amount
-**                  of time in seconds.
-**
-** Returns          void
-**
-*******************************************************************************/
-void ptim_start_timer(tPTIM_CB *p_cb, TIMER_LIST_ENT *p_tle, UINT16 type, INT32 timeout)
-{
-    /* if timer list is currently empty, start periodic GKI timer */
-    if (p_cb->timer_queue.p_first == NULL)
-    {
-        p_cb->last_gki_ticks = GKI_get_tick_count();
-        GKI_start_timer(p_cb->timer_id, GKI_MS_TO_TICKS(p_cb->period), TRUE);
-    }
-
-    GKI_remove_from_timer_list(&p_cb->timer_queue, p_tle);
-
-    p_tle->event = type;
-    p_tle->ticks = timeout;
-    p_tle->ticks_initial = timeout;
-
-    GKI_add_to_timer_list(&p_cb->timer_queue, p_tle);
-}
-
-/*******************************************************************************
-**
-** Function         ptim_stop_timer
-**
-** Description      Stop a protocol timer.
-**
-** Returns          void
-**
-*******************************************************************************/
-void ptim_stop_timer(tPTIM_CB *p_cb, TIMER_LIST_ENT *p_tle)
-{
-    GKI_remove_from_timer_list (&p_cb->timer_queue, p_tle);
-
-    /* if timer list is empty stop periodic GKI timer */
-    if (p_cb->timer_queue.p_first == NULL)
-    {
-        GKI_stop_timer(p_cb->timer_id);
-    }
-}
diff --git a/btcore/Android.mk b/btcore/Android.mk
new file mode 100644
index 0000000..8c3e368
--- /dev/null
+++ b/btcore/Android.mk
@@ -0,0 +1,67 @@
+ ##############################################################################
+ #
+ #  Copyright (C) 2014 Google, Inc.
+ #
+ #  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.
+ #
+ ##############################################################################
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_C_INCLUDES := \
+    $(LOCAL_PATH)/include \
+    $(LOCAL_PATH)/../osi/include \
+    $(LOCAL_PATH)/..
+
+LOCAL_SRC_FILES := \
+    src/bdaddr.c \
+    src/counter.c \
+    src/device_class.c \
+    src/module.c \
+    src/property.c \
+    src/uuid.c
+
+LOCAL_CFLAGS := -std=c99 $(bdroid_CFLAGS)
+LOCAL_MODULE := libbtcore
+LOCAL_MODULE_TAGS := optional
+LOCAL_SHARED_LIBRARIES := libc liblog
+LOCAL_MODULE_CLASS := STATIC_LIBRARIES
+
+include $(BUILD_STATIC_LIBRARY)
+
+#####################################################
+
+include $(CLEAR_VARS)
+
+LOCAL_C_INCLUDES := \
+    $(LOCAL_PATH)/include \
+    $(LOCAL_PATH)/..
+
+LOCAL_SRC_FILES := \
+    ./test/bdaddr_test.cpp \
+    ./test/counter_test.cpp \
+    ./test/device_class_test.cpp \
+    ./test/property_test.cpp \
+    ./test/uuid_test.cpp \
+    ../osi/test/AllocationTestHarness.cpp
+
+LOCAL_CFLAGS := -Wall -Werror -Werror=unused-variable
+LOCAL_MODULE := net_test_btcore
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_SHARED_LIBRARIES := liblog
+LOCAL_STATIC_LIBRARIES := libbtcore libosi
+
+include $(BUILD_NATIVE_TEST)
diff --git a/btcore/include/bdaddr.h b/btcore/include/bdaddr.h
new file mode 100644
index 0000000..b9a99ce
--- /dev/null
+++ b/btcore/include/bdaddr.h
@@ -0,0 +1,60 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <hardware/bluetooth.h>
+#include <stdbool.h>
+#include <stddef.h>
+
+#include "osi/include/hash_map.h"
+
+// Note: the string representation of a bdaddr is expected to have the format
+// xx:xx:xx:xx:xx:xx
+// where each 'x' is a hex digit. The API presented in this header will accept
+// both uppercase and lowercase digits but will only ever produce lowercase
+// digits.
+
+// Returns true if |addr| is the empty address (00:00:00:00:00:00).
+// |addr| may not be NULL.
+bool bdaddr_is_empty(const bt_bdaddr_t *addr);
+
+// Returns true if |first| and |second| refer to the same address. Neither
+// may be NULL.
+bool bdaddr_equals(const bt_bdaddr_t *first, const bt_bdaddr_t *second);
+
+// Returns destination bdaddr |dest| after copying |src| to |dest|.
+// |dest| and |src| must not be NULL.
+bt_bdaddr_t *bdaddr_copy(bt_bdaddr_t *dest, const bt_bdaddr_t *src);
+
+// Makes a string representation of |addr| and places it into |string|. |size|
+// refers to the size of |string|'s buffer and must be >= 18. On success, this
+// function returns |string|, otherwise it returns NULL. Neither |addr| nor |string|
+// may be NULL.
+const char *bdaddr_to_string(const bt_bdaddr_t *addr, char *string, size_t size);
+
+// Returns true if |string| represents a Bluetooth address. |string| may not be NULL.
+bool string_is_bdaddr(const char *string);
+
+// Converts |string| to bt_bdaddr_t and places it in |addr|. If |string| does not
+// represent a Bluetooth address, |addr| is not modified and this function returns
+// false. Otherwise, it returns true. Neither |string| nor |addr| may be NULL.
+bool string_to_bdaddr(const char *string, bt_bdaddr_t *addr);
+
+// A hash function tailored for bdaddrs.
+hash_index_t hash_function_bdaddr(const void *key);
diff --git a/test/suite/support/property.h b/btcore/include/counter.h
similarity index 62%
copy from test/suite/support/property.h
copy to btcore/include/counter.h
index a8b77c7..10e384f 100644
--- a/test/suite/support/property.h
+++ b/btcore/include/counter.h
@@ -18,15 +18,19 @@
 
 #pragma once
 
-#include "base.h"
+#include <stdbool.h>
+#include <stdint.h>
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+static const char COUNTER_MODULE[] = "counter_module";
 
-const char *property_extract_name(const bt_property_t *property);
+typedef int64_t counter_data_t;
 
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
+// Used to iterate across all counters.
+typedef bool (*counter_iter_cb)(const char *name, counter_data_t val, void *context);
 
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+// Mutators.
+void counter_set(const char *name, counter_data_t val);
+void counter_add(const char *name, counter_data_t val);
+
+// Iteration.
+bool counter_foreach(counter_iter_cb, void *context);
diff --git a/btcore/include/device_class.h b/btcore/include/device_class.h
new file mode 100644
index 0000000..8c2c3c0
--- /dev/null
+++ b/btcore/include/device_class.h
@@ -0,0 +1,92 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+
+// Provides Class Of Device primitive as specified in the bluetooth spec.
+// [Class Of Device](https://www.bluetooth.org/en-us/specification/assigned-numbers/baseband)
+
+// Device class may be defined in other structures.
+// Only use defined methods to manipulate internals.
+typedef struct bt_device_class_t {
+  uint8_t _[3];  // Do not access directly; use methods below.
+} bt_device_class_t;
+
+// Copies the |data| class of device stream into device class |dc|.  |dc|
+// and |data| must not be NULL.
+void device_class_from_stream(bt_device_class_t *dc, const uint8_t *data);
+
+// Serializes the device class |dc| to pointer argument |data| in big endian
+// format.  |len| must contain the buffer size of |data|.  Returns the actual
+// number of bytes copied into |data|.  |dc| and |data| must not be NULL.
+int device_class_to_stream(const bt_device_class_t *dc, uint8_t *data, size_t len);
+
+// Copies the |data| class of device integer into device class |dc|.  |dc|
+// must not be NULL.
+void device_class_from_int(bt_device_class_t *dc, int data);
+
+// Returns the device class |dc| in integer format.  |dc| must not be NULL.
+int device_class_to_int(const bt_device_class_t *dc);
+
+// Compares and returns |true| if two device classes |p1| and |p2| are equal.
+// False otherwise.
+bool device_class_equals(const bt_device_class_t *p1, const bt_device_class_t *p2);
+
+// Copies and returns |true| if the device class was successfully copied from
+//  |p2| into |p1|.  False otherwise.
+bool device_class_copy(bt_device_class_t *dest, const bt_device_class_t *src);
+
+// Query, getters and setters for the major device class.  |dc| must not be NULL.
+int device_class_get_major_device(const bt_device_class_t *dc);
+void device_class_set_major_device(bt_device_class_t *dc, int val);
+
+// Query, getters and setters for the minor device class. |dc| must not be NULL.
+int device_class_get_minor_device(const bt_device_class_t *dc);
+void device_class_set_minor_device(bt_device_class_t *dc, int val);
+
+// Query, getters and setters for the various major service class features.
+// |dc| must not be NULL.
+bool device_class_get_limited(const bt_device_class_t *dc);
+void device_class_set_limited(bt_device_class_t *dc, bool set);
+
+bool device_class_get_positioning(const bt_device_class_t *dc);
+void device_class_set_positioning(bt_device_class_t *dc, bool set);
+
+bool device_class_get_networking(const bt_device_class_t *dc);
+void device_class_set_networking(bt_device_class_t *dc, bool set);
+
+bool device_class_get_rendering(const bt_device_class_t *dc);
+void device_class_set_rendering(bt_device_class_t *dc, bool set);
+
+bool device_class_get_capturing(const bt_device_class_t *dc);
+void device_class_set_capturing(bt_device_class_t *dc, bool set);
+
+bool device_class_get_object_transfer(const bt_device_class_t *dc);
+void device_class_set_object_transfer(bt_device_class_t *dc, bool set);
+
+bool device_class_get_audio(const bt_device_class_t *dc);
+void device_class_set_audio(bt_device_class_t *dc, bool set);
+
+bool device_class_get_telephony(const bt_device_class_t *dc);
+void device_class_set_telephony(bt_device_class_t *dc, bool set);
+
+bool device_class_get_information(const bt_device_class_t *dc);
+void device_class_set_information(bt_device_class_t *dc, bool set);
diff --git a/test/suite/support/property.h b/btcore/include/device_features.h
similarity index 61%
copy from test/suite/support/property.h
copy to btcore/include/device_features.h
index a8b77c7..f3069e3 100644
--- a/test/suite/support/property.h
+++ b/btcore/include/device_features.h
@@ -18,15 +18,10 @@
 
 #pragma once
 
-#include "base.h"
+#include <stdint.h>
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
-
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+// Represents a page of device feature enabled/disabled bits returned
+// by the local controller. See the bluetooth spec for bit indexes.
+typedef struct {
+  uint8_t as_array[8];
+} bt_device_features_t;
diff --git a/test/suite/support/property.h b/btcore/include/event_mask.h
similarity index 61%
copy from test/suite/support/property.h
copy to btcore/include/event_mask.h
index a8b77c7..ec662b2 100644
--- a/test/suite/support/property.h
+++ b/btcore/include/event_mask.h
@@ -18,15 +18,11 @@
 
 #pragma once
 
-#include "base.h"
+#include <stdint.h>
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
-
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+// Represents a mask which can be used to tell the controller which
+// HCI events the stack wishes to be informed about. See the bluetooth
+// spec for more information on what each bit means.
+typedef struct {
+  uint8_t as_array[8];
+} bt_event_mask_t;
diff --git a/test/suite/support/property.h b/btcore/include/iac.h
similarity index 61%
copy from test/suite/support/property.h
copy to btcore/include/iac.h
index a8b77c7..bcb8ab8 100644
--- a/test/suite/support/property.h
+++ b/btcore/include/iac.h
@@ -18,15 +18,10 @@
 
 #pragma once
 
-#include "base.h"
+#include <stdint.h>
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
-
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+// Inquiry Access Code
+// [Bluetooth Baseband](https://www.bluetooth.org/en-us/specification/assigned-numbers/baseband)
+typedef struct {
+  uint8_t iac[3];
+} __attribute__((packed))bt_inquiry_access_code_t;
diff --git a/btcore/include/module.h b/btcore/include/module.h
new file mode 100644
index 0000000..d88f5f3
--- /dev/null
+++ b/btcore/include/module.h
@@ -0,0 +1,67 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+
+#include "osi/include/future.h"
+#include "osi/include/thread.h"
+
+typedef future_t *(*module_lifecycle_fn)(void);
+
+typedef struct {
+  const char *name;
+  module_lifecycle_fn init;
+  module_lifecycle_fn start_up;
+  module_lifecycle_fn shut_down;
+  module_lifecycle_fn clean_up;
+  const char *dependencies[];
+} module_t;
+
+// Prepares module management. Must be called before doing anything with modules.
+void module_management_start(void);
+// Cleans up all module management resources.
+void module_management_stop(void);
+
+const module_t *get_module(const char *name);
+
+// Initialize the provided module. |module| may not be NULL
+// and must not be initialized.
+bool module_init(const module_t *module);
+// Start up the provided module. |module| may not be NULL
+// and must be initialized or have no init function.
+bool module_start_up(const module_t *module);
+// Shut down the provided module. |module| may not be NULL.
+// If not started, does nothing.
+void module_shut_down(const module_t *module);
+// Clean up the provided module. |module| may not be NULL.
+// If not initialized, does nothing.
+void module_clean_up(const module_t *module);
+
+// Temporary callbacked wrapper for module start up, so real modules can be
+// spliced into the current janky startup sequence. Runs on a separate thread,
+// which terminates when the module start up has finished. When module startup
+// has finished, |callback| is called within the context of |callback_thread|
+// with |FUTURE_SUCCESS| or |FUTURE_FAIL| depending on whether startup succeeded
+// or not.
+void module_start_up_callbacked_wrapper(
+  const module_t *module,
+  thread_t *callback_thread,
+  thread_fn callback
+);
diff --git a/btcore/include/property.h b/btcore/include/property.h
new file mode 100644
index 0000000..3a41422
--- /dev/null
+++ b/btcore/include/property.h
@@ -0,0 +1,77 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <hardware/bluetooth.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include "btcore/include/device_class.h"
+
+// Copies an array of consecutive properties of |count| to a newly
+// allocated array. |properties| must not be NULL.
+bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
+
+// Copies |src| to |dest|. Returns the value of |dest|.
+// |src| and |dest| must not be NULL.
+bt_property_t *property_copy(bt_property_t *dest, const bt_property_t *src);
+
+// Returns true if the value of the two properties |p1| and |p2| are equal.
+// |p1| and |p2| must not be NULL.
+bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
+
+// Property resource allocations. Caller is expected to free |property|
+// using |property_free| or |property_free_array|.
+// Parameter must not be NULL. A copy of the parameter is made and
+// stored in the property.
+bt_property_t *property_new_addr(const bt_bdaddr_t *addr);
+bt_property_t *property_new_device_class(const bt_device_class_t *dc);
+bt_property_t *property_new_device_type(bt_device_type_t device_type);
+bt_property_t *property_new_discovery_timeout(const uint32_t timeout);
+bt_property_t *property_new_name(const char *name);
+bt_property_t *property_new_rssi(const int8_t rssi);
+bt_property_t *property_new_scan_mode(bt_scan_mode_t scan_mode);
+bt_property_t *property_new_uuids(const bt_uuid_t *uuid, size_t count);
+
+// Property resource frees both property and value.
+void property_free(bt_property_t *property);
+void property_free_array(bt_property_t *properties, size_t count);
+
+// Value check convenience methods. The contents of the property are
+// checked for the respective validity and returns true, false otherwise.
+// |property| must not be NULL.
+bool property_is_addr(const bt_property_t *property);
+bool property_is_device_class(const bt_property_t *property);
+bool property_is_device_type(const bt_property_t *property);
+bool property_is_discovery_timeout(const bt_property_t *property);
+bool property_is_name(const bt_property_t *property);
+bool property_is_rssi(const bt_property_t *property);
+bool property_is_scan_mode(const bt_property_t *property);
+bool property_is_uuids(const bt_property_t *property);
+
+// Value conversion convenience methods. The contents of the property are
+// properly typed and returned to the caller. |property| must not be NULL.
+const bt_bdaddr_t *property_as_addr(const bt_property_t *property);
+const bt_device_class_t *property_as_device_class(const bt_property_t *property);
+bt_device_type_t property_as_device_type(const bt_property_t *property);
+uint32_t property_as_discovery_timeout(const bt_property_t *property);
+const bt_bdname_t *property_as_name(const bt_property_t *property);
+int8_t property_as_rssi(const bt_property_t *property);
+bt_scan_mode_t property_as_scan_mode(const bt_property_t *property);
+const bt_uuid_t *property_as_uuids(const bt_property_t *property, size_t *count);
diff --git a/btcore/include/uuid.h b/btcore/include/uuid.h
new file mode 100644
index 0000000..40607cf
--- /dev/null
+++ b/btcore/include/uuid.h
@@ -0,0 +1,75 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <hardware/bluetooth.h>
+#include <stdbool.h>
+
+typedef struct uuid_string_t uuid_string_t;
+
+// Creates uuid string structure to hold a well formed UUID
+// string.  Must release resources with |uuid_string_free|.
+// Returns NULL if no memory.
+uuid_string_t *uuid_string_new(void);
+
+// Frees a uuid string structure created from |uuid_string_new|.
+// |uuid_string| may be NULL.
+void uuid_string_free(uuid_string_t *uuid_string);
+
+// Returns a string pointer to the well formed UUID string
+// entry.  |uuid_string| must not be NULL.
+const char *uuid_string_data(const uuid_string_t *uuid_string);
+
+// Creates uuid structure from a well formed UUID string
+// |uuid_string|.  The caller takes ownership of the uuid
+// structure and must release resources with |uuid_free|.
+// |uuid_string| must not be NULL.
+//
+// Returns NULL if |uuid_string| is malformed or no memory.
+//
+// A well formed UUID string is structured like this:
+//   "00112233-4455-6677-8899-aabbccddeeff"
+bt_uuid_t *uuid_new(const char *uuid_string);
+
+// Frees a uuid structure created from |uuid_new| and friends.
+// |uuid| may be NULL.
+void uuid_free(bt_uuid_t *uuid);
+
+// Returns true if the UUID is all zeros, false otherwise.
+// |uuid| may not be NULL.
+bool uuid_is_empty(const bt_uuid_t *uuid);
+
+// Returns true if the two UUIDs are equal, false otherwise.
+// |first| and |second| may not be NULL.
+bool uuid_is_equal(const bt_uuid_t *first, const bt_uuid_t *second);
+
+// Copies uuid |src| into |dest| and returns a pointer to |dest|.
+// |src| and |dest| must not be NULL.
+bt_uuid_t *uuid_copy(bt_uuid_t *dest, const bt_uuid_t *src);
+
+// Converts contents of |uuid| to a well formed UUID string
+// |uuid_string| using numbers and lower case letter.  |uuid|
+// and |uuid_string| must not be NULL.
+void uuid_to_string(const bt_uuid_t *uuid, uuid_string_t *uuid_string);
+
+// Converts contents of |uuid| to a short uuid if possible.  Returns
+// true if conversion is possible, false otherwise.
+// |uuid|, |uuid16| and |uuid32| must not be NULL.
+bool uuid_128_to_16(const bt_uuid_t *uuid, uint16_t *uuid16);
+bool uuid_128_to_32(const bt_uuid_t *uuid, uint32_t *uuid32);
diff --git a/test/suite/support/property.h b/btcore/include/version.h
similarity index 61%
copy from test/suite/support/property.h
copy to btcore/include/version.h
index a8b77c7..a0696ad 100644
--- a/test/suite/support/property.h
+++ b/btcore/include/version.h
@@ -18,15 +18,12 @@
 
 #pragma once
 
-#include "base.h"
+#include <stdint.h>
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
-
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+typedef struct {
+  uint8_t hci_version;
+  uint16_t hci_revision;
+  uint8_t lmp_version;
+  uint16_t manufacturer;
+  uint16_t lmp_subversion;
+} bt_version_t;
diff --git a/btcore/src/bdaddr.c b/btcore/src/bdaddr.c
new file mode 100644
index 0000000..ddbd9d3
--- /dev/null
+++ b/btcore/src/bdaddr.c
@@ -0,0 +1,101 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <assert.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "btcore/include/bdaddr.h"
+
+bool bdaddr_is_empty(const bt_bdaddr_t *addr) {
+  assert(addr != NULL);
+
+  uint8_t zero[sizeof(bt_bdaddr_t)] = { 0 };
+  return memcmp(addr, &zero, sizeof(bt_bdaddr_t)) == 0;
+}
+
+bool bdaddr_equals(const bt_bdaddr_t *first, const bt_bdaddr_t *second) {
+  assert(first != NULL);
+  assert(second != NULL);
+
+  return memcmp(first, second, sizeof(bt_bdaddr_t)) == 0;
+}
+
+bt_bdaddr_t *bdaddr_copy(bt_bdaddr_t *dest, const bt_bdaddr_t *src) {
+  assert(dest != NULL);
+  assert(src != NULL);
+
+  return (bt_bdaddr_t *)memcpy(dest, src, sizeof(bt_bdaddr_t));
+}
+
+const char *bdaddr_to_string(const bt_bdaddr_t *addr, char *string, size_t size) {
+  assert(addr != NULL);
+  assert(string != NULL);
+
+  if (size < 18)
+    return NULL;
+
+  const uint8_t *ptr = addr->address;
+  sprintf(string, "%02x:%02x:%02x:%02x:%02x:%02x",
+           ptr[0], ptr[1], ptr[2],
+           ptr[3], ptr[4], ptr[5]);
+  return string;
+}
+
+bool string_is_bdaddr(const char *string) {
+  assert(string != NULL);
+
+  size_t len = strlen(string);
+  if (len != 17)
+    return false;
+
+  for (size_t i = 0; i < len; ++i) {
+    // Every 3rd char must be ':'.
+    if (((i + 1) % 3) == 0 && string[i] != ':')
+      return false;
+
+    // All other chars must be a hex digit.
+    if (((i + 1) % 3) != 0 && !isxdigit(string[i]))
+      return false;
+  }
+  return true;
+}
+
+bool string_to_bdaddr(const char *string, bt_bdaddr_t *addr) {
+  assert(string != NULL);
+  assert(addr != NULL);
+
+  bt_bdaddr_t new_addr;
+  uint8_t *ptr = new_addr.address;
+  bool ret = sscanf(string, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
+      &ptr[0], &ptr[1], &ptr[2], &ptr[3], &ptr[4], &ptr[5]) == 6;
+
+  if (ret)
+    memcpy(addr, &new_addr, sizeof(bt_bdaddr_t));
+
+  return ret;
+}
+
+hash_index_t hash_function_bdaddr(const void *key) {
+  hash_index_t hash = 5381;
+  const char *bytes = (const char *)key;
+  for (size_t i = 0; i < sizeof(bt_bdaddr_t); ++i)
+    hash = ((hash << 5) + hash) + bytes[i];
+  return hash;
+}
diff --git a/btcore/src/counter.c b/btcore/src/counter.c
new file mode 100644
index 0000000..08aa518
--- /dev/null
+++ b/btcore/src/counter.c
@@ -0,0 +1,421 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_core_counter"
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/eventfd.h>
+
+#include "osi/include/allocator.h"
+#include "osi/include/atomic.h"
+#include "btcore/include/counter.h"
+#include "osi/include/hash_map.h"
+#include "osi/include/list.h"
+#include "btcore/include/module.h"
+#include "osi/include/osi.h"
+#include "osi/include/hash_functions.h"
+#include "osi/include/log.h"
+#include "osi/include/socket.h"
+#include "osi/include/thread.h"
+
+typedef int (*handler_t)(socket_t * socket);
+
+typedef struct counter_t {
+  atomic_s64_t val;
+} counter_t;
+
+typedef struct hash_element_t {
+  const char *key;
+  counter_t *val;
+} hash_element_t;
+
+typedef struct counter_data_cb_t {
+  counter_iter_cb counter_iter_cb;
+  void *user_context;
+} counter_data_cb_t;
+
+typedef struct {
+  socket_t *socket;
+  uint8_t buffer[256];
+  size_t buffer_size;
+} client_t;
+
+typedef struct {
+  const char *name;
+  const char *help;
+  handler_t handler;
+} command_t;
+
+// Counter core
+static hash_map_t *hash_map_counter_;
+static pthread_mutex_t hash_map_lock_;
+static int counter_cnt_;
+
+// Counter port access
+static socket_t *listen_socket_;
+static thread_t *thread_;
+static list_t *clients_;
+
+static void accept_ready(socket_t *socket, void *context);
+static void read_ready(socket_t *socket, void *context);
+static void client_free(void *ptr);
+static const command_t *find_command(const char *name);
+static void output(socket_t *socket, const char* format, ...);
+
+// Commands
+static int help(socket_t *socket);
+static int show(socket_t *socket);
+static int set(socket_t *socket);
+static int quit(socket_t *socket);
+
+static const command_t commands[] = {
+  { "help", "<command> - show help text for <command>", help},
+  { "quit", "<command> - Quit and exit", quit},
+  { "set", "<counter> - Set something", set},
+  { "show", "<counter> - Show counters", show},
+};
+
+static counter_t *counter_new_(counter_data_t initial_val);
+static void counter_free_(counter_t *counter);
+
+static hash_element_t *hash_element_new_(void);
+// NOTE: The parameter datatype is void in order to satisfy the hash
+// data free function signature
+static void hash_element_free_(void *data);
+
+static struct counter_t *name_to_counter_(const char *name);
+static bool counter_foreach_cb_(hash_map_entry_t *hash_map_entry, void *context);
+
+static bool counter_socket_open(void);
+static void counter_socket_close(void);
+
+static const int COUNTER_NUM_BUCKETS = 53;
+
+// TODO(cmanton) Friendly interface, but may remove for automation
+const char *WELCOME = "Welcome to counters\n";
+const char *PROMPT = "\n> ";
+const char *GOODBYE = "Quitting... Bye !!";
+
+// TODO(cmanton) Develop port strategy; or multiplex all bt across single port
+static const port_t LISTEN_PORT = 8879;
+
+static future_t *counter_init(void) {
+  assert(hash_map_counter_ == NULL);
+  pthread_mutex_init(&hash_map_lock_, NULL);
+  hash_map_counter_ = hash_map_new(COUNTER_NUM_BUCKETS, hash_function_string,
+      NULL, hash_element_free_, NULL);
+  if (hash_map_counter_ == NULL) {
+    LOG_ERROR("%s unable to allocate resources", __func__);
+    return future_new_immediate(FUTURE_FAIL);
+  }
+
+  if (!counter_socket_open()) {
+    LOG_ERROR("%s unable to open counter port", __func__);
+    return future_new_immediate(FUTURE_FAIL);
+  }
+  return future_new_immediate(FUTURE_SUCCESS);
+}
+
+static future_t *counter_clean_up(void) {
+  counter_socket_close();
+  hash_map_free(hash_map_counter_);
+  pthread_mutex_destroy(&hash_map_lock_);
+  hash_map_counter_ = NULL;
+  return future_new_immediate(FUTURE_SUCCESS);
+}
+
+module_t counter_module = {
+  .name = COUNTER_MODULE,
+  .init = counter_init,
+  .start_up = NULL,
+  .shut_down = NULL,
+  .clean_up = counter_clean_up,
+  .dependencies = {NULL},
+};
+
+void counter_set(const char *name, counter_data_t val) {
+  assert(name != NULL);
+  counter_t *counter = name_to_counter_(name);
+  if (counter)
+    atomic_store_s64(&counter->val, val);
+}
+
+void counter_add(const char *name, counter_data_t val) {
+  assert(name != NULL);
+  counter_t *counter = name_to_counter_(name);
+  if (counter) {
+    if (val == 1)
+      atomic_inc_prefix_s64(&counter->val);
+    else
+      atomic_add_s64(&counter->val, val);
+  }
+}
+
+bool counter_foreach(counter_iter_cb cb, void *context) {
+  assert(cb != NULL);
+  counter_data_cb_t counter_cb_data = {
+    cb,
+    context
+  };
+
+  hash_map_foreach(hash_map_counter_, counter_foreach_cb_, &counter_cb_data);
+  return true;
+}
+
+static counter_t *counter_new_(counter_data_t initial_val) {
+  counter_t *counter = (counter_t *)osi_calloc(sizeof(counter_t));
+  if (!counter) {
+    return NULL;
+  }
+  atomic_store_s64(&counter->val, initial_val);
+  return counter;
+}
+
+static void counter_free_(counter_t *counter) {
+  osi_free(counter);
+}
+
+static hash_element_t *hash_element_new_(void) {
+  return (hash_element_t *)osi_calloc(sizeof(hash_element_t));
+}
+
+static void hash_element_free_(void *data) {
+  hash_element_t *hash_element = (hash_element_t *)data;
+  // We don't own the key
+  counter_free_(hash_element->val);
+  osi_free(hash_element);
+}
+
+// Returns a counter from the |hash_map_counter_|.  Creates
+// a new one if not found and inserts into |hash_map_counter_|.
+// Returns NULL upon memory allocation failure.
+static counter_t *name_to_counter_(const char *name) {
+  assert(hash_map_counter_ != NULL);
+  if (hash_map_has_key(hash_map_counter_, name))
+    return (counter_t *)hash_map_get(hash_map_counter_, name);
+
+  pthread_mutex_lock(&hash_map_lock_);
+  // On the uncommon path double check to make sure that another thread has
+  // not already created this counter
+  counter_t *counter = (counter_t *)hash_map_get(hash_map_counter_, name);
+  if (counter)
+    goto exit;
+
+  counter = counter_new_(0);
+  if (!counter) {
+    LOG_ERROR("%s unable to create new counter name:%s", __func__, name);
+    goto exit;
+  }
+
+  hash_element_t *element = hash_element_new_();
+  if (!element) {
+    LOG_ERROR("%s unable to create counter element name:%s", __func__, name);
+    counter_free_(counter);
+    counter = NULL;
+    goto exit;
+  }
+
+  element->key = name;
+  element->val = counter;
+  if (!hash_map_set(hash_map_counter_, name, counter)) {
+    LOG_ERROR("%s unable to set new counter into hash map name:%s", __func__, name);
+    hash_element_free_(element);
+    counter_free_(counter);
+    counter = NULL;
+  }
+
+ exit:;
+  pthread_mutex_unlock(&hash_map_lock_);
+  return counter;
+}
+
+static bool counter_foreach_cb_(hash_map_entry_t *hash_map_entry, void *context) {
+  assert(hash_map_entry != NULL);
+  const char *key = (const char *)hash_map_entry->key;
+  counter_data_t data = *(counter_data_t *)hash_map_entry->data;
+  counter_data_cb_t *counter_cb_data = (counter_data_cb_t *)context;
+  counter_cb_data->counter_iter_cb(key, data, counter_cb_data->user_context);
+  return true;
+}
+
+static bool counter_socket_open(void) {
+  assert(listen_socket_ == NULL);
+  assert(thread_ == NULL);
+  assert(clients_ == NULL);
+
+  clients_ = list_new(client_free);
+  if (!clients_) {
+    LOG_ERROR("%s unable to create counter clients list", __func__);
+    goto error;
+  }
+
+  thread_ = thread_new("counter_socket");
+  if (!thread_) {
+    LOG_ERROR("%s unable to create counter thread", __func__);
+    goto error;
+  }
+
+  listen_socket_ = socket_new();
+  if (!listen_socket_) {
+    LOG_ERROR("%s unable to create listen socket", __func__);
+    goto error;
+  }
+
+  if (!socket_listen(listen_socket_, LISTEN_PORT)) {
+    LOG_ERROR("%s unable to setup listen socket", __func__);
+    goto error;
+  }
+
+  LOG_INFO("%s opened counter server socket", __func__);
+  socket_register(listen_socket_, thread_get_reactor(thread_), NULL, accept_ready, NULL);
+  return true;
+
+error:;
+  counter_socket_close();
+  return false;
+}
+
+static void counter_socket_close(void) {
+  socket_free(listen_socket_);
+  thread_free(thread_);
+  list_free(clients_);
+
+  listen_socket_ = NULL;
+  thread_ = NULL;
+  clients_ = NULL;
+
+  LOG_INFO("%s closed counter server socket", __func__);
+}
+
+static bool monitor_counter_iter_cb(const char *name, counter_data_t val, void *context) {
+  socket_t *socket = (socket_t *)context;
+  output(socket, "counter:%s val:%lld\n", name, val);
+  return true;
+}
+
+static void client_free(void *ptr) {
+  if (!ptr)
+    return;
+
+  client_t *client = (client_t *)ptr;
+  socket_free(client->socket);
+  osi_free(client);
+}
+
+static void accept_ready(socket_t *socket, UNUSED_ATTR void *context) {
+  assert(socket != NULL);
+  assert(socket == listen_socket_);
+
+  LOG_INFO("%s accepted OSI monitor socket", __func__);
+  socket = socket_accept(socket);
+  if (!socket)
+    return;
+
+  client_t *client = (client_t *)osi_calloc(sizeof(client_t));
+  if (!client) {
+    LOG_ERROR("%s unable to allocate memory for client", __func__);
+    socket_free(socket);
+    return;
+  }
+
+  client->socket = socket;
+
+  if (!list_append(clients_, client)) {
+    LOG_ERROR("%s unable to add client to list", __func__);
+    client_free(client);
+    return;
+  }
+
+  socket_register(socket, thread_get_reactor(thread_), client, read_ready, NULL);
+
+  output(socket, WELCOME);
+  output(socket, PROMPT);
+}
+
+static void read_ready(socket_t *socket, void *context) {
+  assert(socket != NULL);
+
+  client_t *client = (client_t *)context;
+
+  ssize_t ret = socket_read(socket, client->buffer + client->buffer_size, sizeof(client->buffer) - client->buffer_size);
+  if (ret == 0 || (ret == -1 && ret != EWOULDBLOCK && ret != EAGAIN)) {
+    list_remove(clients_, client);
+    return;
+  }
+
+  // Replace newline with end of string termination
+  // TODO(cmanton) Need proper semantics
+  for (size_t i = ret - 1; i > 0; --i) {
+    if (client->buffer[i] < 16)
+      *(client->buffer + i) = 0;
+    else
+      break;
+  }
+
+  const command_t *command = find_command((const char *)client->buffer);
+  if (!command) {
+    output(socket, "unable to find command %s\n", client->buffer);
+  } else {
+    int rc = command->handler(socket);
+    if (rc == 1) {
+      output(socket, GOODBYE);
+      socket_free(socket);
+      return;
+    }
+  }
+  output(socket, PROMPT);
+}
+
+static void output(socket_t *socket, const char* format, ...) {
+  char dest[4096];
+  va_list argptr;
+  va_start(argptr, format);
+  vsprintf(dest, format, argptr);
+  va_end(argptr);
+  socket_write(socket, dest, strlen(dest));
+}
+
+static int help(UNUSED_ATTR socket_t *socket) {
+  output(socket, "help command unimplemented\n");
+  return 0;
+}
+
+static int quit(UNUSED_ATTR socket_t *socket) {
+  return 1;
+}
+
+static int set(UNUSED_ATTR socket_t *socket) {
+  output(socket, "set command unimplemented\n");
+  return 0;
+}
+
+static int show(socket_t *socket) {
+  output(socket, "counter count registered:%d\n", counter_cnt_);
+  counter_foreach(monitor_counter_iter_cb, (void *)socket);
+  return 0;
+}
+
+static const command_t *find_command(const char *name) {
+  for  (size_t i = 0; i < ARRAY_SIZE(commands); ++i)
+    if (!strcmp(commands[i].name, name))
+      return &commands[i];
+  return NULL;
+}
diff --git a/btcore/src/device_class.c b/btcore/src/device_class.c
new file mode 100644
index 0000000..6a72ed1
--- /dev/null
+++ b/btcore/src/device_class.c
@@ -0,0 +1,158 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <arpa/inet.h>
+#include <assert.h>
+#include <string.h>
+
+#include "btcore/include/device_class.h"
+#include "osi/include/osi.h"
+
+typedef struct _bt_device_class_t {
+  uint32_t unused : 2;          // LSBs
+  uint32_t minor_device : 6;
+  uint32_t major_device : 5;
+  uint32_t major_service : 11;  // MSBs
+} __attribute__ ((__packed__)) _bt_device_class_t;
+
+// Convenience to interpret raw device class bytes.
+#define DC(x) ((_bt_device_class_t *)x)
+
+// Ensure the internal device class implementation and public one
+// have equal size.
+COMPILE_ASSERT(sizeof(_bt_device_class_t) == sizeof(bt_device_class_t));
+
+// [Major Service Classes](https://www.bluetooth.org/en-us/specification/assigned-numbers/baseband)
+enum {
+  DC_LIMITED_DISCOVERABLE_MODE = 0x0001,
+  DC_RESERVED14 = 0x0002,
+  DC_RESERVED15 = 0x0004,
+  DC_POSITIONING = 0x0008,
+  DC_NETWORKING = 0x0010,
+  DC_RENDERING = 0x0020,
+  DC_CAPTURING = 0x0040,
+  DC_OBJECT_TRANSFER = 0x0080,
+  DC_AUDIO = 0x0100,
+  DC_TELEPHONY = 0x0200,
+  DC_INFORMATION = 0x0400,
+};
+
+static bool device_class_get_major_service_(const bt_device_class_t *dc, int bitmask);
+static void device_class_clr_major_service_(bt_device_class_t *dc, int bitmask);
+static void device_class_set_major_service_(bt_device_class_t *dc, int bitmask);
+
+void device_class_from_stream(bt_device_class_t *dc, const uint8_t *data) {
+  assert(dc != NULL);
+  assert(data != NULL);
+  *dc = *(bt_device_class_t *)data;
+}
+
+int device_class_to_stream(const bt_device_class_t *dc, uint8_t *data, size_t len) {
+  assert(dc != NULL);
+  assert(data != NULL);
+  assert(len >= sizeof(bt_device_class_t));
+  for (size_t i = 0; i < sizeof(bt_device_class_t); ++i) {
+    data[i] = dc->_[i];
+  }
+  return sizeof(bt_device_class_t);
+}
+
+void device_class_from_int(bt_device_class_t *dc, int data) {
+  assert(dc != NULL);
+  assert(data != 0);
+  // Careful with endianess.
+  dc->_[0] = data & 0xff;
+  dc->_[1] = (data >> 8) & 0xff;
+  dc->_[2] = (data >> 16) & 0xff;
+}
+
+int device_class_to_int(const bt_device_class_t *dc) {
+  assert(dc != NULL);
+  // Careful with endianess.
+  return (int)(le32toh(*(int*)dc) & 0xffffff);
+}
+
+bool device_class_equals(const bt_device_class_t *p1, const bt_device_class_t *p2) {
+  assert(p1 != NULL);
+  assert(p2 != NULL);
+  return (memcmp(p1, p2, sizeof(bt_device_class_t)) == 0);
+}
+
+bool device_class_copy(bt_device_class_t *dest, const bt_device_class_t *src) {
+  assert(dest != NULL);
+  assert(src != NULL);
+  return (memcpy(dest, src, sizeof(bt_device_class_t)) == dest);
+}
+
+int device_class_get_major_device(const bt_device_class_t *dc) {
+  assert(dc != NULL);
+  return DC(dc)->major_device;
+}
+
+void device_class_set_major_device(bt_device_class_t *dc, int val) {
+  assert(dc != NULL);
+  DC(dc)->major_device = val;
+}
+
+int device_class_get_minor_device(const bt_device_class_t *dc) {
+  assert(dc != NULL);
+  return DC(dc)->minor_device;
+}
+
+void device_class_set_minor_device(bt_device_class_t *dc, int val) {
+  assert(dc != NULL);
+  DC(dc)->minor_device = val;
+}
+
+bool device_class_get_information(const bt_device_class_t *dc) {
+  assert(dc != NULL);
+  return device_class_get_major_service_(dc, DC_INFORMATION);
+}
+
+void device_class_set_information(bt_device_class_t *dc, bool set) {
+  assert(dc != NULL);
+  if (set)
+    device_class_set_major_service_(dc, DC_INFORMATION);
+  else
+    device_class_clr_major_service_(dc, DC_INFORMATION);
+}
+
+bool device_class_get_limited(const bt_device_class_t *dc) {
+  assert(dc != NULL);
+  return device_class_get_major_service_(dc, DC_LIMITED_DISCOVERABLE_MODE);
+}
+
+void device_class_set_limited(bt_device_class_t *dc, bool set) {
+  assert(dc != NULL);
+  if (set)
+    device_class_set_major_service_(dc, DC_LIMITED_DISCOVERABLE_MODE);
+  else
+    device_class_clr_major_service_(dc, DC_LIMITED_DISCOVERABLE_MODE);
+}
+
+static bool device_class_get_major_service_(const bt_device_class_t *dc, int bitmask) {
+  return (DC(dc)->major_service & bitmask);
+}
+
+static void device_class_clr_major_service_(bt_device_class_t *dc, int bitmask) {
+  DC(dc)->major_service &= ~bitmask;
+}
+
+static void device_class_set_major_service_(bt_device_class_t *dc, int bitmask) {
+  DC(dc)->major_service |= bitmask;
+}
diff --git a/btcore/src/module.c b/btcore/src/module.c
new file mode 100644
index 0000000..5f3902e
--- /dev/null
+++ b/btcore/src/module.c
@@ -0,0 +1,226 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_core_module"
+
+#include <assert.h>
+#include <dlfcn.h>
+#include <pthread.h>
+
+#include "osi/include/allocator.h"
+#include "osi/include/hash_map.h"
+#include "btcore/include/module.h"
+#include "osi/include/osi.h"
+#include "osi/include/hash_functions.h"
+#include "osi/include/log.h"
+
+typedef enum {
+  MODULE_STATE_NONE = 0,
+  MODULE_STATE_INITIALIZED = 1,
+  MODULE_STATE_STARTED = 2
+} module_state_t;
+
+static const size_t number_of_metadata_buckets = 42;
+static hash_map_t *metadata;
+// Include this lock for now for correctness, while the startup sequence is being refactored
+static pthread_mutex_t metadata_lock;
+
+static bool call_lifecycle_function(module_lifecycle_fn function);
+static module_state_t get_module_state(const module_t *module);
+static void set_module_state(const module_t *module, module_state_t state);
+
+void module_management_start(void) {
+  metadata = hash_map_new(
+    number_of_metadata_buckets,
+    hash_function_pointer,
+    NULL,
+    osi_free,
+    NULL
+  );
+
+  pthread_mutex_init(&metadata_lock, NULL);
+}
+
+void module_management_stop(void) {
+  if (!metadata)
+    return;
+
+  hash_map_free(metadata);
+  metadata = NULL;
+
+  pthread_mutex_destroy(&metadata_lock);
+}
+
+const module_t *get_module(const char *name) {
+  return (module_t *)dlsym(RTLD_DEFAULT, name);
+}
+
+bool module_init(const module_t *module) {
+  assert(metadata != NULL);
+  assert(module != NULL);
+  assert(get_module_state(module) == MODULE_STATE_NONE);
+
+  if (!call_lifecycle_function(module->init)) {
+    LOG_ERROR("%s failed to initialize \"%s\"", __func__, module->name);
+    return false;
+  }
+
+  set_module_state(module, MODULE_STATE_INITIALIZED);
+  return true;
+}
+
+bool module_start_up(const module_t *module) {
+  assert(metadata != NULL);
+  assert(module != NULL);
+  // TODO(zachoverflow): remove module->init check once automagic order/call is in place.
+  // This hack is here so modules which don't require init don't have to have useless calls
+  // as we're converting the startup sequence.
+  assert(get_module_state(module) == MODULE_STATE_INITIALIZED || module->init == NULL);
+
+  if (!call_lifecycle_function(module->start_up)) {
+    LOG_ERROR("%s failed to start up \"%s\"", __func__, module->name);
+    return false;
+  }
+
+  set_module_state(module, MODULE_STATE_STARTED);
+  return true;
+}
+
+void module_shut_down(const module_t *module) {
+  assert(metadata != NULL);
+  assert(module != NULL);
+  module_state_t state = get_module_state(module);
+  assert(state <= MODULE_STATE_STARTED);
+
+  // Only something to do if the module was actually started
+  if (state < MODULE_STATE_STARTED)
+    return;
+
+  if (!call_lifecycle_function(module->shut_down))
+    LOG_ERROR("%s found \"%s\" reported failure during shutdown. Continuing anyway.", __func__, module->name);
+
+  set_module_state(module, MODULE_STATE_INITIALIZED);
+}
+
+void module_clean_up(const module_t *module) {
+  assert(metadata != NULL);
+  assert(module != NULL);
+  module_state_t state = get_module_state(module);
+  assert(state <= MODULE_STATE_INITIALIZED);
+
+  // Only something to do if the module was actually initialized
+  if (state < MODULE_STATE_INITIALIZED)
+    return;
+
+  if (!call_lifecycle_function(module->clean_up))
+    LOG_ERROR("%s found \"%s\" reported failure during cleanup. Continuing anyway.", __func__, module->name);
+
+  set_module_state(module, MODULE_STATE_NONE);
+}
+
+static bool call_lifecycle_function(module_lifecycle_fn function) {
+  // A NULL lifecycle function means it isn't needed, so assume success
+  if (!function)
+    return true;
+
+  future_t *future = function();
+
+  // A NULL future means synchronous success
+  if (!future)
+    return true;
+
+  // Otherwise fall back to the future
+  return future_await(future);
+}
+
+static module_state_t get_module_state(const module_t *module) {
+  pthread_mutex_lock(&metadata_lock);
+  module_state_t *state_ptr = hash_map_get(metadata, module);
+  pthread_mutex_unlock(&metadata_lock);
+
+  return state_ptr ? *state_ptr : MODULE_STATE_NONE;
+}
+
+static void set_module_state(const module_t *module, module_state_t state) {
+  pthread_mutex_lock(&metadata_lock);
+
+  module_state_t *state_ptr = hash_map_get(metadata, module);
+  if (!state_ptr) {
+    state_ptr = osi_malloc(sizeof(module_state_t));
+    hash_map_set(metadata, module, state_ptr);
+  }
+
+  pthread_mutex_unlock(&metadata_lock);
+
+  *state_ptr = state;
+}
+
+// TODO(zachoverflow): remove when everything modulized
+// Temporary callback-wrapper-related code
+
+typedef struct {
+  const module_t *module;
+  thread_t *lifecycle_thread;
+  thread_t *callback_thread; // we don't own this thread
+  thread_fn callback;
+  bool success;
+} callbacked_wrapper_t;
+
+static void run_wrapped_start_up(void *context);
+static void post_result_to_callback(void *context);
+
+void module_start_up_callbacked_wrapper(
+    const module_t *module,
+    thread_t *callback_thread,
+    thread_fn callback) {
+  callbacked_wrapper_t *wrapper = osi_calloc(sizeof(callbacked_wrapper_t));
+
+  wrapper->module = module;
+  wrapper->lifecycle_thread = thread_new("module_wrapper");
+  wrapper->callback_thread = callback_thread;
+  wrapper->callback = callback;
+
+  // Run the actual module start up
+  thread_post(wrapper->lifecycle_thread, run_wrapped_start_up, wrapper);
+}
+
+static void run_wrapped_start_up(void *context) {
+  assert(context);
+
+  callbacked_wrapper_t *wrapper = context;
+  wrapper->success = module_start_up(wrapper->module);
+
+  // Post the result back to the callback
+  thread_post(wrapper->callback_thread, post_result_to_callback, wrapper);
+}
+
+static void post_result_to_callback(void *context) {
+  assert(context);
+
+  callbacked_wrapper_t *wrapper = context;
+
+  // Save the values we need for callback
+  void *result = wrapper->success ? FUTURE_SUCCESS : FUTURE_FAIL;
+  thread_fn callback = wrapper->callback;
+
+  // Clean up the resources we used
+  thread_stop(wrapper->lifecycle_thread);
+  osi_free(wrapper);
+
+  callback(result);
+}
diff --git a/btcore/src/property.c b/btcore/src/property.c
new file mode 100644
index 0000000..ddefb68
--- /dev/null
+++ b/btcore/src/property.c
@@ -0,0 +1,223 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <assert.h>
+#include "btcore/include/bdaddr.h"
+#include "btcore/include/device_class.h"
+#include "btcore/include/property.h"
+#include "btcore/include/uuid.h"
+#include "osi/include/allocator.h"
+
+static bt_property_t *property_new_(void *val, size_t len, bt_property_type_t type);
+
+bt_property_t *property_copy_array(const bt_property_t *properties, size_t count) {
+  assert(properties != NULL);
+  bt_property_t *clone = osi_calloc(sizeof(bt_property_t) * count);
+  if (!clone) {
+    return NULL;
+  }
+
+  memcpy(&clone[0], &properties[0], sizeof(bt_property_t) * count);
+  for (size_t i = 0; i < count; ++i) {
+    clone[i].val = osi_calloc(clone[i].len);
+    memcpy(clone[i].val, properties[i].val, clone[i].len);
+  }
+
+  return clone;
+}
+
+bt_property_t *property_copy(bt_property_t *dest, const bt_property_t *src) {
+  assert(dest != NULL);
+  assert(src != NULL);
+  return (bt_property_t *)memcpy(dest, src, sizeof(bt_property_t));
+}
+
+bool property_equals(const bt_property_t *p1, const bt_property_t *p2) {
+  // Two null properties are not the same. May need to revisit that
+  // decision when we have a test case that exercises that condition.
+  if (!p1 || !p2 || p1->type != p2->type) {
+    return false;
+  }
+
+  // Although the Bluetooth name is a 249-byte array, the implementation
+  // treats it like a variable-length array with its size specified in the
+  // property's `len` field. We special-case the equivalence of BDNAME
+  // types here by truncating the larger, zero-padded name to its string
+  // length and comparing against the shorter name.
+  //
+  // Note: it may be the case that both strings are zero-padded but that
+  // hasn't come up yet so this implementation doesn't handle it.
+  if (p1->type == BT_PROPERTY_BDNAME && p1->len != p2->len) {
+    const bt_property_t *shorter = p1, *longer = p2;
+    if (p1->len > p2->len) {
+      shorter = p2;
+      longer = p1;
+    }
+    return strlen((const char *)longer->val) == (size_t)shorter->len && !memcmp(longer->val, shorter->val, shorter->len);
+  }
+
+  return p1->len == p2->len && !memcmp(p1->val, p2->val, p1->len);
+}
+
+bt_property_t *property_new_addr(const bt_bdaddr_t *addr) {
+  assert(addr != NULL);
+  return property_new_((void *)addr, sizeof(bt_bdaddr_t), BT_PROPERTY_BDADDR);
+}
+
+bt_property_t *property_new_device_class(const bt_device_class_t *dc) {
+  assert(dc != NULL);
+  return property_new_((void *)dc, sizeof(bt_device_class_t), BT_PROPERTY_CLASS_OF_DEVICE);
+}
+
+bt_property_t *property_new_device_type(bt_device_type_t type) {
+  return property_new_((void *)&type, sizeof(bt_device_type_t), BT_PROPERTY_TYPE_OF_DEVICE);
+}
+
+bt_property_t *property_new_discovery_timeout(const uint32_t timeout) {
+  return property_new_((void *)&timeout, sizeof(uint32_t), BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT);
+}
+
+bt_property_t *property_new_name(const char *name) {
+  assert(name != NULL);
+  return property_new_((void *)name, sizeof(bt_bdname_t), BT_PROPERTY_BDNAME);
+}
+
+bt_property_t *property_new_rssi(int8_t rssi) {
+  return property_new_((void *)&rssi, sizeof(int8_t), BT_PROPERTY_REMOTE_RSSI);
+}
+
+bt_property_t *property_new_scan_mode(bt_scan_mode_t scan_mode) {
+  return property_new_((void *)&scan_mode, sizeof(bt_scan_mode_t), BT_PROPERTY_ADAPTER_SCAN_MODE);
+}
+
+bt_property_t *property_new_uuids(const bt_uuid_t *uuid, size_t count) {
+  assert(uuid != NULL);
+  return property_new_((void *)uuid, sizeof(bt_uuid_t) * count, BT_PROPERTY_UUIDS);
+}
+
+void property_free(bt_property_t *property) {
+  property_free_array(property, 1);
+}
+
+void property_free_array(bt_property_t *properties, size_t count) {
+  if (properties == NULL)
+    return;
+
+  for (size_t i = 0; i < count; ++i) {
+    osi_free(properties[i].val);
+  }
+
+  osi_free(properties);
+}
+
+bool property_is_addr(const bt_property_t *property) {
+  assert(property != NULL);
+  return property->type == BT_PROPERTY_BDADDR;
+}
+
+bool property_is_device_class(const bt_property_t *property) {
+  assert(property != NULL);
+  return property->type == BT_PROPERTY_CLASS_OF_DEVICE;
+}
+
+bool property_is_device_type(const bt_property_t *property) {
+  assert(property != NULL);
+  return property->type == BT_PROPERTY_TYPE_OF_DEVICE;
+}
+
+bool property_is_discovery_timeout(const bt_property_t *property) {
+  assert(property != NULL);
+  return property->type == BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT;
+}
+
+bool property_is_name(const bt_property_t *property) {
+  assert(property != NULL);
+  return property->type == BT_PROPERTY_BDNAME;
+}
+
+bool property_is_rssi(const bt_property_t *property) {
+  assert(property != NULL);
+  return property->type == BT_PROPERTY_REMOTE_RSSI;
+}
+
+bool property_is_scan_mode(const bt_property_t *property) {
+  assert(property != NULL);
+  return property->type == BT_PROPERTY_ADAPTER_SCAN_MODE;
+}
+
+bool property_is_uuids(const bt_property_t *property) {
+  assert(property != NULL);
+  return property->type == BT_PROPERTY_UUIDS;
+}
+
+// Convenience conversion methods to property values
+const bt_bdaddr_t *property_as_addr(const bt_property_t *property) {
+  assert(property_is_addr(property));
+  return (const bt_bdaddr_t *)property->val;
+}
+
+const bt_device_class_t *property_as_device_class(const bt_property_t *property) {
+  assert(property_is_device_class(property));
+  return (const bt_device_class_t *)property->val;
+}
+
+bt_device_type_t property_as_device_type(const bt_property_t *property) {
+  assert(property_is_device_type(property));
+  return *(const bt_device_type_t *)property->val;
+}
+
+uint32_t property_as_discovery_timeout(const bt_property_t *property) {
+  assert(property_is_discovery_timeout(property));
+  return *(const uint32_t *)property->val;
+}
+
+const bt_bdname_t *property_as_name(const bt_property_t *property) {
+  assert(property_is_name(property));
+  return (const bt_bdname_t *)property->val;
+}
+
+int8_t property_as_rssi(const bt_property_t *property) {
+  assert(property_is_rssi(property));
+  return *(const int8_t *)property->val;
+}
+
+bt_scan_mode_t property_as_scan_mode(const bt_property_t *property) {
+  assert(property_is_scan_mode(property));
+  return *(const bt_scan_mode_t *)property->val;
+}
+
+const bt_uuid_t *property_as_uuids(const bt_property_t *property, size_t *count) {
+  assert(property_is_uuids(property));
+  *count = sizeof(bt_uuid_t) / property->len;
+  return (const bt_uuid_t *)property->val;
+}
+
+static bt_property_t *property_new_(void *val, size_t len, bt_property_type_t type) {
+  bt_property_t *property = osi_calloc(sizeof(bt_property_t));
+  assert(property != NULL);
+
+  property->val = osi_malloc(len);
+  assert(property->val != NULL);
+
+  memcpy(property->val, val, len);
+
+  property->type = type;
+  property->len = len;
+
+  return property;
+}
diff --git a/btcore/src/uuid.c b/btcore/src/uuid.c
new file mode 100644
index 0000000..bebb63f
--- /dev/null
+++ b/btcore/src/uuid.c
@@ -0,0 +1,166 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "btcore/include/uuid.h"
+#include "osi/include/allocator.h"
+
+static const size_t UUID_WELL_FORMED_STRING_LEN = 36;
+static const size_t UUID_WELL_FORMED_STRING_LEN_WITH_NULL = 36 + 1;
+
+typedef struct uuid_string_t {
+  char string[0];
+} uuid_string_t;
+
+static const bt_uuid_t empty_uuid = {{ 0 }};
+
+// The base UUID is used for calculating 128-bit UUIDs from 16 and
+// 32 bit UUIDs as described in the SDP specification.
+static const bt_uuid_t base_uuid = {
+  { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
+    0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb, }};
+
+static bool uuid_is_base(const bt_uuid_t *uuid);
+
+uuid_string_t *uuid_string_new(void) {
+  return osi_calloc(UUID_WELL_FORMED_STRING_LEN_WITH_NULL);
+}
+
+void uuid_string_free(uuid_string_t *uuid_string) {
+  osi_free(uuid_string);
+}
+
+const char *uuid_string_data(const uuid_string_t *uuid_string) {
+  assert(uuid_string != NULL);
+  return (const char *)uuid_string->string;
+}
+
+bt_uuid_t *uuid_new(const char *uuid_string) {
+  assert(uuid_string != NULL);
+
+  if (strlen(uuid_string) < UUID_WELL_FORMED_STRING_LEN)
+    return NULL;
+  if (uuid_string[8] != '-' || uuid_string[13] != '-' || uuid_string[18] != '-' || uuid_string[23] != '-')
+    return NULL;
+
+  bt_uuid_t *uuid = osi_calloc(sizeof(bt_uuid_t));
+  if (uuid == NULL)
+    return NULL;
+
+  const char *s = uuid_string;
+  for (size_t i = 0; i < sizeof(bt_uuid_t); ++i, s+=2) {
+    char buf[2];
+    buf[0] = s[0];
+    buf[1] = s[1];
+    uuid->uu[i] = strtoul(buf, NULL, 16);
+    // Adjust by skipping the dashes
+    switch(i) {
+      case 3:
+      case 5:
+      case 7:
+      case 9:
+        s++;
+        break;
+    }
+  }
+  return uuid;
+}
+
+void uuid_free(bt_uuid_t *uuid) {
+  osi_free(uuid);
+}
+
+bool uuid_is_empty(const bt_uuid_t *uuid) {
+  return !uuid || !memcmp(uuid, &empty_uuid, sizeof(bt_uuid_t));
+}
+
+bool uuid_is_equal(const bt_uuid_t *first, const bt_uuid_t *second) {
+  assert(first != NULL);
+  assert(second != NULL);
+  return !memcmp(first, second, sizeof(bt_uuid_t));
+}
+
+bt_uuid_t *uuid_copy(bt_uuid_t *dest, const bt_uuid_t *src) {
+  assert(dest != NULL);
+  assert(src != NULL);
+  return (bt_uuid_t *)memcpy(dest, src, sizeof(bt_uuid_t));
+}
+
+bool uuid_128_to_16(const bt_uuid_t *uuid, uint16_t *uuid16) {
+  assert(uuid != NULL);
+  assert(uuid16 != NULL);
+
+  if (!uuid_is_base(uuid))
+    return false;
+
+  *uuid16 = (uuid->uu[2] << 8) + uuid->uu[3];
+  return true;
+}
+
+bool uuid_128_to_32(const bt_uuid_t *uuid, uint32_t *uuid32) {
+  assert(uuid != NULL);
+  assert(uuid32 != NULL);
+
+  if (!uuid_is_base(uuid))
+    return false;
+
+  *uuid32 = (uuid->uu[0] << 24) + (uuid->uu[1] << 16) + (uuid->uu[2] << 8) + uuid->uu[3];
+  return true;
+}
+
+void uuid_to_string(const bt_uuid_t *uuid, uuid_string_t *uuid_string) {
+  assert(uuid != NULL);
+  assert(uuid_string != NULL);
+
+  char *string = uuid_string->string;
+
+  for (int i = 0; i < 4; i++) {
+    string += sprintf(string, "%02x", uuid->uu[i]);
+  }
+  string += sprintf(string, "-");
+  for (int i = 4; i < 6; i++) {
+    string += sprintf(string, "%02x", uuid->uu[i]);
+  }
+  string += sprintf(string, "-");
+  for (int i = 6; i < 8; i++) {
+    string += sprintf(string, "%02x", uuid->uu[i]);
+  }
+  string += sprintf(string, "-");
+  for (int i = 8; i < 10; i++) {
+    string += sprintf(string, "%02x", uuid->uu[i]);
+  }
+  string += sprintf(string, "-");
+  for (int i = 10; i < 16; i++) {
+    string += sprintf(string, "%02x", uuid->uu[i]);
+  }
+}
+
+static bool uuid_is_base(const bt_uuid_t *uuid) {
+  if (!uuid)
+    return false;
+
+  for (int i = 4; i < 16; i++) {
+    if (uuid->uu[i] != base_uuid.uu[i])
+      return false;
+  }
+  return true;
+}
diff --git a/btcore/test/bdaddr_test.cpp b/btcore/test/bdaddr_test.cpp
new file mode 100644
index 0000000..1e7918e
--- /dev/null
+++ b/btcore/test/bdaddr_test.cpp
@@ -0,0 +1,48 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+extern "C" {
+#include "btcore/include/bdaddr.h"
+}
+
+TEST(HashFunctionBdaddrTest, test_same_pointer_is_same) {
+  bt_bdaddr_t test_address;
+  string_to_bdaddr("12:34:56:78:9A:BC", &test_address);
+
+  EXPECT_EQ(hash_function_bdaddr(&test_address), hash_function_bdaddr(&test_address));
+}
+
+TEST(HashFunctionBdaddrTest, test_same_value_is_same) {
+  bt_bdaddr_t test_address0;
+  bt_bdaddr_t test_address1;
+  string_to_bdaddr("12:34:56:78:9A:BC", &test_address0);
+  string_to_bdaddr("12:34:56:78:9A:BC", &test_address1);
+
+  EXPECT_EQ(hash_function_bdaddr(&test_address0), hash_function_bdaddr(&test_address1));
+}
+
+TEST(HashFunctionBdaddrTest, test_different_value_is_different) {
+  bt_bdaddr_t test_address0;
+  bt_bdaddr_t test_address1;
+  string_to_bdaddr("12:34:56:78:9A:BC", &test_address0);
+  string_to_bdaddr("43:56:21:78:9A:BC", &test_address1);
+
+  EXPECT_NE(hash_function_bdaddr(&test_address0), hash_function_bdaddr(&test_address1));
+}
diff --git a/btcore/test/counter_test.cpp b/btcore/test/counter_test.cpp
new file mode 100644
index 0000000..e16135d
--- /dev/null
+++ b/btcore/test/counter_test.cpp
@@ -0,0 +1,103 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+#include "osi/test/AllocationTestHarness.h"
+
+extern "C" {
+#include "btcore/include/counter.h"
+#include "btcore/include/module.h"
+
+extern module_t counter_module;
+}  // "C"
+
+static const uint64_t COUNTER_TEST_TEN = 10;
+static const uint64_t COUNTER_TEST_ZERO = 0;
+
+typedef struct mycounter_t {
+  const char *name;
+  uint64_t val;
+  bool found;
+} mycounter_t;
+
+static bool counter_iter(const char *name, counter_data_t val, void *context) {
+  mycounter_t *mycounter = (mycounter_t *)context;
+  if (!strcmp(name, mycounter->name)) {
+    mycounter->val = val;
+    mycounter->found = true;
+    return false;
+  }
+  return true;
+}
+
+static bool find_val(const char *name, uint64_t *val) {
+  mycounter_t mycounter;
+
+  mycounter.val = 0;
+  mycounter.name = name;
+  mycounter.found = false;
+  counter_foreach(counter_iter, &mycounter);
+  *val = mycounter.val;
+  if (mycounter.found)
+    return true;
+  return false;
+}
+
+class CounterTest : public AllocationTestHarness {
+  protected:
+    virtual void SetUp() {
+      counter_module.init();
+    }
+
+    virtual void TearDown() {
+      counter_module.clean_up();
+    }
+};
+
+TEST_F(CounterTest, counter_no_exist) {
+  uint64_t val;
+
+  EXPECT_FALSE(find_val("one.two.three", &val));
+}
+
+TEST_F(CounterTest, counter_inc_dec) {
+  uint64_t val;
+
+  counter_add("one.two.three", 1);
+
+  EXPECT_TRUE(find_val("one.two.three", &val));
+  EXPECT_EQ((uint64_t)1, val);
+
+  counter_add("one.two.three", 1);
+  EXPECT_TRUE(find_val("one.two.three", &val));
+  EXPECT_EQ((uint64_t)2, val);
+
+  counter_add("one.two.three", -1);
+  EXPECT_TRUE(find_val("one.two.three", &val));
+  EXPECT_EQ((uint64_t)1, val);
+}
+
+TEST_F(CounterTest, counter_get_set) {
+  uint64_t val;
+
+  counter_set("one.two.three", COUNTER_TEST_TEN);
+  EXPECT_TRUE(find_val("one.two.three", &val));
+  EXPECT_EQ(COUNTER_TEST_TEN, val);
+
+  EXPECT_FALSE(find_val("foo.bar", &val));
+}
diff --git a/btcore/test/device_class_test.cpp b/btcore/test/device_class_test.cpp
new file mode 100644
index 0000000..c3098a2
--- /dev/null
+++ b/btcore/test/device_class_test.cpp
@@ -0,0 +1,220 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <arpa/inet.h>
+#include <gtest/gtest.h>
+#include "osi/test/AllocationTestHarness.h"
+
+extern "C" {
+#include "btcore/include/device_class.h"
+}  // "C"
+
+// Device Class is 3 bytes.
+static const int DC_MASK = 0xffffff;
+
+::testing::AssertionResult check_bitfield(const char *m_expr,
+    const char *n_expr, int m, int n) {
+  if (m == n)
+    return ::testing::AssertionSuccess();
+
+  std::stringstream ss;
+
+  ss.str("");
+  ss << std::showbase << std::hex << std::setw(8) << std::setfill('0') << m;
+  std::string expected_str = ss.str();
+
+  ss.str("");
+  ss << std::showbase << std::hex << std::setw(8) << std::setfill('0') << n;
+  std::string actual_str = ss.str();
+
+  return ::testing::AssertionFailure() << m_expr << " and " << n_expr
+    << " ( " << expected_str << " vs " << actual_str << " )";
+}
+
+class DeviceClassTest : public AllocationTestHarness {};
+
+TEST_F(DeviceClassTest, cod_sizeof) {
+  uint8_t dc_stream[] = { 0x00, 0x00, 0x00, 0x00};
+  bt_device_class_t dc0;
+  device_class_from_stream(&dc0, dc_stream);
+  EXPECT_EQ((size_t)3, sizeof(dc0));
+}
+
+TEST_F(DeviceClassTest, simple) {
+  uint8_t dc_stream[][sizeof(bt_device_class_t)] = {
+    { 0x00, 0x00, 0x00 },
+    { 0xff, 0xff, 0xff },
+    { 0xaa, 0x55, 0xaa },
+    { 0x01, 0x23, 0x45 },
+    { 0x20, 0x07, 0x14 },
+  };
+
+  for (size_t i = 0; i < sizeof(dc_stream)/sizeof(bt_device_class_t); i++) {
+    bt_device_class_t dc;
+    device_class_from_stream(&dc, (uint8_t*)&dc_stream[i]);
+
+    uint8_t *to_stream = (uint8_t *)&dc;
+    EXPECT_PRED_FORMAT2(check_bitfield, (unsigned)dc_stream[i][0], to_stream[0]);
+    EXPECT_PRED_FORMAT2(check_bitfield, (unsigned)dc_stream[i][1], to_stream[1]);
+    EXPECT_PRED_FORMAT2(check_bitfield, (unsigned)dc_stream[i][2], to_stream[2]);
+  }
+}
+
+TEST_F(DeviceClassTest, to_stream) {
+  {
+    bt_device_class_t dc;
+
+    uint8_t dc_stream0[] = { 0x00, 0x00, 0x00, 0xaa };
+    device_class_from_stream(&dc, dc_stream0);
+
+    uint8_t dc_stream1[] = { 0x00, 0x00, 0x00, 0x00 };
+    int rc = device_class_to_stream(&dc, dc_stream1, sizeof(dc_stream1));
+    EXPECT_EQ(3, rc);
+
+    uint32_t *val = (uint32_t *)&dc;
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x00000000, *val & 0xffffff);
+
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x00, dc_stream1[0]);
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x00, dc_stream1[1]);
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x00, dc_stream1[2]);
+  }
+
+  {
+    uint8_t dc_stream0[] = { 0xaa, 0x55, 0xaa, 0x55 };
+    uint8_t dc_stream1[] = { 0x00, 0x00, 0x00, 0x00 };
+
+    bt_device_class_t dc;
+    device_class_from_stream(&dc, dc_stream0);
+
+    int rc = device_class_to_stream(&dc, dc_stream1, sizeof(dc_stream1));
+    EXPECT_EQ(3, rc);
+    uint32_t *val = (uint32_t *)&dc;
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x00aa55aa, *val & 0xffffff);
+
+    EXPECT_PRED_FORMAT2(check_bitfield, 0xaa, dc_stream1[0]);
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x55, dc_stream1[1]);
+    EXPECT_PRED_FORMAT2(check_bitfield, 0xaa, dc_stream1[2]);
+  }
+
+  {
+    uint8_t dc_stream0[] = { 0x01, 0x23, 0x45, 0x67 };
+    uint8_t dc_stream1[] = { 0x00, 0x00, 0x00, 0x00 };
+
+    bt_device_class_t dc;
+    device_class_from_stream(&dc, dc_stream0);
+
+    int rc = device_class_to_stream(&dc, dc_stream1, sizeof(dc_stream1));
+    EXPECT_EQ(3, rc);
+    uint32_t *val = (uint32_t *)&dc;
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x452301, *val & 0xffffff);
+
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x01, dc_stream1[0]);
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x23, dc_stream1[1]);
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x45, dc_stream1[2]);
+  }
+}
+
+TEST_F(DeviceClassTest, limited_discoverable_mode) {
+  uint8_t dc_stream[] = { 0x00, 0x00, 0x00 };
+  bt_device_class_t dc;
+  device_class_from_stream(&dc, dc_stream);
+  uint32_t *test = (uint32_t *)&dc;
+
+  EXPECT_FALSE(device_class_get_limited(&dc));
+  EXPECT_EQ((unsigned)0x00000000, *test & DC_MASK);
+
+  device_class_set_limited(&dc, true);
+  EXPECT_TRUE(device_class_get_limited(&dc));
+  EXPECT_EQ((unsigned)0x00002000, *test & DC_MASK);
+
+  device_class_set_limited(&dc, false);
+  EXPECT_FALSE(device_class_get_limited(&dc));
+  EXPECT_EQ((unsigned)0x00000000, *test & DC_MASK);
+
+  device_class_set_limited(&dc, true);
+  EXPECT_PRED_FORMAT2(check_bitfield, 0x00002000, *test & DC_MASK);
+
+  device_class_set_limited(&dc, false);
+  EXPECT_PRED_FORMAT2(check_bitfield, 0x00000000, *test & DC_MASK);
+}
+
+TEST_F(DeviceClassTest, equals) {
+  uint8_t dc_stream0[] = { 0x00, 0x01, 0x02 };
+  uint8_t dc_stream1[] = { 0x00, 0x02, 0x03 };
+
+  bt_device_class_t dc0;
+  device_class_from_stream(&dc0, dc_stream0);
+  bt_device_class_t dc1;
+  device_class_from_stream(&dc1, dc_stream1);
+  EXPECT_FALSE(device_class_equals(&dc0, &dc1));
+}
+
+TEST_F(DeviceClassTest, copy) {
+  uint8_t dc_stream0[] = { 0xaa, 0x55, 0x33 };
+  bt_device_class_t dc0;
+  device_class_from_stream(&dc0, dc_stream0);
+  bt_device_class_t dc1;
+  EXPECT_TRUE(device_class_copy(&dc1, &dc0));
+  EXPECT_TRUE(device_class_equals(&dc0, &dc1));
+}
+
+TEST_F(DeviceClassTest, from_int) {
+  bt_device_class_t dc1;
+  int cod1 = 0x5a020c;  // 5898764
+  device_class_from_int(&dc1, cod1);
+
+  uint8_t dc_stream[] = { 0x0c, 0x02, 0x5a };
+  bt_device_class_t dc2;
+  device_class_from_stream(&dc2, dc_stream);
+  EXPECT_TRUE(device_class_equals(&dc1, &dc2));
+}
+
+TEST_F(DeviceClassTest, to_int) {
+  bt_device_class_t dc1 = {{ 0x0c, 0x02, 0x5a }};
+  int cod1 = device_class_to_int(&dc1);
+
+  EXPECT_EQ(dc1._[0], 0x0c);
+  EXPECT_EQ(dc1._[1], 0x02);
+  EXPECT_EQ(dc1._[2], 0x5a);
+
+  bt_device_class_t dc2;
+  uint8_t dc_stream[] = { 0x0c, 0x02, 0x5a };
+  device_class_from_stream(&dc2, dc_stream);
+
+  EXPECT_EQ(dc2._[0], 0x0c);
+  EXPECT_EQ(dc2._[1], 0x02);
+  EXPECT_EQ(dc2._[2], 0x5a);
+
+  int cod2 = device_class_to_int(&dc2);
+  EXPECT_EQ(cod1, cod2);
+  EXPECT_EQ(cod1, 0x5a020c);  // 5898764
+}
+
+TEST_F(DeviceClassTest, endian) {
+  bt_device_class_t dc;
+  int cod1 = 0x200714;  // 2098964
+  device_class_from_int(&dc, cod1);
+
+  EXPECT_EQ(dc._[0], 0x14);
+  EXPECT_EQ(dc._[1], 0x07);
+  EXPECT_EQ(dc._[2], 0x20);
+
+  int cod2 = device_class_to_int(&dc);
+  EXPECT_EQ(cod1, cod2);
+  EXPECT_EQ(cod2, 0x200714); // 2098964
+}
diff --git a/btcore/test/property_test.cpp b/btcore/test/property_test.cpp
new file mode 100644
index 0000000..8032e97
--- /dev/null
+++ b/btcore/test/property_test.cpp
@@ -0,0 +1,247 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <arpa/inet.h>
+#include <gtest/gtest.h>
+#include "osi/test/AllocationTestHarness.h"
+
+extern "C" {
+#include "btcore/include/property.h"
+}  // "C"
+
+class PropertyTest : public AllocationTestHarness {};
+
+TEST_F(PropertyTest, addr) {
+  bt_bdaddr_t addr0 = {{0x1, 0x2, 0x3, 0x4, 0x5, 0x6}};
+  bt_property_t *property = property_new_addr(&addr0);
+
+  EXPECT_EQ(addr0.address[0], ((uint8_t*)property->val)[0]);
+  EXPECT_EQ(addr0.address[1], ((uint8_t*)property->val)[1]);
+  EXPECT_EQ(addr0.address[2], ((uint8_t*)property->val)[2]);
+  EXPECT_EQ(addr0.address[3], ((uint8_t*)property->val)[3]);
+  EXPECT_EQ(addr0.address[4], ((uint8_t*)property->val)[4]);
+  EXPECT_EQ(addr0.address[5], ((uint8_t*)property->val)[5]);
+  EXPECT_EQ(BT_PROPERTY_BDADDR, property->type);
+  EXPECT_EQ((int)sizeof(bt_bdaddr_t), property->len);
+
+  const bt_bdaddr_t *addr1 = property_as_addr(property);
+  EXPECT_EQ(addr0.address[0], addr1->address[0]);
+
+  property_free(property);
+}
+
+TEST_F(PropertyTest, device_class) {
+  bt_device_class_t dc0 = {{ 0x01, 0x23, 0x45 }};
+  bt_property_t *property = property_new_device_class(&dc0);
+
+  EXPECT_EQ(dc0._[0], ((uint8_t*)property->val)[0]);
+  EXPECT_EQ(dc0._[1], ((uint8_t*)property->val)[1]);
+  EXPECT_EQ(dc0._[2], ((uint8_t*)property->val)[2]);
+  EXPECT_EQ(BT_PROPERTY_CLASS_OF_DEVICE, property->type);
+  EXPECT_EQ((int)sizeof(bt_device_class_t), property->len);
+
+  const bt_device_class_t *dc1 = property_as_device_class(property);
+  int dc_int = device_class_to_int(dc1);
+  EXPECT_EQ(0x452301, dc_int);
+
+  property_free(property);
+}
+
+TEST_F(PropertyTest, device_type) {
+  bt_device_type_t dt0 = (bt_device_type_t)1;
+  bt_property_t *property = property_new_device_type(dt0);
+
+  EXPECT_EQ((int)dt0, *(int*)property->val);
+  EXPECT_EQ(BT_PROPERTY_TYPE_OF_DEVICE, property->type);
+  EXPECT_EQ((int)sizeof(bt_device_type_t), property->len);
+
+  bt_device_type_t dt1 = property_as_device_type(property);
+  EXPECT_EQ(1, (int)dt1);
+
+  property_free(property);
+}
+
+TEST_F(PropertyTest, discovery_timeout) {
+  uint32_t timeout0 = 12345;
+  bt_property_t *property = property_new_discovery_timeout(timeout0);
+
+  EXPECT_EQ(timeout0, *(uint32_t *)property->val);
+  EXPECT_EQ(BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT, property->type);
+  EXPECT_EQ((int)sizeof(uint32_t), property->len);
+
+  uint32_t timeout1 = property_as_discovery_timeout(property);
+  EXPECT_EQ(timeout0, timeout1);
+
+  property_free(property);
+}
+
+TEST_F(PropertyTest, name) {
+  const char *name0 = "My btcore name";
+  bt_property_t *property = property_new_name(name0);
+
+  EXPECT_EQ(0, strcmp((char *)name0, (char *)property->val));
+  EXPECT_EQ(BT_PROPERTY_BDNAME, property->type);
+  EXPECT_EQ((int)sizeof(bt_bdname_t), property->len);
+
+  const bt_bdname_t *name1 = property_as_name(property);
+  EXPECT_EQ(0, strcmp((char *)name0, (char *)name1->name));
+
+  property_free(property);
+}
+
+TEST_F(PropertyTest, rssi) {
+  int8_t rssi0 = -56;
+  bt_property_t *property = property_new_rssi(rssi0);
+
+  EXPECT_EQ(*(int8_t *)property->val, rssi0);
+  EXPECT_EQ(BT_PROPERTY_REMOTE_RSSI, property->type);
+  EXPECT_EQ((int)sizeof(int8_t), property->len);
+
+  int8_t rss1 = property_as_rssi(property);
+  EXPECT_EQ(rssi0, rss1);
+
+  property_free(property);
+}
+
+TEST_F(PropertyTest, scan_mode) {
+  bt_scan_mode_t mode0 = (bt_scan_mode_t)3;
+  bt_property_t *property = property_new_scan_mode(mode0);
+
+  EXPECT_EQ(*(int *)property->val, mode0);
+  EXPECT_EQ(BT_PROPERTY_ADAPTER_SCAN_MODE, property->type);
+  EXPECT_EQ((int)sizeof(int), property->len);
+
+  bt_scan_mode_t mode1 = property_as_scan_mode(property);
+  EXPECT_EQ((int)mode0, (int)mode1);
+
+  property_free(property);
+}
+
+TEST_F(PropertyTest, uuids) {
+  bt_uuid_t uuid0 = {
+    {
+      0x00, 0x11, 0x22, 0x33,
+      0x44, 0x55, 0x66, 0x77,
+      0x88, 0x99, 0xaa, 0xbb,
+      0xcc, 0xdd, 0xee, 0xff,
+    }
+  };
+  bt_property_t *property = property_new_uuids(&uuid0, 1);
+
+  EXPECT_EQ(0, strcmp((const char *)uuid0.uu, (char *)property->val));
+  EXPECT_EQ(BT_PROPERTY_UUIDS, property->type);
+  EXPECT_EQ((int)sizeof(bt_uuid_t), property->len);
+
+  size_t uuid_cnt1;
+  const bt_uuid_t *uuid1 = property_as_uuids(property, &uuid_cnt1);
+  EXPECT_EQ(0, memcmp(uuid1->uu, uuid1->uu, sizeof(bt_uuid_t)));
+
+  property_free(property);
+}
+
+TEST_F(PropertyTest, copy) {
+  {
+    bt_uuid_t uuids[] = {
+      {{
+         0x00, 0x11, 0x22, 0x33,
+         0x44, 0x55, 0x66, 0x77,
+         0x88, 0x99, 0xaa, 0xbb,
+         0xcc, 0xdd, 0xee, 0xff,
+       }},
+      {{
+         0xf0, 0xe1, 0xd2, 0xc3,
+         0xf4, 0xe5, 0xd6, 0xc7,
+         0xf8, 0xe9, 0xda, 0xcb,
+         0xfc, 0xed, 0xde, 0xcf,
+       }},
+    };
+
+    bt_property_t *property0 = property_new_uuids(uuids, sizeof(bt_uuid_t)/sizeof(uuids));
+
+    bt_property_t property1;
+    property_copy(&property1, property0);
+    EXPECT_TRUE(property_equals(property0, &property1));
+
+    property_free(property0);
+  }
+}
+
+TEST_F(PropertyTest, equals) {
+  {
+    bt_bdaddr_t addr0 = {{0x1, 0x2, 0x3, 0x4, 0x5, 0x6}};
+    bt_property_t *property0 = property_new_addr(&addr0);
+
+    bt_device_class_t dc0 = {{ 0x01, 0x23, 0x45 }};
+    bt_property_t *property1 = property_new_device_class(&dc0);
+
+    EXPECT_FALSE(property_equals(property0, property1));
+
+    property_free(property0);
+    property_free(property1);
+  }
+
+  {
+    bt_bdaddr_t addr = {{0x1, 0x2, 0x3, 0x4, 0x5, 0x6}};
+    bt_property_t *property0 = property_new_addr(&addr);
+    bt_property_t *property1 = property_new_addr(&addr);
+
+    EXPECT_TRUE(property_equals(property0, property1));
+
+    property_free(property0);
+    property_free(property1);
+  }
+
+  {
+    bt_bdaddr_t addr0 = {{0x1, 0x2, 0x3, 0x4, 0x5, 0x6}};
+    bt_property_t *property0 = property_new_addr(&addr0);
+
+    bt_bdaddr_t addr1 = {{0x1, 0x2, 0x3, 0x4, 0x5, 0xff}};
+    bt_property_t *property1 = property_new_addr(&addr1);
+
+    EXPECT_FALSE(property_equals(property0, property1));
+
+    property_free(property0);
+    property_free(property1);
+  }
+
+  {
+    const char *name0 = "My btcore name";
+    bt_property_t *property0 = property_new_name(name0);
+
+    const char *name1 = "My btcore name";
+    bt_property_t *property1 = property_new_name(name1);
+
+    EXPECT_TRUE(property_equals(property0, property1));
+
+    property_free(property0);
+    property_free(property1);
+  }
+
+  {
+    const char *name0 = "My btcore name";
+    bt_property_t *property0 = property_new_name(name0);
+
+    const char *name1 = "My btcore name     ";
+    bt_property_t *property1 = property_new_name(name1);
+
+    EXPECT_FALSE(property_equals(property0, property1));
+
+    property_free(property0);
+    property_free(property1);
+  }
+}
diff --git a/btcore/test/uuid_test.cpp b/btcore/test/uuid_test.cpp
new file mode 100644
index 0000000..7b3e788
--- /dev/null
+++ b/btcore/test/uuid_test.cpp
@@ -0,0 +1,166 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+#include "osi/test/AllocationTestHarness.h"
+
+extern "C" {
+#include "btcore/include/uuid.h"
+}
+
+static const char *UUID_EMPTY = "00000000-0000-0000-0000-000000000000";
+static const char *UUID_ONES = "11111111-1111-1111-1111-111111111111";
+static const char *UUID_SEQUENTIAL = "01234567-89ab-cdef-ABCD-EF0123456789";
+static const char *UUID_BASE = "00000000-0000-1000-8000-00805f9b34fb";
+
+class UuidTest : public AllocationTestHarness {
+  protected:
+    virtual void SetUp() {
+    }
+
+    virtual void TearDown() {
+    }
+};
+
+TEST_F(UuidTest, new_from_string) {
+  bt_uuid_t *uuid;
+
+  uuid = uuid_new("incorrect length");
+  EXPECT_EQ(NULL, uuid);
+
+  uuid = uuid_new("correct length but missing dashes --");
+  EXPECT_EQ(NULL, uuid);
+
+  uuid = uuid_new(UUID_ONES);
+  ASSERT_TRUE(uuid != NULL);
+  for (int i = 0; i < 16; i++) {
+    EXPECT_EQ(0x11, uuid->uu[i]);
+  }
+  uuid_free(uuid);
+
+  uuid = uuid_new(UUID_SEQUENTIAL);
+  EXPECT_EQ(0x01, uuid->uu[0]);
+  EXPECT_EQ(0x23, uuid->uu[1]);
+  EXPECT_EQ(0x45, uuid->uu[2]);
+  EXPECT_EQ(0x67, uuid->uu[3]);
+  EXPECT_EQ(0x89, uuid->uu[4]);
+  EXPECT_EQ(0xAB, uuid->uu[5]);
+  EXPECT_EQ(0xCD, uuid->uu[6]);
+  EXPECT_EQ(0xEF, uuid->uu[7]);
+  EXPECT_EQ(0xab, uuid->uu[8]);
+  EXPECT_EQ(0xcd, uuid->uu[9]);
+  EXPECT_EQ(0xef, uuid->uu[10]);
+  EXPECT_EQ(0x01, uuid->uu[11]);
+  EXPECT_EQ(0x23, uuid->uu[12]);
+  EXPECT_EQ(0x45, uuid->uu[13]);
+  EXPECT_EQ(0x67, uuid->uu[14]);
+  EXPECT_EQ(0x89, uuid->uu[15]);
+  uuid_free(uuid);
+
+  uuid = uuid_new(UUID_BASE);
+  EXPECT_EQ(0x00, uuid->uu[0]);
+  EXPECT_EQ(0x00, uuid->uu[1]);
+  EXPECT_EQ(0x00, uuid->uu[2]);
+  EXPECT_EQ(0x00, uuid->uu[3]);
+  EXPECT_EQ(0x00, uuid->uu[4]);
+  EXPECT_EQ(0x00, uuid->uu[5]);
+  EXPECT_EQ(0x10, uuid->uu[6]);
+  EXPECT_EQ(0x00, uuid->uu[7]);
+  EXPECT_EQ(0x80, uuid->uu[8]);
+  EXPECT_EQ(0x00, uuid->uu[9]);
+  EXPECT_EQ(0x00, uuid->uu[10]);
+  EXPECT_EQ(0x80, uuid->uu[11]);
+  EXPECT_EQ(0x5f, uuid->uu[12]);
+  EXPECT_EQ(0x9b, uuid->uu[13]);
+  EXPECT_EQ(0x34, uuid->uu[14]);
+  EXPECT_EQ(0xfb, uuid->uu[15]);
+  uuid_free(uuid);
+}
+
+TEST_F(UuidTest, uuid_is_empty) {
+  bt_uuid_t *uuid = NULL;
+
+  uuid = uuid_new(UUID_EMPTY);
+  ASSERT_TRUE(uuid != NULL);
+  EXPECT_TRUE(uuid_is_empty(uuid));
+  uuid_free(uuid);
+
+  uuid = uuid_new(UUID_BASE);
+  ASSERT_TRUE(uuid != NULL);
+  EXPECT_FALSE(uuid_is_empty(uuid));
+  uuid_free(uuid);
+}
+
+TEST_F(UuidTest, uuid_128_to_16) {
+  bt_uuid_t *uuid = NULL;
+  uint16_t uuid16 = 0xffff;
+
+  uuid = uuid_new(UUID_ONES);
+  EXPECT_FALSE(uuid_128_to_16(uuid, &uuid16));
+  uuid_free(uuid);
+  EXPECT_EQ((uint16_t)0xffff, uuid16);
+
+  uuid = uuid_new(UUID_BASE);
+  EXPECT_TRUE(uuid_128_to_16(uuid, &uuid16));
+  uuid_free(uuid);
+  EXPECT_NE((uint16_t)0xffff, uuid16);
+  EXPECT_EQ((uint16_t)0, uuid16);
+}
+
+TEST_F(UuidTest, uuid_128_to_32) {
+  bt_uuid_t *uuid = NULL;
+  uint32_t uuid32 = 0xffffffff;
+
+  uuid = uuid_new(UUID_ONES);
+  EXPECT_FALSE(uuid_128_to_32(uuid, &uuid32));
+  uuid_free(uuid);
+  EXPECT_EQ((uint32_t)0xffffffff, uuid32);
+
+  uuid = uuid_new(UUID_BASE);
+  EXPECT_TRUE(uuid_128_to_32(uuid, &uuid32));
+  uuid_free(uuid);
+  EXPECT_NE((uint32_t)0xffffffff, uuid32);
+  EXPECT_EQ((uint32_t)0, uuid32);
+}
+
+TEST_F(UuidTest, uuid_to_string) {
+  bt_uuid_t *uuid = NULL;
+
+  uuid_string_t *uuid_string = uuid_string_new();
+  EXPECT_TRUE(uuid_string != NULL);
+
+  uuid = uuid_new(UUID_BASE);
+  EXPECT_TRUE(uuid != NULL);
+  uuid_to_string(uuid, uuid_string);
+  uuid_free(uuid);
+
+  EXPECT_TRUE(!strcmp(UUID_BASE, uuid_string_data(uuid_string)));
+
+  uuid = uuid_new(UUID_SEQUENTIAL);
+  EXPECT_TRUE(uuid != NULL);
+
+  uuid_to_string(uuid, uuid_string);
+  uuid_free(uuid);
+
+  char lower_case_buf[36+1];
+  for (int i = 0; i < 36+1; i++) {
+    lower_case_buf[i] = tolower(UUID_SEQUENTIAL[i]);
+  }
+  EXPECT_TRUE(!strcmp(lower_case_buf, uuid_string_data(uuid_string)));
+  uuid_string_free(uuid_string);
+}
diff --git a/btif/co/bta_ag_co.c b/btif/co/bta_ag_co.c
index 13c1aff..e18cc9d 100755
--- a/btif/co/bta_ag_co.c
+++ b/btif/co/bta_ag_co.c
@@ -15,32 +15,14 @@
  *  limitations under the License.
  *
  ******************************************************************************/
-#include "gki.h"
-#include "bta_api.h"
-#include "bta_sys.h"
-#include "bta_ag_api.h"
-#include "bta_ag_co.h"
-#include "bte_appl.h"
-#include "bt_utils.h"
 
-#define LOG_TAG "BTA_AG_CO: "
+#define LOG_TAG "bt_btif_bta_ag"
 
-#ifndef LINUX_NATIVE
 #include <cutils/properties.h>
-#include <cutils/log.h>
-#else
-#include <stdio.h>
-#define LOGI(format, ...)  fprintf (stdout, LOG_TAG format"\n", ## __VA_ARGS__)
-#define LOGD(format, ...)  fprintf (stdout, LOG_TAG format"\n", ## __VA_ARGS__)
-#define LOGV(format, ...)  fprintf (stdout, LOG_TAG format"\n", ## __VA_ARGS__)
-#define LOGE(format, ...)  fprintf (stderr, LOG_TAG format"\n", ## __VA_ARGS__)
-#endif
 
-
-/************************************************************************************
-**  Externs
-************************************************************************************/
-extern int set_audio_state(UINT16 handle, UINT16 codec, UINT8 state, void *param);
+#include "bta/include/bta_ag_api.h"
+#include "hci/include/hci_audio.h"
+#include "osi/include/osi.h"
 
 /*******************************************************************************
 **
@@ -70,12 +52,8 @@
 **
 ** Parameters       handle - handle of the AG instance
 **                  state - Audio state
-**                      BTA_AG_CO_AUD_STATE_OFF     - Audio has been turned off
-**                      BTA_AG_CO_AUD_STATE_OFF_XFER - Audio has been turned off (xfer)
-**                      BTA_AG_CO_AUD_STATE_ON      - Audio has been turned on
-**                      BTA_AG_CO_AUD_STATE_SETUP   - Audio is about to be turned on
 **                  codec - if WBS support is compiled in, codec to going to be used is provided
-**                      and when in BTA_AG_CO_AUD_STATE_SETUP, BTM_I2SPCMConfig() must be called with
+**                      and when in SCO_STATE_SETUP, BTM_I2SPCMConfig() must be called with
 **                      the correct platform parameters.
 **                      in the other states codec type should not be ignored
 **
@@ -91,24 +69,24 @@
     BTIF_TRACE_DEBUG("bta_ag_co_audio_state: handle %d, state %d", handle, state);
     switch (state)
     {
-    case BTA_AG_CO_AUD_STATE_OFF:
+    case SCO_STATE_OFF:
 #if (BTM_WBS_INCLUDED == TRUE )
         BTIF_TRACE_DEBUG("bta_ag_co_audio_state(handle %d)::Closed (OFF), codec: 0x%x",
                         handle, codec);
-        set_audio_state(handle, codec, state, NULL);
+        set_audio_state(handle, codec, state);
 #else
         BTIF_TRACE_DEBUG("bta_ag_co_audio_state(handle %d)::Closed (OFF)",
                         handle);
 #endif
         break;
-    case BTA_AG_CO_AUD_STATE_OFF_XFER:
+    case SCO_STATE_OFF_TRANSFER:
         BTIF_TRACE_DEBUG("bta_ag_co_audio_state(handle %d)::Closed (XFERRING)", handle);
         break;
-    case BTA_AG_CO_AUD_STATE_SETUP:
+    case SCO_STATE_SETUP:
 #if (BTM_WBS_INCLUDED == TRUE )
-        set_audio_state(handle, codec, state, NULL);
+        set_audio_state(handle, codec, state);
 #else
-        set_audio_state(handle, BTA_AG_CODEC_CVSD, state, NULL);
+        set_audio_state(handle, BTA_AG_CODEC_CVSD, state);
 #endif
         break;
     default:
@@ -171,9 +149,7 @@
  ** Returns          void
  **
  *******************************************************************************/
-void bta_ag_co_tx_write(UINT16 handle, UINT8 * p_data, UINT16 len)
+void bta_ag_co_tx_write(UINT16 handle, UNUSED_ATTR UINT8 * p_data, UINT16 len)
 {
-    UNUSED(p_data);
     BTIF_TRACE_DEBUG( "bta_ag_co_tx_write: handle: %d, len: %d", handle, len );
 }
-
diff --git a/btif/co/bta_av_co.c b/btif/co/bta_av_co.c
index e0d7e4a..1460fca 100644
--- a/btif/co/bta_av_co.c
+++ b/btif/co/bta_av_co.c
@@ -339,7 +339,7 @@
  ** Returns          void.
  **
  *******************************************************************************/
-BTA_API void bta_av_co_audio_disc_res(tBTA_AV_HNDL hndl, UINT8 num_seps, UINT8 num_snk,
+void bta_av_co_audio_disc_res(tBTA_AV_HNDL hndl, UINT8 num_seps, UINT8 num_snk,
         UINT8 num_src, BD_ADDR addr, UINT16 uuid_local)
 {
     tBTA_AV_CO_PEER *p_peer;
@@ -589,9 +589,9 @@
  ** Returns          Stream codec and content protection configuration info.
  **
  *******************************************************************************/
-BTA_API UINT8 bta_av_co_audio_getconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
-        UINT8 *p_codec_info, UINT8 *p_sep_info_idx, UINT8 seid, UINT8 *p_num_protect,
-        UINT8 *p_protect_info)
+UINT8 bta_av_co_audio_getconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+                                UINT8 *p_codec_info, UINT8 *p_sep_info_idx, UINT8 seid, UINT8 *p_num_protect,
+                                UINT8 *p_protect_info)
 
 {
     UINT8 result = A2D_FAIL;
@@ -748,10 +748,9 @@
  ** Returns          void
  **
  *******************************************************************************/
-BTA_API void bta_av_co_audio_setconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+void bta_av_co_audio_setconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
         UINT8 *p_codec_info, UINT8 seid, BD_ADDR addr, UINT8 num_protect, UINT8 *p_protect_info,
         UINT8 t_local_sep, UINT8 avdt_handle)
-
 {
     tBTA_AV_CO_PEER *p_peer;
     UINT8 status = A2D_SUCCESS;
@@ -905,8 +904,8 @@
  ** Returns          void
  **
  *******************************************************************************/
-BTA_API void bta_av_co_audio_open(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, UINT8 *p_codec_info,
-        UINT16 mtu)
+void bta_av_co_audio_open(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, UINT8 *p_codec_info,
+                          UINT16 mtu)
 {
     tBTA_AV_CO_PEER *p_peer;
     UNUSED(p_codec_info);
@@ -939,7 +938,7 @@
  ** Returns          void
  **
  *******************************************************************************/
-BTA_API void bta_av_co_audio_close(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, UINT16 mtu)
+void bta_av_co_audio_close(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, UINT16 mtu)
 
 {
     tBTA_AV_CO_PEER *p_peer;
@@ -977,8 +976,8 @@
  ** Returns          void
  **
  *******************************************************************************/
-BTA_API void bta_av_co_audio_start(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
-        UINT8 *p_codec_info, BOOLEAN *p_no_rtp_hdr)
+void bta_av_co_audio_start(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type,
+                           UINT8 *p_codec_info, BOOLEAN *p_no_rtp_hdr)
 {
     UNUSED(hndl);
     UNUSED(codec_type);
@@ -1002,7 +1001,7 @@
  ** Returns          void
  **
  *******************************************************************************/
-BTA_API extern void bta_av_co_audio_stop(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type)
+extern void bta_av_co_audio_stop(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type)
 {
     UNUSED(hndl);
     UNUSED(codec_type);
@@ -1022,8 +1021,8 @@
  ** Returns          Pointer to the GKI buffer to send, NULL if no buffer to send
  **
  *******************************************************************************/
-BTA_API void * bta_av_co_audio_src_data_path(tBTA_AV_CODEC codec_type, UINT32 *p_len,
-        UINT32 *p_timestamp)
+void * bta_av_co_audio_src_data_path(tBTA_AV_CODEC codec_type, UINT32 *p_len,
+                                     UINT32 *p_timestamp)
 {
     BT_HDR *p_buf;
     UNUSED(p_len);
@@ -1853,5 +1852,3 @@
 
     return TRUE;
 }
-
-
diff --git a/btif/co/bta_fs_co.c b/btif/co/bta_fs_co.c
deleted file mode 100644
index 6aa2571..0000000
--- a/btif/co/bta_fs_co.c
+++ /dev/null
@@ -1,1237 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/statfs.h>
-#include <sys/vfs.h>
-#include <unistd.h>
-#include <dirent.h>
-#include <time.h>
-#include <limits.h>
-#include "gki.h"
-#include "bta_fs_co.h"
-#include "bta_fs_ci.h"
-#include <inttypes.h>
-#include "bt_utils.h"
-
-#ifndef AID_SYSTEM
-#define AID_SYSTEM        1000
-#define AID_BLUETOOTH     1002
-#define AID_SDCARD_RW     1015
-#define AID_MISC          9998
-#endif
-
-#define FAT_FS 0x4d44
-const unsigned short BT_UID= AID_BLUETOOTH;
-const unsigned short BT_GID= AID_BLUETOOTH;
-
-/* enable additional debugging traces that should be compiled out by default! */
-#ifndef BTA_FS_DEBUG
-#define BTA_FS_DEBUG TRUE
-#define LOG_TAG  "BTA_FS_CO"
-#define LOGI(format, ...)  fprintf (stdout, LOG_TAG format"\n", ## __VA_ARGS__)
-#endif
-
-#if (defined BTA_PBS_INCLUDED) && (BTA_PBS_INCLUDED == TRUE)
-extern const tBTA_PBS_CFG bta_pbs_cfg;
-#endif
-
-
-
-static int del_path (const char *path)
-{
-    DIR *dir;
-    struct dirent *de;
-    int ret = 0;
-    char nameBuffer[PATH_MAX] = {0};
-    struct stat statBuffer;
-    BTIF_TRACE_DEBUG("in del_path for path:%s", path);
-    dir = opendir(path);
-
-    if (dir == NULL) {
-        BTIF_TRACE_DEBUG("opendir failed on path:%s", path);
-        return -1;
-    }
-
-    char *filenameOffset;
-
-    strncpy(nameBuffer, path, PATH_MAX - 1);
-    strcat(nameBuffer, "/");
-    int nameLen = strlen(nameBuffer);
-    filenameOffset = nameBuffer + nameLen;
-
-    for (;;) {
-        de = readdir(dir);
-
-        if (de == NULL) {
-            BTIF_TRACE_DEBUG("readdir failed for path:%s", path);
-            //ret = -1;
-            break;
-        }
-
-        if (0 == strcmp(de->d_name, ".") || 0 == strcmp(de->d_name, ".."))
-           continue;
-
-        if((int)strlen(de->d_name) > PATH_MAX - nameLen) {
-            BTIF_TRACE_DEBUG("d_name len:%d is too big", strlen(de->d_name));
-            ret = -1;
-            break;
-        }
-
-        strcpy(filenameOffset, de->d_name);
-
-        ret = lstat (nameBuffer, &statBuffer);
-
-        if (ret != 0) {
-            BTIF_TRACE_DEBUG("lstat failed for path:%s", nameBuffer);
-            break;
-        }
-
-        if(S_ISDIR(statBuffer.st_mode)) {
-
-            ret = del_path(nameBuffer);
-            if(ret != 0)
-                break;
-        } else {
-            ret = unlink(nameBuffer);
-            if (ret != 0) {
-                BTIF_TRACE_DEBUG("unlink failed for path:%s", nameBuffer);
-                break;
-            }
-        }
-    }
-
-    closedir(dir);
-    if(ret == 0) {
-        ret = rmdir(path);
-        BTIF_TRACE_DEBUG("rmdir return:%d for path:%s", ret, path);
-    }
-
-    return ret;
-
-}
-
-inline int getAccess(int accType, struct stat *buffer, char *p_path)
-{
-
-    struct statfs fsbuffer;
-    int idType;
-
-    if(! buffer)
-	return BTA_FS_CO_FAIL;
-
-    //idType= (buffer->st_uid== BT_UID) ? 1 : (buffer->st_uid== BT_GID) ? 2 : 3;
-    if(buffer->st_uid == BT_UID)
-        idType = 1;
-    else if(buffer->st_gid == BT_GID ||
-            buffer->st_gid == AID_SYSTEM ||
-            buffer->st_gid == AID_MISC ||
-            buffer->st_gid == AID_SDCARD_RW)
-        idType = 2;
-    else idType = 3;
-
-    if(statfs(p_path, &fsbuffer)==0)
-    {
-        if(fsbuffer.f_type == FAT_FS)
-	    return BTA_FS_CO_OK;
-    }
-    else {
-        return BTA_FS_CO_FAIL;
-    }
-
-    switch(accType) {
-        case 4:
-	if(idType== 1) {	//Id is User Id
-	   if(buffer-> st_mode & S_IRUSR)
-	       return BTA_FS_CO_OK;
-	}
-	else if(idType==2) {   //Id is Group Id
-	    if(buffer-> st_mode & S_IRGRP)
-	       return BTA_FS_CO_OK;
-	}
-	else {			//Id is Others
-	    if(buffer-> st_mode & S_IROTH)
-	       return BTA_FS_CO_OK;
-	}
-	break;
-
-	case 6:
-	if(idType== 1) {	//Id is User Id
-	   if((buffer-> st_mode & S_IRUSR) && (buffer-> st_mode & S_IWUSR))
-	       return BTA_FS_CO_OK;
-	}
-	else if(idType==2) {   //Id is Group Id
-	    if((buffer-> st_mode & S_IRGRP) && (buffer-> st_mode & S_IWGRP))
-	       return BTA_FS_CO_OK;
-	}
-	else {			//Id is Others
-	    if((buffer-> st_mode & S_IROTH) && (buffer-> st_mode & S_IWOTH))
-	       return BTA_FS_CO_OK;
-	}
-	break;
-
-	default:
-	return BTA_FS_CO_OK;
-    }
-    BTIF_TRACE_DEBUG("*************FTP- Access Failed **********");
-    return BTA_FS_CO_EACCES;
-}
-
-
-/*****************************************************************************
-**  Function Declarations
-*****************************************************************************/
-
-/*******************************************************************************
-**
-** Function         bta_fs_convert_oflags
-**
-** Description      This function converts the open flags from BTA into MFS.
-**
-** Returns          BTA FS status value.
-**
-*******************************************************************************/
-int bta_fs_convert_bta_oflags(int bta_oflags)
-{
-    int oflags = 0; /* Initially read only */
-
-    /* Only one of these can be set: Read Only, Read/Write, or Write Only */
-    if (bta_oflags & BTA_FS_O_RDWR)
-        oflags |= O_RDWR;
-    else if (bta_oflags & BTA_FS_O_WRONLY)
-        oflags |= O_WRONLY;
-
-    /* OR in any other flags that are set by BTA */
-    if (bta_oflags & BTA_FS_O_CREAT)
-        oflags |= O_CREAT;
-
-    if (bta_oflags & BTA_FS_O_EXCL)
-        oflags |= O_EXCL;
-
-    if (bta_oflags & BTA_FS_O_TRUNC)
-        oflags |= O_TRUNC;
-
-    return (oflags);
-}
-
-
-
-/*******************************************************************************
- **
- ** Function        btapp_fs_check_space
- **
- ** Description     determines access and if there is enough space for given files size on given path
- **
- ** Parameters      p_path  - Fully qualified path and file name.
- **                           WARNING: file name is stripped off! so it must be present!
- **                 size    - size of file to put (0 if unavailable or not applicable)
- **                 app_id  - in case application specific treatement is required (e.g opp versus ftp)
- ** Returns         0 if enough space, otherwise errno failure codes
- **
- *******************************************************************************/
-static int btapp_fs_check_space( const char *p_path, const UINT32 size, const UINT8 app_id )
-{
-    unsigned long long max_space;
-    struct statfs fs_buffer;
-    int err = 0;
-    char *p_dir;
-    char *p_end;
-    UNUSED(app_id);
-
-    if(size==BTA_FS_LEN_UNKNOWN)
-        return 0;
-    /* fail silently in case of no memory. write will catch if not enough space */
-
-    if (NULL != (p_dir = (char *) GKI_getbuf(strlen(p_path) + 1)))
-    {
-        strcpy(p_dir, p_path);
-        if (NULL != (p_end = strrchr(p_dir, '/')))
-        {
-
-            *p_end = '\0';
-            /* get fs info and calculate available space. if not enough, the fs error EFBIG is returned */
-
-            if (0 == statfs(p_dir, &fs_buffer))
-            {
-
-                max_space = fs_buffer.f_bavail * fs_buffer.f_bsize;
-#if (BTA_FS_DEBUG==TRUE)
-                BTIF_TRACE_DEBUG("btapp_fs_enough_space(file size: %d): (uint)max_size: %u", size, (UINT32)max_space);
-#endif
-                if (max_space < size)
-                    err = EFBIG;
-            }
-            else
-            {
-                err = errno;
-                BTIF_TRACE_WARNING("btapp_fs_enough_space(): statfs() failed with err: %d", err);
-            }
-        }
-        else
-        {
-            err = ENOENT;
-        }
-        GKI_freebuf(p_dir);
-    }
-    else
-    {
-        err = ENOMEM;
-    }
-    return err;
-
-} /* btapp_fs_check_access_space() */
-
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_open
-**
-** Description      This function is executed by BTA when a file is opened.
-**                  The phone uses this function to open
-**                  a file for reading or writing.
-**
-** Parameters       p_path  - Fully qualified path and file name.
-**                  oflags  - permissions and mode (see constants above)
-**                  size    - size of file to put (0 if unavailable or not applicable)
-**                  evt     - event that must be passed into the call-in function.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-**                  Note: Upon completion of the request, a file descriptor (int),
-**                        if successful, and an error code (tBTA_FS_CO_STATUS)
-**                        are returned in the call-in function, bta_fs_ci_open().
-**
-*******************************************************************************/
-
-void bta_fs_co_open(const char *p_path, int oflags, UINT32 size, UINT16 evt,
-                    UINT8 app_id)
-{
-
-    tBTA_FS_CO_STATUS  status;
-    UINT32  file_size = 0;
-    struct  stat file_stat;
-    int fd = -1;
-    int err = 0;
-
-    /* Convert BTA oflags into os specific flags */
-    oflags = bta_fs_convert_bta_oflags(oflags);
-
-    /* check available space in case of write access. oflags are in OS format! */
-    if (oflags & (O_RDWR|O_WRONLY))
-    {
-        err = btapp_fs_check_space(p_path, size, app_id);
-    }
-
-    if ( 0==err )
-    {
-        if ((fd = open(p_path, oflags | O_NONBLOCK, 0666)) >= 0)
-        {
-            if (fstat(fd, &file_stat) == 0)
-            {
-                file_size = file_stat.st_size;
-                if (oflags & O_CREAT)
-                {
-                    fchown(fd, BT_UID, BT_GID);
-                    BTIF_TRACE_DEBUG("\n ******CHANGED OWNERSHIP SUCCESSFULLY**********");
-                }
-            }
-        }
-
-        else
-        {
-            err = errno;
-        }
-    }
-
-    BTIF_TRACE_DEBUG("[CO] bta_fs_co_open: handle:%d err:%d, flags:%x, app id:%d",
-            fd, err, oflags, app_id);
-    BTIF_TRACE_DEBUG("file=%s", p_path);
-
-    /* convert fs error into bta_fs err. erro is set by first call to enough space to a valid value
-     * and needs only updating in case of error. This reports correct failure to remote obex! */
-
-    switch (err)
-    {
-
-    case 0:
-        status = BTA_FS_CO_OK;
-        break;
-    case EACCES:
-        status = BTA_FS_CO_EACCES;
-        break;
-    case EFBIG: /* file to big for available fs space */
-        status = BTA_FS_CO_ENOSPACE;
-        break;
-    default:
-        status = BTA_FS_CO_FAIL;
-        break;
-    }
-    bta_fs_ci_open(fd, status, file_size, evt);
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_close
-**
-** Description      This function is called by BTA when a connection to a
-**                  client is closed.
-**
-** Parameters       fd      - file descriptor of file to close.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful],
-**                      [BTA_FS_CO_FAIL if failed  ]
-**
-*******************************************************************************/
-tBTA_FS_CO_STATUS bta_fs_co_close(int fd, UINT8 app_id)
-{
-    tBTA_FS_CO_STATUS status = BTA_FS_CO_OK;
-    int err;
-
-    BTIF_TRACE_DEBUG("[CO] bta_fs_co_close: handle:%d, app id:%d",
-        fd, app_id);
-    if (close (fd) < 0)
-    {
-        err = errno;
-        status = BTA_FS_CO_FAIL;
-        BTIF_TRACE_WARNING("[CO] bta_fs_co_close: handle:%d error=%d app_id:%d", fd, err, app_id);
-    }
-
-    return (status);
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_read
-**
-** Description      This function is called by BTA to read in data from the
-**                  previously opened file on the phone.
-**
-** Parameters       fd      - file descriptor of file to read from.
-**                  p_buf   - buffer to read the data into.
-**                  nbytes  - number of bytes to read into the buffer.
-**                  evt     - event that must be passed into the call-in function.
-**                  ssn     - session sequence number. Ignored, if bta_fs_co_open
-**							  was not called with BTA_FS_CO_RELIABLE.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-**                  Note: Upon completion of the request, bta_fs_ci_read() is
-**                        called with the buffer of data, along with the number
-**                        of bytes read into the buffer, and a status.  The
-**                        call-in function should only be called when ALL requested
-**                        bytes have been read, the end of file has been detected,
-**                        or an error has occurred.
-**
-*******************************************************************************/
-void bta_fs_co_read(int fd, UINT8 *p_buf, UINT16 nbytes, UINT16 evt, UINT8 ssn, UINT8 app_id)
-{
-    tBTA_FS_CO_STATUS  status = BTA_FS_CO_OK;
-    INT32   num_read;
-    int     err;
-    UNUSED(ssn);
-
-    if ((num_read = read (fd, p_buf, nbytes)) < 0)
-    {
-        err = errno;
-        status = BTA_FS_CO_FAIL;
-        BTIF_TRACE_WARNING("[CO] bta_fs_co_read: handle:%d error=%d app_id:%d",
-                            fd, err, app_id);
-    }
-    else if (num_read < nbytes)
-        status = BTA_FS_CO_EOF;
-
-    bta_fs_ci_read(fd, (UINT16)num_read, status, evt);
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_write
-**
-** Description      This function is called by io to send file data to the
-**                  phone.
-**
-** Parameters       fd      - file descriptor of file to write to.
-**                  p_buf   - buffer to read the data from.
-**                  nbytes  - number of bytes to write out to the file.
-**                  evt     - event that must be passed into the call-in function.
-**                  ssn     - session sequence number. Ignored, if bta_fs_co_open
-**							  was not called with BTA_FS_CO_RELIABLE.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-**                  Note: Upon completion of the request, bta_fs_ci_write() is
-**                        called with the file descriptor and the status.  The
-**                        call-in function should only be called when ALL requested
-**                        bytes have been written, or an error has been detected,
-**
-*******************************************************************************/
-void bta_fs_co_write(int fd, const UINT8 *p_buf, UINT16 nbytes, UINT16 evt,
-                     UINT8 ssn, UINT8 app_id)
-{
-    tBTA_FS_CO_STATUS  status = BTA_FS_CO_OK;
-    INT32   num_written;
-    int     err=0;
-    UNUSED(ssn);
-    UNUSED(app_id);
-
-    if ((num_written = write (fd, p_buf, nbytes)) < 0)
-    {
-        err = errno;
-        status = BTA_FS_CO_FAIL;
-    }
-/*    BTIF_TRACE_DEBUG("[CO] bta_fs_co_write: handle:%d error=%d, num_written:%d", fd, err, num_written);*/
-
-    bta_fs_ci_write(fd, status, evt);
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_seek
-**
-** Description      This function is called by io to move the file pointer
-**                  of a previously opened file to the specified location for
-**                  the next read or write operation.
-**
-** Parameters       fd      - file descriptor of file.
-**                  offset  - Number of bytes from origin.
-**                  origin  - Initial position.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_co_seek (int fd, INT32 offset, INT16 origin, UINT8 app_id)
-{
-    UNUSED(app_id);
-    lseek(fd, offset, origin);
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_access
-**
-** Description      This function is called to check the existence of
-**                  a file or directory, and return whether or not it is a
-**                  directory or length of the file.
-**
-** Parameters       p_path   - (input) file or directory to access (fully qualified path).
-**                  mode     - (input) [BTA_FS_ACC_EXIST, BTA_FS_ACC_READ, or BTA_FS_ACC_RDWR]
-**                  p_is_dir - (output) returns TRUE if p_path specifies a directory.
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                   [BTA_FS_CO_OK if it exists]
-**                   [BTA_FS_CO_EACCES if permissions are wrong]
-**                   [BTA_FS_CO_FAIL if it does not exist]
-**
-*******************************************************************************/
-tBTA_FS_CO_STATUS bta_fs_co_access(const char *p_path, int mode, BOOLEAN *p_is_dir,
-                                   UINT8 app_id)
-{
-    int os_mode = 0;
-    tBTA_FS_CO_STATUS status = BTA_FS_CO_OK;
-    struct stat buffer;
-    UNUSED(app_id);
-
-    #if (TRUE==BTA_FS_DEBUG)
-    LOGI("***********CHECKING ACCESS TO = %s", p_path);
-    #endif
-
-    #if (defined BTA_PBS_INCLUDED) && (BTA_PBS_INCLUDED == TRUE)
-
-    if (app_id == UI_PBS_ID)
-    {
-
-        *p_is_dir = TRUE;
-
-        #if (TRUE==BTA_FS_DEBUG)
-        LOGI("***********SUPPORTED REPO = %d", bta_pbs_cfg.supported_repositories);
-        #endif
-        //Check if SIM contact requested,  and if so if it's supported.
-        //If not, return error!
-        if (strstr(p_path,"SIM1") && !(bta_pbs_cfg.supported_repositories & 0x2)) {
-            LOGI("***********RETURNING FAIL!");
-            return BTA_FS_CO_FAIL;
-        }
-
-        #if (TRUE==BTA_FS_DEBUG)
-        LOGI("***********RETURNING success!");
-        #endif
-        return (status);
-    }
-    #endif
-
-
-    *p_is_dir = FALSE;
-
-    if (mode == BTA_FS_ACC_RDWR)
-        os_mode = 6;
-    else if (mode == BTA_FS_ACC_READ)
-        os_mode = 4;
-
-    if (stat(p_path, &buffer) == 0)
-    {
-	/* Determine if the object is a file or directory */
-        if (S_ISDIR(buffer.st_mode))
-            *p_is_dir = TRUE;
-    }
-    else
-    {
-	BTIF_TRACE_DEBUG("stat() failed! ");
-        return BTA_FS_CO_FAIL;
-    }
-
-    status=getAccess (os_mode, &buffer, (char*)p_path);
-    return (status);
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_mkdir
-**
-** Description      This function is called to create a directory with
-**                  the pathname given by path. The pathname is a null terminated
-**                  string. All components of the path must already exist.
-**
-** Parameters       p_path   - (input) name of directory to create (fully qualified path).
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                  [BTA_FS_CO_OK if successful]
-**                  [BTA_FS_CO_FAIL if unsuccessful]
-**
-*******************************************************************************/
-tBTA_FS_CO_STATUS bta_fs_co_mkdir(const char *p_path, UINT8 app_id)
-{
-    int err;
-    tBTA_FS_CO_STATUS status = BTA_FS_CO_OK;
-
-    if ((mkdir (p_path, 0666)) != 0)
-    {
-        err = errno;
-        status = BTA_FS_CO_FAIL;
-        BTIF_TRACE_WARNING("[CO] bta_fs_co_mkdir: error=%d, path [%s] app_id:%d",
-                            err, p_path, app_id);
-    }
-    return (status);
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_rmdir
-**
-** Description      This function is called to remove a directory whose
-**                  name is given by path. The directory must be empty.
-**
-** Parameters       p_path   - (input) name of directory to remove (fully qualified path).
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful]
-**                      [BTA_FS_CO_EACCES if read-only]
-**                      [BTA_FS_CO_ENOTEMPTY if directory is not empty]
-**                      [BTA_FS_CO_FAIL otherwise]
-**
-*******************************************************************************/
-tBTA_FS_CO_STATUS bta_fs_co_rmdir(const char *p_path, UINT8 app_id)
-{
-    int err, path_len;
-    tBTA_FS_CO_STATUS status = BTA_FS_CO_OK;
-    struct stat buffer;
-    char *dirName, *tmp = NULL;
-
-    path_len = strlen( p_path )+1;
-    BTIF_TRACE_DEBUG( "bta_fs_co_rmdir( app_id: %d ): path_len: %d", app_id, path_len );
-#if (TRUE==BTA_FS_DEBUG)
-    BTIF_TRACE_DEBUG( "bta_fs_co_rmdir():path_len: %d, p_path", app_id );
-    BTIF_TRACE_DEBUG( p_path );
-#endif
-
-    /* allocate a temp buffer for path with 0 char. make sure not to crash if path is too big! */
-    dirName = (char*) calloc(1, path_len+1);
-    if ( NULL != dirName )
-    {
-        strcpy( dirName, p_path );
-    }
-    else
-    {
-        BTIF_TRACE_WARNING( "bta_fs_co_rmdir( app_id: %d ) for path_len: %d::out of memory",
-                             app_id, path_len );
-        return BTA_FS_CO_FAIL;
-    }
-
-    if (NULL!= (tmp = strrchr(dirName, '/')))
-    {
-        *tmp = '\0';
-    }
-    if (stat(dirName, &buffer) == 0)
-    {
-        status = getAccess(6, &buffer, dirName);
-    }
-    else
-    {
-        free(dirName);
-#if (TRUE==BTA_FS_DEBUG)
-        BTIF_TRACE_WARNING( "bta_fs_co_rmdir()::stat(dirName) failed" );
-#endif
-        return BTA_FS_CO_FAIL;
-    }
-
-    free(dirName);
-    if (status != BTA_FS_CO_OK)
-    {
-#if (TRUE==BTA_FS_DEBUG)
-        BTIF_TRACE_WARNING( "bta_fs_co_rmdir()::getAccess(dirName) FAILED");
-#endif
-        return status;
-    }
-
-    if (stat(p_path, &buffer) == 0)
-    {
-        status = getAccess(6, &buffer, (char*)p_path);
-    }
-    else
-    {
-#if (TRUE==BTA_FS_DEBUG)
-        BTIF_TRACE_WARNING( "bta_fs_co_rmdir()::stat(p_path) FAILED");
-#endif
-        return BTA_FS_CO_FAIL;
-    }
-
-    if (status != BTA_FS_CO_OK)
-    {
-#if (TRUE==BTA_FS_DEBUG)
-        BTIF_TRACE_DEBUG( "bta_fs_co_rmdir()::getAccess(p_path) FAILED");
-#endif
-        return status;
-    }
-    //if ((rmdir (p_path)) != 0)
-    if (del_path(p_path) != 0)
-    {
-        err = errno;
-        BTIF_TRACE_WARNING( "bta_fs_co_rmdir():rmdir/del_path FAILED with err: %d", err );
-        if (err == EACCES)
-            status = BTA_FS_CO_EACCES;
-        else if (err == ENOTEMPTY)
-            status = BTA_FS_CO_ENOTEMPTY;
-        else
-            status = BTA_FS_CO_FAIL;
-    }
-    return (status);
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_unlink
-**
-** Description      This function is called to remove a file whose name
-**                  is given by p_path.
-**
-** Parameters       p_path   - (input) name of file to remove (fully qualified path).
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful]
-**                      [BTA_FS_CO_EACCES if read-only]
-**                      [BTA_FS_CO_FAIL otherwise]
-**
-*******************************************************************************/
-tBTA_FS_CO_STATUS bta_fs_co_unlink(const char *p_path, UINT8 app_id)
-{
-    BTIF_TRACE_DEBUG("bta_fs_co_unlink");
-    int err;
-    tBTA_FS_CO_STATUS status = BTA_FS_CO_OK;
-    char *dirName, *tmp=NULL;
-    struct stat buffer;
-    UNUSED(app_id);
-
-    if(! p_path)
-        return BTA_FS_CO_FAIL;
-
-    /* buffer needs to be NULL terminated - so add one more byte to be zero'd out */
-#if 0
-    dirName= (char*) calloc(1, strlen(p_path));  /* <--- this can cause problems  */
-#else
-    dirName= (char*) calloc(1, strlen(p_path) + 1);
-#endif
-
-    strncpy(dirName, p_path, strlen(p_path));
-    if((tmp=strrchr(dirName, '/')))
-    {
-	    *tmp='\0';
-    }
-    if (stat(dirName, &buffer) == 0)
-    {
-        status=getAccess (6, &buffer, dirName);
-        free(dirName);
-    }
-    else
-    {
-        BTIF_TRACE_DEBUG("stat() failed! ");
-        free(dirName);
-        return BTA_FS_CO_FAIL;
-    }
-
-    if(status!= BTA_FS_CO_OK)
-	return status;
-
-    if ((unlink (p_path)) != 0)
-    {
-        err = errno;
-        if (err == EACCES)
-            status = BTA_FS_CO_EACCES;
-        else
-            status = BTA_FS_CO_FAIL;
-    }
-    return (status);
-
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_getdirentry
-**
-** Description      This function is called to get a directory entry for the
-**                  specified p_path.  The first/next directory should be filled
-**                  into the location specified by p_entry.
-**
-** Parameters       p_path      - directory to search (Fully qualified path)
-**                  first_item  - TRUE if first search, FALSE if next search
-**                                      (p_cur contains previous)
-**                  p_entry (input/output) - Points to last entry data (valid when
-**                                           first_item is FALSE)
-**                  evt     - event that must be passed into the call-in function.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-**                  Note: Upon completion of the request, the status is passed
-**                        in the bta_fs_ci_direntry() call-in function.
-**                        BTA_FS_CO_OK is returned when p_entry is valid,
-**                        BTA_FS_CO_EODIR is returned when no more entries [finished]
-**                        BTA_FS_CO_FAIL is returned if an error occurred
-**
-*******************************************************************************/
-void bta_fs_co_getdirentry(const char *p_path, BOOLEAN first_item,
-                           tBTA_FS_DIRENTRY *p_entry, UINT16 evt, UINT8 app_id)
-{
-    tBTA_FS_CO_STATUS    co_status = BTA_FS_CO_FAIL;
-    int                  status = -1;    /* '0' - success, '-1' - fail */
-    struct tm           *p_tm;
-    DIR *dir;
-    struct dirent *dirent;
-    struct stat buf;
-    char fullname[500];
-    UNUSED(app_id);
-
-    BTIF_TRACE_DEBUG("Entered bta_fs_co_getdirentry");
-
-    /* First item is to be retrieved */
-    if (first_item)
-    {
-        BTIF_TRACE_DEBUG("bta_fs_co_getdirentry: path = %s", p_path);
-
-        dir = opendir(p_path);
-        if(dir == NULL)
-        {
-     	    BTIF_TRACE_DEBUG("bta_fs_co_getdirentry: dir is NULL so error out with errno=%d", errno);
-            co_status = BTA_FS_CO_EODIR;
-            bta_fs_ci_direntry(co_status, evt);
-            return;
-        }
-
-        BTIF_TRACE_DEBUG("bta_fs_co_getdirentry: dir = %p", dir);
-        if((dirent = readdir(dir)) != NULL)
-        {
-            p_entry->refdata = (UINT32) dir;     /* Save this for future searches */
-            status = 0;
-            BTIF_TRACE_DEBUG("bta_fs_co_getdirentry: dirent = %p", dirent);
-        }
-        else
-        {
-            BTIF_TRACE_DEBUG("bta_fs_co_getdirentry: dirent = %p", dirent);
-            /* Close the search if there are no more items */
-            closedir( (DIR*) p_entry->refdata);
-            co_status = BTA_FS_CO_EODIR;
-        }
-    }
-    else    /* Get the next entry based on the p_ref data from previous search */
-    {
-        if ((dirent = readdir((DIR*)p_entry->refdata))  == NULL)
-        {
-            /* Close the search if there are no more items */
-            closedir( (DIR*) p_entry->refdata);
-            co_status = BTA_FS_CO_EODIR;
-            BTIF_TRACE_DEBUG("bta_fs_co_getdirentry: dirent = %p", dirent);
-        }
-        else
-        {
-            BTIF_TRACE_DEBUG("bta_fs_co_getdirentry: dirent = %p", dirent);
-            status = 0;
-        }
-    }
-
-    if (status == 0)
-    {
-        BTIF_TRACE_DEBUG("bta_fs_co_getdirentry: status = 0");
-
-        sprintf(fullname, "%s/%s", p_path,  dirent->d_name);
-
-        /* Load new values into the return structure (refdata is left untouched) */
-        if (stat(fullname, &buf) == 0) {
-            p_entry->filesize = buf.st_size;
-            p_entry->mode = 0; /* Default is normal read/write file access */
-
-            if (S_ISDIR(buf.st_mode))
-                p_entry->mode |= BTA_FS_A_DIR;
-            else
-                p_entry->mode |= BTA_FS_A_RDONLY;
-
-            strcpy(p_entry->p_name, dirent->d_name);
-#if 0
-            fprintf(stderr, "bta_fs_co_getdirentry(): %s %9d %d\n",
-                            dirent->d_name,
-                            buf.st_size,
-                            p_entry->mode);
-#endif
-            p_tm = localtime((const time_t*)&buf.st_mtime);
-            if (p_tm != NULL)
-            {
-                sprintf(p_entry->crtime, "%04d%02d%02dT%02d%02d%02dZ",
-                        p_tm->tm_year + 1900,   /* Base Year ISO 6201 */
-                        p_tm->tm_mon + 1,       /* month starts at 0 */
-                        p_tm->tm_mday,
-                        p_tm->tm_hour,
-                        p_tm->tm_min,
-                        p_tm->tm_sec);
-            }
-            else
-                p_entry->crtime[0] = '\0';  /* No valid time */
-#if 0
-            fprintf(stderr, "bta_fs_co_getdirentry(): %s %9d %d %s\n",
-                            dirent->d_name,
-                            p_entry->filesize,
-                            p_entry->mode,
-                            p_entry->crtime);
-#endif
-            co_status = BTA_FS_CO_OK;
-        } else {
-            BTIF_TRACE_WARNING("stat() failed! ");
-            co_status = BTA_FS_CO_EACCES;
-        }
-    }
-    BTIF_TRACE_DEBUG("bta_fs_co_getdirentry: calling bta_fs_ci_getdirentry");
-
-    bta_fs_ci_direntry(co_status, evt);
-}
-
-
-
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_setdir
-**
-** Description      This function is executed by BTA when the server changes the
-**                  local path
-**
-** Parameters       p_path  - the new path.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_co_setdir(const char *p_path, UINT8 app_id)
-{
-    UNUSED(p_path);
-    UNUSED(app_id);
-
-    BTIF_TRACE_DEBUG("Entered %s. New path: %s", __FUNCTION__, p_path);
-}
-
-/*******************************************************************************
-** OBEX14 Reliable Session not supported. Stub associated callouts.
-******************************************************************************/
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_resume
-**
-** Description      This function is executed by BTA when resuming a session.
-**                  This is used to retrieve the session ID and related information
-**
-** Parameters       evt     - event that must be passed into the call-in function.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-**                  Note: Upon completion of the request, the related session information,
-**                        if successful, and an error code (tBTA_FS_CO_STATUS)
-**                        are returned in the call-in function, bta_fs_ci_resume().
-**
-*******************************************************************************/
-void bta_fs_co_resume(UINT16 evt, UINT8 app_id)
-{
-    UNUSED(evt);
-    UNUSED(app_id);
-
-    BTIF_TRACE_WARNING("[CO] bta_fs_co_resume - NOT implemented");
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_set_perms
-**
-** Description      This function is called to set the permission a file/directory
-**                  with name as p_src_path.
-**
-** Parameters       p_src_path  - (input) name of file/directory to set permission (fully qualified path).
-**                  p_perms     - the permission .
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful]
-**                      [BTA_FS_CO_EACCES if p_dest_path already exists or could not be created (invalid path);
-**                                        or p_src_path is a directory and p_dest_path specifies a different path. ]
-**                      [BTA_FS_CO_FAIL otherwise]
-**
-*******************************************************************************/
-void bta_fs_co_set_perms(const char *p_src_path,  UINT8 *p_perms, UINT16 evt, UINT8 app_id)
-{
-    UNUSED(p_src_path);
-    UNUSED(p_perms);
-    UNUSED(evt);
-    UNUSED(app_id);
-
-    BTIF_TRACE_WARNING("[CO] bta_fs_co_set_perms - NOT implemented");
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_rename
-**
-** Description      This function is called to move a file/directory whose
-**                  name is given by p_src_path to p_dest_path.
-**
-** Parameters       p_src_path  - (input) name of file/directory to be moved (fully qualified path).
-**                  p_dest_path - (input) new name of file/directory(fully qualified path).
-**                  p_perms     - the permission of the new object.
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful]
-**                      [BTA_FS_CO_EACCES if p_dest_path already exists or could not be created (invalid path);
-**                                        or p_src_path is a directory and p_dest_path specifies a different path. ]
-**                      [BTA_FS_CO_FAIL otherwise]
-**
-*******************************************************************************/
-void bta_fs_co_rename(const char *p_src_path, const char *p_dest_path, UINT8 *p_perms, UINT16 evt, UINT8 app_id)
-{
-    UNUSED(p_src_path);
-    UNUSED(p_dest_path);
-    UNUSED(p_perms);
-    UNUSED(evt);
-    UNUSED(app_id);
-
-    BTIF_TRACE_WARNING("[CO] bta_fs_co_rename - NOT implemented");
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_copy
-**
-** Description      This function is called to copy a file/directory whose
-**                  name is given by p_src_path to p_dest_path.
-**
-** Parameters       p_src_path  - (input) name of file/directory to be copied (fully qualified path).
-**                  p_dest_path - (input) new name of file/directory(fully qualified path).
-**                  p_perms     - the permission of the new object.
-**                  evt     - event that must be passed into the call-in function.
-**                  app_id   - (input) application ID specified in the enable functions.
-**                                     It can be used to identify which profile is the caller
-**                                     of the call-out function.
-**
-** Returns          (tBTA_FS_CO_STATUS) status of the call.
-**                      [BTA_FS_CO_OK if successful]
-**                      [BTA_FS_CO_EIS_DIR if p_src_path is a folder]
-**                      [BTA_FS_CO_EACCES if p_dest_path already exists or could not be created (invalid path);
-**                                        or p_src_path is a directory and p_dest_path specifies a different path. ]
-**                      [BTA_FS_CO_FAIL otherwise]
-**
-*******************************************************************************/
-void bta_fs_co_copy(const char *p_src_path, const char *p_dest_path, UINT8 *p_perms, UINT16 evt, UINT8 app_id)
-{
-    UNUSED(p_src_path);
-    UNUSED(p_dest_path);
-    UNUSED(p_perms);
-    UNUSED(evt);
-    UNUSED(app_id);
-
-    BTIF_TRACE_WARNING("[CO] bta_fs_co_copy - NOT implemented");
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_resume_op
-**
-** Description      This function is executed by BTA when a reliable session is
-**                  resumed and there was an interrupted operation.
-**
-** Parameters       offset  - the session ID and related information.
-**                  evt     - event that must be passed into the call-in function.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_co_resume_op(UINT32 offset, UINT16 evt, UINT8 app_id)
-{
-    UNUSED(offset);
-    UNUSED(evt);
-    UNUSED(app_id);
-
-    BTIF_TRACE_WARNING("[CO] bta_fs_co_resume_op - NOT implemented");
-}
-
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_session_info
-**
-** Description      This function is executed by BTA when a reliable session is
-**                  established (p_sess_info != NULL) or ended (p_sess_info == NULL).
-**
-** Parameters       bd_addr     - the peer address
-**                  p_sess_info - the session ID and related information.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_co_session_info(BD_ADDR bd_addr, UINT8 *p_sess_info, UINT8 ssn,
-                                           tBTA_FS_CO_SESS_ST new_st, char *p_path, UINT8 *p_info, UINT8 app_id)
-{
-    UNUSED(bd_addr);
-    UNUSED(p_sess_info);
-    UNUSED(ssn);
-    UNUSED(new_st);
-    UNUSED(p_path);
-    UNUSED(p_info);
-    UNUSED(app_id);
-
-    BTIF_TRACE_WARNING("[CO] bta_fs_co_session_info - NOT implemented");
-}
-
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_suspend
-**
-** Description      This function is executed by BTA when a reliable session is
-**                  suspended.
-**
-** Parameters       bd_addr - the peer address
-**                  ssn     - the session sequence number.
-**                  info    - the BTA specific information (like last active operation).
-**                  p_offset- the location to receive object offset of the suspended session
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_co_suspend(BD_ADDR bd_addr, UINT8 *p_sess_info, UINT8 ssn,
-                                      UINT32 *p_timeout, UINT32 *p_offset, UINT8 info, UINT8 app_id)
-{
-    UNUSED(bd_addr);
-    UNUSED(p_sess_info);
-    UNUSED(ssn);
-    UNUSED(p_timeout);
-    UNUSED(p_offset);
-    UNUSED(info);
-    UNUSED(app_id);
-
-    BTIF_TRACE_WARNING("[CO] bta_fs_co_suspend - NOT implemented");
-}
-
-/*******************************************************************************
-**
-** Function         bta_fs_co_sess_ssn
-**
-** Description      This function is executed by BTA when resuming a session.
-**                  This is used to inform call-out module if the ssn/file offset
-**                  needs to be adjusted.
-**
-** Parameters       ssn     - the session sequence number of the first request
-**                            after resume.
-**                  app_id  - application ID specified in the enable functions.
-**                            It can be used to identify which profile is the caller
-**                            of the call-out function.
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_fs_co_sess_ssn(int fd, UINT8 ssn, UINT8 app_id)
-{
-    UNUSED(fd);
-    UNUSED(ssn);
-    UNUSED(app_id);
-
-    BTIF_TRACE_WARNING("[CO] bta_fs_co_suspend - NOT implemented");
-}
-
diff --git a/btif/co/bta_gattc_co.c b/btif/co/bta_gattc_co.c
index 5ed7f8f..96f1bd7 100644
--- a/btif/co/bta_gattc_co.c
+++ b/btif/co/bta_gattc_co.c
@@ -16,6 +16,8 @@
  *
  ******************************************************************************/
 
+#include <stdio.h>
+#include <unistd.h>
 
 #include "gki.h"
 #include "bta_gattc_co.h"
diff --git a/btif/co/bta_gatts_co.c b/btif/co/bta_gatts_co.c
index 09a16a2..e1263d7 100644
--- a/btif/co/bta_gatts_co.c
+++ b/btif/co/bta_gatts_co.c
@@ -24,7 +24,6 @@
 #include <stdlib.h>
 #include <string.h>
 #include "gki.h"
-#include "bd.h"
 #include "bta_gatts_co.h"
 #include "btif_util.h"
 
diff --git a/btif/co/bta_hh_co.c b/btif/co/bta_hh_co.c
index d7458b1..4edf52b 100644
--- a/btif/co/bta_hh_co.c
+++ b/btif/co/bta_hh_co.c
@@ -471,8 +471,6 @@
 {
     UNUSED(app_id);
 
-    unsigned len = 0;
-    unsigned type = 0;
     unsigned idx = 0;
 
     bdstr_t bdstr;
@@ -480,18 +478,18 @@
         remote_bda[0], remote_bda[1], remote_bda[2],
         remote_bda[3], remote_bda[4], remote_bda[5]);
 
-    btif_config_get("Remote", bdstr, "HidReport", NULL, (int*)&len, (int*)&type);
+    size_t len = btif_config_get_bin_length(bdstr, "HidReport");
     if (len >= sizeof(tBTA_HH_RPT_CACHE_ENTRY) && len <= sizeof(sReportCache))
     {
-        btif_config_get("Remote", bdstr, "HidReport", (char*)sReportCache, (int*)&len, (int*)&type);
+        btif_config_get_bin(bdstr, "HidReport", (uint8_t *)sReportCache, &len);
         idx = len / sizeof(tBTA_HH_RPT_CACHE_ENTRY);
     }
 
     if (idx < BTA_HH_NV_LOAD_MAX)
     {
         memcpy(&sReportCache[idx++], p_entry, sizeof(tBTA_HH_RPT_CACHE_ENTRY));
-        btif_config_set("Remote", bdstr, "HidReport", (const char*)sReportCache,
-            idx * sizeof(tBTA_HH_RPT_CACHE_ENTRY), BTIF_CFG_TYPE_BIN);
+        btif_config_set_bin(bdstr, "HidReport", (const uint8_t *)sReportCache,
+            idx * sizeof(tBTA_HH_RPT_CACHE_ENTRY));
         BTIF_TRACE_DEBUG("%s() - Saving report; dev=%s, idx=%d", __FUNCTION__, bdstr, idx);
     }
 }
@@ -517,8 +515,6 @@
 {
     UNUSED(app_id);
 
-    unsigned len = 0;
-    unsigned type = 0;
     unsigned idx = 0;
 
     bdstr_t bdstr;
@@ -526,13 +522,13 @@
         remote_bda[0], remote_bda[1], remote_bda[2],
         remote_bda[3], remote_bda[4], remote_bda[5]);
 
-    btif_config_get("Remote", bdstr, "HidReport", NULL, (int*)&len, (int*)&type);
+    size_t len = btif_config_get_bin_length(bdstr, "HidReport");
     if (!p_num_rpt && len < sizeof(tBTA_HH_RPT_CACHE_ENTRY))
         return NULL;
 
     if (len > sizeof(sReportCache))
         len = sizeof(sReportCache);
-    btif_config_get("Remote", bdstr, "HidReport", (char*)sReportCache, (int*)&len, (int*)&type);
+    btif_config_get_bin(bdstr, "HidReport", (uint8_t *)sReportCache, &len);
     *p_num_rpt = len / sizeof(tBTA_HH_RPT_CACHE_ENTRY);
 
     BTIF_TRACE_DEBUG("%s() - Loaded %d reports; dev=%s", __FUNCTION__, *p_num_rpt, bdstr);
@@ -559,7 +555,7 @@
     sprintf(bdstr, "%02x:%02x:%02x:%02x:%02x:%02x",
         remote_bda[0], remote_bda[1], remote_bda[2],
         remote_bda[3], remote_bda[4], remote_bda[5]);
-    btif_config_remove("Remote", bdstr, "HidReport");
+    btif_config_remove(bdstr, "HidReport");
 
     BTIF_TRACE_DEBUG("%s() - Reset cache for bda %s", __FUNCTION__, bdstr);
 }
diff --git a/btif/co/bta_hl_co.c b/btif/co/bta_hl_co.c
index 22b7c89..9aa91f7 100644
--- a/btif/co/bta_hl_co.c
+++ b/btif/co/bta_hl_co.c
@@ -34,7 +34,6 @@
 #include <fcntl.h>
 #include <ctype.h>
 #include <cutils/sockets.h>
-#include <cutils/log.h>
 #include "bta_api.h"
 #include "btm_api.h"
 #include "bta_sys.h"
diff --git a/btif/co/bta_pan_co.c b/btif/co/bta_pan_co.c
index 631ffbe..50e0d8c 100644
--- a/btif/co/bta_pan_co.c
+++ b/btif/co/bta_pan_co.c
@@ -34,7 +34,6 @@
 #include <hardware/bt_pan.h>
 #include "btif_pan_internal.h"
 #include "btif_sock_thread.h"
-#include "bd.h"
 #include <string.h>
 #include "btif_util.h"
 
@@ -171,7 +170,7 @@
     if(!conn || conn->state != PAN_STATE_OPEN)
     {
         BTIF_TRACE_ERROR("bta_pan_co_tx_path: cannot find pan connction or conn"
-            "is not opened, conn:%p, conn->state:%d", conn, conn->state);
+            "is not opened, conn:%p, conn->state:%d", conn, conn ? conn->state : -1);
         return;
     }
     do
diff --git a/btif/co/bta_sys_co.c b/btif/co/bta_sys_co.c
deleted file mode 100644
index b7768ad..0000000
--- a/btif/co/bta_sys_co.c
+++ /dev/null
@@ -1,57 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#include "bta_sys.h"
-#include "bta_sys_ci.h"
-
-/*******************************************************************************
-**
-** Function         bta_sys_hw_co_enable
-**
-** Description      This function is called by the stack to power up the HW
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_sys_hw_co_enable( tBTA_SYS_HW_MODULE module )
-{
-    /* platform specific implementation to power-up the HW */
-
-
-    /* if no client/server asynchronous system like linux-based OS, directly call the ci here */
-    bta_sys_hw_ci_enabled( module );
-}
-
-
-/*******************************************************************************
-**
-** Function         bta_sys_hw_co_disable
-**
-** Description     This function is called by the stack to power down the HW
-**
-** Returns          void
-**
-*******************************************************************************/
-void bta_sys_hw_co_disable( tBTA_SYS_HW_MODULE module )
-{
-    /* platform specific implementation to power-down the HW */
-
-
-    /* if no client/server asynchronous system like linux-based OS, directly call the ci here */
-    bta_sys_hw_ci_disabled( module );
-
-}
diff --git a/btif/include/btif_common.h b/btif/include/btif_common.h
index f6361e1..9fc8df8 100644
--- a/btif/include/btif_common.h
+++ b/btif/include/btif_common.h
@@ -20,21 +20,23 @@
 #ifndef BTIF_COMMON_H
 #define BTIF_COMMON_H
 
-#include "data_types.h"
+#include <hardware/bluetooth.h>
+
 #include "bt_types.h"
 #include "bta_api.h"
+#include "osi.h"
 
 #ifndef LOG_TAG
 #error "LOG_TAG not defined, please add in .c file prior to including bt_common.h"
 #endif
 
-#include <utils/Log.h>
+#include "osi/include/log.h"
 
 /*******************************************************************************
 **  Constants & Macros
 ********************************************************************************/
 
-#define ASSERTC(cond, msg, val) if (!(cond)) { ALOGE( \
+#define ASSERTC(cond, msg, val) if (!(cond)) { LOG_ERROR( \
     "### ASSERT : %s line %d %s (%d) ###", __FILE__, __LINE__, msg, val);}
 
 /* Calculate start of event enumeration; id is top 8 bits of event */
@@ -183,9 +185,13 @@
 /**
  * BTIF_Events
  */
-void btif_enable_bluetooth_evt(tBTA_STATUS status, BD_ADDR local_bd);
+void btif_enable_bluetooth_evt(tBTA_STATUS status);
 void btif_disable_bluetooth_evt(void);
 void btif_adapter_properties_evt(bt_status_t status, uint32_t num_props, bt_property_t *p_props);
 void btif_remote_properties_evt(bt_status_t status, bt_bdaddr_t *remote_addr,
                                    uint32_t num_props, bt_property_t *p_props);
+
+void btif_init_ok(UNUSED_ATTR uint16_t event, UNUSED_ATTR char *p_param);
+void btif_init_fail(UNUSED_ATTR uint16_t event, UNUSED_ATTR char *p_param);
+
 #endif /* BTIF_COMMON_H */
diff --git a/btif/include/btif_config.h b/btif/include/btif_config.h
index 2a23a9c..30f5f5b 100644
--- a/btif/include/btif_config.h
+++ b/btif/include/btif_config.h
@@ -1,6 +1,6 @@
 /******************************************************************************
  *
- *  Copyright (C) 2009-2012 Broadcom Corporation
+ *  Copyright (C) 2014 Google, Inc.
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
@@ -16,69 +16,38 @@
  *
  ******************************************************************************/
 
-/*******************************************************************************
- *
- *  Filename:      btif_config.h
- *
- *  Description:   Bluetooth configuration Interface
- *
- *******************************************************************************/
+#pragma once
 
-#ifndef BTIF_CONFIG_H
-#define BTIF_CONFIG_H
+#include <stdbool.h>
+#include <stddef.h>
 
-#include "data_types.h"
 #include "bt_types.h"
 
-#ifdef __cplusplus
-#include <stdint.h>
-extern "C" {
-#endif
+static const char BTIF_CONFIG_MODULE[] = "btif_config_module";
 
-/*******************************************************************************
-** Constants & Macros
-********************************************************************************/
+typedef struct btif_config_section_iter_t btif_config_section_iter_t;
 
-#define BTIF_CFG_TYPE_INVALID   0
-#define BTIF_CFG_TYPE_STR       1
-#define BTIF_CFG_TYPE_INT      (1 << 1)
-#define BTIF_CFG_TYPE_BIN      (1 << 2)
-#define BTIF_CFG_TYPE_VOLATILE (1 << 15)
+bool btif_config_has_section(const char *section);
+bool btif_config_exist(const char *section, const char *key);
+bool btif_config_get_int(const char *section, const char *key, int *value);
+bool btif_config_set_int(const char *section, const char *key, int value);
+bool btif_config_get_str(const char *section, const char *key, char *value, int *size_bytes);
+bool btif_config_set_str(const char *section, const char *key, const char *value);
+bool btif_config_get_bin(const char *section, const char *key, uint8_t *value, size_t *length);
+bool btif_config_set_bin(const char *section, const char *key, const uint8_t *value, size_t length);
+bool btif_config_remove(const char *section, const char *key);
 
+size_t btif_config_get_bin_length(const char *section, const char *key);
 
-/*******************************************************************************
-**  Functions
-********************************************************************************/
+const btif_config_section_iter_t *btif_config_section_begin(void);
+const btif_config_section_iter_t *btif_config_section_end(void);
+const btif_config_section_iter_t *btif_config_section_next(const btif_config_section_iter_t *section);
+const char *btif_config_section_name(const btif_config_section_iter_t *section);
 
-int btif_config_init();
+void btif_config_save(void);
+void btif_config_flush(void);
 
-int btif_config_exist(const char* section, const char* key, const char* name);
-int btif_config_get_int(const char* section, const char* key, const char* name, int* value);
-int btif_config_set_int(const char* section, const char* key, const char* name, int value);
-int btif_config_get_str(const char* section, const char* key, const char* name, char* value, int* bytes);
-int btif_config_set_str(const char* section, const char* key, const char* name, const char* value);
+// TODO(zachoverflow): Eww...we need to move these out. These are peer specific, not config general.
+bool btif_get_address_type(const BD_ADDR bd_addr, int *p_addr_type);
+bool btif_get_device_type(const BD_ADDR bd_addr, int *p_device_type);
 
-int btif_config_get(const char* section, const char* key, const char* name, char* value, int* bytes, int* type);
-int btif_config_set(const char* section, const char* key, const char* name, const char*  value, int bytes, int type);
-
-int btif_config_remove(const char* section, const char* key, const char* name);
-int btif_config_filter_remove(const char* section, const char* filter[], int filter_count, int max_allowed);
-
-short btif_config_next_key(short current_key_pos, const char* section, char * key_name, int* key_name_bytes);
-short btif_config_next_value(short pos, const char* section, const char* key, char* value_name, int* value_name_bytes);
-
-typedef void (*btif_config_enum_callback)(void* user_data, const char* section, const char* key, const char* name,
-                                          const char*  value, int bytes, int type);
-int btif_config_enum(btif_config_enum_callback cb, void* user_data);
-
-int btif_config_save();
-void btif_config_flush();
-
-BOOLEAN btif_get_address_type(const BD_ADDR bd_addr, int *p_addr_type);
-BOOLEAN btif_get_device_type(const BD_ADDR bd_addr, int *p_device_type);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/test/suite/support/property.h b/btif/include/btif_config_transcode.h
similarity index 61%
copy from test/suite/support/property.h
copy to btif/include/btif_config_transcode.h
index a8b77c7..e020ba6 100644
--- a/test/suite/support/property.h
+++ b/btif/include/btif_config_transcode.h
@@ -18,15 +18,6 @@
 
 #pragma once
 
-#include "base.h"
+typedef struct config_t config_t;
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
-
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+config_t *btif_config_transcode(const char *xml_filename);
diff --git a/btif/include/btif_config_util.h b/btif/include/btif_config_util.h
deleted file mode 100644
index 6a8bb72..0000000
--- a/btif/include/btif_config_util.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/************************************************************************************
- *
- *  Filename:      btif_config_util.h
- *
- *  Description:   Bluetooth configuration utility api
- *
- ***********************************************************************************/
-
-#ifndef BTIF_CONFIG_UTIL_H
-#define BTIF_CONFIG_UTIL_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*******************************************************************************
-** Constants & Macros
-********************************************************************************/
-
-#define BLUEZ_PATH "/data/misc/bluetoothd/"
-#define BLUEZ_PATH_BAK "/data/misc/bluetoothd_bak"
-#define BLUEZ_LINKKEY  "linkkeys"
-#define BLUEZ_NAMES "names"
-#define BLUEZ_PROFILES "profiles"
-#define BLUEZ_CLASSES "classes"
-#define BLUEZ_TYPES "types"
-#define BLUEZ_CONFIG "config"
-#define BLUEZ_ALIASES "aliases"
-#define BLUEZ_SDP "sdp"
-
-/*******************************************************************************
-**  Functions
-********************************************************************************/
-
-int btif_config_save_file(const char* file_name);
-int btif_config_load_file(const char* file_name);
-int load_bluez_adapter_info(char* adapter_path, int size);
-int load_bluez_linkkeys(const char* adapter_path);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/btif/include/btif_media.h b/btif/include/btif_media.h
index f01286b..2ec19cb 100644
--- a/btif/include/btif_media.h
+++ b/btif/include/btif_media.h
@@ -27,8 +27,9 @@
 #ifndef BTIF_MEDIA_H
 #define BTIF_MEDIA_H
 
+#include <stdbool.h>
+
 #include "bta_api.h"
-#include "bd.h"
 #include "gki.h"
 #include "btif_av_api.h"
 #include "audio_a2dp_hw.h"
@@ -111,7 +112,7 @@
  ** Returns          void
  **
  *******************************************************************************/
-extern int btif_media_task(void *p);
+extern void btif_media_task(void);
 
 /*******************************************************************************
  **
@@ -256,7 +257,7 @@
  * Local adaptation helper functions between btif and media task
  */
 
-int btif_a2dp_start_media_task(void);
+bool btif_a2dp_start_media_task(void);
 void btif_a2dp_stop_media_task(void);
 
 void btif_a2dp_on_init(void);
@@ -273,7 +274,6 @@
 void btif_a2dp_set_rx_flush(BOOLEAN enable);
 void btif_media_check_iop_exceptions(UINT8 *peer_bda);
 void btif_reset_decoder(UINT8 *p_av);
-BOOLEAN btif_media_task_start_decoding_req(void);
 
 int btif_a2dp_get_track_frequency(UINT8 frequency);
 int btif_a2dp_get_track_channel_count(UINT8 channeltype);
diff --git a/btif/include/btif_profile_queue.h b/btif/include/btif_profile_queue.h
index b586575..f28daac 100644
--- a/btif/include/btif_profile_queue.h
+++ b/btif/include/btif_profile_queue.h
@@ -31,6 +31,7 @@
 
 bt_status_t btif_queue_connect(uint16_t uuid, const bt_bdaddr_t *bda, btif_connect_cb_t connect_cb);
 void btif_queue_advance();
+bt_status_t btif_queue_connect_next(void);
 void btif_queue_release();
 
 #endif
diff --git a/btif/include/btif_sock.h b/btif/include/btif_sock.h
index ad2c71d..1747230 100644
--- a/btif/include/btif_sock.h
+++ b/btif/include/btif_sock.h
@@ -1,6 +1,6 @@
 /******************************************************************************
  *
- *  Copyright (C) 2009-2012 Broadcom Corporation
+ *  Copyright (C) 2014 Google, Inc.
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
@@ -16,21 +16,11 @@
  *
  ******************************************************************************/
 
-/*******************************************************************************
- *
- *  Filename:      btif_sock.h
- *
- *  Description:   Bluetooth socket Interface
- *
- *******************************************************************************/
-
-#ifndef BTIF_SOCK_H
-#define BTIF_SOCK_H
+#pragma once
 
 #include <hardware/bt_sock.h>
 
-bt_status_t btif_sock_init();
-btsock_interface_t *btif_sock_get_interface();
-void btif_sock_cleanup();
+btsock_interface_t *btif_sock_get_interface(void);
 
-#endif
+bt_status_t btif_sock_init(void);
+void btif_sock_cleanup(void);
diff --git a/btif/include/btif_sock_sco.h b/btif/include/btif_sock_sco.h
new file mode 100644
index 0000000..972aeeb
--- /dev/null
+++ b/btif/include/btif_sock_sco.h
@@ -0,0 +1,28 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2013 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <hardware/bluetooth.h>
+
+typedef struct thread_t thread_t;
+
+bt_status_t btsock_sco_init(thread_t *thread);
+bt_status_t btsock_sco_cleanup(void);
+bt_status_t btsock_sco_listen(int *sock_fd, int flags);
+bt_status_t btsock_sco_connect(const bt_bdaddr_t *bd_addr, int *sock_fd, int flags);
diff --git a/btif/include/btif_sock_sdp.h b/btif/include/btif_sock_sdp.h
index 0028b50..d374d72 100644
--- a/btif/include/btif_sock_sdp.h
+++ b/btif/include/btif_sock_sdp.h
@@ -18,16 +18,17 @@
 
 #ifndef BTIF_SOCK_SDP_H
 #define BTIF_SOCK_SDP_H
-static const UINT8  UUID_OBEX_OBJECT_PUSH[] = {0x00, 0x00, 0x11, 0x05, 0x00, 0x00, 0x10, 0x00,
-                                               0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
-static const UINT8  UUID_PBAP_PSE[]         = {0x00, 0x00, 0x11, 0x2F, 0x00, 0x00, 0x10, 0x00,
-                                               0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
-static const UINT8  UUID_MAPS_MAS[]         = {0x00, 0x00, 0x11, 0x32, 0x00, 0x00, 0x10, 0x00,
-                                               0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
-static const UINT8  UUID_SPP[]              = {0x00, 0x00, 0x11, 0x01, 0x00, 0x00, 0x10, 0x00,
-                                               0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
 
-static inline BOOLEAN is_uuid_empty(const uint8_t* uuid)
+static const uint8_t  UUID_OBEX_OBJECT_PUSH[] = {0x00, 0x00, 0x11, 0x05, 0x00, 0x00, 0x10, 0x00,
+                                                 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
+static const uint8_t  UUID_PBAP_PSE[]         = {0x00, 0x00, 0x11, 0x2F, 0x00, 0x00, 0x10, 0x00,
+                                                 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
+static const uint8_t  UUID_MAPS_MAS[]         = {0x00, 0x00, 0x11, 0x32, 0x00, 0x00, 0x10, 0x00,
+                                                 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
+static const uint8_t  UUID_SPP[]              = {0x00, 0x00, 0x11, 0x01, 0x00, 0x00, 0x10, 0x00,
+                                                 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
+
+static inline bool is_uuid_empty(const uint8_t* uuid)
 {
    static  uint8_t empty_uuid[16];
    return uuid == NULL || memcmp(uuid, empty_uuid, sizeof(empty_uuid)) == 0;
@@ -35,7 +36,7 @@
 
 int add_rfc_sdp_rec(const char* name, const uint8_t* uuid, int scn);
 void del_rfc_sdp_rec(int handle);
-BOOLEAN is_reserved_rfc_channel(int channel);
+bool is_reserved_rfc_channel(int channel);
 int get_reserved_rfc_channel(const uint8_t* uuid);
 
 #endif
diff --git a/btif/include/btif_sock_thread.h b/btif/include/btif_sock_thread.h
index 9b12f56..1b5e241 100644
--- a/btif/include/btif_sock_thread.h
+++ b/btif/include/btif_sock_thread.h
@@ -19,6 +19,7 @@
 #ifndef BTIF_SOCK_THREAD_H
 #define BTIF_SOCK_THREAD_H
 
+#include <stdbool.h>
 #include <hardware/bt_sock.h>
 
 /*******************************************************************************
@@ -40,6 +41,7 @@
 
 int btsock_thread_init();
 int btsock_thread_add_fd(int handle, int fd, int type, int flags, uint32_t user_id);
+bool btsock_thread_remove_fd_and_close(int thread_handle, int fd);
 int btsock_thread_wakeup(int handle);
 int btsock_thread_post_cmd(int handle, int cmd_type, const unsigned char* cmd_data,
                            int data_size, uint32_t user_id);
diff --git a/btif/include/btif_sock_util.h b/btif/include/btif_sock_util.h
index 968f740..0659930 100644
--- a/btif/include/btif_sock_util.h
+++ b/btif/include/btif_sock_util.h
@@ -27,7 +27,35 @@
 #ifndef BTIF_SOCK_UTIL_H
 #define BTIF_SOCK_UTIL_H
 
-#include <cutils/log.h>
+#include <pthread.h>
+
+#include "osi/include/log.h"
+
+/*******************************************************************************
+**  Functions
+********************************************************************************/
+
+static inline void init_slot_lock( pthread_mutex_t* mutex)
+{
+    pthread_mutexattr_t attr;
+    pthread_mutexattr_init(&attr);
+    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
+    pthread_mutex_init(mutex, &attr);
+}
+
+static inline void lock_slot(pthread_mutex_t* mutex)
+{
+    if(mutex->value)
+        pthread_mutex_lock(mutex);
+    else LOG_ERROR("mutex: %p is not initialized", mutex);
+}
+
+static inline void unlock_slot(pthread_mutex_t* mutex)
+{
+   if(mutex->value)
+        pthread_mutex_unlock(mutex);
+   else LOG_ERROR("mutex: %p is not initialized", mutex);
+}
 
 void dump_bin(const char* title, const char* data, int size);
 
diff --git a/btif/include/btif_storage.h b/btif/include/btif_storage.h
index f64c695..bf6a5ed 100644
--- a/btif/include/btif_storage.h
+++ b/btif/include/btif_storage.h
@@ -19,19 +19,14 @@
 #ifndef BTIF_STORAGE_H
 #define BTIF_STORAGE_H
 
-#include "data_types.h"
 #include "bt_types.h"
 
-#include <utils/Log.h>
-
 /*******************************************************************************
 **  Constants & Macros
 ********************************************************************************/
 #define BTIF_STORAGE_FILL_PROPERTY(p_prop, t, l, p_v) \
          (p_prop)->type = t;(p_prop)->len = l; (p_prop)->val = (p_v);
 
-#define  BTIF_STORAGE_MAX_ALLOWED_REMOTE_DEVICE 512
-
 /*******************************************************************************
 **  Functions
 ********************************************************************************/
diff --git a/btif/include/btif_util.h b/btif/include/btif_util.h
index 4f1a9cc..2315523 100644
--- a/btif/include/btif_util.h
+++ b/btif/include/btif_util.h
@@ -22,10 +22,9 @@
 
 #include <hardware/bluetooth.h>
 #include <hardware/bt_hf.h>
-#include <utils/Log.h>
+#include <stdbool.h>
 #include <sys/time.h>
 
-#include "data_types.h"
 #include "bt_types.h"
 #include "bt_utils.h"
 
@@ -65,14 +64,11 @@
 const char* dump_rc_notification_event_id(UINT8 event_id);
 const char* dump_rc_pdu(UINT8 pdu);
 
-int str2bd(char *str, bt_bdaddr_t *addr);
-char *bd2str(const bt_bdaddr_t *addr, bdstr_t *bdstr);
-
 UINT32 devclass2uint(DEV_CLASS dev_class);
 void uint2devclass(UINT32 dev, DEV_CLASS dev_class);
 void uuid16_to_uuid128(uint16_t uuid16, bt_uuid_t* uuid128);
 
-void uuid_to_string(bt_uuid_t *p_uuid, char *str);
+void uuid_to_string_legacy(bt_uuid_t *p_uuid, char *str);
 void string_to_uuid(char *str, bt_uuid_t *p_uuid);
 int ascii_2_hex (char *p_ascii, int len, UINT8 *p_hex);
 
diff --git a/test/suite/support/property.h b/btif/include/stack_manager.h
similarity index 62%
copy from test/suite/support/property.h
copy to btif/include/stack_manager.h
index a8b77c7..1cb87fe 100644
--- a/test/suite/support/property.h
+++ b/btif/include/stack_manager.h
@@ -18,15 +18,18 @@
 
 #pragma once
 
-#include "base.h"
+#include "future.h"
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+typedef struct {
+  void (*init_stack)(void);
+  void (*start_up_stack_async)(void);
+  void (*shut_down_stack_async)(void);
+  void (*clean_up_stack_async)(void);
 
-const char *property_extract_name(const bt_property_t *property);
+  bool (*get_stack_is_running)(void);
+} stack_manager_t;
 
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
+const stack_manager_t *stack_manager_get_interface();
 
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+// TODO(zachoverflow): remove this terrible hack once the startup sequence is more sane
+future_t *stack_manager_get_hack_future();
diff --git a/btif/src/bluetooth.c b/btif/src/bluetooth.c
index 980507a..075e9cf 100644
--- a/btif/src/bluetooth.c
+++ b/btif/src/bluetooth.c
@@ -42,10 +42,15 @@
 #include <hardware/bt_rc.h>
 
 #define LOG_NDDEBUG 0
-#define LOG_TAG "bluedroid"
+#define LOG_TAG "bt_bluedroid"
 
 #include "btif_api.h"
+#include "btsnoop.h"
 #include "bt_utils.h"
+#include "osi/include/osi.h"
+#include "osi/include/allocation_tracker.h"
+#include "osi/include/log.h"
+#include "stack_manager.h"
 
 /************************************************************************************
 **  Constants & Macros
@@ -54,10 +59,6 @@
 #define is_profile(profile, str) ((strlen(str) == strlen(profile)) && strncmp((const char *)profile, str, strlen(str)) == 0)
 
 /************************************************************************************
-**  Local type definitions
-************************************************************************************/
-
-/************************************************************************************
 **  Static variables
 ************************************************************************************/
 
@@ -67,10 +68,6 @@
 bt_os_callouts_t *bt_os_callouts = NULL;
 
 /************************************************************************************
-**  Static functions
-************************************************************************************/
-
-/************************************************************************************
 **  Externs
 ************************************************************************************/
 
@@ -106,74 +103,51 @@
 **  Functions
 ************************************************************************************/
 
-static uint8_t interface_ready(void)
-{
-    /* add checks here that would prevent API calls other than init to be executed */
-    if (bt_hal_cbacks == NULL)
-        return FALSE;
-
-    return TRUE;
+static bool interface_ready(void) {
+  return bt_hal_cbacks != NULL;
 }
 
-
 /*****************************************************************************
 **
 **   BLUETOOTH HAL INTERFACE FUNCTIONS
 **
 *****************************************************************************/
 
-static int init(bt_callbacks_t* callbacks )
-{
-    ALOGI("init");
+static int init(bt_callbacks_t *callbacks) {
+  LOG_INFO("%s", __func__);
 
-    /* sanity check */
-    if (interface_ready() == TRUE)
-        return BT_STATUS_DONE;
+  if (interface_ready())
+    return BT_STATUS_DONE;
 
-    /* store reference to user callbacks */
-    bt_hal_cbacks = callbacks;
+#ifdef BLUEDROID_DEBUG
+  allocation_tracker_init();
+#endif
 
-    /* add checks for individual callbacks ? */
-
-    bt_utils_init();
-
-    /* init btif */
-    btif_init_bluetooth();
-
-    return BT_STATUS_SUCCESS;
+  bt_hal_cbacks = callbacks;
+  stack_manager_get_interface()->init_stack();
+  return BT_STATUS_SUCCESS;
 }
 
-static int enable( void )
-{
-    ALOGI("enable");
+static int enable(void) {
+  LOG_INFO("%s", __func__);
 
-    /* sanity check */
-    if (interface_ready() == FALSE)
-        return BT_STATUS_NOT_READY;
+  if (!interface_ready())
+    return BT_STATUS_NOT_READY;
 
-    return btif_enable_bluetooth();
+  stack_manager_get_interface()->start_up_stack_async();
+  return BT_STATUS_SUCCESS;
 }
 
-static int disable(void)
-{
-    /* sanity check */
-    if (interface_ready() == FALSE)
-        return BT_STATUS_NOT_READY;
+static int disable(void) {
+  if (!interface_ready())
+    return BT_STATUS_NOT_READY;
 
-    return btif_disable_bluetooth();
+  stack_manager_get_interface()->shut_down_stack_async();
+  return BT_STATUS_SUCCESS;
 }
 
-static void cleanup( void )
-{
-    /* sanity check */
-    if (interface_ready() == FALSE)
-        return;
-
-    btif_shutdown_bluetooth();
-
-    /* hal callbacks reset upon shutdown complete callback */
-
-    return;
+static void cleanup(void) {
+  stack_manager_get_interface()->clean_up_stack_async();
 }
 
 static int get_adapter_properties(void)
@@ -332,7 +306,7 @@
 
 static const void* get_profile_interface (const char *profile_id)
 {
-    ALOGI("get_profile_interface %s", profile_id);
+    LOG_INFO("get_profile_interface %s", profile_id);
 
     /* sanity check */
     if (interface_ready() == FALSE)
@@ -382,7 +356,7 @@
 
 int dut_mode_configure(uint8_t enable)
 {
-    ALOGI("dut_mode_configure");
+    LOG_INFO("dut_mode_configure");
 
     /* sanity check */
     if (interface_ready() == FALSE)
@@ -393,7 +367,7 @@
 
 int dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len)
 {
-    ALOGI("dut_mode_send");
+    LOG_INFO("dut_mode_send");
 
     /* sanity check */
     if (interface_ready() == FALSE)
@@ -405,7 +379,7 @@
 #if BLE_INCLUDED == TRUE
 int le_test_mode(uint16_t opcode, uint8_t* buf, uint8_t len)
 {
-    ALOGI("le_test_mode");
+    LOG_INFO("le_test_mode");
 
     /* sanity check */
     if (interface_ready() == FALSE)
@@ -417,13 +391,13 @@
 
 int config_hci_snoop_log(uint8_t enable)
 {
-    ALOGI("config_hci_snoop_log");
+    LOG_INFO("config_hci_snoop_log");
 
-    /* sanity check */
-    if (interface_ready() == FALSE)
+    if (!interface_ready())
         return BT_STATUS_NOT_READY;
 
-    return btif_config_hci_snoop_log(enable);
+    btsnoop_get_interface()->set_api_wants_to_log(enable);
+    return BT_STATUS_SUCCESS;
 }
 
 static int set_os_callouts(bt_os_callouts_t *callouts) {
@@ -480,20 +454,19 @@
     return 0;
 }
 
-static int open_bluetooth_stack (const struct hw_module_t* module, char const* name,
-                                 struct hw_device_t** abstraction)
-{
-    UNUSED(name);
+static int open_bluetooth_stack(const struct hw_module_t *module, UNUSED_ATTR char const *name, struct hw_device_t **abstraction) {
+  static bluetooth_device_t device = {
+    .common = {
+      .tag = HARDWARE_DEVICE_TAG,
+      .version = 0,
+      .close = close_bluetooth_stack,
+    },
+    .get_bluetooth_interface = bluetooth__get_bluetooth_interface
+  };
 
-    bluetooth_device_t *stack = malloc(sizeof(bluetooth_device_t) );
-    memset(stack, 0, sizeof(bluetooth_device_t) );
-    stack->common.tag = HARDWARE_DEVICE_TAG;
-    stack->common.version = 0;
-    stack->common.module = (struct hw_module_t*)module;
-    stack->common.close = close_bluetooth_stack;
-    stack->get_bluetooth_interface = bluetooth__get_bluetooth_interface;
-    *abstraction = (struct hw_device_t*)stack;
-    return 0;
+  device.common.module = (struct hw_module_t *)module;
+  *abstraction = (struct hw_device_t *)&device;
+  return 0;
 }
 
 
@@ -510,4 +483,3 @@
     .author = "The Android Open Source Project",
     .methods = &bt_stack_module_methods
 };
-
diff --git a/btif/src/btif_av.c b/btif/src/btif_av.c
index 22e33f8..fe30555 100644
--- a/btif/src/btif_av.c
+++ b/btif/src/btif_av.c
@@ -30,7 +30,7 @@
 #include <string.h>
 #include "hardware/bt_av.h"
 
-#define LOG_TAG "BTIF_AV"
+#define LOG_TAG "bt_btif_av"
 
 #include "btif_av.h"
 #include "btif_util.h"
@@ -39,7 +39,6 @@
 #include "btif_media.h"
 #include "bta_av_api.h"
 #include "gki.h"
-#include "bd.h"
 #include "btu.h"
 #include "bt_utils.h"
 
@@ -890,10 +889,10 @@
 {
     if (btif_av_cb.sm_handle == NULL)
     {
-        if (btif_a2dp_start_media_task() != GKI_SUCCESS)
+        if (!btif_a2dp_start_media_task())
             return BT_STATUS_FAIL;
 
-        btif_enable_service(BTA_A2DP_SERVICE_ID);
+        btif_enable_service(BTA_A2DP_SOURCE_SERVICE_ID);
 
         /* Also initialize the AV state machine */
         btif_av_cb.sm_handle = btif_sm_init((const btif_sm_handler_t*)btif_av_state_handlers, BTIF_AV_STATE_IDLE);
diff --git a/btif/src/btif_config.c b/btif/src/btif_config.c
index eb69f7d..3c5e1c4 100644
--- a/btif/src/btif_config.c
+++ b/btif/src/btif_config.c
@@ -1,6 +1,6 @@
 /******************************************************************************
  *
- *  Copyright (C) 2009-2012 Broadcom Corporation
+ *  Copyright (C) 2014 Google, Inc.
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
@@ -16,358 +16,35 @@
  *
  ******************************************************************************/
 
-/************************************************************************************
- *
- *  Filename:      btif_config.c
- *
- *  Description:   Stores the local BT adapter and remote device properties in
- *                 NVRAM storage, typically as xml file in the
- *                 mobile's filesystem
- *
- *
- ***********************************************************************************/
-#include <stdlib.h>
-#include <time.h>
-#include <string.h>
+#define LOG_TAG "bt_btif_config"
+
+#include <assert.h>
 #include <ctype.h>
+#include <pthread.h>
 #include <stdio.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <unistd.h>
-#include <dirent.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/mman.h>
-#include <stdlib.h>
-#include <private/android_filesystem_config.h>
+#include <string.h>
 
-#define LOG_TAG "btif_config"
-
-#include <hardware/bluetooth.h>
-#include "data_types.h"
-#include "bd.h"
-#include "btif_api.h"
+#include "osi/include/alarm.h"
+#include "btcore/include/bdaddr.h"
 #include "btif_config.h"
-#include "btif_config_util.h"
-#include "btif_sock_thread.h"
-#include "btif_sock_util.h"
+#include "btif_config_transcode.h"
 #include "btif_util.h"
+#include "osi/include/config.h"
+#include "btcore/include/module.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
 
-//#define UNIT_TEST
-#define CFG_PATH "/data/misc/bluedroid/"
-#define CFG_FILE_NAME "bt_config"
-#define CFG_FILE_EXT ".xml"
-#define CFG_FILE_EXT_OLD ".old"
-#define CFG_FILE_EXT_NEW ".new"
-#define CFG_GROW_SIZE (10*sizeof(cfg_node))
-#define GET_CHILD_MAX_COUNT(node) (short)((int)(node)->bytes / sizeof(cfg_node))
-#define GET_CHILD_COUNT(p) (short)((int)(p)->used / sizeof(cfg_node))
-#define ADD_CHILD_COUNT(p, c) (p)->used += (short)((c)*sizeof(cfg_node))
-#define DEC_CHILD_COUNT(p, c) (p)->used -= (short)((c)*sizeof(cfg_node))
-#define GET_NODE_COUNT(bytes) (bytes / sizeof(cfg_node))
-#define GET_NODE_BYTES(c) (c * sizeof(cfg_node))
-#define MAX_NODE_BYTES 32000
-#define CFG_CMD_SAVE 1
+#include "bt_types.h"
 
-#ifndef FALSE
-#define TRUE 1
-#define FALSE 0
-#endif
-typedef struct cfg_node_s
-{
-    const char* name;
-    union
-    {
-        struct cfg_node_s* child;
-        char* value;
-    };
-    short bytes;
-    short type;
-    short used;
-    short flag;
-} cfg_node;
+static const char *CONFIG_FILE_PATH = "/data/misc/bluedroid/bt_config.conf";
+static const char *LEGACY_CONFIG_FILE_PATH = "/data/misc/bluedroid/bt_config.xml";
+static const period_ms_t CONFIG_SETTLE_PERIOD_MS = 3000;
 
-static pthread_mutex_t slot_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
-static int pth = -1; //poll thread handle
-static cfg_node root;
-static int cached_change;
-static int save_cmds_queued;
-static void cfg_cmd_callback(int cmd_fd, int type, int flags, uint32_t user_id);
-static inline short alloc_node(cfg_node* p, short grow);
-static inline void free_node(cfg_node* p);
-static inline short find_inode(const cfg_node* p, const char* name);
-static cfg_node* find_node(const char* section, const char* key, const char* name);
-static int remove_node(const char* section, const char* key, const char* name);
-static int remove_filter_node(const char* section, const char* filter[], int filter_count, int max_allowed);
-static inline cfg_node* find_free_node(cfg_node* p);
-static int set_node(const char* section, const char* key, const char* name,
-                        const char* value, short bytes, short type);
-static int save_cfg();
-static void load_cfg();
-static short find_next_node(const cfg_node* p, short start, char* name, int* bytes);
-#ifdef UNIT_TEST
-static void cfg_test_load();
-static void cfg_test_write();
-static void cfg_test_read();
-#endif
-#define MY_LOG_LEVEL appl_trace_level
-#define MY_LOG_LAYER TRACE_LAYER_NONE | TRACE_ORG_APPL
+static void timer_config_save(void *data);
 
-static inline void dump_node(const char* title, const cfg_node* p)
-{
-    if(p) {
-        bdld("%s, p->name:%s, child/value:%p, bytes:%d",
-                          title, p->name, p->child, p->bytes);
-        bdld("p->used:%d, type:%x, p->flag:%d",
-                          p->used, p->type, p->flag);
-    } else bdld("%s is NULL", title);
-}
-
-////////////////////////////////////////////////////////////////////////////////////////////////////////////
-int btif_config_init()
-{
-    static int initialized;
-    bdld("in initialized:%d", initialized);
-    if(!initialized)
-    {
-        initialized = 1;
-        struct stat st;
-        if(stat(CFG_PATH, &st) != 0)
-            bdle("%s does not exist, need provision", CFG_PATH);
-        btsock_thread_init();
-        pthread_mutex_lock(&slot_lock);
-        root.name = "Bluedroid";
-        alloc_node(&root, CFG_GROW_SIZE);
-        dump_node("root", &root);
-        pth = btsock_thread_create(NULL, cfg_cmd_callback);
-        load_cfg();
-        pthread_mutex_unlock(&slot_lock);
-        #ifdef UNIT_TEST
-            cfg_test_write();
-            //cfg_test_read();
-            exit(0);
-        #endif
-    }
-    return pth >= 0;
-}
-int btif_config_get_int(const char* section, const char* key, const char* name, int* value)
-{
-    int size = sizeof(*value);
-    int type = BTIF_CFG_TYPE_INT;
-    return btif_config_get(section, key, name, (char*)value, &size, &type);
-}
-int btif_config_set_int(const char* section, const char* key, const char* name, int value)
-{
-    return btif_config_set(section, key, name, (char*)&value, sizeof(value), BTIF_CFG_TYPE_INT);
-}
-int btif_config_get_str(const char* section, const char* key, const char* name, char* value, int* size)
-{
-    int type = BTIF_CFG_TYPE_STR;
-    if(value)
-        *value = 0;
-    return btif_config_get(section, key, name, value, size, &type);
-}
-int btif_config_set_str(const char* section, const char* key, const char* name, const char* value)
-{
-   value = value ? value : "";
-   return btif_config_set(section, key, name, value, strlen(value) + 1, BTIF_CFG_TYPE_STR);
-}
-int btif_config_exist(const char* section, const char* key, const char* name)
-{
-    int ret = FALSE;
-    if(section && *section && key && *key)
-    {
-        pthread_mutex_lock(&slot_lock);
-        ret = find_node(section, key, name) != NULL;
-        pthread_mutex_unlock(&slot_lock);
-    }
-    return ret;
-}
-int btif_config_get(const char* section, const char* key, const char* name, char* value, int* bytes, int* type)
-{
-    int ret = FALSE;
-    bdla(section && *section && key && *key && name && *name && bytes && type);
-    bdld("section:%s, key:%s, name:%s, value:%p, bytes:%d, type:%d",
-                section, key, name, value, *bytes, *type);
-    if(section && *section && key && *key && name && *name && bytes && type)
-    {
-        pthread_mutex_lock(&slot_lock);
-        const cfg_node* node = find_node(section, key, name);
-        dump_node("found node", node);
-        if(node)
-        {
-            if(*type == node->type && value && *bytes >= node->used)
-            {
-                if(node->used > 0)
-                    memcpy(value, node->value, node->used);
-                ret = TRUE;
-            }
-            *type = node->type;
-            *bytes = node->used;
-            if(ret != TRUE)
-            {
-                if(*type != node->type)
-                    bdle("value:%s, wrong type:%d, need to be type: %d",
-                                      name, *type, node->type);
-                if(value && *bytes < node->used)
-                    bdle("value:%s, not enough size: %d bytes, need %d bytes",
-                                      name, node->used, *bytes);
-            }
-        }
-        pthread_mutex_unlock(&slot_lock);
-    }
-    return ret;
-}
-int btif_config_set(const char* section, const char* key, const char* name, const char*  value, int bytes, int type)
-{
-    int ret = FALSE;
-    bdla(section && *section && key && *key && name && *name);
-    bdla(bytes < MAX_NODE_BYTES);
-    if(section && *section && key && *key && name && *name && bytes < MAX_NODE_BYTES)
-    {
-        pthread_mutex_lock(&slot_lock);
-        ret = set_node(section, key, name, value, (short)bytes, (short)type);
-        if(ret && !(type & BTIF_CFG_TYPE_VOLATILE))
-            cached_change++;
-        pthread_mutex_unlock(&slot_lock);
-    }
-    return ret;
-}
-int btif_config_remove(const char* section, const char* key, const char* name)
-{
-    bdla(section && *section && key && *key);
-    bdld("section:%s, key:%s, name:%s", section, key, name);
-    int ret = FALSE;
-    if(section && *section && key && *key)
-    {
-         pthread_mutex_lock(&slot_lock);
-         ret = remove_node(section, key, name);
-         if(ret)
-            cached_change++;
-         pthread_mutex_unlock(&slot_lock);
-    }
-    return ret;
-}
-
-int btif_config_filter_remove(const char* section, const char* filter[], int filter_count, int max_allowed)
-{
-    bdla(section && *section && max_allowed > 0);
-    bdld("section:%s, filter:%s, filter count:%d, max allowed:%d",
-                section, filter[0], filter_count, max_allowed);
-    int ret = FALSE;
-    if(section && *section && max_allowed > 0)
-    {
-         pthread_mutex_lock(&slot_lock);
-         ret = remove_filter_node(section, filter, filter_count, max_allowed);
-         if(ret)
-            cached_change++;
-         pthread_mutex_unlock(&slot_lock);
-    }
-    return ret;
-}
-typedef struct {
-    short si;
-    short ki;
-    short vi;
-    short reserved;
-} cfg_node_pos;
-short btif_config_next_key(short pos, const char* section, char * name, int* bytes)
-{
-    int next = -1;
-    pthread_mutex_lock(&slot_lock);
-    short si = find_inode(&root, section);
-    if(si >= 0)
-    {
-        const cfg_node* section_node = &root.child[si];
-        next = find_next_node(section_node, pos, name, bytes);
-    }
-    pthread_mutex_unlock(&slot_lock);
-    return next;
-}
-short btif_config_next_value(short pos, const char* section, const char* key, char* name, int* bytes)
-{
-    int next = -1;
-    pthread_mutex_lock(&slot_lock);
-    short si = find_inode(&root, section);
-    if(si >= 0)
-    {
-        const cfg_node* section_node = &root.child[si];
-        short ki = find_inode(section_node, key);
-        if(ki >= 0)
-        {
-            const cfg_node* key_node = &section_node->child[ki];
-            next = find_next_node(key_node, pos, name, bytes);
-        }
-    }
-    pthread_mutex_unlock(&slot_lock);
-    return next;
-}
-int btif_config_enum(btif_config_enum_callback cb, void* user_data)
-{
-    bdla(cb);
-    if(!cb)
-        return FALSE;
-    pthread_mutex_lock(&slot_lock);
-    int si, ki, vi;
-    cfg_node *section_node, *key_node, *value_node;
-    for(si = 0; si < GET_CHILD_COUNT(&root); si++)
-    {
-        section_node = &root.child[si];
-        if(section_node->name && *section_node->name)
-        {
-            for(ki = 0; ki < GET_CHILD_COUNT(section_node); ki++)
-            {
-                key_node = &section_node->child[ki];
-                if(key_node->name && *key_node->name)
-                {
-                    for(vi = 0; vi < GET_CHILD_COUNT(key_node); vi++)
-                    {
-                        value_node = &key_node->child[vi];
-                        if(value_node->name && *value_node->name)
-                        {
-                            cb(user_data, section_node->name, key_node->name, value_node->name,
-                                            value_node->value, value_node->used, value_node->type);
-                        }
-                    }
-                }
-            }
-        }
-    }
-    pthread_mutex_unlock(&slot_lock);
-    return TRUE;
-}
-int btif_config_save()
-{
-    int post_cmd = 0;
-    pthread_mutex_lock(&slot_lock);
-    bdld("save_cmds_queued:%d, cached_change:%d", save_cmds_queued, cached_change);
-    if((save_cmds_queued == 0) && (cached_change > 0))
-    {
-        post_cmd = 1;
-        save_cmds_queued++;
-        bdld("post_cmd set to 1, save_cmds_queued:%d", save_cmds_queued);
-    }
-    pthread_mutex_unlock(&slot_lock);
-    /* don't hold lock when invoking send or else a deadlock could
-     * occur when the socket thread tries to do the actual saving.
-     */
-    if (post_cmd)
-        btsock_thread_post_cmd(pth, CFG_CMD_SAVE, NULL, 0, 0);
-
-    return TRUE;
-}
-void btif_config_flush()
-{
-    pthread_mutex_lock(&slot_lock);
-    if(cached_change > 0)
-        save_cfg();
-    pthread_mutex_unlock(&slot_lock);
-}
-
-/*******************************************************************************
- * Device information
- *******************************************************************************/
-BOOLEAN btif_get_device_type(const BD_ADDR bd_addr, int *p_device_type)
+// TODO(zachoverflow): Move these two functions out, because they are too specific for this file
+// {grumpy-cat/no, monty-python/you-make-me-sad}
+bool btif_get_device_type(const BD_ADDR bd_addr, int *p_device_type)
 {
     if (p_device_type == NULL)
         return FALSE;
@@ -375,17 +52,17 @@
     bt_bdaddr_t bda;
     bdcpy(bda.address, bd_addr);
 
-    char bd_addr_str[18] = {0};
-    bd2str(&bda, &bd_addr_str);
+    bdstr_t bd_addr_str;
+    bdaddr_to_string(&bda, bd_addr_str, sizeof(bd_addr_str));
 
-    if (!btif_config_get_int("Remote", bd_addr_str, "DevType", p_device_type))
+    if (!btif_config_get_int(bd_addr_str, "DevType", p_device_type))
         return FALSE;
 
-    ALOGD("%s: Device [%s] type %d", __FUNCTION__, bd_addr_str, *p_device_type);
+    LOG_DEBUG("%s: Device [%s] type %d", __FUNCTION__, bd_addr_str, *p_device_type);
     return TRUE;
 }
 
-BOOLEAN btif_get_address_type(const BD_ADDR bd_addr, int *p_addr_type)
+bool btif_get_address_type(const BD_ADDR bd_addr, int *p_addr_type)
 {
     if (p_addr_type == NULL)
         return FALSE;
@@ -393,594 +70,331 @@
     bt_bdaddr_t bda;
     bdcpy(bda.address, bd_addr);
 
-    char bd_addr_str[18] = {0};
-    bd2str(&bda, &bd_addr_str);
+    bdstr_t bd_addr_str;
+    bdaddr_to_string(&bda, bd_addr_str, sizeof(bd_addr_str));
 
-    if (!btif_config_get_int("Remote", bd_addr_str, "AddrType", p_addr_type))
+    if (!btif_config_get_int(bd_addr_str, "AddrType", p_addr_type))
         return FALSE;
 
-    ALOGD("%s: Device [%s] address type %d", __FUNCTION__, bd_addr_str, *p_addr_type);
+    LOG_DEBUG("%s: Device [%s] address type %d", __FUNCTION__, bd_addr_str, *p_addr_type);
     return TRUE;
 }
 
-/////////////////////////////////////////////////////////////////////////////////////////////
-static inline short alloc_node(cfg_node* p, short grow)
-{
-    int new_bytes = p->bytes + grow;
-    if(grow > 0 && new_bytes < MAX_NODE_BYTES)
-    {
-        char* value = (char*)realloc(p->value, new_bytes);
-        if(value)
-        {
-            short old_bytes = p->bytes;
-            //clear to zero
-            memset(value + old_bytes, 0, grow);
-            p->bytes = old_bytes + grow;
-            p->value = value;
-            return old_bytes;//return the previous size
-        }
-        else bdle("realloc failed, old_bytes:%d, grow:%d, total:%d", p->bytes, grow,  p->bytes + grow);
-    }
-    return -1;
-}
-static inline void free_node(cfg_node* p)
-{
-    if(p)
-    {
-        if(p->child)
-        {
-            free(p->child);
-            p->child = NULL;
-        }
-        if(p->name)
-        {
-            free((void*)p->name);
-            p->name = 0;
-        }
-        p->used = p->bytes = p->flag = p->type = 0;
-    }
-}
-static inline short find_inode(const cfg_node* p, const char* name)
-{
-    if(p && p->child && name && *name)
-    {
-        int i;
-        int count = GET_CHILD_COUNT(p);
-        //bdld("parent name:%s, child name:%s, child count:%d", p->name, name, count);
-        for(i = 0; i < count; i++)
-        {
-            if(p->child[i].name && *p->child[i].name &&
-                strcmp(p->child[i].name, name) == 0)
-            {
-                  return (short)i;
-            }
-        }
-    }
-    return -1;
-}
-static inline cfg_node* find_free_node(cfg_node* p)
-{
-    if(p && p->child)
-    {
-        int count = GET_CHILD_COUNT(p);
-        if(count < GET_CHILD_MAX_COUNT(p))
-            return  p->child + count;
-    }
-    return NULL;
-}
-static cfg_node* find_add_node(cfg_node* p, const char* name)
-{
-    int i = -1;
-    cfg_node* node = NULL;
-    if((i = find_inode(p, name)) < 0)
-    {
-        if(!(node = find_free_node(p)))
-        {
-            int old_size = alloc_node(p, CFG_GROW_SIZE);
-            if(old_size >= 0)
-            {
-                i = GET_NODE_COUNT(old_size);
-                node = &p->child[i];
-                ADD_CHILD_COUNT(p, 1);
-            }
-        } else ADD_CHILD_COUNT(p, 1);
-    }
-    else node = &p->child[i];
-    if(node && (!node->name))
-        node->name = strdup(name);
-    return node;
-}
-static int set_node(const char* section, const char* key, const char* name,
-                    const char* value, short bytes, short type)
-{
-    cfg_node* section_node = NULL;
-    if((section_node = find_add_node(&root, section)))
-    {
-        cfg_node* key_node;
-        if((key_node = find_add_node(section_node, key)))
-        {
-            cfg_node* value_node;
-            if((value_node = find_add_node(key_node, name)))
-            {
-                if(value_node->bytes < bytes)
-                {
-                    if(value_node->value)
-                        free(value_node->value);
-                    value_node->value = (char*)malloc(bytes);
-                    if(value_node->value)
-                        value_node->bytes = bytes;
-                    else
-                    {
-                        bdle("not enough memory!");
-                        value_node->bytes = 0;
-                        return FALSE;
-                    }
-                }
-                if(value_node->value && value != NULL && bytes > 0)
-                    memcpy(value_node->value, value, bytes);
-                value_node->type = type;
-                value_node->used = bytes;
-                return TRUE;
-            }
-        }
-    }
-    return FALSE;
-}
-static cfg_node* find_node(const char* section, const char* key, const char* name)
-{
-    int si = -1, ki = -1, vi = -1;
-    if((si = find_inode(&root, section)) >= 0)
-    {
-        cfg_node* section_node = &root.child[si];
-        if(key)
-        {
-            if((ki = find_inode(section_node, key)) >= 0)
-            {
-                cfg_node* key_node = &section_node->child[ki];
-                if(name)
-                {
-                    if((vi = find_inode(key_node, name)) >= 0)
-                    {
-                        return &key_node->child[vi];
-                    }
-                    return NULL;
-                }
-                return key_node;
-            }
-            return NULL;
-        }
-        return section_node;
-    }
-    return NULL;
-}
-static short find_next_node(const cfg_node* p, short start, char* name, int* bytes)
-{
-    bdla(0 <= start && start < GET_CHILD_COUNT(p));
-    bdld("in, start:%d, child count:%d, max count:%d", start, GET_CHILD_COUNT(p), GET_CHILD_MAX_COUNT(p));
-    short next = -1;
-    if(name) *name = 0;
-    if(0 <= start && start < GET_CHILD_COUNT(p))
-    {
-        int i;
-        for(i = start; i < GET_CHILD_COUNT(p); i++)
-        {
-            cfg_node* child = &p->child[i];
-            if(child->name)
-            {
-                int name_bytes = strlen(child->name) + 1;
-                if(name && bytes && *bytes >= name_bytes)
-                {
-                    memcpy(name, child->name, name_bytes);
-                    if(i + 1 < GET_CHILD_COUNT(p))
-                        next = (short)(i + 1);
-                    *bytes = name_bytes;
-                }
-                else if(bytes)
-                {
-                    *bytes = name_bytes;
-                }
-                break;
-            }
-        }
-    }
-    return next;
-}
-static void free_child(cfg_node* p, int ichild, int count)
-{
-    int child_count = GET_CHILD_COUNT(p);
-    bdla(p && ichild + count <= child_count && count > 0);
-    int icount = ichild + count;
-    icount = icount <= child_count ? icount : child_count;
-    int i;
-    for(i = ichild; i < icount; i++)
-        free_node(p->child + i);
-    if(i < child_count)
-    {
-        int mv_count = child_count - i;
-        memmove(p->child + ichild, p->child + i, GET_NODE_BYTES(mv_count));
-        //cleanup the buffer of already moved children
-        memset(p->child + i, 0, GET_NODE_BYTES(mv_count));
-    }
-    DEC_CHILD_COUNT(p, i - ichild);
-}
-static int remove_node(const char* section, const char* key, const char* name)
-{
-    short  si = -1, ki = -1, vi = -1;
-    if((si = find_inode(&root, section)) >= 0)
-    {
-        cfg_node* section_node = &root.child[si];
-        if((ki = find_inode(section_node, key)) >= 0)
-        {
-            cfg_node* key_node = &section_node->child[ki];
-            if(name == NULL)
-            {
-                int count = GET_CHILD_COUNT(key_node);
-                free_child(key_node, 0, count);
-                free_child(section_node, ki, 1);
-                return TRUE;
-            }
-            else if((vi = find_inode(key_node, name)) >= 0)
-            {
-                free_child(key_node, vi, 1);
-                return TRUE;
-            }
-        }
-    }
-    return FALSE;
-}
-static inline int find_first_empty(cfg_node*p, int start, int count)
-{
-    int i;
-    for(i = start; i < count; i++)
-    {
-        if(p->child[i].name == NULL)
-            return i;
-    }
-    return -1;
-}
-static inline int find_first_occupy(cfg_node*p, int start, int count)
-{
-    int i;
-    for(i = start; i < count; i++)
-        if(p->child[i].name)
-            return i;
-    return -1;
-}
+static pthread_mutex_t lock;  // protects operations on |config|.
+static config_t *config;
+static alarm_t *alarm_timer;
 
-static void pack_child(cfg_node* p)
-{
-    int child_count = GET_CHILD_COUNT(p);
-    int occupy = 1;
-    int empty = 0;
-    for(;;)
-    {
-        empty = find_first_empty(p, empty, child_count);
-        if(empty >= 0)
-        {
-            if(occupy <= empty)
-                occupy = empty + 1;
-            occupy = find_first_occupy(p, occupy, child_count);
-            bdla(occupy != 0);
-            if(occupy > 0)
-            {//move
-                p->child[empty] = p->child[occupy];
-                memset(&p->child[occupy], 0, sizeof(cfg_node));
-                empty++;
-                occupy++;
-            }
-            else break;
-        }
-        else break;
-    }
-}
-static inline int value_in_filter(cfg_node* key, const char* filter[], int filter_count)
-{
-    int i, j;
-    int child_count = GET_CHILD_COUNT(key);
-    for(i = 0; i < child_count; i++)
-    {
-        if(key->child[i].name && *key->child[i].name)
-        {
-            for(j = 0; j < filter_count; j++)
-                if(strcmp(filter[j], key->child[i].name) == 0)
-                    return TRUE;
-        }
-    }
-    return FALSE;
-}
-static int remove_filter_node(const char* section, const char* filter[], int filter_count, int max_allowed)
-{
-    int  si = -1;
-    if((si = find_inode(&root, section)) < 0)
-    {
-        bdle("cannot find section:%s", section);
-        return FALSE;
-    }
-    cfg_node* s = &root.child[si];
-    int child_count = GET_CHILD_COUNT(s);
-    bdld("section:%s, curr child count:%d, filter count:%d", section, child_count, filter_count);
-    if(child_count < max_allowed)
-        return FALSE;
-    //remove until half of max allowance left
-    int total_rm = child_count - max_allowed / 2;
-    int rm_count = 0;
-    int i;
-    for(i = 0; i < child_count; i++)
-    {
-        if(!value_in_filter(&s->child[i], filter, filter_count))
-        {
-            free_child(&s->child[i], 0, GET_CHILD_COUNT(&s->child[i]));
-            free_node(&s->child[i]);
-            rm_count++;
-            if(rm_count >= total_rm)
-                break;
-        }
-    }
-    if(rm_count)
-    {
-        pack_child(s);
-        DEC_CHILD_COUNT(s, rm_count);
-        return TRUE;
-    }
-    return FALSE;
-}
+// Module lifecycle functions
 
-static int save_cfg()
-{
-    const char* file_name = CFG_PATH CFG_FILE_NAME CFG_FILE_EXT;
-    const char* file_name_new = CFG_PATH CFG_FILE_NAME CFG_FILE_EXT_NEW;
-    const char* file_name_old = CFG_PATH CFG_FILE_NAME CFG_FILE_EXT_OLD;
-    int ret = FALSE;
-    if(access(file_name_old,  F_OK) == 0)
-        unlink(file_name_old);
-    if(access(file_name_new, F_OK) == 0)
-        unlink(file_name_new);
-   if(btif_config_save_file(file_name_new))
-    {
-        cached_change = 0;
-        chown(file_name_new, -1, AID_NET_BT_STACK);
-        chmod(file_name_new, 0660);
-        rename(file_name, file_name_old);
-        rename(file_name_new, file_name);
-        ret = TRUE;
-    }
-    else bdle("btif_config_save_file failed");
-    return ret;
-}
-
-static int load_bluez_cfg()
-{
-    char adapter_path[256];
-    if(load_bluez_adapter_info(adapter_path, sizeof(adapter_path)))
-    {
-        if(load_bluez_linkkeys(adapter_path))
-            return TRUE;
-    }
-    return FALSE;
-}
-static void remove_bluez_cfg()
-{
-    rename(BLUEZ_PATH, BLUEZ_PATH_BAK);
-}
-static void clean_newline_char()
-{
-    char kname[128], vname[128];
-    short kpos = 0;
-    int kname_size, vname_size;
-    vname[0] = 0;
-    vname_size = sizeof(vname);
-    //bdld("removing newline at the end of the adapter and device name");
-    if(btif_config_get_str("Local", "Adapter", "Name", vname, &vname_size) &&
-        vname_size > 2)
-    {
-        if(vname[vname_size - 2] == '\n')
-        {
-            bdld("remove newline at the end of the adapter name:%s", vname);
-            vname[vname_size - 2] = 0;
-            btif_config_set_str("Local", "Adapter", "Name", vname);
-        }
-    }
-    do
-    {
-        kname_size = sizeof(kname);
-        kname[0] = 0;
-        kpos = btif_config_next_key(kpos, "Remote", kname, &kname_size);
-        //bdld("Remote device:%s, size:%d", kname, kname_size);
-        vname_size = sizeof(vname);
-        vname[0] = 0;
-        if(btif_config_get_str("Remote", kname, "Name", vname, &vname_size) &&
-            vname_size > 2)
-        {
-            bdld("remote device name:%s", vname);
-            if(vname[vname_size - 2] == '\n')
-            {
-                bdld("remove newline at the end of the device name:%s", vname);
-                vname[vname_size - 2] = 0;
-                btif_config_set_str("Remote", kname, "Name", vname);
-            }
-        }
-     } while(kpos != -1);
-}
-static void load_cfg()
-{
-    const char* file_name = CFG_PATH CFG_FILE_NAME CFG_FILE_EXT;
-    const char* file_name_old = CFG_PATH CFG_FILE_NAME CFG_FILE_EXT_OLD;
-    if(!btif_config_load_file(file_name))
-    {
-        unlink(file_name);
-        if(!btif_config_load_file(file_name_old))
-        {
-            unlink(file_name_old);
-            if(load_bluez_cfg() && save_cfg())
-                remove_bluez_cfg();
-        }
-    }
-    int bluez_migration_done = 0;
-    btif_config_get_int("Local", "Adapter", "BluezMigrationDone", &bluez_migration_done);
-    if(!bluez_migration_done)
-    {
-        //clean the new line char at the end of the device name. Caused by bluez config import bug
-        clean_newline_char();
-        btif_config_set_int("Local", "Adapter", "BluezMigrationDone", 1);
-        btif_config_save();
-    }
-}
-static void cfg_cmd_callback(int cmd_fd, int type, int size, uint32_t user_id)
-{
-    UNUSED(cmd_fd);
-    UNUSED(size);
-    UNUSED(user_id);
-
-    switch(type)
-    {
-        case CFG_CMD_SAVE:
-        {
-            int i;
-            int last_cached_change;
-
-            // grab lock while accessing cached_change.
-            pthread_mutex_lock(&slot_lock);
-            bdla(save_cmds_queued > 0);
-            save_cmds_queued--;
-            last_cached_change = cached_change;
-            //hold the file saving until no more change in last 3 seconds.
-            bdld("wait until no more changes in short time, cached change:%d", cached_change);
-            for(i = 0; i < 100; i ++) //5 minutes max waiting
-            {
-                // don't sleep if there is nothing to do
-                if(cached_change == 0)
-                    break;
-                // release lock during sleep
-                pthread_mutex_unlock(&slot_lock);
-                sleep(3);
-                pthread_mutex_lock(&slot_lock);
-                if(last_cached_change == cached_change)
-                    break;
-                last_cached_change = cached_change;
-            }
-            bdld("writing the bt_config.xml now, cached change:%d", cached_change);
-            if(cached_change > 0)
-                save_cfg();
-            pthread_mutex_unlock(&slot_lock);
-            break;
-        }
-    }
-}
-#ifdef UNIT_TEST
-static void cfg_test_load()
-{
-    load_cfg();
-    char kname[128], vname[128];
-    short kpos, vpos;
-    int kname_size, vname_size;
-    bdld("list all remote devices values:");
-    kname_size = sizeof(kname);
-    kname[0] = 0;
-    kpos = 0;
-    do
-    {
-        kpos = btif_config_next_key(kpos, "Remote Devices", kname, &kname_size);
-        bdld("Remote devices:%s, size:%d", kname, kname_size);
-        vpos = 0;
-        vname[0] = 0;
-        vname_size = sizeof(vname);
-        while((vpos = btif_config_next_value(vpos, "Remote Devices", kname, vname, &vname_size)) != -1)
-        {
-            char v[128] = {0};
-            int vtype = BTIF_CFG_TYPE_STR;
-            int vsize = sizeof(v);
-            int ret = btif_config_get("Remote Devices", kname, vname, v, &vsize, &vtype);
-            bdld("btif_config_get return:%d, Remote devices:%s, value name:%s, value:%s, value size:%d, type:0x%x",
-                              ret, kname, vname, v, vsize, vtype);
-
-            vname[0] = 0;
-            vname_size = sizeof(vname);
-        }
-        kname[0] = 0;
-        kname_size = sizeof(kname);
-    } while(kpos != -1);
-}
-static void cfg_test_write()
-{
-    int i;
-
-    char key[128];
-    const char* section = "Remote";
-    char link_key[64];
-    for(i = 0; i < (int)sizeof(link_key); i++)
-        link_key[i] = i;
-    bdld("[start write testing");
-    if(btif_config_exist("test", "test cfg", "write"))
-        return;
-    btif_config_set_int("test", "test cfg", "write", 1);
-    for(i = 0; i < 50; i++)
-    {
-        if(i % 3 == 0)
-            sprintf(key, "Remote paired %d", i);
-        else sprintf(key, "Remote %d", i);
-        link_key[0] = i;
-        btif_config_set_str(section, key, "class", "smart phone");
-        if(i % 3 == 0)
-        {
-            if(i % 6 == 0)
-                btif_config_set(section, key, "LinkKey", link_key, sizeof(link_key), BTIF_CFG_TYPE_BIN);
-            else btif_config_set(section, key, "LE_KEY_LCSRK", link_key, sizeof(link_key), BTIF_CFG_TYPE_BIN);
-        }
-        btif_config_set_int(section, key, "count", i);
-        if(!btif_config_exist(section, key, "time stamp"))
-            btif_config_set_int(section, key, "time stamp", time(NULL));
-    }
-    static const char* exclude_filter[] =
-    {"LinkKey", "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"};
-    const int max_allowed_remote_device = 40;
-    btif_config_filter_remove("Remote", exclude_filter, sizeof(exclude_filter)/sizeof(char*),
-            max_allowed_remote_device);
-    bdld("]end write testing");
-    btif_config_flush();
-}
-static void cfg_test_read()
-{
-    //debug("in");
-    char class[128] = {0};
-    char link_key[128] = {0};
-    int size, type;
-    char key[128];
-    const char* section;
-    int ret, i;
-    for(i = 0; i < 100; i++)
-    {
-        sprintf(key, "00:22:5F:97:56:%02d", i);
-        section = "Remote";
-        size = sizeof(class);
-        ret = btif_config_get_str(section, key, "class", class, &size);
-        bdld("btif_config_get_str return:%d, Remote devices:%s, class:%s", ret, key, class);
-
-        size = sizeof(link_key);
-        type = BTIF_CFG_TYPE_BIN;
-        ret = btif_config_get(section, key, "link keys", link_key, &size, &type);
-        //debug("btif_config_get return:%d, Remote devices:%s, link key:%x, %x",
-        //            ret, key, *(int *)link_key, *((int *)link_key + 1));
-
-        int timeout;
-        ret = btif_config_get_int(section, key, "connect time out", &timeout);
-        //debug("btif_config_get_int return:%d, Remote devices:%s, connect time out:%d", ret, key, timeout);
+static future_t *init(void) {
+  pthread_mutex_init(&lock, NULL);
+  config = config_new(CONFIG_FILE_PATH);
+  if (!config) {
+    LOG_WARN("%s unable to load config file; attempting to transcode legacy file.", __func__);
+    config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH);
+    if (!config) {
+      LOG_WARN("%s unable to transcode legacy file, starting unconfigured.", __func__);
+      config = config_new_empty();
+      if (!config) {
+        LOG_ERROR("%s unable to allocate a config object.", __func__);
+        goto error;
+      }
     }
 
-    // debug("testing btif_config_remove");
-    size = sizeof(class);
-    type = BTIF_CFG_TYPE_STR;
-    btif_config_set("Remote", "00:22:5F:97:56:04", "Class Delete", class, strlen(class) + 1, BTIF_CFG_TYPE_STR);
+    if (config_save(config, CONFIG_FILE_PATH))
+      unlink(LEGACY_CONFIG_FILE_PATH);
+  }
 
-    btif_config_get("Remote", "00:22:5F:97:56:04", "Class Delete", class, &size, &type);
-    // debug("Remote devices, 00:22:5F:97:56:04 Class Delete:%s", class);
-    btif_config_remove("Remote", "00:22:5F:97:56:04", "Class Delete");
+  // TODO(sharvil): use a non-wake alarm for this once we have
+  // API support for it. There's no need to wake the system to
+  // write back to disk.
+  alarm_timer = alarm_new();
+  if (!alarm_timer) {
+    LOG_ERROR("%s unable to create alarm.", __func__);
+    goto error;
+  }
 
-    size = sizeof(class);
-    type = BTIF_CFG_TYPE_STR;
-    ret = btif_config_get("Remote", "00:22:5F:97:56:04", "Class Delete", class, &size, &type);
-    // debug("after removed, btif_config_get ret:%d, Remote devices, 00:22:5F:97:56:04 Class Delete:%s", ret, class);
-    // debug("out");
+  return future_new_immediate(FUTURE_SUCCESS);
+
+error:;
+  alarm_free(alarm_timer);
+  config_free(config);
+  pthread_mutex_destroy(&lock);
+  alarm_timer = NULL;
+  config = NULL;
+  return future_new_immediate(FUTURE_FAIL);
 }
 
+static future_t *shut_down(void) {
+  btif_config_flush();
+  return future_new_immediate(FUTURE_SUCCESS);
+}
 
-#endif
+static future_t *clean_up(void) {
+  btif_config_flush();
+
+  alarm_free(alarm_timer);
+  config_free(config);
+  pthread_mutex_destroy(&lock);
+  alarm_timer = NULL;
+  config = NULL;
+  return future_new_immediate(FUTURE_SUCCESS);
+}
+
+const module_t btif_config_module = {
+  .name = BTIF_CONFIG_MODULE,
+  .init = init,
+  .start_up = NULL,
+  .shut_down = shut_down,
+  .clean_up = clean_up,
+  .dependencies = {
+    NULL
+  }
+};
+
+bool btif_config_has_section(const char *section) {
+  assert(config != NULL);
+  assert(section != NULL);
+
+  pthread_mutex_lock(&lock);
+  bool ret = config_has_section(config, section);
+  pthread_mutex_unlock(&lock);
+
+  return ret;
+}
+
+bool btif_config_exist(const char *section, const char *key) {
+  assert(config != NULL);
+  assert(section != NULL);
+  assert(key != NULL);
+
+  pthread_mutex_lock(&lock);
+  bool ret = config_has_key(config, section, key);
+  pthread_mutex_unlock(&lock);
+
+  return ret;
+}
+
+bool btif_config_get_int(const char *section, const char *key, int *value) {
+  assert(config != NULL);
+  assert(section != NULL);
+  assert(key != NULL);
+  assert(value != NULL);
+
+  pthread_mutex_lock(&lock);
+  bool ret = config_has_key(config, section, key);
+  if (ret)
+    *value = config_get_int(config, section, key, *value);
+  pthread_mutex_unlock(&lock);
+
+  return ret;
+}
+
+bool btif_config_set_int(const char *section, const char *key, int value) {
+  assert(config != NULL);
+  assert(section != NULL);
+  assert(key != NULL);
+
+  pthread_mutex_lock(&lock);
+  config_set_int(config, section, key, value);
+  pthread_mutex_unlock(&lock);
+
+  return true;
+}
+
+bool btif_config_get_str(const char *section, const char *key, char *value, int *size_bytes) {
+  assert(config != NULL);
+  assert(section != NULL);
+  assert(key != NULL);
+  assert(value != NULL);
+  assert(size_bytes != NULL);
+
+  pthread_mutex_lock(&lock);
+  const char *stored_value = config_get_string(config, section, key, NULL);
+  pthread_mutex_unlock(&lock);
+
+  if (!stored_value)
+    return false;
+
+  strlcpy(value, stored_value, *size_bytes);
+  *size_bytes = strlen(value) + 1;
+
+  return true;
+}
+
+bool btif_config_set_str(const char *section, const char *key, const char *value) {
+  assert(config != NULL);
+  assert(section != NULL);
+  assert(key != NULL);
+  assert(value != NULL);
+
+  pthread_mutex_lock(&lock);
+  config_set_string(config, section, key, value);
+  pthread_mutex_unlock(&lock);
+
+  return true;
+}
+
+bool btif_config_get_bin(const char *section, const char *key, uint8_t *value, size_t *length) {
+  assert(config != NULL);
+  assert(section != NULL);
+  assert(key != NULL);
+  assert(value != NULL);
+  assert(length != NULL);
+
+  pthread_mutex_lock(&lock);
+  const char *value_str = config_get_string(config, section, key, NULL);
+  pthread_mutex_unlock(&lock);
+
+  if (!value_str)
+    return false;
+
+  size_t value_len = strlen(value_str);
+  if ((value_len % 2) != 0 || *length < (value_len / 2))
+    return false;
+
+  for (size_t i = 0; i < value_len; ++i)
+    if (!isxdigit(value_str[i]))
+      return false;
+
+  for (*length = 0; *value_str; value_str += 2, *length += 1)
+    sscanf(value_str, "%02hhx", &value[*length]);
+
+  return true;
+}
+
+size_t btif_config_get_bin_length(const char *section, const char *key) {
+  assert(config != NULL);
+  assert(section != NULL);
+  assert(key != NULL);
+
+  pthread_mutex_lock(&lock);
+  const char *value_str = config_get_string(config, section, key, NULL);
+  pthread_mutex_unlock(&lock);
+
+  if (!value_str)
+    return 0;
+
+  size_t value_len = strlen(value_str);
+  return ((value_len % 2) != 0) ? 0 : (value_len / 2);
+}
+
+bool btif_config_set_bin(const char *section, const char *key, const uint8_t *value, size_t length) {
+  static const char *lookup = "0123456789abcdef";
+
+  assert(config != NULL);
+  assert(section != NULL);
+  assert(key != NULL);
+  assert(value != NULL);
+
+  char *str = (char *)calloc(length * 2 + 1, 1);
+  if (!str)
+    return false;
+
+  for (size_t i = 0; i < length; ++i) {
+    str[(i * 2) + 0] = lookup[(value[i] >> 4) & 0x0F];
+    str[(i * 2) + 1] = lookup[(value[i] >> 0) & 0x0F];
+  }
+
+  pthread_mutex_lock(&lock);
+  config_set_string(config, section, key, str);
+  pthread_mutex_unlock(&lock);
+
+  free(str);
+  return true;
+}
+
+const btif_config_section_iter_t *btif_config_section_begin(void) {
+  assert(config != NULL);
+  return (const btif_config_section_iter_t *)config_section_begin(config);
+}
+
+const btif_config_section_iter_t *btif_config_section_end(void) {
+  assert(config != NULL);
+  return (const btif_config_section_iter_t *)config_section_end(config);
+}
+
+const btif_config_section_iter_t *btif_config_section_next(const btif_config_section_iter_t *section) {
+  assert(config != NULL);
+  assert(section != NULL);
+  return (const btif_config_section_iter_t *)config_section_next((const config_section_node_t *)section);
+}
+
+const char *btif_config_section_name(const btif_config_section_iter_t *section) {
+  assert(config != NULL);
+  assert(section != NULL);
+  return config_section_name((const config_section_node_t *)section);
+}
+
+bool btif_config_remove(const char *section, const char *key) {
+  assert(config != NULL);
+  assert(section != NULL);
+  assert(key != NULL);
+
+  pthread_mutex_lock(&lock);
+  bool ret = config_remove_key(config, section, key);
+  pthread_mutex_unlock(&lock);
+
+  return ret;
+}
+
+void btif_config_save(void) {
+  assert(alarm_timer != NULL);
+  assert(config != NULL);
+
+  alarm_set(alarm_timer, CONFIG_SETTLE_PERIOD_MS, timer_config_save, NULL);
+}
+
+void btif_config_flush(void) {
+  assert(config != NULL);
+  assert(alarm_timer != NULL);
+
+  alarm_cancel(alarm_timer);
+
+  pthread_mutex_lock(&lock);
+  config_save(config, CONFIG_FILE_PATH);
+  pthread_mutex_unlock(&lock);
+}
+
+static void timer_config_save(UNUSED_ATTR void *data) {
+  assert(config != NULL);
+  assert(alarm_timer != NULL);
+
+  // Garbage collection process: the config file accumulates
+  // cached information about remote devices during regular
+  // inquiry scans. We remove some of these junk entries
+  // so the file doesn't grow indefinitely. We have to take care
+  // to make sure we don't remove information about bonded
+  // devices (hence the check for link keys).
+  static const size_t CACHE_MAX = 256;
+  const char *keys[CACHE_MAX];
+  size_t num_keys = 0;
+  size_t total_candidates = 0;
+
+  pthread_mutex_lock(&lock);
+  for (const config_section_node_t *snode = config_section_begin(config); snode != config_section_end(config); snode = config_section_next(snode)) {
+    const char *section = config_section_name(snode);
+    if (!string_is_bdaddr(section))
+      continue;
+
+    if (config_has_key(config, section, "LinkKey") ||
+        config_has_key(config, section, "LE_KEY_PENC") ||
+        config_has_key(config, section, "LE_KEY_PID") ||
+        config_has_key(config, section, "LE_KEY_PCSRK") ||
+        config_has_key(config, section, "LE_KEY_LENC") ||
+        config_has_key(config, section, "LE_KEY_LCSRK"))
+      continue;
+
+    if (num_keys < CACHE_MAX)
+      keys[num_keys++] = section;
+
+    ++total_candidates;
+  }
+
+  if (total_candidates > CACHE_MAX * 2)
+    while (num_keys > 0)
+      config_remove_section(config, keys[--num_keys]);
+
+  config_save(config, CONFIG_FILE_PATH);
+  pthread_mutex_unlock(&lock);
+}
diff --git a/btif/src/btif_config_transcode.cpp b/btif/src/btif_config_transcode.cpp
new file mode 100644
index 0000000..fb38a4a
--- /dev/null
+++ b/btif/src/btif_config_transcode.cpp
@@ -0,0 +1,61 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_btif_config_transcode"
+
+#include <tinyxml2.h>
+
+extern "C" {
+#include "osi/include/config.h"
+#include "osi/include/log.h"
+}
+
+using namespace tinyxml2;
+
+extern "C" config_t *btif_config_transcode(const char *xml_filename) {
+  XMLDocument document;
+  int error = document.LoadFile(xml_filename);
+  if (error != XML_SUCCESS) {
+    LOG_ERROR("%s unable to load XML file '%s': %d", __func__, xml_filename, error);
+    return NULL;
+  }
+
+  XMLElement *rootElement = document.RootElement();
+  if (!rootElement) {
+    LOG_ERROR("%s unable to find root element; assuming corrupted config file.", __func__);
+    return NULL;
+  }
+
+  config_t *config = config_new_empty();
+  if (!config) {
+    LOG_ERROR("%s unable to allocate config object.", __func__);
+    return NULL;
+  }
+
+  for (XMLElement *i = rootElement->FirstChildElement(); i != NULL; i = i->NextSiblingElement())
+    for (XMLElement *j = i->FirstChildElement(); j != NULL; j = j->NextSiblingElement()) {
+      const char *section = j->Attribute("Tag");
+      for (XMLElement *k = j->FirstChildElement(); k != NULL; k = k->NextSiblingElement()) {
+        const char *key = k->Attribute("Tag");
+        const char *value = k->GetText();
+        config_set_string(config, section, key, value);
+      }
+    }
+
+  return config;
+}
diff --git a/btif/src/btif_config_util.cpp b/btif/src/btif_config_util.cpp
deleted file mode 100644
index a6d9f6f..0000000
--- a/btif/src/btif_config_util.cpp
+++ /dev/null
@@ -1,909 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-#include <stdio.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/statfs.h>
-#include <sys/vfs.h>
-#include <unistd.h>
-#include <dirent.h>
-#include <limits.h>
-#include <sys/file.h>
-#include <sys/mman.h>
-
-#include "btif_config.h"
-#include "btif_config_util.h"
-#ifndef ANDROID_NDK
-#define ANDROID_NDK
-#endif
-#include "tinyxml2.h"
-#ifndef FALSE
-#define TRUE 1
-#define FALSE 0
-#endif
-#define LOG_TAG "btif_config_util"
-extern "C" {
-#include "btif_sock_util.h"
-}
-#include <stdlib.h>
-#include <cutils/log.h>
-#define info(fmt, ...)  ALOGI ("%s(L%d): " fmt,__FUNCTION__, __LINE__,  ## __VA_ARGS__)
-#define debug(fmt, ...) ALOGD ("%s(L%d): " fmt,__FUNCTION__, __LINE__,  ## __VA_ARGS__)
-#define warn(fmt, ...) ALOGW ("## WARNING : %s(L%d): " fmt "##",__FUNCTION__, __LINE__, ## __VA_ARGS__)
-#define error(fmt, ...) ALOGE ("## ERROR : %s(L%d): " fmt "##",__FUNCTION__, __LINE__, ## __VA_ARGS__)
-#define asrt(s) if(!(s)) ALOGE ("## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
-
-#define BLUEDROID_ROOT "Bluedroid"
-#define BLUEDROID_NAME_TAG "Tag"
-#define BLUEDROID_VALUE_TYPE "Type"
-#define BLUEDROID_TAG_REMOTE_DEVICE "Remote Devices"
-
-#define HID_SUB_CLASS      "020208"
-#define HID_COUNTRY_CODE      "020308"
-#define HID_VIRTUAL_CABLE      "020428"
-#define HID_RECON_INNITIATE      "020528"
-#define HID_REP_DSC_1      "020636"
-#define HID_REP_DSC_2      "020635"
-#define HID_SDP_DISABLE      "020828"
-#define HID_BAT_POWER      "020928"
-#define HID_REM_WAKE      "020A28"
-#define HID_SUP_TIME      "020C09"
-#define HID_NORM_CONN      "020D28"
-#define HID_SSR_MAX_LAT      "020F09"
-#define HID_SSR_MIN_TIM      "021009"
-#define HID_VENDOR_ID      "020109"
-#define HID_PRODUCT_ID      "020209"
-#define HID_PRODUCT_VERSION      "020309"
-#define HID_APP_ID_MOUSE      1
-#define HID_APP_ID_KYB      2
-#define HID_PAIRED_DEV_PRIORITY      100
-#define HID_SSR_PARAM_INVALID    0xffff
-#define HID_RPT_DSCR_HDR_LEN_1    10
-#define HID_RPT_DSCR_HDR_LEN_2    7
-
-/* Hid Atribute Mask */
-#define HID_ATTR_MASK_VIRTUAL_CABLE        0x0001
-#define HID_ATTR_MASK_NORMALLY_CONNECTABLE 0x0002
-#define HID_ATTR_MASK_RECONN_INIT          0x0004
-#define HID_ATTR_MASK_SDP_DISABLE          0x0008
-#define HID_ATTR_MASK_BATTERY_POWER        0x0010
-#define HID_ATTR_MASK_REMOTE_WAKE          0x0020
-#define HID_ATTR_MASK_SUP_TOUT_AVLBL       0x0040
-#define HID_ATTR_MASK_SSR_MAX_LATENCY      0x0080
-#define HID_ATTR_MASK_SSR_MIN_TOUT         0x0100
-#define HID_ATTR_MASK_SEC_REQUIRED         0x8000
-
-using namespace tinyxml2;
-struct enum_user_data
-{
-    const char* sn; //current section name
-    const char* kn; //current key name
-    const char* vn; //current value name
-    int si, ki, vi;
-    XMLDocument* xml;
-    XMLElement* se;
-    XMLElement* ke;
-    XMLElement* ve;
-};
-
-
-static int type_str2int(const char* type);
-static const char* type_int2str(int type);
-static inline void create_ele_name(int index, char* element, int len);
-static inline int validate_ele_name(const char* key);
-static int parse_sections(const char* section_name, const XMLElement* section);
-static void enum_config(void* user_data, const char* section, const char* key, const char* name,
-                                          const char*  value, int bytes, int type);
-static inline void bytes2hex(const char* data, int bytes, char* str)
-{
-    static const char* hex_table = "0123456789abcdef";
-    for(int i = 0; i < bytes; i++)
-    {
-        *str = hex_table[(data[i] >> 4) & 0xf];
-        ++str;
-        *str = hex_table[data[i] & 0xf];
-        ++str;
-    }
-    *str = 0;
-}
-static inline int hex2byte(char hex)
-{
-    if('0' <= hex && hex <= '9')
-        return hex - '0';
-    if('a' <= hex && hex <= 'z')
-        return hex - 'a' + 0xa;
-    if('A' <= hex && hex <= 'Z')
-        return hex - 'A' + 0xa;
-    return -1;
-}
-static inline int trim_bin_str_value(const char** str)
-{
-    while(**str == ' ' || **str == '\r' || **str == '\t' || **str == '\n')
-        (*str)++;
-    int len = 0;
-    const char* s = *str;
-    while(*s && *s != ' ' && *s != '\r' && *s != '\t' && *s != '\n')
-    {
-        len++;
-        s++;
-    }
-    return len;
-}
-static inline bool hex2bytes(const char* str, int len, char* data)
-{
-    if(len % 2)
-    {
-        error("cannot convert odd len hex str: %s, len:%d to binary", str, len);
-        return false;
-    }
-    for(int i = 0; i < len; i+= 2)
-    {
-        int d = hex2byte(str[i]);
-        if(d < 0)
-        {
-            error("cannot convert hex: %s, len:%d to binary", str, len);
-            return false;
-        }
-        *data = (char)(d << 4);
-        d = hex2byte(str[i+1]);
-        if(d < 0)
-        {
-            error("cannot convert hex: %s, len:%d to binary", str, len);
-            return false;
-        }
-        *data++ |= (char)d;
-    }
-    return true;
-}
-static inline void reverse_bin(char *bin, int size)
-{
-    for(int i = 0; i < size /2; i++)
-    {
-        int b = bin[i];
-        bin[i] = bin[size - i - 1];
-        bin[size -i  - 1] = b;
-    }
-}
-////////////////////////////////////////////////////////////////////////////////////////////////////////
-int btif_config_save_file(const char* file_name)
-{
-    debug("in file name:%s", file_name);
-    XMLDocument xml;
-    XMLElement* root = xml.NewElement(BLUEDROID_ROOT);
-    xml.InsertFirstChild(root);
-    int ret = FALSE;
-    enum_user_data data;
-    memset(&data, 0, sizeof(data));
-    data.xml = &xml;
-    if(btif_config_enum(enum_config, &data))
-        ret = xml.SaveFile(file_name) == XML_SUCCESS;
-    return ret;
-}
-int btif_config_load_file(const char* file_name)
-{
-    //if(access(file_name, 0) != 0)
-    //    return XML_ERROR_FILE_NOT_FOUND;
-    XMLDocument xml;
-    int err = xml.LoadFile(file_name);
-    const XMLElement* root = xml.RootElement();
-    int ret = FALSE;
-    if(err == XML_SUCCESS && root && strcmp(root->Name(), BLUEDROID_ROOT) == 0)
-    {
-        const XMLElement* section;
-        for(section = root->FirstChildElement(); section; section = section->NextSiblingElement())
-        {
-            //debug("section tag:%s", section->Name());
-            if(validate_ele_name(section->Name()))
-            {
-                const char* section_name = section->Attribute(BLUEDROID_NAME_TAG);
-                if(section_name && *section_name)
-                    if(parse_sections(section_name, section))
-                        ret = TRUE;
-            }
-        }
-    }
-    return ret;
-}
-//////////////////////////////////////////////////////////////////////////////////////////////////////////
-static int parse_sections(const char* section_name, const XMLElement* section)
-{
-    const XMLElement* key;
-    //debug("in");
-    for(key = section->FirstChildElement(); key; key = key->NextSiblingElement())
-    {
-        //debug("key tag:%s", key->Name());
-        if(validate_ele_name(key->Name()))
-        {
-            const char* key_name = key->Attribute(BLUEDROID_NAME_TAG);
-            //debug("key name:%s", key_name);
-            if(key_name && *key_name)
-            {
-                const XMLElement* value;
-                for(value = key->FirstChildElement(); value; value = value->NextSiblingElement())
-                {
-                    const char* value_name = value->Attribute(BLUEDROID_NAME_TAG);
-                    const char* value_type = value->Attribute(BLUEDROID_VALUE_TYPE);
-                    //debug("value ele name:%s, section name:%s, key name:%s, value name:%s, value type:%s",
-                    //        value->Name(), section_name, key_name, value_name, value_type);
-                    int type = type_str2int(value_type);
-                    if(value_name && *value_name && type != BTIF_CFG_TYPE_INVALID)
-                    {
-                        const char* value_str = value->GetText() ? value->GetText() : "";
-                        //debug("value_name:%s, value_str:%s, value_type:%s, type:%x",
-                        //       value_name, value_str, value_type, type);
-                        if(type & BTIF_CFG_TYPE_STR)
-                            btif_config_set_str(section_name, key_name, value_name, value_str);
-                        else if(type & BTIF_CFG_TYPE_INT)
-                        {
-                            if(*value_str)
-                            {
-                                int v = atoi(value_str);
-                                btif_config_set_int(section_name, key_name, value_name, v);
-                            }
-                        }
-                        else if(type & BTIF_CFG_TYPE_BIN)
-                        {
-                            int len = trim_bin_str_value(&value_str);
-                            if(len > 0 && len % 2 == 0)
-                            {
-                                char *bin = (char*)alloca(len / 2);
-                                if(hex2bytes(value_str, len, bin))
-                                    btif_config_set(section_name, key_name, value_name, bin, len/2, BTIF_CFG_TYPE_BIN);
-                            }
-                        }
-                        else error("Unsupported value:%s, type:%s not loaded", value_name, value_type);
-                    }
-                }
-            }
-        }
-    }
-    //debug("out");
-    return TRUE;
-}
-static inline XMLElement* add_ele(XMLDocument* xml, XMLElement* p, int index,
-                                  const char* name_tag, const char* value_type = NULL)
-{
-    //debug("in, tag:%s", name_tag);
-    char ele_name[128] = {0};
-    create_ele_name(index, ele_name, sizeof(ele_name));
-    XMLElement* ele = xml->NewElement(ele_name);
-    //debug("ele name:%s, tag:%s, index:%d, value type:%s", ele_name, name_tag, index, value_type);
-    ele->SetAttribute(BLUEDROID_NAME_TAG, name_tag);
-    if(value_type && *value_type)
-        ele->SetAttribute(BLUEDROID_VALUE_TYPE, value_type);
-    p->InsertEndChild(ele);
-    //debug("out, tag:%s", name_tag);
-    return ele;
-}
-static void enum_config(void* user_data, const char* section_name, const char* key_name, const char* value_name,
-                        const char*  value, int bytes, int type)
-{
-    enum_user_data& d = *(enum_user_data*)user_data;
-    //debug("in, key:%s, value:%s", key_name, value_name);
-    //debug("section name:%s, key name:%s, value name:%s, value type:%s",
-    //                      section_name, key_name, value_name, type_int2str(type));
-    if(type & BTIF_CFG_TYPE_VOLATILE)
-        return; //skip any volatile value
-    if(d.sn != section_name)
-    {
-        d.sn = section_name;
-        d.se = add_ele(d.xml, d.xml->RootElement(), ++d.si, section_name);
-        d.ki = 0;
-    }
-    if(d.kn != key_name)
-    {
-        d.kn = key_name;
-        d.ke = add_ele(d.xml, d.se, ++d.ki, key_name);
-        d.vi = 0;
-    }
-    if(d.vn != value_name)
-    {
-        if(type & BTIF_CFG_TYPE_STR)
-        {
-            d.vn = value_name;
-            d.ve = add_ele(d.xml, d.ke, ++d.vi, value_name, type_int2str(type));
-            d.ve->InsertFirstChild(d.xml->NewText(value));
-        }
-        else if(type & BTIF_CFG_TYPE_INT)
-        {
-            d.vn = value_name;
-            d.ve = add_ele(d.xml, d.ke, ++d.vi, value_name, type_int2str(type));
-            char value_str[64] = {0};
-            snprintf(value_str, sizeof(value_str), "%d", *(int*)value);
-            d.ve->InsertFirstChild(d.xml->NewText(value_str));
-        }
-        else if(type & BTIF_CFG_TYPE_BIN)
-        {
-            d.vn = value_name;
-            d.ve = add_ele(d.xml, d.ke, ++d.vi, value_name, type_int2str(type));
-            char* value_str = (char*)alloca(bytes*2 + 1);
-            bytes2hex(value, bytes, value_str);
-            d.ve->InsertFirstChild(d.xml->NewText(value_str));
-        }
-        else error("unsupported config value name:%s, type:%s not saved", d.vn, type_int2str(type));
-    }
-    //debug("out, key:%s, value:%s", key_name, value_name);
-}
-
-static int type_str2int(const char* type)
-{
-    if(strcmp(type, "int") == 0)
-        return BTIF_CFG_TYPE_INT;
-    if(strcmp(type, "binary") == 0)
-        return BTIF_CFG_TYPE_BIN;
-    if(type == 0 || *type == 0 || strcmp(type, "string") == 0)
-        return  BTIF_CFG_TYPE_STR;
-    error("unknown value type:%s", type);
-    return BTIF_CFG_TYPE_INVALID;
-}
-static const char* type_int2str(int type)
-{
-    switch(type)
-    {
-        case BTIF_CFG_TYPE_INT:
-            return "int";
-        case BTIF_CFG_TYPE_BIN:
-            return "binary";
-        case BTIF_CFG_TYPE_STR:
-            return "string";
-        default:
-            error("unknown type:%d", type);
-            break;
-    }
-    return NULL;
-}
-
-static inline void create_ele_name(int index, char* element, int len)
-{
-    snprintf(element, len, "N%d", index);
-}
-static inline int validate_ele_name(const char* key)
-{
-    //must be 'N' followed with numbers
-    if(key && *key == 'N' && *++key)
-    {
-        while(*key)
-        {
-            if(*key < '0' || *key > '9')
-                return FALSE;
-            ++key;
-        }
-        return TRUE;
-    }
-    return FALSE;
-}
-static int open_file_map(const char *pathname, const char**map, int* size)
-{
-    struct stat st;
-    st.st_size = 0;
-    int fd;
-    //debug("in");
-    if((fd = open(pathname, O_RDONLY)) >= 0)
-    {
-        //debug("fd:%d", fd);
-        if(fstat(fd, &st) == 0 && st.st_size)
-        {
-            *size = st.st_size;
-            *map = (const char*)mmap(NULL, *size, PROT_READ, MAP_SHARED, fd, 0);
-            if(*map && *map != MAP_FAILED)
-            {
-                //debug("out map:%p, size:%d", *map, *size);
-                return fd;
-            }
-        }
-        close(fd);
-    }
-    //debug("out, failed");
-    return -1;
-}
-static void close_file_map(int fd, const char* map, int size)
-{
-    munmap((void*)map, size);
-    close(fd);
-}
-static int read_file_line(const char* map, int start_pos, int size, int* line_size)
-{
-    *line_size = 0;
-    //debug("in, start pos:%d, size:%d", start_pos, size);
-    int i;
-    for(i = start_pos; i < size; i++)
-    {
-        if(map[i] == '\r' || map[i] == '\n')
-            break;
-         ++*line_size;
-    }
-    //debug("out, ret:%d, start pos:%d, size:%d, line_size:%d", i, start_pos, size, *line_size);
-    return i + 1;
-}
-static const char* find_value_line(const char* map, int size, const char *key, int* value_size)
-{
-    int key_len = strlen(key);
-    int i;
-    for(i = 0; i < size; i++)
-    {
-        if(map[i] == *key)
-        {
-            if(i + key_len + 1 > size)
-                return NULL;
-            if(memcmp(map + i, key, key_len) == 0)
-            {
-                read_file_line(map, i + key_len + 1, size, value_size);
-                if(*value_size)
-                    return map + i + key_len + 1;
-                break;
-            }
-        }
-    }
-    return NULL;
-}
-static int read_line_word(const char* line, int start_pos, int line_size, char* word, int *word_size, bool lower_case = false)
-{
-    int i;
-    //skip space
-    //debug("in, line start_pos:%d, line_size:%d", start_pos, line_size);
-    for(i = start_pos; i < line_size; i++)
-    {
-        //debug("skip space loop, line[%d]:%c", i, line[i]);
-        if(line[i] != ' ' && line[i] != '\t' && line[i] != '\r' && line[i] !='\n')
-            break;
-    }
-    *word_size = 0;
-    for(; i < line_size; i++)
-    {
-        //debug("add word loop, line[%d]:%c", i, line[i]);
-        if(line[i] != ' ' && line[i] != '\t' && line[i] != '\r' && line[i] !='\n')
-        {
-            ++*word_size;
-            if(lower_case && 'A' <= line[i] && line[i] <= 'Z')
-                *word++ = 'a' - 'A' + line[i];
-            else
-                *word++ = line[i];
-        }
-        else break;
-    }
-    *word = 0;
-    //debug("out, ret:%d, word:%s, word_size:%d, line start_pos:%d, line_size:%d",
-    //            i, word, *word_size, start_pos, line_size);
-    return i;
-}
-static int is_valid_bd_addr(const char* addr)
-{
-    int len = strlen(addr);
-    //debug("addr: %s, len:%d", addr, len);
-    return len == 17 && addr[2] == ':' && addr[5] == ':' && addr[14] == ':';
-}
-static int load_bluez_cfg_value(const char* adapter_path, const char* file_name)
-{
-    //debug("in");
-
-    const char* map = NULL;
-    int size = 0;
-    int ret = FALSE;
-    char path[256];
-    snprintf(path, sizeof(path), "%s/%s", adapter_path, file_name);
-    int fd = open_file_map(path, &map, &size);
-    //debug("in, path:%s, fd:%d, size:%d", path, fd, size);
-    if(fd < 0 || size == 0)
-    {
-        error("open_file_map fail, fd:%d, path:%s, size:%d", fd, path, size);
-        //debug("out");
-        if (fd >= 0)
-            close(fd);
-        return FALSE;
-    }
-    //get local bt device name from bluez config
-    int line_size = 0;
-    const char *value_line = find_value_line(map, size, "name", &line_size);
-    if(value_line && line_size > 0)
-    {
-        char value[line_size + 1];
-        memcpy(value, value_line, line_size);
-        value[line_size] = 0;
-        //debug("import local bt dev names:%s", value);
-        btif_config_set_str("Local", "Adapter", "Name", value);
-        ret = TRUE;
-    }
-
-    close_file_map(fd, map, size);
-    //debug("out, ret:%d", ret);
-    return ret;
-}
-
-int load_bluez_adapter_info(char* adapter_path, int size)
-{
-    struct dirent *dptr;
-    DIR *dirp;
-    int ret = FALSE;
-    if((dirp = opendir(BLUEZ_PATH)) != NULL)
-    {
-        while((dptr = readdir(dirp)) != NULL)
-        {
-            //debug("readdir: %s",dptr->d_name);
-            if(is_valid_bd_addr(dptr->d_name))
-            {
-                snprintf(adapter_path, size, "%s%s", BLUEZ_PATH, dptr->d_name);
-                btif_config_set_str("Local", "Adapter", "Address", dptr->d_name);
-                load_bluez_cfg_value(adapter_path, BLUEZ_CONFIG);
-                ret = TRUE;
-                break;
-            }
-        }
-        closedir(dirp);
-    }
-    return ret;
-}
-static inline void upcase_addr(const char* laddr, char* uaddr, int size)
-{
-    int i;
-    for(i = 0; i < size && laddr[i]; i++)
-        uaddr[i] = ('a' <= laddr[i] && laddr[i] <= 'z') ?
-                        laddr[i] - ('a' - 'A') : laddr[i];
-    uaddr[i] = 0;
-}
-
-static int parse_hid_attribute(const char *str, int line_size, int len)
-{
-    if (len == 0 || line_size == 0 || str == NULL || (len%2))
-        return 0;
-
-    char hex_string[len + 1], hex_bytes[len/2];
-    memcpy(hex_string, str - 1, len);
-    hex_string[len] = 0;
-    hex2bytes(hex_string, len, hex_bytes);
-    if (len == 2)
-        return hex_bytes[0];
-    else if (len == 4)
-        return hex_bytes[0] << 8 | hex_bytes[1];
-    else return 0;
-}
-
-static int parse_bluez_hid_sdp_records(const char* adapter_path, const char* bd_addr)
-{
-    //debug("in");
-    char addr[32];
-    char pattern_to_search[50];
-    upcase_addr(bd_addr, addr, sizeof(addr));
-
-    const char* map = NULL;
-    int size = 0;
-    int ret = FALSE;
-    char path[256];
-    snprintf(path, sizeof(path), "%s/%s", adapter_path, BLUEZ_SDP);
-    int fd = open_file_map(path, &map, &size);
-    //debug("in, path:%s, addr:%s, fd:%d, size:%d", path, addr, fd, size);
-    if(fd < 0 || size == 0)
-    {
-        error("open_file_map fail, fd:%d, path:%s, size:%d", fd, path, size);
-        //debug("out");
-        return FALSE;
-    }
-    int line_size = 0;
-    snprintf(pattern_to_search, sizeof(pattern_to_search), "%s#00010000", addr);
-    const char *value_line = find_value_line(map, size, pattern_to_search, &line_size);
-    int dev_sub_class = 0;
-    int app_id = 0;
-    int countrycode = 0;
-    int product = 0;
-    int vendor = 0;
-    int product_ver = 0;
-    int attr_mask = 0;
-    int ssr_max_lat = 0;
-    int ssr_min_timeout = 0;
-    int rep_desc_len = 0;
-    if(value_line && line_size)
-    {
-        char hid_sdp[line_size + 2];
-        memcpy(hid_sdp, value_line - 1, line_size);
-        hid_sdp[line_size + 1] = 0;
-        //debug("addr:%s, hid_sdp:%s", bd_addr, hid_sdp);
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_SUB_CLASS, &line_size);
-        dev_sub_class = parse_hid_attribute(value_line, line_size, 2);
-        if(dev_sub_class)
-        {
-            if ((dev_sub_class & 0x80) == 0x80)
-                app_id = HID_APP_ID_MOUSE;
-            else
-                app_id = HID_APP_ID_KYB;
-            //debug("dev_sub_class:%d", dev_sub_class);
-        }
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_COUNTRY_CODE, &line_size);
-        countrycode = parse_hid_attribute(value_line, line_size, 2);
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_VIRTUAL_CABLE, &line_size);
-        if(parse_hid_attribute(value_line, line_size, 2))
-        {
-            attr_mask |= HID_ATTR_MASK_VIRTUAL_CABLE;
-            //debug("attr_mask after Virtual Unplug:%04x", attr_mask);
-        }
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_RECON_INNITIATE, &line_size);
-        if(parse_hid_attribute(value_line, line_size, 2))
-        {
-            attr_mask |= HID_ATTR_MASK_RECONN_INIT;
-            //debug("attr_mask after Reconnect Initiate:%04x", attr_mask);
-        }
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_REP_DSC_1, &line_size);
-        if(value_line && line_size)
-        {
-            char rep_desc[line_size + 1], rd[line_size/2 + 1];
-            char rep_dsc_len[5], rd_len[2];
-            memcpy(rep_dsc_len, value_line - 1, 4);
-            rep_dsc_len[4] = 0;
-            hex2bytes(rep_dsc_len, 4, rd_len);
-            rep_desc_len = (rd_len[0] << 8 | rd_len[1]) - (HID_RPT_DSCR_HDR_LEN_1 - 2);
-            //debug("rep_desc_len:%d", rep_desc_len);
-            memcpy(rep_desc, value_line - 1 + (HID_RPT_DSCR_HDR_LEN_1 * 2), rep_desc_len * 2);
-            rep_desc[rep_desc_len * 2] = 0;
-            hex2bytes(rep_desc, rep_desc_len* 2, rd);
-            if (rep_desc_len)
-            {
-                //debug("rep_desc:%s", rep_desc);
-                btif_config_set("Remote", bd_addr, "HidDescriptor", rd, rep_desc_len,
-                        BTIF_CFG_TYPE_BIN);
-            }
-        }
-        else
-        {
-            value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_REP_DSC_2, &line_size);
-            if(value_line && line_size)
-            {
-                char rep_dsc_len[3], rd_len[1];
-                memcpy(rep_dsc_len, value_line - 1, 2);
-                rep_dsc_len[2] = 0;
-                hex2bytes(rep_dsc_len, 2, rd_len);
-                rep_desc_len = rd_len[0] - (HID_RPT_DSCR_HDR_LEN_2 - 1);
-                //debug("rep_desc_len:%d", rep_desc_len);
-                char rep_desc[(rep_desc_len * 2) + 1], rd[rep_desc_len + 1];
-                memcpy(rep_desc, value_line - 1 + (HID_RPT_DSCR_HDR_LEN_2 * 2), rep_desc_len * 2);
-                rep_desc[rep_desc_len * 2] = 0;
-                hex2bytes(rep_desc, rep_desc_len * 2, rd);
-                if (rep_desc_len)
-                {
-                    //debug("rep_desc:%s", rep_desc);
-                    btif_config_set("Remote", bd_addr, "HidDescriptor", rd, rep_desc_len,
-                            BTIF_CFG_TYPE_BIN);
-                }
-            }
-        }
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_SDP_DISABLE, &line_size);
-        if(parse_hid_attribute(value_line, line_size, 2))
-        {
-            attr_mask |= HID_ATTR_MASK_SDP_DISABLE;
-            //debug("attr_mask after SDP Disable:%04x", attr_mask);
-        }
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_BAT_POWER, &line_size);
-        if(parse_hid_attribute(value_line, line_size, 2))
-        {
-            attr_mask |= HID_ATTR_MASK_BATTERY_POWER;
-            //debug("attr_mask after Battery Powered:%04x", attr_mask);
-        }
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_REM_WAKE, &line_size);
-        if(parse_hid_attribute(value_line, line_size, 2))
-        {
-            attr_mask |= HID_ATTR_MASK_REMOTE_WAKE;
-            //debug("attr_mask after Remote Wake:%04x", attr_mask);
-        }
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_NORM_CONN, &line_size);
-        if(parse_hid_attribute(value_line, line_size, 2))
-        {
-            attr_mask |= HID_ATTR_MASK_NORMALLY_CONNECTABLE;
-            //debug("attr_mask after Normally Conenctable:%04x", attr_mask);
-        }
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_SUP_TIME, &line_size);
-        if(value_line && line_size)
-            attr_mask |= HID_ATTR_MASK_SUP_TOUT_AVLBL;
-        //debug("attr_mask after Supervision Timeout:%04x", attr_mask);
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_SSR_MAX_LAT, &line_size);
-        ssr_max_lat = parse_hid_attribute(value_line, line_size, 4);
-        if(!ssr_max_lat)
-            ssr_max_lat = HID_SSR_PARAM_INVALID;
-        value_line = find_value_line(hid_sdp, strlen(hid_sdp), HID_SSR_MIN_TIM, &line_size);
-        ssr_min_timeout = parse_hid_attribute(value_line, line_size, 4);
-        if(!ssr_min_timeout)
-            ssr_min_timeout = HID_SSR_PARAM_INVALID;
-        snprintf(pattern_to_search, sizeof(pattern_to_search), "%s#00010001", addr);
-        value_line = find_value_line(map, size, pattern_to_search, &line_size);
-        if(value_line && line_size)
-        {
-            char did_sdp[line_size + 2];
-            memcpy(did_sdp, value_line - 1, line_size + 1);
-            did_sdp[line_size + 1] = 0;
-            //debug("addr:%s, did_sdp:%s", bd_addr, did_sdp);
-            value_line = find_value_line(did_sdp, strlen(did_sdp), HID_VENDOR_ID, &line_size);
-            vendor = parse_hid_attribute(value_line, line_size, 4);
-            value_line = find_value_line(did_sdp, strlen(did_sdp), HID_PRODUCT_ID, &line_size);
-            product = parse_hid_attribute(value_line, line_size, 4);
-            value_line = find_value_line(did_sdp, strlen(did_sdp), HID_PRODUCT_VERSION, &line_size);
-            product_ver = parse_hid_attribute(value_line, line_size, 4);
-         }
-    }
-    btif_config_set_int("Remote", bd_addr, "HidAttrMask", attr_mask);
-    btif_config_set_int("Remote", bd_addr, "HidSubClass", dev_sub_class);
-    btif_config_set_int("Remote", bd_addr, "HidAppId", app_id);
-    btif_config_set_int("Remote", bd_addr, "HidVendorId", vendor);
-    btif_config_set_int("Remote", bd_addr, "HidProductId", product);
-    btif_config_set_int("Remote", bd_addr, "HidVersion", product_ver);
-    btif_config_set_int("Remote", bd_addr, "HidCountryCode", countrycode);
-    btif_config_set_int("Remote", bd_addr, "HidSSRMinTimeout", ssr_min_timeout);
-    btif_config_set_int("Remote", bd_addr, "HidSSRMaxLatency", ssr_max_lat);
-    //debug("HidSubClass: %02x, app_id = %d, vendor = %04x, product = %04x, product_ver = %04x"
-    //    "countrycode = %02x, ssr_min_timeout = %04x, ssr_max_lat = %04x",
-    //    HidSubClass, app_id, vendor, product, product_ver, countrycode, ssr_min_timeout,
-    //    ssr_max_lat);
-    close_file_map(fd, map, size);
-    ret = TRUE;
-    //debug("out, ret:%d", ret);
-    return ret;
-}
-
-static int load_bluez_dev_value(const char* adapter_path, const char* bd_addr,
-                                const char* file_name, const char* cfg_value_name, int type)
-{
-    //debug("in");
-    char addr[32];
-    upcase_addr(bd_addr, addr, sizeof(addr));
-
-    const char* map = NULL;
-    int size = 0;
-    int ret = FALSE;
-    char path[256];
-    snprintf(path, sizeof(path), "%s/%s", adapter_path, file_name);
-    int fd = open_file_map(path, &map, &size);
-    //debug("in, path:%s, addr:%s, fd:%d, size:%d", path, addr, fd, size);
-    if(fd < 0 || size == 0)
-    {
-        error("open_file_map fail, fd:%d, path:%s, size:%d", fd, path, size);
-        //debug("out");
-        if (fd >= 0)
-            close(fd);
-        return FALSE;
-    }
-    int line_size = 0;
-    const char *value_line = find_value_line(map, size, addr, &line_size);
-    if(value_line && line_size)
-    {
-        char line[line_size + 1];
-        memcpy(line, value_line, line_size);
-        line[line_size] = 0;
-        //debug("addr:%s, Names:%s", bd_addr, line);
-        if(type == BTIF_CFG_TYPE_STR)
-            btif_config_set_str("Remote", bd_addr, cfg_value_name, line);
-        else if(type == BTIF_CFG_TYPE_INT)
-        {
-            int v = strtol(line, NULL, 16);
-            //parse sdp record in case remote device is hid
-            if(strcmp(file_name, BLUEZ_CLASSES) == 0)
-            {
-                switch((v & 0x1f00) >> 8)
-                {
-                    case 0x5: //hid device
-                        info("parsing sdp for hid device %s", bd_addr);
-                        parse_bluez_hid_sdp_records(adapter_path, bd_addr);
-                        break;
-                }
-            }
-            btif_config_set_int("Remote", bd_addr, cfg_value_name, v);
-        }
-        ret = TRUE;
-    }
-    close_file_map(fd, map, size);
-    //debug("out, ret:%d", ret);
-    return ret;
-}
-static inline int bz2bd_linkkeytype(int type)
-{
-#if 1
-    return type;
-#else
-    int table[5] = {0, 0, 0, 0, 0};
-    if(0 <= type && type < (int)(sizeof(table)/sizeof(int)))
-        return table[type];
-    return 0;
-#endif
-}
-int load_bluez_linkkeys(const char* adapter_path)
-{
-    const char* map = NULL;
-    int size = 0;
-    int ret = FALSE;
-    char path[256];
-    //debug("in");
-    snprintf(path, sizeof(path), "%s/%s", adapter_path, BLUEZ_LINKKEY);
-    int fd = open_file_map(path, &map, &size);
-    if(fd < 0 || size == 0)
-    {
-        error("open_file_map fail, fd:%d, path:%s, size:%d", fd, path, size);
-        //debug("out");
-        if (fd >= 0)
-            close(fd);
-        return FALSE;
-    }
-    int pos = 0;
-    //debug("path:%s, size:%d", path, size);
-    while(pos < size)
-    {
-        int line_size = 0;
-        int next_pos = read_file_line(map, pos, size, &line_size);
-        //debug("pos:%d, next_pos:%d, size:%d, line_size:%d", pos, next_pos, size, line_size);
-        if(line_size)
-        {
-            const char* line = map + pos;
-            char addr[line_size + 1];
-            int word_pos = 0;
-            int addr_size = 0;
-            word_pos = read_line_word(line, word_pos, line_size, addr, &addr_size, true);
-            //debug("read_line_word addr:%s, addr_size:%d", addr, addr_size);
-            if(*addr)
-            {
-                char value[line_size + 1];
-                int value_size = 0;
-                //read link key
-                word_pos = read_line_word(line, word_pos, line_size, value, &value_size);
-                //debug("read_line_word linkkey:%s, size:%d", value, value_size);
-                if(*value)
-                {
-                    int linkkey_size = value_size / 2;
-                    char linkkey[linkkey_size];
-                    if(hex2bytes(value, value_size, linkkey))
-                    { //read link key type
-                        //bluez save the linkkey in reversed order
-                        reverse_bin(linkkey, linkkey_size);
-                        word_pos = read_line_word(line, word_pos,
-                                                    line_size, value, &value_size);
-                        if(*value)
-                        {
-                            if(load_bluez_dev_value(adapter_path, addr,
-                                                BLUEZ_CLASSES, "DevClass", BTIF_CFG_TYPE_INT) &&
-                               load_bluez_dev_value(adapter_path, addr,
-                                                BLUEZ_NAMES, "Name", BTIF_CFG_TYPE_STR) &&
-                               load_bluez_dev_value(adapter_path, addr,
-                                                BLUEZ_TYPES, "DevType", BTIF_CFG_TYPE_INT) &&
-                               load_bluez_dev_value(adapter_path, addr,
-                                                BLUEZ_PROFILES, "Service", BTIF_CFG_TYPE_STR))
-                            {
-                                load_bluez_dev_value(adapter_path, addr,
-                                                BLUEZ_ALIASES, "Aliase", BTIF_CFG_TYPE_STR);
-                                int key_type = bz2bd_linkkeytype(atoi(value));
-
-                                //read pin len
-                                word_pos = read_line_word(line, word_pos, line_size, value, &value_size);
-                                if(*value)
-                                {
-                                    int pin_len = atoi(value);
-                                    ret = TRUE;
-                                    btif_config_set("Remote", addr, "LinkKey", linkkey,
-                                                                    linkkey_size, BTIF_CFG_TYPE_BIN);
-                                    //dump_bin("import bluez linkkey", linkkey, linkkey_size);
-                                    btif_config_set_int("Remote", addr, "LinkKeyType", key_type);
-                                    btif_config_set_int("Remote", addr, "PinLength", pin_len);
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        //debug("pos:%d, next_pos:%d, size:%d, line_size:%d", pos, next_pos, size, line_size);
-        pos = next_pos;
-    }
-    close_file_map(fd, map, size);
-    //debug("out, ret:%d", ret);
-    return ret;
-}
-
diff --git a/btif/src/btif_core.c b/btif/src/btif_core.c
index 4e674c5..f202d7b 100644
--- a/btif/src/btif_core.c
+++ b/btif/src/btif_core.c
@@ -26,46 +26,51 @@
  *
  ***********************************************************************************/
 
-#include <stdlib.h>
-#include <hardware/bluetooth.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <dirent.h>
 #include <ctype.h>
 #include <cutils/properties.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <hardware/bluetooth.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
 
-#define LOG_TAG "BTIF_CORE"
-#include "btif_api.h"
+#define LOG_TAG "bt_btif_core"
+#include "btcore/include/bdaddr.h"
+
+#include "bdaddr.h"
 #include "bt_utils.h"
 #include "bta_api.h"
-#include "gki.h"
-#include "btu.h"
 #include "bte.h"
-#include "bd.h"
+#include "btif_api.h"
 #include "btif_av.h"
-#include "btif_storage.h"
-#include "btif_util.h"
-#include "btif_sock.h"
+#include "btif_config.h"
 #include "btif_pan.h"
 #include "btif_mce.h"
 #include "btif_profile_queue.h"
 #include "btif_config.h"
+#include "btif_sock.h"
+#include "btif_storage.h"
+#include "btif_util.h"
+#include "btu.h"
+#include "device/include/controller.h"
+#include "osi/include/fixed_queue.h"
+#include "osi/include/future.h"
+#include "gki.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "stack_manager.h"
+#include "osi/include/thread.h"
+
 /************************************************************************************
 **  Constants & Macros
 ************************************************************************************/
 
-#ifndef BTIF_TASK_STACK_SIZE
-#define BTIF_TASK_STACK_SIZE       0x2000         /* In bytes */
-#endif
-
 #ifndef BTE_DID_CONF_FILE
 #define BTE_DID_CONF_FILE "/etc/bluetooth/bt_did.conf"
 #endif
 
-#define BTIF_TASK_STR        ((INT8 *) "BTIF")
-
 /************************************************************************************
 **  Local type definitions
 ************************************************************************************/
@@ -101,12 +106,6 @@
 
 bt_bdaddr_t btif_local_bd_addr;
 
-static UINT32 btif_task_stack[(BTIF_TASK_STACK_SIZE + 3) / 4];
-
-/* holds main adapter state */
-static btif_core_state_t btif_core_state = BTIF_CORE_STATE_DISABLED;
-
-static int btif_shutdown_pending = 0;
 static tBTA_SERVICE_MASK btif_enabled_services = 0;
 
 /*
@@ -117,11 +116,14 @@
 */
 static UINT8 btif_dut_mode = 0;
 
+static thread_t *bt_jni_workqueue_thread;
+static const char *BT_JNI_WORKQUEUE_NAME = "bt_jni_workqueue";
+
 /************************************************************************************
 **  Static functions
 ************************************************************************************/
-static bt_status_t btif_associate_evt(void);
-static bt_status_t btif_disassociate_evt(void);
+static void btif_jni_associate(UNUSED_ATTR uint16_t event, UNUSED_ATTR char *p_param);
+static void btif_jni_disassociate(UNUSED_ATTR uint16_t event, UNUSED_ATTR char *p_param);
 
 /* sends message to btif task */
 static void btif_sendmsg(void *p_msg);
@@ -129,11 +131,12 @@
 /************************************************************************************
 **  Externs
 ************************************************************************************/
+extern fixed_queue_t *btu_hci_msg_queue;
+
 extern void bte_load_did_conf(const char *p_path);
 
 /** TODO: Move these to _common.h */
 void bte_main_boot_entry(void);
-void bte_main_enable();
 void bte_main_disable(void);
 void bte_main_shutdown(void);
 #if (defined(HCILP_INCLUDED) && HCILP_INCLUDED == TRUE)
@@ -146,16 +149,6 @@
 #endif
 void bte_main_config_hci_logging(BOOLEAN enable, BOOLEAN bt_disabled);
 
-/************************************************************************************
-**  Functions
-************************************************************************************/
-
-
-/*****************************************************************************
-**   Context switching functions
-*****************************************************************************/
-
-
 /*******************************************************************************
 **
 ** Function         btif_context_switched
@@ -170,11 +163,10 @@
 
 static void btif_context_switched(void *p_msg)
 {
-    tBTIF_CONTEXT_SWITCH_CBACK *p;
 
     BTIF_TRACE_VERBOSE("btif_context_switched");
 
-    p = (tBTIF_CONTEXT_SWITCH_CBACK *) p_msg;
+    tBTIF_CONTEXT_SWITCH_CBACK *p = (tBTIF_CONTEXT_SWITCH_CBACK *) p_msg;
 
     /* each callback knows how to parse the data */
     if (p->p_cb)
@@ -259,7 +251,25 @@
 
 int btif_is_enabled(void)
 {
-    return ((!btif_is_dut_mode()) && (btif_core_state == BTIF_CORE_STATE_ENABLED));
+    return ((!btif_is_dut_mode()) && (stack_manager_get_interface()->get_stack_is_running()));
+}
+
+void btif_init_ok(UNUSED_ATTR uint16_t event, UNUSED_ATTR char *p_param) {
+  BTIF_TRACE_DEBUG("btif_task: received trigger stack init event");
+#if (BLE_INCLUDED == TRUE)
+  btif_dm_load_ble_local_keys();
+#endif
+  BTA_EnableBluetooth(bte_dm_evt);
+}
+
+void btif_init_fail(UNUSED_ATTR uint16_t event, UNUSED_ATTR char *p_param) {
+  BTIF_TRACE_DEBUG("btif_task: hardware init failed");
+  bte_main_disable();
+  btif_queue_release();
+  bte_main_shutdown();
+  btif_dut_mode = 0;
+
+  future_ready(stack_manager_get_hack_future(), FUTURE_FAIL);
 }
 
 /*******************************************************************************
@@ -272,82 +282,22 @@
 ** Returns          void
 **
 *******************************************************************************/
+static void bt_jni_msg_ready(void *context) {
+  BT_HDR *p_msg = (BT_HDR *)context;
 
-static void btif_task(UINT32 params)
-{
-    UINT16   event;
-    BT_HDR   *p_msg;
-    UNUSED(params);
+  BTIF_TRACE_VERBOSE("btif task fetched event %x", p_msg->event);
 
-    BTIF_TRACE_DEBUG("btif task starting");
-
-    btif_associate_evt();
-
-    for(;;)
-    {
-        /* wait for specified events */
-        event = GKI_wait(0xFFFF, 0);
-
-        /*
-         * Wait for the trigger to init chip and stack. This trigger will
-         * be received by btu_task once the UART is opened and ready
-         */
-        if (event == BT_EVT_TRIGGER_STACK_INIT)
-        {
-            BTIF_TRACE_DEBUG("btif_task: received trigger stack init event");
-            #if (BLE_INCLUDED == TRUE)
-            btif_dm_load_ble_local_keys();
-            #endif
-            BTA_EnableBluetooth(bte_dm_evt);
-        }
-
-        /*
-         * Failed to initialize controller hardware, reset state and bring
-         * down all threads
-         */
-        if (event == BT_EVT_HARDWARE_INIT_FAIL)
-        {
-            BTIF_TRACE_DEBUG("btif_task: hardware init failed");
-            bte_main_disable();
-            btif_queue_release();
-            GKI_task_self_cleanup(BTIF_TASK);
-            bte_main_shutdown();
-            btif_dut_mode = 0;
-            btif_core_state = BTIF_CORE_STATE_DISABLED;
-            HAL_CBACK(bt_hal_cbacks,adapter_state_changed_cb,BT_STATE_OFF);
-            break;
-        }
-
-        if (event & EVENT_MASK(GKI_SHUTDOWN_EVT))
-            break;
-
-        if(event & TASK_MBOX_1_EVT_MASK)
-        {
-            while((p_msg = GKI_read_mbox(BTU_BTIF_MBOX)) != NULL)
-            {
-                BTIF_TRACE_VERBOSE("btif task fetched event %x", p_msg->event);
-
-                switch (p_msg->event)
-                {
-                    case BT_EVT_CONTEXT_SWITCH_EVT:
-                        btif_context_switched(p_msg);
-                        break;
-                    default:
-                        BTIF_TRACE_ERROR("unhandled btif event (%d)", p_msg->event & BT_EVT_MASK);
-                        break;
-                }
-
-                GKI_freebuf(p_msg);
-            }
-        }
-    }
-
-    btif_disassociate_evt();
-
-    BTIF_TRACE_DEBUG("btif task exiting");
+  switch (p_msg->event) {
+    case BT_EVT_CONTEXT_SWITCH_EVT:
+      btif_context_switched(p_msg);
+      break;
+    default:
+      BTIF_TRACE_ERROR("unhandled btif event (%d)", p_msg->event & BT_EVT_MASK);
+      break;
+  }
+  GKI_freebuf(p_msg);
 }
 
-
 /*******************************************************************************
 **
 ** Function         btif_sendmsg
@@ -360,7 +310,11 @@
 
 void btif_sendmsg(void *p_msg)
 {
-    GKI_send_msg(BTIF_TASK, BTU_BTIF_MBOX, p_msg);
+    thread_post(bt_jni_workqueue_thread, bt_jni_msg_ready, p_msg);
+}
+
+void btif_thread_post(thread_fn func, void *context) {
+    thread_post(bt_jni_workqueue_thread, func, context);
 }
 
 static void btif_fetch_local_bdaddr(bt_bdaddr_t *local_addr)
@@ -381,7 +335,7 @@
         {
             memset(val, 0, sizeof(val));
             read(addr_fd, val, FACTORY_BT_BDADDR_STORAGE_LEN);
-            str2bd(val, local_addr);
+            string_to_bdaddr(val, local_addr);
             /* If this is not a reserved/special bda, then use it */
             if (memcmp(local_addr->address, null_bdaddr, BD_ADDR_LEN) != 0)
             {
@@ -398,9 +352,9 @@
     if(!valid_bda)
     {
         val_size = sizeof(val);
-        if(btif_config_get_str("Local", "Adapter", "Address", val, &val_size))
+        if(btif_config_get_str("Adapter", "Address", val, &val_size))
         {
-            str2bd(val, local_addr);
+            string_to_bdaddr(val, local_addr);
             BTIF_TRACE_DEBUG("local bdaddr from bt_config.xml is  %s", val);
             return;
         }
@@ -410,7 +364,7 @@
     if ((!valid_bda) && \
         (property_get(PERSIST_BDADDR_PROPERTY, val, NULL)))
     {
-        str2bd(val, local_addr);
+        string_to_bdaddr(val, local_addr);
         valid_bda = TRUE;
         BTIF_TRACE_DEBUG("Got prior random BDA %02X:%02X:%02X:%02X:%02X:%02X",
             local_addr->address[0], local_addr->address[1], local_addr->address[2],
@@ -433,7 +387,7 @@
         local_addr->address[5] = (uint8_t) ((rand() >> 8) & 0xFF);
 
         /* Convert to ascii, and store as a persistent property */
-        bd2str(local_addr, &bdstr);
+        bdaddr_to_string(local_addr, bdstr, sizeof(bdstr));
 
         BTIF_TRACE_DEBUG("No preset BDA. Generating BDA: %s for prop %s",
              (char*)bdstr, PERSIST_BDADDR_PROPERTY);
@@ -444,9 +398,9 @@
 
     //save the bd address to config file
     bdstr_t bdstr;
-    bd2str(local_addr, &bdstr);
+    bdaddr_to_string(local_addr, bdstr, sizeof(bdstr));
     val_size = sizeof(val);
-    if (btif_config_get_str("Local", "Adapter", "Address", val, &val_size))
+    if (btif_config_get_str("Adapter", "Address", val, &val_size))
     {
         if (strcmp(bdstr, val) ==0)
         {
@@ -454,16 +408,9 @@
             return;
         }
     }
-    btif_config_set_str("Local", "Adapter", "Address", bdstr);
-    btif_config_save();
+    btif_config_set_str("Adapter", "Address", bdstr);
 }
 
-/*****************************************************************************
-**
-**   btif core api functions
-**
-*****************************************************************************/
-
 /*******************************************************************************
 **
 ** Function         btif_init_bluetooth
@@ -473,79 +420,34 @@
 ** Returns          bt_status_t
 **
 *******************************************************************************/
+bt_status_t btif_init_bluetooth() {
+  bte_main_boot_entry();
 
-bt_status_t btif_init_bluetooth()
-{
-    UINT8 status;
-    btif_config_init();
-    bte_main_boot_entry();
+  /* As part of the init, fetch the local BD ADDR */
+  memset(&btif_local_bd_addr, 0, sizeof(bt_bdaddr_t));
+  btif_fetch_local_bdaddr(&btif_local_bd_addr);
 
-    /* As part of the init, fetch the local BD ADDR */
-    memset(&btif_local_bd_addr, 0, sizeof(bt_bdaddr_t));
-    btif_fetch_local_bdaddr(&btif_local_bd_addr);
+  bt_jni_workqueue_thread = thread_new(BT_JNI_WORKQUEUE_NAME);
+  if (bt_jni_workqueue_thread == NULL) {
+    LOG_ERROR("%s Unable to create thread %s", __func__, BT_JNI_WORKQUEUE_NAME);
+    goto error_exit;
+  }
 
-    /* start btif task */
-    status = GKI_create_task(btif_task, BTIF_TASK, BTIF_TASK_STR,
-                (UINT16 *) ((UINT8 *)btif_task_stack + BTIF_TASK_STACK_SIZE),
-                sizeof(btif_task_stack));
+  // Associate this workqueue thread with jni.
+  btif_transfer_context(btif_jni_associate, 0, NULL, 0, NULL);
 
-    if (status != GKI_SUCCESS)
-        return BT_STATUS_FAIL;
+  return BT_STATUS_SUCCESS;
 
-    return BT_STATUS_SUCCESS;
+error_exit:;
+     thread_free(bt_jni_workqueue_thread);
+
+     bt_jni_workqueue_thread = NULL;
+
+     return BT_STATUS_FAIL;
 }
 
 /*******************************************************************************
 **
-** Function         btif_associate_evt
-**
-** Description      Event indicating btif_task is up
-**                  Attach btif_task to JVM
-**
-** Returns          void
-**
-*******************************************************************************/
-
-static bt_status_t btif_associate_evt(void)
-{
-    BTIF_TRACE_DEBUG("%s: notify ASSOCIATE_JVM", __FUNCTION__);
-    HAL_CBACK(bt_hal_cbacks, thread_evt_cb, ASSOCIATE_JVM);
-
-    return BT_STATUS_SUCCESS;
-}
-
-
-/*******************************************************************************
-**
-** Function         btif_enable_bluetooth
-**
-** Description      Performs chip power on and kickstarts OS scheduler
-**
-** Returns          bt_status_t
-**
-*******************************************************************************/
-
-bt_status_t btif_enable_bluetooth(void)
-{
-    BTIF_TRACE_DEBUG("BTIF ENABLE BLUETOOTH");
-
-    if (btif_core_state != BTIF_CORE_STATE_DISABLED)
-    {
-        ALOGD("not disabled\n");
-        return BT_STATUS_DONE;
-    }
-
-    btif_core_state = BTIF_CORE_STATE_ENABLING;
-
-    /* Create the GKI tasks and run them */
-    bte_main_enable();
-
-    return BT_STATUS_SUCCESS;
-}
-
-
-/*******************************************************************************
-**
 ** Function         btif_enable_bluetooth_evt
 **
 ** Description      Event indicating bluetooth enable is completed
@@ -555,47 +457,43 @@
 **
 *******************************************************************************/
 
-void btif_enable_bluetooth_evt(tBTA_STATUS status, BD_ADDR local_bd)
+void btif_enable_bluetooth_evt(tBTA_STATUS status)
 {
-    bt_bdaddr_t bd_addr;
+    const controller_t *controller = controller_get_interface();
     bdstr_t bdstr;
+    bdaddr_to_string(controller->get_address(), bdstr, sizeof(bdstr));
 
-    bdcpy(bd_addr.address, local_bd);
-    BTIF_TRACE_DEBUG("%s: status %d, local bd [%s]", __FUNCTION__, status,
-                                                     bd2str(&bd_addr, &bdstr));
+    BTIF_TRACE_DEBUG("%s: status %d, local bd [%s]", __FUNCTION__, status, bdstr);
 
-    if (bdcmp(btif_local_bd_addr.address,local_bd))
+    if (bdcmp(btif_local_bd_addr.address, controller->get_address()->address))
     {
-        bdstr_t buf;
+        // TODO(zachoverflow): this whole code path seems like a bad time waiting to happen
+        // We open the vendor library using the old address.
+        bdstr_t old_address;
         bt_property_t prop;
 
+        bdaddr_to_string(&btif_local_bd_addr, old_address, sizeof(old_address));
+
         /**
          * The Controller's BDADDR does not match to the BTIF's initial BDADDR!
-         * This could be because the factory BDADDR was stored separatley in
+         * This could be because the factory BDADDR was stored separately in
          * the Controller's non-volatile memory rather than in device's file
          * system.
          **/
         BTIF_TRACE_WARNING("***********************************************");
-        BTIF_TRACE_WARNING("BTIF init BDA was %02X:%02X:%02X:%02X:%02X:%02X",
-            btif_local_bd_addr.address[0], btif_local_bd_addr.address[1],
-            btif_local_bd_addr.address[2], btif_local_bd_addr.address[3],
-            btif_local_bd_addr.address[4], btif_local_bd_addr.address[5]);
-        BTIF_TRACE_WARNING("Controller BDA is %02X:%02X:%02X:%02X:%02X:%02X",
-            local_bd[0], local_bd[1], local_bd[2],
-            local_bd[3], local_bd[4], local_bd[5]);
+        BTIF_TRACE_WARNING("BTIF init BDA was %s", old_address);
+        BTIF_TRACE_WARNING("Controller BDA is %s", bdstr);
         BTIF_TRACE_WARNING("***********************************************");
 
-        bdcpy(btif_local_bd_addr.address, local_bd);
+        btif_local_bd_addr = *controller->get_address();
 
         //save the bd address to config file
-        bd2str(&btif_local_bd_addr, &buf);
-        btif_config_set_str("Local", "Adapter", "Address", buf);
+        btif_config_set_str("Adapter", "Address", bdstr);
         btif_config_save();
 
         //fire HAL callback for property change
-        memcpy(buf, &btif_local_bd_addr, sizeof(bt_bdaddr_t));
         prop.type = BT_PROPERTY_BDADDR;
-        prop.val = (void*)buf;
+        prop.val = (void*)&btif_local_bd_addr;
         prop.len = sizeof(bt_bdaddr_t);
         HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, BT_STATUS_SUCCESS, 1, &prop);
     }
@@ -624,10 +522,8 @@
 #ifdef BTIF_DM_OOB_TEST
         btif_dm_load_local_oob();
 #endif
-        /* now fully enabled, update state */
-        btif_core_state = BTIF_CORE_STATE_ENABLED;
 
-        HAL_CBACK(bt_hal_cbacks, adapter_state_changed_cb, BT_STATE_ON);
+        future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS);
     }
     else
     {
@@ -636,10 +532,7 @@
 
         btif_pan_cleanup();
 
-        /* we failed to enable, reset state */
-        btif_core_state = BTIF_CORE_STATE_DISABLED;
-
-        HAL_CBACK(bt_hal_cbacks, adapter_state_changed_cb, BT_STATE_OFF);
+        future_ready(stack_manager_get_hack_future(), FUTURE_FAIL);
     }
 }
 
@@ -656,37 +549,14 @@
 *******************************************************************************/
 bt_status_t btif_disable_bluetooth(void)
 {
-    tBTA_STATUS status;
-
-    if (!btif_is_enabled())
-    {
-        BTIF_TRACE_ERROR("btif_disable_bluetooth : not yet enabled");
-        return BT_STATUS_NOT_READY;
-    }
-
     BTIF_TRACE_DEBUG("BTIF DISABLE BLUETOOTH");
 
     btif_dm_on_disable();
-    btif_core_state = BTIF_CORE_STATE_DISABLING;
-
     /* cleanup rfcomm & l2cap api */
     btif_sock_cleanup();
-
     btif_pan_cleanup();
+    BTA_DisableBluetooth();
 
-    status = BTA_DisableBluetooth();
-
-    btif_config_flush();
-
-    if (status != BTA_SUCCESS)
-    {
-        BTIF_TRACE_ERROR("disable bt failed (%d)", status);
-
-        /* reset the original state to allow attempting disable again */
-        btif_core_state = BTIF_CORE_STATE_ENABLED;
-
-        return BT_STATUS_FAIL;
-    }
     return BT_STATUS_SUCCESS;
 }
 
@@ -716,20 +586,10 @@
 
      bte_main_disable();
 
-    /* update local state */
-    btif_core_state = BTIF_CORE_STATE_DISABLED;
-
     /* callback to HAL */
-    HAL_CBACK(bt_hal_cbacks, adapter_state_changed_cb, BT_STATE_OFF);
-
-    if (btif_shutdown_pending)
-    {
-        BTIF_TRACE_DEBUG("%s: calling btif_shutdown_bluetooth", __FUNCTION__);
-        btif_shutdown_bluetooth();
-    }
+    future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS);
 }
 
-
 /*******************************************************************************
 **
 ** Function         btif_shutdown_bluetooth
@@ -745,78 +605,22 @@
 {
     BTIF_TRACE_DEBUG("%s", __FUNCTION__);
 
-    if (btif_core_state == BTIF_CORE_STATE_DISABLING)
-    {
-        BTIF_TRACE_WARNING("shutdown during disabling");
-        /* shutdown called before disabling is done */
-        btif_shutdown_pending = 1;
-        return BT_STATUS_NOT_READY;
-    }
+    btif_transfer_context(btif_jni_disassociate, 0, NULL, 0, NULL);
 
-    if (btif_is_enabled())
-    {
-        BTIF_TRACE_WARNING("shutdown while still enabled, initiate disable");
-
-        /* shutdown called prior to disabling, initiate disable */
-        btif_disable_bluetooth();
-        btif_shutdown_pending = 1;
-        return BT_STATUS_NOT_READY;
-    }
-
-    btif_shutdown_pending = 0;
-
-    if (btif_core_state == BTIF_CORE_STATE_ENABLING)
-    {
-        // Java layer abort BT ENABLING, could be due to ENABLE TIMEOUT
-        // Direct call from cleanup()@bluetooth.c
-        // bring down HCI/Vendor lib
-        bte_main_disable();
-        btif_core_state = BTIF_CORE_STATE_DISABLED;
-        HAL_CBACK(bt_hal_cbacks, adapter_state_changed_cb, BT_STATE_OFF);
-    }
-
-    GKI_destroy_task(BTIF_TASK);
     btif_queue_release();
+
+    thread_free(bt_jni_workqueue_thread);
+    bt_jni_workqueue_thread = NULL;
+
     bte_main_shutdown();
 
     btif_dut_mode = 0;
 
-    bt_utils_cleanup();
-
     BTIF_TRACE_DEBUG("%s done", __FUNCTION__);
 
     return BT_STATUS_SUCCESS;
 }
 
-
-/*******************************************************************************
-**
-** Function         btif_disassociate_evt
-**
-** Description      Event indicating btif_task is going down
-**                  Detach btif_task to JVM
-**
-** Returns          void
-**
-*******************************************************************************/
-
-static bt_status_t btif_disassociate_evt(void)
-{
-    BTIF_TRACE_DEBUG("%s: notify DISASSOCIATE_JVM", __FUNCTION__);
-
-    HAL_CBACK(bt_hal_cbacks, thread_evt_cb, DISASSOCIATE_JVM);
-
-    /* shutdown complete, all events notified and we reset HAL callbacks */
-    bt_hal_cbacks = NULL;
-
-    return BT_STATUS_SUCCESS;
-}
-
-/****************************************************************************
-**
-**   BTIF Test Mode APIs
-**
-*****************************************************************************/
 /*******************************************************************************
 **
 ** Function         btif_dut_mode_cback
@@ -846,7 +650,7 @@
 {
     BTIF_TRACE_DEBUG("%s", __FUNCTION__);
 
-    if (btif_core_state != BTIF_CORE_STATE_ENABLED) {
+    if (!stack_manager_get_interface()->get_stack_is_running()) {
         BTIF_TRACE_ERROR("btif_dut_mode_configure : Bluetooth not enabled");
         return BT_STATUS_NOT_READY;
     }
@@ -1507,18 +1311,15 @@
     return BT_STATUS_SUCCESS;
 }
 
-/*******************************************************************************
-**
-** Function         btif_config_hci_snoop_log
-**
-** Description      enable or disable HCI snoop log
-**
-** Returns          bt_status_t
-**
-*******************************************************************************/
-bt_status_t btif_config_hci_snoop_log(uint8_t enable)
-{
-    bte_main_config_hci_logging(enable != 0,
-             btif_core_state == BTIF_CORE_STATE_DISABLED);
-    return BT_STATUS_SUCCESS;
+static void btif_jni_associate(UNUSED_ATTR uint16_t event, UNUSED_ATTR char *p_param) {
+  BTIF_TRACE_DEBUG("%s Associating thread to JVM", __func__);
+  HAL_CBACK(bt_hal_cbacks, thread_evt_cb, ASSOCIATE_JVM);
 }
+
+static void btif_jni_disassociate(UNUSED_ATTR uint16_t event, UNUSED_ATTR char *p_param) {
+  BTIF_TRACE_DEBUG("%s Disassociating thread from JVM", __func__);
+  HAL_CBACK(bt_hal_cbacks, thread_evt_cb, DISASSOCIATE_JVM);
+  bt_hal_cbacks = NULL;
+  future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS);
+}
+
diff --git a/btif/src/btif_dm.c b/btif/src/btif_dm.c
index 543ce86..a317a94 100644
--- a/btif/src/btif_dm.c
+++ b/btif/src/btif_dm.c
@@ -24,7 +24,9 @@
  *
  *
  ***********************************************************************************/
-#include <signal.h>
+
+#define LOG_TAG "bt_btif_dm"
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -32,11 +34,10 @@
 
 #include <hardware/bluetooth.h>
 
-#include <utils/Log.h>
 #include <cutils/properties.h>
 #include "gki.h"
 #include "btu.h"
-#include "bd.h"
+#include "btcore/include/bdaddr.h"
 #include "bta_api.h"
 #include "btif_api.h"
 #include "btif_util.h"
@@ -46,6 +47,9 @@
 #include "btif_config.h"
 
 #include "bta_gatt_api.h"
+#include "include/stack_config.h"
+
+#include "osi/include/log.h"
 
 /******************************************************************************
 **  Device specific workarounds
@@ -256,7 +260,7 @@
          {
               btif_hf_execute_service(b_enable);
          }break;
-         case BTA_A2DP_SERVICE_ID:
+         case BTA_A2DP_SOURCE_SERVICE_ID:
          {
               btif_av_execute_service(b_enable);
          }break;
@@ -298,11 +302,11 @@
     /* Check EIR for remote name and services */
     if (p_search_data->inq_res.p_eir)
     {
-        p_eir_remote_name = BTA_CheckEirData(p_search_data->inq_res.p_eir,
+        p_eir_remote_name = BTM_CheckEirData(p_search_data->inq_res.p_eir,
                 BTM_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len);
         if (!p_eir_remote_name)
         {
-            p_eir_remote_name = BTA_CheckEirData(p_search_data->inq_res.p_eir,
+            p_eir_remote_name = BTM_CheckEirData(p_search_data->inq_res.p_eir,
                     BTM_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len);
         }
 
@@ -371,7 +375,7 @@
                                sizeof(uint32_t), &remote_cod);
     if (btif_storage_get_remote_device_property((bt_bdaddr_t *)remote_bdaddr, &prop_name) == BT_STATUS_SUCCESS)
     {
-        BTIF_TRACE_ERROR("%s: remote_cod = 0x%06x", __FUNCTION__, remote_cod);
+        LOG_INFO("%s remote_cod = 0x%08x cod = 0x%08x", __func__, remote_cod, cod);
         if ((remote_cod & 0x7ff) == cod)
             return TRUE;
     }
@@ -411,8 +415,8 @@
         if (remote_dev_type == BT_DEVICE_DEVTYPE_BLE)
         {
             bdstr_t bdstr;
-            bd2str(remote_bdaddr, &bdstr);
-            if(btif_config_exist("Remote", bdstr, "HidAppId"))
+            bdaddr_to_string(remote_bdaddr, bdstr, sizeof(bdstr));
+            if(btif_config_exist(bdstr, "HidAppId"))
                 return TRUE;
         }
     }
@@ -435,7 +439,6 @@
     UINT16 manufacturer = 0;
     UINT8 lmp_ver = 0;
     UINT16 lmp_subver = 0;
-    tBTM_STATUS btm_status;
     bt_property_t prop_name;
     bt_remote_version_t info;
 
@@ -444,7 +447,7 @@
         return FALSE;
 
 /* fetch additional info about remote device used in iop query */
-    btm_status = BTM_ReadRemoteVersion(*(BD_ADDR*)remote_bdaddr, &lmp_ver,
+    BTM_ReadRemoteVersion(*(BD_ADDR*)remote_bdaddr, &lmp_ver,
                     &manufacturer, &lmp_subver);
 
 
@@ -512,7 +515,7 @@
     btm_status = BTM_ReadRemoteVersion(*(BD_ADDR*)p_bd, &lmp_ver,
                           &mfct_set, &lmp_subver);
 
-    ALOGD("remote version info [%s]: %x, %x, %x", bd2str(p_bd, &bdstr),
+    LOG_DEBUG("remote version info [%s]: %x, %x, %x", bdaddr_to_string(p_bd, bdstr, sizeof(bdstr)),
                lmp_ver, mfct_set, lmp_subver);
 
     if (btm_status == BTM_SUCCESS)
@@ -556,16 +559,16 @@
 
     /* class of device */
     cod = devclass2uint(dev_class);
-    BTIF_TRACE_DEBUG("%s():cod is 0x%06x", __FUNCTION__, cod);
+    BTIF_TRACE_DEBUG("%s cod is 0x%06x", __func__, cod);
     if ( cod == 0) {
        /* Try to retrieve cod from storage */
-        BTIF_TRACE_DEBUG("%s():cod is 0, checking cod from storage", __FUNCTION__);
+        BTIF_TRACE_DEBUG("%s cod is 0, checking cod from storage", __func__);
         BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
             BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod);
         status = btif_storage_get_remote_device_property(&bdaddr, &properties[num_properties]);
-        BTIF_TRACE_DEBUG("%s():cod retreived from storage is 0x%06x", __FUNCTION__, cod);
+        BTIF_TRACE_DEBUG("%s cod retrieved from storage is 0x%06x", __func__, cod);
         if ( cod == 0) {
-            BTIF_TRACE_DEBUG("%s():cod is again 0, set as unclassified", __FUNCTION__);
+            BTIF_TRACE_DEBUG("%s cod is again 0, set as unclassified", __func__);
             cod = COD_UNCLASSIFIED;
         }
     }
@@ -635,19 +638,19 @@
     int device_type;
     int addr_type;
     bdstr_t bdstr;
-    bd2str(bd_addr, &bdstr);
+    bdaddr_to_string(bd_addr, bdstr, sizeof(bdstr));
     if (transport == BT_TRANSPORT_LE)
     {
-        if (!btif_config_get_int("Remote", (char const *)&bdstr,"DevType", &device_type))
+        if (!btif_config_get_int((char const *)&bdstr,"DevType", &device_type))
         {
-            btif_config_set_int("Remote", bdstr, "DevType", BT_DEVICE_TYPE_BLE);
+            btif_config_set_int(bdstr, "DevType", BT_DEVICE_TYPE_BLE);
         }
         if (btif_storage_get_remote_addr_type(bd_addr, &addr_type) != BT_STATUS_SUCCESS)
         {
             btif_storage_set_remote_addr_type(bd_addr, BLE_ADDR_PUBLIC);
         }
     }
-    if((btif_config_get_int("Remote", (char const *)&bdstr,"DevType", &device_type) &&
+    if((btif_config_get_int((char const *)&bdstr,"DevType", &device_type) &&
        (btif_storage_get_remote_addr_type(bd_addr, &addr_type) == BT_STATUS_SUCCESS) &&
        (device_type == BT_DEVICE_TYPE_BLE)) || (transport == BT_TRANSPORT_LE))
     {
@@ -844,8 +847,8 @@
 
     cod = devclass2uint(p_pin_req->dev_class);
 
-    if ( cod == 0) {
-        BTIF_TRACE_DEBUG("%s():cod is 0, set as unclassified", __FUNCTION__);
+    if (cod == 0) {
+        BTIF_TRACE_DEBUG("%s cod is 0, set as unclassified", __func__);
         cod = COD_UNCLASSIFIED;
     }
 
@@ -964,8 +967,8 @@
 
     cod = devclass2uint(p_ssp_cfm_req->dev_class);
 
-    if ( cod == 0) {
-        ALOGD("cod is 0, set as unclassified");
+    if (cod == 0) {
+        LOG_DEBUG("%s cod is 0, set as unclassified", __func__);
         cod = COD_UNCLASSIFIED;
     }
 
@@ -999,8 +1002,8 @@
     pairing_cb.is_ssp = TRUE;
     cod = devclass2uint(p_ssp_key_notif->dev_class);
 
-    if ( cod == 0) {
-        ALOGD("cod is 0, set as unclassified");
+    if (cod == 0) {
+        LOG_DEBUG("%s cod is 0, set as unclassified", __func__);
         cod = COD_UNCLASSIFIED;
     }
 
@@ -1063,15 +1066,14 @@
 
         if (check_sdp_bl(&bd_addr) && check_cod_hid(&bd_addr, COD_HID_MAJOR))
         {
-            ALOGW("%s:skip SDP",
-                              __FUNCTION__);
+            LOG_WARN("%s:skip SDP", __FUNCTION__);
             skip_sdp = TRUE;
         }
         if(!pairing_cb.is_local_initiated && skip_sdp)
         {
             bond_state_changed(status, &bd_addr, state);
 
-            ALOGW("%s: Incoming HID Connection",__FUNCTION__);
+            LOG_WARN("%s: Incoming HID Connection",__FUNCTION__);
             bt_property_t prop;
             bt_bdaddr_t bd_addr;
             bt_uuid_t  uuid;
@@ -1232,7 +1234,7 @@
             p_search_data = (tBTA_DM_SEARCH *)p_param;
             bdcpy(bdaddr.address, p_search_data->inq_res.bd_addr);
 
-            BTIF_TRACE_DEBUG("%s() %s device_type = 0x%x\n", __FUNCTION__, bd2str(&bdaddr, &bdstr),
+            BTIF_TRACE_DEBUG("%s() %s device_type = 0x%x\n", __FUNCTION__, bdaddr_to_string(&bdaddr, bdstr, sizeof(bdstr)),
 #if (BLE_INCLUDED == TRUE)
                     p_search_data->inq_res.device_type);
 #else
@@ -1242,8 +1244,8 @@
 
             cod = devclass2uint (p_search_data->inq_res.dev_class);
 
-            if ( cod == 0) {
-                ALOGD("cod is 0, set as unclassified");
+            if (cod == 0) {
+                LOG_DEBUG("%s cod is 0, set as unclassified", __func__);
                 cod = COD_UNCLASSIFIED;
             }
 
@@ -1348,6 +1350,12 @@
             */
            if (btif_dm_inquiry_in_progress == FALSE)
            {
+#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
+               tBTA_DM_BLE_PF_FILT_PARAMS adv_filt_param;
+               memset(&adv_filt_param, 0, sizeof(tBTA_DM_BLE_PF_FILT_PARAMS));
+               BTA_DmBleScanFilterSetup(BTA_DM_BLE_SCAN_COND_DELETE, 0, &adv_filt_param, NULL,
+                                        bte_scan_filt_param_cfg_evt, 0);
+#endif
                HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb, BT_DISCOVERY_STOPPED);
            }
         }
@@ -1400,8 +1408,8 @@
                  for (i=0; i < p_data->disc_res.num_uuids; i++)
                  {
                       char temp[256];
-                      uuid_to_string((bt_uuid_t*)(p_data->disc_res.p_uuid_list + (i*MAX_UUID_SIZE)), temp);
-                      BTIF_TRACE_ERROR("Index: %d uuid:%s", i, temp);
+                      uuid_to_string_legacy((bt_uuid_t*)(p_data->disc_res.p_uuid_list + (i*MAX_UUID_SIZE)), temp);
+                      LOG_INFO("%s index:%d uuid:%s", __func__, i, temp);
                  }
             }
 
@@ -1460,8 +1468,8 @@
                     j--;
                 }
 
-                uuid_to_string(&uuid, temp);
-                BTIF_TRACE_ERROR(" uuid:%s", temp);
+                uuid_to_string_legacy(&uuid, temp);
+                LOG_INFO("%s uuid:%s", __func__, temp);
 
                 bdcpy(bd_addr.address, p_data->disc_ble_res.bd_addr);
                 prop.type = BT_PROPERTY_UUIDS;
@@ -1608,7 +1616,7 @@
 
              btif_storage_load_autopair_device_list();
 
-             btif_enable_bluetooth_evt(p_data->enable.status, p_data->enable.bd_addr);
+             btif_enable_bluetooth_evt(p_data->enable.status);
         }
         break;
 
@@ -2266,8 +2274,7 @@
     bdcpy(create_bond_cb.bdaddr.address, bd_addr->address);
 
     bdstr_t bdstr;
-    BTIF_TRACE_EVENT("%s: bd_addr=%s, transport=%d", __FUNCTION__,
-            bd2str((bt_bdaddr_t *) bd_addr, &bdstr), transport);
+    BTIF_TRACE_EVENT("%s: bd_addr=%s, transport=%d", __FUNCTION__, bdaddr_to_string(bd_addr, bdstr, sizeof(bdstr)), transport);
     if (pairing_cb.state != BT_BOND_STATE_NONE)
         return BT_STATUS_BUSY;
 
@@ -2291,7 +2298,7 @@
 {
     bdstr_t bdstr;
 
-    BTIF_TRACE_EVENT("%s: bd_addr=%s", __FUNCTION__, bd2str((bt_bdaddr_t *)bd_addr, &bdstr));
+    BTIF_TRACE_EVENT("%s: bd_addr=%s", __FUNCTION__, bdaddr_to_string(bd_addr, bdstr, sizeof(bdstr)));
 
     /* TODO:
     **  1. Restore scan modes
@@ -2380,7 +2387,7 @@
 {
     bdstr_t bdstr;
 
-    BTIF_TRACE_EVENT("%s: bd_addr=%s", __FUNCTION__, bd2str((bt_bdaddr_t *)bd_addr, &bdstr));
+    BTIF_TRACE_EVENT("%s: bd_addr=%s", __FUNCTION__, bdaddr_to_string(bd_addr, bdstr, sizeof(bdstr)));
     btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_REMOVE_BOND,
                           (char *)bd_addr, sizeof(bt_bdaddr_t), NULL);
 
@@ -2494,7 +2501,9 @@
         case BT_PROPERTY_BDNAME:
         {
             bt_bdname_t *bd_name = (bt_bdname_t*)prop->val;
-            strcpy((char *)bd_name->name, btif_get_default_local_name());
+            strncpy((char *)bd_name->name,btif_get_default_local_name(),
+                   sizeof(bd_name->name) - 1);
+            bd_name->name[sizeof(bd_name->name) - 1] = 0;
             prop->len = strlen((char *)bd_name->name);
         }
         break;
@@ -2536,7 +2545,7 @@
 {
     bdstr_t bdstr;
 
-    BTIF_TRACE_EVENT("%s: remote_addr=%s", __FUNCTION__, bd2str(remote_addr, &bdstr));
+    BTIF_TRACE_EVENT("%s: remote_addr=%s", __FUNCTION__, bdaddr_to_string(remote_addr, bdstr, sizeof(bdstr)));
 
     BTA_DmDiscover(remote_addr->address, BTA_ALL_SERVICE_MASK,
                    bte_dm_search_services_evt, TRUE);
@@ -2559,7 +2568,7 @@
     tSDP_UUID sdp_uuid;
     bdstr_t bdstr;
 
-    BTIF_TRACE_EVENT("%s: remote_addr=%s", __FUNCTION__, bd2str(remote_addr, &bdstr));
+    BTIF_TRACE_EVENT("%s: remote_addr=%s", __FUNCTION__, bdaddr_to_string(remote_addr, bdstr, sizeof(bdstr)));
 
     sdp_uuid.len = MAX_UUID_SIZE;
     memcpy(sdp_uuid.uu.uuid128, uuid->uu, MAX_UUID_SIZE);
diff --git a/btif/src/btif_gatt.c b/btif/src/btif_gatt.c
index 1ed5b0c..50ebaee 100644
--- a/btif/src/btif_gatt.c
+++ b/btif/src/btif_gatt.c
@@ -32,7 +32,7 @@
 #include <errno.h>
 #include <string.h>
 
-#define LOG_TAG "BtGatt.btif"
+#define LOG_TAG "bt_btif_gatt"
 
 #include "btif_common.h"
 #include "btif_util.h"
@@ -41,7 +41,6 @@
 
 #include "bta_api.h"
 #include "bta_gatt_api.h"
-#include "bd.h"
 #include "btif_storage.h"
 
 #include "btif_gatt.h"
diff --git a/btif/src/btif_gatt_client.c b/btif/src/btif_gatt_client.c
index 1bd12c2..bd72e03 100644
--- a/btif/src/btif_gatt_client.c
+++ b/btif/src/btif_gatt_client.c
@@ -31,8 +31,9 @@
 #include <errno.h>
 #include <string.h>
 
-#define LOG_TAG "BtGatt.btif"
+#define LOG_TAG "bt_btif_gattc"
 
+#include "btcore/include/bdaddr.h"
 #include "btif_common.h"
 #include "btif_util.h"
 
@@ -42,7 +43,6 @@
 #include <hardware/bt_gatt.h>
 #include "bta_api.h"
 #include "bta_gatt_api.h"
-#include "bd.h"
 #include "btif_storage.h"
 #include "btif_config.h"
 
@@ -51,6 +51,7 @@
 #include "btif_dm.h"
 #include "btif_storage.h"
 
+#include "osi/include/log.h"
 #include "vendor_api.h"
 
 /*******************************************************************************
@@ -59,10 +60,10 @@
 
 #define CHECK_BTGATT_INIT() if (bt_gatt_callbacks == NULL)\
     {\
-        BTIF_TRACE_WARNING("%s: BTGATT not initialized", __FUNCTION__);\
+        LOG_WARN("%s: BTGATT not initialized", __FUNCTION__);\
         return BT_STATUS_NOT_READY;\
     } else {\
-        BTIF_TRACE_DEBUG("%s", __FUNCTION__);\
+        LOG_DEBUG("%s", __FUNCTION__);\
     }
 
 #define BLE_RESOLVE_ADDR_MSB                 0x40   /* bit7, bit6 is 01 to be resolvable random */
@@ -345,7 +346,7 @@
             memcpy(p_dev_cb->remote_dev[i].bd_addr.address, p_bda, BD_ADDR_LEN);
             p_dev_cb->addr_type = addr_type;
             p_dev_cb->remote_dev[i].in_use = TRUE;
-            BTIF_TRACE_DEBUG("%s device added idx=%d", __FUNCTION__, i  );
+            LOG_DEBUG("%s device added idx=%d", __FUNCTION__, i  );
             break;
         }
     }
@@ -356,7 +357,7 @@
         memcpy(p_dev_cb->remote_dev[i].bd_addr.address, p_bda, BD_ADDR_LEN);
         p_dev_cb->addr_type = addr_type;
         p_dev_cb->remote_dev[i].in_use = TRUE;
-        BTIF_TRACE_DEBUG("%s device overwrite idx=%d", __FUNCTION__, i  );
+        LOG_DEBUG("%s device overwrite idx=%d", __FUNCTION__, i  );
         p_dev_cb->next_storage_idx++;
         if (p_dev_cb->next_storage_idx >= BTIF_GATT_MAX_OBSERVED_DEV)
                p_dev_cb->next_storage_idx = 0;
@@ -383,12 +384,12 @@
     uint8_t *p_eir_remote_name=NULL;
     bt_bdname_t bdname;
 
-    p_eir_remote_name = BTA_CheckEirData(p_btif_cb->value,
+    p_eir_remote_name = BTM_CheckEirData(p_btif_cb->value,
                                          BTM_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len);
 
     if (p_eir_remote_name == NULL)
     {
-        p_eir_remote_name = BTA_CheckEirData(p_btif_cb->value,
+        p_eir_remote_name = BTM_CheckEirData(p_btif_cb->value,
                                 BT_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len);
     }
 
@@ -397,7 +398,7 @@
         memcpy(bdname.name, p_eir_remote_name, remote_name_len);
         bdname.name[remote_name_len]='\0';
 
-        BTIF_TRACE_DEBUG("%s BLE device name=%s len=%d dev_type=%d", __FUNCTION__, bdname.name,
+        LOG_DEBUG("%s BLE device name=%s len=%d dev_type=%d", __FUNCTION__, bdname.name,
               remote_name_len, p_btif_cb->device_type  );
         btif_dm_update_ble_remote_properties( p_btif_cb->bd_addr.address,   bdname.name,
                                                p_btif_cb->device_type);
@@ -408,7 +409,7 @@
 
 static void btif_gattc_upstreams_evt(uint16_t event, char* p_param)
 {
-    BTIF_TRACE_EVENT("%s: Event %d", __FUNCTION__, event);
+    LOG_DEBUG("%s: Event %d", __FUNCTION__, event);
 
     tBTA_GATTC *p_data = (tBTA_GATTC*) p_param;
     switch (event)
@@ -550,7 +551,7 @@
         }
 
         case BTA_GATTC_ACL_EVT:
-            BTIF_TRACE_EVENT("BTA_GATTC_ACL_EVT: status = %d", p_data->status);
+            LOG_DEBUG("BTA_GATTC_ACL_EVT: status = %d", p_data->status);
             /* Ignore for now */
             break;
 
@@ -565,12 +566,12 @@
             bt_device_type_t dev_type;
             bt_property_t properties;
 
-            p_eir_remote_name = BTA_CheckEirData(p_btif_cb->value,
+            p_eir_remote_name = BTM_CheckEirData(p_btif_cb->value,
                                          BTM_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len);
 
             if (p_eir_remote_name == NULL)
             {
-                p_eir_remote_name = BTA_CheckEirData(p_btif_cb->value,
+                p_eir_remote_name = BTM_CheckEirData(p_btif_cb->value,
                                 BT_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len);
             }
 
@@ -578,13 +579,9 @@
             {
                if (!btif_gattc_find_bdaddr(p_btif_cb->bd_addr.address))
                {
-                  static const char* exclude_filter[] =
-                        {"LinkKey", "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"};
-
                   btif_gattc_add_remote_bdaddr(p_btif_cb->bd_addr.address, p_btif_cb->addr_type);
                   btif_gattc_update_properties(p_btif_cb);
-                  btif_config_filter_remove("Remote", exclude_filter, sizeof(exclude_filter)/sizeof(char*),
-                  BTIF_STORAGE_MAX_ALLOWED_REMOTE_DEVICE);
+
                }
 
             }
@@ -789,7 +786,7 @@
         }
 
         default:
-            BTIF_TRACE_ERROR("%s: Unhandled event (%d)!", __FUNCTION__, event);
+            LOG_ERROR("%s: Unhandled event (%d)!", __FUNCTION__, event);
             break;
     }
 
@@ -973,7 +970,7 @@
             if (p_data->inq_res.p_eir)
             {
                 memcpy(btif_cb.value, p_data->inq_res.p_eir, 62);
-                if (BTA_CheckEirData(p_data->inq_res.p_eir, BTM_EIR_COMPLETE_LOCAL_NAME_TYPE,
+                if (BTM_CheckEirData(p_data->inq_res.p_eir, BTM_EIR_COMPLETE_LOCAL_NAME_TYPE,
                                       &len))
                 {
                     p_data->inq_res.remt_name_not_required  = TRUE;
@@ -1081,7 +1078,7 @@
     btif_gattc_cb_t* p_cb = (btif_gattc_cb_t*) p_param;
     if (!p_cb) return;
 
-    BTIF_TRACE_EVENT("%s: Event %d", __FUNCTION__, event);
+    LOG_DEBUG("%s: Event %d", __FUNCTION__, event);
 
     switch (event)
     {
@@ -1475,7 +1472,7 @@
                 }
 
                 default:
-                    BTIF_TRACE_ERROR("%s: Unknown filter type (%d)!", __FUNCTION__, p_cb->action);
+                    LOG_ERROR("%s: Unknown filter type (%d)!", __FUNCTION__, p_cb->action);
                     break;
             }
             break;
@@ -1669,7 +1666,7 @@
         }
 
         default:
-            BTIF_TRACE_ERROR("%s: Unknown event (%d)!", __FUNCTION__, event);
+            LOG_ERROR("%s: Unknown event (%d)!", __FUNCTION__, event);
             break;
     }
 }
@@ -2095,8 +2092,8 @@
     int device_type = 0;
     char bd_addr_str[18] = {0};
 
-    bd2str(bd_addr, &bd_addr_str);
-    if (btif_config_get_int("Remote", bd_addr_str, "DevType", &device_type))
+    bdaddr_to_string(bd_addr, bd_addr_str, sizeof(bd_addr_str));
+    if (btif_config_get_int(bd_addr_str, "DevType", &device_type))
         return device_type;
     return 0;
 }
diff --git a/btif/src/btif_gatt_multi_adv_util.c b/btif/src/btif_gatt_multi_adv_util.c
index 30d02db..bd39657 100644
--- a/btif/src/btif_gatt_multi_adv_util.c
+++ b/btif/src/btif_gatt_multi_adv_util.c
@@ -31,7 +31,7 @@
 #include "btu.h"
 #include "bt_target.h"
 
-#define LOG_TAG "BtGatt.btif"
+#define LOG_TAG "bt_btif_gatt"
 #if (BLE_INCLUDED == TRUE)
 
 #include "btif_gatt_multi_adv_util.h"
diff --git a/btif/src/btif_gatt_server.c b/btif/src/btif_gatt_server.c
index eee0ed1..1632b01 100644
--- a/btif/src/btif_gatt_server.c
+++ b/btif/src/btif_gatt_server.c
@@ -32,7 +32,7 @@
 #include <errno.h>
 #include <string.h>
 
-#define LOG_TAG "BtGatt.btif"
+#define LOG_TAG "bt_btif_gatt"
 
 #include "btif_common.h"
 #include "btif_util.h"
@@ -42,13 +42,13 @@
 #include "gki.h"
 #include "bta_api.h"
 #include "bta_gatt_api.h"
-#include "bd.h"
 #include "btif_dm.h"
 #include "btif_storage.h"
 #include "btif_config.h"
 
 #include "btif_gatt.h"
 #include "btif_gatt_util.h"
+#include "osi/include/log.h"
 
 /************************************************************************************
 **  Constants & Macros
@@ -56,10 +56,10 @@
 
 #define CHECK_BTGATT_INIT() if (bt_gatt_callbacks == NULL)\
     {\
-        ALOGW("%s: BTGATT not initialized", __FUNCTION__);\
+        LOG_WARN("%s: BTGATT not initialized", __FUNCTION__);\
         return BT_STATUS_NOT_READY;\
     } else {\
-        ALOGD("%s", __FUNCTION__);\
+        LOG_DEBUG("%s", __FUNCTION__);\
     }
 
 
@@ -169,7 +169,7 @@
 
 static void btapp_gatts_handle_cback(uint16_t event, char* p_param)
 {
-    ALOGD("%s: Event %d", __FUNCTION__, event);
+    LOG_DEBUG("%s: Event %d", __FUNCTION__, event);
 
     tBTA_GATTS *p_data = (tBTA_GATTS*)p_param;
     switch (event)
@@ -344,11 +344,11 @@
         case BTA_GATTS_OPEN_EVT:
         case BTA_GATTS_CANCEL_OPEN_EVT:
         case BTA_GATTS_CLOSE_EVT:
-            ALOGD("%s: Empty event (%d)!", __FUNCTION__, event);
+            LOG_DEBUG("%s: Empty event (%d)!", __FUNCTION__, event);
             break;
 
         default:
-            ALOGE("%s: Unhandled event (%d)!", __FUNCTION__, event);
+            LOG_ERROR("%s: Unhandled event (%d)!", __FUNCTION__, event);
             break;
     }
 
@@ -368,7 +368,7 @@
     btif_gatts_cb_t* p_cb = (btif_gatts_cb_t*)p_param;
     if (!p_cb) return;
 
-    ALOGD("%s: Event %d", __FUNCTION__, event);
+    LOG_DEBUG("%s: Event %d", __FUNCTION__, event);
 
     switch (event)
     {
@@ -509,7 +509,7 @@
         }
 
         default:
-            ALOGE("%s: Unknown event (%d)!", __FUNCTION__, event);
+            LOG_ERROR("%s: Unknown event (%d)!", __FUNCTION__, event);
             break;
     }
 }
diff --git a/btif/src/btif_gatt_test.c b/btif/src/btif_gatt_test.c
index 4d71ad9..4ccf5b0 100644
--- a/btif/src/btif_gatt_test.c
+++ b/btif/src/btif_gatt_test.c
@@ -24,7 +24,7 @@
 #include <errno.h>
 #include <string.h>
 
-#define LOG_TAG "BtGatt.btif_test"
+#define LOG_TAG "bt_btif_gatt"
 
 #include "btif_common.h"
 #include "btif_util.h"
@@ -33,7 +33,6 @@
 
 #include "bta_api.h"
 #include "bta_gatt_api.h"
-#include "bd.h"
 #include "btif_storage.h"
 #include "bte_appl.h"
 
@@ -42,6 +41,7 @@
 #include "btif_dm.h"
 
 #include "gatt_api.h"
+#include "osi/include/log.h"
 
 /*******************************************************************************
  * Typedefs & Macros
@@ -108,14 +108,14 @@
     UNUSED(reason);
     UNUSED (transport);
 
-    ALOGD("%s: conn_id=%d, connected=%d", __FUNCTION__, conn_id, connected);
+    LOG_DEBUG("%s: conn_id=%d, connected=%d", __FUNCTION__, conn_id, connected);
     test_cb.conn_id = connected ? conn_id : 0;
 }
 
 static void btif_test_command_complete_cback(UINT16 conn_id, tGATTC_OPTYPE op,
                                 tGATT_STATUS status, tGATT_CL_COMPLETE *p_data)
 {
-    ALOGD ("%s: op_code=0x%02x, conn_id=0x%x. status=0x%x",
+    LOG_DEBUG ("%s: op_code=0x%02x, conn_id=0x%x. status=0x%x",
             __FUNCTION__, op, conn_id, status);
 
     switch (op)
@@ -132,7 +132,7 @@
             break;
 
         default:
-            ALOGD ("%s: Unknown op_code (0x%02x)", __FUNCTION__, op);
+            LOG_DEBUG ("%s: Unknown op_code (0x%02x)", __FUNCTION__, op);
             break;
     }
 }
@@ -144,50 +144,50 @@
     char    str_buf[50];
     UNUSED(conn_id);
 
-    ALOGD("------ GATT Discovery result %-22s -------", disc_name[disc_type]);
-    ALOGD("      Attribute handle: 0x%04x (%d)", p_data->handle, p_data->handle);
+    LOG_DEBUG("------ GATT Discovery result %-22s -------", disc_name[disc_type]);
+    LOG_DEBUG("      Attribute handle: 0x%04x (%d)", p_data->handle, p_data->handle);
 
     if (disc_type != GATT_DISC_CHAR_DSCPT) {
-        ALOGD("        Attribute type: %s", format_uuid(p_data->type, str_buf));
+        LOG_DEBUG("        Attribute type: %s", format_uuid(p_data->type, str_buf));
     }
 
     switch (disc_type)
     {
         case GATT_DISC_SRVC_ALL:
-            ALOGD("          Handle range: 0x%04x ~ 0x%04x (%d ~ %d)",
+            LOG_DEBUG("          Handle range: 0x%04x ~ 0x%04x (%d ~ %d)",
                   p_data->handle, p_data->value.group_value.e_handle,
                   p_data->handle, p_data->value.group_value.e_handle);
-            ALOGD("          Service UUID: %s",
+            LOG_DEBUG("          Service UUID: %s",
                     format_uuid(p_data->value.group_value.service_type, str_buf));
             break;
 
         case GATT_DISC_SRVC_BY_UUID:
-            ALOGD("          Handle range: 0x%04x ~ 0x%04x (%d ~ %d)",
+            LOG_DEBUG("          Handle range: 0x%04x ~ 0x%04x (%d ~ %d)",
                   p_data->handle, p_data->value.handle,
                   p_data->handle, p_data->value.handle);
             break;
 
         case GATT_DISC_INC_SRVC:
-            ALOGD("          Handle range: 0x%04x ~ 0x%04x (%d ~ %d)",
+            LOG_DEBUG("          Handle range: 0x%04x ~ 0x%04x (%d ~ %d)",
                   p_data->value.incl_service.s_handle, p_data->value.incl_service.e_handle,
                   p_data->value.incl_service.s_handle, p_data->value.incl_service.e_handle);
-            ALOGD("          Service UUID: %s",
+            LOG_DEBUG("          Service UUID: %s",
                   format_uuid(p_data->value.incl_service.service_type, str_buf));
             break;
 
         case GATT_DISC_CHAR:
-            ALOGD("            Properties: 0x%02x",
+            LOG_DEBUG("            Properties: 0x%02x",
                   p_data->value.dclr_value.char_prop);
-            ALOGD("   Characteristic UUID: %s",
+            LOG_DEBUG("   Characteristic UUID: %s",
                   format_uuid(p_data->value.dclr_value.char_uuid, str_buf));
             break;
 
         case GATT_DISC_CHAR_DSCPT:
-            ALOGD("       Descriptor UUID: %s", format_uuid(p_data->type, str_buf));
+            LOG_DEBUG("       Descriptor UUID: %s", format_uuid(p_data->type, str_buf));
             break;
     }
 
-    ALOGD("-----------------------------------------------------------");
+    LOG_DEBUG("-----------------------------------------------------------");
 }
 
 static void btif_test_discovery_complete_cback(UINT16 conn_id,
@@ -196,7 +196,7 @@
 {
     UNUSED(conn_id);
     UNUSED(disc_type);
-    ALOGD("%s: status=%d", __FUNCTION__, status);
+    LOG_DEBUG("%s: status=%d", __FUNCTION__, status);
 }
 
 static tGATT_CBACK btif_test_callbacks =
@@ -219,7 +219,7 @@
     switch(command) {
         case 0x01: /* Enable */
         {
-            ALOGD("%s: ENABLE - enable=%d", __FUNCTION__, params->u1);
+            LOG_DEBUG("%s: ENABLE - enable=%d", __FUNCTION__, params->u1);
             if (params->u1)
             {
                 tBT_UUID app_uuid = {LEN_UUID_128,{0xAE}};
@@ -234,7 +234,7 @@
 
         case 0x02: /* Connect */
         {
-            ALOGD("%s: CONNECT - device=%02x:%02x:%02x:%02x:%02x:%02x (dev_type=%d, addr_type=%d)",
+            LOG_DEBUG("%s: CONNECT - device=%02x:%02x:%02x:%02x:%02x:%02x (dev_type=%d, addr_type=%d)",
                 __FUNCTION__,
                 params->bda1->address[0], params->bda1->address[1],
                 params->bda1->address[2], params->bda1->address[3],
@@ -246,14 +246,14 @@
 
             if ( !GATT_Connect(test_cb.gatt_if, params->bda1->address, TRUE, BT_TRANSPORT_LE) )
             {
-                ALOGE("%s: GATT_Connect failed!", __FUNCTION__);
+                LOG_ERROR("%s: GATT_Connect failed!", __FUNCTION__);
             }
             break;
         }
 
         case 0x03: /* Disconnect */
         {
-            ALOGD("%s: DISCONNECT - conn_id=%d", __FUNCTION__, test_cb.conn_id);
+            LOG_DEBUG("%s: DISCONNECT - conn_id=%d", __FUNCTION__, test_cb.conn_id);
             GATT_Disconnect(test_cb.conn_id);
             break;
         }
@@ -266,7 +266,7 @@
 
             if (params->u1 >= GATT_DISC_MAX)
             {
-                ALOGE("%s: DISCOVER - Invalid type (%d)!", __FUNCTION__, params->u1);
+                LOG_ERROR("%s: DISCOVER - Invalid type (%d)!", __FUNCTION__, params->u1);
                 return 0;
             }
 
@@ -274,7 +274,7 @@
             param.e_handle = params->u3;
             btif_to_bta_uuid(&param.service, params->uuid1);
 
-            ALOGD("%s: DISCOVER (%s), conn_id=%d, uuid=%s, handles=0x%04x-0x%04x",
+            LOG_DEBUG("%s: DISCOVER (%s), conn_id=%d, uuid=%s, handles=0x%04x-0x%04x",
                   __FUNCTION__, disc_name[params->u1], test_cb.conn_id,
                   format_uuid(param.service, buf), params->u2, params->u3);
             GATTC_Discover(test_cb.conn_id, params->u1, &param);
@@ -282,7 +282,7 @@
         }
 
         case 0xF0: /* Pairing configuration */
-            ALOGD("%s: Setting pairing config auth=%d, iocaps=%d, keys=%d/%d/%d",
+            LOG_DEBUG("%s: Setting pairing config auth=%d, iocaps=%d, keys=%d/%d/%d",
                   __FUNCTION__, params->u1, params->u2, params->u3, params->u4,
                   params->u5);
 
@@ -294,7 +294,7 @@
             break;
 
         default:
-            ALOGE("%s: UNKNOWN TEST COMMAND 0x%02x", __FUNCTION__, command);
+            LOG_ERROR("%s: UNKNOWN TEST COMMAND 0x%02x", __FUNCTION__, command);
             break;
     }
     return 0;
diff --git a/btif/src/btif_gatt_util.c b/btif/src/btif_gatt_util.c
index 03c208c..7e00757 100644
--- a/btif/src/btif_gatt_util.c
+++ b/btif/src/btif_gatt_util.c
@@ -23,12 +23,12 @@
 #include <errno.h>
 #include <string.h>
 
-#define LOG_TAG "BtGatt.btif"
+#define LOG_TAG "bt_btif_gatt"
 
+#include "btcore/include/bdaddr.h"
 #include "bta_api.h"
 #include "bta_gatt_api.h"
 #include "bta_jv_api.h"
-#include "bd.h"
 #include "btif_storage.h"
 #include "btif_config.h"
 
@@ -102,7 +102,7 @@
             break;
 
         default:
-            ALOGE("%s: Unknown UUID length %d!", __FUNCTION__, p_dest->len);
+            LOG_ERROR("%s: Unknown UUID length %d!", __FUNCTION__, p_dest->len);
             break;
     }
 }
@@ -192,7 +192,7 @@
             break;
 
         default:
-            ALOGE("%s: Unknown UUID length %d!", __FUNCTION__, p_src->len);
+            LOG_ERROR("%s: Unknown UUID length %d!", __FUNCTION__, p_src->len);
             break;
     }
 }
@@ -257,7 +257,7 @@
         default:
             if (( p_src->status == BTA_GATT_OK ) &&(p_src->p_value != NULL))
             {
-                ALOGI("%s unformat.len = %d ", __FUNCTION__, p_src->p_value->unformat.len);
+                LOG_INFO("%s unformat.len = %d ", __FUNCTION__, p_src->p_value->unformat.len);
                 p_dest->value.len = p_src->p_value->unformat.len;
                 if ( p_src->p_value->unformat.len > 0  && p_src->p_value->unformat.p_value != NULL )
                 {
diff --git a/btif/src/btif_hf.c b/btif/src/btif_hf.c
index 976b6f4..f8c118b 100644
--- a/btif/src/btif_hf.c
+++ b/btif/src/btif_hf.c
@@ -30,12 +30,12 @@
 #include <stdlib.h>
 #include <string.h>
 
-#define LOG_TAG "BTIF_HF"
+#define LOG_TAG "bt_btif_hf"
 #include "btif_common.h"
 #include "btif_util.h"
 #include "btif_profile_queue.h"
 
-#include "bd.h"
+#include "btcore/include/bdaddr.h"
 #include "bta_ag_api.h"
 
 /************************************************************************************
@@ -422,7 +422,7 @@
             {
                 BTIF_TRACE_WARNING("%s: AG open failed, but another device connected. status=%d state=%d connected device=%s",
                         __FUNCTION__, p_data->open.status, btif_hf_cb[idx].state,
-                                 bd2str(&btif_hf_cb[idx].connected_bda, &bdstr));
+                                 bdaddr_to_string(&btif_hf_cb[idx].connected_bda, bdstr, sizeof(bdstr)));
                 break;
             }
 
diff --git a/btif/src/btif_hf_client.c b/btif/src/btif_hf_client.c
index a874e44..ee78a8a 100644
--- a/btif/src/btif_hf_client.c
+++ b/btif/src/btif_hf_client.c
@@ -32,12 +32,12 @@
 #include <string.h>
 #include <cutils/properties.h>
 
-#define LOG_TAG "BTIF_HF_CLIENT"
+#define LOG_TAG "bt_btif_hfc"
 #include "btif_common.h"
 #include "btif_util.h"
 #include "btif_profile_queue.h"
 #include "bt_utils.h"
-#include "bd.h"
+#include "btcore/include/bdaddr.h"
 #include "bta_hf_client_api.h"
 
 /************************************************************************************
@@ -764,7 +764,7 @@
             else
             {
                 BTIF_TRACE_WARNING("%s: HF CLient open failed, but another device connected. status=%d state=%d connected device=%s",
-                        __FUNCTION__, p_data->open.status, btif_hf_client_cb.state, bd2str(&btif_hf_client_cb.connected_bda, &bdstr));
+                        __FUNCTION__, p_data->open.status, btif_hf_client_cb.state, bdaddr_to_string(&btif_hf_client_cb.connected_bda, bdstr, sizeof(bdstr)));
                 break;
             }
 
diff --git a/btif/src/btif_hh.c b/btif/src/btif_hh.c
index 176643e..997f523 100644
--- a/btif/src/btif_hh.c
+++ b/btif/src/btif_hh.c
@@ -31,11 +31,10 @@
 #include <errno.h>
 #include <string.h>
 
-#define LOG_TAG "BTIF_HH"
+#define LOG_TAG "bt_btif_hh"
 
 #include "bta_api.h"
 #include "bta_hh_api.h"
-#include "bd.h"
 #include "btif_storage.h"
 
 #include "btif_common.h"
@@ -43,7 +42,7 @@
 #include "btif_hh.h"
 #include "gki.h"
 #include "l2c_api.h"
-
+#include "osi/include/log.h"
 
 #define BTIF_HH_APP_ID_MI       0x01
 #define BTIF_HH_APP_ID_KB       0x02
@@ -502,7 +501,7 @@
     btif_hh_device_t       *p_dev;
     btif_hh_added_device_t *p_added_dev;
 
-    ALOGI("%s: bda = %02x:%02x:%02x:%02x:%02x:%02x", __FUNCTION__,
+    LOG_INFO("%s: bda = %02x:%02x:%02x:%02x:%02x:%02x", __FUNCTION__,
          bd_addr.address[0], bd_addr.address[1], bd_addr.address[2], bd_addr.address[3], bd_addr.address[4], bd_addr.address[5]);
 
     for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
@@ -923,7 +922,7 @@
                 return;
             }
             if (p_dev->fd < 0) {
-                ALOGE("BTA_HH_GET_DSCP_EVT: Error, failed to find the uhid driver...");
+                LOG_ERROR("BTA_HH_GET_DSCP_EVT: Error, failed to find the uhid driver...");
                 return;
             }
             {
@@ -1065,7 +1064,7 @@
                 break;
 
         case BTA_HH_API_ERR_EVT  :
-                ALOGI("BTA_HH API_ERR");
+                LOG_INFO("BTA_HH API_ERR");
                 break;
 
 
@@ -1358,7 +1357,7 @@
     dscp_info.descriptor.dsc_list = (UINT8 *) GKI_getbuf(dscp_info.descriptor.dl_len);
     if (dscp_info.descriptor.dsc_list == NULL)
     {
-        ALOGE("%s: Failed to allocate DSCP for CB", __FUNCTION__);
+        LOG_ERROR("%s: Failed to allocate DSCP for CB", __FUNCTION__);
         return BT_STATUS_FAIL;
     }
     memcpy(dscp_info.descriptor.dsc_list, &(hid_info.dsc_list), hid_info.dl_len);
@@ -1552,7 +1551,7 @@
         memset(hexbuf, 0, len);
         //TODO
         hex_bytes_filled = ascii_2_hex(report, len, hexbuf);
-        BTIF_TRACE_DEBUG("Hex bytes filled, hex value: %d", hex_bytes_filled);
+        LOG_INFO("Hex bytes filled, hex value: %d", hex_bytes_filled);
         if (hex_bytes_filled) {
             BT_HDR* p_buf = create_pbuf(hex_bytes_filled, hexbuf);
             if (p_buf == NULL) {
diff --git a/btif/src/btif_hl.c b/btif/src/btif_hl.c
index e9b0f22..9d0c0d7 100644
--- a/btif/src/btif_hl.c
+++ b/btif/src/btif_hl.c
@@ -24,17 +24,26 @@
  *
  *
  ***********************************************************************************/
-#define LOG_TAG "BTIF_HL"
+#define LOG_TAG "bt_btif_hl"
 
+#include <assert.h>
+#include <ctype.h>
+#include <cutils/sockets.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <hardware/bluetooth.h>
+#include <hardware/bt_hl.h>
+#include <pthread.h>
+#include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <errno.h>
 #include <string.h>
-#include <sys/types.h>
+#include <sys/poll.h>
+#include <sys/select.h>
 #include <sys/socket.h>
+#include <sys/types.h>
 #include <sys/un.h>
 #include <time.h>
-#include <fcntl.h>
 #include <unistd.h>
 #include <pthread.h>
 #include <signal.h>
@@ -51,13 +60,17 @@
 #include "btif_common.h"
 #include "btif_util.h"
 #include "gki.h"
-#include "bd.h"
 #include "bta_api.h"
 #include "bta_hl_api.h"
-#include "mca_api.h"
+#include "btif_common.h"
 #include "btif_hl.h"
 #include "btif_storage.h"
+#include "btif_util.h"
 #include "btu.h"
+#include "gki.h"
+#include "osi/include/list.h"
+#include "mca_api.h"
+#include "osi/include/log.h"
 
 #define MAX_DATATYPE_SUPPORTED 8
 
@@ -91,7 +104,7 @@
 static int connected_s = -1;
 static int select_thread_id = -1;
 static int signal_fds[2] = { -1, -1 };
-static BUFFER_Q soc_queue;
+static list_t *soc_queue;
 static int reg_counter;
 
 static inline int btif_hl_select_wakeup(void);
@@ -564,7 +577,7 @@
 {
     btif_hl_app_cb_t          *p_acb  =BTIF_HL_GET_APP_CB_PTR(app_idx);
     btif_hl_mcl_cb_t          *p_mcb  =BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx);
-    UINT8                   i, j, num_recs,num_elems, num_mdeps, mdep_cnt, mdep_idx;
+    UINT8                   i, j, num_recs,num_elems, num_mdeps, mdep_idx;
     tBTA_HL_MDEP_ROLE       peer_mdep_role;
     UINT16                  data_type;
     tBTA_HL_SDP_MDEP_CFG    *p_mdep;
@@ -590,7 +603,6 @@
             data_type = p_acb->filter.elem[j].data_type;
             peer_mdep_role = p_acb->filter.elem[j].peer_mdep_role;
             elem_found = FALSE;
-            mdep_cnt =0;
             mdep_idx=0;
             while (!elem_found && mdep_idx < num_mdeps )
             {
@@ -1176,7 +1188,6 @@
                                          UINT16 data_type,
                                          tBTA_HL_MDEP_ID *p_peer_mdep_id){
     UINT8               app_idx, mcl_idx;
-    btif_hl_app_cb_t     *p_acb;
     btif_hl_mcl_cb_t     *p_mcb;
     tBTA_HL_SDP_REC     *p_rec;
     UINT8               i, num_mdeps;
@@ -1203,7 +1214,7 @@
 
     if (btif_hl_find_app_idx(app_id, &app_idx) )
     {
-        p_acb  = BTIF_HL_GET_APP_CB_PTR(app_idx);
+        BTIF_HL_GET_APP_CB_PTR(app_idx);
         if (btif_hl_find_mcl_idx(app_idx, bd_addr, &mcl_idx))
         {
             p_mcb  =BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx);
@@ -1828,8 +1839,8 @@
     {
         p_acb =BTIF_HL_GET_APP_CB_PTR(i);
         if (p_acb->delete_mdl.active) {
-            BTIF_TRACE_DEBUG("btif_hl_find_app_idx_using_deleted_mdl_id: app_idx=%d,"
-                              "mdl_id=%d mcl_handle=%d",i,mdl_id,p_acb->mcb[i].mcl_handle);
+            BTIF_TRACE_DEBUG("%s: app_idx=%d, mdl_id=%d",
+                             __FUNCTION__,i,mdl_id);
         }
         if (p_acb->delete_mdl.active &&
             (p_acb->delete_mdl.mdl_id == mdl_id))
@@ -2570,7 +2581,6 @@
 static BOOLEAN btif_hl_proc_cch_open_cfm(tBTA_HL *p_data)
 
 {
-    btif_hl_app_cb_t         *p_acb;
     btif_hl_mcl_cb_t         *p_mcb;
     UINT8                    app_idx, mcl_idx;
     BOOLEAN                  status = FALSE;
@@ -2582,7 +2592,7 @@
         BTIF_TRACE_DEBUG("app_idx=%d", app_idx);
         if (btif_hl_find_mcl_idx(app_idx, p_data->cch_open_cfm.bd_addr, &mcl_idx))
         {
-            p_acb = BTIF_HL_GET_APP_CB_PTR(app_idx);
+            BTIF_HL_GET_APP_CB_PTR(app_idx);
 
             p_mcb = BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx);
             BTIF_TRACE_DEBUG("mcl_idx=%d, mcl_handle=%d", mcl_idx,p_data->cch_open_cfm.mcl_handle);
@@ -2758,8 +2768,6 @@
 static void btif_hl_proc_dch_open_ind(tBTA_HL *p_data)
 
 {
-    btif_hl_app_cb_t         *p_acb;
-    btif_hl_mcl_cb_t         *p_mcb;
     btif_hl_mdl_cb_t         *p_dcb;
     UINT8                    orig_app_idx, mcl_idx, mdl_idx, mdep_cfg_idx;
     BOOLEAN close_dch = FALSE;
@@ -2771,8 +2779,8 @@
 
     if (btif_hl_find_mcl_idx_using_app_idx(p_data->dch_open_ind.mcl_handle, orig_app_idx, &mcl_idx ))
     {
-        p_acb =BTIF_HL_GET_APP_CB_PTR(orig_app_idx);
-        p_mcb =BTIF_HL_GET_MCL_CB_PTR(orig_app_idx, mcl_idx);
+        BTIF_HL_GET_APP_CB_PTR(orig_app_idx);
+        BTIF_HL_GET_MCL_CB_PTR(orig_app_idx, mcl_idx);
 
         if (btif_hl_find_avail_mdl_idx(orig_app_idx, mcl_idx, &mdl_idx))
         {
@@ -2837,8 +2845,6 @@
 static BOOLEAN btif_hl_proc_dch_open_cfm(tBTA_HL *p_data)
 
 {
-    btif_hl_app_cb_t            *p_acb;
-    btif_hl_mcl_cb_t            *p_mcb;
     btif_hl_mdl_cb_t            *p_dcb;
     btif_hl_pending_chan_cb_t   *p_pcb;
     UINT8                    app_idx, mcl_idx, mdl_idx, mdep_cfg_idx;
@@ -2852,8 +2858,8 @@
 
     if (btif_hl_find_mcl_idx_using_app_idx(p_data->dch_open_cfm.mcl_handle, app_idx, &mcl_idx ))
     {
-        p_acb = BTIF_HL_GET_APP_CB_PTR(app_idx);
-        p_mcb = BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx);
+        BTIF_HL_GET_APP_CB_PTR(app_idx);
+        BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx);
         p_pcb = BTIF_HL_GET_PCB_PTR(app_idx, mcl_idx);
 
         if (btif_hl_find_avail_mdl_idx(app_idx, mcl_idx, &mdl_idx))
@@ -2914,8 +2920,6 @@
 *******************************************************************************/
 static BOOLEAN btif_hl_proc_dch_reconnect_cfm(tBTA_HL *p_data)
 {
-    btif_hl_app_cb_t            *p_acb;
-    btif_hl_mcl_cb_t            *p_mcb;
     btif_hl_mdl_cb_t            *p_dcb;
     btif_hl_pending_chan_cb_t   *p_pcb;
     UINT8                    app_idx, mcl_idx, mdl_idx, mdep_cfg_idx;
@@ -2928,8 +2932,8 @@
 
     if (btif_hl_find_mcl_idx_using_app_idx(p_data->dch_reconnect_cfm.mcl_handle, app_idx, &mcl_idx ))
     {
-        p_acb = BTIF_HL_GET_APP_CB_PTR(app_idx);
-        p_mcb = BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx);
+        BTIF_HL_GET_APP_CB_PTR(app_idx);
+        BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx);
         p_pcb = BTIF_HL_GET_PCB_PTR(app_idx, mcl_idx);
 
         if (btif_hl_find_avail_mdl_idx(app_idx, mcl_idx, &mdl_idx))
@@ -2993,7 +2997,6 @@
 
 {
     btif_hl_app_cb_t        *p_acb;
-    btif_hl_mcl_cb_t        *p_mcb;
     btif_hl_mdl_cb_t        *p_dcb;
     UINT8                   app_idx, mcl_idx, mdl_idx, mdep_cfg_idx;
     BOOLEAN                 close_dch = FALSE;
@@ -3008,7 +3011,7 @@
         p_acb = BTIF_HL_GET_APP_CB_PTR(app_idx);
         BTIF_TRACE_DEBUG("btif_hl_proc_dch_reconnect_ind: app_idx = %d, mcl_idx = %d",
                                 app_idx, mcl_idx);
-        p_mcb = BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx);
+        BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx);
 
         if (btif_hl_find_avail_mdl_idx(app_idx, mcl_idx, &mdl_idx))
         {
@@ -3277,7 +3280,9 @@
     BOOLEAN                         send_chan_cb=TRUE;
     tBTA_HL_REG_PARAM               reg_param;
     btif_hl_app_cb_t                *p_acb;
-    int                             app_id;
+    bthl_app_reg_state_t            reg_state = BTHL_APP_REG_STATE_REG_FAILED;
+    UINT8                           preg_idx;
+    bt_status_t                     bt_status;
 
     BTIF_TRACE_DEBUG("%s event %d", __FUNCTION__, event);
     btif_hl_display_calling_process_name();
@@ -3309,7 +3314,6 @@
             break;
         case BTIF_HL_REG_APP:
             p_acb  = BTIF_HL_GET_APP_CB_PTR(p_data->reg.app_idx);
-            app_id = (int) p_acb->app_id;
             BTIF_TRACE_DEBUG("Rcv BTIF_HL_REG_APP app_idx=%d reg_pending=%d", p_data->reg.app_idx, p_acb->reg_pending);
             if (btif_hl_get_state() == BTIF_HL_STATE_ENABLED && p_acb->reg_pending)
             {
@@ -4147,7 +4151,6 @@
 **
 *******************************************************************************/
 static bt_status_t unregister_application(int app_id){
-    btif_hl_app_cb_t    *p_acb;
     UINT8               app_idx;
     int                 len;
     bt_status_t         status = BT_STATUS_SUCCESS;
@@ -4160,7 +4163,7 @@
     if (btif_hl_find_app_idx(((UINT8)app_id), &app_idx))
     {
         evt_param.unreg.app_idx = app_idx;
-        p_acb = BTIF_HL_GET_APP_CB_PTR(app_idx);
+        BTIF_HL_GET_APP_CB_PTR(app_idx);
         reg_counter --;
         len = sizeof(btif_hl_unreg_t);
         status = btif_transfer_context (btif_hl_proc_cb_evt, BTIF_HL_UNREG_APP,
@@ -4384,7 +4387,6 @@
 BOOLEAN  btif_hl_delete_mdl_cfg(UINT8 mdep_id, UINT8 item_idx){
     btif_hl_mdl_cfg_t     *p_mdl=NULL;
     BOOLEAN             success = FALSE;
-    btif_hl_app_cb_t      *p_acb;
     UINT8               app_idx, len;
     bt_status_t         bt_status;
     btif_hl_evt_cb_t    evt_param;
@@ -4392,7 +4394,7 @@
     if(btif_hl_find_app_idx_using_mdepId(mdep_id,&app_idx))
     {
 
-        p_acb = BTIF_HL_GET_APP_CB_PTR(app_idx);
+        BTIF_HL_GET_APP_CB_PTR(app_idx);
 
         p_mdl = BTIF_HL_GET_MDL_CFG_PTR(app_idx, item_idx);
         if (p_mdl)
@@ -4491,29 +4493,16 @@
 ** Returns int
 **
 *******************************************************************************/
-int btif_hl_update_maxfd( int max_org_s){
-    btif_hl_soc_cb_t      *p_scb = NULL;
-    int maxfd=0;
+int btif_hl_update_maxfd(int max_org_s) {
+    int maxfd = max_org_s;
 
     BTIF_TRACE_DEBUG("btif_hl_update_maxfd max_org_s= %d", max_org_s);
-
-    maxfd = max_org_s;
-    if (!GKI_queue_is_empty(&soc_queue))
-    {
-        p_scb = (btif_hl_soc_cb_t *)GKI_getfirst((void *)&soc_queue);
-        if (maxfd < p_scb->max_s)
-        {
+    for (const list_node_t *node = list_begin(soc_queue);
+            node != list_end(soc_queue); node = list_next(node)) {
+        btif_hl_soc_cb_t *p_scb = list_node(node);
+        if (maxfd < p_scb->max_s) {
             maxfd = p_scb->max_s;
-            BTIF_TRACE_DEBUG("btif_hl_update_maxfd 1 maxfd=%d", maxfd);
-        }
-        while (p_scb != NULL)
-        {
-            if (maxfd < p_scb->max_s)
-            {
-                maxfd = p_scb->max_s;
-                BTIF_TRACE_DEBUG("btif_hl_update_maxfd 2 maxfd=%d", maxfd);
-            }
-            p_scb = (btif_hl_soc_cb_t *)GKI_getnext((void *)p_scb );
+            BTIF_TRACE_DEBUG("btif_hl_update_maxfd maxfd=%d", maxfd);
         }
     }
 
@@ -4629,7 +4618,7 @@
             memcpy(p_scb->bd_addr, p_mcb->bd_addr,sizeof(BD_ADDR));
             btif_hl_set_socket_state(p_scb,  BTIF_HL_SOC_STATE_W4_ADD);
             p_scb->max_s = p_scb->socket_id[1];
-            GKI_enqueue(&soc_queue, (void *) p_scb);
+            list_append(soc_queue, (void *)p_scb);
             btif_hl_select_wakeup();
             status = TRUE;
         }
@@ -4652,8 +4641,7 @@
 ** Returns void
 **
 *******************************************************************************/
-void btif_hl_add_socket_to_set( fd_set *p_org_set){
-    btif_hl_soc_cb_t                *p_scb = NULL;
+void btif_hl_add_socket_to_set(fd_set *p_org_set) {
     btif_hl_mdl_cb_t                *p_dcb = NULL;
     btif_hl_mcl_cb_t                *p_mcb = NULL;
     btif_hl_app_cb_t                *p_acb = NULL;
@@ -4663,42 +4651,37 @@
 
     BTIF_TRACE_DEBUG("entering %s",__FUNCTION__);
 
-    if (!GKI_queue_is_empty(&soc_queue))
-    {
-        p_scb = (btif_hl_soc_cb_t *)GKI_getfirst((void *)&soc_queue);
+    for (const list_node_t *node = list_begin(soc_queue);
+            node != list_end(soc_queue); node = list_next(node)) {
+        btif_hl_soc_cb_t *p_scb = list_node(node);
+
         BTIF_TRACE_DEBUG("btif_hl_add_socket_to_set first p_scb=0x%x", p_scb);
-        while (p_scb != NULL)
-        {
-            if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_ADD)
-            {
-                btif_hl_set_socket_state(p_scb,   BTIF_HL_SOC_STATE_W4_READ);
-                FD_SET(p_scb->socket_id[1], p_org_set);
-                BTIF_TRACE_DEBUG("found and set socket_id=%d is_set=%d", p_scb->socket_id[1], FD_ISSET(p_scb->socket_id[1], p_org_set));
-                p_mcb = BTIF_HL_GET_MCL_CB_PTR(p_scb->app_idx, p_scb->mcl_idx);
-                p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx);
-                p_acb = BTIF_HL_GET_APP_CB_PTR(p_scb->app_idx);
-                if (p_mcb && p_dcb)
-                {
-                    btif_hl_stop_timer_using_handle(p_mcb->mcl_handle);
-                    evt_param.chan_cb.app_id = p_acb->app_id;
-                    memcpy(evt_param.chan_cb.bd_addr, p_mcb->bd_addr, sizeof(BD_ADDR));
-                    evt_param.chan_cb.channel_id = p_dcb->channel_id;
-                    evt_param.chan_cb.fd = p_scb->socket_id[0];
-                    evt_param.chan_cb.mdep_cfg_index = (int ) p_dcb->local_mdep_cfg_idx;
-                    evt_param.chan_cb.cb_state = BTIF_HL_CHAN_CB_STATE_CONNECTED_PENDING;
-                    len = sizeof(btif_hl_send_chan_state_cb_t);
-                    status = btif_transfer_context (btif_hl_proc_cb_evt, BTIF_HL_SEND_CONNECTED_CB,
-                                                    (char*) &evt_param, len, NULL);
-                    ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status);
-                }
+        if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_ADD) {
+            btif_hl_set_socket_state(p_scb, BTIF_HL_SOC_STATE_W4_READ);
+            FD_SET(p_scb->socket_id[1], p_org_set);
+            BTIF_TRACE_DEBUG("found and set socket_id=%d is_set=%d",
+                    p_scb->socket_id[1], FD_ISSET(p_scb->socket_id[1], p_org_set));
+            p_mcb = BTIF_HL_GET_MCL_CB_PTR(p_scb->app_idx, p_scb->mcl_idx);
+            p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx);
+            p_acb = BTIF_HL_GET_APP_CB_PTR(p_scb->app_idx);
+            if (p_mcb && p_dcb) {
+                btif_hl_stop_timer_using_handle(p_mcb->mcl_handle);
+                evt_param.chan_cb.app_id = p_acb->app_id;
+                memcpy(evt_param.chan_cb.bd_addr, p_mcb->bd_addr, sizeof(BD_ADDR));
+                evt_param.chan_cb.channel_id = p_dcb->channel_id;
+                evt_param.chan_cb.fd = p_scb->socket_id[0];
+                evt_param.chan_cb.mdep_cfg_index = (int ) p_dcb->local_mdep_cfg_idx;
+                evt_param.chan_cb.cb_state = BTIF_HL_CHAN_CB_STATE_CONNECTED_PENDING;
+                len = sizeof(btif_hl_send_chan_state_cb_t);
+                status = btif_transfer_context (btif_hl_proc_cb_evt, BTIF_HL_SEND_CONNECTED_CB,
+                        (char*) &evt_param, len, NULL);
+                ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status);
             }
-            p_scb = (btif_hl_soc_cb_t *)GKI_getnext((void *)p_scb );
-            BTIF_TRACE_DEBUG("next p_scb=0x%x", p_scb);
         }
     }
-
     BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__);
 }
+
 /*******************************************************************************
 **
 ** Function btif_hl_close_socket
@@ -4709,75 +4692,55 @@
 **
 *******************************************************************************/
 void btif_hl_close_socket( fd_set *p_org_set){
-    btif_hl_soc_cb_t                *p_scb = NULL;
-    BOOLEAN                         element_removed = FALSE;
-    btif_hl_mdl_cb_t                *p_dcb = NULL ;
-    btif_hl_evt_cb_t                evt_param;
-    int                             len;
-    bt_status_t                     status;
-
     BTIF_TRACE_DEBUG("entering %s",__FUNCTION__);
-    if (!GKI_queue_is_empty(&soc_queue))
-    {
-        p_scb = (btif_hl_soc_cb_t *)GKI_getfirst((void *)&soc_queue);
-        while (p_scb != NULL)
-        {
-            if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_REL)
-            {
-                BTIF_TRACE_DEBUG("app_idx=%d mcl_id=%d, mdl_idx=%d",
-                                  p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx);
-                btif_hl_set_socket_state(p_scb,   BTIF_HL_SOC_STATE_IDLE);
-                if (p_scb->socket_id[1] != -1)
-                {
-                    FD_CLR(p_scb->socket_id[1] , p_org_set);
-                    shutdown(p_scb->socket_id[1], SHUT_RDWR);
-                    close(p_scb->socket_id[1]);
+    for (const list_node_t *node = list_begin(soc_queue);
+            node != list_end(soc_queue); node = list_next(node)) {
+        btif_hl_soc_cb_t *p_scb = list_node(node);
+        if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_REL) {
+            BTIF_TRACE_DEBUG("app_idx=%d mcl_id=%d, mdl_idx=%d",
+                    p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx);
+            btif_hl_set_socket_state(p_scb, BTIF_HL_SOC_STATE_IDLE);
+            if (p_scb->socket_id[1] != -1) {
+                FD_CLR(p_scb->socket_id[1] , p_org_set);
+                shutdown(p_scb->socket_id[1], SHUT_RDWR);
+                close(p_scb->socket_id[1]);
 
-                    evt_param.chan_cb.app_id = (int) btif_hl_get_app_id(p_scb->channel_id);
-                    memcpy(evt_param.chan_cb.bd_addr, p_scb->bd_addr, sizeof(BD_ADDR));
-                    evt_param.chan_cb.channel_id = p_scb->channel_id;
-                    evt_param.chan_cb.fd = p_scb->socket_id[0];
-                    evt_param.chan_cb.mdep_cfg_index = (int ) p_scb->mdep_cfg_idx;
-                    evt_param.chan_cb.cb_state = BTIF_HL_CHAN_CB_STATE_DISCONNECTED_PENDING;
-                    len = sizeof(btif_hl_send_chan_state_cb_t);
-                    status = btif_transfer_context (btif_hl_proc_cb_evt, BTIF_HL_SEND_DISCONNECTED_CB,
-                                                    (char*) &evt_param, len, NULL);
-                    ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status);
-
-
-                }
+                btif_hl_evt_cb_t evt_param;
+                evt_param.chan_cb.app_id = (int) btif_hl_get_app_id(p_scb->channel_id);
+                memcpy(evt_param.chan_cb.bd_addr, p_scb->bd_addr, sizeof(BD_ADDR));
+                evt_param.chan_cb.channel_id = p_scb->channel_id;
+                evt_param.chan_cb.fd = p_scb->socket_id[0];
+                evt_param.chan_cb.mdep_cfg_index = (int ) p_scb->mdep_cfg_idx;
+                evt_param.chan_cb.cb_state = BTIF_HL_CHAN_CB_STATE_DISCONNECTED_PENDING;
+                int len = sizeof(btif_hl_send_chan_state_cb_t);
+                bt_status_t status = btif_transfer_context (btif_hl_proc_cb_evt,
+                        BTIF_HL_SEND_DISCONNECTED_CB,
+                        (char*) &evt_param, len, NULL);
+                ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status);
             }
-            p_scb = (btif_hl_soc_cb_t *)GKI_getnext((void *)p_scb );
-            BTIF_TRACE_DEBUG("while loop next p_scb=0x%x", p_scb);
         }
+    }
 
-        p_scb = (btif_hl_soc_cb_t *)GKI_getfirst((void *)&soc_queue);
-        while (p_scb != NULL)
-        {
-            if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_IDLE)
-            {
-                p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx);
-                BTIF_TRACE_DEBUG("idle socket app_idx=%d mcl_id=%d, mdl_idx=%d p_dcb->in_use=%d",
-                                  p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx, p_dcb->in_use);
-                GKI_remove_from_queue((void *)&soc_queue, p_scb);
-                btif_hl_free_buf((void **)&p_scb);
-                p_dcb->p_scb = NULL;
-                element_removed = TRUE;
-            }
-            BTIF_TRACE_DEBUG("element_removed=%d p_scb=0x%x", element_removed, p_scb);
-            if (element_removed)
-            {
-                element_removed = FALSE;
-                p_scb = (btif_hl_soc_cb_t *)GKI_getfirst((void *)&soc_queue);
-            }
-            else
-                p_scb = (btif_hl_soc_cb_t *)GKI_getnext((void *)p_scb );
-
-            BTIF_TRACE_DEBUG("while loop p_scb=0x%x", p_scb);
+    for (const list_node_t *node = list_begin(soc_queue);
+        node != list_end(soc_queue); ) {
+        // We may mutate this list so we need keep track of
+        // the current node and only remove items behind.
+        btif_hl_soc_cb_t *p_scb = list_node(node);
+        node = list_next(node);
+        if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_IDLE) {
+            btif_hl_mdl_cb_t *p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx,
+                    p_scb->mcl_idx, p_scb->mdl_idx);
+            BTIF_TRACE_DEBUG("idle socket app_idx=%d mcl_id=%d, mdl_idx=%d p_dcb->in_use=%d",
+                    p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx, p_dcb->in_use);
+            list_remove(soc_queue, p_scb);
+            btif_hl_free_buf((void **)&p_scb);
+            p_dcb->p_scb = NULL;
         }
+        BTIF_TRACE_DEBUG("p_scb=0x%x", p_scb);
     }
     BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__);
 }
+
 /*******************************************************************************
 **
 ** Function btif_hl_select_wakeup_callback
@@ -4811,65 +4774,49 @@
 ** Returns void
 **
 *******************************************************************************/
-void btif_hl_select_monitor_callback( fd_set *p_cur_set , fd_set *p_org_set){
-    btif_hl_soc_cb_t      *p_scb = NULL;
-    btif_hl_mdl_cb_t      *p_dcb = NULL;
-    int r;
+void btif_hl_select_monitor_callback(fd_set *p_cur_set ,fd_set *p_org_set) {
     UNUSED(p_org_set);
 
     BTIF_TRACE_DEBUG("entering %s",__FUNCTION__);
 
-    if (!GKI_queue_is_empty(&soc_queue))
-    {
-        p_scb = (btif_hl_soc_cb_t *)GKI_getfirst((void *)&soc_queue);
-        BTIF_TRACE_DEBUG(" GKI queue is not empty ");
-        while (p_scb != NULL)
-        {
-            if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_READ)
-            {
-                if (FD_ISSET(p_scb->socket_id[1], p_cur_set))
-                {
-                    BTIF_TRACE_DEBUG("read data");
-                    BTIF_TRACE_DEBUG("state= BTIF_HL_SOC_STATE_W4_READ");
-                    p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx);
-                    if (p_dcb->p_tx_pkt)
-                    {
-                        BTIF_TRACE_ERROR("Rcv new pkt but the last pkt is still not been sent tx_size=%d", p_dcb->tx_size);
-                        btif_hl_free_buf((void **) &p_dcb->p_tx_pkt);
-                    }
-                    p_dcb->p_tx_pkt =  btif_hl_get_buf (p_dcb->mtu);
-                    if (p_dcb )
-                    {
-                        //do
-                        // {
-                        //     r = recv(p_scb->socket_id[1], p_dcb->p_tx_pkt, p_dcb->mtu , MSG_DONTWAIT));
-                        // } while (r == SOCKET_ERROR && errno == EINTR);
-
-                        if ((r = (int)recv(p_scb->socket_id[1], p_dcb->p_tx_pkt, p_dcb->mtu , MSG_DONTWAIT)) > 0)
-                        {
-                            BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data r =%d", r);
-                            p_dcb->tx_size = r;
-                            BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data tx_size=%d", p_dcb->tx_size );
-                            BTA_HlSendData(p_dcb->mdl_handle, p_dcb->tx_size  );
-                        }
-
-                        if (r <= 0 )
-                        {
-                            BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback  receive failed r=%d",r);
-                            BTA_HlDchClose(p_dcb->mdl_handle );
-                        }
+    for (const list_node_t *node = list_begin(soc_queue);
+            node != list_end(soc_queue); node = list_next(node)) {
+        btif_hl_soc_cb_t *p_scb = list_node(node);
+        if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_READ) {
+            if (FD_ISSET(p_scb->socket_id[1], p_cur_set)) {
+                BTIF_TRACE_DEBUG("read data state= BTIF_HL_SOC_STATE_W4_READ");
+                btif_hl_mdl_cb_t *p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx,
+                        p_scb->mcl_idx, p_scb->mdl_idx);
+                assert(p_dcb != NULL);
+                if (p_dcb->p_tx_pkt) {
+                    BTIF_TRACE_ERROR("Rcv new pkt but the last pkt is still not been"
+                            "  sent tx_size=%d", p_dcb->tx_size);
+                    btif_hl_free_buf((void **) &p_dcb->p_tx_pkt);
+                }
+                p_dcb->p_tx_pkt = btif_hl_get_buf (p_dcb->mtu);
+                if (p_dcb) {
+                    int r = (int)recv(p_scb->socket_id[1], p_dcb->p_tx_pkt,
+                            p_dcb->mtu, MSG_DONTWAIT);
+                    if (r > 0) {
+                        BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data r =%d", r);
+                        p_dcb->tx_size = r;
+                        BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data tx_size=%d", p_dcb->tx_size );
+                        BTA_HlSendData(p_dcb->mdl_handle, p_dcb->tx_size);
+                    } else {
+                        BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback receive failed r=%d",r);
+                        BTA_HlDchClose(p_dcb->mdl_handle);
                     }
                 }
             }
-            p_scb = (btif_hl_soc_cb_t *)GKI_getnext((void *)p_scb );
         }
     }
-    else
-    {
+
+    if (list_is_empty(soc_queue))
         BTIF_TRACE_DEBUG("btif_hl_select_monitor_queue is empty");
-    }
+
     BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__);
 }
+
 /*******************************************************************************
 **
 ** Function btif_hl_select_wakeup_init
@@ -4947,6 +4894,7 @@
             select_thread_id = -1;
         }
     }
+    list_free(soc_queue);
     return result;
 }
 
@@ -5098,7 +5046,9 @@
 *******************************************************************************/
 void btif_hl_soc_thread_init(void){
     BTIF_TRACE_DEBUG("%s", __FUNCTION__);
-    GKI_init_q(&soc_queue);
+    soc_queue = list_new(NULL);
+    if (soc_queue == NULL)
+        LOG_ERROR("%s unable to allocate resources for thread", __func__);
     select_thread_id = create_thread(btif_hl_select_thread, NULL);
 }
 /*******************************************************************************
diff --git a/btif/src/btif_mce.c b/btif/src/btif_mce.c
index 7345384..c50ef8b 100644
--- a/btif/src/btif_mce.c
+++ b/btif/src/btif_mce.c
@@ -31,14 +31,15 @@
 #include <stdlib.h>
 #include <string.h>
 
-#define LOG_TAG "BTIF_MCE"
+#define LOG_TAG "bt_btif_mce"
 #include "btif_common.h"
 #include "btif_util.h"
 #include "btif_profile_queue.h"
 #include "bta_api.h"
 #include "bta_mce_api.h"
 
-#include "bd.h"
+#include "bt_types.h"
+#include "btcore/include/bdaddr.h"
 
 /*****************************************************************************
 **  Static variables
@@ -134,7 +135,7 @@
 {
     bdstr_t bdstr;
 
-    BTIF_TRACE_EVENT("%s: remote_addr=%s", __FUNCTION__, bd2str(bd_addr, &bdstr));
+    BTIF_TRACE_EVENT("%s: remote_addr=%s", __FUNCTION__, bdaddr_to_string(bd_addr, bdstr, sizeof(bdstr)));
 
     BTA_MceGetRemoteMasInstances(bd_addr->address);
 
diff --git a/btif/src/btif_media_task.c b/btif/src/btif_media_task.c
index 7908996..2d6f68a 100644
--- a/btif/src/btif_media_task.c
+++ b/btif/src/btif_media_task.c
@@ -26,6 +26,9 @@
  **
  ******************************************************************************/
 
+#define LOG_TAG "bt_btif_media"
+
+#include <assert.h>
 #include <string.h>
 #include <stdio.h>
 #include <sys/types.h>
@@ -38,6 +41,7 @@
 #include <errno.h>
 
 #include "bt_target.h"
+#include "osi/include/fixed_queue.h"
 #include "gki.h"
 #include "bta_api.h"
 #include "btu.h"
@@ -55,12 +59,14 @@
 #include "btif_av_co.h"
 #include "btif_media.h"
 
+#include "osi/include/alarm.h"
+#include "osi/include/log.h"
+#include "osi/include/thread.h"
+
 #if (BTA_AV_INCLUDED == TRUE)
 #include "sbc_encoder.h"
 #endif
 
-#define LOG_TAG "BTIF-MEDIA"
-
 #include <hardware/bluetooth.h>
 #include "audio_a2dp_hw.h"
 #include "btif_av.h"
@@ -73,8 +79,6 @@
 #include "stdio.h"
 #include <dlfcn.h>
 
-//#define DEBUG_MEDIA_AV_FLOW TRUE
-
 #if (BTA_AV_SINK_INCLUDED == TRUE)
 OI_CODEC_SBC_DECODER_CONTEXT context;
 OI_UINT32 contextData[CODEC_DATA_WORDS(2, SBC_CODEC_FAST_FILTER_BUFFERS)];
@@ -93,25 +97,6 @@
 #define AUDIO_CHANNEL_OUT_STEREO 0x03
 #endif
 
-/* BTIF media task gki event definition */
-#define BTIF_MEDIA_TASK_CMD TASK_MBOX_0_EVT_MASK
-#define BTIF_MEDIA_TASK_DATA TASK_MBOX_1_EVT_MASK
-
-#define BTIF_MEDIA_TASK_KILL EVENT_MASK(GKI_SHUTDOWN_EVT)
-
-#define BTIF_MEDIA_AA_TASK_TIMER_ID TIMER_0
-#define BTIF_MEDIA_AV_TASK_TIMER_ID TIMER_1
-#define BTIF_MEDIA_AVK_TASK_TIMER_ID TIMER_2
-
-#define BTIF_MEDIA_AA_TASK_TIMER TIMER_0_EVT_MASK
-#define BTIF_MEDIA_AV_TASK_TIMER TIMER_1_EVT_MASK
-#define BTIF_MEDIA_AVK_TASK_TIMER TIMER_2_EVT_MASK
-
-
-#define BTIF_MEDIA_TASK_CMD_MBOX        TASK_MBOX_0     /* cmd mailbox  */
-#define BTIF_MEDIA_TASK_DATA_MBOX       TASK_MBOX_1     /* data mailbox  */
-
-
 /* BTIF media cmd event definition : BTIF_MEDIA_TASK_CMD */
 enum
 {
@@ -128,8 +113,6 @@
     BTIF_MEDIA_AUDIO_FEEDING_INIT,
     BTIF_MEDIA_AUDIO_RECEIVING_INIT,
     BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE,
-    BTIF_MEDIA_AUDIO_SINK_START_DECODING,
-    BTIF_MEDIA_AUDIO_SINK_STOP_DECODING,
     BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK
 };
 
@@ -175,15 +158,6 @@
 #define BTIF_A2DP_NON_EDR_MAX_RATE 229
 #endif
 
-#ifndef A2DP_MEDIA_TASK_STACK_SIZE
-#define A2DP_MEDIA_TASK_STACK_SIZE       0x2000         /* In bytes */
-#endif
-
-#define A2DP_MEDIA_TASK_TASK_STR        ((INT8 *) "A2DP-MEDIA")
-static UINT32 a2dp_media_task_stack[(A2DP_MEDIA_TASK_STACK_SIZE + 3) / 4];
-
-#define BT_MEDIA_TASK A2DP_MEDIA_TASK
-
 #define USEC_PER_SEC 1000000L
 #define TPUT_STATS_INTERVAL_US (3000*1000)
 
@@ -213,7 +187,6 @@
 #define MAX_PCM_FRAME_NUM_PER_TICK     14
 #endif
 
-//#define BTIF_MEDIA_VERBOSE_ENABLED
 /* In case of A2DP SINK, we will delay start by 5 AVDTP Packets*/
 #define MAX_A2DP_DELAYED_START_FRAME_COUNT 5
 #define PACKET_PLAYED_PER_TICK_48 8
@@ -221,18 +194,6 @@
 #define PACKET_PLAYED_PER_TICK_32 5
 #define PACKET_PLAYED_PER_TICK_16 3
 
-
-#ifdef BTIF_MEDIA_VERBOSE_ENABLED
-#define VERBOSE(fmt, ...) \
-      LogMsg( TRACE_CTRL_GENERAL | TRACE_LAYER_NONE | TRACE_ORG_APPL | \
-              TRACE_TYPE_ERROR, fmt, ## __VA_ARGS__)
-#else
-#define VERBOSE(fmt, ...)
-#endif
-
-/*****************************************************************************
- **  Data types
- *****************************************************************************/
 typedef struct
 {
     UINT16 num_frames_to_be_processed;
@@ -250,7 +211,6 @@
     UINT32 bytes_per_tick;  /* pcm bytes read each media task tick */
 } tBTIF_AV_MEDIA_FEEDINGS_PCM_STATE;
 
-
 typedef union
 {
     tBTIF_AV_MEDIA_FEEDINGS_PCM_STATE pcm;
@@ -281,6 +241,8 @@
 
     UINT32  sample_rate;
     UINT8   channel_count;
+    alarm_t *media_alarm;
+    alarm_t *decode_alarm;
 #endif
 
 } tBTIF_MEDIA_CB;
@@ -293,23 +255,11 @@
     long long ts_prev_us;
 } t_stat;
 
-/*****************************************************************************
- **  Local data
- *****************************************************************************/
-
-static tBTIF_MEDIA_CB btif_media_cb;
-static int media_task_running = MEDIA_TASK_STATE_OFF;
 static UINT64 last_frame_us = 0;
 
-
-/*****************************************************************************
- **  Local functions
- *****************************************************************************/
-
 static void btif_a2dp_data_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event);
 static void btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event);
 static void btif_a2dp_encoder_update(void);
-const char* dump_media_event(UINT16 event);
 #if (BTA_AV_SINK_INCLUDED == TRUE)
 extern OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT *context,
                                           const OI_BYTE **frameData,
@@ -326,14 +276,12 @@
 static void btif_media_flush_q(BUFFER_Q *p_q);
 static void btif_media_task_aa_handle_stop_decoding(void );
 static void btif_media_task_aa_rx_flush(void);
-static BOOLEAN btif_media_task_stop_decoding_req(void);
 
-/*****************************************************************************
- **  Externs
- *****************************************************************************/
+static const char *dump_media_event(UINT16 event);
+static void btif_media_thread_init(void *context);
+static void btif_media_thread_cleanup(void *context);
+static void btif_media_thread_handle_cmd(fixed_queue_t *queue, void *context);
 
-static void btif_media_task_handle_cmd(BT_HDR *p_msg);
-static void btif_media_task_handle_media(BT_HDR*p_msg);
 /* Handle incoming media packets A2DP SINK streaming*/
 #if (BTA_AV_SINK_INCLUDED == TRUE)
 static void btif_media_task_handle_inc_media(tBT_SBC_HDR*p_msg);
@@ -353,10 +301,19 @@
 static void btif_media_task_aa_handle_decoder_reset(BT_HDR *p_msg);
 static void btif_media_task_aa_handle_clear_track(void);
 #endif
-static void btif_media_task_aa_handle_start_decoding(void );
+static void btif_media_task_aa_handle_start_decoding(void);
 #endif
-BOOLEAN btif_media_task_start_decoding_req(void);
 BOOLEAN btif_media_task_clear_track(void);
+
+static void btif_media_task_aa_handle_timer(UNUSED_ATTR void *context);
+static void btif_media_task_avk_handle_timer(UNUSED_ATTR void *context);
+
+static tBTIF_MEDIA_CB btif_media_cb;
+static int media_task_running = MEDIA_TASK_STATE_OFF;
+
+static fixed_queue_t *btif_media_cmd_msg_queue;
+static thread_t *worker_thread;
+
 /*****************************************************************************
  **  Misc helper functions
  *****************************************************************************/
@@ -373,11 +330,11 @@
     static UINT64 prev_us = 0;
     const UINT64 now_us = time_now_us();
     APPL_TRACE_DEBUG("[%s] ts %08llu, diff : %08llu, queue sz %d", comment, now_us, now_us - prev_us,
-                btif_media_cb.TxAaQ.count);
+                GKI_queue_length(&btif_media_cb.TxAaQ));
     prev_us = now_us;
 }
 
-const char* dump_media_event(UINT16 event)
+UNUSED_ATTR static const char *dump_media_event(UINT16 event)
 {
     switch(event)
     {
@@ -394,8 +351,6 @@
         CASE_RETURN_STR(BTIF_MEDIA_AUDIO_FEEDING_INIT)
         CASE_RETURN_STR(BTIF_MEDIA_AUDIO_RECEIVING_INIT)
         CASE_RETURN_STR(BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE)
-        CASE_RETURN_STR(BTIF_MEDIA_AUDIO_SINK_START_DECODING)
-        CASE_RETURN_STR(BTIF_MEDIA_AUDIO_SINK_STOP_DECODING)
         CASE_RETURN_STR(BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK)
 
         default:
@@ -749,61 +704,49 @@
     btif_media_task_enc_update_req(&msg);
 }
 
-
-/*****************************************************************************
-**
-** Function        btif_a2dp_start_media_task
-**
-** Description
-**
-** Returns
-**
-*******************************************************************************/
-
-int btif_a2dp_start_media_task(void)
+bool btif_a2dp_start_media_task(void)
 {
-    int retval;
-
     if (media_task_running != MEDIA_TASK_STATE_OFF)
     {
         APPL_TRACE_ERROR("warning : media task already running");
-        return GKI_FAILURE;
+        return false;
     }
 
-    APPL_TRACE_EVENT("## A2DP START MEDIA TASK ##");
+    APPL_TRACE_EVENT("## A2DP START MEDIA THREAD ##");
+
+    btif_media_cmd_msg_queue = fixed_queue_new(SIZE_MAX);
 
     /* start a2dp media task */
-    retval = GKI_create_task((TASKPTR)btif_media_task, A2DP_MEDIA_TASK,
-                A2DP_MEDIA_TASK_TASK_STR,
-                (UINT16 *) ((UINT8 *)a2dp_media_task_stack + A2DP_MEDIA_TASK_STACK_SIZE),
-                sizeof(a2dp_media_task_stack));
+    worker_thread = thread_new("media_worker");
+    if (worker_thread == NULL)
+        goto error_exit;
 
-    if (retval != GKI_SUCCESS)
-        return retval;
+    fixed_queue_register_dequeue(btif_media_cmd_msg_queue,
+        thread_get_reactor(worker_thread),
+        btif_media_thread_handle_cmd,
+        NULL);
 
-    /* wait for task to come up to sure we are able to send messages to it */
-    while (media_task_running == MEDIA_TASK_STATE_OFF)
-        usleep(10);
+    thread_post(worker_thread, btif_media_thread_init, NULL);
 
-    APPL_TRACE_EVENT("## A2DP MEDIA TASK STARTED ##");
+    APPL_TRACE_EVENT("## A2DP MEDIA THREAD STARTED ##");
 
-    return retval;
+    return true;
+
+ error_exit:;
+    APPL_TRACE_ERROR("%s unable to start up media thread", __func__);
+    return false;
 }
 
-/*****************************************************************************
-**
-** Function        btif_a2dp_stop_media_task
-**
-** Description
-**
-** Returns
-**
-*******************************************************************************/
-
 void btif_a2dp_stop_media_task(void)
 {
-    APPL_TRACE_EVENT("## A2DP STOP MEDIA TASK ##");
-    GKI_destroy_task(BT_MEDIA_TASK);
+    APPL_TRACE_EVENT("## A2DP STOP MEDIA THREAD ##");
+
+    fixed_queue_free(btif_media_cmd_msg_queue, NULL);
+    thread_post(worker_thread, btif_media_thread_cleanup, NULL);
+    thread_free(worker_thread);
+
+    worker_thread = NULL;
+    btif_media_cmd_msg_queue = NULL;
 }
 
 /*****************************************************************************
@@ -890,7 +833,7 @@
     {
         btif_media_cb.rx_flush = TRUE;
         btif_media_task_aa_rx_flush_req();
-        btif_media_task_stop_decoding_req();
+        btif_media_task_aa_handle_stop_decoding();
         btif_media_task_clear_track();
         APPL_TRACE_DEBUG("Stopped BT track");
     }
@@ -935,60 +878,7 @@
 
     p_buf->event = BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK;
 
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
-    return TRUE;
-}
-/*******************************************************************************
- **
- ** Function         btif_media_task_stop_decoding_req
- **
- ** Description
- **
- ** Returns          TRUE is success
- **
- *******************************************************************************/
-BOOLEAN btif_media_task_stop_decoding_req(void)
-{
-    BT_HDR *p_buf;
-
-    if (!btif_media_cb.is_rx_timer)
-        return TRUE;   /*  if timer is not running no need to send message */
-
-    if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
-    {
-        return FALSE;
-    }
-
-    p_buf->event = BTIF_MEDIA_AUDIO_SINK_STOP_DECODING;
-
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
-    return TRUE;
-}
-
-/*******************************************************************************
- **
- ** Function         btif_media_task_start_decoding_req
- **
- ** Description
- **
- ** Returns          TRUE is success
- **
- *******************************************************************************/
-BOOLEAN btif_media_task_start_decoding_req(void)
-{
-    BT_HDR *p_buf;
-
-    if(btif_media_cb.is_rx_timer)
-        return FALSE;   /*  if timer is already running no need to send message */
-
-    if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
-    {
-        return FALSE;
-    }
-
-    p_buf->event = BTIF_MEDIA_AUDIO_SINK_START_DECODING;
-
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
+    fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
     return TRUE;
 }
 
@@ -1019,7 +909,7 @@
     memcpy(p_buf->codec_info,p_av, AVDT_CODEC_SIZE);
     p_buf->hdr.event = BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE;
 
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
+    fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
 }
 
 /*****************************************************************************
@@ -1108,7 +998,7 @@
     {
         btif_media_cb.rx_flush = TRUE;
         btif_media_task_aa_rx_flush_req();
-        btif_media_task_stop_decoding_req();
+        btif_media_task_aa_handle_stop_decoding();
         UIPC_Close(UIPC_CH_ID_AV_AUDIO);
         btif_media_cb.data_channel_open = FALSE;
         return;
@@ -1154,7 +1044,7 @@
     {
         btif_media_cb.rx_flush = TRUE;
         btif_media_task_aa_rx_flush_req();
-        btif_media_task_stop_decoding_req();
+        btif_media_task_aa_handle_stop_decoding();
         return;
     }
 
@@ -1189,16 +1079,7 @@
 }
 
 #if (BTA_AV_SINK_INCLUDED == TRUE)
-/*******************************************************************************
- **
- ** Function         btif_media_task_avk_handle_timer
- **
- ** Description
- **
- ** Returns          void
- **
- *******************************************************************************/
-static void btif_media_task_avk_handle_timer ( void )
+static void btif_media_task_avk_handle_timer(UNUSED_ATTR void *context)
 {
     UINT8 count;
     tBT_SBC_HDR *p_msg;
@@ -1256,25 +1137,12 @@
         APPL_TRACE_DEBUG(" Process Frames - ");
     }
 }
+#else
+static void btif_media_task_avk_handle_timer(UNUSED_ATTR void *context) {}
 #endif
 
-/*******************************************************************************
- **
- ** Function         btif_media_task_aa_handle_timer
- **
- ** Description
- **
- ** Returns          void
- **
- *******************************************************************************/
-
-static void btif_media_task_aa_handle_timer(void)
+static void btif_media_task_aa_handle_timer(UNUSED_ATTR void *context)
 {
-#if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
-    static UINT16 Debug = 0;
-    APPL_TRACE_DEBUG("btif_media_task_aa_handle_timer: %d", Debug++);
-#endif
-
     log_tstamps_us("media task tx timer");
 
 #if (BTA_AV_INCLUDED == TRUE)
@@ -1290,142 +1158,39 @@
 }
 
 #if (BTA_AV_INCLUDED == TRUE)
-/*******************************************************************************
- **
- ** Function         btif_media_task_aa_handle_timer
- **
- ** Description
- **
- ** Returns          void
- **
- *******************************************************************************/
 static void btif_media_task_aa_handle_uipc_rx_rdy(void)
 {
-#if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
-    static UINT16 Debug = 0;
-    APPL_TRACE_DEBUG("btif_media_task_aa_handle_uipc_rx_rdy: %d", Debug++);
-#endif
-
     /* process all the UIPC data */
     btif_media_aa_prep_2_send(0xFF);
 
     /* send it */
-    VERBOSE("btif_media_task_aa_handle_uipc_rx_rdy calls bta_av_ci_src_data_ready");
+    LOG_VERBOSE("btif_media_task_aa_handle_uipc_rx_rdy calls bta_av_ci_src_data_ready");
     bta_av_ci_src_data_ready(BTA_AV_CHNL_AUDIO);
 }
 #endif
 
-/*******************************************************************************
- **
- ** Function         btif_media_task_init
- **
- ** Description
- **
- ** Returns          void
- **
- *******************************************************************************/
-
-void btif_media_task_init(void)
-{
-    memset(&(btif_media_cb), 0, sizeof(btif_media_cb));
-
-    UIPC_Init(NULL);
+static void btif_media_thread_init(UNUSED_ATTR void *context) {
+  memset(&btif_media_cb, 0, sizeof(btif_media_cb));
+  UIPC_Init(NULL);
 
 #if (BTA_AV_INCLUDED == TRUE)
-    UIPC_Open(UIPC_CH_ID_AV_CTRL , btif_a2dp_ctrl_cb);
+  UIPC_Open(UIPC_CH_ID_AV_CTRL , btif_a2dp_ctrl_cb);
 #endif
-}
-/*******************************************************************************
- **
- ** Function         btif_media_task
- **
- ** Description      Task for SBC encoder.  This task receives an
- **                  event when the waveIn interface has a pcm data buffer
- **                  ready.  On receiving the event, handle all ready pcm
- **                  data buffers.  If stream is started, run the SBC encoder
- **                  on each chunk of pcm samples and build an output packet
- **                  consisting of one or more encoded SBC frames.
- **
- ** Returns          void
- **
- *******************************************************************************/
-int btif_media_task(void *p)
-{
-    UINT16 event;
-    BT_HDR *p_msg;
-    UNUSED(p);
 
-    VERBOSE("================ MEDIA TASK STARTING ================");
-
-    btif_media_task_init();
-
-    media_task_running = MEDIA_TASK_STATE_ON;
-
-    raise_priority_a2dp(TASK_HIGH_MEDIA);
-
-    while (1)
-    {
-        event = GKI_wait(0xffff, 0);
-
-        VERBOSE("================= MEDIA TASK EVENT %d ===============", event);
-
-        if (event & BTIF_MEDIA_TASK_CMD)
-        {
-            /* Process all messages in the queue */
-            while ((p_msg = (BT_HDR *) GKI_read_mbox(BTIF_MEDIA_TASK_CMD_MBOX)) != NULL)
-            {
-                btif_media_task_handle_cmd(p_msg);
-            }
-        }
-
-        if (event & BTIF_MEDIA_TASK_DATA)
-        {
-            VERBOSE("================= Received Media Packets %d ===============", event);
-            /* Process all messages in the queue */
-            while ((p_msg = (BT_HDR *) GKI_read_mbox(BTIF_MEDIA_TASK_DATA_MBOX)) != NULL)
-            {
-                btif_media_task_handle_media(p_msg);
-            }
-        }
-
-        if (event & BTIF_MEDIA_AA_TASK_TIMER)
-        {
-            /* advance audio timer expiration */
-            btif_media_task_aa_handle_timer();
-        }
-
-        if (event & BTIF_MEDIA_AVK_TASK_TIMER)
-        {
-#if (BTA_AV_SINK_INCLUDED == TRUE)
-            /* advance audio timer expiration for a2dp sink */
-            btif_media_task_avk_handle_timer();
-#endif
-        }
-
-
-
-        VERBOSE("=============== MEDIA TASK EVENT %d DONE ============", event);
-
-        /* When we get this event we exit the task  - should only happen on GKI_shutdown  */
-        if (event & BTIF_MEDIA_TASK_KILL)
-        {
-            /* make sure no channels are restarted while shutting down */
-            media_task_running = MEDIA_TASK_STATE_SHUTTING_DOWN;
-
-            /* this calls blocks until uipc is fully closed */
-            UIPC_Close(UIPC_CH_ID_ALL);
-            break;
-        }
-    }
-
-    /* Clear media task flag */
-    media_task_running = MEDIA_TASK_STATE_OFF;
-
-    APPL_TRACE_DEBUG("MEDIA TASK EXITING");
-
-    return 0;
+  raise_priority_a2dp(TASK_HIGH_MEDIA);
+  media_task_running = MEDIA_TASK_STATE_ON;
 }
 
+static void btif_media_thread_cleanup(UNUSED_ATTR void *context) {
+  /* make sure no channels are restarted while shutting down */
+  media_task_running = MEDIA_TASK_STATE_SHUTTING_DOWN;
+
+  /* this calls blocks until uipc is fully closed */
+  UIPC_Close(UIPC_CH_ID_ALL);
+
+  /* Clear media task flag */
+  media_task_running = MEDIA_TASK_STATE_OFF;
+}
 
 /*******************************************************************************
  **
@@ -1446,7 +1211,7 @@
 
     p_buf->event = Evt;
 
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
+    fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
     return TRUE;
 }
 
@@ -1467,19 +1232,10 @@
     }
 }
 
-
-/*******************************************************************************
- **
- ** Function         btif_media_task_handle_cmd
- **
- ** Description
- **
- ** Returns          void
- **
- *******************************************************************************/
-static void btif_media_task_handle_cmd(BT_HDR *p_msg)
+static void btif_media_thread_handle_cmd(fixed_queue_t *queue, UNUSED_ATTR void *context)
 {
-    VERBOSE("btif_media_task_handle_cmd : %d %s", p_msg->event,
+    BT_HDR *p_msg = (BT_HDR *)fixed_queue_dequeue(queue);
+    LOG_VERBOSE("btif_media_thread_handle_cmd : %d %s", p_msg->event,
              dump_media_event(p_msg->event));
 
     switch (p_msg->event)
@@ -1511,26 +1267,20 @@
         btif_media_task_aa_handle_decoder_reset(p_msg);
 #endif
         break;
-    case BTIF_MEDIA_AUDIO_SINK_START_DECODING:
-        btif_media_task_aa_handle_start_decoding();
-        break;
     case BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK:
 #if (BTA_AV_SINK_INCLUDED == TRUE)
         btif_media_task_aa_handle_clear_track();
 #endif
         break;
-    case BTIF_MEDIA_AUDIO_SINK_STOP_DECODING:
-        btif_media_task_aa_handle_stop_decoding();
-        break;
      case BTIF_MEDIA_FLUSH_AA_RX:
         btif_media_task_aa_rx_flush();
         break;
 #endif
     default:
-        APPL_TRACE_ERROR("ERROR in btif_media_task_handle_cmd unknown event %d", p_msg->event);
+        APPL_TRACE_ERROR("ERROR in %s unknown event %d", __func__, p_msg->event);
     }
     GKI_freebuf(p_msg);
-    VERBOSE("btif_media_task_handle_cmd : %s DONE", dump_media_event(p_msg->event));
+    LOG_VERBOSE("%s: %s DONE", __func__, dump_media_event(p_msg->event));
 }
 
 #if (BTA_AV_SINK_INCLUDED == TRUE)
@@ -1587,20 +1337,6 @@
 }
 #endif
 
-/*******************************************************************************
- **
- ** Function         btif_media_task_handle_media
- **
- ** Description
- **
- ** Returns          void
- **
- *******************************************************************************/
-static void btif_media_task_handle_media(BT_HDR*p_msg)
-{
-    APPL_TRACE_DEBUG(" btif_media_task_handle_media ");
-    GKI_freebuf(p_msg);
-}
 #if (BTA_AV_INCLUDED == TRUE)
 /*******************************************************************************
  **
@@ -1622,7 +1358,7 @@
     memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_INIT_AUDIO));
     p_buf->hdr.event = BTIF_MEDIA_SBC_ENC_INIT;
 
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
+    fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
     return TRUE;
 }
 
@@ -1646,7 +1382,7 @@
     memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_UPDATE_AUDIO));
     p_buf->hdr.event = BTIF_MEDIA_SBC_ENC_UPDATE;
 
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
+    fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
     return TRUE;
 }
 
@@ -1670,7 +1406,7 @@
     memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_INIT_AUDIO_FEEDING));
     p_buf->hdr.event = BTIF_MEDIA_AUDIO_FEEDING_INIT;
 
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
+    fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
     return TRUE;
 }
 
@@ -1694,7 +1430,7 @@
 
     p_buf->event = BTIF_MEDIA_START_AA_TX;
 
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
+    fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
     return TRUE;
 }
 
@@ -1717,7 +1453,7 @@
 
     p_buf->event = BTIF_MEDIA_STOP_AA_TX;
 
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
+    fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
     return TRUE;
 }
 /*******************************************************************************
@@ -1743,7 +1479,7 @@
 
     p_buf->event = BTIF_MEDIA_FLUSH_AA_RX;
 
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
+    fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
     return TRUE;
 }
 
@@ -1766,7 +1502,7 @@
 
     p_buf->event = BTIF_MEDIA_FLUSH_AA_TX;
 
-    GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
+    fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
     return TRUE;
 }
 /*******************************************************************************
@@ -2158,36 +1894,26 @@
     btif_media_cb.peer_sep = sep;
 }
 
-/*******************************************************************************
- **
- ** Function         btif_media_task_aa_handle_stop_decoding
- **
- ** Description
- **
- ** Returns          void
- **
- *******************************************************************************/
-static void btif_media_task_aa_handle_stop_decoding(void )
-{
-    btif_media_cb.is_rx_timer = FALSE;
-    GKI_stop_timer(BTIF_MEDIA_AVK_TASK_TIMER_ID);
+static void btif_decode_alarm_cb(UNUSED_ATTR void *context) {
+  thread_post(worker_thread, btif_media_task_avk_handle_timer, NULL);
 }
 
-/*******************************************************************************
- **
- ** Function         btif_media_task_aa_handle_start_decoding
- **
- ** Description
- **
- ** Returns          void
- **
- *******************************************************************************/
-static void btif_media_task_aa_handle_start_decoding(void )
-{
-    if(btif_media_cb.is_rx_timer == TRUE)
-        return;
-    btif_media_cb.is_rx_timer = TRUE;
-    GKI_start_timer(BTIF_MEDIA_AVK_TASK_TIMER_ID, GKI_MS_TO_TICKS(BTIF_SINK_MEDIA_TIME_TICK), TRUE);
+static void btif_media_task_aa_handle_stop_decoding(void) {
+  alarm_free(btif_media_cb.decode_alarm);
+  btif_media_cb.decode_alarm = NULL;
+}
+
+static void btif_media_task_aa_handle_start_decoding(void) {
+  if (btif_media_cb.decode_alarm)
+    return;
+
+  btif_media_cb.decode_alarm = alarm_new();
+  if (!btif_media_cb.decode_alarm) {
+    LOG_ERROR("%s unable to allocate decode alarm.", __func__);
+    return;
+  }
+
+  alarm_set_periodic(btif_media_cb.decode_alarm, BTIF_SINK_MEDIA_TIME_TICK, btif_decode_alarm_cb, NULL);
 }
 
 #if (BTA_AV_SINK_INCLUDED == TRUE)
@@ -2365,6 +2091,11 @@
                             (int)btif_media_cb.media_feeding_state.pcm.bytes_per_tick);
     }
 }
+
+static void btif_media_task_alarm_cb(UNUSED_ATTR void *context) {
+  thread_post(worker_thread, btif_media_task_aa_handle_timer, NULL);
+}
+
 /*******************************************************************************
  **
  ** Function         btif_media_task_aa_start_tx
@@ -2388,10 +2119,17 @@
     /* Reset the media feeding state */
     btif_media_task_feeding_state_reset();
 
-    APPL_TRACE_EVENT("starting timer %d ticks (%d)",
-                  GKI_MS_TO_TICKS(BTIF_MEDIA_TIME_TICK), TICKS_PER_SEC);
+    APPL_TRACE_EVENT("starting timer %dms", BTIF_MEDIA_TIME_TICK);
 
-    GKI_start_timer(BTIF_MEDIA_AA_TASK_TIMER_ID, GKI_MS_TO_TICKS(BTIF_MEDIA_TIME_TICK), TRUE);
+    assert(btif_media_cb.media_alarm == NULL);
+
+    btif_media_cb.media_alarm = alarm_new();
+    if (!btif_media_cb.media_alarm) {
+      LOG_ERROR("%s unable to allocate media alarm.", __func__);
+      return;
+    }
+
+    alarm_set_periodic(btif_media_cb.media_alarm, BTIF_MEDIA_TIME_TICK, btif_media_task_alarm_cb, NULL);
 }
 
 /*******************************************************************************
@@ -2408,7 +2146,8 @@
     APPL_TRACE_DEBUG("btif_media_task_aa_stop_tx is timer: %d", btif_media_cb.is_tx_timer);
 
     /* Stop the timer first */
-    GKI_stop_timer(BTIF_MEDIA_AA_TASK_TIMER_ID);
+    alarm_free(btif_media_cb.media_alarm);
+    btif_media_cb.media_alarm = NULL;
     btif_media_cb.is_tx_timer = FALSE;
 
     UIPC_Close(UIPC_CH_ID_AV_AUDIO);
@@ -2463,7 +2202,7 @@
             }
             btif_media_cb.media_feeding_state.pcm.counter -= result*pcm_bytes_per_frame;
 
-            VERBOSE("WRITE %d FRAMES", result);
+            LOG_VERBOSE("WRITE %d FRAMES", result);
         }
         break;
 
@@ -2474,10 +2213,6 @@
             break;
     }
 
-#if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
-    APPL_TRACE_DEBUG("btif_get_num_aa_frame returns %d", result);
-#endif
-
     return (UINT8)result;
 }
 
@@ -2495,8 +2230,8 @@
     tBT_SBC_HDR *p_msg;
 
     if(btif_media_cb.rx_flush == TRUE) /* Flush enabled, do not enque*/
-        return btif_media_cb.RxSbcQ.count;
-    if(btif_media_cb.RxSbcQ.count == MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ)
+        return GKI_queue_length(&btif_media_cb.RxSbcQ);
+    if(GKI_queue_length(&btif_media_cb.RxSbcQ) == MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ)
     {
         GKI_freebuf(GKI_dequeue(&(btif_media_cb.RxSbcQ)));
     }
@@ -2510,10 +2245,10 @@
         p_msg->num_frames_to_be_processed = (*((UINT8*)(p_msg + 1) + p_msg->offset)) & 0x0f;
         BTIF_TRACE_VERBOSE("btif_media_sink_enque_buf + ", p_msg->num_frames_to_be_processed);
         GKI_enqueue(&(btif_media_cb.RxSbcQ), p_msg);
-        if(btif_media_cb.RxSbcQ.count == MAX_A2DP_DELAYED_START_FRAME_COUNT)
+        if(GKI_queue_length(&btif_media_cb.RxSbcQ) == MAX_A2DP_DELAYED_START_FRAME_COUNT)
         {
             BTIF_TRACE_DEBUG(" Initiate Decoding ");
-            btif_media_task_start_decoding_req();
+            btif_media_task_aa_handle_start_decoding();
         }
     }
     else
@@ -2521,7 +2256,7 @@
         /* let caller deal with a failed allocation */
         BTIF_TRACE_VERBOSE("btif_media_sink_enque_buf No Buffer left - ");
     }
-    return btif_media_cb.RxSbcQ.count;
+    return GKI_queue_length(&btif_media_cb.RxSbcQ);
 }
 
 /*******************************************************************************
@@ -2682,11 +2417,6 @@
             sizeof(up_sampled_buffer) - btif_media_cb.media_feeding_state.pcm.aa_feed_residue,
             &src_size_used);
 
-#if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
-    APPL_TRACE_DEBUG("btif_media_aa_read_feeding readsz:%d src_size_used:%d dst_size_used:%d",
-            read_size, src_size_used, dst_size_used);
-#endif
-
     /* update the residue */
     btif_media_cb.media_feeding_state.pcm.aa_feed_residue += dst_size_used;
 
@@ -2709,11 +2439,6 @@
         return TRUE;
     }
 
-#if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
-    APPL_TRACE_DEBUG("btif_media_aa_read_feeding residue:%d, dst_size_used %d, bytes_needed %d",
-            btif_media_cb.media_feeding_state.pcm.aa_feed_residue, dst_size_used, bytes_needed);
-#endif
-
     return FALSE;
 }
 
@@ -2732,16 +2457,12 @@
     UINT16 blocm_x_subband = btif_media_cb.encoder.s16NumOfSubBands *
                              btif_media_cb.encoder.s16NumOfBlocks;
 
-#if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
-    APPL_TRACE_DEBUG("btif_media_aa_prep_sbc_2_send nb_frame %d, TxAaQ %d",
-                       nb_frame, btif_media_cb.TxAaQ.count);
-#endif
     while (nb_frame)
     {
         if (NULL == (p_buf = GKI_getpoolbuf(BTIF_MEDIA_AA_POOL_ID)))
         {
             APPL_TRACE_ERROR ("ERROR btif_media_aa_prep_sbc_2_send no buffer TxCnt %d ",
-                                btif_media_cb.TxAaQ.count);
+                                GKI_queue_length(&btif_media_cb.TxAaQ));
             return;
         }
 
@@ -2801,13 +2522,11 @@
 
             btif_media_cb.timestamp += p_buf->layer_specific * blocm_x_subband;
 
-            VERBOSE("TX QUEUE NOW %d", btif_media_cb.TxAaQ.count);
-
             if (btif_media_cb.tx_flush)
             {
                 APPL_TRACE_DEBUG("### tx suspended, discarded frame ###");
 
-                if (btif_media_cb.TxAaQ.count > 0)
+                if (GKI_queue_length(&btif_media_cb.TxAaQ) > 0)
                     btif_media_flush_q(&(btif_media_cb.TxAaQ));
 
                 GKI_freebuf(p_buf);
@@ -2837,16 +2556,14 @@
 
 static void btif_media_aa_prep_2_send(UINT8 nb_frame)
 {
-    VERBOSE("%s() - frames=%d (queue=%d)", __FUNCTION__, nb_frame, btif_media_cb.TxAaQ.count);
-
-    while (btif_media_cb.TxAaQ.count >= (MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ-nb_frame))
+    while (GKI_queue_length(&btif_media_cb.TxAaQ) >= (MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ-nb_frame))
     {
         APPL_TRACE_WARNING("%s() - TX queue buffer count %d",
-            __FUNCTION__, btif_media_cb.TxAaQ.count);
+            __FUNCTION__, GKI_queue_length(&btif_media_cb.TxAaQ));
         GKI_freebuf(GKI_dequeue(&(btif_media_cb.TxAaQ)));
     }
 
-    if (btif_media_cb.TxAaQ.count) --nb_frame;
+    if (GKI_queue_length(&btif_media_cb.TxAaQ)) --nb_frame;
 
     switch (btif_media_cb.TxTranscoding)
     {
@@ -2884,7 +2601,7 @@
     }
 
     /* send it */
-    VERBOSE("btif_media_send_aa_frame : send %d frames", nb_frame_2_send);
+    LOG_VERBOSE("btif_media_send_aa_frame : send %d frames", nb_frame_2_send);
     bta_av_ci_src_data_ready(BTA_AV_CHNL_AUDIO);
 }
 
diff --git a/btif/src/btif_pan.c b/btif/src/btif_pan.c
index 5a0a0ce..25f27eb 100644
--- a/btif/src/btif_pan.c
+++ b/btif/src/btif_pan.c
@@ -46,11 +46,12 @@
 #include <linux/if_tun.h>
 #include <linux/if_ether.h>
 
-#define LOG_TAG "BTIF_PAN"
+#define LOG_TAG "bt_btif_pan"
 #include "btif_common.h"
 #include "btif_util.h"
 #include "btm_api.h"
-#include "bd.h"
+#include "btcore/include/bdaddr.h"
+#include "device/include/controller.h"
 
 #include "bta_api.h"
 #include "bta_pan_api.h"
@@ -58,6 +59,8 @@
 #include "btif_sock_util.h"
 #include "btif_pan_internal.h"
 #include "gki.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
 
 #define FORWARD_IGNORE        1
 #define FORWARD_SUCCESS       0
@@ -81,7 +84,6 @@
 
 btpan_cb_t btpan_cb;
 
-BD_ADDR local_addr;
 static int jni_initialized, stack_initialized;
 static bt_status_t btpan_jni_init(const btpan_callbacks_t* callbacks);
 static void btpan_jni_cleanup();
@@ -304,7 +306,7 @@
     }
 }
 
-static int tap_if_up(const char *devname, BD_ADDR addr)
+static int tap_if_up(const char *devname, const bt_bdaddr_t *addr)
 {
     struct ifreq ifr;
     int sk, err;
@@ -321,14 +323,9 @@
         close(sk);
         return -1;
     }
-    /* debug("found mac address for interface:%s = %02x:%02x:%02x:%02x:%02x:%02x", devname, */
-    /*         ifr.ifr_hwaddr.sa_data[0], ifr.ifr_hwaddr.sa_data[1], ifr.ifr_hwaddr.sa_data[2], */
-    /*         ifr.ifr_hwaddr.sa_data[3], ifr.ifr_hwaddr.sa_data[4], ifr.ifr_hwaddr.sa_data[5]); */
+
     strncpy(ifr.ifr_name, devname, IFNAMSIZ - 1);
-    memcpy(ifr.ifr_hwaddr.sa_data, addr, 6);
-    /* debug("setting bt address for interface:%s = %02x:%02x:%02x:%02x:%02x:%02x", devname, */
-    /*         ifr.ifr_hwaddr.sa_data[0], ifr.ifr_hwaddr.sa_data[1], ifr.ifr_hwaddr.sa_data[2], */
-    /*         ifr.ifr_hwaddr.sa_data[3], ifr.ifr_hwaddr.sa_data[4], ifr.ifr_hwaddr.sa_data[5]); */
+    memcpy(ifr.ifr_hwaddr.sa_data, addr->address, 6);
 
     /* The IEEE has specified that the most significant bit of the most significant byte is used to
      * determine a multicast address. If its a 1, that means multicast, 0 means unicast.
@@ -371,7 +368,7 @@
 static int tap_if_down(const char *devname)
 {
     struct ifreq ifr;
-    int sk, err;
+    int sk;
 
     sk = socket(AF_INET, SOCK_DGRAM, 0);
 
@@ -380,7 +377,7 @@
 
     ifr.ifr_flags &= ~IFF_UP;
 
-    err = ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr);
+    ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr);
 
     close(sk);
 
@@ -406,7 +403,6 @@
 
     /* open the clone device */
 
-    //system("insmod /system/lib/modules/tun.ko");
     if( (fd = open(clonedev, O_RDWR)) < 0 ) {
 
         BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno);
@@ -419,14 +415,13 @@
     strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ);
 
     /* try to create the device */
-    if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 )//|| tap_setup_ip(TAP_IF_NAME) == FALSE)
+    if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 )
     {
         BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno));
         close(fd);
         return err;
     }
-    BTM_GetLocalDeviceAddr (local_addr);
-    if(tap_if_up(TAP_IF_NAME, local_addr) == 0)
+    if(tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0)
     {
         int flags = fcntl(fd, F_GETFL, 0);
         fcntl(fd, F_SETFL, flags | O_NONBLOCK);
@@ -445,9 +440,6 @@
     if(tap_fd != -1)
     {
         tETH_HDR eth_hdr;
-        //if(is_empty_eth_addr(dst))
-        //    memcpy(&eth_hdr.h_dest, local_addr, ETH_ADDR_LEN);
-        //else
         memcpy(&eth_hdr.h_dest, dst, ETH_ADDR_LEN);
         memcpy(&eth_hdr.h_src, src, ETH_ADDR_LEN);
         eth_hdr.h_proto = htons(proto);
@@ -455,14 +447,12 @@
         memcpy(packet, &eth_hdr, sizeof(tETH_HDR));
         if(len > 2000)
         {
-            ALOGE("btpan_tap_send eth packet size:%d is exceeded limit!", len);
+            LOG_ERROR("btpan_tap_send eth packet size:%d is exceeded limit!", len);
             return -1;
         }
         memcpy(packet + sizeof(tETH_HDR), buf, len);
 
         /* Send data to network interface */
-        //btnet_send(btpan_cb.conn[i].sock.sock, &buffer, (len + sizeof(tETH_HDR)));
-        //dump_bin("packet to network", packet, len + sizeof(tETH_HDR));
         int ret = write(tap_fd, packet, len + sizeof(tETH_HDR));
         BTIF_TRACE_DEBUG("ret:%d", ret);
         return ret;
@@ -594,7 +584,7 @@
             {
                 btpan_conn_t* conn;
                 bdstr_t bds;
-                bd2str((bt_bdaddr_t*)p_data->opening.bd_addr, &bds);
+                bdaddr_to_string((bt_bdaddr_t *)p_data->opening.bd_addr, bds, sizeof(bds));
                 BTIF_TRACE_DEBUG("BTA_PAN_OPENING_EVT handle %d, addr: %s", p_data->opening.handle, bds);
                 conn = btpan_find_conn_addr(p_data->opening.bd_addr);
 
@@ -613,15 +603,11 @@
             }
         case BTA_PAN_OPEN_EVT:
             {
-                /* debug("BTA_PAN_OPEN_EVT, open status:%d, bd_addr = [%02X:%02X:%02X:%02X:%02X:%02X]", */
-                /*         p_data->open.status, */
-                /*         p_data->open.bd_addr[0], p_data->open.bd_addr[1], p_data->open.bd_addr[2], */
-                /*         p_data->open.bd_addr[3], p_data->open.bd_addr[4], p_data->open.bd_addr[5]); */
                 btpan_connection_state_t state;
                 bt_status_t status;
                 btpan_conn_t *conn = btpan_find_conn_handle(p_data->open.handle);
 
-                ALOGV("%s pan connection open status: %d", __func__, p_data->open.status);
+                LOG_VERBOSE("%s pan connection open status: %d", __func__, p_data->open.status);
                 if(p_data->open.status == BTA_PAN_SUCCESS)
                 {
                     state = BTPAN_STATE_CONNECTED;
@@ -636,7 +622,6 @@
                 /* debug("BTA_PAN_OPEN_EVT handle:%d, conn:%p",  p_data->open.handle, conn); */
                 /* debug("conn bta local_role:%d, bta remote role:%d", conn->local_role, conn->remote_role); */
                 int btpan_conn_local_role = bta_role_to_btpan(p_data->open.local_role);
-                /* debug("bta local_role:%d, bta remote role:%d", p_data->open.local_role, p_data->open.peer_role); */
                 int btpan_remote_role = bta_role_to_btpan(p_data->open.peer_role);
                 callback.connection_state_cb(state, status, (const bt_bdaddr_t*)p_data->open.bd_addr,
                         btpan_conn_local_role, btpan_remote_role);
@@ -646,11 +631,10 @@
             {
                 btpan_conn_t* conn = btpan_find_conn_handle(p_data->close.handle);
 
-                ALOGI("%s: event = BTA_PAN_CLOSE_EVT handle %d", __FUNCTION__, p_data->close.handle);
+                LOG_INFO("%s: event = BTA_PAN_CLOSE_EVT handle %d", __FUNCTION__, p_data->close.handle);
 
                 if(conn && conn->handle >= 0)
                 {
-                    /* debug("BTA_PAN_CLOSE_EVT, conn local_role:%d, remote_role:%d", conn->local_role, conn->remote_role); */
                     int btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
                     int btpan_remote_role = bta_role_to_btpan(conn->remote_role);
                     callback.connection_state_cb(BTPAN_STATE_DISCONNECTED, 0, (const bt_bdaddr_t*)conn->peer,
@@ -760,10 +744,13 @@
 }
 
 static void btpan_tap_fd_signaled(int fd, int type, int flags, uint32_t user_id) {
-    assert(btpan_cb.tap_fd == fd);
+    assert(btpan_cb.tap_fd == INVALID_FD || btpan_cb.tap_fd == fd);
 
-    if (btpan_cb.tap_fd != fd)
+    if (btpan_cb.tap_fd != fd) {
+        BTIF_TRACE_WARNING("%s Signaled on mismatched fds exp:%d act:%d\n",
+                __func__, btpan_cb.tap_fd, fd);
         return;
+    }
 
     if(flags & SOCK_THREAD_FD_EXCEPTION) {
         btpan_cb.tap_fd = -1;
diff --git a/btif/src/btif_profile_queue.c b/btif/src/btif_profile_queue.c
index 28d0d28..5693860 100644
--- a/btif/src/btif_profile_queue.c
+++ b/btif/src/btif_profile_queue.c
@@ -24,14 +24,17 @@
  *
  ******************************************************************************/
 
+#include <assert.h>
 #include <hardware/bluetooth.h>
 #include <string.h>
 
-#define LOG_TAG "BTIF_QUEUE"
+#define LOG_TAG "bt_btif_queue"
 #include "btif_common.h"
 #include "btif_profile_queue.h"
 #include "gki.h"
-#include "list.h"
+#include "osi/include/list.h"
+#include "osi/include/allocator.h"
+#include "stack_manager.h"
 
 /*******************************************************************************
 **  Local type definitions
@@ -55,21 +58,31 @@
 
 static list_t *connect_queue;
 
+static const size_t MAX_REASONABLE_REQUESTS = 10;
+
 /*******************************************************************************
 **  Queue helper functions
 *******************************************************************************/
 
 static void queue_int_add(connect_node_t *p_param) {
-    connect_node_t *p_node = GKI_getbuf(sizeof(connect_node_t));
-    ASSERTC(p_node != NULL, "Failed to allocate new list node", 0);
-
-    memcpy(p_node, p_param, sizeof(connect_node_t));
-
     if (!connect_queue) {
-        connect_queue = list_new(GKI_freebuf);
-        ASSERTC(connect_queue != NULL, "Failed to allocate list", 0);
+        connect_queue = list_new(osi_free);
+        assert(connect_queue != NULL);
     }
 
+    // Sanity check to make sure we're not leaking connection requests
+    assert(list_length(connect_queue) < MAX_REASONABLE_REQUESTS);
+
+    for (const list_node_t *node = list_begin(connect_queue); node != list_end(connect_queue); node = list_next(node)) {
+        if (((connect_node_t *)list_node(node))->uuid == p_param->uuid) {
+            LOG_INFO("%s dropping duplicate connect request for uuid: %04x", __func__, p_param->uuid);
+            return;
+        }
+    }
+
+    connect_node_t *p_node = osi_malloc(sizeof(connect_node_t));
+    assert(p_node != NULL);
+    memcpy(p_node, p_param, sizeof(connect_node_t));
     list_append(connect_queue, p_node);
 }
 
@@ -78,21 +91,6 @@
         list_remove(connect_queue, list_front(connect_queue));
 }
 
-static bt_status_t queue_int_connect_next() {
-    if (!connect_queue || list_is_empty(connect_queue))
-        return BT_STATUS_FAIL;
-
-    connect_node_t *p_head = list_front(connect_queue);
-
-    // If the queue is currently busy, we return success anyway,
-    // since the connection has been queued...
-    if (p_head->busy)
-        return BT_STATUS_SUCCESS;
-
-    p_head->busy = true;
-    return p_head->connect_cb(&p_head->bda, p_head->uuid);
-}
-
 static void queue_int_handle_evt(UINT16 event, char *p_param) {
     switch(event) {
         case BTIF_QUEUE_CONNECT_EVT:
@@ -104,7 +102,8 @@
             break;
     }
 
-    queue_int_connect_next();
+    if (stack_manager_get_interface()->get_stack_is_running())
+        btif_queue_connect_next();
 }
 
 /*******************************************************************************
@@ -143,6 +142,24 @@
                           NULL, 0, NULL);
 }
 
+// This function dispatches the next pending connect request. It is called from
+// stack_manager when the stack comes up.
+bt_status_t btif_queue_connect_next(void) {
+    if (!connect_queue || list_is_empty(connect_queue))
+        return BT_STATUS_FAIL;
+
+    connect_node_t *p_head = list_front(connect_queue);
+
+    // If the queue is currently busy, we return success anyway,
+    // since the connection has been queued...
+    if (p_head->busy)
+        return BT_STATUS_SUCCESS;
+
+    p_head->busy = true;
+    return p_head->connect_cb(&p_head->bda, p_head->uuid);
+}
+
+
 /*******************************************************************************
 **
 ** Function         btif_queue_release
diff --git a/btif/src/btif_rc.c b/btif/src/btif_rc.c
index 13cc37b..1c26dff 100644
--- a/btif/src/btif_rc.c
+++ b/btif/src/btif_rc.c
@@ -30,10 +30,9 @@
 #include "bta_api.h"
 #include "bta_av_api.h"
 #include "avrc_defs.h"
-#include "bd.h"
 #include "gki.h"
 
-#define LOG_TAG "BTIF_RC"
+#define LOG_TAG "bt_btif_avrc"
 #include "btif_common.h"
 #include "btif_util.h"
 #include "btif_av.h"
@@ -668,7 +667,6 @@
     UINT8             scratch_buf[512] = {0};
     tAVRC_COMMAND    avrc_command = {0};
     tAVRC_STS status;
-    int param_len;
 
     BTIF_TRACE_EVENT("+ %s", __FUNCTION__);
 
@@ -728,7 +726,6 @@
         if (avrc_command.cmd.pdu == AVRC_PDU_REGISTER_NOTIFICATION)
         {
             UINT8 event_id = avrc_command.reg_notif.event_id;
-            param_len = sizeof(tAVRC_REG_NOTIF_CMD);
             BTIF_TRACE_EVENT("%s:New register notification received.event_id:%s,label:0x%x,code:%x",
             __FUNCTION__,dump_rc_notification_event_id(event_id), pmeta_msg->label,pmeta_msg->code);
             btif_rc_cb.rc_notif[event_id-1].bNotify = TRUE;
diff --git a/btif/src/btif_sm.c b/btif/src/btif_sm.c
index e3ccbf8..61409ae 100644
--- a/btif/src/btif_sm.c
+++ b/btif/src/btif_sm.c
@@ -24,9 +24,12 @@
  *  Description:   Generic BTIF state machine API
  *
  *****************************************************************************/
+
+#define LOG_TAG "bt_btif"
+
 #include <hardware/bluetooth.h>
 
-#define LOG_TAG "BTIF_SM"
+#include "osi/include/allocator.h"
 #include "btif_common.h"
 #include "btif_sm.h"
 #include "gki.h"
@@ -83,7 +86,7 @@
         return NULL;
     }
 
-    p_cb = (btif_sm_cb_t*) GKI_os_malloc(sizeof(btif_sm_cb_t));
+    p_cb = (btif_sm_cb_t *)osi_malloc(sizeof(btif_sm_cb_t));
     p_cb->state = initial_state;
     p_cb->p_handlers = (btif_sm_handler_t*)p_handlers;
 
@@ -111,7 +114,7 @@
         BTIF_TRACE_ERROR("%s : Invalid handle", __FUNCTION__);
         return;
     }
-    GKI_os_free((void*)p_cb);
+    osi_free(p_cb);
 }
 
 /*****************************************************************************
diff --git a/btif/src/btif_sock.c b/btif/src/btif_sock.c
index 4136cda..831ae73 100644
--- a/btif/src/btif_sock.c
+++ b/btif/src/btif_sock.c
@@ -1,6 +1,6 @@
 /******************************************************************************
  *
- *  Copyright (C) 2009-2012 Broadcom Corporation
+ *  Copyright (C) 2014 Google, Inc.
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
@@ -16,158 +16,153 @@
  *
  ******************************************************************************/
 
+#define LOG_TAG "bt_btif_sock"
 
-/************************************************************************************
- *
- *  Filename:      btif_sock.c
- *
- *  Description:   Bluetooth Socket Interface
- *
- *
- ***********************************************************************************/
-
+#include <assert.h>
 #include <hardware/bluetooth.h>
 #include <hardware/bt_sock.h>
 
-#define LOG_TAG "BTIF_SOCK"
-#include "btif_common.h"
-#include "btif_util.h"
-
-#include "bd.h"
-
 #include "bta_api.h"
-#include "btif_sock_thread.h"
+#include "btif_common.h"
 #include "btif_sock_rfc.h"
+#include "btif_sock_sco.h"
+#include "btif_sock_thread.h"
+#include "btif_util.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/thread.h"
 
-static bt_status_t btsock_listen(btsock_type_t type, const char* service_name,
-                                const uint8_t* uuid, int channel, int* sock_fd, int flags);
-static bt_status_t btsock_connect(const bt_bdaddr_t *bd_addr, btsock_type_t type,
-                                  const uint8_t* uuid, int channel, int* sock_fd, int flags);
+static bt_status_t btsock_listen(btsock_type_t type, const char *service_name, const uint8_t *uuid, int channel, int *sock_fd, int flags);
+static bt_status_t btsock_connect(const bt_bdaddr_t *bd_addr, btsock_type_t type, const uint8_t *uuid, int channel, int *sock_fd, int flags);
 
 static void btsock_signaled(int fd, int type, int flags, uint32_t user_id);
 
-/*******************************************************************************
-**
-** Function         btsock_ini
-**
-** Description     initializes the bt socket interface
-**
-** Returns         bt_status_t
-**
-*******************************************************************************/
-static btsock_interface_t sock_if = {
-                sizeof(sock_if),
-                btsock_listen,
-                btsock_connect
-       };
-btsock_interface_t *btif_sock_get_interface()
-{
-    return &sock_if;
+static int thread_handle = -1;
+static thread_t *thread;
+
+btsock_interface_t *btif_sock_get_interface(void) {
+  static btsock_interface_t interface = {
+    sizeof(interface),
+    btsock_listen,
+    btsock_connect
+  };
+
+  return &interface;
 }
-bt_status_t btif_sock_init()
-{
-    static volatile int binit;
-    if(!binit)
-    {
-        //fix me, the process doesn't exit right now. don't set the init flag for now
-        //binit = 1;
-        BTIF_TRACE_DEBUG("btsock initializing...");
-        btsock_thread_init();
-        int handle = btsock_thread_create(btsock_signaled, NULL);
-        if(handle >= 0 && btsock_rfc_init(handle) == BT_STATUS_SUCCESS)
-        {
-            BTIF_TRACE_DEBUG("btsock successfully initialized");
-            return BT_STATUS_SUCCESS;
-        }
-    }
-    else BTIF_TRACE_ERROR("btsock interface already initialized");
-    return BT_STATUS_FAIL;
-}
-void btif_sock_cleanup()
-{
+
+bt_status_t btif_sock_init(void) {
+  assert(thread_handle == -1);
+  assert(thread == NULL);
+
+  btsock_thread_init();
+  thread_handle = btsock_thread_create(btsock_signaled, NULL);
+  if (thread_handle == -1) {
+    LOG_ERROR("%s unable to create btsock_thread.", __func__);
+    goto error;
+  }
+
+  bt_status_t status = btsock_rfc_init(thread_handle);
+  if (status != BT_STATUS_SUCCESS) {
+    LOG_ERROR("%s error initializing RFCOMM sockets: %d", __func__, status);
+    goto error;
+  }
+
+  thread = thread_new("btif_sock");
+  if (!thread) {
+    LOG_ERROR("%s error creating new thread.", __func__);
     btsock_rfc_cleanup();
-    BTIF_TRACE_DEBUG("leaving");
+    goto error;
+  }
+
+  status = btsock_sco_init(thread);
+  if (status != BT_STATUS_SUCCESS) {
+    LOG_ERROR("%s error initializing SCO sockets: %d", __func__, status);
+    btsock_rfc_cleanup();
+    goto error;
+  }
+
+  return BT_STATUS_SUCCESS;
+
+error:;
+  thread_free(thread);
+  thread = NULL;
+  if (thread_handle != -1)
+    btsock_thread_exit(thread_handle);
+  thread_handle = -1;
+  return BT_STATUS_FAIL;
 }
 
-static bt_status_t btsock_listen(btsock_type_t type, const char* service_name,
-        const uint8_t* service_uuid, int channel, int* sock_fd, int flags)
-{
-    if((service_uuid == NULL && channel <= 0) || sock_fd == NULL)
-    {
-        BTIF_TRACE_ERROR("invalid parameters, uuid:%p, channel:%d, sock_fd:%p", service_uuid, channel, sock_fd);
-        return BT_STATUS_PARM_INVALID;
-    }
-    *sock_fd = -1;
-    bt_status_t status = BT_STATUS_FAIL;
-    switch(type)
-    {
-        case BTSOCK_RFCOMM:
-            status = btsock_rfc_listen(service_name, service_uuid, channel, sock_fd, flags);
-            break;
-        case BTSOCK_L2CAP:
-            BTIF_TRACE_ERROR("bt l2cap socket type not supported, type:%d", type);
-            status = BT_STATUS_UNSUPPORTED;
-            break;
-        case BTSOCK_SCO:
-            BTIF_TRACE_ERROR("bt sco socket not supported, type:%d", type);
-            status = BT_STATUS_UNSUPPORTED;
-            break;
-        default:
-            BTIF_TRACE_ERROR("unknown bt socket type:%d", type);
-            status = BT_STATUS_UNSUPPORTED;
-            break;
-    }
-    return status;
-}
-static bt_status_t btsock_connect(const bt_bdaddr_t *bd_addr, btsock_type_t type,
-        const uint8_t* uuid, int channel, int* sock_fd, int flags)
-{
-    if((uuid == NULL && channel <= 0) || bd_addr == NULL || sock_fd == NULL)
-    {
-        BTIF_TRACE_ERROR("invalid parameters, bd_addr:%p, uuid:%p, channel:%d, sock_fd:%p",
-                bd_addr, uuid, channel, sock_fd);
-        return BT_STATUS_PARM_INVALID;
-    }
-    *sock_fd = -1;
-    bt_status_t status = BT_STATUS_FAIL;
-    switch(type)
-    {
-        case BTSOCK_RFCOMM:
-            status = btsock_rfc_connect(bd_addr, uuid, channel, sock_fd, flags);
-            break;
-        case BTSOCK_L2CAP:
-            BTIF_TRACE_ERROR("bt l2cap socket type not supported, type:%d", type);
-            status = BT_STATUS_UNSUPPORTED;
-            break;
-        case BTSOCK_SCO:
-            BTIF_TRACE_ERROR("bt sco socket not supported, type:%d", type);
-            status = BT_STATUS_UNSUPPORTED;
-            break;
-        default:
-            BTIF_TRACE_ERROR("unknown bt socket type:%d", type);
-            status = BT_STATUS_UNSUPPORTED;
-            break;
-    }
-    return status;
-}
-static void btsock_signaled(int fd, int type, int flags, uint32_t user_id)
-{
-    switch(type)
-    {
-        case BTSOCK_RFCOMM:
-            btsock_rfc_signaled(fd, flags, user_id);
-            break;
-        case BTSOCK_L2CAP:
-            BTIF_TRACE_ERROR("bt l2cap socket type not supported, fd:%d, flags:%d", fd, flags);
-            break;
-        case BTSOCK_SCO:
-            BTIF_TRACE_ERROR("bt sco socket type not supported, fd:%d, flags:%d", fd, flags);
-            break;
-        default:
-            BTIF_TRACE_ERROR("unknown socket type:%d, fd:%d, flags:%d", type, fd, flags);
-            break;
-    }
+void btif_sock_cleanup(void) {
+  if (thread_handle == -1)
+    return;
+
+  thread_stop(thread);
+  thread_join(thread);
+  btsock_thread_exit(thread_handle);
+  btsock_rfc_cleanup();
+  btsock_sco_cleanup();
+  thread_free(thread);
+  thread_handle = -1;
+  thread = NULL;
 }
 
+static bt_status_t btsock_listen(btsock_type_t type, const char *service_name, const uint8_t *service_uuid, int channel, int *sock_fd, int flags) {
+  assert(service_uuid != NULL || channel > 0);
+  assert(sock_fd != NULL);
 
+  *sock_fd = INVALID_FD;
+  bt_status_t status = BT_STATUS_FAIL;
 
+  switch (type) {
+    case BTSOCK_RFCOMM:
+      status = btsock_rfc_listen(service_name, service_uuid, channel, sock_fd, flags);
+      break;
+
+    case BTSOCK_SCO:
+      status = btsock_sco_listen(sock_fd, flags);
+      break;
+
+    default:
+      LOG_ERROR("%s unknown/unsupported socket type: %d", __func__, type);
+      status = BT_STATUS_UNSUPPORTED;
+      break;
+  }
+  return status;
+}
+
+static bt_status_t btsock_connect(const bt_bdaddr_t *bd_addr, btsock_type_t type, const uint8_t *uuid, int channel, int *sock_fd, int flags) {
+  assert(uuid != NULL || channel > 0);
+  assert(bd_addr != NULL);
+  assert(sock_fd != NULL);
+
+  *sock_fd = INVALID_FD;
+  bt_status_t status = BT_STATUS_FAIL;
+
+  switch (type) {
+    case BTSOCK_RFCOMM:
+      status = btsock_rfc_connect(bd_addr, uuid, channel, sock_fd, flags);
+      break;
+
+    case BTSOCK_SCO:
+      status = btsock_sco_connect(bd_addr, sock_fd, flags);
+      break;
+
+    default:
+      LOG_ERROR("%s unknown/unsupported socket type: %d", __func__, type);
+      status = BT_STATUS_UNSUPPORTED;
+      break;
+  }
+  return status;
+}
+
+static void btsock_signaled(int fd, int type, int flags, uint32_t user_id) {
+  switch (type) {
+    case BTSOCK_RFCOMM:
+      btsock_rfc_signaled(fd, flags, user_id);
+      break;
+
+    default:
+      assert(false && "Invalid socket type");
+      break;
+  }
+}
diff --git a/btif/src/btif_sock_rfc.c b/btif/src/btif_sock_rfc.c
index 77db92c..1cd25a3 100644
--- a/btif/src/btif_sock_rfc.c
+++ b/btif/src/btif_sock_rfc.c
@@ -16,81 +16,60 @@
  *
  ******************************************************************************/
 
-/************************************************************************************
- *
- *  Filename:      btif_sock_rfc.c
- *
- *  Description:   Handsfree Profile Bluetooth Interface
- *
- ***********************************************************************************/
+#define LOG_TAG "bt_btif_sock_rfcomm"
+
 #include <assert.h>
+#include <errno.h>
 #include <hardware/bluetooth.h>
 #include <hardware/bt_sock.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <errno.h>
 #include <sys/ioctl.h>
-
-#define LOG_TAG "BTIF_SOCK"
-#include "btif_common.h"
-#include "btif_util.h"
-
-#include "bd.h"
+#include <sys/socket.h>
+#include <sys/types.h>
 
 #include "bta_api.h"
-#include "btif_sock_thread.h"
-#include "btif_sock_sdp.h"
-#include "btif_sock_util.h"
-
 #include "bt_target.h"
-#include "gki.h"
-#include "hcimsgs.h"
-#include "sdp_api.h"
-#include "btu.h"
-#include "btm_api.h"
-#include "btm_int.h"
 #include "bta_jv_api.h"
 #include "bta_jv_co.h"
+#include "btif_common.h"
+#include "btif_sock_sdp.h"
+#include "btif_sock_thread.h"
+#include "btif_sock_util.h"
+#include "btif_util.h"
+#include "btm_api.h"
+#include "btm_int.h"
+#include "btu.h"
+#include "gki.h"
+#include "hcimsgs.h"
+#include "osi/include/list.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
 #include "port_api.h"
-#include "list.h"
+#include "sdp_api.h"
 
-#include <cutils/log.h>
-#include <hardware/bluetooth.h>
-#define asrt(s) if(!(s)) APPL_TRACE_ERROR("## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
+#define MAX_RFC_CHANNEL 30  // Maximum number of RFCOMM channels (1-30 inclusive).
+#define MAX_RFC_SESSION 7   // Maximum number of devices we can have an RFCOMM connection with.
 
-extern void uuid_to_string(bt_uuid_t *p_uuid, char *str);
-static inline void logu(const char* title, const uint8_t * p_uuid)
-{
-    char uuids[128];
-    uuid_to_string((bt_uuid_t*)p_uuid, uuids);
-    ALOGD("%s: %s", title, uuids);
-}
-
-
-
-#define MAX_RFC_CHANNEL 30
-#define MAX_RFC_SESSION BTA_JV_MAX_RFC_SR_SESSION //3 by default
 typedef struct {
-    int outgoing_congest : 1;
-    int pending_sdp_request : 1;
-    int doing_sdp_request : 1;
-    int server : 1;
-    int connected : 1;
-    int closing : 1;
+  int outgoing_congest : 1;
+  int pending_sdp_request : 1;
+  int doing_sdp_request : 1;
+  int server : 1;
+  int connected : 1;
+  int closing : 1;
 } flags_t;
 
 typedef struct {
   flags_t f;
-  uint32_t id;
+  uint32_t id;  // Non-zero indicates a valid (in-use) slot.
   int security;
-  int scn;
+  int scn;      // Server channel number
   bt_bdaddr_t addr;
   uint8_t service_uuid[16];
   char service_name[256];
-  int fd, app_fd;
+  int fd;
+  int app_fd;  // Temporary storage for the half of the socketpair that's sent back to upper layers.
   int mtu;
-  uint8_t* packet;
+  uint8_t *packet;
   int sdp_handle;
   int rfc_handle;
   int rfc_port_handle;
@@ -100,915 +79,740 @@
 
 static rfc_slot_t rfc_slots[MAX_RFC_CHANNEL];
 static uint32_t rfc_slot_id;
-static volatile int pth = -1; //poll thread handle
+static volatile int pth = -1; // poll thread handle
+static pthread_mutex_t slot_lock;
+
+static rfc_slot_t *find_free_slot(void);
+static void cleanup_rfc_slot(rfc_slot_t *rs);
 static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
-static void cleanup_rfc_slot(rfc_slot_t* rs);
 static void *rfcomm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
-static inline BOOLEAN send_app_scn(rfc_slot_t* rs);
-static pthread_mutex_t slot_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
-#define is_init_done() (pth != -1)
-static inline void clear_slot_flag(flags_t* f)
-{
-    memset(f, 0, sizeof(*f));
+static bool send_app_scn(const rfc_slot_t *rs);
+
+static bool is_init_done(void) {
+  return pth != -1;
 }
 
-static inline void bd_copy(UINT8* dest, UINT8* src, BOOLEAN swap)
-{
-    if (swap)
-    {
-        int i;
-        for (i =0; i < 6 ;i++)
-            dest[i]= src[5-i];
-    }
-    else memcpy(dest, src, 6);
+bt_status_t btsock_rfc_init(int poll_thread_handle) {
+  pth = poll_thread_handle;
+
+  memset(rfc_slots, 0, sizeof(rfc_slots));
+  for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
+    rfc_slots[i].scn = -1;
+    rfc_slots[i].sdp_handle = 0;
+    rfc_slots[i].fd = INVALID_FD;
+    rfc_slots[i].app_fd = INVALID_FD;
+    rfc_slots[i].incoming_queue = list_new(GKI_freebuf);
+    assert(rfc_slots[i].incoming_queue != NULL);
+  }
+
+  BTA_JvEnable(jv_dm_cback);
+  init_slot_lock(&slot_lock);
+
+  return BT_STATUS_SUCCESS;
 }
-static void init_rfc_slots()
-{
-    int i;
-    memset(rfc_slots, 0, sizeof(rfc_slot_t)*MAX_RFC_CHANNEL);
-    for(i = 0; i < MAX_RFC_CHANNEL; i++)
-    {
-        rfc_slots[i].scn = -1;
-        rfc_slots[i].sdp_handle = 0;
-        rfc_slots[i].fd = rfc_slots[i].app_fd = -1;
-        rfc_slots[i].incoming_queue = list_new(GKI_freebuf);
-        assert(rfc_slots[i].incoming_queue != NULL);
-    }
-    BTA_JvEnable(jv_dm_cback);
+
+void btsock_rfc_cleanup(void) {
+  pth = -1;
+
+  lock_slot(&slot_lock);
+  for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
+    if (rfc_slots[i].id)
+      cleanup_rfc_slot(&rfc_slots[i]);
+    list_free(rfc_slots[i].incoming_queue);
+  }
+  unlock_slot(&slot_lock);
 }
-bt_status_t btsock_rfc_init(int poll_thread_handle)
-{
-    pth = poll_thread_handle;
-    init_rfc_slots();
-    return BT_STATUS_SUCCESS;
+
+static rfc_slot_t *find_free_slot(void) {
+  for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
+    if (rfc_slots[i].fd == INVALID_FD)
+      return &rfc_slots[i];
+  return NULL;
 }
-void btsock_rfc_cleanup()
-{
-    int curr_pth = pth;
-    pth = -1;
-    btsock_thread_exit(curr_pth);
-    pthread_mutex_lock(&slot_lock);
-    int i;
-    for(i = 0; i < MAX_RFC_CHANNEL; i++)
-    {
-        if(rfc_slots[i].id) {
-            cleanup_rfc_slot(&rfc_slots[i]);
-            list_free(rfc_slots[i].incoming_queue);
-        }
-    }
-    pthread_mutex_unlock(&slot_lock);
+
+static rfc_slot_t *find_rfc_slot_by_id(uint32_t id) {
+  assert(id != 0);
+
+  for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
+    if (rfc_slots[i].id == id)
+      return &rfc_slots[i];
+
+  LOG_ERROR("%s unable to find RFCOMM slot id: %d", __func__, id);
+  return NULL;
 }
-static inline rfc_slot_t* find_free_slot()
-{
-    int i;
-    for(i = 0; i < MAX_RFC_CHANNEL; i++)
-    {
-        if(rfc_slots[i].fd == -1)
-        {
-             return &rfc_slots[i];
-        }
+
+static rfc_slot_t *find_rfc_slot_by_pending_sdp(void) {
+  uint32_t min_id = UINT32_MAX;
+  int slot = -1;
+  for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
+    if (rfc_slots[i].id && rfc_slots[i].f.pending_sdp_request && rfc_slots[i].id < min_id) {
+      min_id = rfc_slots[i].id;
+      slot = i;
     }
+
+  return (slot == -1) ? NULL : &rfc_slots[slot];
+}
+
+static bool is_requesting_sdp(void) {
+  for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
+    if (rfc_slots[i].id && rfc_slots[i].f.doing_sdp_request)
+      return true;
+  return false;
+}
+
+static rfc_slot_t *alloc_rfc_slot(const bt_bdaddr_t *addr, const char *name, const uint8_t *uuid, int channel, int flags, bool server) {
+  int security = 0;
+  if(flags & BTSOCK_FLAG_ENCRYPT)
+      security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
+  if(flags & BTSOCK_FLAG_AUTH)
+      security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
+
+  rfc_slot_t *slot = find_free_slot();
+  if (!slot) {
+    LOG_ERROR("%s unable to find free RFCOMM slot.", __func__);
     return NULL;
-}
-static inline rfc_slot_t* find_rfc_slot_by_id(uint32_t id)
-{
-    int i;
-    if(id)
-    {
-        for(i = 0; i < MAX_RFC_CHANNEL; i++)
-        {
-            if(rfc_slots[i].id == id)
-            {
-                return &rfc_slots[i];
-            }
-        }
-    }
-    APPL_TRACE_WARNING("invalid rfc slot id: %d", id);
+  }
+
+  int fds[2] = { INVALID_FD, INVALID_FD };
+  if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds) == -1) {
+    LOG_ERROR("%s error creating socketpair: %s", __func__, strerror(errno));
     return NULL;
+  }
+
+  // Increment slot id and make sure we don't use id=0.
+  if (++rfc_slot_id == 0)
+    rfc_slot_id = 1;
+
+  slot->fd = fds[0];
+  slot->app_fd = fds[1];
+  slot->security = security;
+  slot->scn = channel;
+
+  if (uuid)
+    memcpy(slot->service_uuid, uuid, sizeof(slot->service_uuid));
+  else
+    memset(&slot->service_uuid, 0, sizeof(slot->service_uuid));
+
+  if (name)
+    strlcpy(slot->service_name, name, sizeof(slot->service_name));
+
+  if (addr)
+    slot->addr = *addr;
+
+  slot->id = rfc_slot_id;
+  slot->f.server = server;
+
+  return slot;
 }
-static inline rfc_slot_t* find_rfc_slot_by_pending_sdp()
-{
-    uint32_t min_id = (uint32_t)-1;
-    int slot = -1;
-    int i;
-    for(i = 0; i < MAX_RFC_CHANNEL; i++)
-    {
-        if(rfc_slots[i].id && rfc_slots[i].f.pending_sdp_request)
-        {
-            if(rfc_slots[i].id < min_id)
-            {
-                min_id = rfc_slots[i].id;
-                slot = i;
-            }
-        }
-    }
-    if(0<= slot && slot < MAX_RFC_CHANNEL)
-        return &rfc_slots[slot];
+
+static rfc_slot_t *create_srv_accept_rfc_slot(rfc_slot_t *srv_rs, const bt_bdaddr_t *addr, int open_handle, int new_listen_handle) {
+  rfc_slot_t *accept_rs = alloc_rfc_slot(addr, srv_rs->service_name, srv_rs->service_uuid, srv_rs->scn, 0, false);
+  if (!accept_rs) {
+    LOG_ERROR("%s unable to allocate RFCOMM slot.", __func__);
     return NULL;
-}
-static inline rfc_slot_t* find_rfc_slot_requesting_sdp()
-{
-    int i;
-    for(i = 0; i < MAX_RFC_CHANNEL; i++)
-    {
-        if(rfc_slots[i].id && rfc_slots[i].f.doing_sdp_request)
-                return &rfc_slots[i];
-    }
-    APPL_TRACE_DEBUG("can not find any slot is requesting sdp");
-    return NULL;
+  }
+
+  accept_rs->f.server = false;
+  accept_rs->f.connected = true;
+  accept_rs->security = srv_rs->security;
+  accept_rs->mtu = srv_rs->mtu;
+  accept_rs->role = srv_rs->role;
+  accept_rs->rfc_handle = open_handle;
+  accept_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(open_handle);
+
+  srv_rs->rfc_handle = new_listen_handle;
+  srv_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(new_listen_handle);
+
+  assert(accept_rs->rfc_port_handle != srv_rs->rfc_port_handle);
+
+  // now swap the slot id
+  uint32_t new_listen_id = accept_rs->id;
+  accept_rs->id = srv_rs->id;
+  srv_rs->id = new_listen_id;
+
+  return accept_rs;
 }
 
-static rfc_slot_t* alloc_rfc_slot(const bt_bdaddr_t *addr, const char* name, const uint8_t* uuid, int channel, int flags, BOOLEAN server)
-{
-    int security = 0;
-    if(flags & BTSOCK_FLAG_ENCRYPT)
-        security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
-    if(flags & BTSOCK_FLAG_AUTH)
-        security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
+bt_status_t btsock_rfc_listen(const char *service_name, const uint8_t *service_uuid, int channel, int *sock_fd, int flags) {
+  assert(sock_fd != NULL);
+  assert(service_uuid != NULL || (channel >= 1 && channel <= MAX_RFC_CHANNEL));
 
-    rfc_slot_t* rs = find_free_slot();
-    if(rs)
-    {
-        int fds[2] = {-1, -1};
-        if(socketpair(AF_LOCAL, SOCK_STREAM, 0, fds))
-        {
-            APPL_TRACE_ERROR("socketpair failed, errno:%d", errno);
-            return NULL;
-        }
-        rs->fd = fds[0];
-        rs->app_fd = fds[1];
-        rs->security = security;
-        rs->scn = channel;
-        if(uuid)
-            memcpy(rs->service_uuid, uuid, sizeof(rs->service_uuid));
-        else memset(rs->service_uuid, 0, sizeof(rs->service_uuid));
-        if(name && *name)
-            strncpy(rs->service_name, name, sizeof(rs->service_name) -1);
-        if(addr)
-            rs->addr = *addr;
-        ++rfc_slot_id;
-        if(rfc_slot_id == 0)
-            rfc_slot_id = 1; //skip 0 when wrapped
-        rs->id = rfc_slot_id;
-        rs->f.server = server;
-    }
-    return rs;
-}
-// rfc_slot_t* accept_rs = create_srv_accept_rfc_slot(srv_rs, p_open->rem_bda,p_opne->handle,  p_open->new_listen_handle);
-static inline rfc_slot_t* create_srv_accept_rfc_slot(rfc_slot_t* srv_rs, const bt_bdaddr_t* addr,
-                                        int open_handle, int new_listen_handle)
-{
-    rfc_slot_t *accept_rs = alloc_rfc_slot(addr, srv_rs->service_name, srv_rs->service_uuid, srv_rs->scn, 0, FALSE);
-    if( accept_rs)
-    {
-        clear_slot_flag(&accept_rs->f);
-        accept_rs->f.server = FALSE;
-        accept_rs->f.connected = TRUE;
-        accept_rs->security = srv_rs->security;
-        accept_rs->mtu = srv_rs->mtu;
-        accept_rs->role = srv_rs->role;
-        accept_rs->rfc_handle = open_handle;
-        accept_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(open_handle);
-        //now update listen rfc_handle of server slot
-        srv_rs->rfc_handle = new_listen_handle;
-        srv_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(new_listen_handle);
-        BTIF_TRACE_DEBUG("create_srv_accept__rfc_slot(open_handle: 0x%x, new_listen_handle:"
-                "0x%x) accept_rs->rfc_handle:0x%x, srv_rs_listen->rfc_handle:0x%x"
-                ,open_handle, new_listen_handle, accept_rs->rfc_port_handle, srv_rs->rfc_port_handle);
-        asrt(accept_rs->rfc_port_handle != srv_rs->rfc_port_handle);
-        //now swap the slot id
-        uint32_t new_listen_id = accept_rs->id;
-        accept_rs->id = srv_rs->id;
-        srv_rs->id = new_listen_id;
+  *sock_fd = INVALID_FD;
 
-        return accept_rs;
-    }
-    else
-    {
-        APPL_TRACE_ERROR(" accept_rs is NULL %s", __FUNCTION__);
-        return NULL;
-    }
-}
-bt_status_t btsock_rfc_listen(const char* service_name, const uint8_t* service_uuid, int channel,
-                            int* sock_fd, int flags)
-{
+  // TODO(sharvil): not sure that this check makes sense; seems like a logic error to call
+  // functions on RFCOMM sockets before initializing the module. Probably should be an assert.
+  if (!is_init_done())
+    return BT_STATUS_NOT_READY;
 
-    APPL_TRACE_DEBUG("btsock_rfc_listen, service_name:%s", service_name);
-    if(sock_fd == NULL || (service_uuid == NULL && (channel < 1 || channel > 30)))
-    {
-        APPL_TRACE_ERROR("invalid rfc channel:%d or sock_fd:%p, uuid:%p", channel, sock_fd, service_uuid);
-        return BT_STATUS_PARM_INVALID;
-    }
-    *sock_fd = -1;
-    if(!is_init_done())
-        return BT_STATUS_NOT_READY;
-    if(is_uuid_empty(service_uuid))
-        service_uuid = UUID_SPP; //use serial port profile to listen to specified channel
-    else
-    {
-        //Check the service_uuid. overwrite the channel # if reserved
-        int reserved_channel = get_reserved_rfc_channel(service_uuid);
-        if(reserved_channel > 0)
-        {
-            channel = reserved_channel;
-        }
-    }
-    int status = BT_STATUS_FAIL;
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = alloc_rfc_slot(NULL, service_name, service_uuid, channel, flags, TRUE);
-    if(rs)
-    {
-        APPL_TRACE_DEBUG("BTA_JvCreateRecordByUser:%s", service_name);
-        BTA_JvCreateRecordByUser((void *)(intptr_t)rs->id);
-        *sock_fd = rs->app_fd;
-        rs->app_fd = -1; //the fd ownership is transferred to app
-        if (btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, rs->id)) {
-            status = BT_STATUS_SUCCESS;
-        }
-        else
-        {
-            cleanup_rfc_slot(rs);
-        }
-    }
-    pthread_mutex_unlock(&slot_lock);
-    return status;
-}
-bt_status_t btsock_rfc_connect(const bt_bdaddr_t *bd_addr, const uint8_t* service_uuid,
-        int channel, int* sock_fd, int flags)
-{
-    if(sock_fd == NULL || (service_uuid == NULL && (channel < 1 || channel > 30)))
-    {
-        APPL_TRACE_ERROR("invalid rfc channel:%d or sock_fd:%p, uuid:%p", channel, sock_fd,
-                          service_uuid);
-        return BT_STATUS_PARM_INVALID;
-    }
-    *sock_fd = -1;
-    if(!is_init_done())
-        return BT_STATUS_NOT_READY;
-    int status = BT_STATUS_FAIL;
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = alloc_rfc_slot(bd_addr, NULL, service_uuid, channel, flags, FALSE);
-    if(rs)
-    {
-        if(is_uuid_empty(service_uuid))
-        {
-            APPL_TRACE_DEBUG("connecting to rfcomm channel:%d without service discovery", channel);
-            if(BTA_JvRfcommConnect(rs->security, rs->role, rs->scn, rs->addr.address,
-                        rfcomm_cback, (void*)(intptr_t)rs->id) == BTA_JV_SUCCESS)
-            {
-                if(send_app_scn(rs))
-                {
-                    btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM,
-                                                        SOCK_THREAD_FD_RD, rs->id);
-                    *sock_fd = rs->app_fd;
-                    rs->app_fd = -1; //the fd ownership is transferred to app
-                    status = BT_STATUS_SUCCESS;
-                }
-                else cleanup_rfc_slot(rs);
-            }
-            else cleanup_rfc_slot(rs);
-        }
-        else
-        {
-            tSDP_UUID sdp_uuid;
-            sdp_uuid.len = 16;
-            memcpy(sdp_uuid.uu.uuid128, service_uuid, sizeof(sdp_uuid.uu.uuid128));
-            logu("service_uuid", service_uuid);
-            *sock_fd = rs->app_fd;
-            rs->app_fd = -1; //the fd ownership is transferred to app
-            status = BT_STATUS_SUCCESS;
-            rfc_slot_t* rs_doing_sdp = find_rfc_slot_requesting_sdp();
-            if(rs_doing_sdp == NULL)
-            {
-                BTA_JvStartDiscovery((UINT8*)bd_addr->address, 1, &sdp_uuid, (void*)(intptr_t)rs->id);
-                rs->f.pending_sdp_request = FALSE;
-                rs->f.doing_sdp_request = TRUE;
-            }
-            else
-            {
-                rs->f.pending_sdp_request = TRUE;
-                rs->f.doing_sdp_request = FALSE;
-            }
-            btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, rs->id);
-        }
-    }
-    pthread_mutex_unlock(&slot_lock);
-    return status;
+  if (!is_uuid_empty(service_uuid)) {
+    // Use a pre-defined channel # if the UUID is reserved.
+    int reserved_channel = get_reserved_rfc_channel(service_uuid);
+    if (reserved_channel != -1)
+      channel = reserved_channel;
+  } else {
+    service_uuid = UUID_SPP;  // Use serial port profile to listen to specified channel
+  }
+
+  int status = BT_STATUS_FAIL;
+  lock_slot(&slot_lock);
+
+  rfc_slot_t *slot = alloc_rfc_slot(NULL, service_name, service_uuid, channel, flags, true);
+  if (!slot) {
+    LOG_ERROR("%s unable to allocate RFCOMM slot.", __func__);
+    goto out;
+  }
+
+  BTA_JvCreateRecordByUser((void *)(uintptr_t)slot->id);
+  *sock_fd = slot->app_fd;    // Transfer ownership of fd to caller.
+  slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
+  btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, slot->id);
+
+  status = BT_STATUS_SUCCESS;
+
+out:;
+  unlock_slot(&slot_lock);
+  return status;
 }
 
-static int create_server_sdp_record(rfc_slot_t* rs)
-{
-    int scn = rs->scn;
-    if(rs->scn > 0)
-    {
-        if(BTM_TryAllocateSCN(rs->scn) == FALSE)
-        {
-            APPL_TRACE_ERROR("rfc channel:%d already in use", scn);
-            return FALSE;
-        }
-    }
-    else if((rs->scn = BTM_AllocateSCN()) == 0)
-    {
-        APPL_TRACE_ERROR("run out of rfc channels");
-        return FALSE;
-    }
-    if((rs->sdp_handle = add_rfc_sdp_rec(rs->service_name, rs->service_uuid, rs->scn)) <= 0)
-    {
-        return FALSE;
-    }
-    return TRUE;
-}
-const char * jv_evt[] = {
-    "BTA_JV_ENABLE_EVT",
-    "BTA_JV_SET_DISCOVER_EVT",
-    "BTA_JV_LOCAL_ADDR_EVT",
-    "BTA_JV_LOCAL_NAME_EVT",
-    "BTA_JV_REMOTE_NAME_EVT",
-    "BTA_JV_SET_ENCRYPTION_EVT",
-    "BTA_JV_GET_SCN_EVT",
-    "BTA_JV_GET_PSM_EVT",
-    "BTA_JV_DISCOVERY_COMP_EVT",
-    "BTA_JV_SERVICES_LEN_EVT",
-    "BTA_JV_SERVICE_SEL_EVT",
-    "BTA_JV_CREATE_RECORD_EVT",
-    "BTA_JV_UPDATE_RECORD_EVT",
-    "BTA_JV_ADD_ATTR_EVT",
-    "BTA_JV_DELETE_ATTR_EVT",
-    "BTA_JV_CANCEL_DISCVRY_EVT",
+bt_status_t btsock_rfc_connect(const bt_bdaddr_t *bd_addr, const uint8_t *service_uuid, int channel, int *sock_fd, int flags) {
+  assert(sock_fd != NULL);
+  assert(service_uuid != NULL || (channel >= 1 && channel <= MAX_RFC_CHANNEL));
 
-    "BTA_JV_L2CAP_OPEN_EVT",
-    "BTA_JV_L2CAP_CLOSE_EVT",
-    "BTA_JV_L2CAP_START_EVT",
-    "BTA_JV_L2CAP_CL_INIT_EVT",
-    "BTA_JV_L2CAP_DATA_IND_EVT",
-    "BTA_JV_L2CAP_CONG_EVT",
-    "BTA_JV_L2CAP_READ_EVT",
-    "BTA_JV_L2CAP_RECEIVE_EVT",
-    "BTA_JV_L2CAP_WRITE_EVT",
+  *sock_fd = INVALID_FD;
 
-    "BTA_JV_RFCOMM_OPEN_EVT",
-    "BTA_JV_RFCOMM_CLOSE_EVT",
-    "BTA_JV_RFCOMM_START_EVT",
-    "BTA_JV_RFCOMM_CL_INIT_EVT",
-    "BTA_JV_RFCOMM_DATA_IND_EVT",
-    "BTA_JV_RFCOMM_CONG_EVT",
-    "BTA_JV_RFCOMM_READ_EVT",
-    "BTA_JV_RFCOMM_WRITE_EVT",
-    "BTA_JV_RFCOMM_SRV_OPEN_EVT", //  33 /* open status of Server RFCOMM connection */
-    "BTA_JV_MAX_EVT"
-};
-static inline void free_rfc_slot_scn(rfc_slot_t* rs)
-{
-    if(rs->scn > 0)
-    {
-        if(rs->f.server && !rs->f.closing && rs->rfc_handle)
-        {
-            BTA_JvRfcommStopServer(rs->rfc_handle, (void*)(uintptr_t)rs->id);
-            rs->rfc_handle = 0;
-        }
-        if(rs->f.server)
-            BTM_FreeSCN(rs->scn);
-        rs->scn = 0;
-    }
-}
-static void cleanup_rfc_slot(rfc_slot_t* rs)
-{
-    APPL_TRACE_DEBUG("cleanup slot:%d, fd:%d, scn:%d, sdp_handle:0x%x", rs->id, rs->fd, rs->scn, rs->sdp_handle);
-    if(rs->fd != -1)
-    {
-        shutdown(rs->fd, 2);
-        close(rs->fd);
-        rs->fd = -1;
-    }
-    if(rs->app_fd != -1)
-    {
-        close(rs->app_fd);
-        rs->app_fd = -1;
-    }
-    if(rs->sdp_handle > 0)
-    {
-        del_rfc_sdp_rec(rs->sdp_handle);
-        rs->sdp_handle = 0;
-    }
-    if(rs->rfc_handle && !rs->f.closing && !rs->f.server)
-    {
-        APPL_TRACE_DEBUG("closing rfcomm connection, rfc_handle:0x%x", rs->rfc_handle);
-        BTA_JvRfcommClose(rs->rfc_handle, (void*)(uintptr_t)rs->id);
-        rs->rfc_handle = 0;
-    }
-    free_rfc_slot_scn(rs);
-    list_clear(rs->incoming_queue);
+  // TODO(sharvil): not sure that this check makes sense; seems like a logic error to call
+  // functions on RFCOMM sockets before initializing the module. Probably should be an assert.
+  if (!is_init_done())
+    return BT_STATUS_NOT_READY;
 
-    rs->rfc_port_handle = 0;
-    //cleanup the flag
-    memset(&rs->f, 0, sizeof(rs->f));
-    rs->id = 0;
-}
-static inline BOOLEAN send_app_scn(rfc_slot_t* rs)
-{
-    if(sock_send_all(rs->fd, (const uint8_t*)&rs->scn, sizeof(rs->scn)) == sizeof(rs->scn))
-    {
-        return TRUE;
+  int status = BT_STATUS_FAIL;
+  lock_slot(&slot_lock);
+
+  rfc_slot_t *slot = alloc_rfc_slot(bd_addr, NULL, service_uuid, channel, flags, false);
+  if (!slot) {
+    LOG_ERROR("%s unable to allocate RFCOMM slot.", __func__);
+    goto out;
+  }
+
+  if (is_uuid_empty(service_uuid)) {
+    tBTA_JV_STATUS ret = BTA_JvRfcommConnect(slot->security, slot->role, slot->scn, slot->addr.address, rfcomm_cback, (void *)(uintptr_t)slot->id);
+    if (ret != BTA_JV_SUCCESS) {
+      LOG_ERROR("%s unable to initiate RFCOMM connection: %d", __func__, ret);
+      cleanup_rfc_slot(slot);
+      goto out;
     }
 
-    return FALSE;
-}
-static BOOLEAN send_app_connect_signal(int fd, const bt_bdaddr_t* addr, int channel, int status, int send_fd)
-{
-/*
-    typedef struct {
-    short size;
-    bt_bdaddr_t bd_addr;
-    int channel;
-    int status;
-} __attribute__((packed)) sock_connect_signal_t;
-*/
-    sock_connect_signal_t cs;
-    cs.size = sizeof(cs);
-    cs.bd_addr = *addr;
-    cs.channel = channel;
-    cs.status = status;
-    if(send_fd != -1)
-    {
-        if(sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs))
-            return TRUE;
-        else APPL_TRACE_ERROR("sock_send_fd failed, fd:%d, send_fd:%d", fd, send_fd);
+    if (!send_app_scn(slot)) {
+      LOG_ERROR("%s unable to send channel number.", __func__);
+      cleanup_rfc_slot(slot);
+      goto out;
     }
-    else if(sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs))
-    {
-        return TRUE;
-    }
-    return FALSE;
-}
-static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT *p_init, uint32_t id)
-{
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = find_rfc_slot_by_id(id);
-    if(rs)
-    {
-        if (p_init->status != BTA_JV_SUCCESS)
-            cleanup_rfc_slot(rs);
-        else
-        {
-            rs->rfc_handle = p_init->handle;
-        }
-    }
-    pthread_mutex_unlock(&slot_lock);
-}
-static void  on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START *p_start, uint32_t id)
-{
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = find_rfc_slot_by_id(id);
-    if(rs)
-    {
-        if (p_start->status != BTA_JV_SUCCESS)
-            cleanup_rfc_slot(rs);
-        else
-        {
-            rs->rfc_handle = p_start->handle;
+  } else {
+    tSDP_UUID sdp_uuid;
+    sdp_uuid.len = 16;
+    memcpy(sdp_uuid.uu.uuid128, service_uuid, sizeof(sdp_uuid.uu.uuid128));
 
-            if(!send_app_scn(rs))
-            {
-                //closed
-                APPL_TRACE_DEBUG("send_app_scn() failed, close rs->id:%d", rs->id);
-                cleanup_rfc_slot(rs);
-            }
-        }
+    if (!is_requesting_sdp()) {
+      BTA_JvStartDiscovery((uint8_t *)bd_addr->address, 1, &sdp_uuid, (void *)(uintptr_t)slot->id);
+      slot->f.pending_sdp_request = false;
+      slot->f.doing_sdp_request = true;
+    } else {
+      slot->f.pending_sdp_request = true;
+      slot->f.doing_sdp_request = false;
     }
-    pthread_mutex_unlock(&slot_lock);
-}
-static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN *p_open, uint32_t id)
-{
-    uint32_t new_listen_slot_id = 0;
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* srv_rs = find_rfc_slot_by_id(id);
-    if(srv_rs)
-    {
-        rfc_slot_t* accept_rs = create_srv_accept_rfc_slot(srv_rs, (const bt_bdaddr_t*)p_open->rem_bda,
-                                                           p_open->handle, p_open->new_listen_handle);
-        if(accept_rs)
-        {
-            //start monitor the socket
-            btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, srv_rs->id);
-            btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, accept_rs->id);
-            APPL_TRACE_DEBUG("sending connect signal & app fd:%dto app server to accept() the connection",
-                             accept_rs->app_fd);
-            APPL_TRACE_DEBUG("server fd:%d, scn:%d", srv_rs->fd, srv_rs->scn);
-            send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0, accept_rs->app_fd);
-            accept_rs->app_fd = -1; //the fd is closed after sent to app
-            new_listen_slot_id = srv_rs->id;
-        }
-    }
-    pthread_mutex_unlock(&slot_lock);
-    return new_listen_slot_id;
-}
-static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN *p_open, uint32_t id)
-{
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = find_rfc_slot_by_id(id);
-    if(rs && p_open->status == BTA_JV_SUCCESS)
-    {
-        rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(p_open->handle);
-        bd_copy(rs->addr.address, p_open->rem_bda, 0);
-        //notify app rfc is connected
-        APPL_TRACE_DEBUG("call send_app_connect_signal, slot id:%d, fd:%d, rfc scn:%d, server:%d",
-                         rs->id, rs->fd, rs->scn, rs->f.server);
-        if(send_app_connect_signal(rs->fd, &rs->addr, rs->scn, 0, -1))
-        {
-            //start monitoring the socketpair to get call back when app writing data
-            APPL_TRACE_DEBUG("on_rfc_connect_ind, connect signal sent, slot id:%d, rfc scn:%d, server:%d",
-                             rs->id, rs->scn, rs->f.server);
-            rs->f.connected = TRUE;
-        }
-        else APPL_TRACE_ERROR("send_app_connect_signal failed");
-    }
-    else if(rs)
-        cleanup_rfc_slot(rs);
-    pthread_mutex_unlock(&slot_lock);
-}
-static void on_rfc_close(tBTA_JV_RFCOMM_CLOSE * p_close, uint32_t id)
-{
-    UNUSED(p_close);
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = find_rfc_slot_by_id(id);
-    if(rs)
-    {
-        APPL_TRACE_DEBUG("on_rfc_close, slot id:%d, fd:%d, rfc scn:%d, server:%d",
-                         rs->id, rs->fd, rs->scn, rs->f.server);
-        free_rfc_slot_scn(rs);
-        // rfc_handle already closed when receiving rfcomm close event from stack.
-        rs->f.connected = FALSE;
-        cleanup_rfc_slot(rs);
-    }
-    pthread_mutex_unlock(&slot_lock);
-}
-static void on_rfc_write_done(tBTA_JV_RFCOMM_WRITE *p, uint32_t id)
-{
-    UNUSED(p);
+  }
 
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = find_rfc_slot_by_id(id);
-    if(rs && !rs->f.outgoing_congest)
-    {
-        //mointer the fd for any outgoing data
-        btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, rs->id);
-    }
-    pthread_mutex_unlock(&slot_lock);
-}
-static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG *p, uint32_t id)
-{
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = find_rfc_slot_by_id(id);
-    if(rs)
-    {
-        rs->f.outgoing_congest = p->cong ? 1 : 0;
-        //mointer the fd for any outgoing data
-        if(!rs->f.outgoing_congest)
-            btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, rs->id);
-    }
-    pthread_mutex_unlock(&slot_lock);
+  *sock_fd = slot->app_fd;    // Transfer ownership of fd to caller.
+  slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
+  btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
+  status = BT_STATUS_SUCCESS;
+
+out:;
+  unlock_slot(&slot_lock);
+  return status;
 }
 
-static void *rfcomm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data)
-{
-    void* new_user_data = NULL;
-    APPL_TRACE_DEBUG("event=%s", jv_evt[event]);
+static int create_server_sdp_record(rfc_slot_t *slot) {
+  if (slot->scn > 0) {
+    if (!BTM_TryAllocateSCN(slot->scn)) {
+      LOG_ERROR("%s attempting to allocate fixed channel %d which is already in use.", __func__, slot->scn);
+      return false;
+    }
+  } else if ((slot->scn = BTM_AllocateSCN()) == 0) {
+    LOG_ERROR("%s unable to allocate RFCOMM server channel.", __func__);
+    return false;
+  }
 
-    switch (event)
-    {
+  slot->sdp_handle = add_rfc_sdp_rec(slot->service_name, slot->service_uuid, slot->scn);
+  return (slot->sdp_handle > 0);
+}
+
+static void free_rfc_slot_scn(rfc_slot_t *slot) {
+  if (slot->scn <= 0)
+    return;
+
+  if(slot->f.server && !slot->f.closing && slot->rfc_handle) {
+    BTA_JvRfcommStopServer(slot->rfc_handle, (void *)(uintptr_t)slot->id);
+    slot->rfc_handle = 0;
+  }
+
+  if (slot->f.server)
+    BTM_FreeSCN(slot->scn);
+  slot->scn = 0;
+}
+
+static void cleanup_rfc_slot(rfc_slot_t *slot) {
+  if (slot->fd != INVALID_FD) {
+    shutdown(slot->fd, SHUT_RDWR);
+    close(slot->fd);
+    slot->fd = INVALID_FD;
+  }
+
+  if (slot->app_fd != INVALID_FD) {
+    close(slot->app_fd);
+    slot->app_fd = INVALID_FD;
+  }
+
+  if (slot->sdp_handle > 0) {
+    del_rfc_sdp_rec(slot->sdp_handle);
+    slot->sdp_handle = 0;
+  }
+
+  if (slot->rfc_handle && !slot->f.closing && !slot->f.server) {
+    BTA_JvRfcommClose(slot->rfc_handle, (void *)(uintptr_t)slot->id);
+    slot->rfc_handle = 0;
+  }
+
+  free_rfc_slot_scn(slot);
+  list_clear(slot->incoming_queue);
+
+  slot->rfc_port_handle = 0;
+  memset(&slot->f, 0, sizeof(slot->f));
+  slot->id = 0;
+}
+
+static bool send_app_scn(const rfc_slot_t *slot) {
+  return sock_send_all(slot->fd, (const uint8_t*)&slot->scn, sizeof(slot->scn)) == sizeof(slot->scn);
+}
+
+static bool send_app_connect_signal(int fd, const bt_bdaddr_t* addr, int channel, int status, int send_fd) {
+  sock_connect_signal_t cs;
+  cs.size = sizeof(cs);
+  cs.bd_addr = *addr;
+  cs.channel = channel;
+  cs.status = status;
+
+  if (send_fd == INVALID_FD)
+    return sock_send_all(fd, (const uint8_t *)&cs, sizeof(cs)) == sizeof(cs);
+
+  return sock_send_fd(fd, (const uint8_t *)&cs, sizeof(cs), send_fd) == sizeof(cs);
+}
+
+static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT *p_init, uint32_t id) {
+  lock_slot(&slot_lock);
+
+  rfc_slot_t *slot = find_rfc_slot_by_id(id);
+  if (!slot)
+    goto out;
+
+  if (p_init->status == BTA_JV_SUCCESS)
+    slot->rfc_handle = p_init->handle;
+  else
+    cleanup_rfc_slot(slot);
+
+out:;
+  unlock_slot(&slot_lock);
+}
+
+static void on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START *p_start, uint32_t id) {
+  lock_slot(&slot_lock);
+
+  rfc_slot_t *slot = find_rfc_slot_by_id(id);
+  if (!slot)
+    goto out;
+
+  if (p_start->status == BTA_JV_SUCCESS) {
+    slot->rfc_handle = p_start->handle;
+
+    if (!send_app_scn(slot)) {
+      LOG_ERROR("%s unable to send server channel number for slot %d.", __func__, slot->id);
+      cleanup_rfc_slot(slot);
+    }
+  } else
+    cleanup_rfc_slot(slot);
+
+out:;
+  unlock_slot(&slot_lock);
+}
+
+static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN *p_open, uint32_t id) {
+  uint32_t new_listen_slot_id = 0;
+  lock_slot(&slot_lock);
+
+  rfc_slot_t *srv_rs = find_rfc_slot_by_id(id);
+  if (!srv_rs)
+    goto out;
+
+  rfc_slot_t *accept_rs = create_srv_accept_rfc_slot(srv_rs, (const bt_bdaddr_t *)p_open->rem_bda, p_open->handle, p_open->new_listen_handle);
+  if (!accept_rs)
+    goto out;
+
+  // Start monitoring the socket.
+  btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, srv_rs->id);
+  btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, accept_rs->id);
+  send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0, accept_rs->app_fd);
+  accept_rs->app_fd = INVALID_FD;  // Ownership of the application fd has been transferred.
+  new_listen_slot_id = srv_rs->id;
+
+out:;
+  unlock_slot(&slot_lock);
+  return new_listen_slot_id;
+}
+
+static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN *p_open, uint32_t id) {
+  lock_slot(&slot_lock);
+
+  rfc_slot_t *slot = find_rfc_slot_by_id(id);
+  if (!slot)
+    goto out;
+
+  if (p_open->status != BTA_JV_SUCCESS) {
+    cleanup_rfc_slot(slot);
+    goto out;
+  }
+
+  slot->rfc_port_handle = BTA_JvRfcommGetPortHdl(p_open->handle);
+  memcpy(slot->addr.address, p_open->rem_bda, 6);
+
+  if (send_app_connect_signal(slot->fd, &slot->addr, slot->scn, 0, -1))
+    slot->f.connected = true;
+  else
+    LOG_ERROR("%s unable to send connect completion signal to caller.", __func__);
+
+out:;
+  unlock_slot(&slot_lock);
+}
+
+static void on_rfc_close(UNUSED_ATTR tBTA_JV_RFCOMM_CLOSE *p_close, uint32_t id) {
+  lock_slot(&slot_lock);
+
+  // rfc_handle already closed when receiving rfcomm close event from stack.
+  rfc_slot_t *slot = find_rfc_slot_by_id(id);
+  if (slot)
+    cleanup_rfc_slot(slot);
+
+  unlock_slot(&slot_lock);
+}
+
+static void on_rfc_write_done(UNUSED_ATTR tBTA_JV_RFCOMM_WRITE *p, uint32_t id) {
+  lock_slot(&slot_lock);
+
+  rfc_slot_t *slot = find_rfc_slot_by_id(id);
+  if (slot && !slot->f.outgoing_congest)
+    btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
+
+  unlock_slot(&slot_lock);
+}
+
+static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG *p, uint32_t id) {
+  lock_slot(&slot_lock);
+
+  rfc_slot_t *slot = find_rfc_slot_by_id(id);
+  if (slot) {
+    slot->f.outgoing_congest = p->cong ? 1 : 0;
+    if (!slot->f.outgoing_congest)
+      btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
+  }
+
+  unlock_slot(&slot_lock);
+}
+
+static void *rfcomm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data) {
+  void *new_user_data = NULL;
+
+  switch (event) {
     case BTA_JV_RFCOMM_START_EVT:
-        on_srv_rfc_listen_started(&p_data->rfc_start, (uintptr_t)user_data);
-        break;
+      on_srv_rfc_listen_started(&p_data->rfc_start, (uintptr_t)user_data);
+      break;
 
     case BTA_JV_RFCOMM_CL_INIT_EVT:
-        on_cl_rfc_init(&p_data->rfc_cl_init, (uintptr_t)user_data);
-        break;
+      on_cl_rfc_init(&p_data->rfc_cl_init, (uintptr_t)user_data);
+      break;
 
     case BTA_JV_RFCOMM_OPEN_EVT:
-        BTA_JvSetPmProfile(p_data->rfc_open.handle,BTA_JV_PM_ID_1,BTA_JV_CONN_OPEN);
-        on_cli_rfc_connect(&p_data->rfc_open, (uintptr_t)user_data);
-        break;
+      BTA_JvSetPmProfile(p_data->rfc_open.handle,BTA_JV_PM_ID_1,BTA_JV_CONN_OPEN);
+      on_cli_rfc_connect(&p_data->rfc_open, (uintptr_t)user_data);
+      break;
+
     case BTA_JV_RFCOMM_SRV_OPEN_EVT:
-        BTA_JvSetPmProfile(p_data->rfc_srv_open.handle,BTA_JV_PM_ALL,BTA_JV_CONN_OPEN);
-        new_user_data = (void*)(intptr_t)on_srv_rfc_connect(&p_data->rfc_srv_open, (uintptr_t)user_data);
-        break;
+      BTA_JvSetPmProfile(p_data->rfc_srv_open.handle,BTA_JV_PM_ALL,BTA_JV_CONN_OPEN);
+      new_user_data = (void *)(uintptr_t)on_srv_rfc_connect(&p_data->rfc_srv_open, (uintptr_t)user_data);
+      break;
 
     case BTA_JV_RFCOMM_CLOSE_EVT:
-        APPL_TRACE_DEBUG("BTA_JV_RFCOMM_CLOSE_EVT: user_data:%d", (uintptr_t)user_data);
-        on_rfc_close(&p_data->rfc_close, (uintptr_t)user_data);
-        break;
-
-    case BTA_JV_RFCOMM_READ_EVT:
-        APPL_TRACE_DEBUG("BTA_JV_RFCOMM_READ_EVT not used");
-        break;
+      APPL_TRACE_DEBUG("BTA_JV_RFCOMM_CLOSE_EVT: user_data:%d", (uintptr_t)user_data);
+      on_rfc_close(&p_data->rfc_close, (uintptr_t)user_data);
+      break;
 
     case BTA_JV_RFCOMM_WRITE_EVT:
-        on_rfc_write_done(&p_data->rfc_write, (uintptr_t)user_data);
-        break;
-
-    case BTA_JV_RFCOMM_DATA_IND_EVT:
-        APPL_TRACE_DEBUG("BTA_JV_RFCOMM_DATA_IND_EVT not used");
-        break;
+      on_rfc_write_done(&p_data->rfc_write, (uintptr_t)user_data);
+      break;
 
     case BTA_JV_RFCOMM_CONG_EVT:
-        //on_rfc_cong(&p_data->rfc_cong);
-        on_rfc_outgoing_congest(&p_data->rfc_cong, (uintptr_t)user_data);
-        break;
+      on_rfc_outgoing_congest(&p_data->rfc_cong, (uintptr_t)user_data);
+      break;
+
+    case BTA_JV_RFCOMM_READ_EVT:
+    case BTA_JV_RFCOMM_DATA_IND_EVT:
+      // Unused.
+      break;
+
     default:
-        APPL_TRACE_ERROR("unhandled event %d, slot id:%d", event, (uintptr_t)user_data);
+      LOG_ERROR("%s unhandled event %d, slot id: %d", __func__, event, (uintptr_t)user_data);
+      break;
+  }
+  return new_user_data;
+}
+
+static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data) {
+  uint32_t id = (uintptr_t)user_data;
+  switch(event) {
+    case BTA_JV_CREATE_RECORD_EVT: {
+      lock_slot(&slot_lock);
+
+      rfc_slot_t *slot = find_rfc_slot_by_id(id);
+      if (slot && create_server_sdp_record(slot)) {
+        // Start the rfcomm server after sdp & channel # assigned.
+        BTA_JvRfcommStartServer(slot->security, slot->role, slot->scn, MAX_RFC_SESSION, rfcomm_cback, (void *)(uintptr_t)slot->id);
+      } else if(slot) {
+        APPL_TRACE_ERROR("jv_dm_cback: cannot start server, slot found:%p", slot);
+        cleanup_rfc_slot(slot);
+      }
+
+      unlock_slot(&slot_lock);
+      break;
+    }
+
+    case BTA_JV_DISCOVERY_COMP_EVT: {
+      lock_slot(&slot_lock);
+      rfc_slot_t *slot = find_rfc_slot_by_id(id);
+      if (p_data->disc_comp.status == BTA_JV_SUCCESS && p_data->disc_comp.scn) {
+        if (slot && slot->f.doing_sdp_request) {
+          // Establish the connection if we successfully looked up a channel number to connect to.
+          if (BTA_JvRfcommConnect(slot->security, slot->role, p_data->disc_comp.scn, slot->addr.address, rfcomm_cback, (void *)(uintptr_t)slot->id) == BTA_JV_SUCCESS) {
+            slot->scn = p_data->disc_comp.scn;
+            slot->f.doing_sdp_request = false;
+            if (!send_app_scn(slot))
+              cleanup_rfc_slot(slot);
+          } else {
+            cleanup_rfc_slot(slot);
+          }
+        } else if (slot) {
+          // TODO(sharvil): this is really a logic error and we should probably assert.
+          LOG_ERROR("%s SDP response returned but RFCOMM slot %d did not request SDP record.", __func__, id);
+        }
+      } else if (slot) {
+        cleanup_rfc_slot(slot);
+      }
+
+      // Find the next slot that needs to perform an SDP request and service it.
+      slot = find_rfc_slot_by_pending_sdp();
+      if (slot) {
+        tSDP_UUID sdp_uuid;
+        sdp_uuid.len = 16;
+        memcpy(sdp_uuid.uu.uuid128, slot->service_uuid, sizeof(sdp_uuid.uu.uuid128));
+        BTA_JvStartDiscovery((uint8_t *)slot->addr.address, 1, &sdp_uuid, (void *)(uintptr_t)slot->id);
+        slot->f.pending_sdp_request = false;
+        slot->f.doing_sdp_request = true;
+      }
+
+      unlock_slot(&slot_lock);
+      break;
+    }
+
+    default:
+      APPL_TRACE_DEBUG("unhandled event:%d, slot id:%d", event, id);
+      break;
+  }
+}
+
+typedef enum {
+  SENT_FAILED,
+  SENT_NONE,
+  SENT_PARTIAL,
+  SENT_ALL,
+} sent_status_t;
+
+static sent_status_t send_data_to_app(int fd, BT_HDR *p_buf) {
+  if (p_buf->len == 0)
+    return SENT_ALL;
+
+  ssize_t sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT);
+
+  if (sent == -1) {
+    if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
+      return SENT_NONE;
+    LOG_ERROR("%s error writing RFCOMM data back to app: %s", __func__, strerror(errno));
+    return SENT_FAILED;
+  }
+
+  if (sent == 0)
+    return SENT_FAILED;
+
+  if (sent == p_buf->len)
+    return SENT_ALL;
+
+  p_buf->offset += sent;
+  p_buf->len -= sent;
+  return SENT_PARTIAL;
+}
+
+static bool flush_incoming_que_on_wr_signal(rfc_slot_t *slot) {
+  while (!list_is_empty(slot->incoming_queue)) {
+    BT_HDR *p_buf = list_front(slot->incoming_queue);
+    switch (send_data_to_app(slot->fd, p_buf)) {
+      case SENT_NONE:
+      case SENT_PARTIAL:
+        //monitor the fd to get callback when app is ready to receive data
+        btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, slot->id);
+        return true;
+
+      case SENT_ALL:
+        list_remove(slot->incoming_queue, p_buf);
+        break;
+
+      case SENT_FAILED:
+        list_remove(slot->incoming_queue, p_buf);
+        return false;
+    }
+  }
+
+  //app is ready to receive data, tell stack to start the data flow
+  //fix me: need a jv flow control api to serialize the call in stack
+  APPL_TRACE_DEBUG("enable data flow, rfc_handle:0x%x, rfc_port_handle:0x%x, user_id:%d",
+      slot->rfc_handle, slot->rfc_port_handle, slot->id);
+  extern int PORT_FlowControl_MaxCredit(uint16_t handle, bool enable);
+  PORT_FlowControl_MaxCredit(slot->rfc_port_handle, true);
+  return true;
+}
+
+void btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) {
+  lock_slot(&slot_lock);
+
+  rfc_slot_t *slot = find_rfc_slot_by_id(user_id);
+  if (!slot)
+    goto out;
+
+  bool need_close = false;
+
+  // Data available from app, tell stack we have outgoing data.
+  if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
+    if (slot->f.connected) {
+      // Make sure there's data pending in case the peer closed the socket.
+      int size = 0;
+      if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(slot->fd, FIONREAD, &size) == 0 && size))
+        BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
+    } else {
+      LOG_ERROR("%s socket signaled for read while disconnected, slot: %d, channel: %d", __func__, slot->id, slot->scn);
+      need_close = true;
+    }
+  }
+
+  if (flags & SOCK_THREAD_FD_WR) {
+    // App is ready to receive more data, tell stack to enable data flow.
+    if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
+      LOG_ERROR("%s socket signaled for write while disconnected (or write failure), slot: %d, channel: %d", __func__, slot->id, slot->scn);
+      need_close = true;
+    }
+  }
+
+  if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
+    // Clean up if there's no data pending.
+    int size = 0;
+    if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size)
+      cleanup_rfc_slot(slot);
+  }
+
+out:;
+  unlock_slot(&slot_lock);
+}
+
+int bta_co_rfc_data_incoming(void *user_data, BT_HDR *p_buf) {
+  lock_slot(&slot_lock);
+
+  int ret = 0;
+  uint32_t id = (uintptr_t)user_data;
+  rfc_slot_t *slot = find_rfc_slot_by_id(id);
+  if (!slot)
+    goto out;
+
+  if (list_is_empty(slot->incoming_queue)) {
+    switch (send_data_to_app(slot->fd, p_buf)) {
+      case SENT_NONE:
+      case SENT_PARTIAL:
+        list_append(slot->incoming_queue, p_buf);
+        btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, slot->id);
+        break;
+
+      case SENT_ALL:
+        GKI_freebuf(p_buf);
+        ret = 1;  // Enable data flow.
+        break;
+
+      case SENT_FAILED:
+        GKI_freebuf(p_buf);
+        cleanup_rfc_slot(slot);
         break;
     }
-    return new_user_data;
+  } else {
+    list_append(slot->incoming_queue, p_buf);
+  }
+
+out:;
+  unlock_slot(&slot_lock);
+  return ret;  // Return 0 to disable data flow.
 }
 
-static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data)
-{
-    uint32_t id = (uintptr_t)user_data;
-    APPL_TRACE_DEBUG("jv_dm_cback: event:%d, slot id:%d", event, id);
-    switch(event)
-    {
-        case BTA_JV_CREATE_RECORD_EVT:
-            {
-                pthread_mutex_lock(&slot_lock);
-                rfc_slot_t* rs = find_rfc_slot_by_id(id);
-                if(rs && create_server_sdp_record(rs))
-                {
-                    //now start the rfcomm server after sdp & channel # assigned
-                    BTA_JvRfcommStartServer(rs->security, rs->role, rs->scn, MAX_RFC_SESSION, rfcomm_cback,
-                                            (void*)(uintptr_t)rs->id);
-                }
-                else if(rs)
-                {
-                    APPL_TRACE_ERROR("jv_dm_cback: cannot start server, slot found:%p", rs);
-                    cleanup_rfc_slot(rs);
-                }
-                pthread_mutex_unlock(&slot_lock);
-                break;
-            }
-        case BTA_JV_DISCOVERY_COMP_EVT:
-            {
-                rfc_slot_t* rs = NULL;
-                pthread_mutex_lock(&slot_lock);
-                if(p_data->disc_comp.status == BTA_JV_SUCCESS && p_data->disc_comp.scn)
-                {
-                    APPL_TRACE_DEBUG("BTA_JV_DISCOVERY_COMP_EVT, slot id:%d, status:%d, scn:%d",
-                                      id, p_data->disc_comp.status, p_data->disc_comp.scn);
+int bta_co_rfc_data_outgoing_size(void *user_data, int *size) {
+  lock_slot(&slot_lock);
 
-                    rs = find_rfc_slot_by_id(id);
-                    if(rs && rs->f.doing_sdp_request)
-                    {
-                        if(BTA_JvRfcommConnect(rs->security, rs->role, p_data->disc_comp.scn, rs->addr.address,
-                                    rfcomm_cback, (void*)(uintptr_t)rs->id) == BTA_JV_SUCCESS)
-                        {
-                            rs->scn = p_data->disc_comp.scn;
-                            rs->f.doing_sdp_request = FALSE;
-                            if(!send_app_scn(rs))
-                                cleanup_rfc_slot(rs);
-                        }
-                        else cleanup_rfc_slot(rs);
-                    }
-                    else if(rs)
-                    {
-                        APPL_TRACE_ERROR("DISCOVERY_COMP_EVT no pending sdp request, slot id:%d, \
-                                flag sdp pending:%d, flag sdp doing:%d",
-                                id, rs->f.pending_sdp_request, rs->f.doing_sdp_request);
-                    }
-                }
-                else
-                {
-                    APPL_TRACE_ERROR("DISCOVERY_COMP_EVT slot id:%d, failed to find channel, \
-                                      status:%d, scn:%d", id, p_data->disc_comp.status,
-                                      p_data->disc_comp.scn);
-                    rs = find_rfc_slot_by_id(id);
-                    if(rs)
-                        cleanup_rfc_slot(rs);
-                }
-                rs = find_rfc_slot_by_pending_sdp();
-                if(rs)
-                {
-                    APPL_TRACE_DEBUG("BTA_JV_DISCOVERY_COMP_EVT, start another pending scn sdp request");
-                    tSDP_UUID sdp_uuid;
-                    sdp_uuid.len = 16;
-                    memcpy(sdp_uuid.uu.uuid128, rs->service_uuid, sizeof(sdp_uuid.uu.uuid128));
-                    BTA_JvStartDiscovery((UINT8*)rs->addr.address, 1, &sdp_uuid, (void*)(uintptr_t)rs->id);
-                    rs->f.pending_sdp_request = FALSE;
-                    rs->f.doing_sdp_request = TRUE;
-                }
-                pthread_mutex_unlock(&slot_lock);
-                break;
-            }
-        default:
-            APPL_TRACE_DEBUG("unhandled event:%d, slot id:%d", event, id);
-            break;
-    }
+  uint32_t id = (uintptr_t)user_data;
+  int ret = false;
+  *size = 0;
+  rfc_slot_t *slot = find_rfc_slot_by_id(id);
+  if (!slot)
+    goto out;
 
-}
-#define SENT_ALL 2
-#define SENT_PARTIAL 1
-#define SENT_NONE 0
-#define SENT_FAILED (-1)
-static int send_data_to_app(int fd, BT_HDR *p_buf)
-{
-    if(p_buf->len == 0)
-        return SENT_ALL;
-    int sent = send(fd, (UINT8 *)(p_buf + 1) + p_buf->offset,  p_buf->len, MSG_DONTWAIT);
-    if(sent == p_buf->len)
-        return SENT_ALL;
+  if (ioctl(slot->fd, FIONREAD, size) == 0) {
+    ret = true;
+  } else {
+    LOG_ERROR("%s unable to determine bytes remaining to be read on fd %d: %s", __func__, slot->fd, strerror(errno));
+    cleanup_rfc_slot(slot);
+  }
 
-    if(sent > 0 && sent < p_buf->len)
-    {
-        //sent partial
-        APPL_TRACE_ERROR("send partial, sent:%d, p_buf->len:%d", sent, p_buf->len);
-        p_buf->offset += sent;
-        p_buf->len -= sent;
-        return SENT_PARTIAL;
-
-    }
-    if(sent < 0 &&
-        (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
-    {
-        APPL_TRACE_ERROR("send none, EAGAIN or EWOULDBLOCK, errno:%d", errno);
-        return SENT_NONE;
-    }
-    APPL_TRACE_ERROR("unknown send() error, sent:%d, p_buf->len:%d,  errno:%d", sent, p_buf->len, errno);
-    return SENT_FAILED;
-}
-static BOOLEAN flush_incoming_que_on_wr_signal(rfc_slot_t* rs)
-{
-    while(!list_is_empty(rs->incoming_queue))
-    {
-        BT_HDR *p_buf = list_front(rs->incoming_queue);
-        int sent = send_data_to_app(rs->fd, p_buf);
-        switch(sent)
-        {
-            case SENT_NONE:
-            case SENT_PARTIAL:
-                //monitor the fd to get callback when app is ready to receive data
-                btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, rs->id);
-                return TRUE;
-            case SENT_ALL:
-                list_remove(rs->incoming_queue, p_buf);
-                break;
-            case SENT_FAILED:
-                list_remove(rs->incoming_queue, p_buf);
-                return FALSE;
-        }
-    }
-
-    //app is ready to receive data, tell stack to start the data flow
-    //fix me: need a jv flow control api to serialize the call in stack
-    APPL_TRACE_DEBUG("enable data flow, rfc_handle:0x%x, rfc_port_handle:0x%x, user_id:%d",
-                        rs->rfc_handle, rs->rfc_port_handle, rs->id);
-    extern int PORT_FlowControl_MaxCredit(UINT16 handle, BOOLEAN enable);
-    PORT_FlowControl_MaxCredit(rs->rfc_port_handle, TRUE);
-    return TRUE;
-}
-void btsock_rfc_signaled(int fd, int flags, uint32_t user_id)
-{
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = find_rfc_slot_by_id(user_id);
-    if(rs)
-    {
-        APPL_TRACE_DEBUG("rfc slot id:%d, fd:%d, flags:%x", rs->id, fd, flags);
-        BOOLEAN need_close = FALSE;
-        if(flags & SOCK_THREAD_FD_RD)
-        {
-            //data available from app, tell stack we have outgoing data
-            if(!rs->f.server)
-            {
-                if(rs->f.connected)
-                {
-                    int size = 0;
-                    //make sure there's data pending in case the peer closed the socket
-                    if(!(flags & SOCK_THREAD_FD_EXCEPTION) ||
-                                (ioctl(rs->fd, FIONREAD, &size) == 0 && size))
-                    {
-                        int rfc_handle = rs->rfc_handle;
-                        UINT32 rs_id = rs->id;
-                        // unlock before BTA_JvRfcommWrite to avoid
-                        // deadlock on concurrent multi-rfcomm connections.
-                        pthread_mutex_unlock(&slot_lock);
-                        BTA_JvRfcommWrite(rfc_handle, rs_id);
-                        return;
-                    }
-                }
-                else
-                {
-                    APPL_TRACE_ERROR("SOCK_THREAD_FD_RD signaled when rfc is not connected, \
-                                      slot id:%d, channel:%d", rs->id, rs->scn);
-                    need_close = TRUE;
-                }
-            }
-        }
-        if(flags & SOCK_THREAD_FD_WR)
-        {
-            //app is ready to receive more data, tell stack to enable the data flow
-            if(!rs->f.connected || !flush_incoming_que_on_wr_signal(rs))
-            {
-                need_close = TRUE;
-                APPL_TRACE_ERROR("SOCK_THREAD_FD_WR signaled when rfc is not connected \
-                                  or app closed fd, slot id:%d, channel:%d", rs->id, rs->scn);
-            }
-
-        }
-        if(need_close || (flags & SOCK_THREAD_FD_EXCEPTION))
-        {
-            int size = 0;
-            if(need_close || ioctl(rs->fd, FIONREAD, &size) != 0 || size == 0 )
-            {
-                //cleanup when no data pending
-                APPL_TRACE_DEBUG("SOCK_THREAD_FD_EXCEPTION, cleanup, flags:%x, need_close:%d, pending size:%d",
-                                flags, need_close, size);
-                cleanup_rfc_slot(rs);
-            }
-            else
-                APPL_TRACE_DEBUG("SOCK_THREAD_FD_EXCEPTION, cleanup pending, flags:%x, need_close:%d, pending size:%d",
-                                flags, need_close, size);
-        }
-    }
-    pthread_mutex_unlock(&slot_lock);
+out:;
+  unlock_slot(&slot_lock);
+  return ret;
 }
 
-int bta_co_rfc_data_incoming(void *user_data, BT_HDR *p_buf)
-{
-    uint32_t id = (uintptr_t)user_data;
-    int ret = 0;
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = find_rfc_slot_by_id(id);
-    if(rs)
-    {
-        if(!list_is_empty(rs->incoming_queue))
-            list_append(rs->incoming_queue, p_buf);
-        else
-        {
-            int sent = send_data_to_app(rs->fd, p_buf);
-            switch(sent)
-            {
-                case SENT_NONE:
-                case SENT_PARTIAL:
-                    //add it to the end of the queue
-                    list_append(rs->incoming_queue, p_buf);
-                    //monitor the fd to get callback when app is ready to receive data
-                    btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, rs->id);
-                    break;
-                case SENT_ALL:
-                    GKI_freebuf(p_buf);
-                    ret = 1;//enable the data flow
-                    break;
-                case SENT_FAILED:
-                    GKI_freebuf(p_buf);
-                    cleanup_rfc_slot(rs);
-                    break;
-            }
-        }
-     }
-    pthread_mutex_unlock(&slot_lock);
-    return ret;//return 0 to disable data flow
-}
-int bta_co_rfc_data_outgoing_size(void *user_data, int *size)
-{
-    uint32_t id = (uintptr_t)user_data;
-    int ret = FALSE;
-    *size = 0;
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = find_rfc_slot_by_id(id);
-    if(rs)
-    {
-        if(ioctl(rs->fd, FIONREAD, size) == 0)
-        {
-            APPL_TRACE_DEBUG("ioctl read avaiable size:%d, fd:%d", *size, rs->fd);
-            ret = TRUE;
-        }
-        else
-        {
-            APPL_TRACE_ERROR("ioctl FIONREAD error, errno:%d, fd:%d", errno, rs->fd);
-            cleanup_rfc_slot(rs);
-        }
-    }
-    else APPL_TRACE_ERROR("bta_co_rfc_data_outgoing_size, invalid slot id:%d", id);
-    pthread_mutex_unlock(&slot_lock);
-    return ret;
-}
-int bta_co_rfc_data_outgoing(void *user_data, UINT8* buf, UINT16 size)
-{
-    uint32_t id = (uintptr_t)user_data;
-    int ret = FALSE;
-    pthread_mutex_lock(&slot_lock);
-    rfc_slot_t* rs = find_rfc_slot_by_id(id);
-    if(rs)
-    {
-        int received = recv(rs->fd, buf, size, 0);
-        if(received == size)
-            ret = TRUE;
-        else
-        {
-            APPL_TRACE_ERROR("recv error, errno:%d, fd:%d, size:%d, received:%d",
-                             errno, rs->fd, size, received);
-            cleanup_rfc_slot(rs);
-        }
-    }
-    else APPL_TRACE_ERROR("bta_co_rfc_data_outgoing, invalid slot id:%d", id);
-    pthread_mutex_unlock(&slot_lock);
-    return ret;
-}
+int bta_co_rfc_data_outgoing(void *user_data, uint8_t *buf, uint16_t size) {
+  lock_slot(&slot_lock);
 
+  uint32_t id = (uintptr_t)user_data;
+  int ret = false;
+  rfc_slot_t *slot = find_rfc_slot_by_id(id);
+  if (!slot)
+    goto out;
+
+  int received = recv(slot->fd, buf, size, 0);
+  if(received == size) {
+    ret = true;
+  } else {
+    LOG_ERROR("%s error receiving RFCOMM data from app: %s", __func__, strerror(errno));
+    cleanup_rfc_slot(slot);
+  }
+
+out:;
+  unlock_slot(&slot_lock);
+  return ret;
+}
diff --git a/btif/src/btif_sock_sco.c b/btif/src/btif_sock_sco.c
new file mode 100644
index 0000000..2c6be49
--- /dev/null
+++ b/btif/src/btif_sock_sco.c
@@ -0,0 +1,327 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_btif_sock_sco"
+
+#include <assert.h>
+#include <hardware/bluetooth.h>
+#include <hardware/bt_sock.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+
+#include "btif_common.h"
+#include "osi/include/list.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/socket.h"
+#include "osi/include/thread.h"
+
+// This module provides a socket abstraction for SCO connections to a higher
+// layer. It returns file descriptors representing two types of sockets:
+// listening (server) and connected (client) sockets. No SCO data is
+// transferred across these sockets; instead, they are used to manage SCO
+// connection lifecycles while the data routing takes place over the I2S bus.
+//
+// This code bridges the gap between the BTM layer, which implements SCO
+// connections, and the Android HAL. It adapts the BTM representation of SCO
+// connections (integer handles) to a file descriptor representation usable by
+// Android's LocalSocket implementation.
+//
+// Sample flow for an incoming connection:
+//   btsock_sco_listen()       - listen for incoming connections
+//   connection_request_cb()   - incoming connection request from remote host
+//   connect_completed_cb()    - connection successfully established
+//   socket_read_ready_cb()    - local host closed SCO socket
+//   disconnect_completed_cb() - connection terminated
+
+typedef struct {
+  uint16_t sco_handle;
+  socket_t *socket;
+  bool connect_completed;
+} sco_socket_t;
+
+// TODO: verify packet types that are being sent OTA.
+static tBTM_ESCO_PARAMS sco_parameters = {
+    BTM_64KBITS_RATE,                   /* TX Bandwidth (64 kbits/sec)              */
+    BTM_64KBITS_RATE,                   /* RX Bandwidth (64 kbits/sec)              */
+    0x000a,                             /* 10 ms (HS/HF can use EV3, 2-EV3, 3-EV3)  */
+    0x0060,                             /* Inp Linear, Air CVSD, 2s Comp, 16bit     */
+    (BTM_SCO_LINK_ALL_PKT_MASK       |
+     BTM_SCO_PKT_TYPES_MASK_NO_2_EV5 |
+     BTM_SCO_PKT_TYPES_MASK_NO_3_EV5),
+     BTM_ESCO_RETRANS_POWER       /* Retransmission effort                      */
+};
+
+static sco_socket_t *sco_socket_establish_locked(bool is_listening, const bt_bdaddr_t *bd_addr, int *sock_fd);
+static sco_socket_t *sco_socket_new(void);
+static void sco_socket_free_locked(sco_socket_t *socket);
+static sco_socket_t *sco_socket_find_locked(uint16_t sco_handle);
+static void connection_request_cb(tBTM_ESCO_EVT event, tBTM_ESCO_EVT_DATA *data);
+static void connect_completed_cb(uint16_t sco_handle);
+static void disconnect_completed_cb(uint16_t sco_handle);
+static void socket_read_ready_cb(socket_t *socket, void *context);
+
+// |lock| protects all of the static variables below and
+// calls into the BTM layer.
+static pthread_mutex_t lock;
+static list_t *sco_sockets;              // Owns a collection of sco_socket_t objects.
+static sco_socket_t *listen_sco_socket;  // Not owned, do not free.
+static thread_t *thread;                 // Not owned, do not free.
+
+bt_status_t btsock_sco_init(thread_t *thread_) {
+  assert(thread_ != NULL);
+
+  sco_sockets = list_new((list_free_cb)sco_socket_free_locked);
+  if (!sco_sockets)
+    return BT_STATUS_FAIL;
+
+  pthread_mutex_init(&lock, NULL);
+
+  thread = thread_;
+  BTM_SetEScoMode(BTM_LINK_TYPE_ESCO, &sco_parameters);
+
+  return BT_STATUS_SUCCESS;
+}
+
+bt_status_t btsock_sco_cleanup(void) {
+  list_free(sco_sockets);
+  sco_sockets = NULL;
+  pthread_mutex_destroy(&lock);
+  return BT_STATUS_SUCCESS;
+}
+
+bt_status_t btsock_sco_listen(int *sock_fd, UNUSED_ATTR int flags) {
+  assert(sock_fd != NULL);
+
+  pthread_mutex_lock(&lock);
+
+  sco_socket_t *sco_socket = sco_socket_establish_locked(true, NULL, sock_fd);
+  if (sco_socket) {
+    BTM_RegForEScoEvts(sco_socket->sco_handle, connection_request_cb);
+    listen_sco_socket = sco_socket;
+  }
+
+  pthread_mutex_unlock(&lock);
+
+  return sco_socket ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
+}
+
+bt_status_t btsock_sco_connect(const bt_bdaddr_t *bd_addr, int *sock_fd, UNUSED_ATTR int flags) {
+  assert(bd_addr != NULL);
+  assert(sock_fd != NULL);
+
+  pthread_mutex_lock(&lock);
+  sco_socket_t *sco_socket = sco_socket_establish_locked(false, bd_addr, sock_fd);
+  pthread_mutex_unlock(&lock);
+
+  return (sco_socket != NULL) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
+}
+
+// Must be called with |lock| held.
+static sco_socket_t *sco_socket_establish_locked(bool is_listening, const bt_bdaddr_t *bd_addr, int *sock_fd) {
+  int pair[2] = { INVALID_FD, INVALID_FD };
+  sco_socket_t *sco_socket = NULL;
+
+  if (socketpair(AF_LOCAL, SOCK_STREAM, 0, pair) == -1) {
+    LOG_ERROR("%s unable to allocate socket pair: %s", __func__, strerror(errno));
+    goto error;
+  }
+
+  sco_socket = sco_socket_new();
+  if (!sco_socket) {
+    LOG_ERROR("%s unable to allocate new SCO socket.", __func__);
+    goto error;
+  }
+
+  tBTM_STATUS status = BTM_CreateSco((uint8_t *)bd_addr, !is_listening, sco_parameters.packet_types, &sco_socket->sco_handle, connect_completed_cb, disconnect_completed_cb);
+  if (status != BTM_CMD_STARTED) {
+    LOG_ERROR("%s unable to create SCO socket: %d", __func__, status);
+    goto error;
+  }
+
+  socket_t *socket = socket_new_from_fd(pair[1]);
+  if (!socket) {
+    LOG_ERROR("%s unable to allocate socket from file descriptor %d.", __func__, pair[1]);
+    goto error;
+  }
+
+  *sock_fd = pair[0];           // Transfer ownership of one end to caller.
+  sco_socket->socket = socket;  // Hang on to the other end.
+  list_append(sco_sockets, sco_socket);
+
+  socket_register(socket, thread_get_reactor(thread), sco_socket, socket_read_ready_cb, NULL);
+  return sco_socket;
+
+error:;
+  if (pair[0] != INVALID_FD)
+    close(pair[0]);
+  if (pair[1] != INVALID_FD)
+    close(pair[1]);
+
+  sco_socket_free_locked(sco_socket);
+  return NULL;
+}
+
+static sco_socket_t *sco_socket_new(void) {
+  sco_socket_t *sco_socket = (sco_socket_t *)calloc(1, sizeof(sco_socket_t));
+  if (sco_socket)
+    sco_socket->sco_handle = BTM_INVALID_SCO_INDEX;
+  return sco_socket;
+}
+
+// Must be called with |lock| held except during teardown when we know the socket thread
+// is no longer alive.
+static void sco_socket_free_locked(sco_socket_t *sco_socket) {
+  if (!sco_socket)
+    return;
+
+  if (sco_socket->sco_handle != BTM_INVALID_SCO_INDEX)
+    BTM_RemoveSco(sco_socket->sco_handle);
+  socket_free(sco_socket->socket);
+  free(sco_socket);
+}
+
+// Must be called with |lock| held.
+static sco_socket_t *sco_socket_find_locked(uint16_t sco_handle) {
+  for (const list_node_t *node = list_begin(sco_sockets); node != list_end(sco_sockets); node = list_next(node)) {
+    sco_socket_t *sco_socket = (sco_socket_t *)list_node(node);
+    if (sco_socket->sco_handle == sco_handle)
+      return sco_socket;
+  }
+  return NULL;
+}
+
+static void connection_request_cb(tBTM_ESCO_EVT event, tBTM_ESCO_EVT_DATA *data) {
+  assert(data != NULL);
+
+  // Don't care about change of link parameters, only connection requests.
+  if (event != BTM_ESCO_CONN_REQ_EVT)
+    return;
+
+  pthread_mutex_lock(&lock);
+
+  const tBTM_ESCO_CONN_REQ_EVT_DATA *conn_data = &data->conn_evt;
+  sco_socket_t *sco_socket = sco_socket_find_locked(conn_data->sco_inx);
+  int client_fd = INVALID_FD;
+
+  if (!sco_socket) {
+    LOG_ERROR("%s unable to find sco_socket for handle: %hu", __func__, conn_data->sco_inx);
+    goto error;
+  }
+
+  if (sco_socket != listen_sco_socket) {
+    LOG_ERROR("%s received connection request on non-listening socket handle: %hu", __func__, conn_data->sco_inx);
+    goto error;
+  }
+
+  sco_socket_t *new_sco_socket = sco_socket_establish_locked(true, NULL, &client_fd);
+  if (!new_sco_socket) {
+    LOG_ERROR("%s unable to allocate new sco_socket.", __func__);
+    goto error;
+  }
+
+  // Swap socket->sco_handle and new_socket->sco_handle
+  uint16_t temp = sco_socket->sco_handle;
+  sco_socket->sco_handle = new_sco_socket->sco_handle;
+  new_sco_socket->sco_handle = temp;
+
+  sock_connect_signal_t connect_signal;
+  connect_signal.size = sizeof(connect_signal);
+  memcpy(&connect_signal.bd_addr, conn_data->bd_addr, sizeof(bt_bdaddr_t));
+  connect_signal.channel = 0;
+  connect_signal.status = 0;
+
+  if (socket_write_and_transfer_fd(sco_socket->socket, &connect_signal, sizeof(connect_signal), client_fd) != sizeof(connect_signal)) {
+    LOG_ERROR("%s unable to send new file descriptor to listening socket.", __func__);
+    goto error;
+  }
+
+  BTM_RegForEScoEvts(listen_sco_socket->sco_handle, connection_request_cb);
+  BTM_EScoConnRsp(conn_data->sco_inx, HCI_SUCCESS, NULL);
+
+  pthread_mutex_unlock(&lock);
+  return;
+
+error:;
+  pthread_mutex_unlock(&lock);
+
+  if (client_fd != INVALID_FD)
+    close(client_fd);
+  BTM_EScoConnRsp(conn_data->sco_inx, HCI_ERR_HOST_REJECT_RESOURCES, NULL);
+}
+
+static void connect_completed_cb(uint16_t sco_handle) {
+  pthread_mutex_lock(&lock);
+
+  sco_socket_t *sco_socket = sco_socket_find_locked(sco_handle);
+  if (!sco_socket) {
+    LOG_ERROR("%s SCO socket not found on connect for handle: %hu", __func__, sco_handle);
+    goto out;
+  }
+
+  // If sco_socket->socket was closed, we should tear down because there is no app-level
+  // interest in the SCO socket.
+  if (!sco_socket->socket) {
+    BTM_RemoveSco(sco_socket->sco_handle);
+    list_remove(sco_sockets, sco_socket);
+    goto out;
+  }
+
+  sco_socket->connect_completed = true;
+
+out:;
+  pthread_mutex_unlock(&lock);
+}
+
+static void disconnect_completed_cb(uint16_t sco_handle) {
+  pthread_mutex_lock(&lock);
+
+  sco_socket_t *sco_socket = sco_socket_find_locked(sco_handle);
+  if (!sco_socket) {
+    LOG_ERROR("%s SCO socket not found on disconnect for handle: %hu", __func__, sco_handle);
+    goto out;
+  }
+
+  list_remove(sco_sockets, sco_socket);
+
+out:;
+  pthread_mutex_unlock(&lock);
+}
+
+static void socket_read_ready_cb(UNUSED_ATTR socket_t *socket, void *context) {
+  pthread_mutex_lock(&lock);
+
+  sco_socket_t *sco_socket = (sco_socket_t *)context;
+  socket_free(sco_socket->socket);
+  sco_socket->socket = NULL;
+
+  // Defer the underlying disconnect until the connection completes
+  // since the BTM code doesn't behave correctly when a disconnect
+  // request is issued while a connect is in progress. The fact that
+  // sco_socket->socket == NULL indicates to the connect callback
+  // routine that the socket is no longer desired and should be torn
+  // down.
+  if (sco_socket->connect_completed || sco_socket == listen_sco_socket) {
+    if (BTM_RemoveSco(sco_socket->sco_handle) == BTM_SUCCESS)
+      list_remove(sco_sockets, sco_socket);
+    if (sco_socket == listen_sco_socket)
+      listen_sco_socket = NULL;
+  }
+
+  pthread_mutex_unlock(&lock);
+}
diff --git a/btif/src/btif_sock_sdp.c b/btif/src/btif_sock_sdp.c
index 3352919..1fcae8f 100644
--- a/btif/src/btif_sock_sdp.c
+++ b/btif/src/btif_sock_sdp.c
@@ -1,6 +1,6 @@
 /******************************************************************************
  *
- *  Copyright (C) 2009-2012 Broadcom Corporation
+ *  Copyright (C) 2014 Google, Inc.
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
@@ -16,32 +16,20 @@
  *
  ******************************************************************************/
 
-/************************************************************************************
- *
- *  Filename:      btif_hf.c
- *
- *  Description:   Handsfree Profile Bluetooth Interface
- *
- *
- ***********************************************************************************/
+#define LOG_TAG "bt_btif_sock_sdp"
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <errno.h>
 
 #include <hardware/bluetooth.h>
 #include <hardware/bt_sock.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
 
-#define LOG_TAG "BTIF_SOCK_SDP"
 #include "btif_common.h"
 #include "btif_util.h"
-
-#include "bd.h"
-
 #include "bta_api.h"
-
-
 #include "bt_target.h"
 #include "gki.h"
 #include "hcimsgs.h"
@@ -54,507 +42,510 @@
 #include "../bta/pb/bta_pbs_int.h"
 #include "../include/bta_op_api.h"
 #include "bta_jv_api.h"
-#include <cutils/log.h>
+
+// This module provides an abstraction on top of the lower-level SDP database
+// code for registration and discovery of various bluetooth sockets.
+//
+// This code also provides for on-demand registration of "pre-registered"
+// services as a backwards compatibility function to third-party applications
+// expecting a bluez stack.
+
+// Realm Character Set -- 0 is ASCII
+#define BTA_PBS_REALM_CHARSET 0
+
+// Specifies whether or not client's user id is required during obex
+// authentication
+#define BTA_PBS_USERID_REQ FALSE
+
+static const tBTA_PBS_CFG bta_pbs_cfg = {
+  BTA_PBS_REALM_CHARSET,                          // realm_charset: Server only
+  BTA_PBS_USERID_REQ,                             // userid_req: Server only
+  (BTA_PBS_SUPF_DOWNLOAD | BTA_PBS_SURF_BROWSE),  // supported_features
+  BTA_PBS_REPOSIT_LOCAL,                          // supported_repositories
+};
+
+// object format lookup table
+#define OBEX_PUSH_NUM_FORMATS 7
+
+static const tBTA_OP_FMT bta_ops_obj_fmt[OBEX_PUSH_NUM_FORMATS] = {
+  BTA_OP_VCARD21_FMT,
+  BTA_OP_VCARD30_FMT,
+  BTA_OP_VCAL_FMT,
+  BTA_OP_ICAL_FMT,
+  BTA_OP_VNOTE_FMT,
+  BTA_OP_VMSG_FMT,
+  BTA_OP_OTHER_FMT
+};
+
+// TODO(jtgans): Figure out if we actually need this define. This is ifndef
+// defined in bt_target.h, but nowhere else, so right now, unless something
+// overrides this before bt_target.h sets it, it will always be bt_target.h's
+// version.
+#ifndef BTUI_OPS_FORMATS
+#define BTUI_OPS_FORMATS (BTA_OP_VCARD21_MASK   \
+                          | BTA_OP_VCARD30_MASK \
+                          | BTA_OP_VCAL_MASK    \
+                          | BTA_OP_ICAL_MASK    \
+                          | BTA_OP_VNOTE_MASK   \
+                          | BTA_OP_VMSG_MASK    \
+                          | BTA_OP_ANY_MASK)
+#endif
+
+/*
+ * This is horrible design - to reserve channel ID's and use them to magically
+ * link a channel number to a hard coded SDP entry.
+ *
+ * TODO: expose a prober SDP API, to avoid hacks like this, and make it possible
+ * to set useful names for the ServiceName
+ */
+#define BTA_MAP_MSG_TYPE_EMAIL    0x01
+#define BTA_MAP_MSG_TYPE_SMS_GSM  0x02
+#define BTA_MAP_MSG_TYPE_SMS_CDMA 0x04
+#define BTA_MAP_MSG_TYPE_MMS      0x08
+
+#define BTA_MAP_MAS_ID_SMSMMS 0
+#define BTA_MAP_MAS_ID_EMAIL 1
+
+// MAP 1.1
+#define BTA_MAP_DEFAULT_VERSION 0x0101
+
+typedef struct {
+  uint8_t mas_id;                  // the MAS instance id
+  const char *service_name;      // Description of the MAS instance
+  uint8_t supported_message_types; // Server supported message types - SMS/MMS/EMAIL
+} tBTA_MAP_CFG;
+
+const tBTA_MAP_CFG bta_map_cfg_sms = {
+  BTA_MAP_MAS_ID_SMSMMS,
+  "MAP SMS",
+  BTA_MAP_MSG_TYPE_SMS_GSM | BTA_MAP_MSG_TYPE_SMS_CDMA
+};
 
 #define RESERVED_SCN_PBS 19
 #define RESERVED_SCN_OPS 12
 
 #define UUID_MAX_LENGTH 16
+#define UUID_MATCHES(u1, u2) !memcmp(u1, u2, UUID_MAX_LENGTH)
 
+// Adds a protocol list and service name (if provided) to an SDP record given by
+// |sdp_handle|, and marks it as browseable. This is a shortcut for defining a
+// set of protocols that includes L2CAP, RFCOMM, and optionally OBEX. If
+// |with_obex| is |TRUE|, then an additional OBEX protocol UUID will be included
+// at the end of the protocol list.
+//
+// Returns TRUE if successful, otherwise FALSE.
+static bool create_base_record(const uint32_t sdp_handle, const char *name,
+                               const uint16_t channel, const bool with_obex) {
+  APPL_TRACE_DEBUG("create_base_record: scn: %d, name: %s, with_obex: %d",
+                   channel, name, with_obex);
 
-#define IS_UUID(u1,u2)  !memcmp(u1,u2,UUID_MAX_LENGTH)
+  // Setup the protocol list and add it.
+  tSDP_PROTOCOL_ELEM proto_list[SDP_MAX_LIST_ELEMS];
+  int num_proto_elements = with_obex ? 3 : 2;
 
+  memset(proto_list, 0, num_proto_elements * sizeof(tSDP_PROTOCOL_ELEM));
 
-#define BTM_NUM_PROTO_ELEMS 2
-static int add_sdp_by_uuid(const char *name,  const uint8_t *service_uuid, UINT16 channel)
-{
+  proto_list[0].protocol_uuid = UUID_PROTOCOL_L2CAP;
+  proto_list[0].num_params = 0;
+  proto_list[1].protocol_uuid = UUID_PROTOCOL_RFCOMM;
+  proto_list[1].num_params = 1;
+  proto_list[1].params[0] = channel;
 
-    UINT32 btm_sdp_handle;
+  if (with_obex == TRUE) {
+    proto_list[2].protocol_uuid = UUID_PROTOCOL_OBEX;
+    proto_list[2].num_params = 0;
+  }
 
-    tSDP_PROTOCOL_ELEM  proto_elem_list[BTM_NUM_PROTO_ELEMS];
+  char *stage = "protocol_list";
+  if (!SDP_AddProtocolList(sdp_handle, num_proto_elements, proto_list))
+    goto error;
 
-    /* register the service */
-    if ((btm_sdp_handle = SDP_CreateRecord()) != FALSE)
-    {
-        /*** Fill out the protocol element sequence for SDP ***/
-        proto_elem_list[0].protocol_uuid = UUID_PROTOCOL_L2CAP;
-        proto_elem_list[0].num_params = 0;
-        proto_elem_list[1].protocol_uuid = UUID_PROTOCOL_RFCOMM;
-        proto_elem_list[1].num_params = 1;
+  // Add the name to the SDP record.
+  if (name[0] != '\0') {
+    stage = "service_name";
+    if (!SDP_AddAttribute(sdp_handle, ATTR_ID_SERVICE_NAME,
+                          TEXT_STR_DESC_TYPE, (uint32_t)(strlen(name) + 1),
+                          (uint8_t *)name))
+      goto error;
+  }
 
-        proto_elem_list[1].params[0] = channel;
+  // Mark the service as browseable.
+  uint16_t list = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP;
+  stage = "browseable";
+  if (!SDP_AddUuidSequence(sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &list))
+    goto error;
 
-        if (SDP_AddProtocolList(btm_sdp_handle, BTM_NUM_PROTO_ELEMS,
-            proto_elem_list))
-        {
-            UINT8           buff[48];
-            UINT8           *p, *type_buf[1];
-            UINT8       type[1], type_len[1];
-         p = type_buf[0] = buff;
-         type[0] = UUID_DESC_TYPE;
+  APPL_TRACE_DEBUG("create_base_record: successfully created base service "
+                   "record, handle: 0x%08x, scn: %d, name: %s, with_obex: %d",
+                   sdp_handle, channel, name, with_obex);
+  return TRUE;
 
-//         UINT8_TO_BE_STREAM  (p, (UUID_DESC_TYPE << 3) | SIZE_SIXTEEN_BYTES);
-         ARRAY_TO_BE_STREAM (p, service_uuid, 16);
-            type_len[0] = 16;
-            if( SDP_AddSequence(btm_sdp_handle, (UINT16) ATTR_ID_SERVICE_CLASS_ID_LIST,
-                          1, type, type_len, type_buf) )
-//            if (SDP_AddServiceClassIdList(btm_sdp_handle, 1, &service_uuid))
-            {
-                if ((SDP_AddAttribute(btm_sdp_handle, ATTR_ID_SERVICE_NAME,
-                    TEXT_STR_DESC_TYPE, (UINT32)(strlen(name)+1),
-                    (UINT8 *)name)) )
-                {
-                    UINT16  list[1];
+error:
+  APPL_TRACE_ERROR("create_base_record: failed to create base service "
+                   "record, stage: %s, scn: %d, name: %s, with_obex: %d",
+                   stage, channel, name, with_obex);
+  return FALSE;
+}
 
-                    /* Make the service browseable */
-                    list[0] = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP;
-                    if ((SDP_AddUuidSequence (btm_sdp_handle,  ATTR_ID_BROWSE_GROUP_LIST,
-                        1, list)) )
+// Registers a service with the given |name|, |uuid|, and |channel| in the SDP
+// database as a generic L2CAP RFCOMM protocol, storing its |uuid| as a service
+// class sequence.
+static int add_sdp_by_uuid(const char *name,  const uint8_t *uuid,
+                           const uint16_t channel) {
+  APPL_TRACE_DEBUG("add_sdp_by_uuid: scn: %d, service_name: %s", channel, name);
 
-                        return btm_sdp_handle;
-                }
-            }
-        }
-    }
-    else APPL_TRACE_ERROR("failed to create sdp record, service_name:%s", name);
+  uint32_t handle = SDP_CreateRecord();
+  if (handle == 0) {
+    APPL_TRACE_ERROR("add_sdp_by_uuid: failed to create sdp record, "
+                     "scn: %d, service_name: %s", channel, name);
     return 0;
+  }
+
+  // Create the base SDP record.
+  char *stage = "create_base_record";
+  if (!create_base_record(handle, name, channel, FALSE /* with_obex */))
+    goto error;
+
+  // Convert the |uuid| into a big-endian representation and add it as a
+  // sequence.
+  uint8_t type = UUID_DESC_TYPE;
+  uint8_t type_len = UUID_MAX_LENGTH;
+  uint8_t type_buf[48];
+  // Store the address of type buf in a pointer on the stack, so we can pass
+  // a double pointer to SDP_AddSequence
+  uint8_t *type_buf_ptr = type_buf;
+
+  // Do the conversion to big-endian -- tmp is only used to iterate through the
+  // UUID array in the macro and serves no other purpose as the conversion
+  // macros are not hygenic.
+  {
+    uint8_t *tmp = type_buf;
+    ARRAY_TO_BE_STREAM(tmp, uuid, UUID_MAX_LENGTH);
+  }
+
+  stage = "service_class_sequence";
+  if (!SDP_AddSequence(handle, (uint16_t)ATTR_ID_SERVICE_CLASS_ID_LIST,
+                       1, &type, &type_len, &type_buf_ptr))
+    goto error;
+
+
+  APPL_TRACE_DEBUG("add_sdp_by_uuid: service registered successfully, "
+                   "service_name: %s, handle: 0x%08x", name, handle);
+  return handle;
+
+error:
+  SDP_DeleteRecord(handle);
+  APPL_TRACE_ERROR("add_sdp_by_uuid: failed to register service "
+                   "stage: %s, service_name: %s", stage, name);
+  return 0;
 }
 
+// Registers a service with the given |name| and |channel| in the SDP
+// database as a PBAP protocol.
+static int add_pbap_sdp(const char *name, const int channel) {
+  APPL_TRACE_DEBUG("add_pbap_sdp: scn %d, service_name %s", channel, name);
 
-/* Realm Character Set */
-#define BTA_PBS_REALM_CHARSET   0       /* ASCII */
+  uint32_t handle = SDP_CreateRecord();
+  if (handle == 0) {
+    APPL_TRACE_ERROR("add_pbap_sdp: failed to create sdp record, "
+                     "service_name: %s", name);
+    return 0;
+  }
 
-/* Specifies whether or not client's user id is required during obex authentication */
-#define BTA_PBS_USERID_REQ      FALSE
-extern const tBTA_PBS_CFG bta_pbs_cfg;
-const tBTA_PBS_CFG bta_pbs_cfg =
-{
-    BTA_PBS_REALM_CHARSET,      /* Server only */
-    BTA_PBS_USERID_REQ,         /* Server only */
-    (BTA_PBS_SUPF_DOWNLOAD | BTA_PBS_SURF_BROWSE),
-    BTA_PBS_REPOSIT_LOCAL,
-};
+  // Create the base SDP record.
+  char *stage = "create_base_record";
+  if (!create_base_record(handle, name, channel, TRUE /* with_obex */))
+    goto error;
 
-static int add_pbap_sdp(const char* p_service_name, int scn)
-{
+  // Add service class
+  uint16_t service = UUID_SERVCLASS_PBAP_PSE;
+  stage = "service_class";
+  if (!SDP_AddServiceClassIdList(handle, 1, &service))
+    goto error;
 
-    tSDP_PROTOCOL_ELEM  protoList [3];
-    UINT16              pbs_service = UUID_SERVCLASS_PBAP_PSE;
-    UINT16              browse = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP;
-    BOOLEAN             status = FALSE;
-    UINT32              sdp_handle = 0;
-    tBTA_PBS_CFG *p_bta_pbs_cfg = (tBTA_PBS_CFG *)&bta_pbs_cfg;
+  // Add in the phone access descriptor
+  stage = "profile_descriptor_list";
+  if (!SDP_AddProfileDescriptorList(handle,
+                                    UUID_SERVCLASS_PHONE_ACCESS,
+                                    BTA_PBS_DEFAULT_VERSION))
+    goto error;
 
-    APPL_TRACE_DEBUG("add_pbap_sdd:scn %d, service name %s", scn, p_service_name);
+  // Set up our supported repositories
+  stage = "supported_repositories";
+  if (!SDP_AddAttribute(handle, ATTR_ID_SUPPORTED_REPOSITORIES, UINT_DESC_TYPE,
+                        1, (uint8_t*)&bta_pbs_cfg.supported_repositories))
+    goto error;
 
-    if ((sdp_handle = SDP_CreateRecord()) == 0)
-    {
-        APPL_TRACE_ERROR("PBS SDP: Unable to register PBS Service");
-        return sdp_handle;
-    }
+  // Notify the system that we've got a new service class UUID.
+  bta_sys_add_uuid(UUID_SERVCLASS_PBAP_PSE);
+  APPL_TRACE_DEBUG("add_pbap_sdp: service registered successfully, "
+                   "service_name: %s, handle: 0x%08x", name, handle);
 
-    /* add service class */
-    if (SDP_AddServiceClassIdList(sdp_handle, 1, &pbs_service))
-    {
-        memset( protoList, 0 , 3*sizeof(tSDP_PROTOCOL_ELEM) );
-        /* add protocol list, including RFCOMM scn */
-        protoList[0].protocol_uuid = UUID_PROTOCOL_L2CAP;
-        protoList[0].num_params = 0;
-        protoList[1].protocol_uuid = UUID_PROTOCOL_RFCOMM;
-        protoList[1].num_params = 1;
-        protoList[1].params[0] = scn;
-        protoList[2].protocol_uuid = UUID_PROTOCOL_OBEX;
-        protoList[2].num_params = 0;
+  return handle;
 
-        if (SDP_AddProtocolList(sdp_handle, 3, protoList))
-        {
-            status = TRUE;  /* All mandatory fields were successful */
-
-            /* optional:  if name is not "", add a name entry */
-            if (*p_service_name != '\0')
-                SDP_AddAttribute(sdp_handle,
-                                 (UINT16)ATTR_ID_SERVICE_NAME,
-                                 (UINT8)TEXT_STR_DESC_TYPE,
-                                 (UINT32)(strlen(p_service_name) + 1),
-                                 (UINT8 *)p_service_name);
-
-            /* Add in the Bluetooth Profile Descriptor List */
-            SDP_AddProfileDescriptorList(sdp_handle,
-                                             UUID_SERVCLASS_PHONE_ACCESS,
-                                             BTA_PBS_DEFAULT_VERSION);
-
-        } /* end of setting mandatory protocol list */
-    } /* end of setting mandatory service class */
-
-    /* add supported feature and repositories */
-    if (status)
-    {
-        SDP_AddAttribute(sdp_handle, ATTR_ID_SUPPORTED_REPOSITORIES, UINT_DESC_TYPE,
-                  (UINT32)1, (UINT8*)&p_bta_pbs_cfg->supported_repositories);
-
-        /* Make the service browseable */
-        SDP_AddUuidSequence (sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse);
-    }
-
-    if (!status)
-    {
-        SDP_DeleteRecord(sdp_handle);
-        sdp_handle = 0;
-        APPL_TRACE_ERROR("bta_pbs_sdp_register FAILED");
-    }
-    else
-    {
-        bta_sys_add_uuid(pbs_service);  /* UUID_SERVCLASS_PBAP_PSE */
-        APPL_TRACE_DEBUG("PBS:  SDP Registered (handle 0x%08x)", sdp_handle);
-    }
-
-    return sdp_handle;
+error:
+  SDP_DeleteRecord(handle);
+  APPL_TRACE_ERROR("add_pbap_sdp: failed to register PBAP service, stage: %s, "
+                   "service_name: %s", stage, name);
+  return 0;
 }
 
-/* This is horrible design - to reserve channel ID's and use them to magically link
- * a channel number to a hard coded SDP entry.
- * TODO: expose a prober SDP API, to avoid hacks like this, and make it possible
- *        to set useful names for the ServiceName */
+// Registers a service with the given |name| and |channel| in the SDP database
+// as a MAP protocol.
+static int add_maps_sdp(const char *name, const int channel) {
+  APPL_TRACE_DEBUG("add_maps_sdp: scn %d, service_name %s", channel,
+                   name);
 
-#define BTA_MAPS_DEFAULT_VERSION 0x0101 /* MAP 1.1 */
-typedef struct
-{
-    UINT8       mas_id;                 /* the MAS instance id */
-    const char* service_name;          /* Description of the MAS instance */
-    UINT8       supported_message_types;/* Server supported message types - SMS/MMS/EMAIL */
-} tBTA_MAPS_CFG;
+  uint32_t handle = SDP_CreateRecord();
+  if (handle == 0) {
+    APPL_TRACE_ERROR("add_maps_sdp: failed to create sdp record, "
+                     "service_name: %s", name);
+    return 0;
+  }
 
-static int add_maps_sdp(const char* p_service_name, int scn)
-{
+  // Create the base SDP record.
+  char *stage = "create_base_record";
+  if (!create_base_record(handle, name, channel, TRUE /* with_obex */))
+    goto error;
 
-    tSDP_PROTOCOL_ELEM  protoList [3];
-    UINT16              service = UUID_SERVCLASS_MESSAGE_ACCESS;
-    UINT16              browse = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP;
-    BOOLEAN             status = FALSE;
-    UINT32              sdp_handle = 0;
-    char                map_handle_buf[3];
-    char                map_type_buf[3];
-    char                *map_name = (char*)&(p_service_name[4]);
-    tBTA_MAPS_CFG       bta_maps_cfg;
-    tBTA_MAPS_CFG       *p_bta_maps_cfg;
-    APPL_TRACE_DEBUG("add_maps_sdp: scn %d, service name %s", scn, p_service_name);
+  // add service class
+  uint16_t service = UUID_SERVCLASS_MESSAGE_ACCESS;
+  stage = "service_class";
+  if (!SDP_AddServiceClassIdList(handle, 1, &service))
+    goto error;
 
-    /* Service name for map is build as XX|YY|name where XX and YY is
-     * MasId and Type flag as 2byte hex as string */
-    map_handle_buf[0] = p_service_name[0];
-    map_handle_buf[1] = p_service_name[1];
-    map_handle_buf[2] = '\0';
+  // TODO: To add support for EMAIL set below depending on the scn to either
+  // SMS or Email
+  const tBTA_MAP_CFG *bta_map_cfg = &bta_map_cfg_sms;
 
-    map_type_buf[0]   = p_service_name[2];
-    map_type_buf[1]   = p_service_name[3];
-    map_type_buf[2]   = '\0';
+  // Add in the Bluetooth Profile Descriptor List
+  stage = "profile_descriptor_list";
+  if (!SDP_AddProfileDescriptorList(handle,
+                                    UUID_SERVCLASS_MAP_PROFILE,
+                                    BTA_MAP_DEFAULT_VERSION))
+    goto error;
 
-    p_bta_maps_cfg = &bta_maps_cfg;
-    p_bta_maps_cfg->mas_id = (UINT16)strtol(&map_handle_buf[0],NULL, 16);
-    p_bta_maps_cfg->supported_message_types = (UINT16)strtol(&map_type_buf[0],NULL, 16);
-    p_bta_maps_cfg->service_name = map_name;
+  stage = "mas_instance_id";
+  if (!SDP_AddAttribute(handle, ATTR_ID_MAS_INSTANCE_ID, UINT_DESC_TYPE,
+                        (uint32_t)1, (uint8_t*)(&bta_map_cfg->mas_id)))
+    goto error;
 
-    APPL_TRACE_DEBUG("  service_name: %s, mas-id: %d, flags: 0x%02x",
-            p_bta_maps_cfg->service_name, p_bta_maps_cfg->mas_id,
-            p_bta_maps_cfg->supported_message_types);
+  stage = "support_message_types";
+  if (!SDP_AddAttribute(handle, ATTR_ID_SUPPORTED_MSG_TYPE, UINT_DESC_TYPE,
+                        (uint32_t)1,
+                        (uint8_t*)(&bta_map_cfg->supported_message_types)))
+    goto error;
 
-    if ((sdp_handle = SDP_CreateRecord()) == 0)
-    {
-        APPL_TRACE_ERROR("MAPS SDP: Unable to register MAPS Service");
-        return sdp_handle;
-    }
+  // Notify the system that we've got a new service class UUID.
+  bta_sys_add_uuid(service);  // UUID_SERVCLASS_MESSAGE_ACCESS
+  APPL_TRACE_DEBUG("ad_maps_sdp: service registered successfully, "
+                   "service_name: %s, handle 0x%08x)", name, handle);
 
-    /* add service class */
-    if (SDP_AddServiceClassIdList(sdp_handle, 1, &service))
-    {
-        memset( protoList, 0 , 3*sizeof(tSDP_PROTOCOL_ELEM) );
-        /* add protocol list, including RFCOMM scn */
-        protoList[0].protocol_uuid = UUID_PROTOCOL_L2CAP;
-        protoList[0].num_params = 0;
-        protoList[1].protocol_uuid = UUID_PROTOCOL_RFCOMM;
-        protoList[1].num_params = 1;
-        protoList[1].params[0] = scn;
-        protoList[2].protocol_uuid = UUID_PROTOCOL_OBEX;
-        protoList[2].num_params = 0;
+  return handle;
 
-        if (SDP_AddProtocolList(sdp_handle, 3, protoList))
-        {
-            status = TRUE;  /* All mandatory fields were successful */
-
-            /* optional:  if name is not "", add a name entry */
-            SDP_AddAttribute(sdp_handle,
-                            (UINT16)ATTR_ID_SERVICE_NAME,
-                            (UINT8)TEXT_STR_DESC_TYPE,
-                            (UINT32)(strlen(p_bta_maps_cfg->service_name) + 1),
-                            (UINT8 *)p_bta_maps_cfg->service_name);
-
-            /* Add in the Bluetooth Profile Descriptor List */
-            SDP_AddProfileDescriptorList(sdp_handle,
-                                             UUID_SERVCLASS_MAP_PROFILE,
-                                             BTA_MAPS_DEFAULT_VERSION);
-
-        } /* end of setting mandatory protocol list */
-    } /* end of setting mandatory service class */
-
-    /* add supported feature and repositories */
-    if (status)
-    {
-        SDP_AddAttribute(sdp_handle, ATTR_ID_MAS_INSTANCE_ID, UINT_DESC_TYPE,
-                  (UINT32)1, (UINT8*)&p_bta_maps_cfg->mas_id);
-        SDP_AddAttribute(sdp_handle, ATTR_ID_SUPPORTED_MSG_TYPE, UINT_DESC_TYPE,
-                  (UINT32)1, (UINT8*)&p_bta_maps_cfg->supported_message_types);
-
-        /* Make the service browseable */
-        SDP_AddUuidSequence (sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse);
-    }
-
-    if (!status)
-    {
-        SDP_DeleteRecord(sdp_handle);
-        sdp_handle = 0;
-        APPL_TRACE_ERROR("bta_mass_sdp_register FAILED");
-    }
-    else
-    {
-        bta_sys_add_uuid(service);  /* UUID_SERVCLASS_MESSAGE_ACCESS */
-        APPL_TRACE_DEBUG("MAPSS:  SDP Registered (handle 0x%08x)", sdp_handle);
-    }
-
-    return sdp_handle;
+error:
+  SDP_DeleteRecord(handle);
+  APPL_TRACE_ERROR("add_maps_sdp: failed to register MAP service, stage: %s, "
+                   "service_name: %s", stage, name);
+  return 0;
 }
 
+// Registers a service with the given |name| and |channel| as an OBEX Push
+// protocol.
+static int add_ops_sdp(const char *name, const int channel) {
+  APPL_TRACE_DEBUG("add_ops_sdp: scn %d, service_name %s", channel, name);
 
-/* object format lookup table */
-static const tBTA_OP_FMT bta_ops_obj_fmt[] =
-{
-    BTA_OP_VCARD21_FMT,
-    BTA_OP_VCARD30_FMT,
-    BTA_OP_VCAL_FMT,
-    BTA_OP_ICAL_FMT,
-    BTA_OP_VNOTE_FMT,
-    BTA_OP_VMSG_FMT,
-    BTA_OP_OTHER_FMT
-};
+  uint32_t handle = SDP_CreateRecord();
+  if (handle == 0) {
+    APPL_TRACE_ERROR("add_ops_sdp: failed to create sdp record, "
+                     "service_name: %s", name);
+    return 0;
+  }
 
-#define BTA_OPS_NUM_FMTS        7
-#define BTA_OPS_PROTOCOL_COUNT  3
+  // Create the base SDP record.
+  char *stage = "create_base_record";
+  if (!create_base_record(handle, name, channel, TRUE /* with_obex */))
+    goto error;
 
-#ifndef BTUI_OPS_FORMATS
-#define BTUI_OPS_FORMATS            (BTA_OP_VCARD21_MASK | BTA_OP_VCARD30_MASK | \
-                                         BTA_OP_VCAL_MASK | BTA_OP_ICAL_MASK | \
-                                         BTA_OP_VNOTE_MASK | BTA_OP_VMSG_MASK | \
-                                         BTA_OP_ANY_MASK )
-#endif
+  // Add service class.
+  stage = "service_class";
+  uint16_t service = UUID_SERVCLASS_OBEX_OBJECT_PUSH;
+  if (!SDP_AddServiceClassIdList(handle, 1, &service))
+    goto error;
 
-static int add_ops_sdp(const char *p_service_name,int scn)
-{
+  // Add the OBEX push profile descriptor.
+  stage = "profile_descriptor_list";
+  if (!SDP_AddProfileDescriptorList(handle, UUID_SERVCLASS_OBEX_OBJECT_PUSH,
+                                    0x0100))
+    goto error;
 
+  // Add sequence for supported types.
+  uint8_t desc_type[OBEX_PUSH_NUM_FORMATS];
+  uint8_t type_len[OBEX_PUSH_NUM_FORMATS];
+  uint8_t *type_value[OBEX_PUSH_NUM_FORMATS];
+  uint8_t j = 0;
 
-    tSDP_PROTOCOL_ELEM  protoList [BTA_OPS_PROTOCOL_COUNT];
-    UINT16      servclass = UUID_SERVCLASS_OBEX_OBJECT_PUSH;
-    int         i, j;
-    tBTA_UTL_COD cod;
-    UINT8       desc_type[BTA_OPS_NUM_FMTS];
-    UINT8       type_len[BTA_OPS_NUM_FMTS];
-    UINT8       *type_value[BTA_OPS_NUM_FMTS];
-    UINT16      browse;
-    UINT32 sdp_handle;
-    tBTA_OP_FMT_MASK    formats = BTUI_OPS_FORMATS;
-
-    APPL_TRACE_DEBUG("scn %d, service name %s", scn, p_service_name);
-
-    sdp_handle = SDP_CreateRecord();
-
-    /* add service class */
-    if (SDP_AddServiceClassIdList(sdp_handle, 1, &servclass))
-    {
-        /* add protocol list, including RFCOMM scn */
-        protoList[0].protocol_uuid = UUID_PROTOCOL_L2CAP;
-        protoList[0].num_params = 0;
-        protoList[1].protocol_uuid = UUID_PROTOCOL_RFCOMM;
-        protoList[1].num_params = 1;
-        protoList[1].params[0] = scn;
-        protoList[2].protocol_uuid = UUID_PROTOCOL_OBEX;
-        protoList[2].num_params = 0;
-
-        if (SDP_AddProtocolList(sdp_handle, BTA_OPS_PROTOCOL_COUNT, protoList))
-        {
-            SDP_AddAttribute(sdp_handle,
-               (UINT16)ATTR_ID_SERVICE_NAME,
-                (UINT8)TEXT_STR_DESC_TYPE,
-                (UINT32)(strlen(p_service_name) + 1),
-                (UINT8 *)p_service_name);
-
-            SDP_AddProfileDescriptorList(sdp_handle,
-                UUID_SERVCLASS_OBEX_OBJECT_PUSH,
-                0x0100);
-        }
+  for (int i = 0; i < OBEX_PUSH_NUM_FORMATS; i++) {
+    if ((BTUI_OPS_FORMATS >> i) & 1) {
+      type_value[j] = (uint8_t*)(&bta_ops_obj_fmt[i]);
+      desc_type[j] = UINT_DESC_TYPE;
+      type_len[j++] = 1;
     }
+  }
 
-    /* Make the service browseable */
-    browse = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP;
-    SDP_AddUuidSequence (sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse);
+  stage = "supported_types";
+  if (!SDP_AddSequence(handle, (uint16_t)ATTR_ID_SUPPORTED_FORMATS_LIST,
+                       j, desc_type, type_len, type_value))
+    goto error;
 
-    /* add sequence for supported types */
-    for (i = 0, j = 0; i < BTA_OPS_NUM_FMTS; i++)
-    {
-        if ((formats >> i) & 1)
-        {
-            type_value[j] = (UINT8 *) &bta_ops_obj_fmt[i];
-            desc_type[j] = UINT_DESC_TYPE;
-            type_len[j++] = 1;
-        }
-    }
+  // Set class of device.
+  tBTA_UTL_COD cod;
+  cod.service = BTM_COD_SERVICE_OBJ_TRANSFER;
+  stage = "class_of_device";
+  if (!utl_set_device_class(&cod, BTA_UTL_SET_COD_SERVICE_CLASS))
+    goto error;
 
-    SDP_AddSequence(sdp_handle, (UINT16) ATTR_ID_SUPPORTED_FORMATS_LIST,
-        (UINT8) j, desc_type, type_len, type_value);
+  // Notify the system that we've got a new service class UUID.
+  bta_sys_add_uuid(UUID_SERVCLASS_OBEX_OBJECT_PUSH);
+  APPL_TRACE_DEBUG("ad_maps_sdp: service registered successfully, "
+                   "service_name: %s, handle 0x%08x)", name, handle);
 
-    /* set class of device */
-    cod.service = BTM_COD_SERVICE_OBJ_TRANSFER;
-    utl_set_device_class(&cod, BTA_UTL_SET_COD_SERVICE_CLASS);
+  return handle;
 
-    bta_sys_add_uuid(servclass); /* UUID_SERVCLASS_OBEX_OBJECT_PUSH */
-
-    return sdp_handle;
-}
-#define SPP_NUM_PROTO_ELEMS 2
-static int add_spp_sdp(const char *service_name, int scn)
-{
-    UINT16 serviceclassid = UUID_SERVCLASS_SERIAL_PORT;
-    tSDP_PROTOCOL_ELEM  proto_elem_list[SPP_NUM_PROTO_ELEMS];
-    int              sdp_handle;
-
-    APPL_TRACE_DEBUG("scn %d, service name %s", scn, service_name);
-
-    /* register the service */
-    if ((sdp_handle = SDP_CreateRecord()) != FALSE)
-    {
-        /*** Fill out the protocol element sequence for SDP ***/
-        proto_elem_list[0].protocol_uuid = UUID_PROTOCOL_L2CAP;
-        proto_elem_list[0].num_params = 0;
-        proto_elem_list[1].protocol_uuid = UUID_PROTOCOL_RFCOMM;
-        proto_elem_list[1].num_params = 1;
-
-        proto_elem_list[1].params[0] = scn;
-
-        if (SDP_AddProtocolList(sdp_handle, SPP_NUM_PROTO_ELEMS, proto_elem_list))
-        {
-            if (SDP_AddServiceClassIdList(sdp_handle, 1, &serviceclassid))
-            {
-                if ((SDP_AddAttribute(sdp_handle, ATTR_ID_SERVICE_NAME,
-                                TEXT_STR_DESC_TYPE, (UINT32)(strlen(service_name)+1),
-                                (UINT8 *)service_name)))
-                {
-                    UINT16  list[1];
-                    /* Make the service browseable */
-                    list[0] = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP;
-                    SDP_AddUuidSequence (sdp_handle,  ATTR_ID_BROWSE_GROUP_LIST,
-                                    1, list);
-                }
-            }
-        }
-    }
-    return sdp_handle;
+error:
+  SDP_DeleteRecord(handle);
+  APPL_TRACE_ERROR("add_ops_sdp: failed to register OPS service, "
+                   "stage: %s, service_name: %s", stage, name);
+  return 0;
 }
 
+// Registers a service with the given |name| and |channel| as a serial port
+// profile protocol.
+static int add_spp_sdp(const char *name, const int channel) {
+  APPL_TRACE_DEBUG("add_spp_sdp: scn %d, service_name %s", channel, name);
 
-static int add_rfc_sdp_by_uuid(const char* name, const uint8_t* uuid, int scn)
-{
-    int handle = 0;
+  int handle = SDP_CreateRecord();
+  if (handle == 0) {
+    APPL_TRACE_ERROR("add_spp_sdp: failed to create sdp record, "
+                     "service_name: %s", name);
+    return 0;
+  }
 
-    APPL_TRACE_DEBUG("name:%s, scn:%d", name, scn);
+  // Create the base SDP record.
+  char *stage = "create_base_record";
+  if (!create_base_record(handle, name, channel, FALSE /* with_obex */))
+    goto error;
 
-    /*
-        Bluetooth Socket API relies on having preregistered bluez sdp records for HSAG, HFAG, OPP & PBAP
-        that are mapped to rc chan 10, 11,12 & 19. Today HSAG and HFAG is routed to BRCM AG and are not
-        using BT socket API so for now we will need to support OPP and PBAP to enable 3rd party developer
-        apps running on BRCM Android.
+  uint16_t service = UUID_SERVCLASS_SERIAL_PORT;
+  stage = "service_class";
+  if (!SDP_AddServiceClassIdList(handle, 1, &service))
+    goto error;
 
-        To do this we will check the UUID for the requested service and mimic the SDP records of bluez
-        upon reception.  See functions add_opush() and add_pbap() in sdptool.c for actual records
-    */
+  APPL_TRACE_DEBUG("add_spp_sdp: service registered successfully, "
+                   "service_name: %s, handle 0x%08x)", name, handle);
 
-    /* special handling for preregistered bluez services (OPP, PBAP) that we need to mimic */
+  return handle;
 
-    int final_scn = get_reserved_rfc_channel(uuid);
-    if (final_scn == -1)
-    {
-        final_scn=scn;
-    }
-    if (IS_UUID(UUID_OBEX_OBJECT_PUSH,uuid))
-    {
-        handle = add_ops_sdp(name,final_scn);
-    }
-    else if (IS_UUID(UUID_PBAP_PSE,uuid))
-    {
-        handle = add_pbap_sdp(name, final_scn); //PBAP Server is always 19
-    }
-    else if (IS_UUID(UUID_MAPS_MAS,uuid))
-    {
-        handle = add_maps_sdp(name, final_scn); //MAP Server is always 19
-    }
-    else if (IS_UUID(UUID_SPP, uuid))
-    {
-        handle = add_spp_sdp(name, final_scn);
-    }
-    else
-    {
-        handle = add_sdp_by_uuid(name, uuid, final_scn);
-    }
-    return handle;
+error:
+  SDP_DeleteRecord(handle);
+  APPL_TRACE_ERROR("add_spp_sdp: failed to register SPP service, "
+                   "stage: %s, service_name: %s", stage, name);
+  return 0;
 }
 
-BOOLEAN is_reserved_rfc_channel(int scn)
-{
-    switch(scn)
-    {
-        case RESERVED_SCN_PBS:
-        case RESERVED_SCN_OPS:
-            return TRUE;
-    }
-    return FALSE;
+// Adds an RFCOMM SDP record for a service with the given |name|, |uuid|, and
+// |channel|. This function attempts to identify the type of the service based
+// upon its |uuid|, and will override the |channel| with a reserved channel
+// number if the |uuid| matches one of the preregistered bluez SDP records.
+static int add_rfc_sdp_by_uuid(const char *name, const uint8_t *uuid,
+                               const int channel) {
+  APPL_TRACE_DEBUG("add_rfc_sdp_by_uuid: service_name: %s, channel: %d", name,
+                   channel);
+
+  /*
+   * Bluetooth Socket API relies on having preregistered bluez sdp records for
+   * HSAG, HFAG, OPP & PBAP that are mapped to rc chan 10, 11,12 & 19. Today
+   * HSAG and HFAG is routed to BRCM AG and are not using BT socket API so for
+   * now we will need to support OPP and PBAP to enable 3rd party developer apps
+   * running on BRCM Android.
+   *
+   * To do this we will check the UUID for the requested service and mimic the
+   * SDP records of bluez upon reception.  See functions add_opush() and
+   * add_pbap() in sdptool.c for actual records.
+   */
+
+  int final_channel = get_reserved_rfc_channel(uuid);
+
+  if (final_channel == -1) {
+    final_channel = channel;
+  }
+
+  int handle = 0;
+
+  if (UUID_MATCHES(UUID_OBEX_OBJECT_PUSH, uuid)) {
+    handle = add_ops_sdp(name, final_channel);
+  } else if (UUID_MATCHES(UUID_PBAP_PSE,uuid)) {
+    // PBAP Server is always channel 19
+    handle = add_pbap_sdp(name, final_channel);
+  } else if (UUID_MATCHES(UUID_SPP, uuid)) {
+    handle = add_spp_sdp(name, final_channel);
+  } else if (UUID_MATCHES(UUID_MAPS_MAS,uuid)) {
+    // MAP Server is always channel 19
+    handle = add_maps_sdp(name, final_channel);
+  } else {
+    handle = add_sdp_by_uuid(name, uuid, final_channel);
+  }
+
+  return handle;
 }
 
+bool is_reserved_rfc_channel(const int channel) {
+  switch(channel) {
+    case RESERVED_SCN_PBS:
+    case RESERVED_SCN_OPS:
+      return TRUE;
+  }
 
-int get_reserved_rfc_channel (const uint8_t* uuid)
-{
-    if (IS_UUID(UUID_PBAP_PSE,uuid))
-    {
-      return RESERVED_SCN_PBS;
-    }
-    else if (IS_UUID(UUID_OBEX_OBJECT_PUSH,uuid))
-    {
-      return RESERVED_SCN_OPS;
-    }
-    return -1;
+  return FALSE;
 }
 
-int add_rfc_sdp_rec(const char* name, const uint8_t* uuid, int scn)
-{
-    int sdp_handle = 0;
-    if(is_uuid_empty(uuid))
-    {
-        switch(scn)
-        {
-            case RESERVED_SCN_PBS: // PBAP Reserved port
-                uuid = UUID_PBAP_PSE;
-                break;
-             case RESERVED_SCN_OPS:
-                uuid = UUID_OBEX_OBJECT_PUSH;
-                break;
-            default:
-                uuid = UUID_SPP;
-                break;
-        }
+int get_reserved_rfc_channel(const uint8_t *uuid) {
+  if (UUID_MATCHES(UUID_PBAP_PSE, uuid)) {
+    return RESERVED_SCN_PBS;
+  } else if (UUID_MATCHES(UUID_OBEX_OBJECT_PUSH, uuid)) {
+    return RESERVED_SCN_OPS;
+  }
+
+  return -1;
+}
+
+// Adds an SDP record to the SDP database using the given |name|, |uuid|, and
+// |channel|. Note that if the |uuid| is empty, the |uuid| will be set based
+// upon the |channel| passed in.
+int add_rfc_sdp_rec(const char *name, const uint8_t *uuid, const int channel) {
+  if (is_uuid_empty(uuid)) {
+    switch(channel) {
+      case RESERVED_SCN_PBS: // PBAP Reserved port
+        uuid = UUID_PBAP_PSE;
+        break;
+
+      case RESERVED_SCN_OPS:
+        uuid = UUID_OBEX_OBJECT_PUSH;
+        break;
+
+      default:
+        uuid = UUID_SPP;
+        break;
     }
-    sdp_handle = add_rfc_sdp_by_uuid(name, uuid, scn);
-    return sdp_handle;
+  }
+
+  return add_rfc_sdp_by_uuid(name, uuid, channel);
 }
 
-void del_rfc_sdp_rec(int handle)
-{
-    APPL_TRACE_DEBUG("del_rfc_sdp_rec: handle:0x%x", handle);
-    if(handle != -1 && handle != 0)
-        BTA_JvDeleteRecord( handle );
-}
+// Deletes an SDP record with the given |handle|.
+void del_rfc_sdp_rec(int handle) {
+  APPL_TRACE_DEBUG("del_rfc_sdp_rec: handle:0x%x", handle);
 
+  if ((handle != -1) && (handle != 0))
+    BTA_JvDeleteRecord(handle);
+}
diff --git a/btif/src/btif_sock_thread.c b/btif/src/btif_sock_thread.c
index 6ae45bd..fc74089 100644
--- a/btif/src/btif_sock_thread.c
+++ b/btif/src/btif_sock_thread.c
@@ -48,18 +48,16 @@
 #include <cutils/sockets.h>
 #include <alloca.h>
 
-#define LOG_TAG "BTIF_SOCK"
+#define LOG_TAG "bt_btif_sock"
 #include "btif_common.h"
 #include "btif_util.h"
 
-#include "bd.h"
 
 #include "bta_api.h"
 #include "btif_sock.h"
 #include "btif_sock_thread.h"
 #include "btif_sock_util.h"
 
-#include <cutils/log.h>
 #define asrt(s) if(!(s)) APPL_TRACE_ERROR("## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
 #define print_events(events) do { \
     APPL_TRACE_DEBUG("print poll event:%x", events); \
@@ -82,7 +80,8 @@
 #define CMD_WAKEUP       1
 #define CMD_EXIT         2
 #define CMD_ADD_FD       3
-#define CMD_USER_PRIVATE 4
+#define CMD_REMOVE_FD    4
+#define CMD_USER_PRIVATE 5
 
 typedef struct {
     struct pollfd pfd;
@@ -254,6 +253,24 @@
     APPL_TRACE_DEBUG("adding fd:%d, flags:0x%x", fd, flags);
     return send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd);
 }
+
+bool btsock_thread_remove_fd_and_close(int thread_handle, int fd)
+{
+    if (thread_handle < 0 || thread_handle >= MAX_THREAD)
+    {
+        APPL_TRACE_ERROR("%s invalid thread handle: %d", __func__, thread_handle);
+        return false;
+    }
+    if (fd == -1)
+    {
+        APPL_TRACE_ERROR("%s invalid file descriptor.", __func__);
+        return false;
+    }
+
+    sock_cmd_t cmd = {CMD_REMOVE_FD, fd, 0, 0, 0};
+    return send(ts[thread_handle].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd);
+}
+
 int btsock_thread_post_cmd(int h, int type, const unsigned char* data, int size, uint32_t user_id)
 {
     if(h < 0 || h >= MAX_THREAD)
@@ -421,6 +438,18 @@
         case CMD_ADD_FD:
             add_poll(h, cmd.fd, cmd.type, cmd.flags, cmd.user_id);
             break;
+        case CMD_REMOVE_FD:
+            for (int i = 1; i < MAX_POLL; ++i)
+            {
+                poll_slot_t *poll_slot = &ts[h].ps[i];
+                if (poll_slot->pfd.fd == cmd.fd)
+                {
+                    remove_poll(h, poll_slot, poll_slot->flags);
+                    break;
+                }
+            }
+            close(cmd.fd);
+            break;
         case CMD_WAKEUP:
             break;
         case CMD_USER_PRIVATE:
diff --git a/btif/src/btif_sock_util.c b/btif/src/btif_sock_util.c
index 8e016e2..ee49eeb 100644
--- a/btif/src/btif_sock_util.c
+++ b/btif/src/btif_sock_util.c
@@ -45,7 +45,7 @@
 #include <netinet/tcp.h>
 
 
-#define LOG_TAG "BTIF_SOCK"
+#define LOG_TAG "bt_btif_sock"
 #include "btif_common.h"
 #include "btif_util.h"
 
@@ -63,6 +63,7 @@
 #include "bta_jv_api.h"
 #include "bta_jv_co.h"
 #include "port_api.h"
+#include "osi/include/log.h"
 
 #define asrt(s) if(!(s)) BTIF_TRACE_ERROR("## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
 
@@ -186,7 +187,7 @@
     char *line;
     int i, j, addr;
     const int width = 16;
-    ALOGD("%s, size:%d, dump started {", title, size);
+    LOG_DEBUG("%s, size:%d, dump started {", title, size);
     if(size <= 0)
         return;
     //write offset
@@ -254,6 +255,6 @@
         //output the line
         PRINT(line_buff);
     }
-    ALOGD("%s, size:%d, dump ended }", title, size);
+    LOG_DEBUG("%s, size:%d, dump ended }", title, size);
 }
 
diff --git a/btif/src/btif_storage.c b/btif/src/btif_storage.c
index d9898cb..2924a2a 100644
--- a/btif/src/btif_storage.c
+++ b/btif/src/btif_storage.c
@@ -36,19 +36,18 @@
 
 #include <hardware/bluetooth.h>
 #include "btif_config.h"
-#define LOG_TAG "BTIF_STORAGE"
+#define LOG_TAG "bt_btif_storage"
 
 #include "btif_api.h"
 #include "btif_storage.h"
 #include "btif_util.h"
-#include "bd.h"
-#include "config.h"
+#include "btcore/include/bdaddr.h"
+#include "osi/include/config.h"
 #include "gki.h"
-#include "osi.h"
+#include "osi/include/osi.h"
 #include "bta_hh_api.h"
 #include "btif_hh.h"
-
-#include <cutils/log.h>
+#include "osi/include/log.h"
 
 /************************************************************************************
 **  Constants & Macros
@@ -175,7 +174,7 @@
 **  Internal Functions
 ************************************************************************************/
 
-bt_status_t btif_in_fetch_bonded_ble_device(char *remote_bd_addr,int add,
+bt_status_t btif_in_fetch_bonded_ble_device(const char *remote_bd_addr,int add,
                                               btif_bonded_devices_t *p_bonded_devices);
 bt_status_t btif_storage_get_remote_addr_type(bt_bdaddr_t *remote_bd_addr,
                                               int *addr_type);
@@ -219,7 +218,7 @@
 {
     bdstr_t bdstr = {0};
     if(remote_bd_addr)
-        bd2str(remote_bd_addr, &bdstr);
+        bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
     BTIF_TRACE_DEBUG("in, bd addr:%s, prop type:%d, len:%d", bdstr, prop->type, prop->len);
     char value[1024];
     if(prop->len <= 0 || prop->len > (int)sizeof(value) - 1)
@@ -230,20 +229,16 @@
     switch(prop->type)
     {
        case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
-            btif_config_set_int("Remote", bdstr,
+            btif_config_set_int(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_DEVTIME, (int)time(NULL));
-            static const char* exclude_filter[] =
-                        {"LinkKey", "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"};
-            btif_config_filter_remove("Remote", exclude_filter, sizeof(exclude_filter)/sizeof(char*),
-                        BTIF_STORAGE_MAX_ALLOWED_REMOTE_DEVICE);
             break;
         case BT_PROPERTY_BDNAME:
             strncpy(value, (char*)prop->val, prop->len);
             value[prop->len]='\0';
             if(remote_bd_addr)
-                btif_config_set_str("Remote", bdstr,
+                btif_config_set_str(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_NAME, value);
-            else btif_config_set_str("Local", "Adapter",
+            else btif_config_set_str("Adapter",
                                 BTIF_STORAGE_KEY_ADAPTER_NAME, value);
             /* save name immediately */
             btif_config_save();
@@ -251,24 +246,24 @@
         case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
             strncpy(value, (char*)prop->val, prop->len);
             value[prop->len]='\0';
-            btif_config_set_str("Remote", bdstr, BTIF_STORAGE_PATH_REMOTE_ALIASE, value);
+            btif_config_set_str(bdstr, BTIF_STORAGE_PATH_REMOTE_ALIASE, value);
             /* save friendly name immediately */
             btif_config_save();
             break;
         case BT_PROPERTY_ADAPTER_SCAN_MODE:
-            btif_config_set_int("Local", "Adapter",
+            btif_config_set_int("Adapter",
                                 BTIF_STORAGE_KEY_ADAPTER_SCANMODE, *(int*)prop->val);
             break;
         case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
-            btif_config_set_int("Local", "Adapter",
+            btif_config_set_int("Adapter",
                                 BTIF_STORAGE_KEY_ADAPTER_DISC_TIMEOUT, *(int*)prop->val);
             break;
         case BT_PROPERTY_CLASS_OF_DEVICE:
-            btif_config_set_int("Remote", bdstr,
+            btif_config_set_int(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_DEVCLASS, *(int*)prop->val);
             break;
         case BT_PROPERTY_TYPE_OF_DEVICE:
-            btif_config_set_int("Remote", bdstr,
+            btif_config_set_int(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_DEVTYPE, *(int*)prop->val);
             break;
         case BT_PROPERTY_UUIDS:
@@ -280,12 +275,12 @@
             {
                 bt_uuid_t *p_uuid = (bt_uuid_t*)prop->val + i;
                 memset(buf, 0, sizeof(buf));
-                uuid_to_string(p_uuid, buf);
+                uuid_to_string_legacy(p_uuid, buf);
                 strcat(value, buf);
                 //strcat(value, ";");
                 strcat(value, " ");
             }
-            btif_config_set_str("Remote", bdstr, BTIF_STORAGE_PATH_REMOTE_SERVICE, value);
+            btif_config_set_str(bdstr, BTIF_STORAGE_PATH_REMOTE_SERVICE, value);
             btif_config_save();
             break;
         }
@@ -296,11 +291,11 @@
             if (!info)
                 return FALSE;
 
-            btif_config_set_int("Remote", bdstr,
+            btif_config_set_int(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_VER_MFCT, info->manufacturer);
-            btif_config_set_int("Remote", bdstr,
+            btif_config_set_int(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_VER_VER, info->version);
-            btif_config_set_int("Remote", bdstr,
+            btif_config_set_int(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_VER_SUBVER, info->sub_ver);
             btif_config_save();
          } break;
@@ -315,7 +310,7 @@
 {
     bdstr_t bdstr = {0};
     if(remote_bd_addr)
-        bd2str(remote_bd_addr, &bdstr);
+        bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
     BTIF_TRACE_DEBUG("in, bd addr:%s, prop type:%d, len:%d", bdstr, prop->type, prop->len);
     if(prop->len <= 0)
     {
@@ -327,16 +322,16 @@
     {
        case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
             if(prop->len >= (int)sizeof(int))
-                ret = btif_config_get_int("Remote", bdstr,
+                ret = btif_config_get_int(bdstr,
                                         BTIF_STORAGE_PATH_REMOTE_DEVTIME, (int*)prop->val);
             break;
         case BT_PROPERTY_BDNAME:
         {
             int len = prop->len;
             if(remote_bd_addr)
-                ret = btif_config_get_str("Remote", bdstr,
+                ret = btif_config_get_str(bdstr,
                                         BTIF_STORAGE_PATH_REMOTE_NAME, (char*)prop->val, &len);
-            else ret = btif_config_get_str("Local", "Adapter",
+            else ret = btif_config_get_str("Adapter",
                                         BTIF_STORAGE_KEY_ADAPTER_NAME, (char*)prop->val, &len);
             if(ret && len && len <= prop->len)
                 prop->len = len - 1;
@@ -350,7 +345,7 @@
         case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
         {
             int len = prop->len;
-            ret = btif_config_get_str("Remote", bdstr,
+            ret = btif_config_get_str(bdstr,
                                        BTIF_STORAGE_PATH_REMOTE_ALIASE, (char*)prop->val, &len);
             if(ret && len && len <= prop->len)
                 prop->len = len - 1;
@@ -363,29 +358,28 @@
         }
         case BT_PROPERTY_ADAPTER_SCAN_MODE:
            if(prop->len >= (int)sizeof(int))
-                ret = btif_config_get_int("Local", "Adapter",
+                ret = btif_config_get_int("Adapter",
                                           BTIF_STORAGE_KEY_ADAPTER_SCANMODE, (int*)prop->val);
            break;
         case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
            if(prop->len >= (int)sizeof(int))
-                ret = btif_config_get_int("Local", "Adapter",
+                ret = btif_config_get_int("Adapter",
                                           BTIF_STORAGE_KEY_ADAPTER_DISC_TIMEOUT, (int*)prop->val);
             break;
         case BT_PROPERTY_CLASS_OF_DEVICE:
             if(prop->len >= (int)sizeof(int))
-                ret = btif_config_get_int("Remote", bdstr,
+                ret = btif_config_get_int(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_DEVCLASS, (int*)prop->val);
             break;
         case BT_PROPERTY_TYPE_OF_DEVICE:
             if(prop->len >= (int)sizeof(int))
-                ret = btif_config_get_int("Remote",
-                                    bdstr, BTIF_STORAGE_PATH_REMOTE_DEVTYPE, (int*)prop->val);
+                ret = btif_config_get_int(bdstr, BTIF_STORAGE_PATH_REMOTE_DEVTYPE, (int*)prop->val);
             break;
         case BT_PROPERTY_UUIDS:
         {
             char value[1280];
             int size = sizeof(value);
-            if(btif_config_get_str("Remote", bdstr,
+            if(btif_config_get_str(bdstr,
                                     BTIF_STORAGE_PATH_REMOTE_SERVICE, value, &size))
             {
                 bt_uuid_t *p_uuid = (bt_uuid_t*)prop->val;
@@ -407,15 +401,15 @@
 
             if(prop->len >= (int)sizeof(bt_remote_version_t))
             {
-                ret = btif_config_get_int("Remote", bdstr,
+                ret = btif_config_get_int(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_VER_MFCT, &info->manufacturer);
 
                 if (ret == TRUE)
-                    ret = btif_config_get_int("Remote", bdstr,
+                    ret = btif_config_get_int(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_VER_VER, &info->version);
 
                 if (ret == TRUE)
-                    ret = btif_config_get_int("Remote", bdstr,
+                    ret = btif_config_get_int(bdstr,
                                 BTIF_STORAGE_PATH_REMOTE_VER_SUBVER, &info->sub_ver);
             }
          } break;
@@ -437,17 +431,16 @@
 ** Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
 **
 *******************************************************************************/
-static bt_status_t btif_in_fetch_bonded_device(char *bdstr)
+static bt_status_t btif_in_fetch_bonded_device(const char *bdstr)
 {
     BOOLEAN bt_linkkey_file_found=FALSE;
 
-        int type = BTIF_CFG_TYPE_BIN;
         LINK_KEY link_key;
-        int size = sizeof(link_key);
-        if(btif_config_get("Remote", bdstr, "LinkKey", (char*)link_key, &size, &type))
+        size_t size = sizeof(link_key);
+        if(btif_config_get_bin(bdstr, "LinkKey", (uint8_t *)link_key, &size))
         {
             int linkkey_type;
-            if(btif_config_get_int("Remote", bdstr, "LinkKeyType", &linkkey_type))
+            if(btif_config_get_int(bdstr, "LinkKeyType", &linkkey_type))
             {
                 bt_linkkey_file_found = TRUE;
             }
@@ -485,44 +478,38 @@
 *******************************************************************************/
 static bt_status_t btif_in_fetch_bonded_devices(btif_bonded_devices_t *p_bonded_devices, int add)
 {
-    BTIF_TRACE_DEBUG("in add:%d", add);
     memset(p_bonded_devices, 0, sizeof(btif_bonded_devices_t));
 
-    char kname[128];
-    short kpos;
-    int kname_size;
-    kname_size = sizeof(kname);
-    kname[0] = 0;
-    kpos = 0;
     BOOLEAN bt_linkkey_file_found=FALSE;
     int device_type;
 
-    do
-    {
-        kpos = btif_config_next_key(kpos, "Remote", kname, &kname_size);
-        BTIF_TRACE_DEBUG("Remote device:%s, size:%d", kname, kname_size);
-        int type = BTIF_CFG_TYPE_BIN;
+    for (const btif_config_section_iter_t *iter = btif_config_section_begin(); iter != btif_config_section_end(); iter = btif_config_section_next(iter)) {
+        const char *name = btif_config_section_name(iter);
+        if (!string_is_bdaddr(name))
+            continue;
+
+        BTIF_TRACE_DEBUG("Remote device:%s", name);
         LINK_KEY link_key;
-        int size = sizeof(link_key);
-        if(btif_config_get("Remote", kname, "LinkKey", (char*)link_key, &size, &type))
+        size_t size = sizeof(link_key);
+        if(btif_config_get_bin(name, "LinkKey", link_key, &size))
         {
             int linkkey_type;
-            if(btif_config_get_int("Remote", kname, "LinkKeyType", &linkkey_type))
+            if(btif_config_get_int(name, "LinkKeyType", &linkkey_type))
             {
                 //int pin_len;
-                //btif_config_get_int("Remote", kname, "PinLength", &pin_len))
+                //btif_config_get_int(name, "PinLength", &pin_len))
                 bt_bdaddr_t bd_addr;
-                str2bd(kname, &bd_addr);
+                string_to_bdaddr(name, &bd_addr);
                 if(add)
                 {
                     DEV_CLASS dev_class = {0, 0, 0};
                     int cod;
-                    if(btif_config_get_int("Remote", kname, "DevClass", &cod))
+                    if(btif_config_get_int(name, "DevClass", &cod))
                         uint2devclass((UINT32)cod, dev_class);
                     BTA_DmAddDevice(bd_addr.address, dev_class, link_key, 0, 0, (UINT8)linkkey_type, 0);
 
 #if BLE_INCLUDED == TRUE
-                    if (btif_config_get_int("Remote", kname, "DevType", &device_type) &&
+                    if (btif_config_get_int(name, "DevType", &device_type) &&
                        (device_type == BT_DEVICE_TYPE_DUMO) )
                     {
                         btif_gatts_add_bonded_dev_from_nv(bd_addr.address);
@@ -537,23 +524,20 @@
 #if (BLE_INCLUDED == TRUE)
                 bt_linkkey_file_found = FALSE;
 #else
-                BTIF_TRACE_ERROR("bounded device:%s, LinkKeyType or PinLength is invalid", kname);
+                BTIF_TRACE_ERROR("bounded device:%s, LinkKeyType or PinLength is invalid", name);
 #endif
             }
         }
 #if (BLE_INCLUDED == TRUE)
-            if(!(btif_in_fetch_bonded_ble_device(kname,add, p_bonded_devices)) && (!bt_linkkey_file_found))
+            if(!(btif_in_fetch_bonded_ble_device(name, add, p_bonded_devices)) && (!bt_linkkey_file_found))
             {
-                BTIF_TRACE_DEBUG("Remote device:%s, no link key or ble key found", kname);
+                BTIF_TRACE_DEBUG("Remote device:%s, no link key or ble key found", name);
             }
 #else
             if(!bt_linkkey_file_found)
-                BTIF_TRACE_DEBUG("Remote device:%s, no link key", kname);
+                BTIF_TRACE_DEBUG("Remote device:%s, no link key", name);
 #endif
-        kname_size = sizeof(kname);
-        kname[0] = 0;
-    } while(kpos != -1);
-    BTIF_TRACE_DEBUG("out");
+    }
     return BT_STATUS_SUCCESS;
 }
 
@@ -620,7 +604,7 @@
         uint32_t i;
 
         tBTA_SERVICE_MASK service_mask = btif_get_enabled_services_mask();
-        BTIF_TRACE_ERROR("%s service_mask:0x%x", __FUNCTION__, service_mask);
+        LOG_INFO("%s service_mask:0x%x", __FUNCTION__, service_mask);
         for (i=0; i < BTA_MAX_SERVICE_ID; i++)
         {
             /* This should eventually become a function when more services are enabled */
@@ -642,7 +626,7 @@
                                               p_uuid+num_uuids);
                             num_uuids++;
                         }break;
-                    case BTA_A2DP_SERVICE_ID:
+                    case BTA_A2DP_SOURCE_SERVICE_ID:
                         {
                             uuid16_to_uuid128(UUID_SERVCLASS_AUDIO_SOURCE,
                                               p_uuid+num_uuids);
@@ -781,10 +765,10 @@
                                            uint8_t pin_length)
 {
     bdstr_t bdstr;
-    bd2str(remote_bd_addr, &bdstr);
-    int ret = btif_config_set_int("Remote", bdstr, "LinkKeyType", (int)key_type);
-    ret &= btif_config_set_int("Remote", bdstr, "PinLength", (int)pin_length);
-    ret &= btif_config_set("Remote", bdstr, "LinkKey", (const char*)link_key, sizeof(LINK_KEY), BTIF_CFG_TYPE_BIN);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
+    int ret = btif_config_set_int(bdstr, "LinkKeyType", (int)key_type);
+    ret &= btif_config_set_int(bdstr, "PinLength", (int)pin_length);
+    ret &= btif_config_set_bin(bdstr, "LinkKey", link_key, sizeof(LINK_KEY));
     /* write bonded info immediately */
     btif_config_flush();
     return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
@@ -803,15 +787,15 @@
 bt_status_t btif_storage_remove_bonded_device(bt_bdaddr_t *remote_bd_addr)
 {
     bdstr_t bdstr;
-    bd2str(remote_bd_addr, &bdstr);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
     BTIF_TRACE_DEBUG("in bd addr:%s", bdstr);
     int ret = 1;
-    if(btif_config_exist("Remote", bdstr, "LinkKeyType"))
-        ret &= btif_config_remove("Remote", bdstr, "LinkKeyType");
-    if(btif_config_exist("Remote", bdstr, "PinLength"))
-        ret &= btif_config_remove("Remote", bdstr, "PinLength");
-    if(btif_config_exist("Remote", bdstr, "LinkKey"))
-        ret &= btif_config_remove("Remote", bdstr, "LinkKey");
+    if(btif_config_exist(bdstr, "LinkKeyType"))
+        ret &= btif_config_remove(bdstr, "LinkKeyType");
+    if(btif_config_exist(bdstr, "PinLength"))
+        ret &= btif_config_remove(bdstr, "PinLength");
+    if(btif_config_exist(bdstr, "LinkKey"))
+        ret &= btif_config_remove(bdstr, "LinkKey");
     /* write bonded info immediately */
     btif_config_flush();
     return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
@@ -963,7 +947,7 @@
                                            UINT8 key_length)
 {
     bdstr_t bdstr;
-    bd2str(remote_bd_addr, &bdstr);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
     const char* name;
     switch(key_type)
     {
@@ -985,7 +969,7 @@
         default:
             return BT_STATUS_FAIL;
     }
-    int ret = btif_config_set("Remote", bdstr, name, (const char*)key, (int)key_length, BTIF_CFG_TYPE_BIN);
+    int ret = btif_config_set_bin(bdstr, name, (const uint8_t *)key, key_length);
     btif_config_save();
     return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
 }
@@ -1006,9 +990,8 @@
                                              int key_length)
 {
     bdstr_t bdstr;
-    bd2str(remote_bd_addr, &bdstr);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
     const char* name;
-    int type = BTIF_CFG_TYPE_BIN;
     switch(key_type)
     {
         case BTIF_DM_LE_KEY_PENC:
@@ -1029,7 +1012,8 @@
         default:
             return BT_STATUS_FAIL;
     }
-    int ret = btif_config_get("Remote", bdstr, name, key_value, &key_length, &type);
+    size_t length = key_length;
+    int ret = btif_config_get_bin(bdstr, name, (uint8_t *)key_value, &length);
     return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
 
 }
@@ -1047,19 +1031,19 @@
 bt_status_t btif_storage_remove_ble_bonding_keys(bt_bdaddr_t *remote_bd_addr)
 {
     bdstr_t bdstr;
-    bd2str(remote_bd_addr, &bdstr);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
     BTIF_TRACE_DEBUG(" %s in bd addr:%s",__FUNCTION__, bdstr);
     int ret = 1;
-    if(btif_config_exist("Remote", bdstr, "LE_KEY_PENC"))
-        ret &= btif_config_remove("Remote", bdstr, "LE_KEY_PENC");
-    if(btif_config_exist("Remote", bdstr, "LE_KEY_PID"))
-        ret &= btif_config_remove("Remote", bdstr, "LE_KEY_PID");
-    if(btif_config_exist("Remote", bdstr, "LE_KEY_PCSRK"))
-        ret &= btif_config_remove("Remote", bdstr, "LE_KEY_PCSRK");
-    if(btif_config_exist("Remote", bdstr, "LE_KEY_LENC"))
-        ret &= btif_config_remove("Remote", bdstr, "LE_KEY_LENC");
-    if(btif_config_exist("Remote", bdstr, "LE_KEY_LCSRK"))
-        ret &= btif_config_remove("Remote", bdstr, "LE_KEY_LCSRK");
+    if(btif_config_exist(bdstr, "LE_KEY_PENC"))
+        ret &= btif_config_remove(bdstr, "LE_KEY_PENC");
+    if(btif_config_exist(bdstr, "LE_KEY_PID"))
+        ret &= btif_config_remove(bdstr, "LE_KEY_PID");
+    if(btif_config_exist(bdstr, "LE_KEY_PCSRK"))
+        ret &= btif_config_remove(bdstr, "LE_KEY_PCSRK");
+    if(btif_config_exist(bdstr, "LE_KEY_LENC"))
+        ret &= btif_config_remove(bdstr, "LE_KEY_LENC");
+    if(btif_config_exist(bdstr, "LE_KEY_LCSRK"))
+        ret &= btif_config_remove(bdstr, "LE_KEY_LCSRK");
     btif_config_save();
     return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
 }
@@ -1096,7 +1080,7 @@
         default:
             return BT_STATUS_FAIL;
     }
-    int ret = btif_config_set("Local", "Adapter", name, (const char*)key, key_length, BTIF_CFG_TYPE_BIN);
+    int ret = btif_config_set_bin("Adapter", name, (const uint8_t *)key, key_length);
     btif_config_save();
     return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
 }
@@ -1116,7 +1100,6 @@
                                            int key_length)
 {
     const char* name;
-    int type = BTIF_CFG_TYPE_BIN;
     switch(key_type)
     {
         case BTIF_DM_LE_LOCAL_KEY_IR:
@@ -1134,9 +1117,9 @@
         default:
             return BT_STATUS_FAIL;
     }
-    int ret = btif_config_get("Local", "Adapter", name, key_value, &key_length, &type);
+    size_t length = key_length;
+    int ret = btif_config_get_bin("Adapter", name, (uint8_t *)key_value, &length);
     return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
-
 }
 
 /*******************************************************************************
@@ -1152,19 +1135,19 @@
 bt_status_t btif_storage_remove_ble_local_keys(void)
 {
     int ret = 1;
-    if(btif_config_exist("Local", "Adapter", "LE_LOCAL_KEY_IR"))
-        ret &= btif_config_remove("Local", "Adapter", "LE_LOCAL_KEY_IR");
-    if(btif_config_exist("Local", "Adapter", "LE_LOCAL_KEY_IRK"))
-        ret &= btif_config_remove("Local", "Adapter", "LE_LOCAL_KEY_IRK");
-    if(btif_config_exist("Local", "Adapter", "LE_LOCAL_KEY_DHK"))
-        ret &= btif_config_remove("Local", "Adapter", "LE_LOCAL_KEY_DHK");
-    if(btif_config_exist("Local", "Adapter", "LE_LOCAL_KEY_ER"))
-        ret &= btif_config_remove("Local", "Adapter", "LE_LOCAL_KEY_ER");
+    if(btif_config_exist("Adapter", "LE_LOCAL_KEY_IR"))
+        ret &= btif_config_remove("Adapter", "LE_LOCAL_KEY_IR");
+    if(btif_config_exist("Adapter", "LE_LOCAL_KEY_IRK"))
+        ret &= btif_config_remove("Adapter", "LE_LOCAL_KEY_IRK");
+    if(btif_config_exist("Adapter", "LE_LOCAL_KEY_DHK"))
+        ret &= btif_config_remove("Adapter", "LE_LOCAL_KEY_DHK");
+    if(btif_config_exist("Adapter", "LE_LOCAL_KEY_ER"))
+        ret &= btif_config_remove("Adapter", "LE_LOCAL_KEY_ER");
     btif_config_save();
     return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
 }
 
-bt_status_t btif_in_fetch_bonded_ble_device(char *remote_bd_addr,int add, btif_bonded_devices_t *p_bonded_devices)
+bt_status_t btif_in_fetch_bonded_ble_device(const char *remote_bd_addr,int add, btif_bonded_devices_t *p_bonded_devices)
 {
     int device_type;
     int addr_type;
@@ -1176,12 +1159,12 @@
     BOOLEAN key_found = FALSE;
     tBTA_LE_KEY_VALUE *p;
 
-    if(!btif_config_get_int("Remote", remote_bd_addr,"DevType", &device_type))
+    if(!btif_config_get_int(remote_bd_addr,"DevType", &device_type))
         return BT_STATUS_FAIL;
     if(device_type == BT_DEVICE_TYPE_BLE)
     {
             BTIF_TRACE_DEBUG("%s %s found a BLE device", __FUNCTION__,remote_bd_addr);
-            str2bd(remote_bd_addr, &bd_addr);
+            string_to_bdaddr(remote_bd_addr, &bd_addr);
             bdcpy(bta_bd_addr, bd_addr.address);
             if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) != BT_STATUS_SUCCESS)
             {
@@ -1341,8 +1324,8 @@
                                               UINT8 addr_type)
 {
     bdstr_t bdstr;
-    bd2str(remote_bd_addr, &bdstr);
-    int ret = btif_config_set_int("Remote", bdstr, "AddrType", (int)addr_type);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
+    int ret = btif_config_set_int(bdstr, "AddrType", (int)addr_type);
     btif_config_save();
     return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
 }
@@ -1361,8 +1344,8 @@
                                               int*addr_type)
 {
     bdstr_t bdstr;
-    bd2str(remote_bd_addr, &bdstr);
-    int ret = btif_config_get_int("Remote", bdstr, "AddrType", addr_type);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
+    int ret = btif_config_get_int(bdstr, "AddrType", addr_type);
     return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
 }
 #endif
@@ -1386,19 +1369,18 @@
 {
     bdstr_t bdstr;
     BTIF_TRACE_DEBUG("btif_storage_add_hid_device_info:");
-    bd2str(remote_bd_addr, &bdstr);
-    btif_config_set_int("Remote", bdstr, "HidAttrMask", attr_mask);
-    btif_config_set_int("Remote", bdstr, "HidSubClass", sub_class);
-    btif_config_set_int("Remote", bdstr, "HidAppId", app_id);
-    btif_config_set_int("Remote", bdstr, "HidVendorId", vendor_id);
-    btif_config_set_int("Remote", bdstr, "HidProductId", product_id);
-    btif_config_set_int("Remote", bdstr, "HidVersion", version);
-    btif_config_set_int("Remote", bdstr, "HidCountryCode", ctry_code);
-    btif_config_set_int("Remote", bdstr, "HidSSRMaxLatency", ssr_max_latency);
-    btif_config_set_int("Remote", bdstr, "HidSSRMinTimeout", ssr_min_tout);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
+    btif_config_set_int(bdstr, "HidAttrMask", attr_mask);
+    btif_config_set_int(bdstr, "HidSubClass", sub_class);
+    btif_config_set_int(bdstr, "HidAppId", app_id);
+    btif_config_set_int(bdstr, "HidVendorId", vendor_id);
+    btif_config_set_int(bdstr, "HidProductId", product_id);
+    btif_config_set_int(bdstr, "HidVersion", version);
+    btif_config_set_int(bdstr, "HidCountryCode", ctry_code);
+    btif_config_set_int(bdstr, "HidSSRMaxLatency", ssr_max_latency);
+    btif_config_set_int(bdstr, "HidSSRMinTimeout", ssr_min_tout);
     if(dl_len > 0)
-        btif_config_set("Remote", bdstr, "HidDescriptor", (const char*)dsc_list, dl_len,
-                        BTIF_CFG_TYPE_BIN);
+        btif_config_set_bin(bdstr, "HidDescriptor", dsc_list, dl_len);
     btif_config_save();
     return BT_STATUS_SUCCESS;
 }
@@ -1421,60 +1403,54 @@
     uint8_t  sub_class;
     uint8_t  app_id;
 
-    char kname[128];
-    short kpos;
-    int kname_size;
-    kname_size = sizeof(kname);
-    kname[0] = 0;
-    kpos = 0;
     memset(&dscp_info, 0, sizeof(dscp_info));
-    do
-    {
-        kpos = btif_config_next_key(kpos, "Remote", kname, &kname_size);
-        BTIF_TRACE_DEBUG("Remote device:%s, size:%d", kname, kname_size);
+    for (const btif_config_section_iter_t *iter = btif_config_section_begin(); iter != btif_config_section_end(); iter = btif_config_section_next(iter)) {
+        const char *name = btif_config_section_name(iter);
+        if (!string_is_bdaddr(name))
+            continue;
+
+        BTIF_TRACE_DEBUG("Remote device:%s", name);
         int value;
-        if(btif_in_fetch_bonded_device(kname) == BT_STATUS_SUCCESS)
+        if(btif_in_fetch_bonded_device(name) == BT_STATUS_SUCCESS)
         {
-            if(btif_config_get_int("Remote", kname, "HidAttrMask", &value))
+            if(btif_config_get_int(name, "HidAttrMask", &value))
             {
                 attr_mask = (uint16_t)value;
 
-                btif_config_get_int("Remote", kname, "HidSubClass", &value);
+                btif_config_get_int(name, "HidSubClass", &value);
                 sub_class = (uint8_t)value;
 
-                btif_config_get_int("Remote", kname, "HidAppId", &value);
+                btif_config_get_int(name, "HidAppId", &value);
                 app_id = (uint8_t)value;
 
-                btif_config_get_int("Remote", kname, "HidVendorId", &value);
+                btif_config_get_int(name, "HidVendorId", &value);
                 dscp_info.vendor_id = (uint16_t) value;
 
-                btif_config_get_int("Remote", kname, "HidProductId", &value);
+                btif_config_get_int(name, "HidProductId", &value);
                 dscp_info.product_id = (uint16_t) value;
 
-                btif_config_get_int("Remote", kname, "HidVersion", &value);
+                btif_config_get_int(name, "HidVersion", &value);
                 dscp_info.version = (uint8_t) value;
 
-                btif_config_get_int("Remote", kname, "HidCountryCode", &value);
+                btif_config_get_int(name, "HidCountryCode", &value);
                 dscp_info.ctry_code = (uint8_t) value;
 
                 value = 0;
-                btif_config_get_int("Remote", kname, "HidSSRMaxLatency", &value);
+                btif_config_get_int(name, "HidSSRMaxLatency", &value);
                 dscp_info.ssr_max_latency = (uint16_t) value;
 
                 value = 0;
-                btif_config_get_int("Remote", kname, "HidSSRMinTimeout", &value);
+                btif_config_get_int(name, "HidSSRMinTimeout", &value);
                 dscp_info.ssr_min_tout = (uint16_t) value;
 
-                int len = 0;
-                int type;
-                btif_config_get("Remote", kname, "HidDescriptor", NULL, &len, &type);
+                size_t len = btif_config_get_bin_length(name, "HidDescriptor");
                 if(len > 0)
                 {
                     dscp_info.descriptor.dl_len = (uint16_t)len;
                     dscp_info.descriptor.dsc_list = (uint8_t*)alloca(len);
-                    btif_config_get("Remote", kname, "HidDescriptor", (char*)dscp_info.descriptor.dsc_list, &len, &type);
+                    btif_config_get_bin(name, "HidDescriptor", (uint8_t *)dscp_info.descriptor.dsc_list, &len);
                 }
-                str2bd(kname, &bd_addr);
+                string_to_bdaddr(name, &bd_addr);
                 // add extracted information to BTA HH
                 if (btif_hh_add_added_dev(bd_addr,attr_mask))
                 {
@@ -1485,13 +1461,13 @@
         }
         else
         {
-            if(btif_config_get_int("Remote", kname, "HidAttrMask", &value))
+            if(btif_config_get_int(name, "HidAttrMask", &value))
             {
                 btif_storage_remove_hid_info(&bd_addr);
-                str2bd(kname, &bd_addr);
+                string_to_bdaddr(name, &bd_addr);
             }
         }
-    } while(kpos != -1);
+    }
 
     return BT_STATUS_SUCCESS;
 }
@@ -1509,18 +1485,18 @@
 bt_status_t btif_storage_remove_hid_info(bt_bdaddr_t *remote_bd_addr)
 {
     bdstr_t bdstr;
-    bd2str(remote_bd_addr, &bdstr);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
 
-    btif_config_remove("Remote", bdstr, "HidAttrMask");
-    btif_config_remove("Remote", bdstr, "HidSubClass");
-    btif_config_remove("Remote", bdstr, "HidAppId");
-    btif_config_remove("Remote", bdstr, "HidVendorId");
-    btif_config_remove("Remote", bdstr, "HidProductId");
-    btif_config_remove("Remote", bdstr, "HidVersion");
-    btif_config_remove("Remote", bdstr, "HidCountryCode");
-    btif_config_remove("Remote", bdstr, "HidSSRMaxLatency");
-    btif_config_remove("Remote", bdstr, "HidSSRMinTimeout");
-    btif_config_remove("Remote", bdstr, "HidDescriptor");
+    btif_config_remove(bdstr, "HidAttrMask");
+    btif_config_remove(bdstr, "HidSubClass");
+    btif_config_remove(bdstr, "HidAppId");
+    btif_config_remove(bdstr, "HidVendorId");
+    btif_config_remove(bdstr, "HidProductId");
+    btif_config_remove(bdstr, "HidVersion");
+    btif_config_remove(bdstr, "HidCountryCode");
+    btif_config_remove(bdstr, "HidSSRMaxLatency");
+    btif_config_remove(bdstr, "HidSSRMinTimeout");
+    btif_config_remove(bdstr, "HidDescriptor");
     btif_config_save();
     return BT_STATUS_SUCCESS;
 }
@@ -1538,13 +1514,12 @@
 bt_status_t btif_storage_read_hl_apps_cb(char *value, int value_size)
 {
     bt_status_t bt_status = BT_STATUS_SUCCESS;
-    int read_size=value_size, read_type=BTIF_CFG_TYPE_BIN;
 
-    if (!btif_config_exist("Local", BTIF_STORAGE_HL_APP, BTIF_STORAGE_HL_APP_CB))
+    if (!btif_config_exist(BTIF_STORAGE_HL_APP, BTIF_STORAGE_HL_APP_CB))
     {
         memset(value, 0, value_size);
-        if (!btif_config_set("Local", BTIF_STORAGE_HL_APP,BTIF_STORAGE_HL_APP_CB,
-                             value, value_size, BTIF_CFG_TYPE_BIN))
+        if (!btif_config_set_bin(BTIF_STORAGE_HL_APP,BTIF_STORAGE_HL_APP_CB,
+                             (const uint8_t *)value, value_size))
         {
             bt_status = BT_STATUS_FAIL;
         }
@@ -1555,17 +1530,18 @@
     }
     else
     {
-        if (!btif_config_get("Local", BTIF_STORAGE_HL_APP, BTIF_STORAGE_HL_APP_CB,
-                             value, &read_size, &read_type))
+        size_t read_size = value_size;
+        if (!btif_config_get_bin(BTIF_STORAGE_HL_APP, BTIF_STORAGE_HL_APP_CB,
+                             (uint8_t *)value, &read_size))
         {
             bt_status = BT_STATUS_FAIL;
         }
         else
         {
-            if ((read_size != value_size) || (read_type != BTIF_CFG_TYPE_BIN) )
+            if (read_size != (size_t)value_size)
             {
-                BTIF_TRACE_ERROR("%s  value_size=%d read_size=%d read_type=%d",
-                                  __FUNCTION__, value_size, read_size, read_type);
+                BTIF_TRACE_ERROR("%s  value_size=%d read_size=%d",
+                                  __FUNCTION__, value_size, read_size);
                 bt_status = BT_STATUS_FAIL;
             }
         }
@@ -1589,7 +1565,7 @@
 *******************************************************************************/
 bt_status_t btif_storage_load_autopair_device_list() {
     // Configuration has already been loaded. No need to reload.
-    if (btif_config_exist("Local", BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST, NULL)) {
+    if (btif_config_has_section(BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST)) {
         return BT_STATUS_SUCCESS;
     }
 
@@ -1603,14 +1579,14 @@
 
     config_t *config = config_new(BTIF_AUTO_PAIR_CONF_FILE);
     if (!config) {
-        ALOGE("%s failed to open auto pair blacklist conf file '%s'.", __func__, BTIF_AUTO_PAIR_CONF_FILE);
+        LOG_ERROR("%s failed to open auto pair blacklist conf file '%s'.", __func__, BTIF_AUTO_PAIR_CONF_FILE);
         return BT_STATUS_FAIL;
     }
 
     for (size_t i = 0; i < ARRAY_SIZE(key_names); ++i) {
         const char *value = config_get_string(config, CONFIG_DEFAULT_SECTION, key_names[i], NULL);
         if (value) {
-            btif_config_set_str("Local", BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST, key_names[i], value);
+            btif_config_set_str(BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST, key_names[i], value);
         }
     }
 
@@ -1636,12 +1612,12 @@
     char value[BTIF_STORAGE_MAX_LINE_SZ];
     int value_size = sizeof(value);
 
-    bd2str(remote_bd_addr, &bdstr);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
 
     /* Consider only  Lower Address Part from BD Address */
     bdstr[8] = '\0';
 
-    if(btif_config_get_str("Local", BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
+    if(btif_config_get_str(BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
                 BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_ADDR, value, &value_size))
     {
         if (strcasestr(value,bdstr) != NULL)
@@ -1653,14 +1629,14 @@
     if (dev_name_str != NULL)
     {
         value_size = sizeof(value);
-        if(btif_config_get_str("Local", BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
+        if(btif_config_get_str(BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
                     BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_EXACTNAME, value, &value_size))
         {
             if (strstr(value,dev_name_str) != NULL)
                 return TRUE;
         }
         value_size = sizeof(value);
-        if(btif_config_get_str("Local", BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
+        if(btif_config_get_str(BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
                     BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_PARTIALNAME, value, &value_size))
         {
             token = strtok(value, BTIF_AUTO_PAIR_CONF_VALUE_SEPARATOR);
@@ -1673,7 +1649,7 @@
             }
         }
     }
-    if(btif_config_get_str("Local", BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
+    if(btif_config_get_str(BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
                 BTIF_STORAGE_KEY_AUTOPAIR_DYNAMIC_BLACKLIST_ADDR, value, &value_size))
     {
         if (strstr(value,bdstr) != NULL)
@@ -1699,12 +1675,12 @@
     char linebuf[BTIF_STORAGE_MAX_LINE_SZ+20];
     char input_value [20];
 
-    bd2str(remote_bd_addr, &bdstr);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
     strlcpy(input_value, (char*)bdstr, sizeof(input_value));
     strlcat(input_value,BTIF_AUTO_PAIR_CONF_VALUE_SEPARATOR, sizeof(input_value));
 
     int line_size = sizeof(linebuf);
-    if(btif_config_get_str("Local", BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
+    if(btif_config_get_str(BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
                             BTIF_STORAGE_KEY_AUTOPAIR_DYNAMIC_BLACKLIST_ADDR, linebuf, &line_size))
     {
          /* Append this address to the dynamic List of BD address  */
@@ -1716,7 +1692,7 @@
     }
 
     /* Write back the key value */
-    ret = btif_config_set_str("Local", BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
+    ret = btif_config_set_str(BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
                         BTIF_STORAGE_KEY_AUTOPAIR_DYNAMIC_BLACKLIST_ADDR, linebuf);
 
     return ret ? BT_STATUS_SUCCESS:BT_STATUS_FAIL;
@@ -1737,13 +1713,13 @@
     bdstr_t bdstr;
     char linebuf[BTIF_STORAGE_MAX_LINE_SZ];
 
-    bd2str(remote_bd_addr, &bdstr);
+    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
 
     /*consider on LAP part of BDA string*/
     bdstr[8] = '\0';
 
     int line_size = sizeof(linebuf);
-    if(btif_config_get_str("Local", BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
+    if(btif_config_get_str(BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST,
                             BTIF_STORAGE_KEY_AUTOPAIR_FIXPIN_KBLIST, linebuf, &line_size))
     {
         if (strcasestr(linebuf,bdstr) != NULL)
@@ -1771,7 +1747,7 @@
     bdstr_t bdstr = {0};
     if(remote_bd_addr)
     {
-        bd2str(remote_bd_addr, &bdstr);
+        bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
     }
     else
     {
@@ -1779,7 +1755,7 @@
         return BT_STATUS_FAIL;
     }
 
-   ret = btif_config_set_int("Remote", bdstr,"DMTSupported", (int)dmt_supported);
+   ret = btif_config_set_int(bdstr,"DMTSupported", (int)dmt_supported);
    return ret ? BT_STATUS_SUCCESS:BT_STATUS_FAIL;
 
 }
@@ -1799,11 +1775,11 @@
     int    dmt_supported = 0;
     bdstr_t bdstr = {0};
     if(remote_bd_addr)
-        bd2str(remote_bd_addr, &bdstr);
+        bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
 
     if(remote_bd_addr)
     {
-        bd2str(remote_bd_addr, &bdstr);
+        bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
     }
     else
     {
@@ -1811,7 +1787,7 @@
         return FALSE;
     }
 
-    btif_config_get_int("Remote", bdstr,"DMTSupported", &dmt_supported);
+    btif_config_get_int(bdstr,"DMTSupported", &dmt_supported);
 
     return dmt_supported == 1 ? TRUE:FALSE;
 }
diff --git a/btif/src/btif_util.c b/btif/src/btif_util.c
index b86c51a..42576eb 100644
--- a/btif/src/btif_util.c
+++ b/btif/src/btif_util.c
@@ -36,13 +36,12 @@
 #include <ctype.h>
 
 
-#define LOG_TAG "BTIF_UTIL"
+#define LOG_TAG "bt_btif_util"
 #include "btif_common.h"
 #include "bta_api.h"
 #include "gki.h"
 #include "btu.h"
 #include "bte.h"
-#include "bd.h"
 #include "btif_dm.h"
 #include "btif_util.h"
 #include "bta_ag_api.h"
@@ -81,26 +80,6 @@
 **   Logging helper functions
 *****************************************************************************/
 
-int str2bd(char *str, bt_bdaddr_t *addr)
-{
-    int32_t i = 0;
-    for (i = 0; i < 6; i++) {
-       addr->address[i] = (uint8_t)strtoul(str, &str, 16);
-       str++;
-    }
-    return 0;
-}
-
-char *bd2str(const bt_bdaddr_t *bdaddr, bdstr_t *bdstr)
-{
-    const uint8_t *addr = bdaddr->address;
-
-    sprintf(*bdstr, "%02x:%02x:%02x:%02x:%02x:%02x",
-             addr[0], addr[1], addr[2],
-             addr[3], addr[4], addr[5]);
-    return *bdstr;
-}
-
 UINT32 devclass2uint(DEV_CLASS dev_class)
 {
     UINT32 cod = 0;
@@ -158,7 +137,7 @@
 
 }
 
-void uuid_to_string(bt_uuid_t *p_uuid, char *str)
+void uuid_to_string_legacy(bt_uuid_t *p_uuid, char *str)
 {
     uint32_t uuid0, uuid4;
     uint16_t uuid1, uuid2, uuid3, uuid5;
diff --git a/btif/src/stack_manager.c b/btif/src/stack_manager.c
new file mode 100644
index 0000000..ff71b08
--- /dev/null
+++ b/btif/src/stack_manager.c
@@ -0,0 +1,230 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_stack_manager"
+
+#include <hardware/bluetooth.h>
+
+#include "btif_api.h"
+#include "btif_common.h"
+#include "device/include/controller.h"
+#include "btcore/include/module.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/semaphore.h"
+#include "stack_manager.h"
+#include "osi/include/thread.h"
+
+// Temp includes
+#include "btif_config.h"
+#include "btif_profile_queue.h"
+#include "bt_utils.h"
+
+static thread_t *management_thread;
+
+// If initialized, any of the bluetooth API functions can be called.
+// (e.g. turning logging on and off, enabling/disabling the stack, etc)
+static bool stack_is_initialized;
+// If running, the stack is fully up and able to bluetooth.
+static bool stack_is_running;
+
+static void event_init_stack(void *context);
+static void event_start_up_stack(void *context);
+static void event_shut_down_stack(void *context);
+static void event_clean_up_stack(void *context);
+
+static void event_signal_stack_up(void *context);
+static void event_signal_stack_down(void *context);
+
+// Unvetted includes/imports, etc which should be removed or vetted in the future
+static future_t *hack_future;
+void bte_main_enable();
+void btif_thread_post(thread_fn func, void *context);
+// End unvetted section
+
+// Interface functions
+
+static void init_stack(void) {
+  // This is a synchronous process. Post it to the thread though, so
+  // state modification only happens there.
+  semaphore_t *semaphore = semaphore_new(0);
+  thread_post(management_thread, event_init_stack, semaphore);
+  semaphore_wait(semaphore);
+  semaphore_free(semaphore);
+}
+
+static void start_up_stack_async(void) {
+  thread_post(management_thread, event_start_up_stack, NULL);
+}
+
+static void shut_down_stack_async(void) {
+  thread_post(management_thread, event_shut_down_stack, NULL);
+}
+
+static void clean_up_stack_async(void) {
+  thread_post(management_thread, event_clean_up_stack, NULL);
+}
+
+static bool get_stack_is_running(void) {
+  return stack_is_running;
+}
+
+// Internal functions
+
+// Synchronous function to initialize the stack
+static void event_init_stack(void *context) {
+  semaphore_t *semaphore = (semaphore_t *)context;
+
+  if (!stack_is_initialized) {
+    module_management_start();
+
+    module_init(get_module(BT_UTILS_MODULE));
+    module_init(get_module(BTIF_CONFIG_MODULE));
+    btif_init_bluetooth();
+
+    // stack init is synchronous, so no waiting necessary here
+    stack_is_initialized = true;
+  }
+
+  if (semaphore)
+    semaphore_post(semaphore);
+}
+
+static void ensure_stack_is_initialized(void) {
+  if (!stack_is_initialized) {
+    LOG_WARN("%s found the stack was uninitialized. Initializing now.", __func__);
+    // No semaphore needed since we are calling it directly
+    event_init_stack(NULL);
+  }
+}
+
+// Synchronous function to start up the stack
+static void event_start_up_stack(UNUSED_ATTR void *context) {
+  if (stack_is_running) {
+    LOG_DEBUG("%s stack already brought up.", __func__);
+    return;
+  }
+
+  ensure_stack_is_initialized();
+
+  LOG_DEBUG("%s is bringing up the stack.", __func__);
+  hack_future = future_new();
+
+  // Include this for now to put btif config into a shutdown-able state
+  module_start_up(get_module(BTIF_CONFIG_MODULE));
+  bte_main_enable();
+
+  if (future_await(hack_future) != FUTURE_SUCCESS) {
+    stack_is_running = true; // So stack shutdown actually happens
+    event_shut_down_stack(NULL);
+    return;
+  }
+
+  stack_is_running = true;
+  LOG_DEBUG("%s finished", __func__);
+  btif_thread_post(event_signal_stack_up, NULL);
+}
+
+// Synchronous function to shut down the stack
+static void event_shut_down_stack(UNUSED_ATTR void *context) {
+  if (!stack_is_running) {
+    LOG_DEBUG("%s stack is already brought down.", __func__);
+    return;
+  }
+
+  LOG_DEBUG("%s is bringing down the stack.", __func__);
+  hack_future = future_new();
+  stack_is_running = false;
+
+  btif_disable_bluetooth();
+  module_shut_down(get_module(BTIF_CONFIG_MODULE));
+
+  future_await(hack_future);
+  module_shut_down(get_module(CONTROLLER_MODULE)); // Doesn't do any work, just puts it in a restartable state
+  LOG_DEBUG("%s finished.", __func__);
+  btif_thread_post(event_signal_stack_down, NULL);
+}
+
+static void ensure_stack_is_not_running(void) {
+  if (stack_is_running) {
+    LOG_WARN("%s found the stack was still running. Bringing it down now.", __func__);
+    event_shut_down_stack(NULL);
+  }
+}
+
+// Synchronous function to clean up the stack
+static void event_clean_up_stack(UNUSED_ATTR void *context) {
+  if (!stack_is_initialized) {
+    LOG_DEBUG("%s found the stack already in a clean state.", __func__);
+    return;
+  }
+
+  ensure_stack_is_not_running();
+
+  LOG_DEBUG("%s is cleaning up the stack.", __func__);
+  hack_future = future_new();
+  stack_is_initialized = false;
+
+  btif_shutdown_bluetooth();
+  module_clean_up(get_module(BTIF_CONFIG_MODULE));
+  module_clean_up(get_module(BT_UTILS_MODULE));
+
+  future_await(hack_future);
+  module_management_stop();
+  LOG_DEBUG("%s finished.", __func__);
+}
+
+static void event_signal_stack_up(UNUSED_ATTR void *context) {
+  // Notify BTIF connect queue that we've brought up the stack. It's
+  // now time to dispatch all the pending profile connect requests.
+  btif_queue_connect_next();
+  HAL_CBACK(bt_hal_cbacks, adapter_state_changed_cb, BT_STATE_ON);
+}
+
+static void event_signal_stack_down(UNUSED_ATTR void *context) {
+  HAL_CBACK(bt_hal_cbacks, adapter_state_changed_cb, BT_STATE_OFF);
+}
+
+static void ensure_manager_initialized(void) {
+  if (management_thread)
+    return;
+
+  management_thread = thread_new("stack_manager");
+  if (!management_thread) {
+    LOG_ERROR("%s unable to create stack management thread.", __func__);
+    return;
+  }
+}
+
+static const stack_manager_t interface = {
+  init_stack,
+  start_up_stack_async,
+  shut_down_stack_async,
+  clean_up_stack_async,
+
+  get_stack_is_running
+};
+
+const stack_manager_t *stack_manager_get_interface() {
+  ensure_manager_initialized();
+  return &interface;
+}
+
+future_t *stack_manager_get_hack_future() {
+  return hack_future;
+}
diff --git a/device/Android.mk b/device/Android.mk
new file mode 100644
index 0000000..18b19dd
--- /dev/null
+++ b/device/Android.mk
@@ -0,0 +1,66 @@
+ ##############################################################################
+ #
+ #  Copyright (C) 2014 Google, Inc.
+ #
+ #  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.
+ #
+ ##############################################################################
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_C_INCLUDES := \
+    $(LOCAL_PATH)/.. \
+    $(LOCAL_PATH)/include \
+    $(LOCAL_PATH)/../btcore/include \
+    $(LOCAL_PATH)/../gki/common \
+    $(LOCAL_PATH)/../hci/include \
+    $(LOCAL_PATH)/../include \
+    $(LOCAL_PATH)/../osi/include \
+    $(LOCAL_PATH)/../stack/include \
+    $(bdroid_C_INCLUDES)
+
+LOCAL_SRC_FILES := \
+    src/classic/peer.c \
+    src/controller.c
+
+LOCAL_CFLAGS := $(bdroid_CFLAGS)
+LOCAL_CONLYFLAGS := $(bdroid_CONLYFLAGS)
+LOCAL_MODULE := libbtdevice
+LOCAL_MODULE_TAGS := optional
+LOCAL_SHARED_LIBRARIES := libc liblog
+LOCAL_MODULE_CLASS := STATIC_LIBRARIES
+
+include $(BUILD_STATIC_LIBRARY)
+
+#####################################################
+
+include $(CLEAR_VARS)
+
+LOCAL_C_INCLUDES := \
+    $(LOCAL_PATH)/.. \
+    $(LOCAL_PATH)/../osi/include \
+    $(bdroid_C_INCLUDES)
+
+LOCAL_SRC_FILES := \
+    ../osi/test/AllocationTestHarness.cpp \
+    ./test/classic/peer_test.cpp
+
+LOCAL_CFLAGS := -Wall -Werror $(bdroid_CFLAGS)
+LOCAL_MODULE := net_test_device
+LOCAL_MODULE_TAGS := tests
+LOCAL_SHARED_LIBRARIES := liblog libdl
+LOCAL_STATIC_LIBRARIES := libbtdevice libbtcore libosi libcutils
+
+include $(BUILD_NATIVE_TEST)
diff --git a/device/include/classic/peer.h b/device/include/classic/peer.h
new file mode 100644
index 0000000..069be72
--- /dev/null
+++ b/device/include/classic/peer.h
@@ -0,0 +1,34 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include "btcore/include/bdaddr.h"
+
+static const char CLASSIC_PEER_MODULE[] = "classic_peer_module";
+
+typedef struct classic_peer_t classic_peer_t;
+
+// Returns a classic_peer_t for the provided |address|. If the peer
+// already exists, that instance is returned. Otherwise a classic_peer_t
+// is constructed for that |address| and then returned. |address| may not
+// be NULL.
+classic_peer_t *classic_peer_by_address(bt_bdaddr_t *address);
+
+// Returns the bluetooth address of the |peer|. |peer| may not be NULL.
+const bt_bdaddr_t *classic_peer_get_address(classic_peer_t *peer);
diff --git a/device/include/controller.h b/device/include/controller.h
new file mode 100644
index 0000000..2ef2332
--- /dev/null
+++ b/device/include/controller.h
@@ -0,0 +1,75 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "bdaddr.h"
+#include "device_features.h"
+#include "hci_layer.h"
+#include "hci_packet_factory.h"
+#include "hci_packet_parser.h"
+
+static const char CONTROLLER_MODULE[] = "controller_module";
+
+typedef struct controller_t {
+  bool (*get_is_ready)(void);
+
+  const bt_bdaddr_t *(*get_address)(void);
+  const bt_version_t *(*get_bt_version)(void);
+
+  const bt_device_features_t *(*get_features_classic)(int index);
+  uint8_t (*get_last_features_classic_index)(void);
+
+  const bt_device_features_t *(*get_features_ble)(void);
+  const uint8_t *(*get_ble_supported_states)(void);
+
+  bool (*supports_simple_pairing)(void);
+  bool (*supports_simultaneous_le_bredr)(void);
+  bool (*supports_reading_remote_extended_features)(void);
+  bool (*supports_interlaced_inquiry_scan)(void);
+  bool (*supports_rssi_with_inquiry_results)(void);
+  bool (*supports_extended_inquiry_response)(void);
+  bool (*supports_master_slave_role_switch)(void);
+
+  bool (*supports_ble)(void);
+  bool (*supports_ble_connection_parameters_request)(void);
+
+  // Get the cached acl data sizes for the controller.
+  uint16_t (*get_acl_data_size_classic)(void);
+  uint16_t (*get_acl_data_size_ble)(void);
+
+  // Get the cached acl packet sizes for the controller.
+  // This is a convenience function for the respective
+  // acl data size + size of the acl header.
+  uint16_t (*get_acl_packet_size_classic)(void);
+  uint16_t (*get_acl_packet_size_ble)(void);
+
+  // Get the number of acl packets the controller can buffer.
+  uint16_t (*get_acl_buffer_count_classic)(void);
+  uint8_t (*get_acl_buffer_count_ble)(void);
+} controller_t;
+
+const controller_t *controller_get_interface();
+
+const controller_t *controller_get_test_interface(
+    const hci_t *hci_interface,
+    const hci_packet_factory_t *packet_factory_interface,
+    const hci_packet_parser_t *packet_parser_interface);
diff --git a/device/src/classic/peer.c b/device/src/classic/peer.c
new file mode 100644
index 0000000..6d1a7b5
--- /dev/null
+++ b/device/src/classic/peer.c
@@ -0,0 +1,120 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_classic_peer"
+
+#include <assert.h>
+#include <cutils/log.h>
+#include <pthread.h>
+#include <stdbool.h>
+
+#include "btcore/include/module.h"
+#include "device/include/classic/peer.h"
+#include "osi/include/allocator.h"
+#include "osi/include/future.h"
+#include "osi/include/hash_map.h"
+#include "osi/include/osi.h"
+
+struct classic_peer_t {
+  bt_bdaddr_t address;
+};
+
+static const size_t number_of_address_buckets = 42;
+
+static bool initialized;
+static pthread_mutex_t bag_of_peers_lock;
+static hash_map_t *peers_by_address;
+
+static bool bdaddr_equality_fn(const void *x, const void *y);
+
+// Module lifecycle functions
+
+static future_t *init(void) {
+  peers_by_address = hash_map_new(
+    number_of_address_buckets,
+    hash_function_bdaddr,
+    NULL,
+    osi_free,
+    bdaddr_equality_fn);
+
+  pthread_mutex_init(&bag_of_peers_lock, NULL);
+
+  initialized = true;
+  return NULL;
+}
+
+static future_t *clean_up(void) {
+  initialized = false;
+
+  hash_map_free(peers_by_address);
+  peers_by_address = NULL;
+
+  pthread_mutex_destroy(&bag_of_peers_lock);
+  return NULL;
+}
+
+const module_t classic_peer_module = {
+  .name = CLASSIC_PEER_MODULE,
+  .init = init,
+  .start_up = NULL,
+  .shut_down = NULL,
+  .clean_up = clean_up,
+  .dependencies = {
+    NULL
+  }
+};
+
+// Interface functions
+
+classic_peer_t *classic_peer_by_address(bt_bdaddr_t *address) {
+  assert(initialized);
+  assert(address != NULL);
+
+  classic_peer_t *peer = hash_map_get(peers_by_address, address);
+
+  if (!peer) {
+    pthread_mutex_lock(&bag_of_peers_lock);
+
+    // Make sure it didn't get added in the meantime
+    peer = hash_map_get(peers_by_address, address);
+    if (peer)
+      goto done;
+
+    // Splice in a new peer struct on behalf of the caller.
+    peer = osi_calloc(sizeof(classic_peer_t));
+    peer->address = *address;
+    hash_map_set(peers_by_address, &peer->address, peer);
+
+    pthread_mutex_unlock(&bag_of_peers_lock);
+  }
+
+done:
+  return peer;
+}
+
+const bt_bdaddr_t *classic_peer_get_address(classic_peer_t *peer) {
+  assert(peer != NULL);
+  return &peer->address;
+}
+
+// Internal functions
+
+// Wrapper for bdaddr_equals used in the hash map of peers by address
+static bool bdaddr_equality_fn(const void *x, const void *y) {
+  return bdaddr_equals((bt_bdaddr_t *)x, (bt_bdaddr_t *)y);
+}
diff --git a/device/src/controller.c b/device/src/controller.c
new file mode 100644
index 0000000..c1eadc0
--- /dev/null
+++ b/device/src/controller.c
@@ -0,0 +1,412 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_controller"
+
+#include <assert.h>
+#include <stdbool.h>
+
+#include "btcore/include/bdaddr.h"
+#include "bt_types.h"
+#include "device/include/controller.h"
+#include "btcore/include/event_mask.h"
+#include "osi/include/future.h"
+#include "hcimsgs.h"
+#include "hci/include/hci_layer.h"
+#include "hci/include/hci_packet_factory.h"
+#include "hci/include/hci_packet_parser.h"
+#include "btcore/include/module.h"
+#include "stack/include/btm_ble_api.h"
+#include "btcore/include/version.h"
+
+const bt_event_mask_t BLE_EVENT_MASK = { "\x00\x00\x00\x00\x00\x00\x00\x3f" };
+#if (BLE_INCLUDED)
+const bt_event_mask_t CLASSIC_EVENT_MASK = { HCI_DUMO_EVENT_MASK_EXT };
+#else
+const bt_event_mask_t CLASSIC_EVENT_MASK = { HCI_LISBON_EVENT_MASK_EXT };
+#endif
+
+// TODO(zachoverflow): factor out into common module
+const uint8_t SCO_HOST_BUFFER_SIZE = 0xff;
+
+#define HCI_SUPPORTED_COMMANDS_ARRAY_SIZE 64
+#define MAX_FEATURES_CLASSIC_PAGE_COUNT 3
+#define BLE_SUPPORTED_STATES_SIZE         8
+#define BLE_SUPPORTED_FEATURES_SIZE       8
+
+static const hci_t *hci;
+static const hci_packet_factory_t *packet_factory;
+static const hci_packet_parser_t *packet_parser;
+
+static bt_bdaddr_t address;
+static bt_version_t bt_version;
+
+static uint8_t supported_commands[HCI_SUPPORTED_COMMANDS_ARRAY_SIZE];
+static bt_device_features_t features_classic[MAX_FEATURES_CLASSIC_PAGE_COUNT];
+static uint8_t last_features_classic_page_index;
+
+static uint16_t acl_data_size_classic;
+static uint16_t acl_data_size_ble;
+static uint16_t acl_buffer_count_classic;
+static uint8_t acl_buffer_count_ble;
+
+static uint8_t ble_white_list_size;
+static uint8_t ble_supported_states[BLE_SUPPORTED_STATES_SIZE];
+static bt_device_features_t features_ble;
+
+static bool readable;
+static bool ble_supported;
+static bool simple_pairing_supported;
+
+#define AWAIT_COMMAND(command) future_await(hci->transmit_command_futured(command))
+
+// Module lifecycle functions
+
+static future_t *start_up(void) {
+  BT_HDR *response;
+
+  // Send the initial reset command
+  response = AWAIT_COMMAND(packet_factory->make_reset());
+  packet_parser->parse_generic_command_complete(response);
+
+  // Request the classic buffer size next
+  response = AWAIT_COMMAND(packet_factory->make_read_buffer_size());
+  packet_parser->parse_read_buffer_size_response(
+      response, &acl_data_size_classic, &acl_buffer_count_classic);
+
+  // Tell the controller about our buffer sizes and buffer counts next
+  // TODO(zachoverflow): factor this out. eww l2cap contamination. And why just a hardcoded 10?
+  response = AWAIT_COMMAND(
+    packet_factory->make_host_buffer_size(
+      L2CAP_MTU_SIZE,
+      SCO_HOST_BUFFER_SIZE,
+      L2CAP_HOST_FC_ACL_BUFS,
+      10
+    )
+  );
+
+  packet_parser->parse_generic_command_complete(response);
+
+  // Read the local version info off the controller next, including
+  // information such as manufacturer and supported HCI version
+  response = AWAIT_COMMAND(packet_factory->make_read_local_version_info());
+  packet_parser->parse_read_local_version_info_response(response, &bt_version);
+
+  // Read the bluetooth address off the controller next
+  response = AWAIT_COMMAND(packet_factory->make_read_bd_addr());
+  packet_parser->parse_read_bd_addr_response(response, &address);
+
+  // Request the controller's supported commands next
+  response = AWAIT_COMMAND(packet_factory->make_read_local_supported_commands());
+  packet_parser->parse_read_local_supported_commands_response(
+    response,
+    supported_commands,
+    HCI_SUPPORTED_COMMANDS_ARRAY_SIZE
+  );
+
+  // Read page 0 of the controller features next
+  uint8_t page_number = 0;
+  response = AWAIT_COMMAND(packet_factory->make_read_local_extended_features(page_number));
+  packet_parser->parse_read_local_extended_features_response(
+    response,
+    &page_number,
+    &last_features_classic_page_index,
+    features_classic,
+    MAX_FEATURES_CLASSIC_PAGE_COUNT
+  );
+
+  assert(page_number == 0);
+  page_number++;
+
+  // Inform the controller what page 0 features we support, based on what
+  // it told us it supports. We need to do this first before we request the
+  // next page, because the controller's response for page 1 may be
+  // dependent on what we configure from page 0
+  simple_pairing_supported = HCI_SIMPLE_PAIRING_SUPPORTED(features_classic[0].as_array);
+  if (simple_pairing_supported) {
+    response = AWAIT_COMMAND(packet_factory->make_write_simple_pairing_mode(HCI_SP_MODE_ENABLED));
+    packet_parser->parse_generic_command_complete(response);
+  }
+
+#if (BLE_INCLUDED == TRUE)
+  if (HCI_LE_SPT_SUPPORTED(features_classic[0].as_array)) {
+    uint8_t simultaneous_le_host = HCI_SIMUL_LE_BREDR_SUPPORTED(features_classic[0].as_array) ? BTM_BLE_SIMULTANEOUS_HOST : 0;
+    response = AWAIT_COMMAND(
+      packet_factory->make_ble_write_host_support(BTM_BLE_HOST_SUPPORT, simultaneous_le_host)
+    );
+
+    packet_parser->parse_generic_command_complete(response);
+  }
+#endif
+
+  // Done telling the controller about what page 0 features we support
+  // Request the remaining feature pages
+  while (page_number <= last_features_classic_page_index &&
+         page_number < MAX_FEATURES_CLASSIC_PAGE_COUNT) {
+    response = AWAIT_COMMAND(packet_factory->make_read_local_extended_features(page_number));
+    packet_parser->parse_read_local_extended_features_response(
+      response,
+      &page_number,
+      &last_features_classic_page_index,
+      features_classic,
+      MAX_FEATURES_CLASSIC_PAGE_COUNT
+    );
+
+    page_number++;
+  }
+
+#if (BLE_INCLUDED == TRUE)
+  ble_supported = last_features_classic_page_index >= 1 && HCI_LE_HOST_SUPPORTED(features_classic[1].as_array);
+  if (ble_supported) {
+    // Request the ble white list size next
+    response = AWAIT_COMMAND(packet_factory->make_ble_read_white_list_size());
+    packet_parser->parse_ble_read_white_list_size_response(response, &ble_white_list_size);
+
+    // Request the ble buffer size next
+    response = AWAIT_COMMAND(packet_factory->make_ble_read_buffer_size());
+    packet_parser->parse_ble_read_buffer_size_response(
+      response,
+      &acl_data_size_ble,
+      &acl_buffer_count_ble
+    );
+
+    // Response of 0 indicates ble has the same buffer size as classic
+    if (acl_data_size_ble == 0)
+      acl_data_size_ble = acl_data_size_classic;
+
+    // Request the ble supported states next
+    response = AWAIT_COMMAND(packet_factory->make_ble_read_supported_states());
+    packet_parser->parse_ble_read_supported_states_response(
+      response,
+      ble_supported_states,
+      sizeof(ble_supported_states)
+    );
+
+    // Request the ble supported features next
+    response = AWAIT_COMMAND(packet_factory->make_ble_read_local_supported_features());
+    packet_parser->parse_ble_read_local_supported_features_response(
+      response,
+      &features_ble
+    );
+
+    // Set the ble event mask next
+    response = AWAIT_COMMAND(packet_factory->make_ble_set_event_mask(&BLE_EVENT_MASK));
+    packet_parser->parse_generic_command_complete(response);
+  }
+#endif
+
+  if (simple_pairing_supported) {
+    response = AWAIT_COMMAND(packet_factory->make_set_event_mask(&CLASSIC_EVENT_MASK));
+    packet_parser->parse_generic_command_complete(response);
+  }
+
+  readable = true;
+  return future_new_immediate(FUTURE_SUCCESS);
+}
+
+static future_t *shut_down(void) {
+  readable = false;
+  return future_new_immediate(FUTURE_SUCCESS);
+}
+
+const module_t controller_module = {
+  .name = CONTROLLER_MODULE,
+  .init = NULL,
+  .start_up = start_up,
+  .shut_down = shut_down,
+  .clean_up = NULL,
+  .dependencies = {
+    HCI_MODULE,
+    NULL
+  }
+};
+
+// Interface functions
+
+static bool get_is_ready(void) {
+  return readable;
+}
+
+static const bt_bdaddr_t *get_address(void) {
+  assert(readable);
+  return &address;
+}
+
+static const bt_version_t *get_bt_version(void) {
+  assert(readable);
+  return &bt_version;
+}
+
+// TODO(zachoverflow): hide inside, move decoder inside too
+static const bt_device_features_t *get_features_classic(int index) {
+  assert(readable);
+  assert(index < MAX_FEATURES_CLASSIC_PAGE_COUNT);
+  return &features_classic[index];
+}
+
+static uint8_t get_last_features_classic_index(void) {
+  assert(readable);
+  return last_features_classic_page_index;
+}
+
+static const bt_device_features_t *get_features_ble(void) {
+  assert(readable);
+  assert(ble_supported);
+  return &features_ble;
+}
+
+static const uint8_t *get_ble_supported_states(void) {
+  assert(readable);
+  assert(ble_supported);
+  return ble_supported_states;
+}
+
+static bool supports_simple_pairing(void) {
+  assert(readable);
+  return simple_pairing_supported;
+}
+
+static bool supports_simultaneous_le_bredr(void) {
+  assert(readable);
+  return HCI_SIMUL_LE_BREDR_SUPPORTED(features_classic[0].as_array);
+}
+
+static bool supports_reading_remote_extended_features(void) {
+  assert(readable);
+  return HCI_READ_REMOTE_EXT_FEATURES_SUPPORTED(supported_commands);
+}
+
+static bool supports_interlaced_inquiry_scan(void) {
+  assert(readable);
+  return HCI_LMP_INTERLACED_INQ_SCAN_SUPPORTED(features_classic[0].as_array);
+}
+
+static bool supports_rssi_with_inquiry_results(void) {
+  assert(readable);
+  return HCI_LMP_INQ_RSSI_SUPPORTED(features_classic[0].as_array);
+}
+
+static bool supports_extended_inquiry_response(void) {
+  assert(readable);
+  return HCI_EXT_INQ_RSP_SUPPORTED(features_classic[0].as_array);
+}
+
+static bool supports_master_slave_role_switch(void) {
+  assert(readable);
+  return HCI_SWITCH_SUPPORTED(features_classic[0].as_array);
+}
+
+static bool supports_ble(void) {
+  assert(readable);
+  return ble_supported;
+}
+
+static bool supports_ble_connection_parameters_request(void) {
+  assert(readable);
+  assert(ble_supported);
+  return HCI_LE_CONN_PARAM_REQ_SUPPORTED(features_ble.as_array);
+}
+
+static uint16_t get_acl_data_size_classic(void) {
+  assert(readable);
+  return acl_data_size_classic;
+}
+
+static uint16_t get_acl_data_size_ble(void) {
+  assert(readable);
+  assert(ble_supported);
+  return acl_data_size_ble;
+}
+
+static uint16_t get_acl_packet_size_classic(void) {
+  assert(readable);
+  return acl_data_size_classic + HCI_DATA_PREAMBLE_SIZE;
+}
+
+static uint16_t get_acl_packet_size_ble(void) {
+  assert(readable);
+  return acl_data_size_ble + HCI_DATA_PREAMBLE_SIZE;
+}
+
+static uint16_t get_acl_buffer_count_classic(void) {
+  assert(readable);
+  return acl_buffer_count_classic;
+}
+
+static uint8_t get_acl_buffer_count_ble(void) {
+  assert(readable);
+  assert(ble_supported);
+  return acl_buffer_count_ble;
+}
+
+static const controller_t interface = {
+  get_is_ready,
+
+  get_address,
+  get_bt_version,
+
+  get_features_classic,
+  get_last_features_classic_index,
+
+  get_features_ble,
+  get_ble_supported_states,
+
+  supports_simple_pairing,
+  supports_simultaneous_le_bredr,
+  supports_reading_remote_extended_features,
+  supports_interlaced_inquiry_scan,
+  supports_rssi_with_inquiry_results,
+  supports_extended_inquiry_response,
+  supports_master_slave_role_switch,
+
+  supports_ble,
+  supports_ble_connection_parameters_request,
+
+  get_acl_data_size_classic,
+  get_acl_data_size_ble,
+
+  get_acl_packet_size_classic,
+  get_acl_packet_size_ble,
+
+  get_acl_buffer_count_classic,
+  get_acl_buffer_count_ble
+};
+
+const controller_t *controller_get_interface() {
+  static bool loaded = false;
+  if (!loaded) {
+    loaded = true;
+
+    hci = hci_layer_get_interface();
+    packet_factory = hci_packet_factory_get_interface();
+    packet_parser = hci_packet_parser_get_interface();
+  }
+
+  return &interface;
+}
+
+const controller_t *controller_get_test_interface(
+    const hci_t *hci_interface,
+    const hci_packet_factory_t *packet_factory_interface,
+    const hci_packet_parser_t *packet_parser_interface) {
+
+  hci = hci_interface;
+  packet_factory = packet_factory_interface;
+  packet_parser = packet_parser_interface;
+  return &interface;
+}
diff --git a/device/test/classic/peer_test.cpp b/device/test/classic/peer_test.cpp
new file mode 100644
index 0000000..9f8b9ac
--- /dev/null
+++ b/device/test/classic/peer_test.cpp
@@ -0,0 +1,86 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+#include "osi/test/AllocationTestHarness.h"
+
+extern "C" {
+#include "btcore/include/bdaddr.h"
+#include "btcore/include/module.h"
+#include "device/include/classic/peer.h"
+
+extern const module_t classic_peer_module;
+}
+
+class ClassicPeerTest : public AllocationTestHarness {
+  protected:
+    virtual void SetUp() {
+      AllocationTestHarness::SetUp();
+
+      module_management_start();
+      module_init(&classic_peer_module);
+    }
+
+    virtual void TearDown() {
+      module_clean_up(&classic_peer_module);
+      module_management_stop();
+
+      AllocationTestHarness::TearDown();
+    }
+};
+
+TEST_F(ClassicPeerTest, test_basic_get) {
+  bt_bdaddr_t test_address;
+  string_to_bdaddr("12:34:56:78:9A:BC", &test_address);
+
+  classic_peer_t *peer = classic_peer_by_address(&test_address);
+
+  EXPECT_TRUE(peer != NULL);
+  // The stored address should be a copy (different memory address)
+  EXPECT_NE(&test_address, classic_peer_get_address(peer));
+  EXPECT_TRUE(bdaddr_equals(&test_address, classic_peer_get_address(peer)));
+}
+
+TEST_F(ClassicPeerTest, test_multi_get_are_same) {
+  bt_bdaddr_t test_address;
+  string_to_bdaddr("12:34:56:78:9A:BC", &test_address);
+
+  classic_peer_t *peer = classic_peer_by_address(&test_address);
+  classic_peer_t *peer_again = classic_peer_by_address(&test_address);
+
+  EXPECT_TRUE(peer != NULL);
+  EXPECT_TRUE(peer_again != NULL);
+  EXPECT_EQ(peer, peer_again);
+}
+
+TEST_F(ClassicPeerTest, test_multi_get_different) {
+  bt_bdaddr_t test_address0;
+  bt_bdaddr_t test_address1;
+  string_to_bdaddr("12:34:56:78:9A:BC", &test_address0);
+  string_to_bdaddr("42:42:42:42:42:42", &test_address1);
+
+  classic_peer_t *peer0 = classic_peer_by_address(&test_address0);
+  classic_peer_t *peer1 = classic_peer_by_address(&test_address1);
+
+  EXPECT_TRUE(peer0 != NULL);
+  EXPECT_TRUE(peer1 != NULL);
+  EXPECT_TRUE(bdaddr_equals(&test_address0, classic_peer_get_address(peer0)));
+  EXPECT_TRUE(bdaddr_equals(&test_address1, classic_peer_get_address(peer1)));
+}
+
diff --git a/doc/directory_layout.md b/doc/directory_layout.md
new file mode 100644
index 0000000..a7e1496
--- /dev/null
+++ b/doc/directory_layout.md
@@ -0,0 +1,30 @@
+## Directory Layout
+
+### General directory layout
+Each directory should be a self contained subsystem consisting
+of one or more modules.
+
+* src/ - All source files for the subsystem.
+* include/ - All include files for the subsystem.
+* test/ - All unit tests for the subsystem.
+
+### Top level directory layout
+* audio_a2dp_hw - A2DP audio HAL implementation.
+* bta - *Bluetooth Application* - Strange collection of a-lot of things **Deprecate?**
+* btcore - *Bluetooth Core* - Bluetooth data type definitions and operations on those data types.
+* btif - *Bluetooth Interface* - Bluedroid JNI interface to Android.
+* conf - *Configuration* - Various configuration text files.
+* doc - *Documentation* - Stack documentation.
+* embdrv - **Deprecated** - Bluetooth SBC Codec.
+* gki - **Deprecated** *General Kernel Interface* - Eliminate - replaced by osi.
+* hci - *Host Controller Interface* - Communication protocol with bluetooth chip.
+* include - **Deprecated** - System global include files.
+* main - *Main stack entrypoint* - Provides HAL for stack access.
+* osi - *Operating System Interface* - General resource support for stack.
+* profiles - *Bluetooth Profiles* - **TBD** Collection of all profiles.
+* stack - **Deprecated** - The Stack - Push to proper spot in *./profiles*
+* test - *Test suite* - Stack level validiation and stress test suite.
+* tools - *Tools* - Various engineering support tools.
+* udrv -  **Deprecated**  *UIPC implementation*
+* utils - **Deprecated** *Bluetooth utilities* - Eliminate.
+* vnd - *Vendor* - Vendor specific APIs - *to be integrated into rest of stack ?*.
diff --git a/doc/log_tags.md b/doc/log_tags.md
new file mode 100644
index 0000000..b1b6016
--- /dev/null
+++ b/doc/log_tags.md
@@ -0,0 +1,60 @@
+Log Tags
+===
+This document lists all of the log tags used by bluedroid.
+
+* audio_a2dp_hw
+* bluedroid
+* BTA_AG_CO:
+* bta_sys_main
+* bt_btif_config
+* bt_btif_config_transcode
+* bt_classic_peer
+* bte_conf
+* BtGatt.btif
+* BtGatt.btif_test
+* bt_gki
+* bt_hci
+* bt_hci_h4
+* bt_hci_inject
+* bt_hci_mct
+* bt_hci_packet_fragmenter
+* BTIF_AV
+* BTIF_CORE
+* BTIF_HF
+* BTIF_HF_CLIENT
+* BTIF_HH
+* BTIF_HL
+* BTIF-MEDIA
+* BTIF_PAN
+* BTIF_QUEUE
+* BTIF_RC
+* BTIF_SM
+* btif_sock
+* BTIF_SOCK
+* btif_sock_rfcomm
+* btif_sock_sco
+* BTIF_SOCK_SDP
+* BTIF_STORAGE
+* BTIF_UTIL
+* BTLD
+* bt_low_power_manager
+* bt_module
+* bt_osi_alarm
+* bt_osi_config
+* bt_osi_data_dispatcher
+* bt_osi_reactor
+* bt_osi_socket
+* bt_profile_manager
+* bt_sdp_client
+* btsnoop
+* btsnoop_net
+* bt_stack_config
+* bt_stack_manager
+* bt_task
+* btu_task
+* BT_UTILS
+* bt_vendor
+* osi_eager_reader
+* osi_future
+* osi_semaphore
+* osi_thread
diff --git a/doc/network_ports.md b/doc/network_ports.md
new file mode 100644
index 0000000..731ed79
--- /dev/null
+++ b/doc/network_ports.md
@@ -0,0 +1,7 @@
+Network Ports
+===
+This document lists all of the network ports used by bluedroid. It should be
+used as a reference and as a mechanism to avoid port namespace conflicts.
+
+* TCP 8872 (hci/src/btsnoop_net.c) - read live btsnoop logs
+* TCP 8873 (hci/src/hci_inject.c) - inject HCI packets into HCI stream
diff --git a/doc/power_management.md b/doc/power_management.md
new file mode 100644
index 0000000..ae90d29
--- /dev/null
+++ b/doc/power_management.md
@@ -0,0 +1,202 @@
+## Power Management
+
+### Overview
+
+Power management (PM) in bluedroid is an event-driven state machine, tickled by
+various `bta/sys` events via a callback. The actual state switching calls are
+handled by the BTM HCI interfacing code, with results being posted back to the
+PM code via the BTA workqueue thread.
+
+Power states are managed per-device, per-profile, so every incoming event
+includes a profile ID, app ID, and a `BD_ADDR`.
+
+The events fired to drive the state machine at the time of this writing are:
+
+  - `BTA_SYS_CONN_OPEN`
+  - `BTA_SYS_CONN_CLOSE`
+  - `BTA_SYS_CONN_IDLE`
+  - `BTA_SYS_CONN_BUSY`
+  - `BTA_SYS_APP_OPEN`
+  - `BTA_SYS_APP_CLOSE`
+  - `BTA_SYS_SCO_OPEN`
+  - `BTA_SYS_SCO_CLOSE`
+
+Each of these correspond to a function name in `bta/sys/bta_sys_conn.c`, which
+are called by each profile definition in `bta/$PROFILE`.
+
+The PM code makes calls into the BTM module to set various power
+states. Responses are handled in an asynchronous fashion, primarily via the
+callbacks `bta_dm_pm_cback` and `bta_dm_pm_timer_cback`. Responses are handled
+through the BTA workqueue thread and the `bta_dm_pm_btm_status` function. Since
+we might possibly get into a bad state where we never hear back from the
+controller, timers are used to post messages to the BTA workqueue thread as
+well, which filters down through the same status function.
+
+Overall power states are managed *per device*, not per connection, but the power
+policy is determined by the greatest allowable power action defined across all
+currently known connections to a given device. Thus, if RFCOMM specifies that
+it's willing to go to into SNIFF and specifies that as an action, and say, a PAN
+connection is up which specifies it is willing to go into SNIFF, but its action
+states it wants ACTIVE, the power management code will change to ACTIVE.
+
+### Power management tables
+
+The tables that determine which power levels are acceptable for which profiles
+and what actions to take for the above events are defined in the
+`bta/dm/bta_dm_cfg.c` file, as `bta_dm_pm_cfg`, `bta_dm_pm_spec`, and
+`bta_dm_ssr_spec`.
+
+During a lookup attempt, the code iterates over the `bta_dm_pm_cfg` array,
+looking for a match between the profile and app IDs. When it finds one, it uses
+the `spec_idx` field to index into `bta_dm_pm_spec` array to determine which
+power modes are acceptable and what actions to take for each event.
+
+The action constants are defined in `bta_api.h` and are defined as a series of
+hex bitfields. The actual actions taken are determined by the
+`bta_dm_pm_set_mode` function, but a few of the actions listed deserve some
+additional description:
+
+  - `BTA_DM_PM_NO_ACTION` is effectively a no-op and has a value of zero, so any
+    other profile will override this.
+  - `BTA_DM_PM_NO_PREF` overrides `BTA_DM_PM_NO_ACTION` and if selected as the
+    action that `bta_dm_pm_set_mode` will take, the connection will be removed
+    from `bta_dm_conn_srvcs` and no longer be considered for power management
+    decisions.
+  - `BTA_DM_PM_SNIFF` through `BTA_DM_PM_SNIFF4` are special, in that each
+    level specifies a set of parameters for the SNIFF mode which relate to the
+    min and max intervals, the number of attempts and the timeout. The overall
+    action is still the same, however -- SNIFF mode is attempted. There are
+    definitions available up to SNIFF7, but actual SSR values are only defined
+    up to SNIFF4. Params are defined in `bta_dm_ssr_spec`.
+  - `BTA_DM_PM_ACTIVE` is full-on power.
+  - `BTA_DM_PM_RETRY` has the same effect as `BTA_DM_PM_NO_ACTION`, except a
+    timeout is possible to be set, which effectively allows a power operation to
+    be "retried".
+
+### Initialization
+
+`bta_dm_pm.c`'s `bta_dm_init_pm` function calls out to register
+`bta_dm_pm_cback` with the bta sys module for incoming power management events,
+and also registers `bta_dm_pm_btm_cback` with the btm module to handle responses
+and timeouts of HCI requests (via `bta_dm_pm_btm_status`).
+
+At this point, the power managment code is basically done until the first set of
+events come in through `bta_dm_pm_cback`.
+
+Throughout the `bta_dm_pm.c` file, connections whose power management states are
+managed are tracked in a global array called `bta_dm_conn_srvcs`. Unfortunately,
+while this variable is declared as an extern in the `bta_dm_int.h` file, it only
+seems to be used in the `bta_dm_act.c` file, and only for reinitialization.
+
+### Event flow
+
+#### Events fired from SYS
+
+  1. An event is fired from one of the methods mentioned above in
+     `bta/sys/bta_sys_conn.c`
+  2. The `bta_dm_pm_cback` function is called.
+     - The power mode config is looked up in the `bta_dm_pm_cfg` table. If none
+       are found for the given profile ID and app ID, the function simply
+       returns with no action taken.
+     - If any timers were set for the given `BD_ADDR`, they are stopped.
+     - The SSR params for the CONN_OPEN event are looked up.
+     - The power spec state table (`bta_dm_pm_spec`) is checked to see if
+       there's no action to be performed (`BTA_DM_PM_NO_ACTION`), and if so,
+       returns with no action taken.
+     - `bta_dm_conn_srvcs` is consulted to ensure there's an entry for this
+       connection if it's supposed to be managed according to the power spec
+       state tables. If the spec specifies `BTA_DM_PM_NO_PREF`, then any
+       existing entry in this list is removed, otherwise one is added/updated
+       with the state given to the function.
+  3. `bta_dm_pm_cback` checks to see if the `bta_dm_ssr_spec` specifies SSR
+     adjustments are to be made, and if so, `bta_dm_pm_ssr` is called with the
+     peer `BD_ADDR`.
+     - `bta_dm_pm_ssr` iterates the managed services array to find all connected
+       services for the given `BD_ADDR`, then looks up the ssr values from the
+       `bta_dm_ssr_spec` tables, looking for the smallest max latency to use.
+     - `bta_dm_pm_ssr` calls `BTM_SetSsrParams` to actually send along the SSR
+       params to the bluetooth chip.
+  4. `bta_dm_pm_cback` calls `bta_dm_pm_set_mode` with the peer address and the
+     `timed_out` parameter set to `false`.
+     - For each managed connection, `bta_dm_pm_set_mode` grabs
+       both actions specified for the profile in the `bta_dm_pm_spec` tables. If
+       the first power management action didn't timeout (or was never attempted,
+       according to the `tBTA_DM_PEER_DEVICE` `pm_mode_failed` and
+       `pm_mode_attempted` fields), its timeout and mode are used. Otherwise,
+       the same check is done against the second action and it is used
+       instead. If both actions have been attempted, then the action is set to
+       `BTA_DM_PM_NO_ACTION`. Only the highest power mode action is chosen from
+       all connected profiles.
+     - If the chosen action is `BTA_DM_PM_PARK` or `BTA_DM_PM_SNIFF` but the
+       profile doesn't allow it, this function takes no action.
+     - If a timeout is specified in the power spec table, then an unused timer
+       in `bta_dm_cb.pm_timer` is started.
+     - If the action chosen is `BTA_DM_PM_PARK`, `bta_dm_pm_park` is called,
+       which calls `BTM_ReadPowerMode` and `BTM_SetPowerMode` to make an HCI
+       request to enable PARK for the given peer and connection.
+     - If the action chosen is `BTA_DM_PM_SNIFF`, the peer device's link policy
+       is checked to see if it's allowed. If so, then `bta_dm_pm_sniff` is
+       called, which makes various calls to `BTM_ReadLocalFeatures`,
+       `BTM_ReadRemoteFeatures` and `BTM_SetPowerMode` to ensure SNIFF mode is
+       enabled.
+     - If the action chosen is `BTA_DM_PM_ACTIVE`, a call to `bta_dm_pm_active`
+       is made, which calls `BTM_SetPowerMode` to set the link into ACTIVE
+       mode.
+
+At this point, if one of the timers in `bta_dm_cb.pm_timer` times out, a call is
+made through the BTA workqueue thread to `bta_dm_pm_btm_cback`, which then
+triggers `bta_dm_pm_btm_status`, with the timeout field set to TRUE. HCI
+responses are also fired as messages through the BTA workqueue thread, which are
+handled again, through `bta_dm_pm_btm_status`.
+
+#### Events fired through BTM
+
+Essentially these messages eventually go through the same functions as events
+fired from the SYS side of things, except from the initial path they take:
+
+  1. An event is fired from a callback in BTM to `bta_dm_pm_btm_cback`.
+  2. `bta_dm_pm_btm_cback` packages up the given parameters into a
+     `tBTA_DM_PM_BTM_STATUS` struct and posts it to the BTA workqueue thread via
+     `bta_sys_sendmsg`, with the event header set to
+     `BTA_DM_PM_BTM_STATUS_EVT`.
+  3. This is eventually routed to the `bta_dm_pm_btm_status` function.
+     **Determine if this is running on the workqueue thread or not**
+     - The message `status` passed in is actually the current status of the
+       device.
+     - If the status is `BTM_PM_STS_ACTIVE` (still in the ACTIVE power mode),
+       checks the HCI status code:
+       - If that's non-zero and a PARK or SNIFF mode change was attempted,
+         `bta_dm_pm_btm_status` stops any timers started for the device in
+         `bta_dm_pm_set_mode`, clears some status bits in the peer device
+         structure, and then calls back into `bta_dm_pm_set_mode` with the peer
+         device address and timeout set to FALSE.
+       - If the status is zero, and if the peer device `tBTA_DM_PEER_DEVICE`
+         `prev_low` field is set, calls `bta_dm_pm_ssr` to re-send SSR params,
+         stops all timers for the device, and then re-calls `bta_dm_pm_set_mode`
+         with timeout set to FALSE to re-attempt with a second action (if the
+         previous PARK or SNIFF failed, otherwise it'll re-attempt the first
+         action).
+     - If the status is `BTM_PM_STS_PARK` or `BTM_PM_STS_HOLD`, saves the
+       previous low power mode in the peer device's `prev_low` field.
+     - If the status is `BTM_PM_STS_SSR`, simply clears or sets the device
+       `info` field's `BTA_DM_DI_USE_SSR` bit, depending on the value of
+       `tBTA_DM_MSG.value`, which determines if the device can handle SSR.
+     - If the status is `BTM_PM_STS_SNIFF` and the info field has the
+       `BTA_DM_DI_SET_SNIFF` bit set, then `BTA_DM_DI_INT_SNIFF` is set,
+       otherwise `BTA_DM_DI_ACP_SNIFF` is set.
+     - If `BTA_PM_STS_ERROR`, the `BTA_DM_DI_SET_SNIFF` bit is cleared in the
+       device info field.
+
+At this point, either the method simply returns, or has called back into
+`bta_dm_pm_set_mode`, in which case the usual flow takes over.
+
+#### Events fired from timers
+
+Timers are used exclusively for handling HCI command timeouts, and filter
+through to a call to `bta_dm_pm_set_mode`:
+
+  1. A timer expires, and calls `bta_dm_pm_timer_cback`.
+  2. `bta_dm_pm_timer_cback` clears the use flag on the timer that fired, and
+     sends off an event to the BTA workqueue thread.
+  3. The event eventually fires off a call to `bta_dm_pm_timer`, which just
+     calls `bta_dm_pm_set_mode` with timeout set to `TRUE`.
diff --git a/doc/properties.md b/doc/properties.md
index b279b01..7d1edca 100644
--- a/doc/properties.md
+++ b/doc/properties.md
@@ -4,7 +4,11 @@
 
 Please keep the following list in alphabetical order.
 
-### TODO (Broadcom): write descriptions of what each property means and how
+* ``` bluetooth.enable_timeout_ms ```  
+  Maximum amount of time Bluetooth can take to start-up, upload firmware etc.  
+  Used in hci/src/hci_layer.c, default 8000.
+
+### TODO: write descriptions of what each property means and how
 it's used.
 
 * ``` debug.sys.noschedgroups ```
diff --git a/doc/style_guide.md b/doc/style_guide.md
new file mode 100644
index 0000000..f2f2804
--- /dev/null
+++ b/doc/style_guide.md
@@ -0,0 +1,260 @@
+# Bluedroid Style Guide
+This document outlines the coding conventions and code style used in Bluedroid.
+Its primary purpose is to provide explicit guidance on style so that developers
+are consistent with one another and spend less time debating style.
+
+## Directory structure
+Directories at the top-level should consist of major subsystems in Bluedroid.
+Each subsystem's purpose should be documented in the `doc/directory_layout.md`
+file, even if it seems obvious from the name.
+
+For a subsystem that contains code, its directory structure should look like:
+```
+  Android.mk
+  include/
+  src/
+  test/
+```
+Further, the directory structure inside `src/` and `include/` should be
+mirrored. In other words, if `src/` contains a subdirectory called `foo/`,
+`include/` must also have a subdirectory named `foo/`.
+
+## Target architecture
+Bluedroid targets a variety of hardware and cannot make many assumptions about
+memory layout, sizes, byte order, etc. As a result, some operations are
+considered unsafe and this section outlines the most important ones to watch out
+for.
+
+### Pointer / integer casts
+In general, do not cast pointers to integers or vice versa.
+
+The one exception is if an integer needs to be temporarily converted to a
+pointer and then back to the original integer. This style of code is typically
+needed when providing an integral value as the context to a callback, as in the
+following example.
+```
+void my_callback(void *context) {
+  uintptr_t arg = context;
+}
+
+set_up_callback(my_callback, (uintptr_t)5);
+```
+Note, however, that the integral value was written into the pointer and read
+from the pointer as a `uintptr_t` to avoid a loss of precision (or to make the
+loss explicit).
+
+### Byte order
+It is not safe to assume any particular byte order. When serializing or
+deserializing data, it is unsafe to memcpy unless both source and destination
+pointers have the same type.
+
+## Language
+Bluedroid is written in C99 and should take advantage of the features offered by
+it. However, not all language features lend themselves well to the type of
+development required by Bluedroid. This section provides guidance on some of the
+features to embrace or avoid.
+
+### C Preprocessor
+The use of the C preprocessor should be minimized. In particular:
+* use functions or, if absolutely necessary, inline functions instead of macros
+* use `static const` variables instead of `#define`
+* use `enum` for enumerations, not a collection of `#define`s
+* minimize the use of feature / conditional macros
+
+The last point is perhaps the most contentious. It's well-understood that
+feature macros are useful in reducing code size but it leads to an exponential
+explosion in build configurations. Setting up, testing, and verifying each of
+the `2^n` build configurations is untenable for `n` greater than, say, 4.
+
+### C++
+Although C++ offers constructs that may make Bluedroid development faster,
+safer, more pleasant, etc. the decision _for the time being_ is to stick with
+pure C99. The exceptions are when linking against libraries that are written
+in C++. At the time of writing these libraries are `gtest` and `tinyxml2`,
+where the latter is a dependency that should be eliminated in favor of simpler,
+non-XML formats.
+
+### Variadic functions
+Variadic functions are dangerous and should be avoided for most code. The
+exception is when implementing logging since the benefits of readability
+outweigh the cost of safety.
+
+### Functions with zero arguments
+Functions that do not take any arguments (0 arity) should be declared like so:
+```
+void function(void);
+```
+Note that the function explicitly includes `void` in its parameter list to
+indicate to the compiler that it takes no arguments.
+
+### Contiguous memory structs
+Use C99 flexible arrays as the last member of a struct if the array needs
+to be allocated in contiguous memory with its containing struct.
+A flexible array member is writen as array_name[] without a specific size.  
+For example:
+```
+typedef struct {
+  size_t length;
+  uint8_t data[];
+} buffer_t;
+
+// Allocate a buffer with 128 bytes available for my_buffer->data.
+buffer_t *my_buffer = malloc(sizeof(buffer_t) + 128);
+uint8_t *data = my_buffer->data;
+```
+
+### Pointer arithmetic
+Avoid pointer arithmetic when possible as it results in difficult to read code.
+Prefer array-indexing syntax over pointer arithmetic.
+
+In particular, do not write code like this:
+```
+typedef struct {
+  size_t length;
+} buffer_t;
+
+buffer_t *my_buffer = malloc(sizeof(buffer_t) + 128);
+uint8_t *data = (uint8_t *)(my_buffer + 1);
+```
+Instead, use zero-length arrays as described above to avoid pointer arithmetic
+and array indexing entirely.
+
+### Boolean type
+Use the C99 `bool` type with values `true` and `false` defined in `stdbool.h`.
+Not only is this a standardized type, it is also safer and provides more
+compile-time checks.
+
+### Booleans instead of bitfields
+Use booleans to represent boolean state, instead of a set of masks into an
+integer. It's more transparent and readable, and less error prone.
+
+## Header files
+In general, every source file (`.c` or `.cpp`) in a `src/` directory should
+have a corresponding header (`.h`) in the `include/` directory.
+
+### Template header file
+```
+[copyright header]
+
+#pragma once
+
+#include <system/a.h>
+#include <system/b.h>
+
+#include "subsystem/include/a.h"
+#include "subsystem/include/b.h"
+
+typedef struct alarm_t alarm_t;
+typedef struct list_t list_t;
+
+// This comment describes the following function. It is not a structured
+// comment, it's English prose. Function arguments can be referred to as
+// |param|. This function returns true if a new object was created, false
+// otherwise.
+bool template_new(const list_t *param);
+
+// Each public function must have a comment describing its semantics. In
+// particular, edge cases, and whether a pointer argument may or may not be
+// NULL.
+void template_use_alarm(alarm_t *alarm);
+```
+
+### License header
+Each header file must begin with the following Apache 2.0 License with `<year>`
+and `<owner>` replaced with the year in which the file was authored and the
+owner of the copyright, respectively.
+```
+/******************************************************************************
+ *
+ *  Copyright (C) <year> <owner>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+```
+
+### Include guard
+After the license header, each header file must contain the include guard:
+```
+#pragma once
+```
+This form is used over traditional `#define`-based include guards as it is less
+error-prone, doesn't pollute the global namespace, is more compact, and can
+result in faster compilation.
+
+## Formatting
+Code formatting is pretty arbitrary, but the codebase is easier to follow if
+everyone uses the same style. Individuals may not agree with every aspect of
+the formatting rules, and some of the rules may take some getting used to,
+but it is important that all engineers follow the formatting rules so we can all
+understand and read the code easily.
+
+### White space
+* use only spaces, indent 2 spaces at a time
+* no trailing whitespaces at the end of a line
+* no tab characters
+* use one blank line to separate logical code blocks, function definitions,
+  and sections of a file
+
+```
+// Space after keyword in conditionals and loops.
+// No space immeidately before or after parentheses.
+if (foo)
+
+// Space surrounding binary operators.
+if (foo < 5)
+
+// Space after comma.
+for (int x = 0, y = 0; x; ++y)
+
+// No space between unary operators and their argument.
+++x;
+z = -y;
+
+// No space between function name and open parenthesis.
+call_my_fn(arg1, arg2);
+
+// Space before * in variable declaration.
+int *x = NULL;
+
+// Space after // beginning a comment.
+// Notice the space between "//" and "N".
+```
+
+Use only spaces, and indent 2 spaces at a time. Do not use tab characters in the
+codebase.
+
+Use a single blank line to separate logical code blocks, function definitions,
+and sections of a file.
+
+### Brace style
+```
+// Open curly braces are never on a line by themselves.
+void my_function(void) {
+  // Conditional statements with only one child statement should elide braces.
+  // The child statement must be on a new line, indented by 2 spaces.
+  if (foo)
+    do_bar();
+  else
+    do_baz();
+
+  // Conditionals with a branch containing more than one child statement forces
+  // braces on both branches.
+  if (foo) {
+    do_bar();
+  } else {
+    do_baz();
+    ++var1;
+  }
+}
+```
diff --git a/embdrv/sbc/encoder/include/sbc_encoder.h b/embdrv/sbc/encoder/include/sbc_encoder.h
index 78ed044..a1c963f 100644
--- a/embdrv/sbc/encoder/include/sbc_encoder.h
+++ b/embdrv/sbc/encoder/include/sbc_encoder.h
@@ -194,8 +194,8 @@
 extern "C"
 {
 #endif
-SBC_API extern void SBC_Encoder(SBC_ENC_PARAMS *strEncParams);
-SBC_API extern void SBC_Encoder_Init(SBC_ENC_PARAMS *strEncParams);
+extern void SBC_Encoder(SBC_ENC_PARAMS *strEncParams);
+extern void SBC_Encoder_Init(SBC_ENC_PARAMS *strEncParams);
 #ifdef __cplusplus
 }
 #endif
diff --git a/embdrv/sbc/encoder/include/sbc_types.h b/embdrv/sbc/encoder/include/sbc_types.h
index d161051..991fc7d 100644
--- a/embdrv/sbc/encoder/include/sbc_types.h
+++ b/embdrv/sbc/encoder/include/sbc_types.h
@@ -29,7 +29,7 @@
 #include "bt_target.h"
 #endif
 
-#include "data_types.h"
+#include "bt_types.h"
 
 typedef short SINT16;
 typedef long SINT32;
diff --git a/gki/Android.mk b/gki/Android.mk
index b39bcf6..76f5790 100644
--- a/gki/Android.mk
+++ b/gki/Android.mk
@@ -5,9 +5,12 @@
 LOCAL_C_INCLUDES := \
 	$(LOCAL_PATH)/common \
 	$(LOCAL_PATH)/ulinux \
+	$(LOCAL_PATH)/../btcore/include \
 	$(LOCAL_PATH)/../include \
+	$(LOCAL_PATH)/../osi/include \
 	$(LOCAL_PATH)/../stack/include \
 	$(LOCAL_PATH)/../utils/include \
+	$(LOCAL_PATH)/../ \
 	$(bdroid_C_INCLUDES)
 
 LOCAL_CFLAGS += -Wno-error=unused-parameter $(bdroid_CFLAGS) -std=c99
@@ -19,8 +22,6 @@
 
 LOCAL_SRC_FILES := \
 	./common/gki_buffer.c \
-	./common/gki_debug.c \
-	./common/gki_time.c \
 	./ulinux/gki_ulinux.c
 
 LOCAL_MODULE := libbt-brcm_gki
diff --git a/gki/common/gki.h b/gki/common/gki.h
index 8bbcd10..cf1c48c 100644
--- a/gki/common/gki.h
+++ b/gki/common/gki.h
@@ -15,66 +15,13 @@
  *  limitations under the License.
  *
  ******************************************************************************/
-#ifndef GKI_H
-#define GKI_H
 
+#pragma once
 
 #include "bt_target.h"
 #include "bt_types.h"
 
-/* Error codes */
-#define GKI_SUCCESS         0x00
-#define GKI_FAILURE         0x01
-#define GKI_INVALID_TASK    0xF0
-#define GKI_INVALID_POOL    0xFF
-
-
-/************************************************************************
-** Mailbox definitions. Each task has 4 mailboxes that are used to
-** send buffers to the task.
-*/
-#define TASK_MBOX_0    0
-#define TASK_MBOX_1    1
-#define TASK_MBOX_2    2
-#define TASK_MBOX_3    3
-
-#define NUM_TASK_MBOX  4
-
-/************************************************************************
-** Event definitions.
-**
-** There are 4 reserved events used to signal messages rcvd in task mailboxes.
-** There are 4 reserved events used to signal timeout events.
-** There are 8 general purpose events available for applications.
-*/
-#define MAX_EVENTS              16
-
-#define TASK_MBOX_0_EVT_MASK   0x0001
-#define TASK_MBOX_1_EVT_MASK   0x0002
-#define TASK_MBOX_2_EVT_MASK   0x0004
-#define TASK_MBOX_3_EVT_MASK   0x0008
-
-
-#define TIMER_0             0
-#define TIMER_1             1
-#define TIMER_2             2
-#define TIMER_3             3
-
-#define TIMER_0_EVT_MASK    0x0010
-#define TIMER_1_EVT_MASK    0x0020
-#define TIMER_2_EVT_MASK    0x0040
-#define TIMER_3_EVT_MASK    0x0080
-
-#define APPL_EVT_0          8
-#define APPL_EVT_1          9
-#define APPL_EVT_2          10
-#define APPL_EVT_3          11
-#define APPL_EVT_4          12
-#define APPL_EVT_5          13
-#define APPL_EVT_6          14
-#define APPL_EVT_7          15
-
-#define EVENT_MASK(evt)       ((UINT16)(0x0001 << (evt)))
+static const char GKI_MODULE[] = "gki_module";
 
 /* Timer list entry callback type
 */
@@ -97,34 +44,16 @@
     UINT8         in_use;
 } TIMER_LIST_ENT;
 
-/* Define a timer list queue
-*/
-typedef struct
-{
-    TIMER_LIST_ENT   *p_first;
-    TIMER_LIST_ENT   *p_last;
-} TIMER_LIST_Q;
-
-
 /***********************************************************************
 ** This queue is a general purpose buffer queue, for application use.
 */
 typedef struct
 {
-    void    *p_first;
-    void    *p_last;
-    UINT16   count;
+    void    *_p_first;
+    void    *_p_last;
+    UINT16   _count;
 } BUFFER_Q;
 
-#define GKI_IS_QUEUE_EMPTY(p_q) ((p_q)->count == 0)
-
-/* Task constants
-*/
-#ifndef TASKPTR
-typedef void (*TASKPTR)(UINT32);
-#endif
-
-
 #define GKI_PUBLIC_POOL         0       /* General pool accessible to GKI_getbuf() */
 #define GKI_RESTRICTED_POOL     1       /* Inaccessible pool to GKI_getbuf() */
 
@@ -132,101 +61,38 @@
 ** Function prototypes
 */
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Task management
-*/
-GKI_API extern UINT8   GKI_create_task (TASKPTR, UINT8, INT8 *, UINT16 *, UINT16);
-GKI_API extern void    GKI_destroy_task(UINT8 task_id);
-GKI_API extern void    GKI_task_self_cleanup(UINT8 task_id);
-GKI_API extern void    GKI_exit_task(UINT8);
-GKI_API extern UINT8   GKI_get_taskid(void);
-GKI_API extern void    GKI_init(void);
-GKI_API extern void    GKI_shutdown(void);
-GKI_API extern INT8   *GKI_map_taskname(UINT8);
-GKI_API extern void    GKI_run(void);
-GKI_API extern void    GKI_stop(void);
-
-/* To send buffers and events between tasks
-*/
-GKI_API extern void   *GKI_read_mbox  (UINT8);
-GKI_API extern void    GKI_send_msg   (UINT8, UINT8, void *);
-GKI_API extern UINT8   GKI_send_event (UINT8, UINT16);
-
-
 /* To get and release buffers, change owner and get size
 */
-GKI_API extern void    GKI_freebuf (void *);
-GKI_API extern void   *GKI_getbuf (UINT16);
-GKI_API extern UINT16  GKI_get_buf_size (void *);
-GKI_API extern void   *GKI_getpoolbuf (UINT8);
-GKI_API extern UINT16  GKI_poolcount (UINT8);
-GKI_API extern UINT16  GKI_poolfreecount (UINT8);
-GKI_API extern UINT16  GKI_poolutilization (UINT8);
+void    GKI_freebuf (void *);
+void   *GKI_getbuf (UINT16);
+UINT16  GKI_get_buf_size (void *);
+void   *GKI_getpoolbuf (UINT8);
+UINT16  GKI_poolcount (UINT8);
+UINT16  GKI_poolfreecount (UINT8);
+UINT16  GKI_poolutilization (UINT8);
 
 
 /* User buffer queue management
 */
-GKI_API extern void   *GKI_dequeue  (BUFFER_Q *);
-GKI_API extern void    GKI_enqueue (BUFFER_Q *, void *);
-GKI_API extern void    GKI_enqueue_head (BUFFER_Q *, void *);
-GKI_API extern void   *GKI_getfirst (BUFFER_Q *);
-GKI_API extern void   *GKI_getlast (BUFFER_Q *);
-GKI_API extern void   *GKI_getnext (void *);
-GKI_API extern void    GKI_init_q (BUFFER_Q *);
-GKI_API extern BOOLEAN GKI_queue_is_empty(BUFFER_Q *);
-GKI_API extern void   *GKI_remove_from_queue (BUFFER_Q *, void *);
-GKI_API extern UINT16  GKI_get_pool_bufsize (UINT8);
+void   *GKI_dequeue  (BUFFER_Q *);
+void    GKI_enqueue (BUFFER_Q *, void *);
+void   *GKI_getfirst (BUFFER_Q *);
+void   *GKI_getlast (BUFFER_Q *);
+void   *GKI_getnext (void *);
+void    GKI_init_q (BUFFER_Q *);
+UINT16  GKI_queue_length(BUFFER_Q *);
+BOOLEAN GKI_queue_is_empty(BUFFER_Q *);
+void   *GKI_remove_from_queue (BUFFER_Q *, void *);
+UINT16  GKI_get_pool_bufsize (UINT8);
 
 /* Timer management
 */
-GKI_API extern void    GKI_add_to_timer_list (TIMER_LIST_Q *, TIMER_LIST_ENT  *);
-GKI_API extern void    GKI_delay(UINT32);
-GKI_API extern UINT32  GKI_get_tick_count(void);
-GKI_API extern void    GKI_init_timer_list (TIMER_LIST_Q *);
-GKI_API extern INT32   GKI_ready_to_sleep (void);
-GKI_API extern BOOLEAN GKI_remove_from_timer_list (TIMER_LIST_Q *, TIMER_LIST_ENT  *);
-GKI_API extern void    GKI_start_timer(UINT8, INT32, BOOLEAN);
-GKI_API extern void    GKI_stop_timer (UINT8);
-GKI_API extern void    GKI_timer_update(INT32);
-GKI_API extern UINT16  GKI_update_timer_list (TIMER_LIST_Q *, INT32);
-GKI_API extern UINT32  GKI_get_remaining_ticks (TIMER_LIST_Q *, TIMER_LIST_ENT  *);
-GKI_API extern UINT16  GKI_wait(UINT16, UINT32);
-GKI_API extern BOOLEAN GKI_timer_queue_is_empty(const TIMER_LIST_Q *timer_q);
-GKI_API extern TIMER_LIST_ENT *GKI_timer_getfirst(const TIMER_LIST_Q *timer_q);
-GKI_API extern INT32 GKI_timer_ticks_getinitial(const TIMER_LIST_ENT *tle);
+void    GKI_delay(UINT32);
 
 /* Disable Interrupts, Enable Interrupts
 */
-GKI_API extern void    GKI_enable(void);
-GKI_API extern void    GKI_disable(void);
-
-/* Allocate (Free) memory from an OS
-*/
-GKI_API extern void     *GKI_os_malloc (UINT32);
-GKI_API extern void      GKI_os_free (void *);
+void    GKI_enable(void);
+void    GKI_disable(void);
 
 /* os timer operation */
-GKI_API extern UINT32 GKI_get_os_tick_count(void);
-
-/* Exception handling
-*/
-GKI_API extern void    GKI_exception (UINT16, char *);
-
-#if GKI_DEBUG == TRUE
-GKI_API extern void    GKI_PrintBufferUsage(UINT8 *p_num_pools, UINT16 *p_cur_used);
-GKI_API extern void    GKI_PrintBuffer(void);
-GKI_API extern void    GKI_print_task(void);
-#else
-#undef GKI_PrintBufferUsage
-#define GKI_PrintBuffer() NULL
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif
+UINT32 GKI_get_os_tick_count(void);
diff --git a/gki/common/gki_buffer.c b/gki/common/gki_buffer.c
index 1d176b3..78f08d9 100644
--- a/gki/common/gki_buffer.c
+++ b/gki/common/gki_buffer.c
@@ -15,13 +15,25 @@
  *  limitations under the License.
  *
  ******************************************************************************/
+
+#include <assert.h>
+
+#include "osi/include/allocator.h"
 #include "gki_int.h"
-#include <cutils/log.h>
 
 #if (GKI_NUM_TOTAL_BUF_POOLS > 16)
 #error Number of pools out of range (16 Max)!
 #endif
 
+#define ALIGN_POOL(pl_size)  ( (((pl_size) + 3) / sizeof(UINT32)) * sizeof(UINT32))
+#define BUFFER_HDR_SIZE     (sizeof(BUFFER_HDR_T))                  /* Offset past header */
+#define BUFFER_PADDING_SIZE (sizeof(BUFFER_HDR_T) + sizeof(UINT32)) /* Header + Magic Number */
+#define MAGIC_NO            0xDDBADDBA
+
+#define BUF_STATUS_FREE     0
+#define BUF_STATUS_UNLINKED 1
+#define BUF_STATUS_QUEUED   2
+
 /*******************************************************************************
 **
 ** Function         gki_init_free_queue
@@ -47,13 +59,11 @@
     act_size = (UINT16)(tempsize + BUFFER_PADDING_SIZE);
 
     /* Remember pool start and end addresses */
-// btla-specific ++
     if(p_mem)
     {
         p_cb->pool_start[id] = (UINT8 *)p_mem;
         p_cb->pool_end[id]   = (UINT8 *)p_mem + (act_size * total);
     }
-// btla-specific --
 
     p_cb->pool_size[id]  = act_size;
 
@@ -63,14 +73,12 @@
     p_cb->freeq[id].max_cnt   = 0;
 
     /* Initialize  index table */
-// btla-specific ++
     if(p_mem)
     {
         hdr = (BUFFER_HDR_T *)p_mem;
-        p_cb->freeq[id].p_first = hdr;
+        p_cb->freeq[id]._p_first = hdr;
         for (i = 0; i < total; i++)
         {
-            hdr->task_id = GKI_INVALID_TASK;
             hdr->q_id    = id;
             hdr->status  = BUF_STATUS_FREE;
             magic        = (UINT32 *)((UINT8 *)hdr + BUFFER_HDR_SIZE + tempsize);
@@ -80,54 +88,25 @@
             hdr1->p_next = hdr;
         }
         hdr1->p_next = NULL;
-        p_cb->freeq[id].p_last = hdr1;
+        p_cb->freeq[id]._p_last = hdr1;
     }
-// btla-specific --
-    return;
 }
 
-// btla-specific ++
-#ifdef GKI_USE_DEFERED_ALLOC_BUF_POOLS
-static BOOLEAN gki_alloc_free_queue(UINT8 id)
-{
-    FREE_QUEUE_T  *Q;
-    tGKI_COM_CB *p_cb = &gki_cb.com;
-    GKI_TRACE("\ngki_alloc_free_queue in, id:%d \n", (int)id );
-
-    Q = &p_cb->freeq[p_cb->pool_list[id]];
-
-    if(Q->p_first == 0)
-    {
-        void* p_mem = GKI_os_malloc((Q->size + BUFFER_PADDING_SIZE) * Q->total);
-        if(p_mem)
-        {
-            //re-initialize the queue with allocated memory
-            GKI_TRACE("\ngki_alloc_free_queue calling  gki_init_free_queue, id:%d  size:%d, totol:%d\n", id, Q->size, Q->total);
-            gki_init_free_queue(id, Q->size, Q->total, p_mem);
-            GKI_TRACE("\ngki_alloc_free_queue ret OK, id:%d  size:%d, totol:%d\n", id, Q->size, Q->total);
-            return TRUE;
-        }
-        GKI_exception (GKI_ERROR_BUF_SIZE_TOOBIG, "gki_alloc_free_queue: Not enough memory");
-    }
-    GKI_TRACE("\ngki_alloc_free_queue out failed, id:%d\n", id);
-    return FALSE;
-}
-
-void gki_dealloc_free_queue(void)
+void gki_buffer_cleanup(void)
 {
     UINT8   i;
     tGKI_COM_CB *p_cb = &gki_cb.com;
 
-    for (i=0; i < p_cb->curr_total_no_of_pools; i++)
+    for (i=0; i < GKI_NUM_FIXED_BUF_POOLS; i++)
     {
         if ( 0 < p_cb->freeq[i].max_cnt )
         {
-            GKI_os_free(p_cb->pool_start[i]);
+            osi_free(p_cb->pool_start[i]);
 
             p_cb->freeq[i].cur_cnt   = 0;
             p_cb->freeq[i].max_cnt   = 0;
-            p_cb->freeq[i].p_first   = NULL;
-            p_cb->freeq[i].p_last    = NULL;
+            p_cb->freeq[i]._p_first   = NULL;
+            p_cb->freeq[i]._p_last    = NULL;
 
             p_cb->pool_start[i] = NULL;
             p_cb->pool_end[i]   = NULL;
@@ -136,9 +115,6 @@
     }
 }
 
-#endif
-// btla-specific --
-
 /*******************************************************************************
 **
 ** Function         gki_buffer_init
@@ -151,183 +127,46 @@
 *******************************************************************************/
 void gki_buffer_init(void)
 {
-    UINT8   i, tt, mb;
+    static const struct {
+      uint16_t size;
+      uint16_t count;
+    } buffer_info[GKI_NUM_FIXED_BUF_POOLS] = {
+      { GKI_BUF0_SIZE, GKI_BUF0_MAX },
+      { GKI_BUF1_SIZE, GKI_BUF1_MAX },
+      { GKI_BUF2_SIZE, GKI_BUF2_MAX },
+      { GKI_BUF3_SIZE, GKI_BUF3_MAX },
+      { GKI_BUF4_SIZE, GKI_BUF4_MAX },
+      { GKI_BUF5_SIZE, GKI_BUF5_MAX },
+      { GKI_BUF6_SIZE, GKI_BUF6_MAX },
+      { GKI_BUF7_SIZE, GKI_BUF7_MAX },
+      { GKI_BUF8_SIZE, GKI_BUF8_MAX },
+      { GKI_BUF9_SIZE, GKI_BUF9_MAX },
+    };
+
     tGKI_COM_CB *p_cb = &gki_cb.com;
 
-    /* Initialize mailboxes */
-    for (tt = 0; tt < GKI_MAX_TASKS; tt++)
+    for (int i = 0; i < GKI_NUM_TOTAL_BUF_POOLS; i++)
     {
-        for (mb = 0; mb < NUM_TASK_MBOX; mb++)
-        {
-            p_cb->OSTaskQFirst[tt][mb] = NULL;
-            p_cb->OSTaskQLast [tt][mb] = NULL;
-        }
-    }
+        p_cb->pool_start[i] = NULL;
+        p_cb->pool_end[i]   = NULL;
+        p_cb->pool_size[i]  = 0;
 
-    for (tt = 0; tt < GKI_NUM_TOTAL_BUF_POOLS; tt++)
-    {
-        p_cb->pool_start[tt] = NULL;
-        p_cb->pool_end[tt]   = NULL;
-        p_cb->pool_size[tt]  = 0;
-
-        p_cb->freeq[tt].p_first = 0;
-        p_cb->freeq[tt].p_last  = 0;
-        p_cb->freeq[tt].size    = 0;
-        p_cb->freeq[tt].total   = 0;
-        p_cb->freeq[tt].cur_cnt = 0;
-        p_cb->freeq[tt].max_cnt = 0;
+        p_cb->freeq[i]._p_first = 0;
+        p_cb->freeq[i]._p_last  = 0;
+        p_cb->freeq[i].size    = 0;
+        p_cb->freeq[i].total   = 0;
+        p_cb->freeq[i].cur_cnt = 0;
+        p_cb->freeq[i].max_cnt = 0;
     }
 
     /* Use default from target.h */
     p_cb->pool_access_mask = GKI_DEF_BUFPOOL_PERM_MASK;
 
-// btla-specific ++
-#if (!defined GKI_USE_DEFERED_ALLOC_BUF_POOLS && (GKI_USE_DYNAMIC_BUFFERS == TRUE))
-// btla-specific --
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 0)
-    p_cb->bufpool0 = (UINT8 *)GKI_os_malloc ((GKI_BUF0_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF0_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 1)
-    p_cb->bufpool1 = (UINT8 *)GKI_os_malloc ((GKI_BUF1_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF1_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 2)
-    p_cb->bufpool2 = (UINT8 *)GKI_os_malloc ((GKI_BUF2_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF2_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 3)
-    p_cb->bufpool3 = (UINT8 *)GKI_os_malloc ((GKI_BUF3_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF3_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 4)
-    p_cb->bufpool4 = (UINT8 *)GKI_os_malloc ((GKI_BUF4_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF4_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 5)
-    p_cb->bufpool5 = (UINT8 *)GKI_os_malloc ((GKI_BUF5_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF5_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 6)
-    p_cb->bufpool6 = (UINT8 *)GKI_os_malloc ((GKI_BUF6_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF6_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 7)
-    p_cb->bufpool7 = (UINT8 *)GKI_os_malloc ((GKI_BUF7_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF7_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 8)
-    p_cb->bufpool8 = (UINT8 *)GKI_os_malloc ((GKI_BUF8_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF8_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 9)
-    p_cb->bufpool9 = (UINT8 *)GKI_os_malloc ((GKI_BUF9_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF9_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 10)
-    p_cb->bufpool10 = (UINT8 *)GKI_os_malloc ((GKI_BUF10_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF10_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 11)
-    p_cb->bufpool11 = (UINT8 *)GKI_os_malloc ((GKI_BUF11_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF11_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 12)
-    p_cb->bufpool12 = (UINT8 *)GKI_os_malloc ((GKI_BUF12_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF12_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 13)
-    p_cb->bufpool13 = (UINT8 *)GKI_os_malloc ((GKI_BUF13_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF13_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 14)
-    p_cb->bufpool14 = (UINT8 *)GKI_os_malloc ((GKI_BUF14_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF14_MAX);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 15)
-    p_cb->bufpool15 = (UINT8 *)GKI_os_malloc ((GKI_BUF15_SIZE + BUFFER_PADDING_SIZE) * GKI_BUF15_MAX);
-#endif
-
-#endif
-
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 0)
-    gki_init_free_queue(0, GKI_BUF0_SIZE, GKI_BUF0_MAX, p_cb->bufpool0);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 1)
-    gki_init_free_queue(1, GKI_BUF1_SIZE, GKI_BUF1_MAX, p_cb->bufpool1);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 2)
-    gki_init_free_queue(2, GKI_BUF2_SIZE, GKI_BUF2_MAX, p_cb->bufpool2);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 3)
-    gki_init_free_queue(3, GKI_BUF3_SIZE, GKI_BUF3_MAX, p_cb->bufpool3);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 4)
-    gki_init_free_queue(4, GKI_BUF4_SIZE, GKI_BUF4_MAX, p_cb->bufpool4);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 5)
-    gki_init_free_queue(5, GKI_BUF5_SIZE, GKI_BUF5_MAX, p_cb->bufpool5);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 6)
-    gki_init_free_queue(6, GKI_BUF6_SIZE, GKI_BUF6_MAX, p_cb->bufpool6);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 7)
-    gki_init_free_queue(7, GKI_BUF7_SIZE, GKI_BUF7_MAX, p_cb->bufpool7);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 8)
-    gki_init_free_queue(8, GKI_BUF8_SIZE, GKI_BUF8_MAX, p_cb->bufpool8);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 9)
-    gki_init_free_queue(9, GKI_BUF9_SIZE, GKI_BUF9_MAX, p_cb->bufpool9);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 10)
-    gki_init_free_queue(10, GKI_BUF10_SIZE, GKI_BUF10_MAX, p_cb->bufpool10);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 11)
-    gki_init_free_queue(11, GKI_BUF11_SIZE, GKI_BUF11_MAX, p_cb->bufpool11);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 12)
-    gki_init_free_queue(12, GKI_BUF12_SIZE, GKI_BUF12_MAX, p_cb->bufpool12);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 13)
-    gki_init_free_queue(13, GKI_BUF13_SIZE, GKI_BUF13_MAX, p_cb->bufpool13);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 14)
-    gki_init_free_queue(14, GKI_BUF14_SIZE, GKI_BUF14_MAX, p_cb->bufpool14);
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 15)
-    gki_init_free_queue(15, GKI_BUF15_SIZE, GKI_BUF15_MAX, p_cb->bufpool15);
-#endif
-
-    /* add pools to the pool_list which is arranged in the order of size */
-    for(i=0; i < GKI_NUM_FIXED_BUF_POOLS ; i++)
-    {
-        p_cb->pool_list[i] = i;
+    for (int i = 0; i < GKI_NUM_FIXED_BUF_POOLS; ++i) {
+      gki_init_free_queue(i, buffer_info[i].size, buffer_info[i].count, NULL);
     }
-
-    p_cb->curr_total_no_of_pools = GKI_NUM_FIXED_BUF_POOLS;
-
-    return;
 }
 
-
 /*******************************************************************************
 **
 ** Function         GKI_init_q
@@ -339,13 +178,10 @@
 *******************************************************************************/
 void GKI_init_q (BUFFER_Q *p_q)
 {
-    p_q->p_first = p_q->p_last = NULL;
-    p_q->count = 0;
-
-    return;
+    p_q->_p_first = p_q->_p_last = NULL;
+    p_q->_count = 0;
 }
 
-
 /*******************************************************************************
 **
 ** Function         GKI_getbuf
@@ -364,81 +200,12 @@
 *******************************************************************************/
 void *GKI_getbuf (UINT16 size)
 {
-    UINT8         i;
-    FREE_QUEUE_T  *Q;
-    BUFFER_HDR_T  *p_hdr;
-    tGKI_COM_CB *p_cb = &gki_cb.com;
-
-    if (size == 0)
-    {
-        GKI_exception (GKI_ERROR_BUF_SIZE_ZERO, "getbuf: Size is zero");
-        return (NULL);
-    }
-
-    /* Find the first buffer pool that is public that can hold the desired size */
-    for (i=0; i < p_cb->curr_total_no_of_pools; i++)
-    {
-        if ( size <= p_cb->freeq[p_cb->pool_list[i]].size )
-            break;
-    }
-
-    if(i == p_cb->curr_total_no_of_pools)
-    {
-        GKI_exception (GKI_ERROR_BUF_SIZE_TOOBIG, "getbuf: Size is too big");
-        return (NULL);
-    }
-
-    /* Make sure the buffers aren't disturbed til finished with allocation */
-    GKI_disable();
-
-    /* search the public buffer pools that are big enough to hold the size
-     * until a free buffer is found */
-    for ( ; i < p_cb->curr_total_no_of_pools; i++)
-    {
-        /* Only look at PUBLIC buffer pools (bypass RESTRICTED pools) */
-        if (((UINT16)1 << p_cb->pool_list[i]) & p_cb->pool_access_mask)
-            continue;
-        if ( size <= p_cb->freeq[p_cb->pool_list[i]].size )
-             Q = &p_cb->freeq[p_cb->pool_list[i]];
-        else
-             continue;
-
-        if(Q->cur_cnt < Q->total)
-        {
-// btla-specific ++
-        #ifdef GKI_USE_DEFERED_ALLOC_BUF_POOLS
-            if(Q->p_first == 0 && gki_alloc_free_queue(i) != TRUE)
-            {
-                GKI_enable();
-                return NULL;
-            }
-        #endif
-// btla-specific --
-            p_hdr = Q->p_first;
-            Q->p_first = p_hdr->p_next;
-
-            if (!Q->p_first)
-                Q->p_last = NULL;
-
-            if(++Q->cur_cnt > Q->max_cnt)
-                Q->max_cnt = Q->cur_cnt;
-
-            GKI_enable();
-
-            p_hdr->task_id = GKI_get_taskid();
-
-            p_hdr->status  = BUF_STATUS_UNLINKED;
-            p_hdr->p_next  = NULL;
-            p_hdr->Type    = 0;
-
-            return ((void *) ((UINT8 *)p_hdr + BUFFER_HDR_SIZE));
-        }
-    }
-
-    GKI_enable();
-
-    GKI_exception (GKI_ERROR_OUT_OF_BUFFERS, "getbuf: out of buffers");
-    return (NULL);
+  BUFFER_HDR_T *header = malloc(size + BUFFER_HDR_SIZE);
+  header->status  = BUF_STATUS_UNLINKED;
+  header->p_next  = NULL;
+  header->Type    = 0;
+  header->size = size;
+  return header + 1;
 }
 
 
@@ -459,58 +226,7 @@
 *******************************************************************************/
 void *GKI_getpoolbuf (UINT8 pool_id)
 {
-    FREE_QUEUE_T  *Q;
-    BUFFER_HDR_T  *p_hdr;
-    tGKI_COM_CB *p_cb = &gki_cb.com;
-
-    if (pool_id >= GKI_NUM_TOTAL_BUF_POOLS)
-    {
-        GKI_exception(GKI_ERROR_GETPOOLBUF_BAD_QID, "getpoolbuf bad pool");
-        return (NULL);
-    }
-
-    /* Make sure the buffers aren't disturbed til finished with allocation */
-    GKI_disable();
-
-    Q = &p_cb->freeq[pool_id];
-    if(Q->cur_cnt < Q->total)
-    {
-// btla-specific ++
-#ifdef GKI_USE_DEFERED_ALLOC_BUF_POOLS
-        if(Q->p_first == 0 && gki_alloc_free_queue(pool_id) != TRUE)
-        {
-            GKI_enable();
-            return NULL;
-        }
-#endif
-// btla-specific --
-        p_hdr = Q->p_first;
-        Q->p_first = p_hdr->p_next;
-
-        if (!Q->p_first)
-            Q->p_last = NULL;
-
-        if(++Q->cur_cnt > Q->max_cnt)
-            Q->max_cnt = Q->cur_cnt;
-
-        GKI_enable();
-
-
-        p_hdr->task_id = GKI_get_taskid();
-
-        p_hdr->status  = BUF_STATUS_UNLINKED;
-        p_hdr->p_next  = NULL;
-        p_hdr->Type    = 0;
-
-        return ((void *) ((UINT8 *)p_hdr + BUFFER_HDR_SIZE));
-    }
-
-    /* If here, no buffers in the specified pool */
-    GKI_enable();
-
-    /* try for free buffers in public pools */
-    return (GKI_getbuf(p_cb->freeq[pool_id].size));
-
+  return GKI_getbuf(gki_cb.com.pool_size[pool_id]);
 }
 
 /*******************************************************************************
@@ -526,52 +242,7 @@
 *******************************************************************************/
 void GKI_freebuf (void *p_buf)
 {
-    FREE_QUEUE_T    *Q;
-    BUFFER_HDR_T    *p_hdr;
-
-#if (GKI_ENABLE_BUF_CORRUPTION_CHECK == TRUE)
-    if (!p_buf || gki_chk_buf_damage(p_buf))
-    {
-        GKI_exception(GKI_ERROR_BUF_CORRUPTED, "Free - Buf Corrupted");
-        return;
-    }
-#endif
-
-    p_hdr = (BUFFER_HDR_T *) ((UINT8 *)p_buf - BUFFER_HDR_SIZE);
-
-    if (p_hdr->status != BUF_STATUS_UNLINKED)
-    {
-        GKI_exception(GKI_ERROR_FREEBUF_BUF_LINKED, "Freeing Linked Buf");
-        return;
-    }
-
-    if (p_hdr->q_id >= GKI_NUM_TOTAL_BUF_POOLS)
-    {
-        GKI_exception(GKI_ERROR_FREEBUF_BAD_QID, "Bad Buf QId");
-        return;
-    }
-
-    GKI_disable();
-
-    /*
-    ** Release the buffer
-    */
-    Q  = &gki_cb.com.freeq[p_hdr->q_id];
-    if (Q->p_last)
-        Q->p_last->p_next = p_hdr;
-    else
-        Q->p_first = p_hdr;
-
-    Q->p_last      = p_hdr;
-    p_hdr->p_next  = NULL;
-    p_hdr->status  = BUF_STATUS_FREE;
-    p_hdr->task_id = GKI_INVALID_TASK;
-    if (Q->cur_cnt > 0)
-        Q->cur_cnt--;
-
-    GKI_enable();
-
-    return;
+  free((BUFFER_HDR_T *)p_buf - 1);
 }
 
 
@@ -588,154 +259,12 @@
 *******************************************************************************/
 UINT16 GKI_get_buf_size (void *p_buf)
 {
-    BUFFER_HDR_T    *p_hdr;
-
-    p_hdr = (BUFFER_HDR_T *)((UINT8 *) p_buf - BUFFER_HDR_SIZE);
-
-    if ((UINT32)p_hdr & 1)
-        return (0);
-
-    if (p_hdr->q_id < GKI_NUM_TOTAL_BUF_POOLS)
-    {
-        return (gki_cb.com.freeq[p_hdr->q_id].size);
-    }
-
-    return (0);
+  BUFFER_HDR_T *header = (BUFFER_HDR_T *)p_buf - 1;
+  return header->size;
 }
 
 /*******************************************************************************
 **
-** Function         gki_chk_buf_damage
-**
-** Description      Called internally by OSS to check for buffer corruption.
-**
-** Returns          TRUE if there is a problem, else FALSE
-**
-*******************************************************************************/
-BOOLEAN gki_chk_buf_damage(void *p_buf)
-{
-#if (GKI_ENABLE_BUF_CORRUPTION_CHECK == TRUE)
-
-    UINT32 *magic;
-    magic  = (UINT32 *)((UINT8 *) p_buf + GKI_get_buf_size(p_buf));
-
-    if ((UINT32)magic & 1)
-        return (TRUE);
-
-    if (*magic == MAGIC_NO)
-        return (FALSE);
-
-    return (TRUE);
-
-#else
-
-    return (FALSE);
-
-#endif
-}
-
-/*******************************************************************************
-**
-** Function         GKI_send_msg
-**
-** Description      Called by applications to send a buffer to a task
-**
-** Returns          Nothing
-**
-*******************************************************************************/
-void GKI_send_msg (UINT8 task_id, UINT8 mbox, void *msg)
-{
-    BUFFER_HDR_T    *p_hdr;
-    tGKI_COM_CB *p_cb = &gki_cb.com;
-
-    /* If task non-existant or not started, drop buffer */
-    if ((task_id >= GKI_MAX_TASKS) || (mbox >= NUM_TASK_MBOX) || (p_cb->OSRdyTbl[task_id] == TASK_DEAD))
-    {
-        GKI_exception(GKI_ERROR_SEND_MSG_BAD_DEST, "Sending to unknown dest");
-        GKI_freebuf (msg);
-        return;
-    }
-
-#if (GKI_ENABLE_BUF_CORRUPTION_CHECK == TRUE)
-    if (gki_chk_buf_damage(msg))
-    {
-        GKI_exception(GKI_ERROR_BUF_CORRUPTED, "Send - Buffer corrupted");
-        return;
-    }
-#endif
-
-    p_hdr = (BUFFER_HDR_T *) ((UINT8 *) msg - BUFFER_HDR_SIZE);
-
-    if (p_hdr->status != BUF_STATUS_UNLINKED)
-    {
-        GKI_exception(GKI_ERROR_SEND_MSG_BUF_LINKED, "Send - buffer linked");
-        return;
-    }
-
-    GKI_disable();
-
-    if (p_cb->OSTaskQFirst[task_id][mbox])
-        p_cb->OSTaskQLast[task_id][mbox]->p_next = p_hdr;
-    else
-        p_cb->OSTaskQFirst[task_id][mbox] = p_hdr;
-
-    p_cb->OSTaskQLast[task_id][mbox] = p_hdr;
-
-    p_hdr->p_next = NULL;
-    p_hdr->status = BUF_STATUS_QUEUED;
-    p_hdr->task_id = task_id;
-
-
-    GKI_enable();
-
-    GKI_send_event(task_id, (UINT16)EVENT_MASK(mbox));
-
-    return;
-}
-
-/*******************************************************************************
-**
-** Function         GKI_read_mbox
-**
-** Description      Called by applications to read a buffer from one of
-**                  the task mailboxes.  A task can only read its own mailbox.
-**
-** Parameters:      mbox  - (input) mailbox ID to read (0, 1, 2, or 3)
-**
-** Returns          NULL if the mailbox was empty, else the address of a buffer
-**
-*******************************************************************************/
-void *GKI_read_mbox (UINT8 mbox)
-{
-    UINT8           task_id = GKI_get_taskid();
-    void            *p_buf = NULL;
-    BUFFER_HDR_T    *p_hdr;
-
-    if ((task_id >= GKI_MAX_TASKS) || (mbox >= NUM_TASK_MBOX))
-        return (NULL);
-
-    GKI_disable();
-
-    if (gki_cb.com.OSTaskQFirst[task_id][mbox])
-    {
-        p_hdr = gki_cb.com.OSTaskQFirst[task_id][mbox];
-        gki_cb.com.OSTaskQFirst[task_id][mbox] = p_hdr->p_next;
-
-        p_hdr->p_next = NULL;
-        p_hdr->status = BUF_STATUS_UNLINKED;
-
-        p_buf = (UINT8 *)p_hdr + BUFFER_HDR_SIZE;
-    }
-
-    GKI_enable();
-
-    return (p_buf);
-}
-
-
-
-/*******************************************************************************
-**
 ** Function         GKI_enqueue
 **
 ** Description      Enqueue a buffer at the tail of the queue
@@ -748,102 +277,29 @@
 *******************************************************************************/
 void GKI_enqueue (BUFFER_Q *p_q, void *p_buf)
 {
-    BUFFER_HDR_T    *p_hdr;
-
-#if (GKI_ENABLE_BUF_CORRUPTION_CHECK == TRUE)
-    if (gki_chk_buf_damage(p_buf))
-    {
-        GKI_exception(GKI_ERROR_BUF_CORRUPTED, "Enqueue - Buffer corrupted");
-        return;
-    }
-#endif
-
-    p_hdr = (BUFFER_HDR_T *) ((UINT8 *) p_buf - BUFFER_HDR_SIZE);
-
-    if (p_hdr->status != BUF_STATUS_UNLINKED)
-    {
-        GKI_exception(GKI_ERROR_ENQUEUE_BUF_LINKED, "Eneueue - buf already linked");
-        return;
-    }
+    BUFFER_HDR_T *p_hdr = (BUFFER_HDR_T *) ((UINT8 *) p_buf - BUFFER_HDR_SIZE);
+    assert(p_hdr->status == BUF_STATUS_UNLINKED);
 
     GKI_disable();
 
     /* Since the queue is exposed (C vs C++), keep the pointers in exposed format */
-    if (p_q->p_last)
+    if (p_q->_p_last)
     {
-        BUFFER_HDR_T *p_last_hdr = (BUFFER_HDR_T *)((UINT8 *)p_q->p_last - BUFFER_HDR_SIZE);
-        p_last_hdr->p_next = p_hdr;
+        BUFFER_HDR_T *_p_last_hdr = (BUFFER_HDR_T *)((UINT8 *)p_q->_p_last - BUFFER_HDR_SIZE);
+        _p_last_hdr->p_next = p_hdr;
     }
     else
-        p_q->p_first = p_buf;
+        p_q->_p_first = p_buf;
 
-    p_q->p_last = p_buf;
-    p_q->count++;
+    p_q->_p_last = p_buf;
+    p_q->_count++;
 
     p_hdr->p_next = NULL;
     p_hdr->status = BUF_STATUS_QUEUED;
 
     GKI_enable();
-
-    return;
 }
 
-
-/*******************************************************************************
-**
-** Function         GKI_enqueue_head
-**
-** Description      Enqueue a buffer at the head of the queue
-**
-** Parameters:      p_q  -  (input) pointer to a queue.
-**                  p_buf - (input) address of the buffer to enqueue
-**
-** Returns          void
-**
-*******************************************************************************/
-void GKI_enqueue_head (BUFFER_Q *p_q, void *p_buf)
-{
-    BUFFER_HDR_T    *p_hdr;
-
-#if (GKI_ENABLE_BUF_CORRUPTION_CHECK == TRUE)
-    if (gki_chk_buf_damage(p_buf))
-    {
-        GKI_exception(GKI_ERROR_BUF_CORRUPTED, "Enqueue - Buffer corrupted");
-        return;
-    }
-#endif
-
-    p_hdr = (BUFFER_HDR_T *) ((UINT8 *) p_buf - BUFFER_HDR_SIZE);
-
-    if (p_hdr->status != BUF_STATUS_UNLINKED)
-    {
-        GKI_exception(GKI_ERROR_ENQUEUE_BUF_LINKED, "Eneueue head - buf already linked");
-        return;
-    }
-
-    GKI_disable();
-
-    if (p_q->p_first)
-    {
-        p_hdr->p_next = (BUFFER_HDR_T *)((UINT8 *)p_q->p_first - BUFFER_HDR_SIZE);
-        p_q->p_first = p_buf;
-    }
-    else
-    {
-        p_q->p_first = p_buf;
-        p_q->p_last  = p_buf;
-        p_hdr->p_next = NULL;
-    }
-    p_q->count++;
-
-    p_hdr->status = BUF_STATUS_QUEUED;
-
-    GKI_enable();
-
-    return;
-}
-
-
 /*******************************************************************************
 **
 ** Function         GKI_dequeue
@@ -861,25 +317,25 @@
 
     GKI_disable();
 
-    if (!p_q || !p_q->count)
+    if (!p_q || !p_q->_count)
     {
         GKI_enable();
         return (NULL);
     }
 
-    p_hdr = (BUFFER_HDR_T *)((UINT8 *)p_q->p_first - BUFFER_HDR_SIZE);
+    p_hdr = (BUFFER_HDR_T *)((UINT8 *)p_q->_p_first - BUFFER_HDR_SIZE);
 
     /* Keep buffers such that GKI header is invisible
     */
     if (p_hdr->p_next)
-        p_q->p_first = ((UINT8 *)p_hdr->p_next + BUFFER_HDR_SIZE);
+        p_q->_p_first = ((UINT8 *)p_hdr->p_next + BUFFER_HDR_SIZE);
     else
     {
-        p_q->p_first = NULL;
-        p_q->p_last  = NULL;
+        p_q->_p_first = NULL;
+        p_q->_p_last  = NULL;
     }
 
-    p_q->count--;
+    p_q->_count--;
 
     p_hdr->p_next = NULL;
     p_hdr->status = BUF_STATUS_UNLINKED;
@@ -889,7 +345,6 @@
     return ((UINT8 *)p_hdr + BUFFER_HDR_SIZE);
 }
 
-
 /*******************************************************************************
 **
 ** Function         GKI_remove_from_queue
@@ -909,14 +364,14 @@
 
     GKI_disable();
 
-    if (p_buf == p_q->p_first)
+    if (p_buf == p_q->_p_first)
     {
         GKI_enable();
         return (GKI_dequeue (p_q));
     }
 
     p_buf_hdr = (BUFFER_HDR_T *)((UINT8 *)p_buf - BUFFER_HDR_SIZE);
-    p_prev    = (BUFFER_HDR_T *)((UINT8 *)p_q->p_first - BUFFER_HDR_SIZE);
+    p_prev    = (BUFFER_HDR_T *)((UINT8 *)p_q->_p_first - BUFFER_HDR_SIZE);
 
     for ( ; p_prev; p_prev = p_prev->p_next)
     {
@@ -925,12 +380,12 @@
         {
             p_prev->p_next = p_buf_hdr->p_next;
 
-            /* If we are removing the last guy in the queue, update p_last */
-            if (p_buf == p_q->p_last)
-                p_q->p_last = p_prev + 1;
+            /* If we are removing the last guy in the queue, update _p_last */
+            if (p_buf == p_q->_p_last)
+                p_q->_p_last = p_prev + 1;
 
             /* One less in the queue */
-            p_q->count--;
+            p_q->_count--;
 
             /* The buffer is now unlinked */
             p_buf_hdr->p_next = NULL;
@@ -958,10 +413,9 @@
 *******************************************************************************/
 void *GKI_getfirst (BUFFER_Q *p_q)
 {
-    return (p_q->p_first);
+    return (p_q->_p_first);
 }
 
-
 /*******************************************************************************
 **
 ** Function         GKI_getlast
@@ -975,7 +429,7 @@
 *******************************************************************************/
 void *GKI_getlast (BUFFER_Q *p_q)
 {
-    return (p_q->p_last);
+    return (p_q->_p_last);
 }
 
 /*******************************************************************************
@@ -1001,8 +455,6 @@
         return (NULL);
 }
 
-
-
 /*******************************************************************************
 **
 ** Function         GKI_queue_is_empty
@@ -1016,52 +468,12 @@
 *******************************************************************************/
 BOOLEAN GKI_queue_is_empty(BUFFER_Q *p_q)
 {
-    return ((BOOLEAN) (p_q->count == 0));
+    return ((BOOLEAN) (p_q->_count == 0));
 }
 
-/*******************************************************************************
-**
-** Function         GKI_igetpoolbuf
-**
-** Description      Called by an interrupt service routine to get a free buffer from
-**                  a specific buffer pool.
-**
-** Parameters       pool_id - (input) pool ID to get a buffer out of.
-**
-** Returns          A pointer to the buffer, or NULL if none available
-**
-*******************************************************************************/
-void *GKI_igetpoolbuf (UINT8 pool_id)
+UINT16 GKI_queue_length(BUFFER_Q *p_q)
 {
-    FREE_QUEUE_T  *Q;
-    BUFFER_HDR_T  *p_hdr;
-
-    if (pool_id >= GKI_NUM_TOTAL_BUF_POOLS)
-        return (NULL);
-
-
-    Q = &gki_cb.com.freeq[pool_id];
-    if(Q->cur_cnt < Q->total)
-    {
-        p_hdr = Q->p_first;
-        Q->p_first = p_hdr->p_next;
-
-        if (!Q->p_first)
-            Q->p_last = NULL;
-
-        if(++Q->cur_cnt > Q->max_cnt)
-            Q->max_cnt = Q->cur_cnt;
-
-        p_hdr->task_id = GKI_get_taskid();
-
-        p_hdr->status  = BUF_STATUS_UNLINKED;
-        p_hdr->p_next  = NULL;
-        p_hdr->Type    = 0;
-
-        return ((void *) ((UINT8 *)p_hdr + BUFFER_HDR_SIZE));
-    }
-
-    return (NULL);
+    return p_q->_count;
 }
 
 /*******************************************************************************
@@ -1153,4 +565,3 @@
 
     return ((Q->cur_cnt * 100) / Q->total);
 }
-
diff --git a/gki/common/gki_common.h b/gki/common/gki_common.h
index 042024e1..cb8fbdc 100644
--- a/gki/common/gki_common.h
+++ b/gki/common/gki_common.h
@@ -15,297 +15,39 @@
  *  limitations under the License.
  *
  ******************************************************************************/
-#ifndef GKI_COMMON_H
-#define GKI_COMMON_H
+
+#pragma once
 
 #include "gki.h"
-#include "dyn_mem.h"
-
-/* Task States: (For OSRdyTbl) */
-#define TASK_DEAD       0   /* b0000 */
-#define TASK_READY      1   /* b0001 */
-#define TASK_WAIT       2   /* b0010 */
-#define TASK_DELAY      4   /* b0100 */
-#define TASK_SUSPEND    8   /* b1000 */
-
-
-/********************************************************************
-**  Internal Error codes
-*********************************************************************/
-#define GKI_ERROR_BUF_CORRUPTED         0xFFFF
-#define GKI_ERROR_NOT_BUF_OWNER         0xFFFE
-#define GKI_ERROR_FREEBUF_BAD_QID       0xFFFD
-#define GKI_ERROR_FREEBUF_BUF_LINKED    0xFFFC
-#define GKI_ERROR_SEND_MSG_BAD_DEST     0xFFFB
-#define GKI_ERROR_SEND_MSG_BUF_LINKED   0xFFFA
-#define GKI_ERROR_ENQUEUE_BUF_LINKED    0xFFF9
-#define GKI_ERROR_DELETE_POOL_BAD_QID   0xFFF8
-#define GKI_ERROR_BUF_SIZE_TOOBIG       0xFFF7
-#define GKI_ERROR_BUF_SIZE_ZERO         0xFFF6
-#define GKI_ERROR_ADDR_NOT_IN_BUF       0xFFF5
-#define GKI_ERROR_OUT_OF_BUFFERS        0xFFF4
-#define GKI_ERROR_GETPOOLBUF_BAD_QID    0xFFF3
-#define GKI_ERROR_TIMER_LIST_CORRUPTED  0xFFF2
-
-
-/********************************************************************
-**  Misc constants
-*********************************************************************/
-
-/********************************************************************
-**  Buffer Management Data Structures
-*********************************************************************/
 
 typedef struct _buffer_hdr
 {
-    struct _buffer_hdr *p_next;   /* next buffer in the queue */
+	struct _buffer_hdr *p_next;   /* next buffer in the queue */
 	UINT8   q_id;                 /* id of the queue */
-	UINT8   task_id;              /* task which allocated the buffer*/
 	UINT8   status;               /* FREE, UNLINKED or QUEUED */
 	UINT8   Type;
+        UINT16  size;
 } BUFFER_HDR_T;
 
 typedef struct _free_queue
 {
-	BUFFER_HDR_T *p_first;      /* first buffer in the queue */
-	BUFFER_HDR_T *p_last;       /* last buffer in the queue */
-	UINT16		 size;          /* size of the buffers in the pool */
-	UINT16		 total;         /* toatal number of buffers */
-	UINT16		 cur_cnt;       /* number of  buffers currently allocated */
-	UINT16		 max_cnt;       /* maximum number of buffers allocated at any time */
+	BUFFER_HDR_T *_p_first;      /* first buffer in the queue */
+	BUFFER_HDR_T *_p_last;       /* last buffer in the queue */
+	UINT16		 size;             /* size of the buffers in the pool */
+	UINT16		 total;            /* toatal number of buffers */
+	UINT16		 cur_cnt;          /* number of  buffers currently allocated */
+	UINT16		 max_cnt;          /* maximum number of buffers allocated at any time */
 } FREE_QUEUE_T;
 
-
-/* Buffer related defines
-*/
-#define ALIGN_POOL(pl_size)  ( (((pl_size) + 3) / sizeof(UINT32)) * sizeof(UINT32))
-#define BUFFER_HDR_SIZE     (sizeof(BUFFER_HDR_T))                  /* Offset past header */
-#define BUFFER_PADDING_SIZE (sizeof(BUFFER_HDR_T) + sizeof(UINT32)) /* Header + Magic Number */
-#define MAX_USER_BUF_SIZE   ((UINT16)0xffff - BUFFER_PADDING_SIZE)  /* pool size must allow for header */
-#define MAGIC_NO            0xDDBADDBA
-
-#define BUF_STATUS_FREE     0
-#define BUF_STATUS_UNLINKED 1
-#define BUF_STATUS_QUEUED   2
-
-// btla-specific ++
-#define GKI_USE_DEFERED_ALLOC_BUF_POOLS
-// btla-specific --
-
-/* Exception related structures (Used in debug mode only)
-*/
-#if (GKI_DEBUG == TRUE)
-typedef struct
-{
-	UINT16  type;
-	UINT8   taskid;
-	UINT8   msg[GKI_MAX_EXCEPTION_MSGLEN];
-} EXCEPTION_T;
-#endif
-
-
 /* Put all GKI variables into one control block
 */
 typedef struct
 {
-    /* Task management variables
-    */
-    /* The stack and stack size are not used on Windows
-    */
-// btla-specific ++
-#if (!defined GKI_USE_DEFERED_ALLOC_BUF_POOLS && (GKI_USE_DYNAMIC_BUFFERS == FALSE))
-// btla-specific --
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 0)
-    UINT8 bufpool0[(ALIGN_POOL(GKI_BUF0_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF0_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 1)
-    UINT8 bufpool1[(ALIGN_POOL(GKI_BUF1_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF1_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 2)
-    UINT8 bufpool2[(ALIGN_POOL(GKI_BUF2_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF2_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 3)
-    UINT8 bufpool3[(ALIGN_POOL(GKI_BUF3_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF3_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 4)
-    UINT8 bufpool4[(ALIGN_POOL(GKI_BUF4_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF4_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 5)
-    UINT8 bufpool5[(ALIGN_POOL(GKI_BUF5_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF5_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 6)
-    UINT8 bufpool6[(ALIGN_POOL(GKI_BUF6_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF6_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 7)
-    UINT8 bufpool7[(ALIGN_POOL(GKI_BUF7_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF7_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 8)
-    UINT8 bufpool8[(ALIGN_POOL(GKI_BUF8_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF8_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 9)
-    UINT8 bufpool9[(ALIGN_POOL(GKI_BUF9_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF9_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 10)
-    UINT8 bufpool10[(ALIGN_POOL(GKI_BUF10_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF10_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 11)
-    UINT8 bufpool11[(ALIGN_POOL(GKI_BUF11_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF11_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 12)
-    UINT8 bufpool12[(ALIGN_POOL(GKI_BUF12_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF12_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 13)
-    UINT8 bufpool13[(ALIGN_POOL(GKI_BUF13_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF13_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 14)
-    UINT8 bufpool14[(ALIGN_POOL(GKI_BUF14_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF14_MAX];
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 15)
-    UINT8 bufpool15[(ALIGN_POOL(GKI_BUF15_SIZE) + BUFFER_PADDING_SIZE) * GKI_BUF15_MAX];
-#endif
-
-#else
-/* Definitions for dynamic buffer use */
-#if (GKI_NUM_FIXED_BUF_POOLS > 0)
-    UINT8 *bufpool0;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 1)
-    UINT8 *bufpool1;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 2)
-    UINT8 *bufpool2;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 3)
-    UINT8 *bufpool3;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 4)
-    UINT8 *bufpool4;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 5)
-    UINT8 *bufpool5;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 6)
-    UINT8 *bufpool6;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 7)
-    UINT8 *bufpool7;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 8)
-    UINT8 *bufpool8;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 9)
-    UINT8 *bufpool9;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 10)
-    UINT8 *bufpool10;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 11)
-    UINT8 *bufpool11;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 12)
-    UINT8 *bufpool12;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 13)
-    UINT8 *bufpool13;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 14)
-    UINT8 *bufpool14;
-#endif
-
-#if (GKI_NUM_FIXED_BUF_POOLS > 15)
-    UINT8 *bufpool15;
-#endif
-
-#endif
-
-    UINT8  *OSStack[GKI_MAX_TASKS];         /* pointer to beginning of stack */
-    UINT16  OSStackSize[GKI_MAX_TASKS];     /* stack size available to each task */
-
-
-    INT8   *OSTName[GKI_MAX_TASKS];         /* name of the task */
-
-    UINT8   OSRdyTbl[GKI_MAX_TASKS];        /* current state of the task */
-    UINT16  OSWaitEvt[GKI_MAX_TASKS];       /* events that have to be processed by the task */
-    UINT16  OSWaitForEvt[GKI_MAX_TASKS];    /* events the task is waiting for*/
-
-    UINT32  OSTicks;                        /* system ticks from start */
-    UINT32  OSIdleCnt;                      /* idle counter */
-    INT16   OSDisableNesting;               /* counter to keep track of interrupt disable nesting */
-    INT16   OSLockNesting;                  /* counter to keep track of sched lock nesting */
-    INT16   OSIntNesting;                   /* counter to keep track of interrupt nesting */
-
-    /* Timer related variables
-    */
-    INT32   OSTicksTilExp;      /* Number of ticks till next timer expires */
-    INT32   OSNumOrigTicks;     /* Number of ticks between last timer expiration to the next one */
-
-    INT32   OSWaitTmr   [GKI_MAX_TASKS];  /* ticks the task has to wait, for specific events */
-
-    /* Only take up space timers used in the system (GKI_NUM_TIMERS defined in target.h) */
-#if (GKI_NUM_TIMERS > 0)
-    INT32   OSTaskTmr0  [GKI_MAX_TASKS];
-    INT32   OSTaskTmr0R [GKI_MAX_TASKS];
-#endif
-
-#if (GKI_NUM_TIMERS > 1)
-    INT32   OSTaskTmr1  [GKI_MAX_TASKS];
-    INT32   OSTaskTmr1R [GKI_MAX_TASKS];
-#endif
-
-#if (GKI_NUM_TIMERS > 2)
-    INT32   OSTaskTmr2  [GKI_MAX_TASKS];
-    INT32   OSTaskTmr2R [GKI_MAX_TASKS];
-#endif
-
-#if (GKI_NUM_TIMERS > 3)
-    INT32   OSTaskTmr3  [GKI_MAX_TASKS];
-    INT32   OSTaskTmr3R [GKI_MAX_TASKS];
-#endif
-
-
-
-    /* Buffer related variables
-    */
-    BUFFER_HDR_T    *OSTaskQFirst[GKI_MAX_TASKS][NUM_TASK_MBOX]; /* array of pointers to the first event in the task mailbox */
-    BUFFER_HDR_T    *OSTaskQLast [GKI_MAX_TASKS][NUM_TASK_MBOX]; /* array of pointers to the last event in the task mailbox */
-
     /* Define the buffer pool management variables
     */
     FREE_QUEUE_T    freeq[GKI_NUM_TOTAL_BUF_POOLS];
 
     UINT16   pool_buf_size[GKI_NUM_TOTAL_BUF_POOLS];
-    UINT16   pool_max_count[GKI_NUM_TOTAL_BUF_POOLS];
-    UINT16   pool_additions[GKI_NUM_TOTAL_BUF_POOLS];
 
     /* Define the buffer pool start addresses
     */
@@ -314,61 +56,10 @@
     UINT16   pool_size[GKI_NUM_TOTAL_BUF_POOLS];    /* actual size of the buffers in a pool */
 
     /* Define the buffer pool access control variables */
-    void        *p_user_mempool;                    /* User O/S memory pool */
     UINT16      pool_access_mask;                   /* Bits are set if the corresponding buffer pool is a restricted pool */
-    UINT8       pool_list[GKI_NUM_TOTAL_BUF_POOLS]; /* buffer pools arranged in the order of size */
-    UINT8       curr_total_no_of_pools;             /* number of fixed buf pools + current number of dynamic pools */
-
-    BOOLEAN     timer_nesting;                      /* flag to prevent timer interrupt nesting */
-
-#if (GKI_DEBUG == TRUE)
-    UINT16      ExceptionCnt;                       /* number of GKI exceptions that have happened */
-    EXCEPTION_T Exception[GKI_MAX_EXCEPTION];
-#endif
-
 } tGKI_COM_CB;
 
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /* Internal GKI function prototypes
 */
-GKI_API extern BOOLEAN   gki_chk_buf_damage(void *);
-extern BOOLEAN   gki_chk_buf_owner(void *);
-extern void      gki_buffer_init (void);
-extern void      gki_timers_init(void);
-extern void      gki_adjust_timer_count (INT32);
-
-#ifdef GKI_USE_DEFERED_ALLOC_BUF_POOLS
-extern void      gki_dealloc_free_queue(void);
-#endif
-
-
-/* Debug aids
-*/
-typedef void  (*FP_PRINT)(char *, ...);
-
-#if (GKI_DEBUG == TRUE)
-
-typedef void  (*PKT_PRINT)(UINT8 *, UINT16);
-
-extern void gki_print_task(FP_PRINT);
-extern void gki_print_exception(FP_PRINT);
-extern void gki_print_timer(FP_PRINT);
-extern void gki_print_stack(FP_PRINT);
-extern void gki_print_buffer(FP_PRINT);
-extern void gki_print_buffer_statistics(FP_PRINT, INT16);
-GKI_API extern void gki_print_used_bufs (FP_PRINT, UINT8);
-extern void gki_dump(UINT8 *, UINT16, FP_PRINT);
-extern void gki_dump2(UINT16 *, UINT16, FP_PRINT);
-extern void gki_dump4(UINT32 *, UINT16, FP_PRINT);
-
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+void      gki_buffer_init(void);
+void      gki_buffer_cleanup(void);
diff --git a/gki/common/gki_debug.c b/gki/common/gki_debug.c
deleted file mode 100644
index adb9c46..0000000
--- a/gki/common/gki_debug.c
+++ /dev/null
@@ -1,354 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-#include "gki_int.h"
-
-#if (GKI_DEBUG == TRUE)
-
-const INT8 * const OSTaskStates[] =
-{
-    (INT8 *)"DEAD",  /* 0 */
-    (INT8 *)"REDY",  /* 1 */
-    (INT8 *)"WAIT",  /* 2 */
-    (INT8 *)"",
-    (INT8 *)"DELY",  /* 4 */
-    (INT8 *)"",
-    (INT8 *)"",
-    (INT8 *)"",
-    (INT8 *)"SUSP",  /* 8 */
-};
-
-
-/*******************************************************************************
-**
-** Function         GKI_PrintBufferUsage
-**
-** Description      Displays Current Buffer Pool summary
-**
-** Returns          void
-**
-*******************************************************************************/
-void GKI_PrintBufferUsage(UINT8 *p_num_pools, UINT16 *p_cur_used)
-{
-    int i;
-    FREE_QUEUE_T    *p;
-    UINT8   num = gki_cb.com.curr_total_no_of_pools;
-    UINT16   cur[GKI_NUM_TOTAL_BUF_POOLS];
-
-    GKI_TRACE("");
-    GKI_TRACE("--- GKI Buffer Pool Summary (R - restricted, P - public) ---");
-
-    GKI_TRACE("POOL     SIZE  USED  MAXU  TOTAL");
-    GKI_TRACE("------------------------------");
-    for (i = 0; i < gki_cb.com.curr_total_no_of_pools; i++)
-    {
-        p = &gki_cb.com.freeq[i];
-        if ((1 << i) & gki_cb.com.pool_access_mask)
-        {
-            GKI_TRACE("%02d: (R), %4d, %3d, %3d, %3d",
-                        i, p->size, p->cur_cnt, p->max_cnt, p->total);
-        }
-        else
-        {
-            GKI_TRACE("%02d: (P), %4d, %3d, %3d, %3d",
-                        i, p->size, p->cur_cnt, p->max_cnt, p->total);
-        }
-        cur[i] = p->cur_cnt;
-    }
-    if (p_num_pools)
-        *p_num_pools = num;
-    if (p_cur_used)
-        memcpy(p_cur_used, cur, num*2);
-}
-
-/*******************************************************************************
-**
-** Function         GKI_PrintBuffer
-**
-** Description      Called internally by OSS to print the buffer pools
-**
-** Returns          void
-**
-*******************************************************************************/
-void GKI_PrintBuffer(void)
-{
-    UINT16 i;
-    for(i=0; i<GKI_NUM_TOTAL_BUF_POOLS; i++)
-	{
-		GKI_TRACE("pool:%4u free %4u cur %3u max %3u  total%3u", i, gki_cb.com.freeq[i].size,
-                    gki_cb.com.freeq[i].cur_cnt, gki_cb.com.freeq[i].max_cnt, gki_cb.com.freeq[i].total);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         gki_calc_stack
-**
-** Description      This function tries to calculate the amount of
-**                  stack used by looking non magic num. Magic num is consider
-**                  the first byte in the stack.
-**
-** Returns          the number of unused byte on the stack. 4 in case of stack overrun
-**
-*******************************************************************************/
-UINT16 gki_calc_stack (UINT8 task)
-{
-    int    j, stacksize;
-    UINT32 MagicNum;
-    UINT32 *p;
-
-    stacksize = (int) gki_cb.com.OSStackSize[task];
-    p = (UINT32 *)gki_cb.com.OSStack[task]; /* assume stack is aligned, */
-    MagicNum = *p;
-
-    for(j = 0; j < stacksize; j++)
-    {
-        if(*p++ != MagicNum) break;
-    }
-
-    return (j * sizeof(UINT32));
-}
-
-/*******************************************************************************
-**
-** Function         GKI_print_task
-**
-** Description      Print task stack usage.
-**
-** Returns          void
-**
-*******************************************************************************/
-void GKI_print_task(void)
-{
-#ifdef _BT_WIN32
-	GKI_TRACE("Service not available under insight");
-#else
-    UINT8 TaskId;
-
-	GKI_TRACE("TID TASKNAME STATE FREE_STACK  STACK");
-	for(TaskId=0; TaskId < GKI_MAX_TASKS; TaskId++)
-	{
-		if (gki_cb.com.OSRdyTbl[TaskId] != TASK_DEAD)
-		{
-			GKI_TRACE("%2u   %-8s %-5s  0x%04X     0x%04X Bytes",
-				(UINT16)TaskId,  gki_cb.com.OSTName[TaskId],
-				OSTaskStates[gki_cb.com.OSRdyTbl[TaskId]],
-                gki_calc_stack(TaskId), gki_cb.com.OSStackSize[TaskId]);
-
-        }
-    }
-#endif
-}
-
-
-/*******************************************************************************
-**
-** Function         gki_print_buffer_statistics
-**
-** Description      Called internally by OSS to print the buffer pools statistics
-**
-** Returns          void
-**
-*******************************************************************************/
-void gki_print_buffer_statistics(FP_PRINT print, INT16 pool)
-{
-    UINT16           i;
-    BUFFER_HDR_T    *hdr;
-    UINT16           size,act_size,maxbuffs;
-    UINT32           *magic;
-
-    if (pool > GKI_NUM_TOTAL_BUF_POOLS || pool < 0)
-    {
-        print("Not a valid Buffer pool\n");
-        return;
-    }
-
-    size = gki_cb.com.freeq[pool].size;
-    maxbuffs = gki_cb.com.freeq[pool].total;
-    act_size = size + BUFFER_PADDING_SIZE;
-    print("Buffer Pool[%u] size=%u cur_cnt=%u max_cnt=%u  total=%u\n",
-        pool, gki_cb.com.freeq[pool].size,
-        gki_cb.com.freeq[pool].cur_cnt, gki_cb.com.freeq[pool].max_cnt, gki_cb.com.freeq[pool].total);
-
-    print("      Owner  State    Sanity\n");
-    print("----------------------------\n");
-    hdr = (BUFFER_HDR_T *)(gki_cb.com.pool_start[pool]);
-    for(i=0; i<maxbuffs; i++)
-    {
-        magic = (UINT32 *)((UINT8 *)hdr + BUFFER_HDR_SIZE + size);
-        print("%3d: 0x%02x %4d %10s\n", i, hdr->task_id, hdr->status, (*magic == MAGIC_NO)?"OK":"CORRUPTED");
-        hdr          = (BUFFER_HDR_T *)((UINT8 *)hdr + act_size);
-    }
-    return;
-}
-
-
-/*******************************************************************************
-**
-** Function         gki_print_used_bufs
-**
-** Description      Dumps used buffers in the particular pool
-**
-*******************************************************************************/
-GKI_API void gki_print_used_bufs (FP_PRINT print, UINT8 pool_id)
-{
-    UINT8        *p_start;
-    UINT16       buf_size;
-    UINT16       num_bufs;
-    BUFFER_HDR_T *p_hdr;
-    UINT16       i;
-    UINT32         *magic;
-    UINT16       *p;
-
-
-    if ((pool_id >= GKI_NUM_TOTAL_BUF_POOLS) || (gki_cb.com.pool_start[pool_id] != 0))
-    {
-        print("Not a valid Buffer pool\n");
-        return;
-    }
-
-    p_start = gki_cb.com.pool_start[pool_id];
-    buf_size = gki_cb.com.freeq[pool_id].size + BUFFER_PADDING_SIZE;
-    num_bufs = gki_cb.com.freeq[pool_id].total;
-
-    for (i = 0; i < num_bufs; i++, p_start += buf_size)
-    {
-        p_hdr = (BUFFER_HDR_T *)p_start;
-        magic = (UINT32 *)((UINT8 *)p_hdr + buf_size - sizeof(UINT32));
-        p     = (UINT16 *) p_hdr;
-
-        if (p_hdr->status != BUF_STATUS_FREE)
-        {
-            print ("%d:0x%x (Q:%d,Task:%s,Stat:%d,%s) %04x %04x %04x %04x %04x %04x %04x %04x\n",
-                i, p_hdr,
-                p_hdr->q_id,
-                GKI_map_taskname(p_hdr->task_id),
-                p_hdr->status,
-                (*magic == MAGIC_NO)? "OK" : "CORRUPTED",
-                p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
-        }
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         gki_print_task
-**
-** Description      This function prints the task states.
-**
-** Returns          void
-**
-*******************************************************************************/
-void gki_print_task (FP_PRINT print)
-{
-    UINT8 i;
-
-    print("TID VID TASKNAME STATE WAIT WAITFOR TIMEOUT STACK\n");
-    print("-------------------------------------------------\n");
-    for(i=0; i<GKI_MAX_TASKS; i++)
-    {
-        if (gki_cb.com.OSRdyTbl[i] != TASK_DEAD)
-        {
-            print("%2u  %-8s %-5s %04X    %04X %7u %u/%u Bytes\n",
-                (UINT16)i,  gki_cb.com.OSTName[i],
-                OSTaskStates[gki_cb.com.OSRdyTbl[i]],
-                gki_cb.com.OSWaitEvt[i], gki_cb.com.OSWaitForEvt[i],
-                gki_cb.com.OSWaitTmr[i], gki_calc_stack(i), gki_cb.com.OSStackSize[i]);
-        }
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         gki_print_exception
-**
-** Description      This function prints the exception information.
-**
-** Returns          void
-**
-*******************************************************************************/
-void gki_print_exception(FP_PRINT print)
-{
-    UINT16 i;
-    EXCEPTION_T *pExp;
-
-    print ("GKI Exceptions:\n");
-    for (i = 0; i < gki_cb.com.ExceptionCnt; i++)
-    {
-        pExp =     &gki_cb.com.Exception[i];
-        print("%d: Type=%d, Task=%d: %s\n", i,
-            (INT32)pExp->type, (INT32)pExp->taskid, (INT8 *)pExp->msg);
-    }
-}
-
-
-/*****************************************************************************/
-void gki_dump (UINT8 *s, UINT16 len, FP_PRINT print)
-{
-    UINT16 i, j;
-
-    for(i=0, j=0; i<len; i++)
-    {
-        if(j == 0)
-            print("\n%lX: %02X, ", &s[i], s[i]);
-        else if(j == 7)
-            print("%02X,  ", s[i]);
-        else
-            print("%02X, ", s[i]);
-        if(++j == 16)
-            j=0;
-    }
-    print("\n");
-}
-
-void gki_dump2 (UINT16 *s, UINT16 len, FP_PRINT print)
-{
-    UINT16 i, j;
-
-    for(i=0, j=0; i<len; i++)
-    {
-        if(j == 0)
-            print("\n%lX: %04X, ", &s[i], s[i]);
-        else
-            print("%04X, ", s[i]);
-        if(++j == 8)
-            j=0;
-    }
-    print("\n");
-}
-
-void gki_dump4 (UINT32 *s, UINT16 len, FP_PRINT print)
-{
-    UINT16 i, j;
-
-    for(i=0, j=0; i<len; i++)
-    {
-        if(j == 0)
-            print("\n%lX: %08lX, ", &s[i], s[i]);
-        else
-            print("%08lX, ", s[i]);
-        if(++j == 4)
-            j=0;
-    }
-    print("\n");
-}
-
-
-#endif
diff --git a/gki/common/gki_time.c b/gki/common/gki_time.c
deleted file mode 100644
index 5c35726..0000000
--- a/gki/common/gki_time.c
+++ /dev/null
@@ -1,787 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-#include <assert.h>
-#include <utils/Log.h>
-#include "gki_int.h"
-
-/* Make sure that this has been defined in target.h */
-#ifndef GKI_NUM_TIMERS
-#error  NO TIMERS: Must define at least 1 timer in the system!
-#endif
-
-
-#define GKI_NO_NEW_TMRS_STARTED (0x7fffffffL)   /* Largest signed positive timer count */
-
-// Used for controlling alarms from AlarmService.
-extern void alarm_service_reschedule(void);
-
-/*******************************************************************************
-**
-** Function         gki_timers_init
-**
-** Description      This internal function is called once at startup to initialize
-**                  all the timer structures.
-**
-** Returns          void
-**
-*******************************************************************************/
-void gki_timers_init(void)
-{
-    UINT8   tt;
-
-    gki_cb.com.OSTicksTilExp = 0;       /* Remaining time (of OSTimeCurTimeout) before next timer expires */
-    gki_cb.com.OSNumOrigTicks = 0;
-
-    for (tt = 0; tt < GKI_MAX_TASKS; tt++)
-    {
-        gki_cb.com.OSWaitTmr   [tt] = 0;
-
-#if (GKI_NUM_TIMERS > 0)
-        gki_cb.com.OSTaskTmr0  [tt] = 0;
-        gki_cb.com.OSTaskTmr0R [tt] = 0;
-#endif
-
-#if (GKI_NUM_TIMERS > 1)
-        gki_cb.com.OSTaskTmr1  [tt] = 0;
-        gki_cb.com.OSTaskTmr1R [tt] = 0;
-#endif
-
-#if (GKI_NUM_TIMERS > 2)
-        gki_cb.com.OSTaskTmr2  [tt] = 0;
-        gki_cb.com.OSTaskTmr2R [tt] = 0;
-#endif
-
-#if (GKI_NUM_TIMERS > 3)
-        gki_cb.com.OSTaskTmr3  [tt] = 0;
-        gki_cb.com.OSTaskTmr3R [tt] = 0;
-#endif
-    }
-
-    return;
-}
-
-/*******************************************************************************
-**
-** Function         gki_timers_is_timer_running
-**
-** Description      This internal function is called to test if any gki timer are running
-**
-**
-** Returns          TRUE if at least one time is running in the system, FALSE else.
-**
-*******************************************************************************/
-BOOLEAN gki_timers_is_timer_running(void)
-{
-    UINT8   tt;
-    for (tt = 0; tt < GKI_MAX_TASKS; tt++)
-    {
-
-#if (GKI_NUM_TIMERS > 0)
-        if(gki_cb.com.OSTaskTmr0  [tt])
-        {
-            return TRUE;
-        }
-#endif
-
-#if (GKI_NUM_TIMERS > 1)
-        if(gki_cb.com.OSTaskTmr1  [tt] )
-        {
-            return TRUE;
-        }
-#endif
-
-#if (GKI_NUM_TIMERS > 2)
-        if(gki_cb.com.OSTaskTmr2  [tt] )
-        {
-            return TRUE;
-        }
-#endif
-
-#if (GKI_NUM_TIMERS > 3)
-        if(gki_cb.com.OSTaskTmr3  [tt] )
-        {
-            return TRUE;
-        }
-#endif
-    }
-
-    return FALSE;
-
-}
-
-/*******************************************************************************
-**
-** Function         GKI_get_tick_count
-**
-** Description      This function returns the current system ticks
-**
-** Returns          The current number of system ticks
-**
-*******************************************************************************/
-UINT32  GKI_get_tick_count(void)
-{
-    return gki_cb.com.OSTicks;
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_ready_to_sleep
-**
-** Description      This function returns the number of system ticks until the
-**                  next timer will expire.  It is typically called by a power
-**                  savings manager to find out how long it can have the system
-**                  sleep before it needs to service the next entry.
-**
-** Parameters:      None
-**
-** Returns          Number of ticks til the next timer expires
-**                  Note: the value is a signed  value.  This value should be
-**                      compared to x > 0, to avoid misinterpreting negative tick
-**                      values.
-**
-*******************************************************************************/
-INT32    GKI_ready_to_sleep (void)
-{
-    return (gki_cb.com.OSTicksTilExp);
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_start_timer
-**
-** Description      An application can call this function to start one of
-**                  it's four general purpose timers. Any of the four timers
-**                  can be 1-shot or continuous. If a timer is already running,
-**                  it will be reset to the new parameters.
-**
-** Parameters       tnum            - (input) timer number to be started (TIMER_0,
-**                                              TIMER_1, TIMER_2, or TIMER_3)
-**                  ticks           - (input) the number of system ticks til the
-**                                              timer expires.
-**                  is_continuous   - (input) TRUE if timer restarts automatically,
-**                                              else FALSE if it is a 'one-shot'.
-**
-** Returns          void
-**
-*******************************************************************************/
-void GKI_start_timer (UINT8 tnum, INT32 ticks, BOOLEAN is_continuous)
-{
-    INT32   reload;
-    INT32   orig_ticks;
-    UINT8   task_id = GKI_get_taskid();
-    BOOLEAN bad_timer = FALSE;
-
-    if (ticks <= 0)
-        ticks = 1;
-
-    orig_ticks = ticks;     /* save the ticks in case adjustment is necessary */
-
-
-    /* If continuous timer, set reload, else set it to 0 */
-    if (is_continuous)
-        reload = ticks;
-    else
-        reload = 0;
-
-    GKI_disable();
-
-    /* Add the time since the last task timer update.
-    ** Note that this works when no timers are active since
-    ** both OSNumOrigTicks and OSTicksTilExp are 0.
-    */
-    if (INT32_MAX - (gki_cb.com.OSNumOrigTicks - gki_cb.com.OSTicksTilExp) > ticks)
-    {
-        ticks += gki_cb.com.OSNumOrigTicks - gki_cb.com.OSTicksTilExp;
-    }
-    else
-        ticks = INT32_MAX;
-
-    switch (tnum)
-    {
-#if (GKI_NUM_TIMERS > 0)
-        case TIMER_0:
-            gki_cb.com.OSTaskTmr0R[task_id] = reload;
-            gki_cb.com.OSTaskTmr0 [task_id] = ticks;
-            break;
-#endif
-
-#if (GKI_NUM_TIMERS > 1)
-        case TIMER_1:
-            gki_cb.com.OSTaskTmr1R[task_id] = reload;
-            gki_cb.com.OSTaskTmr1 [task_id] = ticks;
-            break;
-#endif
-
-#if (GKI_NUM_TIMERS > 2)
-        case TIMER_2:
-            gki_cb.com.OSTaskTmr2R[task_id] = reload;
-            gki_cb.com.OSTaskTmr2 [task_id] = ticks;
-            break;
-#endif
-
-#if (GKI_NUM_TIMERS > 3)
-        case TIMER_3:
-            gki_cb.com.OSTaskTmr3R[task_id] = reload;
-            gki_cb.com.OSTaskTmr3 [task_id] = ticks;
-            break;
-#endif
-        default:
-            bad_timer = TRUE;       /* Timer number is bad, so do not use */
-    }
-
-    /* Update the expiration timeout if a legitimate timer */
-    if (!bad_timer)
-    {
-        /* Only update the timeout value if it is less than any other newly started timers */
-        gki_adjust_timer_count (orig_ticks);
-    }
-
-    GKI_enable();
-
-}
-
-/*******************************************************************************
-**
-** Function         GKI_stop_timer
-**
-** Description      An application can call this function to stop one of
-**                  it's four general purpose timers. There is no harm in
-**                  stopping a timer that is already stopped.
-**
-** Parameters       tnum            - (input) timer number to be started (TIMER_0,
-**                                              TIMER_1, TIMER_2, or TIMER_3)
-** Returns          void
-**
-*******************************************************************************/
-void GKI_stop_timer (UINT8 tnum)
-{
-    UINT8  task_id = GKI_get_taskid();
-
-    switch (tnum)
-    {
-#if (GKI_NUM_TIMERS > 0)
-        case TIMER_0:
-            gki_cb.com.OSTaskTmr0R[task_id] = 0;
-            gki_cb.com.OSTaskTmr0 [task_id] = 0;
-            break;
-#endif
-
-#if (GKI_NUM_TIMERS > 1)
-        case TIMER_1:
-            gki_cb.com.OSTaskTmr1R[task_id] = 0;
-            gki_cb.com.OSTaskTmr1 [task_id] = 0;
-            break;
-#endif
-
-#if (GKI_NUM_TIMERS > 2)
-        case TIMER_2:
-            gki_cb.com.OSTaskTmr2R[task_id] = 0;
-            gki_cb.com.OSTaskTmr2 [task_id] = 0;
-            break;
-#endif
-
-#if (GKI_NUM_TIMERS > 3)
-        case TIMER_3:
-            gki_cb.com.OSTaskTmr3R[task_id] = 0;
-            gki_cb.com.OSTaskTmr3 [task_id] = 0;
-            break;
-#endif
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_timer_update
-**
-** Description      This function is called by an OS to drive the GKI's timers.
-**                  It is typically called at every system tick to
-**                  update the timers for all tasks, and check for timeouts.
-**
-**                  Note: It has been designed to also allow for variable tick updates
-**                      so that systems with strict power savings requirements can
-**                      have the update occur at variable intervals.
-**
-** Parameters:      ticks_since_last_update - (input) This is the number of TICKS that have
-**                          occurred since the last time GKI_timer_update was called.
-**
-** Returns          void
-**
-*******************************************************************************/
-void GKI_timer_update (INT32 ticks_since_last_update)
-{
-    UINT8   task_id;
-    long    next_expiration;        /* Holds the next soonest expiration time after this update */
-
-    /* Increment the number of ticks used for time stamps */
-    gki_cb.com.OSTicks += ticks_since_last_update;
-
-    /* If any timers are running in any tasks, decrement the remaining time til
-     * the timer updates need to take place (next expiration occurs)
-     */
-    gki_cb.com.OSTicksTilExp -= ticks_since_last_update;
-
-    /* Don't allow timer interrupt nesting */
-    if (gki_cb.com.timer_nesting)
-        return;
-
-    gki_cb.com.timer_nesting = 1;
-
-    /* No need to update the ticks if no timeout has occurred */
-    if (gki_cb.com.OSTicksTilExp > 0)
-    {
-        // When using alarms from AlarmService we should
-        // always have work to be done here.
-        ALOGE("%s no work to be done when expected work", __func__);
-        gki_cb.com.timer_nesting = 0;
-        return;
-    }
-
-    next_expiration = GKI_NO_NEW_TMRS_STARTED;
-
-    /* If here then gki_cb.com.OSTicksTilExp <= 0. If negative, then increase gki_cb.com.OSNumOrigTicks
-       to account for the difference so timer updates below are decremented by the full number
-       of ticks. gki_cb.com.OSNumOrigTicks is reset at the bottom of this function so changing this
-       value only affects the timer updates below
-     */
-    gki_cb.com.OSNumOrigTicks -= gki_cb.com.OSTicksTilExp;
-
-    /* Protect this section because if a GKI_timer_stop happens between:
-     *   - gki_cb.com.OSTaskTmr0[task_id] -= gki_cb.com.OSNumOrigTicks;
-     *   - gki_cb.com.OSTaskTmr0[task_id] = gki_cb.com.OSTaskTmr0R[task_id];
-     * then the timer may appear stopped while it is about to be reloaded.
-     */
-    GKI_disable();
-
-    /* Check for OS Task Timers */
-    for (task_id = 0; task_id < GKI_MAX_TASKS; task_id++)
-    {
-        if (gki_cb.com.OSWaitTmr[task_id] > 0) /* If timer is running */
-        {
-            gki_cb.com.OSWaitTmr[task_id] -= gki_cb.com.OSNumOrigTicks;
-            if (gki_cb.com.OSWaitTmr[task_id] <= 0)
-            {
-                /* Timer Expired */
-                gki_cb.com.OSRdyTbl[task_id] = TASK_READY;
-            }
-        }
-
-#if (GKI_NUM_TIMERS > 0)
-         /* If any timer is running, decrement */
-        if (gki_cb.com.OSTaskTmr0[task_id] > 0)
-        {
-            gki_cb.com.OSTaskTmr0[task_id] -= gki_cb.com.OSNumOrigTicks;
-
-            if (gki_cb.com.OSTaskTmr0[task_id] <= 0)
-            {
-                /* Reload timer and set Timer 0 Expired event mask */
-                gki_cb.com.OSTaskTmr0[task_id] = gki_cb.com.OSTaskTmr0R[task_id];
-                GKI_send_event (task_id, TIMER_0_EVT_MASK);
-            }
-        }
-
-        /* Check to see if this timer is the next one to expire */
-        if (gki_cb.com.OSTaskTmr0[task_id] > 0 && gki_cb.com.OSTaskTmr0[task_id] < next_expiration)
-            next_expiration = gki_cb.com.OSTaskTmr0[task_id];
-#endif
-
-#if (GKI_NUM_TIMERS > 1)
-         /* If any timer is running, decrement */
-        if (gki_cb.com.OSTaskTmr1[task_id] > 0)
-        {
-            gki_cb.com.OSTaskTmr1[task_id] -= gki_cb.com.OSNumOrigTicks;
-
-            if (gki_cb.com.OSTaskTmr1[task_id] <= 0)
-            {
-                /* Reload timer and set Timer 1 Expired event mask */
-                gki_cb.com.OSTaskTmr1[task_id] = gki_cb.com.OSTaskTmr1R[task_id];
-                GKI_send_event (task_id, TIMER_1_EVT_MASK);
-            }
-        }
-
-        /* Check to see if this timer is the next one to expire */
-        if (gki_cb.com.OSTaskTmr1[task_id] > 0 && gki_cb.com.OSTaskTmr1[task_id] < next_expiration)
-            next_expiration = gki_cb.com.OSTaskTmr1[task_id];
-#endif
-
-#if (GKI_NUM_TIMERS > 2)
-         /* If any timer is running, decrement */
-        if (gki_cb.com.OSTaskTmr2[task_id] > 0)
-        {
-            gki_cb.com.OSTaskTmr2[task_id] -= gki_cb.com.OSNumOrigTicks;
-
-            if (gki_cb.com.OSTaskTmr2[task_id] <= 0)
-            {
-                /* Reload timer and set Timer 2 Expired event mask */
-                gki_cb.com.OSTaskTmr2[task_id] = gki_cb.com.OSTaskTmr2R[task_id];
-                GKI_send_event (task_id, TIMER_2_EVT_MASK);
-            }
-        }
-
-        /* Check to see if this timer is the next one to expire */
-        if (gki_cb.com.OSTaskTmr2[task_id] > 0 && gki_cb.com.OSTaskTmr2[task_id] < next_expiration)
-            next_expiration = gki_cb.com.OSTaskTmr2[task_id];
-#endif
-
-#if (GKI_NUM_TIMERS > 3)
-         /* If any timer is running, decrement */
-        if (gki_cb.com.OSTaskTmr3[task_id] > 0)
-        {
-            gki_cb.com.OSTaskTmr3[task_id] -= gki_cb.com.OSNumOrigTicks;
-
-            if (gki_cb.com.OSTaskTmr3[task_id] <= 0)
-            {
-                /* Reload timer and set Timer 3 Expired event mask */
-                gki_cb.com.OSTaskTmr3[task_id] = gki_cb.com.OSTaskTmr3R[task_id];
-                GKI_send_event (task_id, TIMER_3_EVT_MASK);
-            }
-        }
-
-        /* Check to see if this timer is the next one to expire */
-        if (gki_cb.com.OSTaskTmr3[task_id] > 0 && gki_cb.com.OSTaskTmr3[task_id] < next_expiration)
-            next_expiration = gki_cb.com.OSTaskTmr3[task_id];
-#endif
-
-    }
-    /* Set the next timer experation value if there is one to start */
-    if (next_expiration < GKI_NO_NEW_TMRS_STARTED)
-    {
-        gki_cb.com.OSTicksTilExp = gki_cb.com.OSNumOrigTicks = next_expiration;
-    }
-    else
-    {
-        gki_cb.com.OSTicksTilExp = gki_cb.com.OSNumOrigTicks = 0;
-    }
-
-    // Set alarm service for next alarm.
-    alarm_service_reschedule();
-
-    GKI_enable();
-
-    gki_cb.com.timer_nesting = 0;
-
-    return;
-}
-
-/*******************************************************************************
-**
-** Function         GKI_init_timer_list
-**
-** Description      This function is called by applications when they
-**                  want to initialize a timer list.
-**
-** Parameters       p_timer_listq   - (input) pointer to the timer list queue object
-**
-** Returns          void
-**
-*******************************************************************************/
-void GKI_init_timer_list(TIMER_LIST_Q *timer_q) {
-    timer_q->p_first    = NULL;
-    timer_q->p_last     = NULL;
-}
-
-bool GKI_timer_queue_is_empty(const TIMER_LIST_Q *timer_q) {
-    assert(timer_q != NULL);
-    return (timer_q->p_first == NULL);
-}
-
-TIMER_LIST_ENT *GKI_timer_getfirst(const TIMER_LIST_Q *timer_q) {
-    assert(timer_q != NULL);
-    return timer_q->p_first;
-}
-
-/* Returns the initial number of ticks for this timer entry. */
-INT32 GKI_timer_ticks_getinitial(const TIMER_LIST_ENT *tle) {
-    assert(tle != NULL);
-    return tle->ticks_initial;
-}
-
-/*******************************************************************************
-**
-** Function         GKI_update_timer_list
-**
-** Description      This function is called by the applications when they
-**                  want to update a timer list. This should be at every
-**                  timer list unit tick, e.g. once per sec, once per minute etc.
-**
-** Parameters       p_timer_listq   - (input) pointer to the timer list queue object
-**                  num_units_since_last_update - (input) number of units since the last update
-**                                  (allows for variable unit update)
-**
-**      NOTE: The following timer list update routines should not be used for exact time
-**            critical purposes.  The timer tasks should be used when exact timing is needed.
-**
-** Returns          the number of timers that have expired
-**
-*******************************************************************************/
-UINT16 GKI_update_timer_list (TIMER_LIST_Q *p_timer_listq, INT32 num_units_since_last_update)
-{
-    TIMER_LIST_ENT  *p_tle;
-    UINT16           num_time_out = 0;
-    INT32            rem_ticks;
-    INT32            temp_ticks;
-
-    p_tle = p_timer_listq->p_first;
-
-    /* First, get the guys who have previously timed out */
-    /* Note that the tick value of the timers should always be '0' */
-    while ((p_tle) && (p_tle->ticks <= 0))
-    {
-        num_time_out++;
-        p_tle = p_tle->p_next;
-    }
-
-    /* Timer entriy tick values are relative to the preceeding entry */
-    rem_ticks = num_units_since_last_update;
-
-    /* Now, adjust remaining timer entries */
-    while ((p_tle != NULL) && (rem_ticks > 0))
-    {
-        temp_ticks = p_tle->ticks;
-        p_tle->ticks -= rem_ticks;
-
-        /* See if this timer has just timed out */
-        if (p_tle->ticks <= 0)
-        {
-            /* We set the number of ticks to '0' so that the legacy code
-             * that assumes a '0' or nonzero value will still work as coded. */
-            p_tle->ticks = 0;
-
-            num_time_out++;
-        }
-
-        rem_ticks -= temp_ticks;  /* Decrement the remaining ticks to process */
-        p_tle = p_tle->p_next;
-    }
-
-    return (num_time_out);
-}
-
-/*******************************************************************************
-**
-** Function         GKI_get_remaining_ticks
-**
-** Description      This function is called by an application to get remaining
-**                  ticks to expire
-**
-** Parameters       p_timer_listq   - (input) pointer to the timer list queue object
-**                  p_target_tle    - (input) pointer to a timer list queue entry
-**
-** Returns          0 if timer is not used or timer is not in the list
-**                  remaining ticks if success
-**
-*******************************************************************************/
-UINT32 GKI_get_remaining_ticks (TIMER_LIST_Q *p_timer_listq, TIMER_LIST_ENT  *p_target_tle)
-{
-    TIMER_LIST_ENT  *p_tle;
-    UINT32           rem_ticks = 0;
-
-    if (p_target_tle->in_use)
-    {
-        p_tle = p_timer_listq->p_first;
-
-        /* adding up all of ticks in previous entries */
-        while ((p_tle)&&(p_tle != p_target_tle))
-        {
-            rem_ticks += p_tle->ticks;
-            p_tle = p_tle->p_next;
-        }
-
-        /* if found target entry */
-        if (p_tle == p_target_tle)
-        {
-            rem_ticks += p_tle->ticks;
-        }
-        else
-        {
-            return(0);
-        }
-    }
-
-    return (rem_ticks);
-}
-
-/*******************************************************************************
-**
-** Function         GKI_add_to_timer_list
-**
-** Description      This function is called by an application to add a timer
-**                  entry to a timer list.
-**
-**                  Note: A timer value of '0' will effectively insert an already
-**                      expired event.  Negative tick values will be ignored.
-**
-** Parameters       p_timer_listq   - (input) pointer to the timer list queue object
-**                  p_tle           - (input) pointer to a timer list queue entry
-**
-** Returns          void
-**
-*******************************************************************************/
-void GKI_add_to_timer_list (TIMER_LIST_Q *p_timer_listq, TIMER_LIST_ENT  *p_tle)
-{
-    /* Only process valid tick values. */
-    if (p_tle->ticks < 0)
-        return;
-
-    p_tle->p_prev = NULL;
-    p_tle->p_next = NULL;
-    p_tle->in_use = true;
-
-    /* Insert at head. */
-    if (p_timer_listq->p_first == NULL)
-    {
-        p_timer_listq->p_first = p_tle;
-        p_timer_listq->p_last = p_tle;
-        return;
-    }
-
-    /* Find the node before which we need to insert p_tle. */
-    TIMER_LIST_ENT *i = p_timer_listq->p_first;
-    while (i && p_tle->ticks > i->ticks)
-    {
-        if (i->ticks > 0)
-            p_tle->ticks -= i->ticks;
-        i = i->p_next;
-    }
-
-    /* Insert at tail. */
-    if (!i)
-    {
-        p_timer_listq->p_last->p_next = p_tle;
-        p_tle->p_prev = p_timer_listq->p_last;
-        p_timer_listq->p_last = p_tle;
-        return;
-    }
-
-    p_tle->p_prev = i->p_prev;
-    if (p_tle->p_prev)
-        p_tle->p_prev->p_next = p_tle;
-    p_tle->p_next = i;
-    i->p_prev = p_tle;
-    i->ticks -= p_tle->ticks;
-
-    if (p_timer_listq->p_first == i)
-        p_timer_listq->p_first = p_tle;
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_remove_from_timer_list
-**
-** Description      This function is called by an application to remove a timer
-**                  entry from a timer list.
-**
-** Parameters       p_timer_listq   - (input) pointer to the timer list queue object
-**                  p_tle           - (input) pointer to a timer list queue entry
-**
-** Returns          TRUE if the entry has been unlinked successfully
-**
-*******************************************************************************/
-BOOLEAN GKI_remove_from_timer_list (TIMER_LIST_Q *p_timer_listq, TIMER_LIST_ENT  *p_tle)
-{
-    /* Verify that the entry is valid */
-    if (p_tle == NULL || p_timer_listq->p_first == NULL)
-        return FALSE;
-
-    /* Add the ticks remaining in this timer (if any) to the next guy in the list.
-    ** Note: Expired timers have a tick value of '0'.
-    */
-    if (p_tle->p_next != NULL)
-    {
-        p_tle->p_next->ticks += p_tle->ticks;
-    }
-
-    p_tle->ticks = 0;
-    p_tle->in_use = FALSE;
-
-    /* Unlink timer from the list.
-    */
-    if (p_timer_listq->p_first == p_tle)
-    {
-        p_timer_listq->p_first = p_tle->p_next;
-
-        if (p_timer_listq->p_first != NULL)
-            p_timer_listq->p_first->p_prev = NULL;
-
-        if (p_timer_listq->p_last == p_tle)
-            p_timer_listq->p_last = NULL;
-    }
-    else
-    {
-        if (p_timer_listq->p_last == p_tle)
-        {
-            p_timer_listq->p_last = p_tle->p_prev;
-
-            if (p_timer_listq->p_last != NULL)
-                p_timer_listq->p_last->p_next = NULL;
-        }
-        else
-        {
-            if (p_tle->p_next != NULL && p_tle->p_next->p_prev == p_tle)
-                p_tle->p_next->p_prev = p_tle->p_prev;
-            else
-                return FALSE; // Timer list broken?!
-
-            if (p_tle->p_prev != NULL && p_tle->p_prev->p_next == p_tle)
-                p_tle->p_prev->p_next = p_tle->p_next;
-            else
-                return FALSE; // Timer list broken?!
-        }
-    }
-
-    p_tle->p_next = p_tle->p_prev = NULL;
-    return TRUE;
-}
-
-
-/*******************************************************************************
-**
-** Function         gki_adjust_timer_count
-**
-** Description      This function is called whenever a new timer or GKI_wait occurs
-**                  to adjust (if necessary) the current time til the first expiration.
-**                  This only needs to make an adjustment if the new timer (in ticks) is
-**                  less than the number of ticks remaining on the current timer.
-**
-** Parameters:      ticks - (input) number of system ticks of the new timer entry
-**
-**                  NOTE:  This routine MUST be called while interrupts are disabled to
-**                          avoid updates while adjusting the timer variables.
-**
-** Returns          void
-**
-*******************************************************************************/
-void gki_adjust_timer_count (INT32 ticks)
-{
-    if (ticks > 0)
-    {
-        /* See if the new timer expires before the current first expiration */
-        if (gki_cb.com.OSNumOrigTicks == 0 || (ticks < gki_cb.com.OSTicksTilExp && gki_cb.com.OSTicksTilExp > 0))
-        {
-            gki_cb.com.OSNumOrigTicks = (gki_cb.com.OSNumOrigTicks - gki_cb.com.OSTicksTilExp) + ticks;
-            gki_cb.com.OSTicksTilExp = ticks;
-            alarm_service_reschedule();
-        }
-    }
-
-    return;
-}
diff --git a/gki/ulinux/data_types.h b/gki/ulinux/data_types.h
deleted file mode 100644
index 14b5899..0000000
--- a/gki/ulinux/data_types.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-#ifndef DATA_TYPES_H
-#define DATA_TYPES_H
-
-#include <stdint.h>
-#include <stdbool.h>
-
-#ifndef FALSE
-#  define FALSE  false
-#endif
-
-#ifndef TRUE
-#  define TRUE   true
-#endif
-
-typedef uint8_t UINT8;
-typedef uint16_t UINT16;
-typedef uint32_t UINT32;
-typedef uint64_t UINT64;
-
-typedef int8_t INT8;
-typedef int16_t INT16;
-typedef int32_t INT32;
-typedef bool BOOLEAN;
-
-typedef UINT32          TIME_STAMP;
-
-#ifdef __arm
-#  define PACKED  __packed
-#  define INLINE  __inline
-#else
-#  define PACKED
-#  define INLINE
-#endif
-
-#define BCM_STRCPY_S(x1,x2,x3)      strcpy((x1),(x3))
-#define BCM_STRNCPY_S(x1,x2,x3,x4)  strncpy((x1),(x3),(x4))
-
-#endif
diff --git a/gki/ulinux/gki_int.h b/gki/ulinux/gki_int.h
index ec9b1cb..6e05a85 100644
--- a/gki/ulinux/gki_int.h
+++ b/gki/ulinux/gki_int.h
@@ -15,80 +15,17 @@
  *  limitations under the License.
  *
  ******************************************************************************/
-#ifndef GKI_INT_H
-#define GKI_INT_H
+
+#pragma once
+
+#include <pthread.h>
 
 #include "gki_common.h"
-#include <pthread.h>
-#include <sys/prctl.h>
-
-/**********************************************************************
-** OS specific definitions
-*/
-/* The base priority used for pthread based GKI task. below value is to keep it retro compatible.
- * It is recommended to use (GKI_MAX_TASKS+3), this will assign real time priorities GKI_MAX_TASKS-
- * task_id -2 to the thread */
-#ifndef GKI_LINUX_BASE_PRIORITY
-#define GKI_LINUX_BASE_PRIORITY 30
-#endif
-
-/* The base policy used for pthread based GKI task. the sched defines are defined here to avoid undefined values due
- * to missing header file, see pthread functions! Overall it is recommend however to use SCHED_NOMRAL */
-#define GKI_SCHED_NORMAL    0
-#define GKI_SCHED_FIFO      1
-#define GKI_SCHED_RR        2
-#ifndef GKI_LINUX_BASE_POLICY
-#define GKI_LINUX_BASE_POLICY GKI_SCHED_NORMAL
-#endif
-
-/* GKI timer bases should use GKI_SCHED_FIFO to ensure the least jitter possible */
-#ifndef GKI_LINUX_TIMER_POLICY
-#define GKI_LINUX_TIMER_POLICY GKI_SCHED_FIFO
-#endif
-
-/* the GKI_timer_update() thread should have the highest real time priority to ensue correct
- * timer expiry.
- */
-#ifndef GKI_LINUX_TIMER_TICK_PRIORITY
-#define GKI_LINUX_TIMER_TICK_PRIORITY GKI_LINUX_BASE_PRIORITY+2
-#endif
 
 typedef struct
 {
-    pthread_mutex_t     GKI_mutex;
-    pthread_t           thread_id[GKI_MAX_TASKS];
-    pthread_mutex_t     thread_evt_mutex[GKI_MAX_TASKS];
-    pthread_cond_t      thread_evt_cond[GKI_MAX_TASKS];
-    pthread_mutex_t     thread_timeout_mutex[GKI_MAX_TASKS];
-    pthread_cond_t      thread_timeout_cond[GKI_MAX_TASKS];
-#if (GKI_DEBUG == TRUE)
-    pthread_mutex_t     GKI_trace_mutex;
-#endif
-} tGKI_OS;
-
-extern void gki_system_tick_start_stop_cback(BOOLEAN start);
-
-/* Contains common control block as well as OS specific variables */
-typedef struct
-{
-    tGKI_OS     os;
+    pthread_mutex_t lock;
     tGKI_COM_CB com;
 } tGKI_CB;
 
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if GKI_DYNAMIC_MEMORY == FALSE
-GKI_API extern tGKI_CB  gki_cb;
-#else
-GKI_API extern tGKI_CB *gki_cb_ptr;
-#define gki_cb (*gki_cb_ptr)
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+extern tGKI_CB  gki_cb;
diff --git a/gki/ulinux/gki_ulinux.c b/gki/ulinux/gki_ulinux.c
index 8a11983..c928fbd 100644
--- a/gki/ulinux/gki_ulinux.c
+++ b/gki/ulinux/gki_ulinux.c
@@ -16,1148 +16,72 @@
  *
  ******************************************************************************/
 
-/****************************************************************************
-**
-**  Name        gki_linux_pthreads.c
-**
-**  Function    pthreads version of Linux GKI. This version is used for
-**              settop projects that already use pthreads and not pth.
-**
-*****************************************************************************/
-#include "bt_target.h"
+#define LOG_TAG "bt_gki"
 
 #include <assert.h>
-#include <errno.h>
-#include <malloc.h>
-#include <string.h>
-#include <signal.h>
-#include <sys/times.h>
+#include <pthread.h>
 #include <time.h>
 
-#include "gki_int.h"
-#include "bt_utils.h"
+#include "btcore/include/module.h"
+#include "gki/ulinux/gki_int.h"
+#include "osi/include/log.h"
+#include "osi/include/osi.h"
 
-#define LOG_TAG "GKI_LINUX"
+tGKI_CB gki_cb;
 
-#include <utils/Log.h>
-#include <hardware/bluetooth.h>
+static future_t *init(void) {
+  memset(&gki_cb, 0, sizeof(gki_cb));
 
-/*****************************************************************************
-**  Constants & Macros
-******************************************************************************/
+  pthread_mutexattr_t attr;
+  pthread_mutexattr_init(&attr);
+  pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
+  pthread_mutex_init(&gki_cb.lock, &attr);
 
-#define SCHED_NORMAL 0
-#define SCHED_FIFO 1
-#define SCHED_RR 2
-#define SCHED_BATCH 3
-
-#define NANOSEC_PER_MILLISEC    1000000
-#define NSEC_PER_SEC            (1000 * NANOSEC_PER_MILLISEC)
-#define USEC_PER_SEC            1000000
-#define NSEC_PER_USEC           1000
-
-#define WAKE_LOCK_ID "bluedroid_timer"
-
-#if GKI_DYNAMIC_MEMORY == FALSE
-tGKI_CB   gki_cb;
-#endif
-
-#ifndef GKI_SHUTDOWN_EVT
-#define GKI_SHUTDOWN_EVT    APPL_EVT_7
-#endif
-
-/*****************************************************************************
-**  Local type definitions
-******************************************************************************/
-
-typedef struct
-{
-    UINT8 task_id;          /* GKI task id */
-    TASKPTR task_entry;     /* Task entry function*/
-    UINT32 params;          /* Extra params to pass to task entry function */
-} gki_pthread_info_t;
-
-// Alarm service structure used to pass up via JNI to the bluetooth
-// app in order to create a wakeable Alarm.
-typedef struct
-{
-    UINT32 ticks_scheduled;
-    UINT64 timer_started_us;
-    UINT64 timer_last_expired_us;
-    bool wakelock;
-} alarm_service_t;
-
-/*****************************************************************************
-**  Static variables
-******************************************************************************/
-
-gki_pthread_info_t gki_pthread_info[GKI_MAX_TASKS];
-
-// Only a single alarm is used to wake bluedroid.
-// NOTE: Must be manipulated with the GKI_disable() lock held.
-static alarm_service_t alarm_service;
-
-static timer_t posix_timer;
-static bool timer_created;
-
-
-/*****************************************************************************
-**  Externs
-******************************************************************************/
-
-extern bt_os_callouts_t *bt_os_callouts;
-
-/*****************************************************************************
-**  Functions
-******************************************************************************/
-
-static UINT64 now_us()
-{
-    struct timespec ts_now;
-    clock_gettime(CLOCK_BOOTTIME, &ts_now);
-    return ((UINT64)ts_now.tv_sec * USEC_PER_SEC) + ((UINT64)ts_now.tv_nsec / NSEC_PER_USEC);
+  gki_buffer_init();
+  return NULL;
 }
 
-static bool set_nonwake_alarm(UINT64 delay_millis)
-{
-    if (!timer_created)
-    {
-        ALOGE("%s timer is not available, not setting timer for %llums", __func__, delay_millis);
-        return false;
-    }
+static future_t *clean_up(void) {
+  gki_buffer_cleanup();
 
-    const UINT64 now = now_us();
-    alarm_service.timer_started_us = now;
-
-    UINT64 prev_timer_delay = 0;
-    if (alarm_service.timer_last_expired_us)
-        prev_timer_delay = now - alarm_service.timer_last_expired_us;
-
-    UINT64 delay_micros = delay_millis * 1000;
-    if (delay_micros > prev_timer_delay)
-        delay_micros -= prev_timer_delay;
-    else
-        delay_micros = 1;
-
-    struct itimerspec new_value;
-    memset(&new_value, 0, sizeof(new_value));
-    new_value.it_value.tv_sec = (delay_micros / USEC_PER_SEC);
-    new_value.it_value.tv_nsec = (delay_micros % USEC_PER_SEC) * NSEC_PER_USEC;
-    if (timer_settime(posix_timer, 0, &new_value, NULL) == -1)
-    {
-        ALOGE("%s unable to set timer: %s", __func__, strerror(errno));
-        return false;
-    }
-    return true;
+  pthread_mutex_destroy(&gki_cb.lock);
+  return NULL;
 }
 
-/** Callback from Java thread after alarm from AlarmService fires. */
-static void bt_alarm_cb(void *data)
-{
-    UINT32 ticks_taken = 0;
+// Temp module until GKI dies
+const module_t gki_module = {
+  .name = GKI_MODULE,
+  .init = init,
+  .start_up = NULL,
+  .shut_down = NULL,
+  .clean_up = clean_up,
+  .dependencies = {
+    NULL
+  }
+};
 
-    alarm_service.timer_last_expired_us = now_us();
-    if (alarm_service.timer_last_expired_us > alarm_service.timer_started_us)
-    {
-        ticks_taken = GKI_MS_TO_TICKS((alarm_service.timer_last_expired_us
-                                       - alarm_service.timer_started_us) / 1000);
-    } else {
-        // this could happen on some platform
-        ALOGE("%s now_us %lld less than %lld", __func__, alarm_service.timer_last_expired_us,
-              alarm_service.timer_started_us);
-    }
-
-    GKI_timer_update(ticks_taken > alarm_service.ticks_scheduled
-                   ? ticks_taken : alarm_service.ticks_scheduled);
+UINT32 GKI_get_os_tick_count(void) {
+  struct timespec timespec;
+  clock_gettime(CLOCK_BOOTTIME, &timespec);
+  return (timespec.tv_sec * 1000) + (timespec.tv_nsec / 1000000);
 }
 
-/** NOTE: This is only called on init and may be called without the GKI_disable()
-  * lock held.
-  */
-static void alarm_service_init()
-{
-    alarm_service.ticks_scheduled = 0;
-    alarm_service.timer_started_us = 0;
-    alarm_service.timer_last_expired_us = 0;
-    alarm_service.wakelock = FALSE;
-    raise_priority_a2dp(TASK_JAVA_ALARM);
+// Sleep the calling thread unconditionally for |timeout_ms| milliseconds.
+void GKI_delay(UINT32 timeout_ms) {
+  struct timespec delay;
+  delay.tv_sec = timeout_ms / 1000;
+  delay.tv_nsec = 1000 * 1000 * (timeout_ms % 1000);
+
+  int err;
+  do {
+    err = nanosleep(&delay, &delay);
+  } while (err == -1 && errno == EINTR);
 }
 
-/** Requests an alarm from AlarmService to fire when the next
-  * timer in the timer queue is set to expire. Only takes a wakelock
-  * if the timer tick expiration is a short interval in the future
-  * and releases the wakelock if the timer is a longer interval
-  * or if there are no more timers in the queue.
-  *
-  * NOTE: Must be called with GKI_disable() lock held.
-  */
-void alarm_service_reschedule()
-{
-    int32_t ticks_till_next_exp = GKI_ready_to_sleep();
-
-    assert(ticks_till_next_exp >= 0);
-    alarm_service.ticks_scheduled = ticks_till_next_exp;
-
-    // No more timers remaining. Release wakelock if we're holding one.
-    if (ticks_till_next_exp == 0)
-    {
-        alarm_service.timer_last_expired_us = 0;
-        alarm_service.timer_started_us = 0;
-        if (alarm_service.wakelock)
-        {
-            ALOGV("%s releasing wake lock.", __func__);
-            alarm_service.wakelock = false;
-            int rc = bt_os_callouts->release_wake_lock(WAKE_LOCK_ID);
-            if (rc != BT_STATUS_SUCCESS)
-            {
-                ALOGE("%s unable to release wake lock with no timers: %d", __func__, rc);
-            }
-        }
-        ALOGV("%s no more alarms.", __func__);
-        return;
-    }
-
-    UINT64 ticks_in_millis = GKI_TICKS_TO_MS(ticks_till_next_exp);
-    if (ticks_in_millis <= GKI_TIMER_INTERVAL_FOR_WAKELOCK)
-    {
-        // The next deadline is close, just take a wakelock and set a regular (non-wake) timer.
-        if (!alarm_service.wakelock)
-        {
-            int rc = bt_os_callouts->acquire_wake_lock(WAKE_LOCK_ID);
-            if (rc != BT_STATUS_SUCCESS)
-            {
-                ALOGE("%s unable to acquire wake lock: %d", __func__, rc);
-                return;
-            }
-            alarm_service.wakelock = true;
-        }
-        ALOGV("%s acquired wake lock, setting short alarm (%lldms).", __func__, ticks_in_millis);
-
-        if (!set_nonwake_alarm(ticks_in_millis))
-        {
-            ALOGE("%s unable to set short alarm.", __func__);
-        }
-    } else {
-        // The deadline is far away, set a wake alarm and release wakelock if we're holding it.
-        alarm_service.timer_started_us = now_us();
-        alarm_service.timer_last_expired_us = 0;
-        if (!bt_os_callouts->set_wake_alarm(ticks_in_millis, true, bt_alarm_cb, &alarm_service))
-        {
-            ALOGE("%s unable to set long alarm, releasing wake lock anyway.", __func__);
-        } else {
-            ALOGV("%s set long alarm (%lldms), releasing wake lock.", __func__, ticks_in_millis);
-        }
-
-        if (alarm_service.wakelock)
-        {
-            alarm_service.wakelock = false;
-            bt_os_callouts->release_wake_lock(WAKE_LOCK_ID);
-        }
-    }
+void GKI_enable(void) {
+  pthread_mutex_unlock(&gki_cb.lock);
 }
 
-
-/*****************************************************************************
-**
-** Function        gki_task_entry
-**
-** Description     GKI pthread callback
-**
-** Returns         void
-**
-*******************************************************************************/
-static void gki_task_entry(UINT32 params)
-{
-    gki_pthread_info_t *p_pthread_info = (gki_pthread_info_t *)params;
-    gki_cb.os.thread_id[p_pthread_info->task_id] = pthread_self();
-
-    prctl(PR_SET_NAME, (unsigned long)gki_cb.com.OSTName[p_pthread_info->task_id], 0, 0, 0);
-
-    ALOGI("gki_task_entry task_id=%i [%s] starting\n", p_pthread_info->task_id,
-                gki_cb.com.OSTName[p_pthread_info->task_id]);
-
-    /* Call the actual thread entry point */
-    (p_pthread_info->task_entry)(p_pthread_info->params);
-
-    ALOGI("gki_task task_id=%i [%s] terminating\n", p_pthread_info->task_id,
-                gki_cb.com.OSTName[p_pthread_info->task_id]);
-
-    pthread_exit(0);    /* GKI tasks have no return value */
-}
-
-/*******************************************************************************
-**
-** Function         GKI_init
-**
-** Description      This function is called once at startup to initialize
-**                  all the timer structures.
-**
-** Returns          void
-**
-*******************************************************************************/
-
-void GKI_init(void)
-{
-    pthread_mutexattr_t attr;
-    tGKI_OS             *p_os;
-
-    memset (&gki_cb, 0, sizeof (gki_cb));
-
-    gki_buffer_init();
-    gki_timers_init();
-    alarm_service_init();
-
-    gki_cb.com.OSTicks = (UINT32) times(0);
-
-    pthread_mutexattr_init(&attr);
-
-#ifndef __CYGWIN__
-    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
-#endif
-    p_os = &gki_cb.os;
-    pthread_mutex_init(&p_os->GKI_mutex, &attr);
-    /* pthread_mutex_init(&GKI_sched_mutex, NULL); */
-#if (GKI_DEBUG == TRUE)
-    pthread_mutex_init(&p_os->GKI_trace_mutex, NULL);
-#endif
-    /* pthread_mutex_init(&thread_delay_mutex, NULL); */  /* used in GKI_delay */
-    /* pthread_cond_init (&thread_delay_cond, NULL); */
-
-    struct sigevent sigevent;
-    memset(&sigevent, 0, sizeof(sigevent));
-    sigevent.sigev_notify = SIGEV_THREAD;
-    sigevent.sigev_notify_function = (void (*)(union sigval))bt_alarm_cb;
-    sigevent.sigev_value.sival_ptr = NULL;
-    if (timer_create(CLOCK_REALTIME, &sigevent, &posix_timer) == -1) {
-        ALOGE("%s unable to create POSIX timer: %s", __func__, strerror(errno));
-        timer_created = false;
-    } else {
-        timer_created = true;
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_get_os_tick_count
-**
-** Description      This function is called to retrieve the native OS system tick.
-**
-** Returns          Tick count of native OS.
-**
-*******************************************************************************/
-UINT32 GKI_get_os_tick_count(void)
-{
-    return gki_cb.com.OSTicks;
-}
-
-/*******************************************************************************
-**
-** Function         GKI_create_task
-**
-** Description      This function is called to create a new OSS task.
-**
-** Parameters:      task_entry  - (input) pointer to the entry function of the task
-**                  task_id     - (input) Task id is mapped to priority
-**                  taskname    - (input) name given to the task
-**                  stack       - (input) pointer to the top of the stack (highest memory location)
-**                  stacksize   - (input) size of the stack allocated for the task
-**
-** Returns          GKI_SUCCESS if all OK, GKI_FAILURE if any problem
-**
-** NOTE             This function take some parameters that may not be needed
-**                  by your particular OS. They are here for compatability
-**                  of the function prototype.
-**
-*******************************************************************************/
-UINT8 GKI_create_task (TASKPTR task_entry, UINT8 task_id, INT8 *taskname, UINT16 *stack, UINT16 stacksize)
-{
-    struct sched_param param;
-    int policy, ret = 0;
-    pthread_attr_t attr1;
-    UNUSED(stack);
-    UNUSED(stacksize);
-
-    GKI_TRACE( "GKI_create_task %x %d %s %x %d", (int)task_entry, (int)task_id,
-            (char*) taskname, (int) stack, (int)stacksize);
-
-    if (task_id >= GKI_MAX_TASKS)
-    {
-        ALOGE("Error! task ID > max task allowed");
-        return (GKI_FAILURE);
-    }
-
-
-    gki_cb.com.OSRdyTbl[task_id]    = TASK_READY;
-    gki_cb.com.OSTName[task_id]     = taskname;
-    gki_cb.com.OSWaitTmr[task_id]   = 0;
-    gki_cb.com.OSWaitEvt[task_id]   = 0;
-
-    /* Initialize mutex and condition variable objects for events and timeouts */
-    pthread_condattr_t cond_attr;
-    pthread_condattr_init(&cond_attr);
-    pthread_condattr_setclock(&cond_attr, CLOCK_MONOTONIC);
-
-    pthread_mutex_init(&gki_cb.os.thread_evt_mutex[task_id], NULL);
-    pthread_cond_init (&gki_cb.os.thread_evt_cond[task_id], &cond_attr);
-    pthread_mutex_init(&gki_cb.os.thread_timeout_mutex[task_id], NULL);
-    pthread_cond_init (&gki_cb.os.thread_timeout_cond[task_id], NULL);
-
-    pthread_attr_init(&attr1);
-    /* by default, pthread creates a joinable thread */
-#if ( FALSE == GKI_PTHREAD_JOINABLE )
-    pthread_attr_setdetachstate(&attr1, PTHREAD_CREATE_DETACHED);
-
-    GKI_TRACE("GKI creating task %i\n", task_id);
-#else
-    GKI_TRACE("GKI creating JOINABLE task %i\n", task_id);
-#endif
-
-    /* On Android, the new tasks starts running before 'gki_cb.os.thread_id[task_id]' is initialized */
-    /* Pass task_id to new task so it can initialize gki_cb.os.thread_id[task_id] for it calls GKI_wait */
-    gki_pthread_info[task_id].task_id = task_id;
-    gki_pthread_info[task_id].task_entry = task_entry;
-    gki_pthread_info[task_id].params = 0;
-
-    ret = pthread_create( &gki_cb.os.thread_id[task_id],
-              &attr1,
-              (void *)gki_task_entry,
-              &gki_pthread_info[task_id]);
-
-    if (ret != 0)
-    {
-         ALOGE("pthread_create failed(%d), %s!", ret, taskname);
-         return GKI_FAILURE;
-    }
-
-    if(pthread_getschedparam(gki_cb.os.thread_id[task_id], &policy, &param)==0)
-     {
-#if (GKI_LINUX_BASE_POLICY!=GKI_SCHED_NORMAL)
-#if defined(PBS_SQL_TASK)
-         if (task_id == PBS_SQL_TASK)
-         {
-             GKI_TRACE("PBS SQL lowest priority task");
-             policy = SCHED_NORMAL;
-         }
-         else
-#endif
-#endif
-         {
-             /* check if define in gki_int.h is correct for this compile environment! */
-             policy = GKI_LINUX_BASE_POLICY;
-#if (GKI_LINUX_BASE_POLICY != GKI_SCHED_NORMAL)
-             param.sched_priority = GKI_LINUX_BASE_PRIORITY - task_id - 2;
-#else
-             param.sched_priority = 0;
-#endif
-         }
-         pthread_setschedparam(gki_cb.os.thread_id[task_id], policy, &param);
-     }
-
-    GKI_TRACE( "Leaving GKI_create_task %x %d %x %s %x %d\n",
-              (int)task_entry,
-              (int)task_id,
-              (int)gki_cb.os.thread_id[task_id],
-              (char*)taskname,
-              (int)stack,
-              (int)stacksize);
-
-    return (GKI_SUCCESS);
-}
-
-void GKI_destroy_task(UINT8 task_id)
-{
-#if ( FALSE == GKI_PTHREAD_JOINABLE )
-        int i = 0;
-#else
-        int result;
-#endif
-    if (gki_cb.com.OSRdyTbl[task_id] != TASK_DEAD)
-    {
-        gki_cb.com.OSRdyTbl[task_id] = TASK_DEAD;
-
-        /* paranoi settings, make sure that we do not execute any mailbox events */
-        gki_cb.com.OSWaitEvt[task_id] &= ~(TASK_MBOX_0_EVT_MASK|TASK_MBOX_1_EVT_MASK|
-                                            TASK_MBOX_2_EVT_MASK|TASK_MBOX_3_EVT_MASK);
-
-#if (GKI_NUM_TIMERS > 0)
-        gki_cb.com.OSTaskTmr0R[task_id] = 0;
-        gki_cb.com.OSTaskTmr0 [task_id] = 0;
-#endif
-
-#if (GKI_NUM_TIMERS > 1)
-        gki_cb.com.OSTaskTmr1R[task_id] = 0;
-        gki_cb.com.OSTaskTmr1 [task_id] = 0;
-#endif
-
-#if (GKI_NUM_TIMERS > 2)
-        gki_cb.com.OSTaskTmr2R[task_id] = 0;
-        gki_cb.com.OSTaskTmr2 [task_id] = 0;
-#endif
-
-#if (GKI_NUM_TIMERS > 3)
-        gki_cb.com.OSTaskTmr3R[task_id] = 0;
-        gki_cb.com.OSTaskTmr3 [task_id] = 0;
-#endif
-
-        GKI_send_event(task_id, EVENT_MASK(GKI_SHUTDOWN_EVT));
-
-#if ( FALSE == GKI_PTHREAD_JOINABLE )
-        i = 0;
-
-        while ((gki_cb.com.OSWaitEvt[task_id] != 0) && (++i < 10))
-            usleep(100 * 1000);
-#else
-        result = pthread_join( gki_cb.os.thread_id[task_id], NULL );
-        if ( result < 0 )
-        {
-            ALOGE( "pthread_join() FAILED: result: %d", result );
-        }
-#endif
-        GKI_exit_task(task_id);
-        ALOGI( "GKI_shutdown(): task [%s] terminated\n", gki_cb.com.OSTName[task_id]);
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_task_self_cleanup
-**
-** Description      This function is used in the case when the calling thread
-**                  is exiting itself. The GKI_destroy_task function can not be
-**                  used in this case due to the pthread_join call. The function
-**                  cleans up GKI control block associated to the terminating
-**                  thread.
-**
-** Parameters:      task_id     - (input) Task id is used for sanity check to
-**                                 make sure the calling thread is in the right
-**                                 context.
-**
-** Returns          None
-**
-*******************************************************************************/
-void GKI_task_self_cleanup(UINT8 task_id)
-{
-    UINT8 my_task_id = GKI_get_taskid();
-
-    if (task_id != my_task_id)
-    {
-        ALOGE("%s: Wrong context - current task %d is not the given task id %d",\
-                      __FUNCTION__, my_task_id, task_id);
-        return;
-    }
-
-    if (gki_cb.com.OSRdyTbl[task_id] != TASK_DEAD)
-    {
-        /* paranoi settings, make sure that we do not execute any mailbox events */
-        gki_cb.com.OSWaitEvt[task_id] &= ~(TASK_MBOX_0_EVT_MASK|TASK_MBOX_1_EVT_MASK|
-                                            TASK_MBOX_2_EVT_MASK|TASK_MBOX_3_EVT_MASK);
-
-#if (GKI_NUM_TIMERS > 0)
-        gki_cb.com.OSTaskTmr0R[task_id] = 0;
-        gki_cb.com.OSTaskTmr0 [task_id] = 0;
-#endif
-
-#if (GKI_NUM_TIMERS > 1)
-        gki_cb.com.OSTaskTmr1R[task_id] = 0;
-        gki_cb.com.OSTaskTmr1 [task_id] = 0;
-#endif
-
-#if (GKI_NUM_TIMERS > 2)
-        gki_cb.com.OSTaskTmr2R[task_id] = 0;
-        gki_cb.com.OSTaskTmr2 [task_id] = 0;
-#endif
-
-#if (GKI_NUM_TIMERS > 3)
-        gki_cb.com.OSTaskTmr3R[task_id] = 0;
-        gki_cb.com.OSTaskTmr3 [task_id] = 0;
-#endif
-
-        GKI_exit_task(task_id);
-
-        /* Calling pthread_detach here to mark the thread as detached.
-           Once the thread terminates, the system can reclaim its resources
-           without waiting for another thread to join with.
-        */
-        pthread_detach(gki_cb.os.thread_id[task_id]);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         GKI_shutdown
-**
-** Description      shutdowns the GKI tasks/threads in from max task id to 0 and frees
-**                  pthread resources!
-**                  IMPORTANT: in case of join method, GKI_shutdown must be called outside
-**                  a GKI thread context!
-**
-** Returns          void
-**
-*******************************************************************************/
-
-void GKI_shutdown(void)
-{
-    UINT8 task_id;
-#if ( FALSE == GKI_PTHREAD_JOINABLE )
-    int i = 0;
-#else
-    int result;
-#endif
-
-#ifdef GKI_USE_DEFERED_ALLOC_BUF_POOLS
-    gki_dealloc_free_queue();
-#endif
-
-    /* release threads and set as TASK_DEAD. going from low to high priority fixes
-     * GKI_exception problem due to btu->hci sleep request events  */
-    for (task_id = GKI_MAX_TASKS; task_id > 0; task_id--)
-    {
-        if (gki_cb.com.OSRdyTbl[task_id - 1] != TASK_DEAD)
-        {
-            gki_cb.com.OSRdyTbl[task_id - 1] = TASK_DEAD;
-
-            /* paranoi settings, make sure that we do not execute any mailbox events */
-            gki_cb.com.OSWaitEvt[task_id-1] &= ~(TASK_MBOX_0_EVT_MASK|TASK_MBOX_1_EVT_MASK|
-                                                TASK_MBOX_2_EVT_MASK|TASK_MBOX_3_EVT_MASK);
-            GKI_send_event(task_id - 1, EVENT_MASK(GKI_SHUTDOWN_EVT));
-
-#if ( FALSE == GKI_PTHREAD_JOINABLE )
-            i = 0;
-
-            while ((gki_cb.com.OSWaitEvt[task_id - 1] != 0) && (++i < 10))
-                usleep(100 * 1000);
-#else
-            result = pthread_join( gki_cb.os.thread_id[task_id-1], NULL );
-
-            if ( result < 0 )
-            {
-                ALOGE( "pthread_join() FAILED: result: %d", result );
-            }
-#endif
-            GKI_exit_task(task_id - 1);
-        }
-    }
-
-    /* Destroy mutex and condition variable objects */
-    pthread_mutex_destroy(&gki_cb.os.GKI_mutex);
-
-    /*    pthread_mutex_destroy(&GKI_sched_mutex); */
-#if (GKI_DEBUG == TRUE)
-    pthread_mutex_destroy(&gki_cb.os.GKI_trace_mutex);
-#endif
-    /*    pthread_mutex_destroy(&thread_delay_mutex);
-     pthread_cond_destroy (&thread_delay_cond); */
-#if ( FALSE == GKI_PTHREAD_JOINABLE )
-    i = 0;
-#endif
-
-    if (timer_created) {
-        timer_delete(posix_timer);
-        timer_created = false;
-    }
-}
-
-/*****************************************************************************
-**
-** Function        gki_set_timer_scheduling
-**
-** Description     helper function to set scheduling policy and priority of btdl
-**
-** Returns         void
-**
-*******************************************************************************/
-
-static void gki_set_timer_scheduling( void )
-{
-    pid_t               main_pid = getpid();
-    struct sched_param  param;
-    int                 policy;
-
-    policy = sched_getscheduler(main_pid);
-
-    if ( policy != -1 )
-    {
-        GKI_TRACE("gki_set_timer_scheduling(()::scheduler current policy: %d", policy);
-
-        /* ensure highest priority in the system + 2 to allow space for read threads */
-        param.sched_priority = GKI_LINUX_TIMER_TICK_PRIORITY;
-
-        if ( 0!=sched_setscheduler(main_pid, GKI_LINUX_TIMER_POLICY, &param ) )
-        {
-            GKI_TRACE("sched_setscheduler() failed with error: %d", errno);
-        }
-    }
-    else
-    {
-        GKI_TRACE( "getscheduler failed: %d", errno);
-    }
-}
-
-
-/*****************************************************************************
-**
-** Function        GKI_run
-**
-** Description     Main GKI loop
-**
-** Returns
-**
-*******************************************************************************/
-
-void GKI_run(void)
-{
-    /* adjust btld scheduling scheme now */
-    gki_set_timer_scheduling();
-    GKI_TRACE( "GKI_run(): Start/Stop GKI_timer_update_registered!" );
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_stop
-**
-** Description      This function is called to stop
-**                  the tasks and timers when the system is being stopped
-**
-** Returns          void
-**
-** NOTE             This function is NOT called by the Broadcom stack and
-**                  profiles. If you want to use it in your own implementation,
-**                  put specific code here.
-**
-*******************************************************************************/
-
-void GKI_stop (void)
-{
-    UINT8 task_id;
-
-    /*  gki_queue_timer_cback(FALSE); */
-    /* TODO - add code here if needed*/
-
-    for(task_id = 0; task_id<GKI_MAX_TASKS; task_id++)
-    {
-        if(gki_cb.com.OSRdyTbl[task_id] != TASK_DEAD)
-        {
-            GKI_exit_task(task_id);
-        }
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_wait
-**
-** Description      This function is called by tasks to wait for a specific
-**                  event or set of events. The task may specify the duration
-**                  that it wants to wait for, or 0 if infinite.
-**
-** Parameters:      flag -    (input) the event or set of events to wait for
-**                  timeout - (input) the duration that the task wants to wait
-**                                    for the specific events (in system ticks)
-**
-**
-** Returns          the event mask of received events or zero if timeout
-**
-*******************************************************************************/
-UINT16 GKI_wait (UINT16 flag, UINT32 timeout)
-{
-    UINT16 evt;
-    UINT8 rtask;
-    struct timespec abstime = { 0, 0 };
-
-    int sec;
-    int nano_sec;
-
-    rtask = GKI_get_taskid();
-
-    GKI_TRACE("GKI_wait %d %x %d", (int)rtask, (int)flag, (int)timeout);
-
-    gki_cb.com.OSWaitForEvt[rtask] = flag;
-
-    /* protect OSWaitEvt[rtask] from modification from an other thread */
-    pthread_mutex_lock(&gki_cb.os.thread_evt_mutex[rtask]);
-
-    if (!(gki_cb.com.OSWaitEvt[rtask] & flag))
-    {
-        if (timeout)
-        {
-            clock_gettime(CLOCK_MONOTONIC, &abstime);
-
-            /* add timeout */
-            sec = timeout / 1000;
-            nano_sec = (timeout % 1000) * NANOSEC_PER_MILLISEC;
-            abstime.tv_nsec += nano_sec;
-            if (abstime.tv_nsec > NSEC_PER_SEC)
-            {
-                abstime.tv_sec += (abstime.tv_nsec / NSEC_PER_SEC);
-                abstime.tv_nsec = abstime.tv_nsec % NSEC_PER_SEC;
-            }
-            abstime.tv_sec += sec;
-
-            pthread_cond_timedwait(&gki_cb.os.thread_evt_cond[rtask],
-                    &gki_cb.os.thread_evt_mutex[rtask], &abstime);
-        }
-        else
-        {
-            pthread_cond_wait(&gki_cb.os.thread_evt_cond[rtask], &gki_cb.os.thread_evt_mutex[rtask]);
-        }
-
-        /* TODO: check, this is probably neither not needed depending on phtread_cond_wait() implmentation,
-         e.g. it looks like it is implemented as a counter in which case multiple cond_signal
-         should NOT be lost! */
-
-        /* we are waking up after waiting for some events, so refresh variables
-           no need to call GKI_disable() here as we know that we will have some events as we've been waking
-           up after condition pending or timeout */
-
-        if (gki_cb.com.OSTaskQFirst[rtask][0])
-            gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_0_EVT_MASK;
-        if (gki_cb.com.OSTaskQFirst[rtask][1])
-            gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_1_EVT_MASK;
-        if (gki_cb.com.OSTaskQFirst[rtask][2])
-            gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_2_EVT_MASK;
-        if (gki_cb.com.OSTaskQFirst[rtask][3])
-            gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_3_EVT_MASK;
-
-        if (gki_cb.com.OSRdyTbl[rtask] == TASK_DEAD)
-        {
-            gki_cb.com.OSWaitEvt[rtask] = 0;
-            /* unlock thread_evt_mutex as pthread_cond_wait() does auto lock when cond is met */
-            pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[rtask]);
-            return (EVENT_MASK(GKI_SHUTDOWN_EVT));
-        }
-    }
-
-    /* Clear the wait for event mask */
-    gki_cb.com.OSWaitForEvt[rtask] = 0;
-
-    /* Return only those bits which user wants... */
-    evt = gki_cb.com.OSWaitEvt[rtask] & flag;
-
-    /* Clear only those bits which user wants... */
-    gki_cb.com.OSWaitEvt[rtask] &= ~flag;
-
-    /* unlock thread_evt_mutex as pthread_cond_wait() does auto lock mutex when cond is met */
-    pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[rtask]);
-
-    GKI_TRACE("GKI_wait %d %x %d %x done", (int)rtask, (int)flag, (int)timeout, (int)evt);
-    return (evt);
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_delay
-**
-** Description      This function is called by tasks to sleep unconditionally
-**                  for a specified amount of time. The duration is in milliseconds
-**
-** Parameters:      timeout -    (input) the duration in milliseconds
-**
-** Returns          void
-**
-*******************************************************************************/
-
-void GKI_delay (UINT32 timeout)
-{
-    UINT8 rtask = GKI_get_taskid();
-    struct timespec delay;
-    int err;
-
-    GKI_TRACE("GKI_delay %d %d", (int)rtask, (int)timeout);
-
-    delay.tv_sec = timeout / 1000;
-    delay.tv_nsec = 1000 * 1000 * (timeout%1000);
-
-    /* [u]sleep can't be used because it uses SIGALRM */
-
-    do {
-        err = nanosleep(&delay, &delay);
-    } while (err < 0 && errno ==EINTR);
-
-    /* Check if task was killed while sleeping */
-
-     /* NOTE : if you do not implement task killing, you do not need this check */
-
-    if (rtask && gki_cb.com.OSRdyTbl[rtask] == TASK_DEAD)
-    {
-    }
-
-    GKI_TRACE("GKI_delay %d %d done", (int)rtask, (int)timeout);
-
-    return;
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_send_event
-**
-** Description      This function is called by tasks to send events to other
-**                  tasks. Tasks can also send events to themselves.
-**
-** Parameters:      task_id -  (input) The id of the task to which the event has to
-**                  be sent
-**                  event   -  (input) The event that has to be sent
-**
-**
-** Returns          GKI_SUCCESS if all OK, else GKI_FAILURE
-**
-*******************************************************************************/
-
-UINT8 GKI_send_event (UINT8 task_id, UINT16 event)
-{
-    GKI_TRACE("GKI_send_event %d %x", task_id, event);
-
-    if (task_id < GKI_MAX_TASKS)
-    {
-        /* protect OSWaitEvt[task_id] from manipulation in GKI_wait() */
-        pthread_mutex_lock(&gki_cb.os.thread_evt_mutex[task_id]);
-
-        /* Set the event bit */
-        gki_cb.com.OSWaitEvt[task_id] |= event;
-
-        pthread_cond_signal(&gki_cb.os.thread_evt_cond[task_id]);
-
-        pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[task_id]);
-
-        GKI_TRACE("GKI_send_event %d %x done", task_id, event);
-        return ( GKI_SUCCESS );
-    }
-    GKI_TRACE("############## GKI_send_event FAILED!! ##################");
-    return (GKI_FAILURE);
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_get_taskid
-**
-** Description      This function gets the currently running task ID.
-**
-** Returns          task ID
-**
-** NOTE             The Broadcom upper stack and profiles may run as a single task.
-**                  If you only have one GKI task, then you can hard-code this
-**                  function to return a '1'. Otherwise, you should have some
-**                  OS-specific method to determine the current task.
-**
-*******************************************************************************/
-UINT8 GKI_get_taskid (void)
-{
-    int i;
-
-    pthread_t thread_id = pthread_self( );
-
-    GKI_TRACE("GKI_get_taskid %x", (int)thread_id);
-
-    for (i = 0; i < GKI_MAX_TASKS; i++) {
-        if (gki_cb.os.thread_id[i] == thread_id) {
-            //GKI_TRACE("GKI_get_taskid %x %d done", thread_id, i);
-            return(i);
-        }
-    }
-
-    GKI_TRACE("GKI_get_taskid: task id = -1");
-
-    return(-1);
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_map_taskname
-**
-** Description      This function gets the task name of the taskid passed as arg.
-**                  If GKI_MAX_TASKS is passed as arg the currently running task
-**                  name is returned
-**
-** Parameters:      task_id -  (input) The id of the task whose name is being
-**                  sought. GKI_MAX_TASKS is passed to get the name of the
-**                  currently running task.
-**
-** Returns          pointer to task name
-**
-** NOTE             this function needs no customization
-**
-*******************************************************************************/
-
-INT8 *GKI_map_taskname (UINT8 task_id)
-{
-    GKI_TRACE("GKI_map_taskname %d", task_id);
-
-    if (task_id < GKI_MAX_TASKS)
-    {
-        GKI_TRACE("GKI_map_taskname %d %s done", task_id, gki_cb.com.OSTName[task_id]);
-         return (gki_cb.com.OSTName[task_id]);
-    }
-    else if (task_id == GKI_MAX_TASKS )
-    {
-        return (gki_cb.com.OSTName[GKI_get_taskid()]);
-    }
-    else
-    {
-        return (INT8*)"BAD";
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_enable
-**
-** Description      This function enables interrupts.
-**
-** Returns          void
-**
-*******************************************************************************/
-void GKI_enable (void)
-{
-    pthread_mutex_unlock(&gki_cb.os.GKI_mutex);
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_disable
-**
-** Description      This function disables interrupts.
-**
-** Returns          void
-**
-*******************************************************************************/
-
-void GKI_disable (void)
-{
-    pthread_mutex_lock(&gki_cb.os.GKI_mutex);
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_exception
-**
-** Description      This function throws an exception.
-**                  This is normally only called for a nonrecoverable error.
-**
-** Parameters:      code    -  (input) The code for the error
-**                  msg     -  (input) The message that has to be logged
-**
-** Returns          void
-**
-*******************************************************************************/
-
-void GKI_exception (UINT16 code, char *msg)
-{
-    UINT8 task_id;
-
-    ALOGE( "GKI_exception(): Task State Table");
-
-    for(task_id = 0; task_id < GKI_MAX_TASKS; task_id++)
-    {
-        ALOGE( "TASK ID [%d] task name [%s] state [%d]",
-                         task_id,
-                         gki_cb.com.OSTName[task_id],
-                         gki_cb.com.OSRdyTbl[task_id]);
-    }
-
-    ALOGE("GKI_exception %d %s", code, msg);
-    ALOGE( "********************************************************************");
-    ALOGE( "* GKI_exception(): %d %s", code, msg);
-    ALOGE( "********************************************************************");
-
-#if 0//(GKI_DEBUG == TRUE)
-    GKI_disable();
-
-    if (gki_cb.com.ExceptionCnt < GKI_MAX_EXCEPTION)
-    {
-        EXCEPTION_T *pExp;
-
-        pExp =  &gki_cb.com.Exception[gki_cb.com.ExceptionCnt++];
-        pExp->type = code;
-        pExp->taskid = GKI_get_taskid();
-        strncpy((char *)pExp->msg, msg, GKI_MAX_EXCEPTION_MSGLEN - 1);
-    }
-
-    GKI_enable();
-#endif
-
-    GKI_TRACE("GKI_exception %d %s done", code, msg);
-    return;
-}
-
-/*******************************************************************************
-**
-** Function         GKI_os_malloc
-**
-** Description      This function allocates memory
-**
-** Parameters:      size -  (input) The size of the memory that has to be
-**                  allocated
-**
-** Returns          the address of the memory allocated, or NULL if failed
-**
-** NOTE             This function is called by the Broadcom stack when
-**                  dynamic memory allocation is used. (see dyn_mem.h)
-**
-*******************************************************************************/
-void *GKI_os_malloc (UINT32 size)
-{
-    return malloc(size);
-}
-
-/*******************************************************************************
-**
-** Function         GKI_os_free
-**
-** Description      This function frees memory
-**
-** Parameters:      size -  (input) The address of the memory that has to be
-**                  freed
-**
-** Returns          void
-**
-** NOTE             This function is NOT called by the Broadcom stack and
-**                  profiles. It is only called from within GKI if dynamic
-**
-*******************************************************************************/
-void GKI_os_free (void *p_mem)
-{
-    free(p_mem);
-}
-
-
-/*******************************************************************************
-**
-** Function         GKI_exit_task
-**
-** Description      This function is called to stop a GKI task.
-**
-** Parameters:      task_id  - (input) the id of the task that has to be stopped
-**
-** Returns          void
-**
-** NOTE             This function is NOT called by the Broadcom stack and
-**                  profiles. If you want to use it in your own implementation,
-**                  put specific code here to kill a task.
-**
-*******************************************************************************/
-void GKI_exit_task (UINT8 task_id)
-{
-    GKI_disable();
-    gki_cb.com.OSRdyTbl[task_id] = TASK_DEAD;
-
-    /* Destroy mutex and condition variable objects */
-    pthread_mutex_destroy(&gki_cb.os.thread_evt_mutex[task_id]);
-    pthread_cond_destroy (&gki_cb.os.thread_evt_cond[task_id]);
-    pthread_mutex_destroy(&gki_cb.os.thread_timeout_mutex[task_id]);
-    pthread_cond_destroy (&gki_cb.os.thread_timeout_cond[task_id]);
-
-    GKI_enable();
-
-    ALOGI("GKI_exit_task %d done", task_id);
-    return;
+void GKI_disable(void) {
+  pthread_mutex_lock(&gki_cb.lock);
 }
diff --git a/hci/Android.mk b/hci/Android.mk
index f93e658..7c69464 100644
--- a/hci/Android.mk
+++ b/hci/Android.mk
@@ -2,42 +2,78 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_CFLAGS += $(bdroid_CFLAGS)
-
 LOCAL_SRC_FILES := \
-	src/bt_hci_bdroid.c \
-	src/btsnoop.c \
-	src/btsnoop_net.c \
-	src/lpm.c \
-	src/utils.c \
-	src/vendor.c
-
-LOCAL_CFLAGS := -Wno-unused-parameter
+    src/btsnoop.c \
+    src/btsnoop_net.c \
+    src/buffer_allocator.c \
+    src/hci_audio.c \
+    src/hci_hal.c \
+    src/hci_hal_h4.c \
+    src/hci_hal_mct.c \
+    src/hci_inject.c \
+    src/hci_layer.c \
+    src/hci_packet_factory.c \
+    src/hci_packet_parser.c \
+    src/low_power_manager.c \
+    src/packet_fragmenter.c \
+    src/vendor.c
 
 ifeq ($(BLUETOOTH_HCI_USE_MCT),true)
-
 LOCAL_CFLAGS += -DHCI_USE_MCT
-
-LOCAL_SRC_FILES += \
-	src/hci_mct.c \
-	src/userial_mct.c
-
-else
-LOCAL_SRC_FILES += \
-	src/hci_h4.c \
-	src/userial.c
 endif
 
-LOCAL_CFLAGS += -std=c99
+LOCAL_CFLAGS += -std=c99 $(bdroid_CFLAGS)
 
 LOCAL_C_INCLUDES += \
-	$(LOCAL_PATH)/include \
-	$(LOCAL_PATH)/../osi/include \
-	$(LOCAL_PATH)/../utils/include \
-        $(bdroid_C_INCLUDES)
+    $(LOCAL_PATH)/include \
+    $(LOCAL_PATH)/.. \
+    $(LOCAL_PATH)/../include \
+    $(LOCAL_PATH)/../btcore/include \
+    $(LOCAL_PATH)/../gki/common \
+    $(LOCAL_PATH)/../gki/ulinux \
+    $(LOCAL_PATH)/../osi/include \
+    $(LOCAL_PATH)/../stack/include \
+    $(LOCAL_PATH)/../utils/include \
+    $(bdroid_C_INCLUDES)
 
 LOCAL_MODULE := libbt-hci
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE_CLASS := STATIC_LIBRARIES
 
 include $(BUILD_STATIC_LIBRARY)
+
+#####################################################
+include $(CLEAR_VARS)
+
+LOCAL_C_INCLUDES := \
+    $(LOCAL_PATH)/include \
+    $(LOCAL_PATH)/.. \
+    $(LOCAL_PATH)/../include \
+    $(LOCAL_PATH)/../btcore/include \
+    $(LOCAL_PATH)/../gki/common \
+    $(LOCAL_PATH)/../gki/ulinux \
+    $(LOCAL_PATH)/../osi/include \
+    $(LOCAL_PATH)/../osi/test \
+    $(LOCAL_PATH)/../stack/include \
+    $(LOCAL_PATH)/../utils/include \
+    $(bdroid_C_INCLUDES)
+
+
+LOCAL_SRC_FILES := \
+    ../osi/test/AllocationTestHarness.cpp \
+    ../osi/test/AlarmTestHarness.cpp \
+    ./test/hci_hal_h4_test.cpp \
+    ./test/hci_hal_mct_test.cpp \
+    ./test/hci_layer_test.cpp \
+    ./test/low_power_manager_test.cpp \
+    ./test/packet_fragmenter_test.cpp \
+    $(bdroid_C_INCLUDES)
+
+
+LOCAL_CFLAGS := -Wall -Werror $(bdroid_CFLAGS)
+LOCAL_MODULE := net_test_hci
+LOCAL_MODULE_TAGS := tests
+LOCAL_SHARED_LIBRARIES := liblog libdl
+LOCAL_STATIC_LIBRARIES := libbt-hci libosi libcutils libbtcore
+
+include $(BUILD_NATIVE_TEST)
diff --git a/hci/include/bt_hci_bdroid.h b/hci/include/bt_hci_bdroid.h
index 220946b..2a0577b 100644
--- a/hci/include/bt_hci_bdroid.h
+++ b/hci/include/bt_hci_bdroid.h
@@ -29,8 +29,6 @@
 
 #pragma once
 
-#include "bt_hci_lib.h"
-
 #ifdef HAS_BDROID_BUILDCFG
 #include "bdroid_buildcfg.h"
 #endif
@@ -64,8 +62,6 @@
   HC_EVENT_LPM_IDLE_TIMEOUT,
 } bthc_event_t;
 
-#define MSG_CTRL_TO_HC_CMD             0x0100 /* evt mask used by HC_EVENT_TX_CMD */
-
 /* Message event mask across Host/Controller lib and stack */
 #define MSG_EVT_MASK                    0xFF00 /* eq. BT_EVT_MASK */
 #define MSG_SUB_EVT_MASK                0x00FF /* eq. BT_SUB_EVT_MASK */
@@ -85,13 +81,6 @@
 /* Local Bluetooth Controller ID for BR/EDR */
 #define LOCAL_BR_EDR_CONTROLLER_ID      0
 
-/* Definitions of audio codec type
- *      inherited from AG callout function "codec" parameter
- */
-#define SCO_CODEC_NONE      0x0000 /* BTA_AG_CODEC_NONE/BTM_SCO_CODEC_NONE */
-#define SCO_CODEC_CVSD      0x0001 /* BTA_AG_CODEC_CVSD/BTM_SCO_CODEC_CVSD */
-#define SCO_CODEC_MSBC      0x0002 /* BTA_AG_CODEC_MSBC/BTM_SCO_CODEC_MSBC */
-
 /******************************************************************************
 **  Type definitions and return values
 ******************************************************************************/
@@ -122,8 +111,6 @@
 **  Extern variables and functions
 ******************************************************************************/
 
-extern bt_hc_callbacks_t *bt_hc_cbacks;
-
 /******************************************************************************
 **  Functions
 ******************************************************************************/
diff --git a/hci/include/bt_hci_lib.h b/hci/include/bt_hci_lib.h
deleted file mode 100644
index c9f8cd7..0000000
--- a/hci/include/bt_hci_lib.h
+++ /dev/null
@@ -1,208 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-#ifndef BT_HCI_LIB_H
-#define BT_HCI_LIB_H
-
-#include <stdint.h>
-#include <stdbool.h>
-#include <sys/cdefs.h>
-#include <sys/types.h>
-
-/** Struct types */
-
-
-/** Typedefs and defines */
-
-/* Generic purpose transac returned upon request complete */
-typedef void* TRANSAC;
-
-/** Bluetooth Power Control States */
-typedef enum {
-    BT_HC_CHIP_PWR_OFF,
-    BT_HC_CHIP_PWR_ON,
-}  bt_hc_chip_power_state_t;
-
-/** Bluetooth Low Power Mode */
-typedef enum {
-    BT_HC_LPM_DISABLE,
-    BT_HC_LPM_ENABLE,
-    BT_HC_LPM_WAKE_ASSERT,
-    BT_HC_LPM_WAKE_DEASSERT,
-} bt_hc_low_power_event_t;
-
-/** Receive flow control */
-typedef enum {
-    BT_RXFLOW_OFF, /* add transport device fd to select set */
-    BT_RXFLOW_ON,  /* remove transport device to from select set */
-} bt_rx_flow_state_t;
-
-/** HCI logging control */
-typedef enum {
-    BT_HC_LOGGING_OFF,
-    BT_HC_LOGGING_ON,
-} bt_hc_logging_state_t;
-
-/* commands to be used in LSB with MSG_CTRL_TO_HC_CMD */
-typedef enum {
-    BT_HC_AUDIO_STATE = 0,
-    BT_HC_CMD_MAX
-} bt_hc_tx_cmd_t;
-/** Result of write request */
-typedef enum {
-    BT_HC_TX_SUCCESS,  /* a buffer is fully processed and can be released */
-    BT_HC_TX_FAIL,     /* transmit fail */
-    BT_HC_TX_FRAGMENT, /* send split ACL pkt back to stack to reprocess */
-} bt_hc_transmit_result_t;
-
-/** Result of preload initialization */
-typedef enum {
-    BT_HC_PRELOAD_SUCCESS,
-    BT_HC_PRELOAD_FAIL,
-} bt_hc_preload_result_t;
-
-/** Result of postload initialization */
-typedef enum {
-    BT_HC_POSTLOAD_SUCCESS,
-    BT_HC_POSTLOAD_FAIL,
-} bt_hc_postload_result_t;
-
-/** Result of low power enable/disable request */
-typedef enum {
-    BT_HC_LPM_DISABLED,
-    BT_HC_LPM_ENABLED,
-} bt_hc_lpm_request_result_t;
-
-/** Host/Controller Library Return Status */
-typedef enum {
-    BT_HC_STATUS_SUCCESS,
-    BT_HC_STATUS_FAIL,
-    BT_HC_STATUS_NOT_READY,
-    BT_HC_STATUS_NOMEM,
-    BT_HC_STATUS_BUSY,
-    BT_HC_STATUS_CORRUPTED_BUFFER
-} bt_hc_status_t;
-
-
-/* Section comment */
-
-/*
- * Bluetooth Host/Controller callback structure.
- */
-
-/* called upon bt host wake signal */
-typedef void (*hostwake_ind_cb)(bt_hc_low_power_event_t event);
-
-/* preload initialization callback */
-typedef void (*preload_result_cb)(TRANSAC transac, bt_hc_preload_result_t result);
-
-/* postload initialization callback */
-typedef void (*postload_result_cb)(TRANSAC transac, bt_hc_postload_result_t result);
-
-/* lpm enable/disable callback */
-typedef void (*lpm_result_cb)(bt_hc_lpm_request_result_t result);
-
-/* datapath buffer allocation callback (callout) */
-typedef char* (*alloc_mem_cb)(int size);
-
-/* datapath buffer deallocation callback (callout) */
-typedef void (*dealloc_mem_cb)(TRANSAC transac);
-
-/* transmit result callback */
-typedef int (*tx_result_cb)(TRANSAC transac, char *p_buf, bt_hc_transmit_result_t result);
-
-/* a previously setup buffer is read and available for processing
-   buffer is deallocated in stack when processed */
-typedef int (*data_ind_cb)(TRANSAC transac, char *p_buf, int len);
-
-typedef struct {
-    /** set to sizeof(bt_hc_callbacks_t) */
-    size_t         size;
-
-    /* notifies caller result of preload request */
-    preload_result_cb  preload_cb;
-
-    /* notifies caller result of postload request */
-    postload_result_cb  postload_cb;
-
-    /* notifies caller result of lpm enable/disable */
-    lpm_result_cb  lpm_cb;
-
-    /* notifies hardware on host wake state */
-    hostwake_ind_cb       hostwake_ind;
-
-    /* buffer allocation request */
-    alloc_mem_cb   alloc;
-
-    /* buffer deallocation request */
-    dealloc_mem_cb dealloc;
-
-    /* notifies stack data is available */
-    data_ind_cb data_ind;
-
-    /* notifies caller when a buffer is transmitted (or failed) */
-    tx_result_cb  tx_result;
-} bt_hc_callbacks_t;
-
-/*
- * Bluetooth Host/Controller Interface
- */
-typedef struct {
-    /** Set to sizeof(bt_hc_interface_t) */
-    size_t          size;
-
-    /**
-     * Opens the interface and provides the callback routines
-     * to the implemenation of this interface.
-     */
-    int   (*init)(const bt_hc_callbacks_t* p_cb, unsigned char *local_bdaddr);
-
-    /** Chip power control */
-    void (*set_power)(bt_hc_chip_power_state_t state);
-
-    /** Set low power mode wake */
-    int   (*lpm)(bt_hc_low_power_event_t event);
-
-    /** Called prior to stack initialization */
-    void (*preload)(TRANSAC transac);
-
-    /** Called post stack initialization */
-    void (*postload)(TRANSAC transac);
-
-    /** Transmit buffer */
-    int (*transmit_buf)(TRANSAC transac, char *p_buf, int len);
-
-    /** Controls HCI logging on/off */
-    int (*logging)(bt_hc_logging_state_t state, char *p_path, bool save_existing);
-
-    /** Closes the interface */
-    void  (*cleanup)( void );
-
-    /** sends commands to hc layer (e.g. SCO state) */
-    int   (*tx_cmd)(TRANSAC transac, char *p_buf, int len);
-} bt_hc_interface_t;
-
-
-/*
- * External shared lib functions
- */
-
-extern const bt_hc_interface_t* bt_hc_get_interface(void);
-
-#endif /* BT_HCI_LIB_H */
-
diff --git a/hci/include/btsnoop.h b/hci/include/btsnoop.h
index 83c8107..14fbf72 100644
--- a/hci/include/btsnoop.h
+++ b/hci/include/btsnoop.h
@@ -1,10 +1,39 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
 #pragma once
 
 #include <stdbool.h>
 
-#include "bt_hci_bdroid.h"
+#include "bt_types.h"
 
-void btsnoop_open(const char *p_path, const bool save_existing);
-void btsnoop_close(void);
+static const char BTSNOOP_MODULE[] = "btsnoop_module";
 
-void btsnoop_capture(const HC_BT_HDR *p_buf, bool is_rcvd);
+typedef struct btsnoop_t {
+  // Inform btsnoop whether the API desires to log. If |value| is true.
+  // logging will be enabled. Otherwise it defers to the value from the
+  // config file.
+  void (*set_api_wants_to_log)(bool value);
+
+  // Capture |packet| and dump it to the btsnoop logs. If |is_received| is
+  // true, the packet is marked as incoming. Otherwise, the packet is marked
+  // as outgoing.
+  void (*capture)(const BT_HDR *packet, bool is_received);
+} btsnoop_t;
+
+const btsnoop_t *btsnoop_get_interface(void);
diff --git a/test/suite/support/property.h b/hci/include/buffer_allocator.h
similarity index 61%
copy from test/suite/support/property.h
copy to hci/include/buffer_allocator.h
index a8b77c7..b44b0f0 100644
--- a/test/suite/support/property.h
+++ b/hci/include/buffer_allocator.h
@@ -18,15 +18,6 @@
 
 #pragma once
 
-#include "base.h"
+#include "allocator.h"
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
-
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+const allocator_t *buffer_allocator_get_interface();
diff --git a/hci/include/hci.h b/hci/include/hci.h
deleted file mode 100644
index 0bfec2b..0000000
--- a/hci/include/hci.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Filename:      hci.h
- *
- *  Description:   Contains definitions used for HCI transport controls
- *
- ******************************************************************************/
-
-#ifndef HCI_H
-#define HCI_H
-
-/******************************************************************************
-**  Constants & Macros
-******************************************************************************/
-
-/******************************************************************************
-**  Type definitions
-******************************************************************************/
-
-/** Prototypes for HCI Service interface functions **/
-
-/* Initialize transport's control block */
-typedef void (*tHCI_INIT)(void);
-
-/* Do transport's control block clean-up */
-typedef void (*tHCI_CLEANUP)(void);
-
-/* Send HCI command/data to the transport */
-typedef void (*tHCI_SEND)(HC_BT_HDR *p_msg);
-
-/* Handler for HCI upstream path */
-typedef uint16_t (*tHCI_RCV)(void);
-
-/* Callback function for the returned event of internally issued command */
-typedef void (*tINT_CMD_CBACK)(void *p_mem);
-
-/* Handler for sending HCI command from the local module */
-typedef uint8_t (*tHCI_SEND_INT)(uint16_t opcode, HC_BT_HDR *p_buf, \
-                                  tINT_CMD_CBACK p_cback);
-
-/* Handler for getting acl data length */
-typedef void (*tHCI_ACL_DATA_LEN_HDLR)(void);
-
-/******************************************************************************
-**  Extern variables and functions
-******************************************************************************/
-
-typedef struct {
-    tHCI_INIT init;
-    tHCI_CLEANUP cleanup;
-    tHCI_SEND send;
-    tHCI_SEND_INT send_int_cmd;
-    tHCI_ACL_DATA_LEN_HDLR get_acl_max_len;
-#ifdef HCI_USE_MCT
-    tHCI_RCV evt_rcv;
-    tHCI_RCV acl_rcv;
-#else
-    tHCI_RCV rcv;
-#endif
-} tHCI_IF;
-
-/******************************************************************************
-**  Functions
-******************************************************************************/
-
-
-#endif /* HCI_H */
-
diff --git a/hci/include/hci_audio.h b/hci/include/hci_audio.h
new file mode 100644
index 0000000..6e8063a
--- /dev/null
+++ b/hci/include/hci_audio.h
@@ -0,0 +1,38 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2015 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+// Audio state definitions.
+typedef enum {
+    SCO_STATE_OFF = 0,      // Audio is off.
+    SCO_STATE_OFF_TRANSFER, // Closed pending final transfer of audio.
+    SCO_STATE_ON,           // Audio is on.
+    SCO_STATE_SETUP,        // Open pending completion of audio setup.
+} sco_state_t;
+
+// Codec type definitions.
+typedef enum {
+    SCO_CODEC_NONE = 0x0000,
+    SCO_CODEC_CVSD = 0x0001,
+    SCO_CODEC_MSBC = 0x0002,
+} sco_codec_t;
+
+// Set the audio state on the controller for SCO (PCM, WBS, ...) using the
+// vendor library.
+void set_audio_state(uint16_t handle, sco_codec_t codec, sco_state_t state);
diff --git a/hci/include/hci_hal.h b/hci/include/hci_hal.h
new file mode 100644
index 0000000..b0b3c67
--- /dev/null
+++ b/hci/include/hci_hal.h
@@ -0,0 +1,88 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "thread.h"
+#include "vendor.h"
+
+typedef enum {
+  DATA_TYPE_COMMAND = 1,
+  DATA_TYPE_ACL     = 2,
+  DATA_TYPE_SCO     = 3,
+  DATA_TYPE_EVENT   = 4
+} serial_data_type_t;
+
+typedef void (*data_ready_cb)(serial_data_type_t type);
+
+typedef struct {
+  // Called when the HAL detects inbound data.
+  // Data |type| may be ACL, SCO, or EVENT.
+  // Executes in the context of the thread supplied to |init|.
+  data_ready_cb data_ready;
+
+  /*
+  // Called when the HAL detects inbound astronauts named Dave.
+  // HAL will deny all requests to open the pod bay doors after this.
+  dave_ready_cb dave_ready;
+  */
+} hci_hal_callbacks_t;
+
+typedef struct hci_hal_t {
+  // Initialize the HAL, with |upper_callbacks| and |upper_thread| to run in the context of.
+  bool (*init)(const hci_hal_callbacks_t *upper_callbacks, thread_t *upper_thread);
+
+  // Connect to the underlying hardware, and let data start flowing.
+  bool (*open)(void);
+  // Disconnect from the underlying hardware, and close the HAL.
+  // "Daisy, Daisy..."
+  void (*close)(void);
+
+  // Retrieve up to |max_size| bytes for ACL, SCO, or EVENT data packets into
+  // |buffer|, blocking until max_size bytes read if |block| is true.
+  // Only guaranteed to be correct in the context of a data_ready callback
+  // of the corresponding type.
+  size_t (*read_data)(serial_data_type_t type, uint8_t *buffer, size_t max_size, bool block);
+  // The upper layer must call this to notify the HAL that it has finished
+  // reading a packet of the specified |type|. Underlying implementations that
+  // use shared channels for multiple data types depend on this to know when
+  // to reinterpret the data stream.
+  void (*packet_finished)(serial_data_type_t type);
+  // Transmit COMMAND, ACL, or SCO data packets.
+  // |data| may not be NULL. |length| must be greater than zero.
+  //
+  // IMPORTANT NOTE:
+  // Depending on the underlying implementation, the byte right
+  // before the beginning of |data| may be borrowed during this call
+  // and then restored to its original value.
+  // This is safe in the bluetooth context, because there is always a buffer
+  // header that prefixes data you're sending.
+  uint16_t (*transmit_data)(serial_data_type_t type, uint8_t *data, uint16_t length);
+} hci_hal_t;
+
+// Gets the correct hal implementation, as compiled for.
+const hci_hal_t *hci_hal_get_interface(void);
+
+const hci_hal_t *hci_hal_h4_get_interface(void);
+const hci_hal_t *hci_hal_h4_get_test_interface(vendor_t *vendor_interface);
+
+const hci_hal_t *hci_hal_mct_get_interface(void);
+const hci_hal_t *hci_hal_mct_get_test_interface(vendor_t *vendor_interface);
diff --git a/test/suite/support/property.h b/hci/include/hci_inject.h
similarity index 62%
copy from test/suite/support/property.h
copy to hci/include/hci_inject.h
index a8b77c7..45d2304 100644
--- a/test/suite/support/property.h
+++ b/hci/include/hci_inject.h
@@ -18,15 +18,17 @@
 
 #pragma once
 
-#include "base.h"
+#include <stdbool.h>
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+typedef struct hci_t hci_t;
 
-const char *property_extract_name(const bt_property_t *property);
+typedef struct hci_inject_t {
+  // Starts the HCI injection module. Returns true on success, false on failure.
+  // Once started, this module must be shut down with |close|.
+  bool (*open)(const hci_t *hci_interface);
 
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
+  // Shuts down the HCI injection module.
+  void (*close)(void);
+} hci_inject_t;
 
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+const hci_inject_t *hci_inject_get_interface();
diff --git a/test/suite/support/property.h b/hci/include/hci_internals.h
similarity index 61%
copy from test/suite/support/property.h
copy to hci/include/hci_internals.h
index a8b77c7..6b9fb01 100644
--- a/test/suite/support/property.h
+++ b/hci/include/hci_internals.h
@@ -18,15 +18,11 @@
 
 #pragma once
 
-#include "base.h"
-
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
-
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+// 2 bytes for opcode, 1 byte for parameter length (Volume 2, Part E, 5.4.1)
+#define HCI_COMMAND_PREAMBLE_SIZE 3
+// 2 bytes for handle, 2 bytes for data length (Volume 2, Part E, 5.4.2)
+#define HCI_ACL_PREAMBLE_SIZE 4
+// 2 bytes for handle, 1 byte for data length (Volume 2, Part E, 5.4.3)
+#define HCI_SCO_PREAMBLE_SIZE 3
+// 1 byte for event code, 1 byte for parameter length (Volume 2, Part E, 5.4.4)
+#define HCI_EVENT_PREAMBLE_SIZE 2
diff --git a/hci/include/hci_layer.h b/hci/include/hci_layer.h
new file mode 100644
index 0000000..bdc4681
--- /dev/null
+++ b/hci/include/hci_layer.h
@@ -0,0 +1,112 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+
+#include "allocator.h"
+#include "bt_types.h"
+#include "data_dispatcher.h"
+#include "fixed_queue.h"
+#include "future.h"
+#include "osi.h"
+
+static const char HCI_MODULE[] = "hci_module";
+
+///// LEGACY DEFINITIONS /////
+
+/* Message event mask across Host/Controller lib and stack */
+#define MSG_EVT_MASK                    0xFF00 /* eq. BT_EVT_MASK */
+#define MSG_SUB_EVT_MASK                0x00FF /* eq. BT_SUB_EVT_MASK */
+
+/* Message event ID passed from Host/Controller lib to stack */
+#define MSG_HC_TO_STACK_HCI_ERR        0x1300 /* eq. BT_EVT_TO_BTU_HCIT_ERR */
+#define MSG_HC_TO_STACK_HCI_ACL        0x1100 /* eq. BT_EVT_TO_BTU_HCI_ACL */
+#define MSG_HC_TO_STACK_HCI_SCO        0x1200 /* eq. BT_EVT_TO_BTU_HCI_SCO */
+#define MSG_HC_TO_STACK_HCI_EVT        0x1000 /* eq. BT_EVT_TO_BTU_HCI_EVT */
+#define MSG_HC_TO_STACK_L2C_SEG_XMIT   0x1900 /* eq. BT_EVT_TO_BTU_L2C_SEG_XMIT */
+
+/* Message event ID passed from stack to vendor lib */
+#define MSG_STACK_TO_HC_HCI_ACL        0x2100 /* eq. BT_EVT_TO_LM_HCI_ACL */
+#define MSG_STACK_TO_HC_HCI_SCO        0x2200 /* eq. BT_EVT_TO_LM_HCI_SCO */
+#define MSG_STACK_TO_HC_HCI_CMD        0x2000 /* eq. BT_EVT_TO_LM_HCI_CMD */
+
+/* Local Bluetooth Controller ID for BR/EDR */
+#define LOCAL_BR_EDR_CONTROLLER_ID      0
+
+///// END LEGACY DEFINITIONS /////
+
+typedef struct hci_hal_t hci_hal_t;
+typedef struct btsnoop_t btsnoop_t;
+typedef struct controller_t controller_t;
+typedef struct hci_inject_t hci_inject_t;
+typedef struct packet_fragmenter_t packet_fragmenter_t;
+typedef struct vendor_t vendor_t;
+typedef struct low_power_manager_t low_power_manager_t;
+
+typedef unsigned char * bdaddr_t;
+typedef uint16_t command_opcode_t;
+
+typedef enum {
+  LPM_DISABLE,
+  LPM_ENABLE,
+  LPM_WAKE_ASSERT,
+  LPM_WAKE_DEASSERT
+} low_power_command_t;
+
+typedef void (*command_complete_cb)(BT_HDR *response, void *context);
+typedef void (*command_status_cb)(uint8_t status, BT_HDR *command, void *context);
+
+typedef struct hci_t {
+  // Send a low power command, if supported and the low power manager is enabled.
+  void (*send_low_power_command)(low_power_command_t command);
+
+  // Do the postload sequence (call after the rest of the BT stack initializes).
+  void (*do_postload)(void);
+
+  // Register with this data dispatcher to receive events flowing upward out of the HCI layer
+  data_dispatcher_t *event_dispatcher;
+
+  // Set the queue to receive ACL data in
+  void (*set_data_queue)(fixed_queue_t *queue);
+
+  // Send a command through the HCI layer
+  void (*transmit_command)(
+      BT_HDR *command,
+      command_complete_cb complete_callback,
+      command_status_cb status_cb,
+      void *context
+  );
+
+  future_t *(*transmit_command_futured)(BT_HDR *command);
+
+  // Send some data downward through the HCI layer
+  void (*transmit_downward)(data_dispatcher_type_t type, void *data);
+} hci_t;
+
+const hci_t *hci_layer_get_interface();
+
+const hci_t *hci_layer_get_test_interface(
+    const allocator_t *buffer_allocator_interface,
+    const hci_hal_t *hal_interface,
+    const btsnoop_t *btsnoop_interface,
+    const hci_inject_t *hci_inject_interface,
+    const packet_fragmenter_t *packet_fragmenter_interface,
+    const vendor_t *vendor_interface,
+    const low_power_manager_t *low_power_manager_interface);
diff --git a/hci/include/hci_packet_factory.h b/hci/include/hci_packet_factory.h
new file mode 100644
index 0000000..b5e207c
--- /dev/null
+++ b/hci/include/hci_packet_factory.h
@@ -0,0 +1,42 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include "bt_types.h"
+#include "event_mask.h"
+
+typedef struct {
+  BT_HDR *(*make_reset)(void);
+  BT_HDR *(*make_read_buffer_size)(void);
+  BT_HDR *(*make_host_buffer_size)(uint16_t acl_size, uint8_t sco_size, uint16_t acl_count, uint16_t sco_count);
+  BT_HDR *(*make_read_local_version_info)(void);
+  BT_HDR *(*make_read_bd_addr)(void);
+  BT_HDR *(*make_read_local_supported_commands)(void);
+  BT_HDR *(*make_read_local_extended_features)(uint8_t page_number);
+  BT_HDR *(*make_write_simple_pairing_mode)(uint8_t mode);
+  BT_HDR *(*make_set_event_mask)(const bt_event_mask_t *event_mask);
+  BT_HDR *(*make_ble_write_host_support)(uint8_t supported_host, uint8_t simultaneous_host);
+  BT_HDR *(*make_ble_read_white_list_size)(void);
+  BT_HDR *(*make_ble_read_buffer_size)(void);
+  BT_HDR *(*make_ble_read_supported_states)(void);
+  BT_HDR *(*make_ble_read_local_supported_features)(void);
+  BT_HDR *(*make_ble_set_event_mask)(const bt_event_mask_t *event_mask);
+} hci_packet_factory_t;
+
+const hci_packet_factory_t *hci_packet_factory_get_interface();
diff --git a/hci/include/hci_packet_parser.h b/hci/include/hci_packet_parser.h
new file mode 100644
index 0000000..219a424
--- /dev/null
+++ b/hci/include/hci_packet_parser.h
@@ -0,0 +1,90 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdint.h>
+
+#include "allocator.h"
+#include "bdaddr.h"
+#include "bt_types.h"
+#include "device_features.h"
+#include "features.h"
+#include "version.h"
+
+typedef struct {
+  void (*parse_generic_command_complete)(BT_HDR *response);
+
+  void (*parse_read_buffer_size_response)(
+    BT_HDR *response,
+    uint16_t *data_size_ptr,
+    uint16_t *acl_buffer_count_ptr
+  );
+
+  void (*parse_read_local_version_info_response)(
+    BT_HDR *response,
+    bt_version_t *bt_version_ptr
+  );
+
+  void (*parse_read_bd_addr_response)(
+    BT_HDR *response,
+    bt_bdaddr_t *address_ptr
+  );
+
+  void (*parse_read_local_supported_commands_response)(
+    BT_HDR *response,
+    uint8_t *supported_commands_ptr,
+    size_t supported_commands_length
+  );
+
+  void (*parse_read_local_extended_features_response)(
+    BT_HDR *response,
+    uint8_t *page_number_ptr,
+    uint8_t *max_page_number_ptr,
+    bt_device_features_t *feature_pages,
+    size_t feature_pages_count
+  );
+
+  void (*parse_ble_read_white_list_size_response)(
+    BT_HDR *response,
+    uint8_t *white_list_size_ptr
+  );
+
+  void (*parse_ble_read_buffer_size_response)(
+    BT_HDR *response,
+    uint16_t *data_size_ptr,
+    uint8_t *acl_buffer_count_ptr
+  );
+
+  void (*parse_ble_read_supported_states_response)(
+    BT_HDR *response,
+    uint8_t *supported_states,
+    size_t supported_states_size
+  );
+
+  void (*parse_ble_read_local_supported_features_response)(
+    BT_HDR *response,
+    bt_device_features_t *supported_features
+  );
+} hci_packet_parser_t;
+
+const hci_packet_parser_t *hci_packet_parser_get_interface();
+
+const hci_packet_parser_t *hci_packet_parser_get_test_interface(
+  allocator_t *buffer_allocator_interface
+);
diff --git a/hci/include/low_power_manager.h b/hci/include/low_power_manager.h
new file mode 100644
index 0000000..95f990a
--- /dev/null
+++ b/hci/include/low_power_manager.h
@@ -0,0 +1,47 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include "hci_layer.h"
+
+typedef struct thread_t thread_t;
+typedef struct vendor_t vendor_t;
+
+typedef struct low_power_manager_t {
+  // Initialize the low power manager, and use |post_thread| to synchronize actions.
+  void (*init)(thread_t *post_thread);
+
+  // Clean up the low power manager and release resources.
+  void (*cleanup)(void);
+
+  // Performs |command| synchronized on the thread that was provided
+  // at initialization time.
+  void (*post_command)(low_power_command_t command);
+
+  // Assert wake (for transmission). Must be called on the thread provided
+  // at initialization time.
+  void (*wake_assert)(void);
+
+  // Tell the low power manager that you're done transmitting data. Must be
+  // called on the thread provided at initialization time.
+  void (*transmit_done)(void);
+} low_power_manager_t;
+
+const low_power_manager_t *low_power_manager_get_interface();
+const low_power_manager_t *low_power_manager_get_test_interface(const vendor_t *vendor_interface);
diff --git a/hci/include/packet_fragmenter.h b/hci/include/packet_fragmenter.h
new file mode 100644
index 0000000..c7f643e
--- /dev/null
+++ b/hci/include/packet_fragmenter.h
@@ -0,0 +1,60 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include "allocator.h"
+#include "bt_types.h"
+#include "hci_layer.h"
+
+typedef void (*transmit_finished_cb)(BT_HDR *packet, bool all_fragments_sent);
+typedef void (*packet_reassembled_cb)(BT_HDR *packet);
+typedef void (*packet_fragmented_cb)(BT_HDR *packet, bool send_transmit_finished);
+
+typedef struct {
+  // Called for every packet fragment.
+  packet_fragmented_cb fragmented;
+
+  // Called for every completely reassembled packet.
+  packet_reassembled_cb reassembled;
+
+  // Called when the fragmenter finishes sending all requested fragments,
+  // but the packet has not been entirely sent.
+  transmit_finished_cb transmit_finished;
+} packet_fragmenter_callbacks_t;
+
+typedef struct packet_fragmenter_t {
+  // Initialize the fragmenter, specifying the |result_callbacks|.
+  void (*init)(const packet_fragmenter_callbacks_t *result_callbacks);
+
+  // Release all resources associated with the fragmenter.
+  void (*cleanup)(void);
+
+  // Fragments |packet| if necessary and hands off everything to the fragmented callback.
+  void (*fragment_and_dispatch)(BT_HDR *packet);
+  // If |packet| is a complete packet, forwards to the reassembled callback. Otherwise
+  // holds onto it until all fragments arrive, at which point the reassembled callback is called
+  // with the reassembled data.
+  void (*reassemble_and_dispatch)(BT_HDR *packet);
+} packet_fragmenter_t;
+
+const packet_fragmenter_t *packet_fragmenter_get_interface();
+
+const packet_fragmenter_t *packet_fragmenter_get_test_interface(
+    const controller_t *controller_interface,
+    const allocator_t *buffer_allocator_interface);
diff --git a/hci/include/utils.h b/hci/include/utils.h
deleted file mode 100644
index 0f1517c..0000000
--- a/hci/include/utils.h
+++ /dev/null
@@ -1,194 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Filename:      utils.h
- *
- *  Description:   Utility functions declaration
- *
- ******************************************************************************/
-
-#ifndef UTILS_H
-#define UTILS_H
-
-/******************************************************************************
-**  Constants & Macros
-******************************************************************************/
-
-#define STREAM_TO_UINT16(u16, p) {u16 = ((uint16_t)(*(p)) + (((uint16_t)(*((p) + 1))) << 8)); (p) += 2;}
-#define UINT16_TO_STREAM(p, u16) {*(p)++ = (uint8_t)(u16); *(p)++ = (uint8_t)((u16) >> 8);}
-#define UINT32_TO_STREAM(p, u32) {*(p)++ = (uint8_t)(u32); *(p)++ = (uint8_t)((u32) >> 8); *(p)++ = (uint8_t)((u32) >> 16); *(p)++ = (uint8_t)((u32) >> 24);}
-
-/******************************************************************************
-**  Type definitions
-******************************************************************************/
-
-typedef struct
-{
-    void        *p_first;
-    void        *p_last;
-    uint16_t    count;
-} BUFFER_Q;
-
-/******************************************************************************
-**  Extern variables and functions
-******************************************************************************/
-
-/******************************************************************************
-**  Functions
-******************************************************************************/
-
-/*******************************************************************************
-**
-** Function        utils_init
-**
-** Description     Utils initialization
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_init ();
-
-/*******************************************************************************
-**
-** Function        utils_cleanup
-**
-** Description     Utils cleanup
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_cleanup ();
-
-/*******************************************************************************
-**
-** Function        utils_queue_init
-**
-** Description     Initialize the given buffer queue
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_queue_init (BUFFER_Q *p_q);
-
-/*******************************************************************************
-**
-** Function        utils_enqueue
-**
-** Description     Enqueue a buffer at the tail of the given queue
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_enqueue (BUFFER_Q *p_q, void *p_buf);
-
-/*******************************************************************************
-**
-** Function        utils_dequeue
-**
-** Description     Dequeues a buffer from the head of the given queue
-**
-** Returns         NULL if queue is empty, else buffer
-**
-*******************************************************************************/
-void *utils_dequeue (BUFFER_Q *p_q);
-
-/*******************************************************************************
-**
-** Function        utils_dequeue_unlocked
-**
-** Description     Dequeues a buffer from the head of the given queue without lock
-**
-** Returns         NULL if queue is empty, else buffer
-**
-*******************************************************************************/
-void *utils_dequeue_unlocked (BUFFER_Q *p_q);
-
-/*******************************************************************************
-**
-** Function        utils_getnext
-**
-** Description     Return a pointer to the next buffer linked to the given buffer
-**
-** Returns         NULL if the given buffer does not point to any next buffer,
-**                 else next buffer address
-**
-*******************************************************************************/
-void *utils_getnext (void *p_buf);
-
-/*******************************************************************************
-**
-** Function        utils_remove_from_queue
-**
-** Description     Dequeue the given buffer from the middle of the given queue
-**
-** Returns         NULL if the given queue is empty, else the given buffer
-**
-*******************************************************************************/
-void *utils_remove_from_queue (BUFFER_Q *p_q, void *p_buf);
-
-/*******************************************************************************
-**
-** Function        utils_remove_from_queue_unlocked
-**
-** Description     Dequeue the given buffer from the middle of the given queue without lock
-**
-** Returns         NULL if the given queue is empty, else the given buffer
-**
-*******************************************************************************/
-void *utils_remove_from_queue_unlocked (BUFFER_Q *p_q, void *p_buf);
-
-
-/*******************************************************************************
-**
-** Function        utils_delay
-**
-** Description     sleep unconditionally for timeout milliseconds
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_delay (uint32_t timeout);
-
-/*******************************************************************************
-**
-** Function        utils_lock
-**
-** Description     application calls this function before entering critical
-**                 section
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_lock (void);
-
-/*******************************************************************************
-**
-** Function        utils_unlock
-**
-** Description     application calls this function when leaving critical
-**                 section
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_unlock (void);
-
-#endif /* UTILS_H */
-
diff --git a/hci/include/vendor.h b/hci/include/vendor.h
index 6c13c9c..3181e62 100644
--- a/hci/include/vendor.h
+++ b/hci/include/vendor.h
@@ -21,15 +21,50 @@
 #include <stdbool.h>
 #include <stdint.h>
 
+#include "bt_types.h"
 #include "bt_vendor_lib.h"
+#include "hci_internals.h"
+#include "hci_layer.h"
 
-// Opens the vendor-specific library and sets the Bluetooth
-// address of the adapter to |local_bdaddr|.
-bool vendor_open(const uint8_t *local_bdaddr);
+typedef enum {
+  VENDOR_CHIP_POWER_CONTROL   = BT_VND_OP_POWER_CTRL,
+  VENDOR_OPEN_USERIAL         = BT_VND_OP_USERIAL_OPEN,
+  VENDOR_CLOSE_USERIAL        = BT_VND_OP_USERIAL_CLOSE,
+  VENDOR_GET_LPM_IDLE_TIMEOUT = BT_VND_OP_GET_LPM_IDLE_TIMEOUT,
+  VENDOR_SET_LPM_WAKE_STATE   = BT_VND_OP_LPM_WAKE_SET_STATE,
+  VENDOR_SET_AUDIO_STATE      = BT_VND_OP_SET_AUDIO_STATE
+} vendor_opcode_t;
 
-// Closes the vendor-specific library and frees all associated resources.
-// Only |vendor_open| may be called after |vendor_close|.
-void vendor_close(void);
+typedef enum {
+  VENDOR_CONFIGURE_FIRMWARE   = BT_VND_OP_FW_CFG,
+  VENDOR_CONFIGURE_SCO        = BT_VND_OP_SCO_CFG,
+  VENDOR_SET_LPM_MODE         = BT_VND_OP_LPM_SET_MODE,
+  VENDOR_DO_EPILOG            = BT_VND_OP_EPILOG
+} vendor_async_opcode_t;
 
-// Sends a vendor-specific command to the library.
-int vendor_send_command(bt_vendor_opcode_t opcode, void *param);
+typedef void (*vendor_cb)(bool success);
+
+typedef struct vendor_t{
+  // Opens the vendor-specific library and sets the Bluetooth
+  // address of the adapter to |local_bdaddr|. |hci_interface| is
+  // used to send commands on behalf of the vendor library.
+  bool (*open)(
+    const uint8_t *local_bdaddr,
+    const hci_t *hci_interface
+  );
+
+  // Closes the vendor-specific library and frees all associated resources.
+  // Only |vendor_open| may be called after |vendor_close|.
+  void (*close)(void);
+
+  // Sends a vendor-specific command to the library.
+  int (*send_command)(vendor_opcode_t opcode, void *param);
+
+  // Sends an asynchronous vendor-specific command to the library.
+  int (*send_async_command)(vendor_async_opcode_t opcode, void *param);
+
+  // Registers a callback for an asynchronous vendor-specific command.
+  void (*set_callback)(vendor_async_opcode_t opcode, vendor_cb callback);
+} vendor_t;
+
+const vendor_t *vendor_get_interface();
diff --git a/hci/src/bt_hci_bdroid.c b/hci/src/bt_hci_bdroid.c
deleted file mode 100644
index f139759..0000000
--- a/hci/src/bt_hci_bdroid.c
+++ /dev/null
@@ -1,531 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Filename:      bt_hci_bdroid.c
- *
- *  Description:   Bluedroid Bluetooth Host/Controller interface library
- *                 implementation
- *
- ******************************************************************************/
-
-#define LOG_TAG "bt_hci_bdroid"
-
-#include <assert.h>
-#include <signal.h>
-#include <utils/Log.h>
-
-#include "btsnoop.h"
-#include "bt_hci_bdroid.h"
-#include "bt_utils.h"
-#include "bt_vendor_lib.h"
-#include "hci.h"
-#include "osi.h"
-#include "thread.h"
-#include "userial.h"
-#include "utils.h"
-#include "vendor.h"
-
-#ifndef BTHC_DBG
-#define BTHC_DBG FALSE
-#endif
-
-#if (BTHC_DBG == TRUE)
-#define BTHCDBG(param, ...) {ALOGD(param, ## __VA_ARGS__);}
-#else
-#define BTHCDBG(param, ...) {}
-#endif
-
-/* Vendor epilog process timeout period  */
-static const uint32_t EPILOG_TIMEOUT_MS = 3000;
-
-/******************************************************************************
-**  Externs
-******************************************************************************/
-
-extern int num_hci_cmd_pkts;
-void lpm_init(void);
-void lpm_cleanup(void);
-void lpm_enable(uint8_t turn_on);
-void lpm_wake_deassert(void);
-void lpm_allow_bt_device_sleep(void);
-void lpm_wake_assert(void);
-void init_vnd_if(unsigned char *local_bdaddr);
-
-/******************************************************************************
-**  Variables
-******************************************************************************/
-
-bt_hc_callbacks_t *bt_hc_cbacks = NULL;
-tHCI_IF *p_hci_if;
-volatile bool fwcfg_acked;
-// Cleanup state indication.
-volatile bool has_cleaned_up = false;
-
-/******************************************************************************
-**  Local type definitions
-******************************************************************************/
-
-/* Host/Controller lib thread control block */
-typedef struct
-{
-    thread_t        *worker_thread;
-    pthread_mutex_t worker_thread_lock;
-    bool            epilog_timer_created;
-    timer_t         epilog_timer_id;
-} bt_hc_cb_t;
-
-/******************************************************************************
-**  Static Variables
-******************************************************************************/
-
-static bt_hc_cb_t hc_cb;
-static bool tx_cmd_pkts_pending = false;
-static BUFFER_Q tx_q;
-
-/******************************************************************************
-**  Functions
-******************************************************************************/
-
-static void event_preload(UNUSED_ATTR void *context) {
-  userial_open(USERIAL_PORT_1);
-  vendor_send_command(BT_VND_OP_FW_CFG, NULL);
-}
-
-static void event_postload(UNUSED_ATTR void *context) {
-  /* Start from SCO related H/W configuration, if SCO configuration
-   * is required. Then, follow with reading requests of getting
-   * ACL data length for both BR/EDR and LE.
-   */
-  int result = vendor_send_command(BT_VND_OP_SCO_CFG, NULL);
-  if (result == -1)
-    p_hci_if->get_acl_max_len();
-}
-
-static void event_tx(UNUSED_ATTR void *context) {
-  /*
-   *  We will go through every packets in the tx queue.
-   *  Fine to clear tx_cmd_pkts_pending.
-   */
-  tx_cmd_pkts_pending = false;
-  HC_BT_HDR *sending_msg_que[64];
-  size_t sending_msg_count = 0;
-  int sending_hci_cmd_pkts_count = 0;
-  utils_lock();
-  HC_BT_HDR *p_next_msg = tx_q.p_first;
-  while (p_next_msg && sending_msg_count < ARRAY_SIZE(sending_msg_que))
-  {
-    if ((p_next_msg->event & MSG_EVT_MASK)==MSG_STACK_TO_HC_HCI_CMD)
-    {
-      /*
-       *  if we have used up controller's outstanding HCI command
-       *  credits (normally is 1), skip all HCI command packets in
-       *  the queue.
-       *  The pending command packets will be sent once controller
-       *  gives back us credits through CommandCompleteEvent or
-       *  CommandStatusEvent.
-       */
-      if (tx_cmd_pkts_pending ||
-          (sending_hci_cmd_pkts_count >= num_hci_cmd_pkts))
-      {
-        tx_cmd_pkts_pending = true;
-        p_next_msg = utils_getnext(p_next_msg);
-        continue;
-      }
-      sending_hci_cmd_pkts_count++;
-    }
-
-    HC_BT_HDR *p_msg = p_next_msg;
-    p_next_msg = utils_getnext(p_msg);
-    utils_remove_from_queue_unlocked(&tx_q, p_msg);
-    sending_msg_que[sending_msg_count++] = p_msg;
-  }
-  utils_unlock();
-  for(size_t i = 0; i < sending_msg_count; i++)
-    p_hci_if->send(sending_msg_que[i]);
-  if (tx_cmd_pkts_pending)
-    BTHCDBG("Used up Tx Cmd credits");
-}
-
-static void event_rx(UNUSED_ATTR void *context) {
-#ifndef HCI_USE_MCT
-  p_hci_if->rcv();
-
-  if (tx_cmd_pkts_pending && num_hci_cmd_pkts > 0) {
-    // Got HCI Cmd credits from controller. Send whatever data
-    // we have in our tx queue. We can call |event_tx| directly
-    // here since we're already on the worker thread.
-    event_tx(NULL);
-  }
-#endif
-}
-
-static void event_lpm_enable(UNUSED_ATTR void *context) {
-  lpm_enable(true);
-}
-
-static void event_lpm_disable(UNUSED_ATTR void *context) {
-  lpm_enable(false);
-}
-
-static void event_lpm_wake_device(UNUSED_ATTR void *context) {
-  lpm_wake_assert();
-}
-
-static void event_lpm_allow_sleep(UNUSED_ATTR void *context) {
-  lpm_allow_bt_device_sleep();
-}
-
-static void event_lpm_idle_timeout(UNUSED_ATTR void *context) {
-  lpm_wake_deassert();
-}
-
-static void event_epilog(UNUSED_ATTR void *context) {
-  vendor_send_command(BT_VND_OP_EPILOG, NULL);
-}
-
-static void event_tx_cmd(void *msg) {
-  HC_BT_HDR *p_msg = (HC_BT_HDR *)msg;
-
-  BTHCDBG("%s: p_msg: %p, event: 0x%x", __func__, p_msg, p_msg->event);
-
-  int event = p_msg->event & MSG_EVT_MASK;
-  int sub_event = p_msg->event & MSG_SUB_EVT_MASK;
-  if (event == MSG_CTRL_TO_HC_CMD && sub_event == BT_HC_AUDIO_STATE) {
-    vendor_send_command(BT_VND_OP_SET_AUDIO_STATE, p_msg->data);
-  } else {
-    ALOGW("%s (event: 0x%x, sub_event: 0x%x) not supported", __func__, event, sub_event);
-  }
-
-  bt_hc_cbacks->dealloc(msg);
-}
-
-void bthc_rx_ready(void) {
-  pthread_mutex_lock(&hc_cb.worker_thread_lock);
-
-  if (hc_cb.worker_thread)
-    thread_post(hc_cb.worker_thread, event_rx, NULL);
-
-  pthread_mutex_unlock(&hc_cb.worker_thread_lock);
-}
-
-void bthc_tx(HC_BT_HDR *buf) {
-  pthread_mutex_lock(&hc_cb.worker_thread_lock);
-
-  if (hc_cb.worker_thread) {
-    if (buf)
-      utils_enqueue(&tx_q, buf);
-    thread_post(hc_cb.worker_thread, event_tx, NULL);
-  }
-
-  pthread_mutex_unlock(&hc_cb.worker_thread_lock);
-}
-
-void bthc_idle_timeout(void) {
-  pthread_mutex_lock(&hc_cb.worker_thread_lock);
-
-  if (hc_cb.worker_thread)
-    thread_post(hc_cb.worker_thread, event_lpm_idle_timeout, NULL);
-
-  pthread_mutex_unlock(&hc_cb.worker_thread_lock);
-}
-
-/*******************************************************************************
-**
-** Function        epilog_wait_timeout
-**
-** Description     Timeout thread of epilog watchdog timer
-**
-** Returns         None
-**
-*******************************************************************************/
-static void epilog_wait_timeout(UNUSED_ATTR union sigval arg)
-{
-    ALOGI("...epilog_wait_timeout...");
-
-    thread_free(hc_cb.worker_thread);
-
-    pthread_mutex_lock(&hc_cb.worker_thread_lock);
-    hc_cb.worker_thread = NULL;
-    pthread_mutex_unlock(&hc_cb.worker_thread_lock);
-}
-
-/*******************************************************************************
-**
-** Function        epilog_wait_timer
-**
-** Description     Launch epilog watchdog timer
-**
-** Returns         None
-**
-*******************************************************************************/
-static void epilog_wait_timer(void)
-{
-    int status;
-    struct itimerspec ts;
-    struct sigevent se;
-    uint32_t timeout_ms = EPILOG_TIMEOUT_MS;
-
-    se.sigev_notify = SIGEV_THREAD;
-    se.sigev_value.sival_ptr = &hc_cb.epilog_timer_id;
-    se.sigev_notify_function = epilog_wait_timeout;
-    se.sigev_notify_attributes = NULL;
-
-    status = timer_create(CLOCK_MONOTONIC, &se, &hc_cb.epilog_timer_id);
-
-    if (status == 0)
-    {
-        hc_cb.epilog_timer_created = true;
-        ts.it_value.tv_sec = timeout_ms/1000;
-        ts.it_value.tv_nsec = 1000000*(timeout_ms%1000);
-        ts.it_interval.tv_sec = 0;
-        ts.it_interval.tv_nsec = 0;
-
-        status = timer_settime(hc_cb.epilog_timer_id, 0, &ts, 0);
-        if (status == -1)
-            ALOGE("Failed to fire epilog watchdog timer");
-    }
-    else
-    {
-        ALOGE("Failed to create epilog watchdog timer");
-        hc_cb.epilog_timer_created = false;
-    }
-}
-
-/*****************************************************************************
-**
-**   BLUETOOTH HOST/CONTROLLER INTERFACE LIBRARY FUNCTIONS
-**
-*****************************************************************************/
-
-static int init(const bt_hc_callbacks_t* p_cb, unsigned char *local_bdaddr)
-{
-    int result;
-
-    ALOGI("init");
-
-    if (p_cb == NULL)
-    {
-        ALOGE("init failed with no user callbacks!");
-        return BT_HC_STATUS_FAIL;
-    }
-
-    hc_cb.epilog_timer_created = false;
-    fwcfg_acked = false;
-    has_cleaned_up = false;
-
-    pthread_mutex_init(&hc_cb.worker_thread_lock, NULL);
-
-    /* store reference to user callbacks */
-    bt_hc_cbacks = (bt_hc_callbacks_t *) p_cb;
-
-    vendor_open(local_bdaddr);
-
-    utils_init();
-#ifdef HCI_USE_MCT
-    extern tHCI_IF hci_mct_func_table;
-    p_hci_if = &hci_mct_func_table;
-#else
-    extern tHCI_IF hci_h4_func_table;
-    p_hci_if = &hci_h4_func_table;
-#endif
-
-    p_hci_if->init();
-
-    userial_init();
-    lpm_init();
-
-    utils_queue_init(&tx_q);
-
-    if (hc_cb.worker_thread)
-    {
-        ALOGW("init has been called repeatedly without calling cleanup ?");
-    }
-
-    // Set prio here and let hci worker thread inherit prio
-    // remove once new thread api (thread_set_priority() ?)
-    // can switch prio
-    raise_priority_a2dp(TASK_HIGH_HCI_WORKER);
-
-    hc_cb.worker_thread = thread_new("bt_hc_worker");
-    if (!hc_cb.worker_thread) {
-        ALOGE("%s unable to create worker thread.", __func__);
-        return BT_HC_STATUS_FAIL;
-    }
-
-    return BT_HC_STATUS_SUCCESS;
-}
-
-
-/** Chip power control */
-static void set_power(bt_hc_chip_power_state_t state)
-{
-    int pwr_state;
-
-    BTHCDBG("set_power %d", state);
-
-    /* Calling vendor-specific part */
-    pwr_state = (state == BT_HC_CHIP_PWR_ON) ? BT_VND_PWR_ON : BT_VND_PWR_OFF;
-
-    vendor_send_command(BT_VND_OP_POWER_CTRL, &pwr_state);
-}
-
-
-/** Configure low power mode wake state */
-static int lpm(bt_hc_low_power_event_t event)
-{
-    switch (event)
-    {
-        case BT_HC_LPM_DISABLE:
-            thread_post(hc_cb.worker_thread, event_lpm_disable, NULL);
-            break;
-
-        case BT_HC_LPM_ENABLE:
-            thread_post(hc_cb.worker_thread, event_lpm_enable, NULL);
-            break;
-
-        case BT_HC_LPM_WAKE_ASSERT:
-            thread_post(hc_cb.worker_thread, event_lpm_wake_device, NULL);
-            break;
-
-        case BT_HC_LPM_WAKE_DEASSERT:
-            thread_post(hc_cb.worker_thread, event_lpm_allow_sleep, NULL);
-            break;
-    }
-    return BT_HC_STATUS_SUCCESS;
-}
-
-
-/** Called prior to stack initialization */
-static void preload(UNUSED_ATTR TRANSAC transac) {
-  BTHCDBG("preload");
-  thread_post(hc_cb.worker_thread, event_preload, NULL);
-}
-
-/** Called post stack initialization */
-static void postload(UNUSED_ATTR TRANSAC transac) {
-  BTHCDBG("postload");
-  thread_post(hc_cb.worker_thread, event_postload, NULL);
-}
-
-/** Transmit frame */
-static int transmit_buf(TRANSAC transac, UNUSED_ATTR char *p_buf, UNUSED_ATTR int len) {
-  bthc_tx((HC_BT_HDR *)transac);
-  return BT_HC_STATUS_SUCCESS;
-}
-
-/** Controls HCI logging on/off */
-static int logging(bt_hc_logging_state_t state, char *p_path, bool save_existing) {
-  BTHCDBG("logging %d", state);
-
-  if (state != BT_HC_LOGGING_ON)
-    btsnoop_close();
-  else if (p_path != NULL)
-    btsnoop_open(p_path, save_existing);
-
-  return BT_HC_STATUS_SUCCESS;
-}
-
-/** sends command HC controller to configure platform specific behaviour */
-static int tx_hc_cmd(TRANSAC transac, char *p_buf, int len) {
-  BTHCDBG("tx_hc_cmd: transac %p", transac);
-
-  if (!transac)
-    return BT_HC_STATUS_FAIL;
-
-  thread_post(hc_cb.worker_thread, event_tx_cmd, transac);
-  return BT_HC_STATUS_SUCCESS;
-}
-
-// Closes the interface.
-// This routine is not thread safe.
-static void cleanup(void)
-{
-    if (has_cleaned_up) {
-        ALOGW("%s Already cleaned up for this session\n", __func__);
-        return;
-    }
-
-    BTHCDBG("cleanup");
-
-    if (hc_cb.worker_thread)
-    {
-        if (fwcfg_acked)
-        {
-            epilog_wait_timer();
-            // Stop reading thread
-            userial_close_reader();
-
-            thread_post(hc_cb.worker_thread, event_epilog, NULL);
-        }
-        thread_free(hc_cb.worker_thread);
-
-        pthread_mutex_lock(&hc_cb.worker_thread_lock);
-        hc_cb.worker_thread = NULL;
-        pthread_mutex_unlock(&hc_cb.worker_thread_lock);
-
-        if (hc_cb.epilog_timer_created)
-        {
-            timer_delete(hc_cb.epilog_timer_id);
-            hc_cb.epilog_timer_created = false;
-        }
-    }
-    BTHCDBG("%s Finalizing cleanup\n", __func__);
-
-    lpm_cleanup();
-    userial_close();
-    p_hci_if->cleanup();
-    utils_cleanup();
-
-    set_power(BT_VND_PWR_OFF);
-    vendor_close();
-
-    pthread_mutex_destroy(&hc_cb.worker_thread_lock);
-
-    fwcfg_acked = false;
-    bt_hc_cbacks = NULL;
-    has_cleaned_up = true;
-}
-
-static const bt_hc_interface_t bluetoothHCLibInterface = {
-    sizeof(bt_hc_interface_t),
-    init,
-    set_power,
-    lpm,
-    preload,
-    postload,
-    transmit_buf,
-    logging,
-    cleanup,
-    tx_hc_cmd,
-};
-
-/*******************************************************************************
-**
-** Function        bt_hc_get_interface
-**
-** Description     Caller calls this function to get API instance
-**
-** Returns         API table
-**
-*******************************************************************************/
-const bt_hc_interface_t *bt_hc_get_interface(void)
-{
-    return &bluetoothHCLibInterface;
-}
diff --git a/hci/src/btsnoop.c b/hci/src/btsnoop.c
index e31af35..869b075 100644
--- a/hci/src/btsnoop.c
+++ b/hci/src/btsnoop.c
@@ -1,6 +1,6 @@
 /******************************************************************************
  *
- *  Copyright (C) 2009-2012 Broadcom Corporation
+ *  Copyright (C) 2014 Google, Inc.
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
@@ -16,25 +16,23 @@
  *
  ******************************************************************************/
 
-#define LOG_TAG "btsnoop"
+#define LOG_TAG "bt_snoop"
 
-#include <arpa/inet.h>
 #include <assert.h>
-#include <ctype.h>
-#include <cutils/log.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <string.h>
 #include <sys/stat.h>
 #include <sys/time.h>
 #include <unistd.h>
 
-#include "bt_hci_bdroid.h"
-#include "bt_utils.h"
-#include "utils.h"
+#include "btsnoop.h"
+#include "bt_types.h"
+#include "hci_layer.h"
+#include "osi/include/log.h"
+#include "stack_config.h"
 
 typedef enum {
   kCommandPacket = 1,
@@ -46,13 +44,130 @@
 // Epoch in microseconds since 01/01/0000.
 static const uint64_t BTSNOOP_EPOCH_DELTA = 0x00dcddb30f2f8000ULL;
 
-// File descriptor for btsnoop file.
-static int hci_btsnoop_fd = -1;
+static const stack_config_t *stack_config;
 
+static int logfile_fd = INVALID_FD;
+static bool module_started;
+static bool is_logging;
+static bool logging_enabled_via_api;
+
+// TODO(zachoverflow): merge btsnoop and btsnoop_net together
 void btsnoop_net_open();
 void btsnoop_net_close();
 void btsnoop_net_write(const void *data, size_t length);
 
+static void btsnoop_write_packet(packet_type_t type, const uint8_t *packet, bool is_received);
+static void update_logging();
+
+// Module lifecycle functions
+
+static future_t *start_up(void) {
+  module_started = true;
+  update_logging();
+
+  return NULL;
+}
+
+static future_t *shut_down(void) {
+  module_started = false;
+  update_logging();
+
+  return NULL;
+}
+
+const module_t btsnoop_module = {
+  .name = BTSNOOP_MODULE,
+  .init = NULL,
+  .start_up = start_up,
+  .shut_down = shut_down,
+  .clean_up = NULL,
+  .dependencies = {
+    STACK_CONFIG_MODULE,
+    NULL
+  }
+};
+
+// Interface functions
+
+static void set_api_wants_to_log(bool value) {
+  logging_enabled_via_api = value;
+  update_logging();
+}
+
+static void capture(const BT_HDR *buffer, bool is_received) {
+  const uint8_t *p = buffer->data + buffer->offset;
+
+  if (logfile_fd == INVALID_FD)
+    return;
+
+  switch (buffer->event & MSG_EVT_MASK) {
+    case MSG_HC_TO_STACK_HCI_EVT:
+      btsnoop_write_packet(kEventPacket, p, false);
+      break;
+    case MSG_HC_TO_STACK_HCI_ACL:
+    case MSG_STACK_TO_HC_HCI_ACL:
+      btsnoop_write_packet(kAclPacket, p, is_received);
+      break;
+    case MSG_HC_TO_STACK_HCI_SCO:
+    case MSG_STACK_TO_HC_HCI_SCO:
+      btsnoop_write_packet(kScoPacket, p, is_received);
+      break;
+    case MSG_STACK_TO_HC_HCI_CMD:
+      btsnoop_write_packet(kCommandPacket, p, true);
+      break;
+  }
+}
+
+static const btsnoop_t interface = {
+  set_api_wants_to_log,
+  capture
+};
+
+const btsnoop_t *btsnoop_get_interface() {
+  stack_config = stack_config_get_interface();
+  return &interface;
+}
+
+// Internal functions
+
+static void update_logging() {
+  bool should_log = module_started &&
+    (logging_enabled_via_api || stack_config->get_btsnoop_turned_on());
+
+  if (should_log == is_logging)
+    return;
+
+  is_logging = should_log;
+  if (should_log) {
+    btsnoop_net_open();
+
+    const char *log_path = stack_config->get_btsnoop_log_path();
+
+    // Save the old log if configured to do so
+    if (stack_config->get_btsnoop_should_save_last()) {
+      char last_log_path[PATH_MAX];
+      snprintf(last_log_path, PATH_MAX, "%s.last", log_path);
+      if (!rename(log_path, last_log_path) && errno != ENOENT)
+        LOG_ERROR("%s unable to rename '%s' to '%s': %s", __func__, log_path, last_log_path, strerror(errno));
+    }
+
+    logfile_fd = open(log_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
+    if (logfile_fd == INVALID_FD) {
+      LOG_ERROR("%s unable to open '%s': %s", __func__, log_path, strerror(errno));
+      is_logging = false;
+      return;
+    }
+
+    write(logfile_fd, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16);
+  } else {
+    if (logfile_fd != INVALID_FD)
+      close(logfile_fd);
+
+    logfile_fd = INVALID_FD;
+    btsnoop_net_close();
+  }
+}
+
 static uint64_t btsnoop_timestamp(void) {
   struct timeval tv;
   gettimeofday(&tv, NULL);
@@ -65,8 +180,8 @@
 }
 
 static void btsnoop_write(const void *data, size_t length) {
-  if (hci_btsnoop_fd != -1)
-    write(hci_btsnoop_fd, data, length);
+  if (logfile_fd != INVALID_FD)
+    write(logfile_fd, data, length);
 
   btsnoop_net_write(data, length);
 }
@@ -105,9 +220,6 @@
   time_hi = htonl(time_hi);
   time_lo = htonl(time_lo);
 
-  // This function is called from different contexts.
-  utils_lock();
-
   btsnoop_write(&length, 4);
   btsnoop_write(&length, 4);
   btsnoop_write(&flags, 4);
@@ -116,69 +228,4 @@
   btsnoop_write(&time_lo, 4);
   btsnoop_write(&type, 1);
   btsnoop_write(packet, length_he - 1);
-
-  utils_unlock();
-}
-
-void btsnoop_open(const char *p_path, const bool save_existing) {
-  assert(p_path != NULL);
-  assert(*p_path != '\0');
-
-  btsnoop_net_open();
-
-  if (hci_btsnoop_fd != -1) {
-    ALOGE("%s btsnoop log file is already open.", __func__);
-    return;
-  }
-
-  if (save_existing)
-  {
-    char fname_backup[266] = {0};
-    strncat(fname_backup, p_path, 255);
-    strcat(fname_backup, ".last");
-    rename(p_path, fname_backup);
-  }
-
-  hci_btsnoop_fd = open(p_path,
-                        O_WRONLY | O_CREAT | O_TRUNC,
-                        S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
-
-  if (hci_btsnoop_fd == -1) {
-    ALOGE("%s unable to open '%s': %s", __func__, p_path, strerror(errno));
-    return;
-  }
-
-  write(hci_btsnoop_fd, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16);
-}
-
-void btsnoop_close(void) {
-  if (hci_btsnoop_fd != -1)
-    close(hci_btsnoop_fd);
-  hci_btsnoop_fd = -1;
-
-  btsnoop_net_close();
-}
-
-void btsnoop_capture(const HC_BT_HDR *p_buf, bool is_rcvd) {
-  const uint8_t *p = (const uint8_t *)(p_buf + 1) + p_buf->offset;
-
-  if (hci_btsnoop_fd == -1)
-    return;
-
-  switch (p_buf->event & MSG_EVT_MASK) {
-    case MSG_HC_TO_STACK_HCI_EVT:
-      btsnoop_write_packet(kEventPacket, p, false);
-      break;
-    case MSG_HC_TO_STACK_HCI_ACL:
-    case MSG_STACK_TO_HC_HCI_ACL:
-      btsnoop_write_packet(kAclPacket, p, is_rcvd);
-      break;
-    case MSG_HC_TO_STACK_HCI_SCO:
-    case MSG_STACK_TO_HC_HCI_SCO:
-      btsnoop_write_packet(kScoPacket, p, is_rcvd);
-      break;
-    case MSG_STACK_TO_HC_HCI_CMD:
-      btsnoop_write_packet(kCommandPacket, p, true);
-      break;
-  }
 }
diff --git a/hci/src/btsnoop_net.c b/hci/src/btsnoop_net.c
index adaddcd..c601da8 100644
--- a/hci/src/btsnoop_net.c
+++ b/hci/src/btsnoop_net.c
@@ -16,10 +16,9 @@
  *
  ******************************************************************************/
 
-#define LOG_TAG "btsnoop_net"
+#define LOG_TAG "bt_snoop_net"
 
 #include <assert.h>
-#include <cutils/log.h>
 #include <errno.h>
 #include <netinet/in.h>
 #include <pthread.h>
@@ -29,7 +28,8 @@
 #include <sys/socket.h>
 #include <sys/types.h>
 
-#include "osi.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
 
 static void safe_close_(int *fd);
 static void *listen_fn_(void *context);
@@ -47,9 +47,9 @@
 void btsnoop_net_open() {
   listen_thread_valid_ = (pthread_create(&listen_thread_, NULL, listen_fn_, NULL) == 0);
   if (!listen_thread_valid_) {
-    ALOGE("%s pthread_create failed: %s", __func__, strerror(errno));
+    LOG_ERROR("%s pthread_create failed: %s", __func__, strerror(errno));
   } else {
-    ALOGD("initialized");
+    LOG_DEBUG("initialized");
   }
 }
 
@@ -78,13 +78,13 @@
 
   listen_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
   if (listen_socket_ == -1) {
-    ALOGE("%s socket creation failed: %s", __func__, strerror(errno));
+    LOG_ERROR("%s socket creation failed: %s", __func__, strerror(errno));
     goto cleanup;
   }
 
   int enable = 1;
   if (setsockopt(listen_socket_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) {
-    ALOGE("%s unable to set SO_REUSEADDR: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to set SO_REUSEADDR: %s", __func__, strerror(errno));
     goto cleanup;
   }
 
@@ -93,29 +93,27 @@
   addr.sin_addr.s_addr = htonl(LOCALHOST_);
   addr.sin_port = htons(LISTEN_PORT_);
   if (bind(listen_socket_, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
-    ALOGE("%s unable to bind listen socket: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to bind listen socket: %s", __func__, strerror(errno));
     goto cleanup;
   }
 
   if (listen(listen_socket_, 10) == -1) {
-    ALOGE("%s unable to listen: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to listen: %s", __func__, strerror(errno));
     goto cleanup;
   }
 
   for (;;) {
-    ALOGD("waiting for client connection");
     int client_socket = accept(listen_socket_, NULL, NULL);
     if (client_socket == -1) {
       if (errno == EINVAL || errno == EBADF) {
         break;
       }
-      ALOGW("%s error accepting socket: %s", __func__, strerror(errno));
+      LOG_WARN("%s error accepting socket: %s", __func__, strerror(errno));
       continue;
     }
 
     /* When a new client connects, we have to send the btsnoop file header. This allows
        a decoder to treat the session as a new, valid btsnoop file. */
-    ALOGI("client connected");
     pthread_mutex_lock(&client_socket_lock_);
     safe_close_(&client_socket_);
     client_socket_ = client_socket;
diff --git a/test/suite/support/property.h b/hci/src/buffer_allocator.c
similarity index 60%
copy from test/suite/support/property.h
copy to hci/src/buffer_allocator.c
index a8b77c7..86985a6 100644
--- a/test/suite/support/property.h
+++ b/hci/src/buffer_allocator.c
@@ -16,17 +16,22 @@
  *
  ******************************************************************************/
 
-#pragma once
+#include <assert.h>
 
-#include "base.h"
+#include "buffer_allocator.h"
+#include "gki.h"
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+// TODO(zachoverflow): move the assertion into GKI_getbuf in the future
+static void *buffer_alloc(size_t size) {
+  assert(size <= GKI_MAX_BUF_SIZE);
+  return GKI_getbuf((uint16_t)size);
+}
 
-const char *property_extract_name(const bt_property_t *property);
+static const allocator_t interface = {
+  buffer_alloc,
+  GKI_freebuf
+};
 
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+const allocator_t *buffer_allocator_get_interface() {
+  return &interface;
+}
diff --git a/hci/src/hci_audio.c b/hci/src/hci_audio.c
new file mode 100644
index 0000000..63def16
--- /dev/null
+++ b/hci/src/hci_audio.c
@@ -0,0 +1,39 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2015 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_hci_audio"
+
+#include <stdint.h>
+
+#include "hci/include/bt_vendor_lib.h"
+#include "hci/include/hci_audio.h"
+#include "hci/include/vendor.h"
+#include "osi/include/log.h"
+
+void set_audio_state(uint16_t handle, sco_codec_t codec, sco_state_t state)
+{
+    LOG_INFO("%s handle:%d codec:0x%x state:%d", __func__, handle, codec, state);
+
+    bt_vendor_op_audio_state_t audio_state;
+
+    audio_state.handle = handle;
+    audio_state.peer_codec = codec;
+    audio_state.state = state;
+
+    vendor_get_interface()->send_command(VENDOR_SET_AUDIO_STATE, &audio_state);
+}
diff --git a/hci/src/hci_h4.c b/hci/src/hci_h4.c
deleted file mode 100644
index b41ad53..0000000
--- a/hci/src/hci_h4.c
+++ /dev/null
@@ -1,1063 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Filename:      hci_h4.c
- *
- *  Description:   Contains HCI transport send/receive functions
- *
- ******************************************************************************/
-
-#define LOG_TAG "bt_h4"
-
-#include <utils/Log.h>
-#include <stdlib.h>
-#include <string.h>
-#include <fcntl.h>
-
-#include "bt_hci_bdroid.h"
-#include "btsnoop.h"
-#include "hci.h"
-#include "userial.h"
-#include "utils.h"
-
-/******************************************************************************
-**  Constants & Macros
-******************************************************************************/
-
-#ifndef HCI_DBG
-#define HCI_DBG FALSE
-#endif
-
-#if (HCI_DBG == TRUE)
-#define HCIDBG(param, ...) {LOGD(param, ## __VA_ARGS__);}
-#else
-#define HCIDBG(param, ...) {}
-#endif
-
-/* Preamble length for HCI Commands:
-**      2-bytes for opcode and 1 byte for length
-*/
-#define HCI_CMD_PREAMBLE_SIZE   3
-
-/* Preamble length for HCI Events:
-**      1-byte for opcode and 1 byte for length
-*/
-#define HCI_EVT_PREAMBLE_SIZE   2
-
-/* Preamble length for SCO Data:
-**      2-byte for Handle and 1 byte for length
-*/
-#define HCI_SCO_PREAMBLE_SIZE   3
-
-/* Preamble length for ACL Data:
-**      2-byte for Handle and 2 byte for length
-*/
-#define HCI_ACL_PREAMBLE_SIZE   4
-
-/* Table of HCI preamble sizes for the different HCI message types */
-static const uint8_t hci_preamble_table[] =
-{
-    HCI_CMD_PREAMBLE_SIZE,
-    HCI_ACL_PREAMBLE_SIZE,
-    HCI_SCO_PREAMBLE_SIZE,
-    HCI_EVT_PREAMBLE_SIZE
-};
-
-/* HCI H4 message type definitions */
-#define H4_TYPE_COMMAND         1
-#define H4_TYPE_ACL_DATA        2
-#define H4_TYPE_SCO_DATA        3
-#define H4_TYPE_EVENT           4
-
-static const uint16_t msg_evt_table[] =
-{
-    MSG_HC_TO_STACK_HCI_ERR,       /* H4_TYPE_COMMAND */
-    MSG_HC_TO_STACK_HCI_ACL,       /* H4_TYPE_ACL_DATA */
-    MSG_HC_TO_STACK_HCI_SCO,       /* H4_TYPE_SCO_DATA */
-    MSG_HC_TO_STACK_HCI_EVT        /* H4_TYPE_EVENT */
-};
-
-#define ACL_RX_PKT_START        2
-#define ACL_RX_PKT_CONTINUE     1
-#define L2CAP_HEADER_SIZE       4
-
-/* Maximum numbers of allowed internal
-** outstanding command packets at any time
-*/
-#define INT_CMD_PKT_MAX_COUNT       8
-#define INT_CMD_PKT_IDX_MASK        0x07
-
-#define HCI_COMMAND_COMPLETE_EVT    0x0E
-#define HCI_COMMAND_STATUS_EVT      0x0F
-#define HCI_READ_BUFFER_SIZE        0x1005
-#define HCI_LE_READ_BUFFER_SIZE     0x2002
-
-/******************************************************************************
-**  Local type definitions
-******************************************************************************/
-
-/* H4 Rx States */
-typedef enum {
-    H4_RX_MSGTYPE_ST,
-    H4_RX_LEN_ST,
-    H4_RX_DATA_ST,
-    H4_RX_IGNORE_ST
-} tHCI_H4_RCV_STATE;
-
-/* Callback function for the returned event of internal issued command */
-typedef void (*tINT_CMD_CBACK)(void *p_mem);
-
-typedef struct
-{
-    uint16_t opcode;        /* OPCODE of outstanding internal commands */
-    tINT_CMD_CBACK cback;   /* Callback function when return of internal
-                             * command is received */
-} tINT_CMD_Q;
-
-/* Control block for HCISU_H4 */
-typedef struct
-{
-    HC_BT_HDR *p_rcv_msg;          /* Buffer to hold current rx HCI message */
-    uint16_t rcv_len;               /* Size of current incoming message */
-    uint8_t rcv_msg_type;           /* Current incoming message type */
-    tHCI_H4_RCV_STATE rcv_state;    /* Receive state of current rx message */
-    uint16_t hc_acl_data_size;      /* Controller's max ACL data length */
-    uint16_t hc_ble_acl_data_size;  /* Controller's max BLE ACL data length */
-    BUFFER_Q acl_rx_q;      /* Queue of base buffers for fragmented ACL pkts */
-    uint8_t preload_count;          /* Count numbers of preload bytes */
-    uint8_t preload_buffer[6];      /* HCI_ACL_PREAMBLE_SIZE + 2 */
-    int int_cmd_rsp_pending;        /* Num of internal cmds pending for ack */
-    uint8_t int_cmd_rd_idx;         /* Read index of int_cmd_opcode queue */
-    uint8_t int_cmd_wrt_idx;        /* Write index of int_cmd_opcode queue */
-    tINT_CMD_Q int_cmd[INT_CMD_PKT_MAX_COUNT]; /* FIFO queue */
-} tHCI_H4_CB;
-
-/******************************************************************************
-**  Externs
-******************************************************************************/
-
-uint8_t hci_h4_send_int_cmd(uint16_t opcode, HC_BT_HDR *p_buf, \
-                                  tINT_CMD_CBACK p_cback);
-void lpm_wake_assert(void);
-void lpm_tx_done(uint8_t is_tx_done);
-
-/******************************************************************************
-**  Variables
-******************************************************************************/
-
-/* Num of allowed outstanding HCI CMD packets */
-volatile int num_hci_cmd_pkts = 1;
-
-/******************************************************************************
-**  Static variables
-******************************************************************************/
-
-static tHCI_H4_CB       h4_cb;
-
-/******************************************************************************
-**  Static functions
-******************************************************************************/
-
-/*******************************************************************************
-**
-** Function         get_acl_data_length_cback
-**
-** Description      Callback function for HCI_READ_BUFFER_SIZE and
-**                  HCI_LE_READ_BUFFER_SIZE commands if they were sent because
-**                  of internal request.
-**
-** Returns          None
-**
-*******************************************************************************/
-void get_acl_data_length_cback(void *p_mem)
-{
-    uint8_t     *p, status;
-    uint16_t    opcode, len=0;
-    HC_BT_HDR   *p_buf = (HC_BT_HDR *) p_mem;
-
-    p = (uint8_t *)(p_buf + 1) + 3;
-    STREAM_TO_UINT16(opcode, p)
-    status = *p++;
-    if (status == 0) /* Success */
-        STREAM_TO_UINT16(len, p)
-
-    if (opcode == HCI_READ_BUFFER_SIZE)
-    {
-        if (status == 0)
-            h4_cb.hc_acl_data_size = len;
-
-        /* reuse the rx buffer for sending HCI_LE_READ_BUFFER_SIZE command */
-        p_buf->event = MSG_STACK_TO_HC_HCI_CMD;
-        p_buf->offset = 0;
-        p_buf->layer_specific = 0;
-        p_buf->len = 3;
-
-        p = (uint8_t *) (p_buf + 1);
-        UINT16_TO_STREAM(p, HCI_LE_READ_BUFFER_SIZE);
-        *p = 0;
-
-        if ((status = hci_h4_send_int_cmd(HCI_LE_READ_BUFFER_SIZE, p_buf, \
-                                           get_acl_data_length_cback)) == FALSE)
-        {
-            bt_hc_cbacks->dealloc(p_buf);
-            bt_hc_cbacks->postload_cb(NULL, BT_HC_POSTLOAD_SUCCESS);
-        }
-    }
-    else if (opcode == HCI_LE_READ_BUFFER_SIZE)
-    {
-        if (status == 0)
-            h4_cb.hc_ble_acl_data_size = (len) ? len : h4_cb.hc_acl_data_size;
-
-        if (bt_hc_cbacks)
-        {
-            bt_hc_cbacks->dealloc(p_buf);
-            ALOGE("vendor lib postload completed");
-            bt_hc_cbacks->postload_cb(NULL, BT_HC_POSTLOAD_SUCCESS);
-        }
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         internal_event_intercept
-**
-** Description      This function is called to parse received HCI event and
-**                  - update the Num_HCI_Command_Packets
-**                  - intercept the event if it is the result of an early
-**                    issued internal command.
-**
-** Returns          TRUE : if the event had been intercepted for internal process
-**                  FALSE : send this event to core stack
-**
-*******************************************************************************/
-uint8_t internal_event_intercept(void)
-{
-    uint8_t     *p;
-    uint8_t     event_code;
-    uint16_t    opcode, len;
-    tHCI_H4_CB  *p_cb = &h4_cb;
-
-    p = (uint8_t *)(p_cb->p_rcv_msg + 1);
-
-    event_code = *p++;
-    len = *p++;
-
-    if (event_code == HCI_COMMAND_COMPLETE_EVT)
-    {
-        num_hci_cmd_pkts = *p++;
-
-        if (p_cb->int_cmd_rsp_pending > 0)
-        {
-            STREAM_TO_UINT16(opcode, p)
-
-            if (opcode == p_cb->int_cmd[p_cb->int_cmd_rd_idx].opcode)
-            {
-                HCIDBG( \
-                "Intercept CommandCompleteEvent for internal command (0x%04X)",\
-                          opcode);
-                if (p_cb->int_cmd[p_cb->int_cmd_rd_idx].cback != NULL)
-                {
-                    p_cb->int_cmd[p_cb->int_cmd_rd_idx].cback(p_cb->p_rcv_msg);
-                }
-                else
-                {
-                    // Missing cback function!
-                    // Release the p_rcv_msg buffer.
-                    if (bt_hc_cbacks)
-                    {
-                        bt_hc_cbacks->dealloc(p_cb->p_rcv_msg);
-                    }
-                }
-                p_cb->int_cmd_rd_idx = ((p_cb->int_cmd_rd_idx+1) & \
-                                        INT_CMD_PKT_IDX_MASK);
-                p_cb->int_cmd_rsp_pending--;
-                return TRUE;
-            }
-        }
-    }
-    else if (event_code == HCI_COMMAND_STATUS_EVT)
-    {
-        num_hci_cmd_pkts = *(++p);
-    }
-
-    return FALSE;
-}
-
-/*******************************************************************************
-**
-** Function         acl_rx_frame_buffer_alloc
-**
-** Description      This function is called from the HCI transport when the
-**                  first 4 or 6 bytes of an HCI ACL packet have been received:
-**                  - Allocate a new buffer if it is a start pakcet of L2CAP
-**                    message.
-**                  - Return the buffer address of the starting L2CAP message
-**                    frame if the packet is the next segment of a fragmented
-**                    L2CAP message.
-**
-** Returns          the address of the receive buffer H4 RX should use
-**                  (CR419: Modified to return NULL in case of error.)
-**
-** NOTE             This assumes that the L2CAP MTU size is less than the size
-**                  of an HCI ACL buffer, so the maximum L2CAP message will fit
-**                  into one buffer.
-**
-*******************************************************************************/
-static HC_BT_HDR *acl_rx_frame_buffer_alloc (void)
-{
-    uint8_t     *p;
-    uint16_t    handle;
-    uint16_t    hci_len;
-    uint16_t    total_len;
-    uint8_t     pkt_type;
-    HC_BT_HDR  *p_return_buf = NULL;
-    tHCI_H4_CB  *p_cb = &h4_cb;
-
-
-    p = p_cb->preload_buffer;
-
-    STREAM_TO_UINT16 (handle, p);
-    STREAM_TO_UINT16 (hci_len, p);
-    STREAM_TO_UINT16 (total_len, p);
-
-    pkt_type = (uint8_t)(((handle) >> 12) & 0x0003);
-    handle   = (uint16_t)((handle) & 0x0FFF);
-
-    if (p_cb->acl_rx_q.count)
-    {
-        uint16_t save_handle;
-        HC_BT_HDR *p_hdr = p_cb->acl_rx_q.p_first;
-
-        while (p_hdr != NULL)
-        {
-            p = (uint8_t *)(p_hdr + 1);
-            STREAM_TO_UINT16 (save_handle, p);
-            save_handle   = (uint16_t)((save_handle) & 0x0FFF);
-            if (save_handle == handle)
-            {
-                p_return_buf = p_hdr;
-                break;
-            }
-            p_hdr = utils_getnext(p_hdr);
-        }
-    }
-
-    if (pkt_type == ACL_RX_PKT_START)       /*** START PACKET ***/
-    {
-        /* Might have read 2 bytes for the L2CAP payload length */
-        p_cb->rcv_len = (hci_len) ? (hci_len - 2) : 0;
-
-        /* Start of packet. If we were in the middle of receiving */
-        /* a packet on the same ACL handle, the original packet is incomplete.
-         * Drop it. */
-        if (p_return_buf)
-        {
-            ALOGW("H4 - dropping incomplete ACL frame");
-
-            utils_remove_from_queue(&(p_cb->acl_rx_q), p_return_buf);
-
-            if (bt_hc_cbacks)
-            {
-                bt_hc_cbacks->dealloc(p_return_buf);
-            }
-            p_return_buf = NULL;
-        }
-
-        /* Allocate a buffer for message */
-        if (bt_hc_cbacks)
-        {
-            int len = total_len + HCI_ACL_PREAMBLE_SIZE + L2CAP_HEADER_SIZE + \
-                      BT_HC_HDR_SIZE;
-            p_return_buf = (HC_BT_HDR *) bt_hc_cbacks->alloc(len);
-        }
-
-        if (p_return_buf)
-        {
-            /* Initialize buffer with preloaded data */
-            p_return_buf->offset = 0;
-            p_return_buf->layer_specific = 0;
-            p_return_buf->event = MSG_HC_TO_STACK_HCI_ACL;
-            p_return_buf->len = p_cb->preload_count;
-            memcpy((uint8_t *)(p_return_buf + 1), p_cb->preload_buffer, \
-                   p_cb->preload_count);
-
-            if (hci_len && ((total_len + L2CAP_HEADER_SIZE) > hci_len))
-            {
-                /* Will expect to see fragmented ACL packets */
-                /* Keep the base buffer address in the watching queue */
-                utils_enqueue(&(p_cb->acl_rx_q), p_return_buf);
-            }
-        }
-    }
-    else                                    /*** CONTINUATION PACKET ***/
-    {
-        p_cb->rcv_len = hci_len;
-
-        if (p_return_buf)
-        {
-            /* Packet continuation and found the original rx buffer */
-            uint8_t *p_f = p = (uint8_t *)(p_return_buf + 1) + 2;
-
-            STREAM_TO_UINT16 (total_len, p);
-
-            /* Update HCI header of first segment (base buffer) with new len */
-            total_len += hci_len;
-            UINT16_TO_STREAM (p_f, total_len);
-        }
-    }
-
-    return (p_return_buf);
-}
-
-/*******************************************************************************
-**
-** Function         acl_rx_frame_end_chk
-**
-** Description      This function is called from the HCI transport when the last
-**                  byte of an HCI ACL packet has been received. It checks if
-**                  the L2CAP message is complete, i.e. no more continuation
-**                  packets are expected.
-**
-** Returns          TRUE if message complete, FALSE if continuation expected
-**
-*******************************************************************************/
-static uint8_t acl_rx_frame_end_chk (void)
-{
-    uint8_t     *p;
-    uint16_t    handle, hci_len, l2cap_len;
-    HC_BT_HDR  *p_buf;
-    tHCI_H4_CB  *p_cb = &h4_cb;
-    uint8_t     frame_end=TRUE;
-
-    p_buf = p_cb->p_rcv_msg;
-    p = (uint8_t *)(p_buf + 1);
-
-    STREAM_TO_UINT16 (handle, p);
-    STREAM_TO_UINT16 (hci_len, p);
-    STREAM_TO_UINT16 (l2cap_len, p);
-
-    if (hci_len > 0)
-    {
-        if (l2cap_len > (p_buf->len-(HCI_ACL_PREAMBLE_SIZE+L2CAP_HEADER_SIZE)) )
-        {
-            /* If the L2CAP length has not been reached, tell H4 not to send
-             * this buffer to stack */
-            frame_end = FALSE;
-        }
-        else
-        {
-            /*
-             * The current buffer coulb be in the watching list.
-             * Remove it from the list if it is in.
-             */
-            if (p_cb->acl_rx_q.count)
-                utils_remove_from_queue(&(p_cb->acl_rx_q), p_buf);
-        }
-    }
-
-    /****
-     ** Print snoop trace
-     ****/
-    if (p_buf->offset)
-    {
-        /* CONTINUATION PACKET */
-
-        /* save original p_buf->len content */
-        uint16_t tmp_u16 = p_buf->len;
-
-        /* borrow HCI_ACL_PREAMBLE_SIZE bytes from the payload section */
-        p = (uint8_t *)(p_buf + 1) + p_buf->offset - HCI_ACL_PREAMBLE_SIZE;
-
-        /* save contents */
-        memcpy(p_cb->preload_buffer, p, HCI_ACL_PREAMBLE_SIZE);
-
-        /* Set packet boundary flags to "continuation packet" */
-        handle = (handle & 0xCFFF) | 0x1000;
-
-        /* write handl & length info */
-        UINT16_TO_STREAM (p, handle);
-        UINT16_TO_STREAM (p, (p_buf->len - p_buf->offset));
-
-        /* roll pointer back */
-        p = p - HCI_ACL_PREAMBLE_SIZE;
-
-        /* adjust `p_buf->offset` & `p_buf->len`
-         * before calling btsnoop_capture() */
-        p_buf->offset = p_buf->offset - HCI_ACL_PREAMBLE_SIZE;
-        p_buf->len = p_buf->len - p_buf->offset;
-
-        btsnoop_capture(p_buf, true);
-
-        /* restore contents */
-        memcpy(p, p_cb->preload_buffer, HCI_ACL_PREAMBLE_SIZE);
-
-        /* restore p_buf->len */
-        p_buf->len = tmp_u16;
-    }
-    else
-    {
-        /* START PACKET */
-        btsnoop_capture(p_buf, true);
-    }
-
-    if (frame_end == TRUE)
-        p_buf->offset = 0;
-    else
-        p_buf->offset = p_buf->len; /* save current buffer-end position */
-
-    return frame_end;
-}
-
-/*****************************************************************************
-**   HCI H4 INTERFACE FUNCTIONS
-*****************************************************************************/
-
-/*******************************************************************************
-**
-** Function        hci_h4_init
-**
-** Description     Initialize H4 module
-**
-** Returns         None
-**
-*******************************************************************************/
-void hci_h4_init(void)
-{
-    HCIDBG("hci_h4_init");
-
-    memset(&h4_cb, 0, sizeof(tHCI_H4_CB));
-    utils_queue_init(&(h4_cb.acl_rx_q));
-
-    /* Per HCI spec., always starts with 1 */
-    num_hci_cmd_pkts = 1;
-
-    /* Give an initial values of Host Controller's ACL data packet length
-     * Will update with an internal HCI(_LE)_Read_Buffer_Size request
-     */
-    h4_cb.hc_acl_data_size = 1021;
-    h4_cb.hc_ble_acl_data_size = 27;
-}
-
-/*******************************************************************************
-**
-** Function        hci_h4_cleanup
-**
-** Description     Clean H4 module
-**
-** Returns         None
-**
-*******************************************************************************/
-void hci_h4_cleanup(void)
-{
-    HCIDBG("hci_h4_cleanup");
-}
-
-/*******************************************************************************
-**
-** Function        hci_h4_send_msg
-**
-** Description     Determine message type, set HCI H4 packet indicator, and
-**                 send message through USERIAL driver
-**
-** Returns         None
-**
-*******************************************************************************/
-void hci_h4_send_msg(HC_BT_HDR *p_msg)
-{
-    uint8_t type = 0;
-    uint16_t handle;
-    uint16_t bytes_to_send, lay_spec;
-    uint8_t *p = ((uint8_t *)(p_msg + 1)) + p_msg->offset;
-    uint16_t event = p_msg->event & MSG_EVT_MASK;
-    uint16_t sub_event = p_msg->event & MSG_SUB_EVT_MASK;
-    uint16_t acl_pkt_size = 0, acl_data_size = 0;
-    uint16_t bytes_sent;
-
-    /* wake up BT device if its in sleep mode */
-    lpm_wake_assert();
-
-    if (event == MSG_STACK_TO_HC_HCI_ACL)
-        type = H4_TYPE_ACL_DATA;
-    else if (event == MSG_STACK_TO_HC_HCI_SCO)
-        type = H4_TYPE_SCO_DATA;
-    else if (event == MSG_STACK_TO_HC_HCI_CMD)
-        type = H4_TYPE_COMMAND;
-
-    if (sub_event == LOCAL_BR_EDR_CONTROLLER_ID)
-    {
-        acl_data_size = h4_cb.hc_acl_data_size;
-        acl_pkt_size = h4_cb.hc_acl_data_size + HCI_ACL_PREAMBLE_SIZE;
-    }
-    else
-    {
-        acl_data_size = h4_cb.hc_ble_acl_data_size;
-        acl_pkt_size = h4_cb.hc_ble_acl_data_size + HCI_ACL_PREAMBLE_SIZE;
-    }
-
-    /* Check if sending ACL data that needs fragmenting */
-    if ((event == MSG_STACK_TO_HC_HCI_ACL) && (p_msg->len > acl_pkt_size))
-    {
-        /* Get the handle from the packet */
-        STREAM_TO_UINT16 (handle, p);
-
-        /* Set packet boundary flags to "continuation packet" */
-        handle = (handle & 0xCFFF) | 0x1000;
-
-        /* Do all the first chunks */
-        while (p_msg->len > acl_pkt_size)
-        {
-            /* remember layer_specific because uart borrow
-               one byte from layer_specific for packet type */
-            lay_spec = p_msg->layer_specific;
-
-            p = ((uint8_t *)(p_msg + 1)) + p_msg->offset - 1;
-            *p = type;
-            bytes_to_send = acl_pkt_size + 1; /* packet_size + message type */
-
-            bytes_sent = userial_write(event,(uint8_t *) p,bytes_to_send);
-
-            /* generate snoop trace message */
-            btsnoop_capture(p_msg, false);
-
-            p_msg->layer_specific = lay_spec;
-            /* Adjust offset and length for what we just sent */
-            p_msg->offset += acl_data_size;
-            p_msg->len    -= acl_data_size;
-
-            p = ((uint8_t *)(p_msg + 1)) + p_msg->offset;
-
-            UINT16_TO_STREAM (p, handle);
-
-            if (p_msg->len > acl_pkt_size)
-            {
-                UINT16_TO_STREAM (p, acl_data_size);
-            }
-            else
-            {
-                UINT16_TO_STREAM (p, p_msg->len - HCI_ACL_PREAMBLE_SIZE);
-            }
-
-            /* If we were only to send partial buffer, stop when done.    */
-            /* Send the buffer back to L2CAP to send the rest of it later */
-            if (p_msg->layer_specific)
-            {
-                if (--p_msg->layer_specific == 0)
-                {
-                    p_msg->event = MSG_HC_TO_STACK_L2C_SEG_XMIT;
-
-                    if (bt_hc_cbacks)
-                    {
-                        bt_hc_cbacks->tx_result((TRANSAC) p_msg, \
-                                                    (char *) (p_msg + 1), \
-                                                    BT_HC_TX_FRAGMENT);
-                    }
-
-                    return;
-                }
-            }
-        }
-    }
-
-
-    /* remember layer_specific because uart borrow
-       one byte from layer_specific for packet type */
-    lay_spec = p_msg->layer_specific;
-
-    /* Put the HCI Transport packet type 1 byte before the message */
-    p = ((uint8_t *)(p_msg + 1)) + p_msg->offset - 1;
-    *p = type;
-    bytes_to_send = p_msg->len + 1;     /* message_size + message type */
-
-    bytes_sent = userial_write(event,(uint8_t *) p, bytes_to_send);
-
-    p_msg->layer_specific = lay_spec;
-
-    if (event == MSG_STACK_TO_HC_HCI_CMD)
-    {
-        num_hci_cmd_pkts--;
-
-        /* If this is an internal Cmd packet, the layer_specific field would
-         * have stored with the opcode of HCI command.
-         * Retrieve the opcode from the Cmd packet.
-         */
-         p++;
-        STREAM_TO_UINT16(lay_spec, p);
-    }
-
-    /* generate snoop trace message */
-    btsnoop_capture(p_msg, false);
-
-    if (bt_hc_cbacks)
-    {
-        if ((event == MSG_STACK_TO_HC_HCI_CMD) && \
-            (h4_cb.int_cmd_rsp_pending > 0) && \
-            (p_msg->layer_specific == lay_spec))
-        {
-            /* dealloc buffer of internal command */
-            bt_hc_cbacks->dealloc(p_msg);
-        }
-        else
-        {
-            bt_hc_cbacks->tx_result((TRANSAC) p_msg, (char *) (p_msg + 1), \
-                                        BT_HC_TX_SUCCESS);
-        }
-    }
-
-    lpm_tx_done(TRUE);
-
-    return;
-}
-
-
-/*******************************************************************************
-**
-** Function        hci_h4_receive_msg
-**
-** Description     Construct HCI EVENT/ACL packets and send them to stack once
-**                 complete packet has been received.
-**
-** Returns         Number of read bytes
-**
-*******************************************************************************/
-uint16_t hci_h4_receive_msg(void)
-{
-    uint16_t    bytes_read = 0;
-    uint8_t     byte;
-    uint16_t    msg_len, len;
-    uint8_t     msg_received;
-    tHCI_H4_CB  *p_cb=&h4_cb;
-
-    while (TRUE)
-    {
-        /* Read one byte to see if there is anything waiting to be read */
-        if (userial_read(0 /*dummy*/, &byte, 1) == 0)
-        {
-            break;
-        }
-
-        bytes_read++;
-        msg_received = FALSE;
-
-        switch (p_cb->rcv_state)
-        {
-        case H4_RX_MSGTYPE_ST:
-            /* Start of new message */
-            if ((byte < H4_TYPE_ACL_DATA) || (byte > H4_TYPE_EVENT))
-            {
-                /* Unknown HCI message type */
-                /* Drop this byte */
-                ALOGE("[h4] Unknown HCI message type drop this byte 0x%x", byte);
-                break;
-            }
-
-            /* Initialize rx parameters */
-            p_cb->rcv_msg_type = byte;
-            p_cb->rcv_len = hci_preamble_table[byte-1];
-            memset(p_cb->preload_buffer, 0 , 6);
-            p_cb->preload_count = 0;
-            // p_cb->p_rcv_msg = NULL;
-            p_cb->rcv_state = H4_RX_LEN_ST; /* Next, wait for length to come */
-            break;
-
-        case H4_RX_LEN_ST:
-            /* Receiving preamble */
-            p_cb->preload_buffer[p_cb->preload_count++] = byte;
-            p_cb->rcv_len--;
-
-            /* Check if we received entire preamble yet */
-            if (p_cb->rcv_len == 0)
-            {
-                if (p_cb->rcv_msg_type == H4_TYPE_ACL_DATA)
-                {
-                    /* ACL data lengths are 16-bits */
-                    msg_len = p_cb->preload_buffer[3];
-                    msg_len = (msg_len << 8) + p_cb->preload_buffer[2];
-
-                    if (msg_len && (p_cb->preload_count == 4))
-                    {
-                        /* Check if this is a start packet */
-                        byte = ((p_cb->preload_buffer[1] >> 4) & 0x03);
-
-                        if (byte == ACL_RX_PKT_START)
-                        {
-                           /*
-                            * A start packet & with non-zero data payload length.
-                            * We want to read 2 more bytes to get L2CAP payload
-                            * length.
-                            */
-                            p_cb->rcv_len = 2;
-
-                            break;
-                        }
-                    }
-
-                    /*
-                     * Check for segmented packets. If this is a continuation
-                     * packet, then we will continue appending data to the
-                     * original rcv buffer.
-                     */
-                    p_cb->p_rcv_msg = acl_rx_frame_buffer_alloc();
-                }
-                else
-                {
-                    /* Received entire preamble.
-                     * Length is in the last received byte */
-                    msg_len = byte;
-                    p_cb->rcv_len = msg_len;
-
-                    /* Allocate a buffer for message */
-                    if (bt_hc_cbacks)
-                    {
-                        len = msg_len + p_cb->preload_count + BT_HC_HDR_SIZE;
-                        p_cb->p_rcv_msg = \
-                            (HC_BT_HDR *) bt_hc_cbacks->alloc(len);
-                    }
-
-                    if (p_cb->p_rcv_msg)
-                    {
-                        /* Initialize buffer with preloaded data */
-                        p_cb->p_rcv_msg->offset = 0;
-                        p_cb->p_rcv_msg->layer_specific = 0;
-                        p_cb->p_rcv_msg->event = \
-                            msg_evt_table[p_cb->rcv_msg_type-1];
-                        p_cb->p_rcv_msg->len = p_cb->preload_count;
-                        memcpy((uint8_t *)(p_cb->p_rcv_msg + 1), \
-                               p_cb->preload_buffer, p_cb->preload_count);
-                    }
-                }
-
-                if (p_cb->p_rcv_msg == NULL)
-                {
-                    /* Unable to acquire message buffer. */
-                    ALOGE( \
-                     "H4: Unable to acquire buffer for incoming HCI message." \
-                    );
-
-                    if (msg_len == 0)
-                    {
-                        /* Wait for next message */
-                        p_cb->rcv_state = H4_RX_MSGTYPE_ST;
-                    }
-                    else
-                    {
-                        /* Ignore rest of the packet */
-                        p_cb->rcv_state = H4_RX_IGNORE_ST;
-                    }
-
-                    break;
-                }
-
-                /* Message length is valid */
-                if (msg_len)
-                {
-                    /* Read rest of message */
-                    p_cb->rcv_state = H4_RX_DATA_ST;
-                }
-                else
-                {
-                    /* Message has no additional parameters.
-                     * (Entire message has been received) */
-                    if (p_cb->rcv_msg_type == H4_TYPE_ACL_DATA)
-                        acl_rx_frame_end_chk(); /* to print snoop trace */
-
-                    msg_received = TRUE;
-
-                    /* Next, wait for next message */
-                    p_cb->rcv_state = H4_RX_MSGTYPE_ST;
-                }
-            }
-            break;
-
-        case H4_RX_DATA_ST:
-            *((uint8_t *)(p_cb->p_rcv_msg + 1) + p_cb->p_rcv_msg->len++) = byte;
-            p_cb->rcv_len--;
-
-            if (p_cb->rcv_len > 0)
-            {
-                /* Read in the rest of the message */
-                len = userial_read(0 /*dummy*/, \
-                      ((uint8_t *)(p_cb->p_rcv_msg+1) + p_cb->p_rcv_msg->len), \
-                      p_cb->rcv_len);
-                p_cb->p_rcv_msg->len += len;
-                p_cb->rcv_len -= len;
-                bytes_read += len;
-            }
-
-            /* Check if we read in entire message yet */
-            if (p_cb->rcv_len == 0)
-            {
-                /* Received entire packet. */
-                /* Check for segmented l2cap packets */
-                if ((p_cb->rcv_msg_type == H4_TYPE_ACL_DATA) &&
-                    !acl_rx_frame_end_chk())
-                {
-                    /* Not the end of packet yet. */
-                    /* Next, wait for next message */
-                    p_cb->rcv_state = H4_RX_MSGTYPE_ST;
-                }
-                else
-                {
-                    msg_received = TRUE;
-                    /* Next, wait for next message */
-                    p_cb->rcv_state = H4_RX_MSGTYPE_ST;
-                }
-            }
-            break;
-
-
-        case H4_RX_IGNORE_ST:
-            /* Ignore reset of packet */
-            p_cb->rcv_len--;
-
-            /* Check if we read in entire message yet */
-            if (p_cb->rcv_len == 0)
-            {
-                /* Next, wait for next message */
-                p_cb->rcv_state = H4_RX_MSGTYPE_ST;
-            }
-            break;
-        }
-
-
-        /* If we received entire message, then send it to the task */
-        if (msg_received)
-        {
-            uint8_t intercepted = FALSE;
-
-            /* generate snoop trace message */
-            /* ACL packet tracing had done in acl_rx_frame_end_chk() */
-            if (p_cb->p_rcv_msg->event != MSG_HC_TO_STACK_HCI_ACL)
-                btsnoop_capture(p_cb->p_rcv_msg, true);
-
-            if (p_cb->p_rcv_msg->event == MSG_HC_TO_STACK_HCI_EVT)
-                intercepted = internal_event_intercept();
-
-            if ((bt_hc_cbacks) && (intercepted == FALSE))
-            {
-                bt_hc_cbacks->data_ind((TRANSAC) p_cb->p_rcv_msg, \
-                                       (char *) (p_cb->p_rcv_msg + 1), \
-                                       p_cb->p_rcv_msg->len + BT_HC_HDR_SIZE);
-            }
-            p_cb->p_rcv_msg = NULL;
-        }
-    }
-
-    return (bytes_read);
-}
-
-
-/*******************************************************************************
-**
-** Function        hci_h4_send_int_cmd
-**
-** Description     Place the internal commands (issued internally by vendor lib)
-**                 in the tx_q.
-**
-** Returns         TRUE/FALSE
-**
-*******************************************************************************/
-uint8_t hci_h4_send_int_cmd(uint16_t opcode, HC_BT_HDR *p_buf, \
-                                  tINT_CMD_CBACK p_cback)
-{
-    if (h4_cb.int_cmd_rsp_pending > INT_CMD_PKT_MAX_COUNT)
-    {
-        ALOGE( \
-        "Allow only %d outstanding internal commands at a time [Reject 0x%04X]"\
-        , INT_CMD_PKT_MAX_COUNT, opcode);
-        return FALSE;
-    }
-
-    h4_cb.int_cmd_rsp_pending++;
-    h4_cb.int_cmd[h4_cb.int_cmd_wrt_idx].opcode = opcode;
-    h4_cb.int_cmd[h4_cb.int_cmd_wrt_idx].cback = p_cback;
-    h4_cb.int_cmd_wrt_idx = ((h4_cb.int_cmd_wrt_idx+1) & INT_CMD_PKT_IDX_MASK);
-
-    /* stamp signature to indicate an internal command */
-    p_buf->layer_specific = opcode;
-
-    bthc_tx(p_buf);
-    return TRUE;
-}
-
-
-/*******************************************************************************
-**
-** Function        hci_h4_get_acl_data_length
-**
-** Description     Issue HCI_READ_BUFFER_SIZE command to retrieve Controller's
-**                 ACL data length setting
-**
-** Returns         None
-**
-*******************************************************************************/
-void hci_h4_get_acl_data_length(void)
-{
-    HC_BT_HDR  *p_buf = NULL;
-    uint8_t     *p, ret;
-
-    if (bt_hc_cbacks)
-    {
-        p_buf = (HC_BT_HDR *) bt_hc_cbacks->alloc(BT_HC_HDR_SIZE + \
-                                                       HCI_CMD_PREAMBLE_SIZE);
-    }
-
-    if (p_buf)
-    {
-        p_buf->event = MSG_STACK_TO_HC_HCI_CMD;
-        p_buf->offset = 0;
-        p_buf->layer_specific = 0;
-        p_buf->len = HCI_CMD_PREAMBLE_SIZE;
-
-        p = (uint8_t *) (p_buf + 1);
-        UINT16_TO_STREAM(p, HCI_READ_BUFFER_SIZE);
-        *p = 0;
-
-        if ((ret = hci_h4_send_int_cmd(HCI_READ_BUFFER_SIZE, p_buf, \
-                                       get_acl_data_length_cback)) == FALSE)
-        {
-            bt_hc_cbacks->dealloc(p_buf);
-        }
-        else
-            return;
-    }
-
-    if (bt_hc_cbacks)
-    {
-        ALOGE("vendor lib postload aborted");
-        bt_hc_cbacks->postload_cb(NULL, BT_HC_POSTLOAD_FAIL);
-    }
-}
-
-
-/******************************************************************************
-**  HCI H4 Services interface table
-******************************************************************************/
-
-const tHCI_IF hci_h4_func_table =
-{
-    hci_h4_init,
-    hci_h4_cleanup,
-    hci_h4_send_msg,
-    hci_h4_send_int_cmd,
-    hci_h4_get_acl_data_length,
-    hci_h4_receive_msg
-};
-
diff --git a/test/suite/support/property.h b/hci/src/hci_hal.c
similarity index 60%
copy from test/suite/support/property.h
copy to hci/src/hci_hal.c
index a8b77c7..fa526ce 100644
--- a/test/suite/support/property.h
+++ b/hci/src/hci_hal.c
@@ -16,17 +16,13 @@
  *
  ******************************************************************************/
 
-#pragma once
+#include "hci_hal.h"
 
-#include "base.h"
+const hci_hal_t *hci_hal_get_interface() {
+#if HCI_USE_MCT
+  return hci_hal_mct_get_interface();
+#else
+  return hci_hal_h4_get_interface();
+#endif
+}
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
-
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
diff --git a/hci/src/hci_hal_h4.c b/hci/src/hci_hal_h4.c
new file mode 100644
index 0000000..368b1aa
--- /dev/null
+++ b/hci/src/hci_hal_h4.c
@@ -0,0 +1,205 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_hci_h4"
+
+#include <assert.h>
+
+#include "osi/include/eager_reader.h"
+#include "hci_hal.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/reactor.h"
+#include "vendor.h"
+
+#define HCI_HAL_SERIAL_BUFFER_SIZE 1026
+
+// Our interface and modules we import
+static const hci_hal_t interface;
+static const hci_hal_callbacks_t *callbacks;
+static const vendor_t *vendor;
+
+static thread_t *thread; // Not owned by us
+
+static int uart_fd;
+static eager_reader_t *uart_stream;
+static serial_data_type_t current_data_type;
+static bool stream_has_interpretation;
+
+static void event_uart_has_bytes(eager_reader_t *reader, void *context);
+
+// Interface functions
+
+static bool hal_init(const hci_hal_callbacks_t *upper_callbacks, thread_t *upper_thread) {
+  assert(upper_callbacks != NULL);
+  assert(upper_thread != NULL);
+
+  callbacks = upper_callbacks;
+  thread = upper_thread;
+  return true;
+}
+
+static bool hal_open() {
+  LOG_INFO("%s", __func__);
+  // TODO(zachoverflow): close if already open / or don't reopen (maybe at the hci layer level)
+
+  int fd_array[CH_MAX];
+  int number_of_ports = vendor->send_command(VENDOR_OPEN_USERIAL, &fd_array);
+
+  if (number_of_ports != 1) {
+    LOG_ERROR("%s opened the wrong number of ports: got %d, expected 1.", __func__, number_of_ports);
+    goto error;
+  }
+
+  uart_fd = fd_array[0];
+  if (uart_fd == INVALID_FD) {
+    LOG_ERROR("%s unable to open the uart serial port.", __func__);
+    goto error;
+  }
+
+  uart_stream = eager_reader_new(uart_fd, &allocator_malloc, HCI_HAL_SERIAL_BUFFER_SIZE, SIZE_MAX, "hci_single_channel");
+  if (!uart_stream) {
+    LOG_ERROR("%s unable to create eager reader for the uart serial port.", __func__);
+    goto error;
+  }
+
+  stream_has_interpretation = false;
+  eager_reader_register(uart_stream, thread_get_reactor(thread), event_uart_has_bytes, NULL);
+
+  return true;
+
+error:
+  interface.close();
+  return false;
+}
+
+static void hal_close() {
+  LOG_INFO("%s", __func__);
+
+  eager_reader_free(uart_stream);
+  vendor->send_command(VENDOR_CLOSE_USERIAL, NULL);
+  uart_fd = INVALID_FD;
+}
+
+static size_t read_data(serial_data_type_t type, uint8_t *buffer, size_t max_size, bool block) {
+  if (type < DATA_TYPE_ACL || type > DATA_TYPE_EVENT) {
+    LOG_ERROR("%s invalid data type: %d", __func__, type);
+    return 0;
+  } else if (!stream_has_interpretation) {
+    LOG_ERROR("%s with no valid stream intepretation.", __func__);
+    return 0;
+  } else if (current_data_type != type) {
+    LOG_ERROR("%s with different type than existing interpretation.", __func__);
+    return 0;
+  }
+
+  return eager_reader_read(uart_stream, buffer, max_size, block);
+}
+
+static void packet_finished(serial_data_type_t type) {
+  if (!stream_has_interpretation)
+    LOG_ERROR("%s with no existing stream interpretation.", __func__);
+  else if (current_data_type != type)
+    LOG_ERROR("%s with different type than existing interpretation.", __func__);
+
+  stream_has_interpretation = false;
+}
+
+static uint16_t transmit_data(serial_data_type_t type, uint8_t *data, uint16_t length) {
+  assert(data != NULL);
+  assert(length > 0);
+
+  if (type < DATA_TYPE_COMMAND || type > DATA_TYPE_SCO) {
+    LOG_ERROR("%s invalid data type: %d", __func__, type);
+    return 0;
+  }
+
+  // Write the signal byte right before the data
+  --data;
+  uint8_t previous_byte = *data;
+  *(data) = type;
+  ++length;
+
+  uint16_t transmitted_length = 0;
+  while (length > 0) {
+    ssize_t ret = write(uart_fd, data + transmitted_length, length);
+    switch (ret) {
+      case -1:
+        LOG_ERROR("In %s, error writing to the uart serial port: %s", __func__, strerror(errno));
+        goto done;
+      case 0:
+        // If we wrote nothing, don't loop more because we
+        // can't go to infinity or beyond
+        goto done;
+      default:
+        transmitted_length += ret;
+        length -= ret;
+        break;
+    }
+  }
+
+done:;
+  // Be nice and restore the old value of that byte
+  *(data) = previous_byte;
+
+  // Remove the signal byte from our transmitted length, if it was actually written
+  if (transmitted_length > 0)
+    --transmitted_length;
+
+  return transmitted_length;
+}
+
+// Internal functions
+
+// See what data is waiting, and notify the upper layer
+static void event_uart_has_bytes(eager_reader_t *reader, UNUSED_ATTR void *context) {
+  if (stream_has_interpretation) {
+    callbacks->data_ready(current_data_type);
+  } else {
+    uint8_t type_byte;
+    eager_reader_read(reader, &type_byte, 1, true);
+    if (type_byte < DATA_TYPE_ACL || type_byte > DATA_TYPE_EVENT) {
+      LOG_ERROR("[h4] Unknown HCI message type. Dropping this byte 0x%x, min %x, max %x", type_byte, DATA_TYPE_ACL, DATA_TYPE_EVENT);
+      return;
+    }
+
+    stream_has_interpretation = true;
+    current_data_type = type_byte;
+  }
+}
+
+static const hci_hal_t interface = {
+  hal_init,
+
+  hal_open,
+  hal_close,
+
+  read_data,
+  packet_finished,
+  transmit_data,
+};
+
+const hci_hal_t *hci_hal_h4_get_interface() {
+  vendor = vendor_get_interface();
+  return &interface;
+}
+
+const hci_hal_t *hci_hal_h4_get_test_interface(vendor_t *vendor_interface) {
+  vendor = vendor_interface;
+  return &interface;
+}
diff --git a/hci/src/hci_hal_mct.c b/hci/src/hci_hal_mct.c
new file mode 100644
index 0000000..d831e93
--- /dev/null
+++ b/hci/src/hci_hal_mct.c
@@ -0,0 +1,207 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_hci_mct"
+
+#include <assert.h>
+
+#include "bt_vendor_lib.h"
+#include "osi/include/eager_reader.h"
+#include "hci_hal.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/reactor.h"
+#include "vendor.h"
+
+#define HCI_HAL_SERIAL_BUFFER_SIZE 1026
+
+// Our interface and modules we import
+static const hci_hal_t interface;
+static const hci_hal_callbacks_t *callbacks;
+static const vendor_t *vendor;
+
+static thread_t *thread; // Not owned by us
+
+static int uart_fds[CH_MAX];
+static eager_reader_t *event_stream;
+static eager_reader_t *acl_stream;
+
+static uint16_t transmit_data_on(int fd, uint8_t *data, uint16_t length);
+static void event_event_stream_has_bytes(eager_reader_t *reader, void *context);
+static void event_acl_stream_has_bytes(eager_reader_t *reader, void *context);
+
+// Interface functions
+
+static bool hal_init(const hci_hal_callbacks_t *upper_callbacks, thread_t *upper_thread) {
+  assert(upper_callbacks != NULL);
+  assert(upper_thread != NULL);
+
+  callbacks = upper_callbacks;
+  thread = upper_thread;
+  return true;
+}
+
+static bool hal_open() {
+  LOG_INFO("%s", __func__);
+  // TODO(zachoverflow): close if already open / or don't reopen (maybe at the hci layer level)
+
+  int number_of_ports = vendor->send_command(VENDOR_OPEN_USERIAL, &uart_fds);
+
+  if (number_of_ports != 2 && number_of_ports != 4) {
+    LOG_ERROR("%s opened the wrong number of ports: got %d, expected 2 or 4.", __func__, number_of_ports);
+    goto error;
+  }
+
+  LOG_INFO("%s got uart fds: CMD=%d, EVT=%d, ACL_OUT=%d, ACL_IN=%d",
+      __func__, uart_fds[CH_CMD], uart_fds[CH_EVT], uart_fds[CH_ACL_OUT], uart_fds[CH_ACL_IN]);
+
+  if (uart_fds[CH_CMD] == INVALID_FD) {
+    LOG_ERROR("%s unable to open the command uart serial port.", __func__);
+    goto error;
+  }
+
+  if (uart_fds[CH_EVT] == INVALID_FD) {
+    LOG_ERROR("%s unable to open the event uart serial port.", __func__);
+    goto error;
+  }
+
+  if (uart_fds[CH_ACL_OUT] == INVALID_FD) {
+    LOG_ERROR("%s unable to open the acl-out uart serial port.", __func__);
+    goto error;
+  }
+
+  if (uart_fds[CH_ACL_IN] == INVALID_FD) {
+    LOG_ERROR("%s unable to open the acl-in uart serial port.", __func__);
+    goto error;
+  }
+
+  event_stream = eager_reader_new(uart_fds[CH_EVT], &allocator_malloc, HCI_HAL_SERIAL_BUFFER_SIZE, SIZE_MAX, "hci_mct");
+  if (!event_stream) {
+    LOG_ERROR("%s unable to create eager reader for the event uart serial port.", __func__);
+    goto error;
+  }
+
+  acl_stream = eager_reader_new(uart_fds[CH_ACL_IN], &allocator_malloc, HCI_HAL_SERIAL_BUFFER_SIZE, SIZE_MAX, "hci_mct");
+  if (!event_stream) {
+    LOG_ERROR("%s unable to create eager reader for the acl-in uart serial port.", __func__);
+    goto error;
+  }
+
+  eager_reader_register(event_stream, thread_get_reactor(thread), event_event_stream_has_bytes, NULL);
+  eager_reader_register(acl_stream, thread_get_reactor(thread), event_acl_stream_has_bytes, NULL);
+
+  return true;
+
+error:;
+  interface.close();
+  return false;
+}
+
+static void hal_close() {
+  LOG_INFO("%s", __func__);
+
+  eager_reader_free(event_stream);
+  eager_reader_free(acl_stream);
+  vendor->send_command(VENDOR_CLOSE_USERIAL, NULL);
+
+  for (int i = 0; i < CH_MAX; i++)
+    uart_fds[i] = INVALID_FD;
+}
+
+static size_t read_data(serial_data_type_t type, uint8_t *buffer, size_t max_size, bool block) {
+  if (type == DATA_TYPE_ACL) {
+    return eager_reader_read(acl_stream, buffer, max_size, block);
+  } else if (type == DATA_TYPE_EVENT) {
+    return eager_reader_read(event_stream, buffer, max_size, block);
+  }
+
+  LOG_ERROR("%s invalid data type: %d", __func__, type);
+  return 0;
+}
+
+static void packet_finished(UNUSED_ATTR serial_data_type_t type) {
+  // not needed by this protocol
+}
+
+static uint16_t transmit_data(serial_data_type_t type, uint8_t *data, uint16_t length) {
+  if (type == DATA_TYPE_ACL) {
+    return transmit_data_on(uart_fds[CH_ACL_OUT], data, length);
+  } else if (type == DATA_TYPE_COMMAND) {
+    return transmit_data_on(uart_fds[CH_CMD], data, length);
+  }
+
+  LOG_ERROR("%s invalid data type: %d", __func__, type);
+  return 0;
+}
+
+// Internal functions
+
+static uint16_t transmit_data_on(int fd, uint8_t *data, uint16_t length) {
+  assert(data != NULL);
+  assert(length > 0);
+
+  uint16_t transmitted_length = 0;
+  while (length > 0) {
+    ssize_t ret = write(fd, data + transmitted_length, length);
+    switch (ret) {
+      case -1:
+        LOG_ERROR("In %s, error writing to the serial port with fd %d: %s", __func__, fd, strerror(errno));
+        return transmitted_length;
+      case 0:
+        // If we wrote nothing, don't loop more because we
+        // can't go to infinity or beyond
+        return transmitted_length;
+      default:
+        transmitted_length += ret;
+        length -= ret;
+        break;
+    }
+  }
+
+  return transmitted_length;
+}
+
+static void event_event_stream_has_bytes(UNUSED_ATTR eager_reader_t *reader, UNUSED_ATTR void *context) {
+  callbacks->data_ready(DATA_TYPE_EVENT);
+}
+
+static void event_acl_stream_has_bytes(UNUSED_ATTR eager_reader_t *reader, UNUSED_ATTR void *context) {
+  // No real concept of incoming SCO typed data, just ACL
+  callbacks->data_ready(DATA_TYPE_ACL);
+}
+
+static const hci_hal_t interface = {
+  hal_init,
+
+  hal_open,
+  hal_close,
+
+  read_data,
+  packet_finished,
+  transmit_data,
+};
+
+const hci_hal_t *hci_hal_mct_get_interface() {
+  vendor = vendor_get_interface();
+  return &interface;
+}
+
+const hci_hal_t *hci_hal_mct_get_test_interface(vendor_t *vendor_interface) {
+  vendor = vendor_interface;
+  return &interface;
+}
diff --git a/hci/src/hci_inject.c b/hci/src/hci_inject.c
new file mode 100644
index 0000000..0ec4f82
--- /dev/null
+++ b/hci/src/hci_inject.c
@@ -0,0 +1,204 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_hci_inject"
+
+#include <assert.h>
+#include <errno.h>
+
+#include "osi/include/allocator.h"
+#include "bt_types.h"
+#include "buffer_allocator.h"
+#include "hci_inject.h"
+#include "hci_layer.h"
+#include "osi/include/list.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/socket.h"
+#include "osi/include/thread.h"
+
+typedef enum {
+  HCI_PACKET_COMMAND  = 1,
+  HCI_PACKET_ACL_DATA = 2,
+  HCI_PACKET_SCO_DATA = 3,
+  HCI_PACKET_EVENT    = 4,
+} hci_packet_t;
+
+typedef struct {
+  socket_t *socket;
+  uint8_t buffer[65536 + 3];  // 2 bytes length prefix, 1 byte type prefix.
+  size_t buffer_size;
+} client_t;
+
+static const port_t LISTEN_PORT = 8873;
+
+static const hci_inject_t interface;
+static const hci_t *hci;
+static const allocator_t *buffer_allocator;
+static socket_t *listen_socket;
+static thread_t *thread;
+static list_t *clients;
+
+static int hci_packet_to_event(hci_packet_t packet);
+static void accept_ready(socket_t *socket, void *context);
+static void read_ready(socket_t *socket, void *context);
+static void client_free(void *ptr);
+
+bool hci_inject_open(const hci_t *hci_interface) {
+  assert(listen_socket == NULL);
+  assert(thread == NULL);
+  assert(clients == NULL);
+  assert(hci_interface != NULL);
+
+  hci = hci_interface;
+
+  thread = thread_new("hci_inject");
+  if (!thread)
+    goto error;
+
+  clients = list_new(client_free);
+  if (!clients)
+    goto error;
+
+  listen_socket = socket_new();
+  if (!listen_socket)
+    goto error;
+
+  if (!socket_listen(listen_socket, LISTEN_PORT))
+    goto error;
+
+  socket_register(listen_socket, thread_get_reactor(thread), NULL, accept_ready, NULL);
+  return true;
+
+error:;
+  interface.close();
+  return false;
+}
+
+void hci_inject_close(void) {
+  socket_free(listen_socket);
+  list_free(clients);
+  thread_free(thread);
+
+  listen_socket = NULL;
+  thread = NULL;
+  clients = NULL;
+}
+
+static int hci_packet_to_event(hci_packet_t packet) {
+  switch (packet) {
+    case HCI_PACKET_COMMAND:
+      return MSG_STACK_TO_HC_HCI_CMD;
+    case HCI_PACKET_ACL_DATA:
+      return MSG_STACK_TO_HC_HCI_ACL;
+    case HCI_PACKET_SCO_DATA:
+      return MSG_STACK_TO_HC_HCI_SCO;
+    default:
+      LOG_ERROR("%s unsupported packet type: %d", __func__, packet);
+      return -1;
+  }
+}
+
+static void accept_ready(socket_t *socket, UNUSED_ATTR void *context) {
+  assert(socket != NULL);
+  assert(socket == listen_socket);
+
+  socket = socket_accept(socket);
+  if (!socket)
+    return;
+
+  client_t *client = (client_t *)osi_calloc(sizeof(client_t));
+  if (!client) {
+    LOG_ERROR("%s unable to allocate memory for client.", __func__);
+    socket_free(socket);
+    return;
+  }
+
+  client->socket = socket;
+
+  if (!list_append(clients, client)) {
+    LOG_ERROR("%s unable to add client to list.", __func__);
+    client_free(client);
+    return;
+  }
+
+  socket_register(socket, thread_get_reactor(thread), client, read_ready, NULL);
+}
+
+static void read_ready(UNUSED_ATTR socket_t *socket, void *context) {
+  assert(socket != NULL);
+  assert(context != NULL);
+
+  client_t *client = (client_t *)context;
+
+  ssize_t ret = socket_read(client->socket, client->buffer + client->buffer_size, sizeof(client->buffer) - client->buffer_size);
+  if (ret == 0 || (ret == -1 && ret != EWOULDBLOCK && ret != EAGAIN)) {
+    list_remove(clients, client);
+    return;
+  }
+  client->buffer_size += ret;
+
+  while (client->buffer_size > 3) {
+    uint8_t *buffer = client->buffer;
+    hci_packet_t packet_type = (hci_packet_t)buffer[0];
+    size_t packet_len = (buffer[2] << 8) | buffer[1];
+    size_t frame_len = 3 + packet_len;
+
+    if (client->buffer_size < frame_len)
+      break;
+
+    // TODO(sharvil): validate incoming HCI messages.
+    // TODO(sharvil): once we have an HCI parser, we can eliminate
+    //   the 2-byte size field since it will be contained in the packet.
+
+    BT_HDR *buf = (BT_HDR *)buffer_allocator->alloc(packet_len);
+    if (buf) {
+      buf->event = hci_packet_to_event(packet_type);
+      buf->offset = 0;
+      buf->layer_specific = 0;
+      buf->len = packet_len;
+      memcpy(buf->data, buffer + 3, packet_len);
+      hci->transmit_downward(buf->event, buf);
+    } else {
+      LOG_ERROR("%s dropping injected packet of length %zu", __func__, packet_len);
+    }
+
+    size_t remainder = client->buffer_size - frame_len;
+    memmove(buffer, buffer + frame_len, remainder);
+    client->buffer_size -= frame_len;
+  }
+}
+
+static void client_free(void *ptr) {
+  if (!ptr)
+    return;
+
+  client_t *client = (client_t *)ptr;
+  socket_free(client->socket);
+  osi_free(client);
+}
+
+static const hci_inject_t interface = {
+  hci_inject_open,
+  hci_inject_close
+};
+
+const hci_inject_t *hci_inject_get_interface() {
+  buffer_allocator = buffer_allocator_get_interface();
+  return &interface;
+}
diff --git a/hci/src/hci_layer.c b/hci/src/hci_layer.c
new file mode 100644
index 0000000..e78f468
--- /dev/null
+++ b/hci/src/hci_layer.c
@@ -0,0 +1,803 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_hci"
+
+#include <assert.h>
+#include <cutils/properties.h>
+
+#include "buffer_allocator.h"
+#include "btsnoop.h"
+#include "osi/include/fixed_queue.h"
+#include "osi/include/future.h"
+#include "hcidefs.h"
+#include "hcimsgs.h"
+#include "hci_hal.h"
+#include "hci_internals.h"
+#include "hci_inject.h"
+#include "hci_layer.h"
+#include "osi/include/list.h"
+#include "low_power_manager.h"
+#include "btcore/include/module.h"
+#include "osi/include/non_repeating_timer.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "packet_fragmenter.h"
+#include "osi/include/reactor.h"
+#include "vendor.h"
+
+// TODO(zachoverflow): remove this hack extern
+#include <hardware/bluetooth.h>
+bt_bdaddr_t btif_local_bd_addr;
+
+#define INBOUND_PACKET_TYPE_COUNT 3
+#define PACKET_TYPE_TO_INBOUND_INDEX(type) ((type) - 2)
+#define PACKET_TYPE_TO_INDEX(type) ((type) - 1)
+
+#define PREAMBLE_BUFFER_SIZE 4 // max preamble size, ACL
+#define RETRIEVE_ACL_LENGTH(preamble) ((((preamble)[3]) << 8) | (preamble)[2])
+
+static const uint8_t preamble_sizes[] = {
+  HCI_COMMAND_PREAMBLE_SIZE,
+  HCI_ACL_PREAMBLE_SIZE,
+  HCI_SCO_PREAMBLE_SIZE,
+  HCI_EVENT_PREAMBLE_SIZE
+};
+
+static const uint16_t outbound_event_types[] =
+{
+  MSG_HC_TO_STACK_HCI_ERR,
+  MSG_HC_TO_STACK_HCI_ACL,
+  MSG_HC_TO_STACK_HCI_SCO,
+  MSG_HC_TO_STACK_HCI_EVT
+};
+
+typedef enum {
+  BRAND_NEW,
+  PREAMBLE,
+  BODY,
+  IGNORE,
+  FINISHED
+} receive_state_t;
+
+typedef struct {
+  receive_state_t state;
+  uint16_t bytes_remaining;
+  uint8_t preamble[PREAMBLE_BUFFER_SIZE];
+  uint16_t index;
+  BT_HDR *buffer;
+} packet_receive_data_t;
+
+typedef struct {
+  uint16_t opcode;
+  future_t *complete_future;
+  command_complete_cb complete_callback;
+  command_status_cb status_callback;
+  void *context;
+  BT_HDR *command;
+} waiting_command_t;
+
+// Using a define here, because it can be stringified for the property lookup
+#define DEFAULT_STARTUP_TIMEOUT_MS 8000
+#define STRING_VALUE_OF(x) #x
+
+static const uint32_t EPILOG_TIMEOUT_MS = 3000;
+static const uint32_t COMMAND_PENDING_TIMEOUT = 8000;
+
+// Our interface
+static bool interface_created;
+static hci_t interface;
+
+// Modules we import and callbacks we export
+static const allocator_t *buffer_allocator;
+static const btsnoop_t *btsnoop;
+static const hci_hal_t *hal;
+static const hci_hal_callbacks_t hal_callbacks;
+static const hci_inject_t *hci_inject;
+static const low_power_manager_t *low_power_manager;
+static const packet_fragmenter_t *packet_fragmenter;
+static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks;
+static const vendor_t *vendor;
+
+static future_t *startup_future;
+static thread_t *thread; // We own this
+
+static volatile bool firmware_is_configured = false;
+static non_repeating_timer_t *epilog_timer;
+static non_repeating_timer_t *startup_timer;
+
+// Outbound-related
+static int command_credits = 1;
+static fixed_queue_t *command_queue;
+static fixed_queue_t *packet_queue;
+
+// Inbound-related
+static non_repeating_timer_t *command_response_timer;
+static list_t *commands_pending_response;
+static pthread_mutex_t commands_pending_response_lock;
+static packet_receive_data_t incoming_packets[INBOUND_PACKET_TYPE_COUNT];
+
+// The hand-off point for data going to a higher layer, set by the higher layer
+static fixed_queue_t *upwards_data_queue;
+
+static future_t *shut_down();
+
+static void event_finish_startup(void *context);
+static void firmware_config_callback(bool success);
+static void startup_timer_expired(void *context);
+
+static void event_postload(void *context);
+static void sco_config_callback(bool success);
+
+static void event_epilog(void *context);
+static void epilog_finished_callback(bool success);
+static void epilog_timer_expired(void *context);
+
+static void event_command_ready(fixed_queue_t *queue, void *context);
+static void event_packet_ready(fixed_queue_t *queue, void *context);
+static void command_timed_out(void *context);
+
+static void hal_says_data_ready(serial_data_type_t type);
+static bool filter_incoming_event(BT_HDR *packet);
+
+static serial_data_type_t event_to_data_type(uint16_t event);
+static waiting_command_t *get_waiting_command(command_opcode_t opcode);
+
+// Module lifecycle functions
+
+static future_t *start_up(void) {
+  LOG_INFO("%s", __func__);
+
+  // The host is only allowed to send at most one command initially,
+  // as per the Bluetooth spec, Volume 2, Part E, 4.4 (Command Flow Control)
+  // This value can change when you get a command complete or command status event.
+  command_credits = 1;
+  firmware_is_configured = false;
+
+  pthread_mutex_init(&commands_pending_response_lock, NULL);
+
+  // Grab the override startup timeout ms, if present.
+  period_ms_t startup_timeout_ms;
+  char timeout_prop[PROPERTY_VALUE_MAX];
+  if (!property_get("bluetooth.enable_timeout_ms", timeout_prop, STRING_VALUE_OF(DEFAULT_STARTUP_TIMEOUT_MS))
+      || (startup_timeout_ms = atoi(timeout_prop)) < 100)
+    startup_timeout_ms = DEFAULT_STARTUP_TIMEOUT_MS;
+
+  startup_timer = non_repeating_timer_new(startup_timeout_ms, startup_timer_expired, NULL);
+  if (!startup_timer) {
+    LOG_ERROR("%s unable to create startup timer.", __func__);
+    goto error;
+  }
+
+  // Make sure we run in a bounded amount of time
+  non_repeating_timer_restart(startup_timer);
+
+  epilog_timer = non_repeating_timer_new(EPILOG_TIMEOUT_MS, epilog_timer_expired, NULL);
+  if (!epilog_timer) {
+    LOG_ERROR("%s unable to create epilog timer.", __func__);
+    goto error;
+  }
+
+  command_response_timer = non_repeating_timer_new(COMMAND_PENDING_TIMEOUT, command_timed_out, NULL);
+  if (!command_response_timer) {
+    LOG_ERROR("%s unable to create command response timer.", __func__);
+    goto error;
+  }
+
+  command_queue = fixed_queue_new(SIZE_MAX);
+  if (!command_queue) {
+    LOG_ERROR("%s unable to create pending command queue.", __func__);
+    goto error;
+  }
+
+  packet_queue = fixed_queue_new(SIZE_MAX);
+  if (!packet_queue) {
+    LOG_ERROR("%s unable to create pending packet queue.", __func__);
+    goto error;
+  }
+
+  thread = thread_new("hci_thread");
+  if (!thread) {
+    LOG_ERROR("%s unable to create thread.", __func__);
+    goto error;
+  }
+
+  commands_pending_response = list_new(NULL);
+  if (!commands_pending_response) {
+    LOG_ERROR("%s unable to create list for commands pending response.", __func__);
+    goto error;
+  }
+
+  memset(incoming_packets, 0, sizeof(incoming_packets));
+
+  packet_fragmenter->init(&packet_fragmenter_callbacks);
+
+  fixed_queue_register_dequeue(command_queue, thread_get_reactor(thread), event_command_ready, NULL);
+  fixed_queue_register_dequeue(packet_queue, thread_get_reactor(thread), event_packet_ready, NULL);
+
+  vendor->open(btif_local_bd_addr.address, &interface);
+  hal->init(&hal_callbacks, thread);
+  low_power_manager->init(thread);
+
+  vendor->set_callback(VENDOR_CONFIGURE_FIRMWARE, firmware_config_callback);
+  vendor->set_callback(VENDOR_CONFIGURE_SCO, sco_config_callback);
+  vendor->set_callback(VENDOR_DO_EPILOG, epilog_finished_callback);
+
+  if (!hci_inject->open(&interface)) {
+    // TODO(sharvil): gracefully propagate failures from this layer.
+  }
+
+  int power_state = BT_VND_PWR_OFF;
+#if (defined (BT_CLEAN_TURN_ON_DISABLED) && BT_CLEAN_TURN_ON_DISABLED == TRUE)
+  LOG_WARN("%s not turning off the chip before turning on.", __func__);
+  // So apparently this hack was needed in the past because a Wingray kernel driver
+  // didn't handle power off commands in a powered off state correctly.
+
+  // The comment in the old code said the workaround should be removed when the
+  // problem was fixed. Sadly, I have no idea if said bug was fixed or if said
+  // kernel is still in use, so we must leave this here for posterity. #sadpanda
+#else
+  // cycle power on the chip to ensure it has been reset
+  vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);
+#endif
+  power_state = BT_VND_PWR_ON;
+  vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);
+
+  startup_future = future_new();
+  LOG_DEBUG("%s starting async portion", __func__);
+  thread_post(thread, event_finish_startup, NULL);
+  return startup_future;
+error:;
+  shut_down(); // returns NULL so no need to wait for it
+  return future_new_immediate(FUTURE_FAIL);
+}
+
+static future_t *shut_down() {
+  LOG_INFO("%s", __func__);
+
+  hci_inject->close();
+
+  if (thread) {
+    if (firmware_is_configured) {
+      non_repeating_timer_restart(epilog_timer);
+      thread_post(thread, event_epilog, NULL);
+    } else {
+      thread_stop(thread);
+    }
+
+    thread_join(thread);
+  }
+
+  fixed_queue_free(command_queue, buffer_allocator->free);
+  fixed_queue_free(packet_queue, buffer_allocator->free);
+  list_free(commands_pending_response);
+
+  pthread_mutex_destroy(&commands_pending_response_lock);
+
+  packet_fragmenter->cleanup();
+
+  non_repeating_timer_free(epilog_timer);
+  non_repeating_timer_free(command_response_timer);
+  non_repeating_timer_free(startup_timer);
+
+  epilog_timer = NULL;
+  command_response_timer = NULL;
+
+  low_power_manager->cleanup();
+  hal->close();
+
+  // Turn off the chip
+  int power_state = BT_VND_PWR_OFF;
+  vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);
+  vendor->close();
+
+  thread_free(thread);
+  thread = NULL;
+  firmware_is_configured = false;
+
+  return NULL;
+}
+
+const module_t hci_module = {
+  .name = HCI_MODULE,
+  .init = NULL,
+  .start_up = start_up,
+  .shut_down = shut_down,
+  .clean_up = NULL,
+  .dependencies = {
+    BTSNOOP_MODULE,
+    NULL
+  }
+};
+
+// Interface functions
+
+static void do_postload() {
+  LOG_DEBUG("%s posting postload work item", __func__);
+  thread_post(thread, event_postload, NULL);
+}
+
+static void set_data_queue(fixed_queue_t *queue) {
+  upwards_data_queue = queue;
+}
+
+static void transmit_command(
+    BT_HDR *command,
+    command_complete_cb complete_callback,
+    command_status_cb status_callback,
+    void *context) {
+  waiting_command_t *wait_entry = osi_calloc(sizeof(waiting_command_t));
+  if (!wait_entry) {
+    LOG_ERROR("%s couldn't allocate space for wait entry.", __func__);
+    return;
+  }
+
+  uint8_t *stream = command->data + command->offset;
+  STREAM_TO_UINT16(wait_entry->opcode, stream);
+  wait_entry->complete_callback = complete_callback;
+  wait_entry->status_callback = status_callback;
+  wait_entry->command = command;
+  wait_entry->context = context;
+
+  // Store the command message type in the event field
+  // in case the upper layer didn't already
+  command->event = MSG_STACK_TO_HC_HCI_CMD;
+
+  fixed_queue_enqueue(command_queue, wait_entry);
+}
+
+static future_t *transmit_command_futured(BT_HDR *command) {
+  waiting_command_t *wait_entry = osi_calloc(sizeof(waiting_command_t));
+  assert(wait_entry != NULL);
+
+  future_t *future = future_new();
+
+  uint8_t *stream = command->data + command->offset;
+  STREAM_TO_UINT16(wait_entry->opcode, stream);
+  wait_entry->complete_future = future;
+  wait_entry->command = command;
+
+  // Store the command message type in the event field
+  // in case the upper layer didn't already
+  command->event = MSG_STACK_TO_HC_HCI_CMD;
+
+  fixed_queue_enqueue(command_queue, wait_entry);
+  return future;
+}
+
+static void transmit_downward(data_dispatcher_type_t type, void *data) {
+  if (type == MSG_STACK_TO_HC_HCI_CMD) {
+    // TODO(zachoverflow): eliminate this call
+    transmit_command((BT_HDR *)data, NULL, NULL, NULL);
+    LOG_WARN("%s legacy transmit of command. Use transmit_command instead.", __func__);
+  } else {
+    fixed_queue_enqueue(packet_queue, data);
+  }
+}
+
+// Start up functions
+
+static void event_finish_startup(UNUSED_ATTR void *context) {
+  LOG_INFO("%s", __func__);
+  hal->open();
+  vendor->send_async_command(VENDOR_CONFIGURE_FIRMWARE, NULL);
+}
+
+static void firmware_config_callback(UNUSED_ATTR bool success) {
+  LOG_INFO("%s", __func__);
+  firmware_is_configured = true;
+  non_repeating_timer_cancel(startup_timer);
+
+  future_ready(startup_future, FUTURE_SUCCESS);
+  startup_future = NULL;
+}
+
+static void startup_timer_expired(UNUSED_ATTR void *context) {
+  LOG_ERROR("%s", __func__);
+  future_ready(startup_future, FUTURE_FAIL);
+  startup_future = NULL;
+}
+
+// Postload functions
+
+static void event_postload(UNUSED_ATTR void *context) {
+  LOG_INFO("%s", __func__);
+  if(vendor->send_async_command(VENDOR_CONFIGURE_SCO, NULL) == -1) {
+    // If couldn't configure sco, we won't get the sco configuration callback
+    // so go pretend to do it now
+    sco_config_callback(false);
+
+  }
+}
+
+static void sco_config_callback(UNUSED_ATTR bool success) {
+  LOG_INFO("%s postload finished.", __func__);
+}
+
+// Epilog functions
+
+static void event_epilog(UNUSED_ATTR void *context) {
+  vendor->send_async_command(VENDOR_DO_EPILOG, NULL);
+}
+
+static void epilog_finished_callback(UNUSED_ATTR bool success) {
+  LOG_INFO("%s", __func__);
+  thread_stop(thread);
+}
+
+static void epilog_timer_expired(UNUSED_ATTR void *context) {
+  LOG_INFO("%s", __func__);
+  thread_stop(thread);
+}
+
+// Command/packet transmitting functions
+
+static void event_command_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
+  if (command_credits > 0) {
+    waiting_command_t *wait_entry = fixed_queue_dequeue(queue);
+    command_credits--;
+
+    // Move it to the list of commands awaiting response
+    pthread_mutex_lock(&commands_pending_response_lock);
+    list_append(commands_pending_response, wait_entry);
+    pthread_mutex_unlock(&commands_pending_response_lock);
+
+    // Send it off
+    low_power_manager->wake_assert();
+    packet_fragmenter->fragment_and_dispatch(wait_entry->command);
+    low_power_manager->transmit_done();
+
+    non_repeating_timer_restart_if(command_response_timer, !list_is_empty(commands_pending_response));
+  }
+}
+
+static void event_packet_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
+  // The queue may be the command queue or the packet queue, we don't care
+  BT_HDR *packet = (BT_HDR *)fixed_queue_dequeue(queue);
+
+  low_power_manager->wake_assert();
+  packet_fragmenter->fragment_and_dispatch(packet);
+  low_power_manager->transmit_done();
+}
+
+// Callback for the fragmenter to send a fragment
+static void transmit_fragment(BT_HDR *packet, bool send_transmit_finished) {
+  uint16_t event = packet->event & MSG_EVT_MASK;
+  serial_data_type_t type = event_to_data_type(event);
+
+  btsnoop->capture(packet, false);
+  hal->transmit_data(type, packet->data + packet->offset, packet->len);
+
+  if (event != MSG_STACK_TO_HC_HCI_CMD && send_transmit_finished)
+    buffer_allocator->free(packet);
+}
+
+static void fragmenter_transmit_finished(BT_HDR *packet, bool all_fragments_sent) {
+  if (all_fragments_sent) {
+    buffer_allocator->free(packet);
+  } else {
+    // This is kind of a weird case, since we're dispatching a partially sent packet
+    // up to a higher layer.
+    // TODO(zachoverflow): rework upper layer so this isn't necessary.
+    data_dispatcher_dispatch(interface.event_dispatcher, packet->event & MSG_EVT_MASK, packet);
+  }
+}
+
+static void command_timed_out(UNUSED_ATTR void *context) {
+  pthread_mutex_lock(&commands_pending_response_lock);
+
+  if (list_is_empty(commands_pending_response)) {
+    LOG_ERROR("%s with no commands pending response", __func__);
+  } else {
+    waiting_command_t *wait_entry = list_front(commands_pending_response);
+    pthread_mutex_unlock(&commands_pending_response_lock);
+
+    // We shouldn't try to recover the stack from this command timeout.
+    // If it's caused by a software bug, fix it. If it's a hardware bug, fix it.
+    LOG_ERROR("%s hci layer timeout waiting for response to a command. opcode: 0x%x", __func__, wait_entry->opcode);
+  }
+
+  LOG_ERROR("%s restarting the bluetooth process.", __func__);
+  usleep(10000);
+  kill(getpid(), SIGKILL);
+}
+
+// Event/packet receiving functions
+
+// This function is not required to read all of a packet in one go, so
+// be wary of reentry. But this function must return after finishing a packet.
+static void hal_says_data_ready(serial_data_type_t type) {
+  packet_receive_data_t *incoming = &incoming_packets[PACKET_TYPE_TO_INBOUND_INDEX(type)];
+
+  uint8_t byte;
+  while (hal->read_data(type, &byte, 1, false) != 0) {
+    switch (incoming->state) {
+      case BRAND_NEW:
+        // Initialize and prepare to jump to the preamble reading state
+        incoming->bytes_remaining = preamble_sizes[PACKET_TYPE_TO_INDEX(type)];
+        memset(incoming->preamble, 0, PREAMBLE_BUFFER_SIZE);
+        incoming->index = 0;
+        incoming->state = PREAMBLE;
+        // INTENTIONAL FALLTHROUGH
+      case PREAMBLE:
+        incoming->preamble[incoming->index] = byte;
+        incoming->index++;
+        incoming->bytes_remaining--;
+
+        if (incoming->bytes_remaining == 0) {
+          // For event and sco preambles, the last byte we read is the length
+          incoming->bytes_remaining = (type == DATA_TYPE_ACL) ? RETRIEVE_ACL_LENGTH(incoming->preamble) : byte;
+
+          size_t buffer_size = BT_HDR_SIZE + incoming->index + incoming->bytes_remaining;
+          incoming->buffer = (BT_HDR *)buffer_allocator->alloc(buffer_size);
+
+          if (!incoming->buffer) {
+            LOG_ERROR("%s error getting buffer for incoming packet of type %d and size %d", __func__, type, buffer_size);
+            // Can't read any more of this current packet, so jump out
+            incoming->state = incoming->bytes_remaining == 0 ? BRAND_NEW : IGNORE;
+            break;
+          }
+
+          // Initialize the buffer
+          incoming->buffer->offset = 0;
+          incoming->buffer->layer_specific = 0;
+          incoming->buffer->event = outbound_event_types[PACKET_TYPE_TO_INDEX(type)];
+          memcpy(incoming->buffer->data, incoming->preamble, incoming->index);
+
+          incoming->state = incoming->bytes_remaining > 0 ? BODY : FINISHED;
+        }
+
+        break;
+      case BODY:
+        incoming->buffer->data[incoming->index] = byte;
+        incoming->index++;
+        incoming->bytes_remaining--;
+
+        size_t bytes_read = hal->read_data(type, (incoming->buffer->data + incoming->index), incoming->bytes_remaining, false);
+        incoming->index += bytes_read;
+        incoming->bytes_remaining -= bytes_read;
+
+        incoming->state = incoming->bytes_remaining == 0 ? FINISHED : incoming->state;
+        break;
+      case IGNORE:
+        incoming->bytes_remaining--;
+        if (incoming->bytes_remaining == 0) {
+          incoming->state = BRAND_NEW;
+          // Don't forget to let the hal know we finished the packet we were ignoring.
+          // Otherwise we'll get out of sync with hals that embed extra information
+          // in the uart stream (like H4). #badnewsbears
+          hal->packet_finished(type);
+          return;
+        }
+
+        break;
+      case FINISHED:
+        LOG_ERROR("%s the state machine should not have been left in the finished state.", __func__);
+        break;
+    }
+
+    if (incoming->state == FINISHED) {
+      incoming->buffer->len = incoming->index;
+      btsnoop->capture(incoming->buffer, true);
+
+      if (type != DATA_TYPE_EVENT) {
+        packet_fragmenter->reassemble_and_dispatch(incoming->buffer);
+      } else if (!filter_incoming_event(incoming->buffer)) {
+        // Dispatch the event by event code
+        uint8_t *stream = incoming->buffer->data;
+        uint8_t event_code;
+        STREAM_TO_UINT8(event_code, stream);
+
+        data_dispatcher_dispatch(
+          interface.event_dispatcher,
+          event_code,
+          incoming->buffer
+        );
+      }
+
+      // We don't control the buffer anymore
+      incoming->buffer = NULL;
+      incoming->state = BRAND_NEW;
+      hal->packet_finished(type);
+
+      // We return after a packet is finished for two reasons:
+      // 1. The type of the next packet could be different.
+      // 2. We don't want to hog cpu time.
+      return;
+    }
+  }
+}
+
+// Returns true if the event was intercepted and should not proceed to
+// higher layers. Also inspects an incoming event for interesting
+// information, like how many commands are now able to be sent.
+static bool filter_incoming_event(BT_HDR *packet) {
+  waiting_command_t *wait_entry = NULL;
+  uint8_t *stream = packet->data;
+  uint8_t event_code;
+  command_opcode_t opcode;
+
+  STREAM_TO_UINT8(event_code, stream);
+  STREAM_SKIP_UINT8(stream); // Skip the parameter total length field
+
+  if (event_code == HCI_COMMAND_COMPLETE_EVT) {
+    STREAM_TO_UINT8(command_credits, stream);
+    STREAM_TO_UINT16(opcode, stream);
+
+    wait_entry = get_waiting_command(opcode);
+    if (!wait_entry)
+      LOG_WARN("%s command complete event with no matching command. opcode: 0x%x.", __func__, opcode);
+    else if (wait_entry->complete_callback)
+      wait_entry->complete_callback(packet, wait_entry->context);
+    else if (wait_entry->complete_future)
+      future_ready(wait_entry->complete_future, packet);
+
+    goto intercepted;
+  } else if (event_code == HCI_COMMAND_STATUS_EVT) {
+    uint8_t status;
+    STREAM_TO_UINT8(status, stream);
+    STREAM_TO_UINT8(command_credits, stream);
+    STREAM_TO_UINT16(opcode, stream);
+
+    // If a command generates a command status event, it won't be getting a command complete event
+
+    wait_entry = get_waiting_command(opcode);
+    if (!wait_entry)
+      LOG_WARN("%s command status event with no matching command. opcode: 0x%x", __func__, opcode);
+    else if (wait_entry->status_callback)
+      wait_entry->status_callback(status, wait_entry->command, wait_entry->context);
+
+    goto intercepted;
+  }
+
+  return false;
+intercepted:;
+  non_repeating_timer_restart_if(command_response_timer, !list_is_empty(commands_pending_response));
+
+  if (wait_entry) {
+    // If it has a callback, it's responsible for freeing the packet
+    if (event_code == HCI_COMMAND_STATUS_EVT || (!wait_entry->complete_callback && !wait_entry->complete_future))
+      buffer_allocator->free(packet);
+
+    // If it has a callback, it's responsible for freeing the command
+    if (event_code == HCI_COMMAND_COMPLETE_EVT || !wait_entry->status_callback)
+      buffer_allocator->free(wait_entry->command);
+
+    osi_free(wait_entry);
+  } else {
+    buffer_allocator->free(packet);
+  }
+
+  return true;
+}
+
+// Callback for the fragmenter to dispatch up a completely reassembled packet
+static void dispatch_reassembled(BT_HDR *packet) {
+  // Events should already have been dispatched before this point
+  assert((packet->event & MSG_EVT_MASK) != MSG_HC_TO_STACK_HCI_EVT);
+  assert(upwards_data_queue != NULL);
+
+  if (upwards_data_queue) {
+    fixed_queue_enqueue(upwards_data_queue, packet);
+  } else {
+    LOG_ERROR("%s had no queue to place upwards data packet in. Dropping it on the floor.", __func__);
+    buffer_allocator->free(packet);
+  }
+}
+
+// Misc internal functions
+
+// TODO(zachoverflow): we seem to do this a couple places, like the HCI inject module. #centralize
+static serial_data_type_t event_to_data_type(uint16_t event) {
+  if (event == MSG_STACK_TO_HC_HCI_ACL)
+    return DATA_TYPE_ACL;
+  else if (event == MSG_STACK_TO_HC_HCI_SCO)
+    return DATA_TYPE_SCO;
+  else if (event == MSG_STACK_TO_HC_HCI_CMD)
+    return DATA_TYPE_COMMAND;
+  else
+    LOG_ERROR("%s invalid event type, could not translate 0x%x", __func__, event);
+
+  return 0;
+}
+
+static waiting_command_t *get_waiting_command(command_opcode_t opcode) {
+  pthread_mutex_lock(&commands_pending_response_lock);
+
+  for (const list_node_t *node = list_begin(commands_pending_response);
+      node != list_end(commands_pending_response);
+      node = list_next(node)) {
+    waiting_command_t *wait_entry = list_node(node);
+
+    if (!wait_entry || wait_entry->opcode != opcode)
+      continue;
+
+    list_remove(commands_pending_response, wait_entry);
+
+    pthread_mutex_unlock(&commands_pending_response_lock);
+    return wait_entry;
+  }
+
+  pthread_mutex_unlock(&commands_pending_response_lock);
+  return NULL;
+}
+
+static void init_layer_interface() {
+  if (!interface_created) {
+    interface.send_low_power_command = low_power_manager->post_command;
+    interface.do_postload = do_postload;
+
+    // It's probably ok for this to live forever. It's small and
+    // there's only one instance of the hci interface.
+    interface.event_dispatcher = data_dispatcher_new("hci_layer");
+    if (!interface.event_dispatcher) {
+      LOG_ERROR("%s could not create upward dispatcher.", __func__);
+      return;
+    }
+
+    interface.set_data_queue = set_data_queue;
+    interface.transmit_command = transmit_command;
+    interface.transmit_command_futured = transmit_command_futured;
+    interface.transmit_downward = transmit_downward;
+    interface_created = true;
+  }
+}
+
+static const hci_hal_callbacks_t hal_callbacks = {
+  hal_says_data_ready
+};
+
+static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = {
+  transmit_fragment,
+  dispatch_reassembled,
+  fragmenter_transmit_finished
+};
+
+const hci_t *hci_layer_get_interface() {
+  buffer_allocator = buffer_allocator_get_interface();
+  hal = hci_hal_get_interface();
+  btsnoop = btsnoop_get_interface();
+  hci_inject = hci_inject_get_interface();
+  packet_fragmenter = packet_fragmenter_get_interface();
+  vendor = vendor_get_interface();
+  low_power_manager = low_power_manager_get_interface();
+
+  init_layer_interface();
+  return &interface;
+}
+
+const hci_t *hci_layer_get_test_interface(
+    const allocator_t *buffer_allocator_interface,
+    const hci_hal_t *hal_interface,
+    const btsnoop_t *btsnoop_interface,
+    const hci_inject_t *hci_inject_interface,
+    const packet_fragmenter_t *packet_fragmenter_interface,
+    const vendor_t *vendor_interface,
+    const low_power_manager_t *low_power_manager_interface) {
+
+  buffer_allocator = buffer_allocator_interface;
+  hal = hal_interface;
+  btsnoop = btsnoop_interface;
+  hci_inject = hci_inject_interface;
+  packet_fragmenter = packet_fragmenter_interface;
+  vendor = vendor_interface;
+  low_power_manager = low_power_manager_interface;
+
+  init_layer_interface();
+  return &interface;
+}
diff --git a/hci/src/hci_mct.c b/hci/src/hci_mct.c
deleted file mode 100644
index 5316326..0000000
--- a/hci/src/hci_mct.c
+++ /dev/null
@@ -1,1167 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Filename:      hci_mct.c
- *
- *  Description:   Contains HCI transport send/receive functions
- *                 for Multi-Channels Transport
- *
- ******************************************************************************/
-
-#define LOG_TAG "bt_mct"
-
-#include <utils/Log.h>
-#include <stdlib.h>
-#include <fcntl.h>
-
-#include "bt_hci_bdroid.h"
-#include "btsnoop.h"
-#include "hci.h"
-#include "userial.h"
-#include "utils.h"
-#include "vendor.h"
-
-/******************************************************************************
-**  Constants & Macros
-******************************************************************************/
-
-#ifndef HCI_DBG
-#define HCI_DBG FALSE
-#endif
-
-#if (HCI_DBG == TRUE)
-#define HCIDBG(param, ...) {LOGD(param, ## __VA_ARGS__);}
-#else
-#define HCIDBG(param, ...) {}
-#endif
-
-/* Preamble length for HCI Commands:
-**      2-bytes for opcode and 1 byte for length
-*/
-#define HCI_CMD_PREAMBLE_SIZE   3
-
-/* Preamble length for HCI Events:
-**      1-byte for opcode and 1 byte for length
-*/
-#define HCI_EVT_PREAMBLE_SIZE   2
-
-/* Preamble length for SCO Data:
-**      2-byte for Handle and 1 byte for length
-*/
-#define HCI_SCO_PREAMBLE_SIZE   3
-
-/* Preamble length for ACL Data:
-**      2-byte for Handle and 2 byte for length
-*/
-#define HCI_ACL_PREAMBLE_SIZE   4
-
-#define ACL_RX_PKT_START        2
-#define ACL_RX_PKT_CONTINUE     1
-#define L2CAP_HEADER_SIZE       4
-
-/* Maximum numbers of allowed internal
-** outstanding command packets at any time
-*/
-#define INT_CMD_PKT_MAX_COUNT       8
-#define INT_CMD_PKT_IDX_MASK        0x07
-
-#define HCI_COMMAND_COMPLETE_EVT    0x0E
-#define HCI_COMMAND_STATUS_EVT      0x0F
-#define HCI_READ_BUFFER_SIZE        0x1005
-#define HCI_LE_READ_BUFFER_SIZE     0x2002
-
-/******************************************************************************
-**  Local type definitions
-******************************************************************************/
-
-/* MCT Rx States */
-typedef enum {
-    MCT_RX_NEWMSG_ST,
-    MCT_RX_LEN_ST,
-    MCT_RX_DATA_ST,
-    MCT_RX_IGNORE_ST
-} tHCI_MCT_RCV_STATE;
-
-/* Callback function for the returned event of internal issued command */
-typedef void (*tINT_CMD_CBACK)(void *p_mem);
-
-typedef struct
-{
-    uint16_t opcode;        /* OPCODE of outstanding internal commands */
-    tINT_CMD_CBACK cback;   /* Callback function when return of internal
-                             * command is received */
-} tINT_CMD_Q;
-
-typedef struct
-{
-    HC_BT_HDR *p_rcv_msg;          /* Buffer to hold current rx HCI message */
-    uint16_t rcv_len;               /* Size of current incoming message */
-    tHCI_MCT_RCV_STATE rcv_state;   /* Receive state of current rx message */
-    uint8_t preload_count;          /* Count numbers of preload bytes */
-    uint8_t preload_buffer[6];      /* HCI_ACL_PREAMBLE_SIZE + 2 */
-} tHCI_RCV_CB;
-
-/* Control block for HCISU_MCT */
-typedef struct
-{
-    tHCI_RCV_CB rcv_evt;
-    tHCI_RCV_CB rcv_acl;
-    uint16_t hc_acl_data_size;      /* Controller's max ACL data length */
-    uint16_t hc_ble_acl_data_size;  /* Controller's max BLE ACL data length */
-    BUFFER_Q acl_rx_q;      /* Queue of base buffers for fragmented ACL pkts */
-    int int_cmd_rsp_pending;        /* Num of internal cmds pending for ack */
-    uint8_t int_cmd_rd_idx;         /* Read index of int_cmd_opcode queue */
-    uint8_t int_cmd_wrt_idx;        /* Write index of int_cmd_opcode queue */
-    tINT_CMD_Q int_cmd[INT_CMD_PKT_MAX_COUNT]; /* FIFO queue */
-} tHCI_MCT_CB;
-
-/******************************************************************************
-**  Externs
-******************************************************************************/
-
-uint8_t hci_mct_send_int_cmd(uint16_t opcode, HC_BT_HDR *p_buf, \
-                                  tINT_CMD_CBACK p_cback);
-void lpm_wake_assert(void);
-void lpm_tx_done(uint8_t is_tx_done);
-
-/******************************************************************************
-**  Variables
-******************************************************************************/
-
-/* Num of allowed outstanding HCI CMD packets */
-volatile int num_hci_cmd_pkts = 1;
-
-/******************************************************************************
-**  Static variables
-******************************************************************************/
-
-static tHCI_MCT_CB       mct_cb;
-
-/******************************************************************************
-**  Static functions
-******************************************************************************/
-
-/*******************************************************************************
-**
-** Function         get_acl_data_length_cback
-**
-** Description      Callback function for HCI_READ_BUFFER_SIZE and
-**                  HCI_LE_READ_BUFFER_SIZE commands if they were sent because
-**                  of internal request.
-**
-** Returns          None
-**
-*******************************************************************************/
-void get_acl_data_length_cback(void *p_mem)
-{
-    uint8_t     *p, status;
-    uint16_t    opcode, len=0;
-    HC_BT_HDR   *p_buf = (HC_BT_HDR *) p_mem;
-
-    p = (uint8_t *)(p_buf + 1) + 3;
-    STREAM_TO_UINT16(opcode, p)
-    status = *p++;
-    if (status == 0) /* Success */
-        STREAM_TO_UINT16(len, p)
-
-    if (opcode == HCI_READ_BUFFER_SIZE)
-    {
-        if (status == 0)
-            mct_cb.hc_acl_data_size = len;
-
-        /* reuse the rx buffer for sending HCI_LE_READ_BUFFER_SIZE command */
-        p_buf->event = MSG_STACK_TO_HC_HCI_CMD;
-        p_buf->offset = 0;
-        p_buf->layer_specific = 0;
-        p_buf->len = 3;
-
-        p = (uint8_t *) (p_buf + 1);
-        UINT16_TO_STREAM(p, HCI_LE_READ_BUFFER_SIZE);
-        *p = 0;
-
-        if ((status = hci_mct_send_int_cmd(HCI_LE_READ_BUFFER_SIZE, p_buf, \
-                                           get_acl_data_length_cback)) == FALSE)
-        {
-            bt_hc_cbacks->dealloc(p_buf);
-            bt_hc_cbacks->postload_cb(NULL, BT_HC_POSTLOAD_SUCCESS);
-        }
-    }
-    else if (opcode == HCI_LE_READ_BUFFER_SIZE)
-    {
-        if (status == 0)
-            mct_cb.hc_ble_acl_data_size = (len) ? len : mct_cb.hc_acl_data_size;
-
-        if (bt_hc_cbacks)
-        {
-            bt_hc_cbacks->dealloc(p_buf);
-            ALOGE("hci lib postload completed");
-            bt_hc_cbacks->postload_cb(NULL, BT_HC_POSTLOAD_SUCCESS);
-        }
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         internal_event_intercept
-**
-** Description      This function is called to parse received HCI event and
-**                  - update the Num_HCI_Command_Packets
-**                  - intercept the event if it is the result of an early
-**                    issued internal command.
-**
-** Returns          TRUE : if the event had been intercepted for internal process
-**                  FALSE : send this event to core stack
-**
-*******************************************************************************/
-uint8_t internal_event_intercept(void)
-{
-    uint8_t     *p;
-    uint8_t     event_code;
-    uint16_t    opcode, len;
-    tHCI_MCT_CB *p_cb = &mct_cb;
-
-    p = (uint8_t *)(p_cb->rcv_evt.p_rcv_msg + 1);
-
-    event_code = *p++;
-    len = *p++;
-
-    if (event_code == HCI_COMMAND_COMPLETE_EVT)
-    {
-        utils_lock();
-        num_hci_cmd_pkts = *p++;
-        utils_unlock();
-
-        // Signal TX event so the worker thread can check if it has anything
-        // to send
-        bthc_tx(NULL);
-
-        if (p_cb->int_cmd_rsp_pending > 0)
-        {
-            STREAM_TO_UINT16(opcode, p)
-
-            if (opcode == p_cb->int_cmd[p_cb->int_cmd_rd_idx].opcode)
-            {
-                HCIDBG( \
-                "Intercept CommandCompleteEvent for internal command (0x%04X)",\
-                          opcode);
-                if (p_cb->int_cmd[p_cb->int_cmd_rd_idx].cback != NULL)
-                {
-                    p_cb->int_cmd[p_cb->int_cmd_rd_idx].cback(p_cb->rcv_evt.p_rcv_msg);
-                }
-                else
-                {
-                    // Missing cback function!
-                    // Release the p_rcv_msg buffer.
-                    if (bt_hc_cbacks)
-                    {
-                        bt_hc_cbacks->dealloc(p_cb->rcv_evt.p_rcv_msg);
-                    }
-                }
-                p_cb->int_cmd_rd_idx = ((p_cb->int_cmd_rd_idx+1) & \
-                                        INT_CMD_PKT_IDX_MASK);
-                p_cb->int_cmd_rsp_pending--;
-                return TRUE;
-            }
-        }
-    }
-    else if (event_code == HCI_COMMAND_STATUS_EVT)
-    {
-        utils_lock();
-        num_hci_cmd_pkts = *(++p);
-        utils_unlock();
-
-        // Signal TX event so the worker thread can check if it has anything
-        // to send
-        bthc_tx(NULL);
-    }
-
-    return FALSE;
-}
-
-/*******************************************************************************
-**
-** Function         acl_rx_frame_buffer_alloc
-**
-** Description      This function is called from the HCI transport when the
-**                  first 4 or 6 bytes of an HCI ACL packet have been received:
-**                  - Allocate a new buffer if it is a start pakcet of L2CAP
-**                    message.
-**                  - Return the buffer address of the starting L2CAP message
-**                    frame if the packet is the next segment of a fragmented
-**                    L2CAP message.
-**
-** Returns          the address of the receive buffer caller should use
-**                  (CR419: Modified to return NULL in case of error.)
-**
-** NOTE             This assumes that the L2CAP MTU size is less than the size
-**                  of an HCI ACL buffer, so the maximum L2CAP message will fit
-**                  into one buffer.
-**
-*******************************************************************************/
-static HC_BT_HDR *acl_rx_frame_buffer_alloc (void)
-{
-    uint8_t     *p;
-    uint16_t    handle;
-    uint16_t    hci_len;
-    uint16_t    total_len;
-    uint8_t     pkt_type;
-    HC_BT_HDR  *p_return_buf = NULL;
-    tHCI_MCT_CB  *p_cb = &mct_cb;
-
-
-    p = p_cb->rcv_acl.preload_buffer;
-
-    STREAM_TO_UINT16 (handle, p);
-    STREAM_TO_UINT16 (hci_len, p);
-    STREAM_TO_UINT16 (total_len, p);
-
-    pkt_type = (uint8_t)(((handle) >> 12) & 0x0003);
-    handle   = (uint16_t)((handle) & 0x0FFF);
-
-    if (p_cb->acl_rx_q.count)
-    {
-        uint16_t save_handle;
-        HC_BT_HDR *p_hdr = p_cb->acl_rx_q.p_first;
-
-        while (p_hdr != NULL)
-        {
-            p = (uint8_t *)(p_hdr + 1);
-            STREAM_TO_UINT16 (save_handle, p);
-            save_handle   = (uint16_t)((save_handle) & 0x0FFF);
-            if (save_handle == handle)
-            {
-                p_return_buf = p_hdr;
-                break;
-            }
-            p_hdr = utils_getnext(p_hdr);
-        }
-    }
-
-    if (pkt_type == ACL_RX_PKT_START)       /*** START PACKET ***/
-    {
-        /* Might have read 2 bytes for the L2CAP payload length */
-        p_cb->rcv_acl.rcv_len = (hci_len) ? (hci_len - 2) : 0;
-
-        /* Start of packet. If we were in the middle of receiving */
-        /* a packet on the same ACL handle, the original packet is incomplete.
-         * Drop it. */
-        if (p_return_buf)
-        {
-            ALOGW("dropping incomplete ACL frame");
-
-            utils_remove_from_queue(&(p_cb->acl_rx_q), p_return_buf);
-
-            if (bt_hc_cbacks)
-            {
-                bt_hc_cbacks->dealloc(p_return_buf);
-            }
-            p_return_buf = NULL;
-        }
-
-        /* Allocate a buffer for message */
-        if (bt_hc_cbacks)
-        {
-            int len = total_len + HCI_ACL_PREAMBLE_SIZE + L2CAP_HEADER_SIZE + \
-                      BT_HC_HDR_SIZE;
-            p_return_buf = (HC_BT_HDR *) bt_hc_cbacks->alloc(len);
-        }
-
-        if (p_return_buf)
-        {
-            /* Initialize buffer with preloaded data */
-            p_return_buf->offset = 0;
-            p_return_buf->layer_specific = 0;
-            p_return_buf->event = MSG_HC_TO_STACK_HCI_ACL;
-            p_return_buf->len = p_cb->rcv_acl.preload_count;
-            memcpy((uint8_t *)(p_return_buf + 1), p_cb->rcv_acl.preload_buffer, \
-                   p_cb->rcv_acl.preload_count);
-
-            if (hci_len && ((total_len + L2CAP_HEADER_SIZE) > hci_len))
-            {
-                /* Will expect to see fragmented ACL packets */
-                /* Keep the base buffer address in the watching queue */
-                utils_enqueue(&(p_cb->acl_rx_q), p_return_buf);
-            }
-        }
-    }
-    else                                    /*** CONTINUATION PACKET ***/
-    {
-        p_cb->rcv_acl.rcv_len = hci_len;
-
-        if (p_return_buf)
-        {
-            /* Packet continuation and found the original rx buffer */
-            uint8_t *p_f = p = (uint8_t *)(p_return_buf + 1) + 2;
-
-            STREAM_TO_UINT16 (total_len, p);
-
-            /* Update HCI header of first segment (base buffer) with new len */
-            total_len += hci_len;
-            UINT16_TO_STREAM (p_f, total_len);
-        }
-    }
-
-    return (p_return_buf);
-}
-
-/*******************************************************************************
-**
-** Function         acl_rx_frame_end_chk
-**
-** Description      This function is called from the HCI transport when the last
-**                  byte of an HCI ACL packet has been received. It checks if
-**                  the L2CAP message is complete, i.e. no more continuation
-**                  packets are expected.
-**
-** Returns          TRUE if message complete, FALSE if continuation expected
-**
-*******************************************************************************/
-static uint8_t acl_rx_frame_end_chk (void)
-{
-    uint8_t     *p;
-    uint16_t    handle, hci_len, l2cap_len;
-    HC_BT_HDR  *p_buf;
-    tHCI_MCT_CB  *p_cb = &mct_cb;
-    uint8_t     frame_end=TRUE;
-
-    p_buf = p_cb->rcv_acl.p_rcv_msg;
-    p = (uint8_t *)(p_buf + 1);
-
-    STREAM_TO_UINT16 (handle, p);
-    STREAM_TO_UINT16 (hci_len, p);
-    STREAM_TO_UINT16 (l2cap_len, p);
-
-    if (hci_len > 0)
-    {
-        if (l2cap_len > (p_buf->len-(HCI_ACL_PREAMBLE_SIZE+L2CAP_HEADER_SIZE)) )
-        {
-            /* If the L2CAP length has not been reached, tell caller not to send
-             * this buffer to stack */
-            frame_end = FALSE;
-        }
-        else
-        {
-            /*
-             * The current buffer coulb be in the watching list.
-             * Remove it from the list if it is in.
-             */
-            if (p_cb->acl_rx_q.count)
-                utils_remove_from_queue(&(p_cb->acl_rx_q), p_buf);
-        }
-    }
-
-    /****
-     ** Print snoop trace
-     ****/
-    if (p_buf->offset)
-    {
-        /* CONTINUATION PACKET */
-
-        /* save original p_buf->len content */
-        uint16_t tmp_u16 = p_buf->len;
-
-        /* borrow HCI_ACL_PREAMBLE_SIZE bytes from the payload section */
-        p = (uint8_t *)(p_buf + 1) + p_buf->offset - HCI_ACL_PREAMBLE_SIZE;
-
-        /* save contents */
-        memcpy(p_cb->rcv_acl.preload_buffer, p, HCI_ACL_PREAMBLE_SIZE);
-
-        /* Set packet boundary flags to "continuation packet" */
-        handle = (handle & 0xCFFF) | 0x1000;
-
-        /* write handl & length info */
-        UINT16_TO_STREAM (p, handle);
-        UINT16_TO_STREAM (p, (p_buf->len - p_buf->offset));
-
-        /* roll pointer back */
-        p = p - HCI_ACL_PREAMBLE_SIZE;
-
-        /* adjust `p_buf->offset` & `p_buf->len`
-         * before calling btsnoop_capture() */
-        p_buf->offset = p_buf->offset - HCI_ACL_PREAMBLE_SIZE;
-        p_buf->len = p_buf->len - p_buf->offset;
-
-        btsnoop_capture(p_buf, true);
-
-        /* restore contents */
-        memcpy(p, p_cb->rcv_acl.preload_buffer, HCI_ACL_PREAMBLE_SIZE);
-
-        /* restore p_buf->len */
-        p_buf->len = tmp_u16;
-    }
-    else
-    {
-        /* START PACKET */
-        btsnoop_capture(p_buf, true);
-    }
-
-    if (frame_end == TRUE)
-        p_buf->offset = 0;
-    else
-        p_buf->offset = p_buf->len; /* save current buffer-end position */
-
-    return frame_end;
-}
-
-/*****************************************************************************
-**   HCI MCT INTERFACE FUNCTIONS
-*****************************************************************************/
-
-/*******************************************************************************
-**
-** Function        hci_mct_init
-**
-** Description     Initialize MCT module
-**
-** Returns         None
-**
-*******************************************************************************/
-void hci_mct_init(void)
-{
-    HCIDBG("hci_mct_init");
-
-    memset(&mct_cb, 0, sizeof(tHCI_MCT_CB));
-    utils_queue_init(&(mct_cb.acl_rx_q));
-
-    /* Per HCI spec., always starts with 1 */
-    num_hci_cmd_pkts = 1;
-
-    /* Give an initial values of Host Controller's ACL data packet length
-     * Will update with an internal HCI(_LE)_Read_Buffer_Size request
-     */
-    mct_cb.hc_acl_data_size = 1021;
-    mct_cb.hc_ble_acl_data_size = 27;
-}
-
-/*******************************************************************************
-**
-** Function        hci_mct_cleanup
-**
-** Description     Clean MCT module
-**
-** Returns         None
-**
-*******************************************************************************/
-void hci_mct_cleanup(void)
-{
-    HCIDBG("hci_mct_cleanup");
-}
-
-/*******************************************************************************
-**
-** Function        hci_mct_send_msg
-**
-** Description     Determine message type, then send message through according
-**                 channel
-**
-** Returns         None
-**
-*******************************************************************************/
-void hci_mct_send_msg(HC_BT_HDR *p_msg)
-{
-    uint16_t handle;
-    uint16_t lay_spec;
-    uint8_t *p = ((uint8_t *)(p_msg + 1)) + p_msg->offset;
-    uint16_t event = p_msg->event & MSG_EVT_MASK;
-    uint16_t sub_event = p_msg->event & MSG_SUB_EVT_MASK;
-    uint16_t acl_pkt_size = 0, acl_data_size = 0;
-
-    /* wake up BT device if its in sleep mode */
-    lpm_wake_assert();
-
-    if (sub_event == LOCAL_BR_EDR_CONTROLLER_ID)
-    {
-        acl_data_size = mct_cb.hc_acl_data_size;
-        acl_pkt_size = mct_cb.hc_acl_data_size + HCI_ACL_PREAMBLE_SIZE;
-    }
-    else
-    {
-        acl_data_size = mct_cb.hc_ble_acl_data_size;
-        acl_pkt_size = mct_cb.hc_ble_acl_data_size + HCI_ACL_PREAMBLE_SIZE;
-    }
-
-    /* Check if sending ACL data that needs fragmenting */
-    if ((event == MSG_STACK_TO_HC_HCI_ACL) && (p_msg->len > acl_pkt_size))
-    {
-        /* Get the handle from the packet */
-        STREAM_TO_UINT16 (handle, p);
-
-        /* Set packet boundary flags to "continuation packet" */
-        handle = (handle & 0xCFFF) | 0x1000;
-
-        /* Do all the first chunks */
-        while (p_msg->len > acl_pkt_size)
-        {
-            p = ((uint8_t *)(p_msg + 1)) + p_msg->offset;
-
-            userial_write(event, (uint8_t *) p, acl_pkt_size);
-
-            /* generate snoop trace message */
-            btsnoop_capture(p_msg, false);
-
-            /* Adjust offset and length for what we just sent */
-            p_msg->offset += acl_data_size;
-            p_msg->len    -= acl_data_size;
-
-            p = ((uint8_t *)(p_msg + 1)) + p_msg->offset;
-
-            UINT16_TO_STREAM (p, handle);
-
-            if (p_msg->len > acl_pkt_size)
-            {
-                UINT16_TO_STREAM (p, acl_data_size);
-            }
-            else
-            {
-                UINT16_TO_STREAM (p, p_msg->len - HCI_ACL_PREAMBLE_SIZE);
-            }
-
-            /* If we were only to send partial buffer, stop when done.    */
-            /* Send the buffer back to L2CAP to send the rest of it later */
-            if (p_msg->layer_specific)
-            {
-                if (--p_msg->layer_specific == 0)
-                {
-                    p_msg->event = MSG_HC_TO_STACK_L2C_SEG_XMIT;
-
-                    if (bt_hc_cbacks)
-                    {
-                        bt_hc_cbacks->tx_result((TRANSAC) p_msg, \
-                                                    (char *) (p_msg + 1), \
-                                                    BT_HC_TX_FRAGMENT);
-                    }
-
-                    return;
-                }
-            }
-        }
-    }
-
-    p = ((uint8_t *)(p_msg + 1)) + p_msg->offset;
-
-    if (event == MSG_STACK_TO_HC_HCI_CMD)
-    {
-        uint8_t *p_tmp = p;
-
-        utils_lock();
-        num_hci_cmd_pkts--;
-        utils_unlock();
-
-        /* If this is an internal Cmd packet, the layer_specific field would
-         * have stored with the opcode of HCI command.
-         * Retrieve the opcode from the Cmd packet.
-         */
-        p_tmp++;
-        STREAM_TO_UINT16(lay_spec, p_tmp);
-    }
-
-    userial_write(event, (uint8_t *) p, p_msg->len);
-
-
-    /* generate snoop trace message */
-    btsnoop_capture(p_msg, false);
-
-    if (bt_hc_cbacks)
-    {
-        if ((event == MSG_STACK_TO_HC_HCI_CMD) && \
-            (mct_cb.int_cmd_rsp_pending > 0) && \
-            (p_msg->layer_specific == lay_spec))
-        {
-            /* dealloc buffer of internal command */
-            bt_hc_cbacks->dealloc(p_msg);
-        }
-        else
-        {
-            bt_hc_cbacks->tx_result((TRANSAC) p_msg, (char *) (p_msg + 1), \
-                                        BT_HC_TX_SUCCESS);
-        }
-    }
-
-    lpm_tx_done(TRUE);
-
-    return;
-}
-
-
-/*******************************************************************************
-**
-** Function        hci_mct_receive_evt_msg
-**
-** Description     Construct HCI EVENT packet
-**
-** Returns         Number of read bytes
-**
-*******************************************************************************/
-uint16_t hci_mct_receive_evt_msg(void)
-{
-    uint16_t    bytes_read = 0;
-    uint8_t     byte;
-    uint16_t    msg_len, len;
-    uint8_t     msg_received;
-    tHCI_RCV_CB  *p_cb=&mct_cb.rcv_evt;
-    uint8_t     continue_fetch_looping = TRUE;
-
-    while (continue_fetch_looping)
-    {
-        /* Read one byte to see if there is anything waiting to be read */
-        if (userial_read(MSG_HC_TO_STACK_HCI_EVT, &byte, 1) == 0)
-        {
-            break;
-        }
-
-        bytes_read++;
-        msg_received = FALSE;
-
-        switch (p_cb->rcv_state)
-        {
-        case MCT_RX_NEWMSG_ST:
-            /* Start of new message */
-            /* Initialize rx parameters */
-            memset(p_cb->preload_buffer, 0 , 6);
-            p_cb->preload_buffer[0] = byte;
-            p_cb->preload_count = 1;
-            p_cb->rcv_len = HCI_EVT_PREAMBLE_SIZE - 1;
-            // p_cb->p_rcv_msg = NULL;
-            p_cb->rcv_state = MCT_RX_LEN_ST; /* Next, wait for length to come */
-            break;
-
-        case MCT_RX_LEN_ST:
-            /* Receiving preamble */
-            p_cb->preload_buffer[p_cb->preload_count++] = byte;
-            p_cb->rcv_len--;
-
-            /* Check if we received entire preamble yet */
-            if (p_cb->rcv_len == 0)
-            {
-                /* Received entire preamble.
-                 * Length is in the last received byte */
-                msg_len = byte;
-                p_cb->rcv_len = msg_len;
-
-                /* Allocate a buffer for message */
-                if (bt_hc_cbacks)
-                {
-                    len = msg_len + p_cb->preload_count + BT_HC_HDR_SIZE;
-                    p_cb->p_rcv_msg = \
-                        (HC_BT_HDR *) bt_hc_cbacks->alloc(len);
-                }
-
-                if (p_cb->p_rcv_msg)
-                {
-                    /* Initialize buffer with preloaded data */
-                    p_cb->p_rcv_msg->offset = 0;
-                    p_cb->p_rcv_msg->layer_specific = 0;
-                    p_cb->p_rcv_msg->event = MSG_HC_TO_STACK_HCI_EVT;
-                    p_cb->p_rcv_msg->len = p_cb->preload_count;
-                    memcpy((uint8_t *)(p_cb->p_rcv_msg + 1), \
-                           p_cb->preload_buffer, p_cb->preload_count);
-                }
-                else
-                {
-                    /* Unable to acquire message buffer. */
-                    ALOGE( \
-                     "Unable to acquire buffer for incoming HCI message." \
-                    );
-
-                    if (msg_len == 0)
-                    {
-                        /* Wait for next message */
-                        p_cb->rcv_state = MCT_RX_NEWMSG_ST;
-                        continue_fetch_looping = FALSE;
-                    }
-                    else
-                    {
-                        /* Ignore rest of the packet */
-                        p_cb->rcv_state = MCT_RX_IGNORE_ST;
-                    }
-
-                    break;
-                }
-
-                /* Message length is valid */
-                if (msg_len)
-                {
-                    /* Read rest of message */
-                    p_cb->rcv_state = MCT_RX_DATA_ST;
-                }
-                else
-                {
-                    /* Message has no additional parameters.
-                     * (Entire message has been received) */
-                    msg_received = TRUE;
-
-                    /* Next, wait for next message */
-                    p_cb->rcv_state = MCT_RX_NEWMSG_ST;
-                    continue_fetch_looping = FALSE;
-                }
-            }
-            break;
-
-        case MCT_RX_DATA_ST:
-            *((uint8_t *)(p_cb->p_rcv_msg + 1) + p_cb->p_rcv_msg->len++) = byte;
-            p_cb->rcv_len--;
-
-            if (p_cb->rcv_len > 0)
-            {
-                /* Read in the rest of the message */
-                len = userial_read(MSG_HC_TO_STACK_HCI_EVT, \
-                      ((uint8_t *)(p_cb->p_rcv_msg+1) + p_cb->p_rcv_msg->len), \
-                      p_cb->rcv_len);
-                p_cb->p_rcv_msg->len += len;
-                p_cb->rcv_len -= len;
-                bytes_read += len;
-            }
-
-            /* Check if we read in entire message yet */
-            if (p_cb->rcv_len == 0)
-            {
-                /* Received entire packet. */
-                msg_received = TRUE;
-                /* Next, wait for next message */
-                p_cb->rcv_state = MCT_RX_NEWMSG_ST;
-                continue_fetch_looping = FALSE;
-            }
-            break;
-
-
-        case MCT_RX_IGNORE_ST:
-            /* Ignore reset of packet */
-            p_cb->rcv_len--;
-
-            /* Check if we read in entire message yet */
-            if (p_cb->rcv_len == 0)
-            {
-                /* Next, wait for next message */
-                p_cb->rcv_state = MCT_RX_NEWMSG_ST;
-                continue_fetch_looping = FALSE;
-            }
-            break;
-        }
-
-
-        /* If we received entire message, then send it to the task */
-        if (msg_received)
-        {
-            uint8_t intercepted = FALSE;
-
-            /* generate snoop trace message */
-            btsnoop_capture(p_cb->p_rcv_msg, true);
-
-            intercepted = internal_event_intercept();
-
-            if ((bt_hc_cbacks) && (intercepted == FALSE))
-            {
-                bt_hc_cbacks->data_ind((TRANSAC) p_cb->p_rcv_msg, \
-                                       (char *) (p_cb->p_rcv_msg + 1), \
-                                       p_cb->p_rcv_msg->len + BT_HC_HDR_SIZE);
-            }
-            p_cb->p_rcv_msg = NULL;
-        }
-    }
-
-    return (bytes_read);
-}
-
-
-/*******************************************************************************
-**
-** Function        hci_mct_receive_acl_msg
-**
-** Description     Construct HCI ACL packet
-**
-** Returns         Number of read bytes
-**
-*******************************************************************************/
-uint16_t hci_mct_receive_acl_msg(void)
-{
-    uint16_t    bytes_read = 0;
-    uint8_t     byte;
-    uint16_t    msg_len, len;
-    uint8_t     msg_received;
-    tHCI_RCV_CB *p_cb=&mct_cb.rcv_acl;
-    uint8_t     continue_fetch_looping = TRUE;
-
-    while (continue_fetch_looping)
-    {
-        /* Read one byte to see if there is anything waiting to be read */
-        if (userial_read(MSG_HC_TO_STACK_HCI_ACL, &byte, 1) == 0)
-        {
-            break;
-        }
-
-        bytes_read++;
-        msg_received = FALSE;
-
-        switch (p_cb->rcv_state)
-        {
-        case MCT_RX_NEWMSG_ST:
-            /* Start of new message */
-            /* Initialize rx parameters */
-            memset(p_cb->preload_buffer, 0 , 6);
-            p_cb->preload_buffer[0] = byte;
-            p_cb->preload_count = 1;
-            p_cb->rcv_len = HCI_ACL_PREAMBLE_SIZE - 1;
-            // p_cb->p_rcv_msg = NULL;
-            p_cb->rcv_state = MCT_RX_LEN_ST; /* Next, wait for length to come */
-            break;
-
-        case MCT_RX_LEN_ST:
-            /* Receiving preamble */
-            p_cb->preload_buffer[p_cb->preload_count++] = byte;
-            p_cb->rcv_len--;
-
-            /* Check if we received entire preamble yet */
-            if (p_cb->rcv_len == 0)
-            {
-                /* ACL data lengths are 16-bits */
-                msg_len = p_cb->preload_buffer[3];
-                msg_len = (msg_len << 8) + p_cb->preload_buffer[2];
-
-                if (msg_len && (p_cb->preload_count == 4))
-                {
-                    /* Check if this is a start packet */
-                    byte = ((p_cb->preload_buffer[1] >> 4) & 0x03);
-
-                    if (byte == ACL_RX_PKT_START)
-                    {
-                       /*
-                        * A start packet & with non-zero data payload length.
-                        * We want to read 2 more bytes to get L2CAP payload
-                        * length.
-                        */
-                        p_cb->rcv_len = 2;
-
-                        break;
-                    }
-                }
-
-                /*
-                 * Check for segmented packets. If this is a continuation
-                 * packet, then we will continue appending data to the
-                 * original rcv buffer.
-                 */
-                p_cb->p_rcv_msg = acl_rx_frame_buffer_alloc();
-
-                if (p_cb->p_rcv_msg == NULL)
-                {
-                    /* Unable to acquire message buffer. */
-                    ALOGE( \
-                     "Unable to acquire buffer for incoming HCI message." \
-                    );
-
-                    if (msg_len == 0)
-                    {
-                        /* Wait for next message */
-                        p_cb->rcv_state = MCT_RX_NEWMSG_ST;
-                        continue_fetch_looping = FALSE;
-                    }
-                    else
-                    {
-                        /* Ignore rest of the packet */
-                        p_cb->rcv_state = MCT_RX_IGNORE_ST;
-                    }
-
-                    break;
-                }
-
-                /* Message length is valid */
-                if (msg_len)
-                {
-                    /* Read rest of message */
-                    p_cb->rcv_state = MCT_RX_DATA_ST;
-                }
-                else
-                {
-                    /* Message has no additional parameters.
-                     * (Entire message has been received) */
-                    acl_rx_frame_end_chk(); /* to print snoop trace */
-
-                    msg_received = TRUE;
-
-                    /* Next, wait for next message */
-                    p_cb->rcv_state = MCT_RX_NEWMSG_ST;
-                    continue_fetch_looping = FALSE;
-                }
-            }
-            break;
-
-        case MCT_RX_DATA_ST:
-            *((uint8_t *)(p_cb->p_rcv_msg + 1) + p_cb->p_rcv_msg->len++) = byte;
-            p_cb->rcv_len--;
-
-            if (p_cb->rcv_len > 0)
-            {
-                /* Read in the rest of the message */
-                len = userial_read(MSG_HC_TO_STACK_HCI_ACL, \
-                      ((uint8_t *)(p_cb->p_rcv_msg+1) + p_cb->p_rcv_msg->len), \
-                      p_cb->rcv_len);
-                p_cb->p_rcv_msg->len += len;
-                p_cb->rcv_len -= len;
-                bytes_read += len;
-            }
-
-            /* Check if we read in entire message yet */
-            if (p_cb->rcv_len == 0)
-            {
-                /* Received entire packet. */
-                /* Check for segmented l2cap packets */
-                if (acl_rx_frame_end_chk())
-                {
-                    msg_received = TRUE;
-                }
-
-                /* Next, wait for next message */
-                p_cb->rcv_state = MCT_RX_NEWMSG_ST;
-                continue_fetch_looping = FALSE;
-            }
-            break;
-
-
-        case MCT_RX_IGNORE_ST:
-            /* Ignore reset of packet */
-            p_cb->rcv_len--;
-
-            /* Check if we read in entire message yet */
-            if (p_cb->rcv_len == 0)
-            {
-                /* Next, wait for next message */
-                p_cb->rcv_state = MCT_RX_NEWMSG_ST;
-                continue_fetch_looping = FALSE;
-            }
-            break;
-        }
-
-
-        /* If we received entire message, then send it to the task */
-        if (msg_received)
-        {
-            if (bt_hc_cbacks)
-            {
-                bt_hc_cbacks->data_ind((TRANSAC) p_cb->p_rcv_msg, \
-                                       (char *) (p_cb->p_rcv_msg + 1), \
-                                       p_cb->p_rcv_msg->len + BT_HC_HDR_SIZE);
-            }
-            p_cb->p_rcv_msg = NULL;
-        }
-    }
-
-    return (bytes_read);
-}
-
-/*******************************************************************************
-**
-** Function        hci_mct_send_int_cmd
-**
-** Description     Place the internal commands (issued internally by hci or
-**                 vendor lib) in the tx_q.
-**
-** Returns         TRUE/FALSE
-**
-*******************************************************************************/
-uint8_t hci_mct_send_int_cmd(uint16_t opcode, HC_BT_HDR *p_buf, \
-                                  tINT_CMD_CBACK p_cback)
-{
-    if (mct_cb.int_cmd_rsp_pending > INT_CMD_PKT_MAX_COUNT)
-    {
-        ALOGE( \
-        "Allow only %d outstanding internal commands at a time [Reject 0x%04X]"\
-        , INT_CMD_PKT_MAX_COUNT, opcode);
-        return FALSE;
-    }
-
-    mct_cb.int_cmd_rsp_pending++;
-    mct_cb.int_cmd[mct_cb.int_cmd_wrt_idx].opcode = opcode;
-    mct_cb.int_cmd[mct_cb.int_cmd_wrt_idx].cback = p_cback;
-    mct_cb.int_cmd_wrt_idx = ((mct_cb.int_cmd_wrt_idx+1) & INT_CMD_PKT_IDX_MASK);
-
-    /* stamp signature to indicate an internal command */
-    p_buf->layer_specific = opcode;
-
-    bthc_tx(p_buf);
-    return TRUE;
-}
-
-
-/*******************************************************************************
-**
-** Function        hci_mct_get_acl_data_length
-**
-** Description     Issue HCI_READ_BUFFER_SIZE command to retrieve Controller's
-**                 ACL data length setting
-**
-** Returns         None
-**
-*******************************************************************************/
-void hci_mct_get_acl_data_length(void)
-{
-    HC_BT_HDR  *p_buf = NULL;
-    uint8_t     *p, ret;
-
-    if (bt_hc_cbacks)
-    {
-        p_buf = (HC_BT_HDR *) bt_hc_cbacks->alloc(BT_HC_HDR_SIZE + \
-                                                       HCI_CMD_PREAMBLE_SIZE);
-    }
-
-    if (p_buf)
-    {
-        p_buf->event = MSG_STACK_TO_HC_HCI_CMD;
-        p_buf->offset = 0;
-        p_buf->layer_specific = 0;
-        p_buf->len = HCI_CMD_PREAMBLE_SIZE;
-
-        p = (uint8_t *) (p_buf + 1);
-        UINT16_TO_STREAM(p, HCI_READ_BUFFER_SIZE);
-        *p = 0;
-
-        if ((ret = hci_mct_send_int_cmd(HCI_READ_BUFFER_SIZE, p_buf, \
-                                       get_acl_data_length_cback)) == FALSE)
-        {
-            bt_hc_cbacks->dealloc(p_buf);
-        }
-        else
-            return;
-    }
-
-    if (bt_hc_cbacks)
-    {
-        ALOGE("hci lib postload aborted");
-        bt_hc_cbacks->postload_cb(NULL, BT_HC_POSTLOAD_FAIL);
-    }
-}
-
-
-/******************************************************************************
-**  HCI MCT Services interface table
-******************************************************************************/
-
-const tHCI_IF hci_mct_func_table =
-{
-    hci_mct_init,
-    hci_mct_cleanup,
-    hci_mct_send_msg,
-    hci_mct_send_int_cmd,
-    hci_mct_get_acl_data_length,
-    hci_mct_receive_evt_msg,
-    hci_mct_receive_acl_msg
-};
-
-
diff --git a/hci/src/hci_packet_factory.c b/hci/src/hci_packet_factory.c
new file mode 100644
index 0000000..032823d
--- /dev/null
+++ b/hci/src/hci_packet_factory.c
@@ -0,0 +1,182 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <assert.h>
+
+#include "osi/include/allocator.h"
+#include "bt_types.h"
+#include "buffer_allocator.h"
+#include "hcidefs.h"
+#include "hcimsgs.h"
+#include "hci_internals.h"
+#include "hci_layer.h"
+#include "hci_packet_factory.h"
+
+static const allocator_t *buffer_allocator;
+
+static BT_HDR *make_packet(size_t data_size);
+static BT_HDR *make_command_no_params(uint16_t opcode);
+static BT_HDR *make_command(uint16_t opcode, size_t parameter_size, uint8_t **stream_out);
+
+// Interface functions
+
+static BT_HDR *make_reset(void) {
+  return make_command_no_params(HCI_RESET);
+}
+
+static BT_HDR *make_read_buffer_size(void) {
+  return make_command_no_params(HCI_READ_BUFFER_SIZE);
+}
+
+static BT_HDR *make_host_buffer_size(uint16_t acl_size, uint8_t sco_size, uint16_t acl_count, uint16_t sco_count) {
+  uint8_t *stream;
+  const uint8_t parameter_size = 2 + 1 + 2 + 2; // from each of the parameters
+  BT_HDR *packet = make_command(HCI_HOST_BUFFER_SIZE, parameter_size, &stream);
+
+  UINT16_TO_STREAM(stream, acl_size);
+  UINT8_TO_STREAM(stream, sco_size);
+  UINT16_TO_STREAM(stream, acl_count);
+  UINT16_TO_STREAM(stream, sco_count);
+  return packet;
+}
+
+static BT_HDR *make_read_local_version_info(void) {
+  return make_command_no_params(HCI_READ_LOCAL_VERSION_INFO);
+}
+
+static BT_HDR *make_read_bd_addr(void) {
+  return make_command_no_params(HCI_READ_BD_ADDR);
+}
+
+static BT_HDR *make_read_local_supported_commands(void) {
+  return make_command_no_params(HCI_READ_LOCAL_SUPPORTED_CMDS);
+}
+
+static BT_HDR *make_read_local_extended_features(uint8_t page_number) {
+  uint8_t *stream;
+  const uint8_t parameter_size = 1;
+  BT_HDR *packet = make_command(HCI_READ_LOCAL_EXT_FEATURES, parameter_size, &stream);
+
+  UINT8_TO_STREAM(stream, page_number);
+  return packet;
+}
+
+static BT_HDR *make_write_simple_pairing_mode(uint8_t mode) {
+  uint8_t *stream;
+  const uint8_t parameter_size = 1;
+  BT_HDR *packet = make_command(HCI_WRITE_SIMPLE_PAIRING_MODE, parameter_size, &stream);
+
+  UINT8_TO_STREAM(stream, mode);
+  return packet;
+}
+
+static BT_HDR *make_set_event_mask(const bt_event_mask_t *event_mask) {
+  uint8_t *stream;
+  uint8_t parameter_size = sizeof(bt_event_mask_t);
+  BT_HDR *packet = make_command(HCI_SET_EVENT_MASK, parameter_size, &stream);
+
+  ARRAY8_TO_STREAM(stream, event_mask->as_array);
+  return packet;
+}
+
+static BT_HDR *make_ble_write_host_support(uint8_t supported_host, uint8_t simultaneous_host) {
+  uint8_t *stream;
+  const uint8_t parameter_size = 1 + 1;
+  BT_HDR *packet = make_command(HCI_WRITE_LE_HOST_SUPPORT, parameter_size, &stream);
+
+  UINT8_TO_STREAM(stream, supported_host);
+  UINT8_TO_STREAM(stream, simultaneous_host);
+  return packet;
+}
+
+static BT_HDR *make_ble_read_white_list_size(void) {
+  return make_command_no_params(HCI_BLE_READ_WHITE_LIST_SIZE);
+}
+
+static BT_HDR *make_ble_read_buffer_size(void) {
+  return make_command_no_params(HCI_BLE_READ_BUFFER_SIZE);
+}
+
+static BT_HDR *make_ble_read_supported_states(void) {
+  return make_command_no_params(HCI_BLE_READ_SUPPORTED_STATES);
+}
+
+static BT_HDR *make_ble_read_local_supported_features(void) {
+  return make_command_no_params(HCI_BLE_READ_LOCAL_SPT_FEAT);
+}
+
+static BT_HDR *make_ble_set_event_mask(const bt_event_mask_t *event_mask) {
+  uint8_t *stream;
+  uint8_t parameter_size = sizeof(bt_event_mask_t);
+  BT_HDR *packet = make_command(HCI_BLE_SET_EVENT_MASK, parameter_size, &stream);
+
+  ARRAY8_TO_STREAM(stream, event_mask->as_array);
+  return packet;
+}
+
+// Internal functions
+
+static BT_HDR *make_command_no_params(uint16_t opcode) {
+  return make_command(opcode, 0, NULL);
+}
+
+static BT_HDR *make_command(uint16_t opcode, size_t parameter_size, uint8_t **stream_out) {
+  BT_HDR *packet = make_packet(HCI_COMMAND_PREAMBLE_SIZE + parameter_size);
+
+  uint8_t *stream = packet->data;
+  UINT16_TO_STREAM(stream, opcode);
+  UINT8_TO_STREAM(stream, parameter_size);
+
+  if (stream_out != NULL)
+    *stream_out = stream;
+
+  return packet;
+}
+
+static BT_HDR *make_packet(size_t data_size) {
+  BT_HDR *ret = (BT_HDR *)buffer_allocator->alloc(sizeof(BT_HDR) + data_size);
+  assert(ret);
+  ret->event = 0;
+  ret->offset = 0;
+  ret->layer_specific = 0;
+  ret->len = data_size;
+  return ret;
+}
+
+static const hci_packet_factory_t interface = {
+  make_reset,
+  make_read_buffer_size,
+  make_host_buffer_size,
+  make_read_local_version_info,
+  make_read_bd_addr,
+  make_read_local_supported_commands,
+  make_read_local_extended_features,
+  make_write_simple_pairing_mode,
+  make_set_event_mask,
+  make_ble_write_host_support,
+  make_ble_read_white_list_size,
+  make_ble_read_buffer_size,
+  make_ble_read_supported_states,
+  make_ble_read_local_supported_features,
+  make_ble_set_event_mask
+};
+
+const hci_packet_factory_t *hci_packet_factory_get_interface() {
+  buffer_allocator = buffer_allocator_get_interface();
+  return &interface;
+}
diff --git a/hci/src/hci_packet_parser.c b/hci/src/hci_packet_parser.c
new file mode 100644
index 0000000..0af9b70
--- /dev/null
+++ b/hci/src/hci_packet_parser.c
@@ -0,0 +1,212 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <assert.h>
+
+#include "buffer_allocator.h"
+#include "bt_types.h"
+#include "hcimsgs.h"
+#include "hci_layer.h"
+#include "hci_packet_parser.h"
+
+static const command_opcode_t NO_OPCODE_CHECKING = 0;
+
+static const allocator_t *buffer_allocator;
+
+static uint8_t *read_command_complete_header(
+  BT_HDR *response,
+  command_opcode_t expected_opcode,
+  size_t minimum_bytes_after);
+
+static void parse_generic_command_complete(BT_HDR *response) {
+  read_command_complete_header(response, NO_OPCODE_CHECKING, 0 /* bytes after */);
+
+  buffer_allocator->free(response);
+}
+
+static void parse_read_buffer_size_response(
+    BT_HDR *response,
+    uint16_t *data_size_ptr,
+    uint16_t *acl_buffer_count_ptr) {
+
+  uint8_t *stream = read_command_complete_header(response, HCI_READ_BUFFER_SIZE, 5 /* bytes after */);
+  STREAM_TO_UINT16(*data_size_ptr, stream);
+  STREAM_SKIP_UINT8(stream); // skip the sco packet length
+  STREAM_TO_UINT16(*acl_buffer_count_ptr, stream);
+
+  buffer_allocator->free(response);
+}
+
+static void parse_read_local_version_info_response(
+    BT_HDR *response,
+    bt_version_t *bt_version) {
+
+  uint8_t *stream = read_command_complete_header(response, HCI_READ_LOCAL_VERSION_INFO, 8 /* bytes after */);
+  STREAM_TO_UINT8(bt_version->hci_version, stream);
+  STREAM_TO_UINT16(bt_version->hci_revision, stream);
+  STREAM_TO_UINT8(bt_version->lmp_version, stream);
+  STREAM_TO_UINT16(bt_version->manufacturer, stream);
+  STREAM_TO_UINT16(bt_version->lmp_subversion, stream);
+
+  buffer_allocator->free(response);
+}
+
+static void parse_read_bd_addr_response(
+    BT_HDR *response,
+    bt_bdaddr_t *address_ptr) {
+
+  uint8_t *stream = read_command_complete_header(response, HCI_READ_BD_ADDR, sizeof(bt_bdaddr_t) /* bytes after */);
+  STREAM_TO_BDADDR(address_ptr->address, stream);
+
+  buffer_allocator->free(response);
+}
+
+static void parse_read_local_supported_commands_response(
+    BT_HDR *response,
+    uint8_t *supported_commands_ptr,
+    size_t supported_commands_length) {
+
+  uint8_t *stream = read_command_complete_header(response, HCI_READ_LOCAL_SUPPORTED_CMDS, supported_commands_length /* bytes after */);
+  STREAM_TO_ARRAY(supported_commands_ptr, stream, (int)supported_commands_length);
+
+  buffer_allocator->free(response);
+}
+
+static void parse_read_local_extended_features_response(
+    BT_HDR *response,
+    uint8_t *page_number_ptr,
+    uint8_t *max_page_number_ptr,
+    bt_device_features_t *feature_pages,
+    size_t feature_pages_count) {
+
+  uint8_t *stream = read_command_complete_header(response, HCI_READ_LOCAL_EXT_FEATURES, 2 + sizeof(bt_device_features_t) /* bytes after */);
+  STREAM_TO_UINT8(*page_number_ptr, stream);
+  STREAM_TO_UINT8(*max_page_number_ptr, stream);
+
+  assert(*page_number_ptr < feature_pages_count);
+  STREAM_TO_ARRAY(feature_pages[*page_number_ptr].as_array, stream, (int)sizeof(bt_device_features_t));
+
+  buffer_allocator->free(response);
+}
+
+static void parse_ble_read_white_list_size_response(
+    BT_HDR *response,
+    uint8_t *white_list_size_ptr) {
+
+  uint8_t *stream = read_command_complete_header(response, HCI_BLE_READ_WHITE_LIST_SIZE, 1 /* byte after */);
+  STREAM_TO_UINT8(*white_list_size_ptr, stream);
+
+  buffer_allocator->free(response);
+}
+
+static void parse_ble_read_buffer_size_response(
+    BT_HDR *response,
+    uint16_t *data_size_ptr,
+    uint8_t *acl_buffer_count_ptr) {
+
+  uint8_t *stream = read_command_complete_header(response, HCI_BLE_READ_BUFFER_SIZE, 3 /* bytes after */);
+  STREAM_TO_UINT16(*data_size_ptr, stream);
+  STREAM_TO_UINT8(*acl_buffer_count_ptr, stream);
+
+  buffer_allocator->free(response);
+}
+
+static void parse_ble_read_supported_states_response(
+    BT_HDR *response,
+    uint8_t *supported_states,
+    size_t supported_states_size) {
+
+  uint8_t *stream = read_command_complete_header(response, HCI_BLE_READ_SUPPORTED_STATES, supported_states_size /* bytes after */);
+  STREAM_TO_ARRAY(supported_states, stream, (int)supported_states_size);
+
+  buffer_allocator->free(response);
+}
+
+static void parse_ble_read_local_supported_features_response(
+    BT_HDR *response,
+    bt_device_features_t *supported_features) {
+
+  uint8_t *stream = read_command_complete_header(response, HCI_BLE_READ_LOCAL_SPT_FEAT, sizeof(bt_device_features_t) /* bytes after */);
+  STREAM_TO_ARRAY(supported_features->as_array, stream, (int)sizeof(bt_device_features_t));
+
+  buffer_allocator->free(response);
+}
+
+// Internal functions
+
+static uint8_t *read_command_complete_header(
+    BT_HDR *response,
+    command_opcode_t expected_opcode,
+    size_t minimum_bytes_after) {
+
+  uint8_t *stream = response->data + response->offset;
+
+  // Read the event header
+  uint8_t event_code;
+  uint8_t parameter_length;
+  STREAM_TO_UINT8(event_code, stream);
+  STREAM_TO_UINT8(parameter_length, stream);
+
+  const size_t parameter_bytes_we_read_here = 4;
+
+  // Check the event header values against what we expect
+  assert(event_code == HCI_COMMAND_COMPLETE_EVT);
+  assert(parameter_length >= (parameter_bytes_we_read_here + minimum_bytes_after));
+
+  // Read the command complete header
+  command_opcode_t opcode;
+  uint8_t status;
+  STREAM_SKIP_UINT8(stream); // skip the number of hci command packets field
+  STREAM_TO_UINT16(opcode, stream);
+
+  // Check the command complete header values against what we expect
+  if (expected_opcode != NO_OPCODE_CHECKING) {
+    assert(opcode == expected_opcode);
+  }
+
+  // Assume the next field is the status field
+  STREAM_TO_UINT8(status, stream);
+  // Make sure it was successful
+  assert(status == HCI_SUCCESS);
+
+  return stream;
+}
+
+static const hci_packet_parser_t interface = {
+  parse_generic_command_complete,
+  parse_read_buffer_size_response,
+  parse_read_local_version_info_response,
+  parse_read_bd_addr_response,
+  parse_read_local_supported_commands_response,
+  parse_read_local_extended_features_response,
+  parse_ble_read_white_list_size_response,
+  parse_ble_read_buffer_size_response,
+  parse_ble_read_supported_states_response,
+  parse_ble_read_local_supported_features_response
+};
+
+const hci_packet_parser_t *hci_packet_parser_get_interface() {
+  buffer_allocator = buffer_allocator_get_interface();
+  return &interface;
+}
+
+const hci_packet_parser_t *hci_packet_parser_get_test_interface(
+    allocator_t *buffer_allocator_interface) {
+  buffer_allocator = buffer_allocator_interface;
+  return &interface;
+}
diff --git a/hci/src/low_power_manager.c b/hci/src/low_power_manager.c
new file mode 100644
index 0000000..9435e4f
--- /dev/null
+++ b/hci/src/low_power_manager.c
@@ -0,0 +1,242 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_low_power_manager"
+
+#include <assert.h>
+#include <stdint.h>
+
+#include "osi/include/alarm.h"
+#include "low_power_manager.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/thread.h"
+#include "vendor.h"
+
+typedef enum {
+  LPM_DISABLED = 0,
+  LPM_ENABLED,
+  LPM_ENABLING,
+  LPM_DISABLING
+} low_power_mode_state_t;
+
+typedef enum {
+  LPM_WAKE_DEASSERTED = 0,
+  LPM_WAKE_W4_TX_DONE,
+  LPM_WAKE_W4_TIMEOUT,
+  LPM_WAKE_ASSERTED,
+} wake_state_t;
+
+// Our interface and modules we import
+static const low_power_manager_t interface;
+static const vendor_t *vendor;
+
+static void vendor_enable_disable_callback(bool success);
+
+static void event_disable(void *context);
+static void event_enable(void *context);
+static void event_wake_assert(void *context);
+static void event_allow_device_sleep(void *context);
+static void event_idle_timeout(void *context);
+
+static void reset_state();
+static void start_idle_timer();
+static void stop_idle_timer();
+
+static thread_fn event_functions[] = {
+  event_disable,
+  event_enable,
+  event_wake_assert,
+  event_allow_device_sleep
+};
+
+static thread_t *thread;
+static low_power_mode_state_t state;
+static wake_state_t wake_state;
+static uint32_t idle_timeout_ms;
+static alarm_t *idle_alarm;
+static bool transmit_is_done;
+
+// Interface functions
+
+static void init(thread_t *post_thread) {
+  assert(post_thread != NULL);
+  thread = post_thread;
+
+  vendor->set_callback(VENDOR_SET_LPM_MODE, vendor_enable_disable_callback);
+  vendor->send_command(VENDOR_GET_LPM_IDLE_TIMEOUT, &idle_timeout_ms);
+
+  idle_alarm = alarm_new();
+  if (!idle_alarm) {
+    LOG_ERROR("%s could not create idle alarm.", __func__);
+  }
+
+  reset_state();
+}
+
+static void cleanup() {
+  reset_state();
+  alarm_free(idle_alarm);
+  idle_alarm = NULL;
+}
+
+static void post_command(low_power_command_t command) {
+  if (command > LPM_WAKE_DEASSERT) {
+    LOG_ERROR("%s unknown low power command %d", __func__, command);
+    return;
+  }
+
+  thread_post(thread, event_functions[command], NULL);
+}
+
+static void wake_assert() {
+  if (state != LPM_DISABLED) {
+    stop_idle_timer();
+
+    uint8_t new_state = BT_VND_LPM_WAKE_ASSERT;
+    vendor->send_command(VENDOR_SET_LPM_WAKE_STATE, &new_state);
+    wake_state = LPM_WAKE_ASSERTED;
+  }
+
+  // TODO(zachoverflow): investigate this interaction. If someone above
+  // HCI asserts wake, we'll wait until we transmit before deasserting.
+  // That doesn't seem quite right.
+  transmit_is_done = false;
+}
+
+static void transmit_done() {
+  transmit_is_done = true;
+  if (wake_state == LPM_WAKE_W4_TX_DONE) {
+    wake_state = LPM_WAKE_W4_TIMEOUT;
+    start_idle_timer();
+  }
+}
+
+// Internal functions
+
+static void enable(bool enable) {
+  if (state == LPM_DISABLING) {
+    if (enable)
+      LOG_ERROR("%s still processing prior disable request, cannot enable.", __func__);
+    else
+      LOG_WARN("%s still processing prior disable request, ignoring new request to disable.", __func__);
+  } else if (state == LPM_ENABLING) {
+    if (enable)
+      LOG_ERROR("%s still processing prior enable request, ignoring new request to enable.", __func__);
+    else
+      LOG_WARN("%s still processing prior enable request, cannot disable.", __func__);
+  } else if (state == LPM_ENABLED && enable) {
+    LOG_INFO("%s already enabled.", __func__);
+  } else if (state == LPM_DISABLED && !enable) {
+    LOG_INFO("%s already disabled.", __func__);
+  } else {
+    uint8_t command = enable ? BT_VND_LPM_ENABLE : BT_VND_LPM_DISABLE;
+    state = enable ? LPM_ENABLING : LPM_DISABLING;
+    vendor->send_async_command(VENDOR_SET_LPM_MODE, &command);
+  }
+}
+
+static void allow_device_sleep() {
+  if (state == LPM_ENABLED && wake_state == LPM_WAKE_ASSERTED) {
+    if (transmit_is_done) {
+      wake_state = LPM_WAKE_W4_TIMEOUT;
+      start_idle_timer();
+    } else {
+      wake_state = LPM_WAKE_W4_TX_DONE;
+    }
+  }
+}
+
+static void wake_deassert() {
+  if (state == LPM_ENABLED && transmit_is_done) {
+    uint8_t new_state = BT_VND_LPM_WAKE_DEASSERT;
+    vendor->send_command(VENDOR_SET_LPM_WAKE_STATE, &new_state);
+    wake_state = LPM_WAKE_DEASSERTED;
+  }
+}
+
+static void reset_state() {
+  state = LPM_DISABLED;
+  wake_state = LPM_WAKE_DEASSERTED;
+  transmit_is_done = true;
+  stop_idle_timer();
+}
+
+static void idle_timer_expired(UNUSED_ATTR void *context) {
+  if (state == LPM_ENABLED && wake_state == LPM_WAKE_W4_TIMEOUT)
+    thread_post(thread, event_idle_timeout, NULL);
+}
+
+static void start_idle_timer() {
+  if (state == LPM_ENABLED) {
+    alarm_set(idle_alarm, idle_timeout_ms, idle_timer_expired, NULL);
+  }
+}
+
+static void stop_idle_timer() {
+  alarm_cancel(idle_alarm);
+}
+
+static void event_disable(UNUSED_ATTR void *context) {
+  enable(false);
+}
+
+static void event_enable(UNUSED_ATTR void *context) {
+  enable(true);
+}
+
+static void event_wake_assert(UNUSED_ATTR void *context) {
+  wake_assert();
+}
+
+static void event_allow_device_sleep(UNUSED_ATTR void *context) {
+  allow_device_sleep();
+}
+
+static void event_idle_timeout(UNUSED_ATTR void *context) {
+  wake_deassert();
+}
+
+static void vendor_enable_disable_callback(bool success) {
+  if (success)
+    state = (state == LPM_ENABLING) ? LPM_ENABLED : LPM_DISABLED;
+  else
+    state = (state == LPM_ENABLING) ? LPM_DISABLED : LPM_ENABLED;
+
+  if (state == LPM_DISABLED) {
+    reset_state();
+  }
+}
+
+static const low_power_manager_t interface = {
+  init,
+  cleanup,
+  post_command,
+  wake_assert,
+  transmit_done
+};
+
+const low_power_manager_t *low_power_manager_get_interface() {
+  vendor = vendor_get_interface();
+  return &interface;
+}
+
+const low_power_manager_t *low_power_manager_get_test_interface(const vendor_t *vendor_interface) {
+  vendor = vendor_interface;
+  return &interface;
+}
diff --git a/hci/src/lpm.c b/hci/src/lpm.c
deleted file mode 100644
index 28e0cfa..0000000
--- a/hci/src/lpm.c
+++ /dev/null
@@ -1,409 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Filename:      lpm.c
- *
- *  Description:   Contains low power mode implementation
- *
- ******************************************************************************/
-
-#define LOG_TAG "bt_lpm"
-
-#include <utils/Log.h>
-#include <signal.h>
-#include <string.h>
-#include <time.h>
-#include "bt_hci_bdroid.h"
-#include "bt_vendor_lib.h"
-#include "bt_utils.h"
-#include "vendor.h"
-
-/******************************************************************************
-**  Constants & Macros
-******************************************************************************/
-
-#ifndef BTLPM_DBG
-#define BTLPM_DBG FALSE
-#endif
-
-#if (BTLPM_DBG == TRUE)
-#define BTLPMDBG(param, ...) {ALOGD(param, ## __VA_ARGS__);}
-#else
-#define BTLPMDBG(param, ...) {}
-#endif
-
-#ifndef DEFAULT_LPM_IDLE_TIMEOUT
-#define DEFAULT_LPM_IDLE_TIMEOUT    3000
-#endif
-
-/******************************************************************************
-**  Externs
-******************************************************************************/
-
-/******************************************************************************
-**  Local type definitions
-******************************************************************************/
-
-/* Low power mode state */
-enum {
-    LPM_DISABLED = 0,                    /* initial state */
-    LPM_ENABLED,
-    LPM_ENABLING,
-    LPM_DISABLING
-};
-
-/* LPM WAKE state */
-enum {
-    LPM_WAKE_DEASSERTED = 0,              /* initial state */
-    LPM_WAKE_W4_TX_DONE,
-    LPM_WAKE_W4_TIMEOUT,
-    LPM_WAKE_ASSERTED
-};
-
-/* low power mode control block */
-typedef struct
-{
-    uint8_t state;                          /* Low power mode state */
-    uint8_t wake_state;                     /* LPM WAKE state */
-    uint8_t no_tx_data;
-    uint8_t timer_created;
-    timer_t timer_id;
-    uint32_t timeout_ms;
-} bt_lpm_cb_t;
-
-
-/******************************************************************************
-**  Static variables
-******************************************************************************/
-
-static bt_lpm_cb_t bt_lpm_cb;
-
-/******************************************************************************
-**   LPM Static Functions
-******************************************************************************/
-
-/*******************************************************************************
-**
-** Function        lpm_idle_timeout
-**
-** Description     Timeout thread of transport idle timer
-**
-** Returns         None
-**
-*******************************************************************************/
-static void lpm_idle_timeout(union sigval arg)
-{
-    UNUSED(arg);
-    BTLPMDBG("..lpm_idle_timeout..");
-
-    if ((bt_lpm_cb.state == LPM_ENABLED) && \
-        (bt_lpm_cb.wake_state == LPM_WAKE_W4_TIMEOUT))
-    {
-        bthc_idle_timeout();
-    }
-}
-
-/*******************************************************************************
-**
-** Function        lpm_start_transport_idle_timer
-**
-** Description     Launch transport idle timer
-**
-** Returns         None
-**
-*******************************************************************************/
-static void lpm_start_transport_idle_timer(void)
-{
-    int status;
-    struct itimerspec ts;
-    struct sigevent se;
-
-    if (bt_lpm_cb.state != LPM_ENABLED)
-        return;
-
-    if (bt_lpm_cb.timer_created == FALSE)
-    {
-        se.sigev_notify = SIGEV_THREAD;
-        se.sigev_value.sival_ptr = &bt_lpm_cb.timer_id;
-        se.sigev_notify_function = lpm_idle_timeout;
-        se.sigev_notify_attributes = NULL;
-
-        status = timer_create(CLOCK_MONOTONIC, &se, &bt_lpm_cb.timer_id);
-
-        if (status == 0)
-            bt_lpm_cb.timer_created = TRUE;
-    }
-
-    if (bt_lpm_cb.timer_created == TRUE)
-    {
-        ts.it_value.tv_sec = bt_lpm_cb.timeout_ms/1000;
-        ts.it_value.tv_nsec = 1000000*(bt_lpm_cb.timeout_ms%1000);
-        ts.it_interval.tv_sec = 0;
-        ts.it_interval.tv_nsec = 0;
-
-        status = timer_settime(bt_lpm_cb.timer_id, 0, &ts, 0);
-        if (status == -1)
-            ALOGE("[START] Failed to set LPM idle timeout");
-    }
-}
-
-/*******************************************************************************
-**
-** Function        lpm_stop_transport_idle_timer
-**
-** Description     Launch transport idle timer
-**
-** Returns         None
-**
-*******************************************************************************/
-static void lpm_stop_transport_idle_timer(void)
-{
-    int status;
-    struct itimerspec ts;
-
-    if (bt_lpm_cb.timer_created == TRUE)
-    {
-        ts.it_value.tv_sec = 0;
-        ts.it_value.tv_nsec = 0;
-        ts.it_interval.tv_sec = 0;
-        ts.it_interval.tv_nsec = 0;
-
-        status = timer_settime(bt_lpm_cb.timer_id, 0, &ts, 0);
-        if (status == -1)
-            ALOGE("[STOP] Failed to set LPM idle timeout");
-    }
-}
-
-/*******************************************************************************
-**
-** Function         lpm_vnd_cback
-**
-** Description      Callback of vendor specific result for lpm enable/disable
-**                  rquest
-**
-** Returns          None
-**
-*******************************************************************************/
-void lpm_vnd_cback(uint8_t vnd_result)
-{
-    if (vnd_result == 0)
-    {
-        /* Status == Success */
-        bt_lpm_cb.state = (bt_lpm_cb.state == LPM_ENABLING) ? \
-                          LPM_ENABLED : LPM_DISABLED;
-    }
-    else
-    {
-        bt_lpm_cb.state = (bt_lpm_cb.state == LPM_ENABLING) ? \
-                          LPM_DISABLED : LPM_ENABLED;
-    }
-
-    if (bt_hc_cbacks)
-    {
-        if (bt_lpm_cb.state == LPM_ENABLED)
-            bt_hc_cbacks->lpm_cb(BT_HC_LPM_ENABLED);
-        else
-            bt_hc_cbacks->lpm_cb(BT_HC_LPM_DISABLED);
-    }
-
-    if (bt_lpm_cb.state == LPM_DISABLED)
-    {
-        if (bt_lpm_cb.timer_created == TRUE)
-        {
-            timer_delete(bt_lpm_cb.timer_id);
-        }
-
-        memset(&bt_lpm_cb, 0, sizeof(bt_lpm_cb_t));
-    }
-}
-
-
-/*****************************************************************************
-**   Low Power Mode Interface Functions
-*****************************************************************************/
-
-/*******************************************************************************
-**
-** Function        lpm_init
-**
-** Description     Init LPM
-**
-** Returns         None
-**
-*******************************************************************************/
-void lpm_init(void)
-{
-    memset(&bt_lpm_cb, 0, sizeof(bt_lpm_cb_t));
-    vendor_send_command(BT_VND_OP_GET_LPM_IDLE_TIMEOUT, &bt_lpm_cb.timeout_ms);
-}
-
-/*******************************************************************************
-**
-** Function        lpm_cleanup
-**
-** Description     Clean up
-**
-** Returns         None
-**
-*******************************************************************************/
-void lpm_cleanup(void)
-{
-    if (bt_lpm_cb.timer_created == TRUE)
-    {
-        timer_delete(bt_lpm_cb.timer_id);
-    }
-}
-
-/*******************************************************************************
-**
-** Function        lpm_enable
-**
-** Description     Enalbe/Disable LPM
-**
-** Returns         None
-**
-*******************************************************************************/
-void lpm_enable(uint8_t turn_on)
-{
-    if ((bt_lpm_cb.state!=LPM_DISABLED) && (bt_lpm_cb.state!=LPM_ENABLED))
-    {
-        ALOGW("Still busy on processing prior LPM enable/disable request...");
-        return;
-    }
-
-    if ((turn_on == TRUE) && (bt_lpm_cb.state == LPM_ENABLED))
-    {
-        ALOGI("LPM is already on!!!");
-        if (bt_hc_cbacks)
-            bt_hc_cbacks->lpm_cb(BT_HC_LPM_ENABLED);
-    }
-    else if ((turn_on == FALSE) && (bt_lpm_cb.state == LPM_DISABLED))
-    {
-        ALOGI("LPM is already off!!!");
-        if (bt_hc_cbacks)
-            bt_hc_cbacks->lpm_cb(BT_HC_LPM_DISABLED);
-    }
-
-    uint8_t lpm_cmd = (turn_on) ? BT_VND_LPM_ENABLE : BT_VND_LPM_DISABLE;
-    bt_lpm_cb.state = (turn_on) ? LPM_ENABLING : LPM_DISABLING;
-    vendor_send_command(BT_VND_OP_LPM_SET_MODE, &lpm_cmd);
-}
-
-/*******************************************************************************
-**
-** Function          lpm_tx_done
-**
-** Description       This function is to inform the lpm module
-**                   if data is waiting in the Tx Q or not.
-**
-**                   IsTxDone: TRUE if All data in the Tx Q are gone
-**                             FALSE if any data is still in the Tx Q.
-**                   Typicaly this function must be called
-**                   before USERIAL Write and in the Tx Done routine
-**
-** Returns           None
-**
-*******************************************************************************/
-void lpm_tx_done(uint8_t is_tx_done)
-{
-    bt_lpm_cb.no_tx_data = is_tx_done;
-
-    if ((bt_lpm_cb.wake_state==LPM_WAKE_W4_TX_DONE) && (is_tx_done==TRUE))
-    {
-        bt_lpm_cb.wake_state = LPM_WAKE_W4_TIMEOUT;
-        lpm_start_transport_idle_timer();
-    }
-}
-
-/*******************************************************************************
-**
-** Function        lpm_wake_assert
-**
-** Description     Called to wake up Bluetooth chip.
-**                 Normally this is called when there is data to be sent
-**                 over UART.
-**
-** Returns         TRUE/FALSE
-**
-*******************************************************************************/
-void lpm_wake_assert(void)
-{
-    if (bt_lpm_cb.state != LPM_DISABLED)
-    {
-        BTLPMDBG("LPM WAKE assert");
-
-        /* Calling vendor-specific part */
-        uint8_t state = BT_VND_LPM_WAKE_ASSERT;
-        vendor_send_command(BT_VND_OP_LPM_WAKE_SET_STATE, &state);
-
-        lpm_stop_transport_idle_timer();
-
-        bt_lpm_cb.wake_state = LPM_WAKE_ASSERTED;
-    }
-
-    lpm_tx_done(FALSE);
-}
-
-/*******************************************************************************
-**
-** Function        lpm_allow_bt_device_sleep
-**
-** Description     Start LPM idle timer if allowed
-**
-** Returns         None
-**
-*******************************************************************************/
-void lpm_allow_bt_device_sleep(void)
-{
-    if ((bt_lpm_cb.state == LPM_ENABLED) && \
-        (bt_lpm_cb.wake_state == LPM_WAKE_ASSERTED))
-    {
-        if(bt_lpm_cb.no_tx_data == TRUE)
-        {
-            bt_lpm_cb.wake_state = LPM_WAKE_W4_TIMEOUT;
-            lpm_start_transport_idle_timer();
-        }
-        else
-        {
-            bt_lpm_cb.wake_state = LPM_WAKE_W4_TX_DONE;
-        }
-    }
-}
-
-/*******************************************************************************
-**
-** Function         lpm_wake_deassert
-**
-** Description      Deassert wake if allowed
-**
-** Returns          None
-**
-*******************************************************************************/
-void lpm_wake_deassert(void)
-{
-    if ((bt_lpm_cb.state == LPM_ENABLED) && (bt_lpm_cb.no_tx_data == TRUE))
-    {
-        BTLPMDBG("LPM WAKE deassert");
-
-        uint8_t state = BT_VND_LPM_WAKE_DEASSERT;
-        vendor_send_command(BT_VND_OP_LPM_WAKE_SET_STATE, &state);
-        bt_lpm_cb.wake_state = LPM_WAKE_DEASSERTED;
-    }
-}
diff --git a/hci/src/packet_fragmenter.c b/hci/src/packet_fragmenter.c
new file mode 100644
index 0000000..b09cf08
--- /dev/null
+++ b/hci/src/packet_fragmenter.c
@@ -0,0 +1,227 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_hci_packet_fragmenter"
+
+#include <assert.h>
+
+#include "buffer_allocator.h"
+#include "device/include/controller.h"
+#include "osi/include/hash_map.h"
+#include "hci_internals.h"
+#include "hci_layer.h"
+#include "packet_fragmenter.h"
+#include "osi/include/osi.h"
+#include "osi/include/hash_functions.h"
+#include "osi/include/log.h"
+
+#define APPLY_CONTINUATION_FLAG(handle) (((handle) & 0xCFFF) | 0x1000)
+#define APPLY_START_FLAG(handle) (((handle) & 0xCFFF) | 0x2000)
+#define SUB_EVENT(event) ((event) & MSG_SUB_EVT_MASK)
+#define GET_BOUNDARY_FLAG(handle) (((handle) >> 12) & 0x0003)
+
+#define HANDLE_MASK 0x0FFF
+#define START_PACKET_BOUNDARY 2
+#define CONTINUATION_PACKET_BOUNDARY 1
+#define L2CAP_HEADER_SIZE       4
+
+// TODO(zachoverflow): find good value for this
+#define NUMBER_OF_BUCKETS 42
+
+// Our interface and callbacks
+static const packet_fragmenter_t interface;
+static const allocator_t *buffer_allocator;
+static const controller_t *controller;
+static const packet_fragmenter_callbacks_t *callbacks;
+
+static hash_map_t *partial_packets;
+
+static void init(const packet_fragmenter_callbacks_t *result_callbacks) {
+  callbacks = result_callbacks;
+  partial_packets = hash_map_new(NUMBER_OF_BUCKETS, hash_function_naive, NULL, NULL, NULL);
+}
+
+static void cleanup() {
+  if (partial_packets)
+    hash_map_free(partial_packets);
+}
+
+static void fragment_and_dispatch(BT_HDR *packet) {
+  assert(packet != NULL);
+
+  uint16_t event = packet->event & MSG_EVT_MASK;
+  uint8_t *stream = packet->data + packet->offset;
+
+  // We only fragment ACL packets
+  if (event != MSG_STACK_TO_HC_HCI_ACL) {
+    callbacks->fragmented(packet, true);
+    return;
+  }
+
+  uint16_t max_data_size =
+    SUB_EVENT(packet->event) == LOCAL_BR_EDR_CONTROLLER_ID ?
+      controller->get_acl_data_size_classic() :
+      controller->get_acl_data_size_ble();
+
+  uint16_t max_packet_size = max_data_size + HCI_ACL_PREAMBLE_SIZE;
+  uint16_t remaining_length = packet->len;
+
+  uint16_t continuation_handle;
+  STREAM_TO_UINT16(continuation_handle, stream);
+  continuation_handle = APPLY_CONTINUATION_FLAG(continuation_handle);
+
+  while (remaining_length > max_packet_size) {
+    // Make sure we use the right ACL packet size
+    stream = packet->data + packet->offset;
+    STREAM_SKIP_UINT16(stream);
+    UINT16_TO_STREAM(stream, max_data_size);
+
+    packet->len = max_packet_size;
+    callbacks->fragmented(packet, false);
+
+    packet->offset += max_data_size;
+    remaining_length -= max_data_size;
+    packet->len = remaining_length;
+
+    // Write the ACL header for the next fragment
+    stream = packet->data + packet->offset;
+    UINT16_TO_STREAM(stream, continuation_handle);
+    UINT16_TO_STREAM(stream, remaining_length - HCI_ACL_PREAMBLE_SIZE);
+
+    // Apparently L2CAP can set layer_specific to a max number of segments to transmit
+    if (packet->layer_specific) {
+      packet->layer_specific--;
+
+      if (packet->layer_specific == 0) {
+        packet->event = MSG_HC_TO_STACK_L2C_SEG_XMIT;
+        callbacks->transmit_finished(packet, false);
+        return;
+      }
+    }
+  }
+
+  callbacks->fragmented(packet, true);
+}
+
+static void reassemble_and_dispatch(UNUSED_ATTR BT_HDR *packet) {
+  if ((packet->event & MSG_EVT_MASK) == MSG_HC_TO_STACK_HCI_ACL) {
+    uint8_t *stream = packet->data;
+    uint16_t handle;
+    uint16_t l2cap_length;
+    uint16_t acl_length;
+
+    STREAM_TO_UINT16(handle, stream);
+    STREAM_TO_UINT16(acl_length, stream);
+    STREAM_TO_UINT16(l2cap_length, stream);
+
+    assert(acl_length == packet->len - HCI_ACL_PREAMBLE_SIZE);
+
+    uint8_t boundary_flag = GET_BOUNDARY_FLAG(handle);
+    handle = handle & HANDLE_MASK;
+
+    BT_HDR *partial_packet = (BT_HDR *)hash_map_get(partial_packets, (void *)(uintptr_t)handle);
+
+    if (boundary_flag == START_PACKET_BOUNDARY) {
+      if (partial_packet) {
+        LOG_WARN("%s found unfinished packet for handle with start packet. Dropping old.", __func__);
+
+        hash_map_erase(partial_packets, (void *)(uintptr_t)handle);
+        buffer_allocator->free(partial_packet);
+      }
+
+      uint16_t full_length = l2cap_length + L2CAP_HEADER_SIZE + HCI_ACL_PREAMBLE_SIZE;
+      if (full_length <= packet->len) {
+        if (full_length < packet->len)
+          LOG_WARN("%s found l2cap full length %d less than the hci length %d.", __func__, l2cap_length, packet->len);
+
+        callbacks->reassembled(packet);
+        return;
+      }
+
+      partial_packet = (BT_HDR *)buffer_allocator->alloc(full_length + sizeof(BT_HDR));
+      partial_packet->event = packet->event;
+      partial_packet->len = full_length;
+      partial_packet->offset = packet->len;
+
+      memcpy(partial_packet->data, packet->data, packet->len);
+
+      // Update the ACL data size to indicate the full expected length
+      stream = partial_packet->data;
+      STREAM_SKIP_UINT16(stream); // skip the handle
+      UINT16_TO_STREAM(stream, full_length - HCI_ACL_PREAMBLE_SIZE);
+
+      hash_map_set(partial_packets, (void *)(uintptr_t)handle, partial_packet);
+      // Free the old packet buffer, since we don't need it anymore
+      buffer_allocator->free(packet);
+    } else {
+      if (!partial_packet) {
+        LOG_WARN("%s got continuation for unknown packet. Dropping it.", __func__);
+        buffer_allocator->free(packet);
+        return;
+      }
+
+      packet->offset = HCI_ACL_PREAMBLE_SIZE;
+      uint16_t projected_offset = partial_packet->offset + (packet->len - HCI_ACL_PREAMBLE_SIZE);
+      if (projected_offset > partial_packet->len) { // len stores the expected length
+        LOG_WARN("%s got packet which would exceed expected length of %d. Truncating.", __func__, partial_packet->len);
+        packet->len = partial_packet->len - partial_packet->offset;
+        projected_offset = partial_packet->len;
+      }
+
+      memcpy(
+        partial_packet->data + partial_packet->offset,
+        packet->data + packet->offset,
+        packet->len - packet->offset
+      );
+
+      // Free the old packet buffer, since we don't need it anymore
+      buffer_allocator->free(packet);
+      partial_packet->offset = projected_offset;
+
+      if (partial_packet->offset == partial_packet->len) {
+        hash_map_erase(partial_packets, (void *)(uintptr_t)handle);
+        partial_packet->offset = 0;
+        callbacks->reassembled(partial_packet);
+      }
+    }
+  } else {
+    callbacks->reassembled(packet);
+  }
+}
+
+static const packet_fragmenter_t interface = {
+  init,
+  cleanup,
+
+  fragment_and_dispatch,
+  reassemble_and_dispatch
+};
+
+const packet_fragmenter_t *packet_fragmenter_get_interface() {
+  controller = controller_get_interface();
+  buffer_allocator = buffer_allocator_get_interface();
+  return &interface;
+}
+
+const packet_fragmenter_t *packet_fragmenter_get_test_interface(
+    const controller_t *controller_interface,
+    const allocator_t *buffer_allocator_interface) {
+  controller = controller_interface;
+  buffer_allocator = buffer_allocator_interface;
+  return &interface;
+}
diff --git a/hci/src/userial.c b/hci/src/userial.c
deleted file mode 100644
index 7d892f9..0000000
--- a/hci/src/userial.c
+++ /dev/null
@@ -1,419 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Filename:      userial.c
- *
- *  Description:   Contains open/read/write/close functions on serial port
- *
- ******************************************************************************/
-
-#define LOG_TAG "bt_userial"
-
-#include <assert.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <memory.h>
-#include <pthread.h>
-#include <stdio.h>
-#include <sys/eventfd.h>
-#include <sys/prctl.h>
-#include <sys/socket.h>
-#include <utils/Log.h>
-
-#include "bt_hci_bdroid.h"
-#include "bt_utils.h"
-#include "bt_vendor_lib.h"
-#include "userial.h"
-#include "utils.h"
-#include "vendor.h"
-
-/******************************************************************************
-**  Constants & Macros
-******************************************************************************/
-
-#ifndef USERIAL_DBG
-#define USERIAL_DBG TRUE
-#endif
-
-#if (USERIAL_DBG == TRUE)
-#define USERIALDBG(param, ...) {ALOGD(param, ## __VA_ARGS__);}
-#else
-#define USERIALDBG(param, ...) {}
-#endif
-
-#define MAX_SERIAL_PORT (USERIAL_PORT_3 + 1)
-
-// The set of events one can send to the userial read thread.
-// Note that the values must be >= 0x8000000000000000 to guarantee delivery
-// of the message (see eventfd(2) for details on blocking behaviour).
-enum {
-    USERIAL_RX_EXIT     = 0x8000000000000000ULL
-};
-
-/******************************************************************************
-**  Externs
-******************************************************************************/
-
-/******************************************************************************
-**  Local type definitions
-******************************************************************************/
-
-typedef struct
-{
-    int             fd;
-    uint8_t         port;
-    pthread_t       read_thread;
-    BUFFER_Q        rx_q;
-    HC_BT_HDR      *p_rx_hdr;
-} tUSERIAL_CB;
-
-/******************************************************************************
-**  Static variables
-******************************************************************************/
-
-static tUSERIAL_CB userial_cb;
-static volatile uint8_t userial_running = 0;
-
-/*****************************************************************************
-**   Socket signal functions to wake up userial_read_thread for termination
-**
-**   creating an unnamed pair of connected sockets
-**      - signal_fds[0]: join fd_set in select call of userial_read_thread
-**      - signal_fds[1]: trigger from userial_close
-*****************************************************************************/
-static int event_fd = -1;
-
-static inline int add_event_fd(fd_set *set) {
-    if (event_fd == -1) {
-      event_fd = eventfd(0, 0);
-      if (event_fd == -1) {
-          ALOGE("%s unable to create event fd: %s", __func__, strerror(errno));
-          return -1;
-      }
-    }
-
-    FD_SET(event_fd, set);
-    return event_fd;
-}
-
-static inline void send_event(uint64_t event_id) {
-    assert(event_fd != -1);
-    eventfd_write(event_fd, event_id);
-}
-
-static inline uint64_t read_event() {
-    assert(event_fd != -1);
-
-    uint64_t value = 0;
-    eventfd_read(event_fd, &value);
-    return value;
-}
-
-static inline bool is_event_available(fd_set *set) {
-    assert(event_fd != -1);
-    return !!FD_ISSET(event_fd, set);
-}
-
-/*******************************************************************************
-**
-** Function        select_read
-**
-** Description     check if fd is ready for reading and listen for termination
-**                  signal. need to use select in order to avoid collision
-**                  between read and close on the same fd
-**
-** Returns         -1: termination
-**                 >=0: numbers of bytes read back from fd
-**
-*******************************************************************************/
-static int select_read(int fd, uint8_t *pbuf, int len)
-{
-    fd_set input;
-    int n = 0, ret = -1;
-
-    while (userial_running)
-    {
-        /* Initialize the input fd set */
-        FD_ZERO(&input);
-        FD_SET(fd, &input);
-        int fd_max = add_event_fd(&input);
-        fd_max = fd_max > fd ? fd_max : fd;
-
-        /* Do the select */
-        n = select(fd_max+1, &input, NULL, NULL, NULL);
-        if(is_event_available(&input))
-        {
-            uint64_t event = read_event();
-            switch (event) {
-                case USERIAL_RX_EXIT:
-                    USERIALDBG("RX termination");
-                    return -1;
-            }
-        }
-
-        if (n > 0)
-        {
-            /* We might have input */
-            if (FD_ISSET(fd, &input))
-            {
-                ret = read(fd, pbuf, (size_t)len);
-                if (0 == ret)
-                    ALOGW( "read() returned 0!" );
-
-                return ret;
-            }
-        }
-        else if (n < 0)
-            ALOGW( "select() Failed");
-        else if (n == 0)
-            ALOGW( "Got a select() TIMEOUT");
-
-    }
-
-    return ret;
-}
-
-static void *userial_read_thread(void *arg)
-{
-    int rx_length = 0;
-    HC_BT_HDR *p_buf = NULL;
-    uint8_t *p;
-    UNUSED(arg);
-
-    USERIALDBG("Entering userial_read_thread()");
-    prctl(PR_SET_NAME, (unsigned long)"userial_read", 0, 0, 0);
-
-    userial_running = 1;
-
-    raise_priority_a2dp(TASK_HIGH_USERIAL_READ);
-
-    while (userial_running)
-    {
-        if (bt_hc_cbacks)
-        {
-            p_buf = (HC_BT_HDR *) bt_hc_cbacks->alloc(
-                        BT_HC_HDR_SIZE + HCI_MAX_FRAME_SIZE + 1); /* H4 HDR = 1 */
-        }
-        else
-            p_buf = NULL;
-
-        if (p_buf != NULL)
-        {
-            p_buf->offset = 0;
-            p_buf->layer_specific = 0;
-
-            p = (uint8_t *) (p_buf + 1);
-            int userial_fd = userial_cb.fd;
-            if (userial_fd != -1)
-                rx_length = select_read(userial_fd, p, HCI_MAX_FRAME_SIZE + 1);
-            else
-                rx_length = 0;
-        }
-        else
-        {
-            rx_length = 0;
-            utils_delay(100);
-            ALOGW("userial_read_thread() failed to gain buffers");
-            continue;
-        }
-
-
-        if (rx_length > 0)
-        {
-            p_buf->len = (uint16_t)rx_length;
-            utils_enqueue(&(userial_cb.rx_q), p_buf);
-            bthc_rx_ready();
-        }
-        else /* either 0 or < 0 */
-        {
-            ALOGW("select_read return size <=0:%d, exiting userial_read_thread",\
-                 rx_length);
-            /* if we get here, we should have a buffer */
-            bt_hc_cbacks->dealloc(p_buf);
-            /* negative value means exit thread */
-            break;
-        }
-    } /* for */
-
-    userial_running = 0;
-    USERIALDBG("Leaving userial_read_thread()");
-    pthread_exit(NULL);
-
-    return NULL;    // Compiler friendly
-}
-
-
-/*****************************************************************************
-**   Userial API Functions
-*****************************************************************************/
-
-bool userial_init(void)
-{
-    USERIALDBG("userial_init");
-    memset(&userial_cb, 0, sizeof(tUSERIAL_CB));
-    userial_cb.fd = -1;
-    utils_queue_init(&userial_cb.rx_q);
-    return true;
-}
-
-bool userial_open(userial_port_t port) {
-    if (port >= MAX_SERIAL_PORT) {
-        ALOGE("%s serial port %d > %d (max).", __func__, port, MAX_SERIAL_PORT);
-        return false;
-    }
-
-    if (userial_running) {
-        userial_close();
-        utils_delay(50);
-    }
-
-    // Call in to the vendor-specific library to open the serial port.
-    int fd_array[CH_MAX];
-    for (int i = 0; i < CH_MAX; i++)
-        fd_array[i] = -1;
-
-    int num_ports = vendor_send_command(BT_VND_OP_USERIAL_OPEN, &fd_array);
-
-    if (num_ports != 1) {
-        ALOGE("%s opened wrong number of ports: got %d, expected 1.", __func__, num_ports);
-        goto error;
-    }
-
-    userial_cb.fd = fd_array[0];
-    if (userial_cb.fd == -1) {
-        ALOGE("%s unable to open serial port.", __func__);
-        goto error;
-    }
-
-    userial_cb.port = port;
-
-    if (pthread_create(&userial_cb.read_thread, NULL, userial_read_thread, NULL)) {
-        ALOGE("%s unable to spawn read thread.", __func__);
-        goto error;
-    }
-
-    return true;
-
-error:
-    vendor_send_command(BT_VND_OP_USERIAL_CLOSE, NULL);
-    return false;
-}
-
-uint16_t userial_read(uint16_t msg_id, uint8_t *p_buffer, uint16_t len)
-{
-    uint16_t total_len = 0;
-    uint16_t copy_len = 0;
-    uint8_t *p_data = NULL;
-    UNUSED(msg_id);
-
-    do
-    {
-        if(userial_cb.p_rx_hdr != NULL)
-        {
-            p_data = ((uint8_t *)(userial_cb.p_rx_hdr + 1)) + \
-                     (userial_cb.p_rx_hdr->offset);
-
-            if((userial_cb.p_rx_hdr->len) <= (len - total_len))
-                copy_len = userial_cb.p_rx_hdr->len;
-            else
-                copy_len = (len - total_len);
-
-            memcpy((p_buffer + total_len), p_data, copy_len);
-
-            total_len += copy_len;
-
-            userial_cb.p_rx_hdr->offset += copy_len;
-            userial_cb.p_rx_hdr->len -= copy_len;
-
-            if(userial_cb.p_rx_hdr->len == 0)
-            {
-                if (bt_hc_cbacks)
-                    bt_hc_cbacks->dealloc(userial_cb.p_rx_hdr);
-
-                userial_cb.p_rx_hdr = NULL;
-            }
-        }
-
-        if(userial_cb.p_rx_hdr == NULL)
-        {
-            userial_cb.p_rx_hdr=(HC_BT_HDR *)utils_dequeue(&(userial_cb.rx_q));
-        }
-    } while ((userial_cb.p_rx_hdr != NULL) && (total_len < len));
-
-    return total_len;
-}
-
-uint16_t userial_write(uint16_t msg_id, const uint8_t *p_data, uint16_t len) {
-    UNUSED(msg_id);
-
-    uint16_t total = 0;
-    while (len) {
-        ssize_t ret = write(userial_cb.fd, p_data + total, len);
-        switch (ret) {
-            case -1:
-                ALOGE("%s error writing to serial port: %s", __func__, strerror(errno));
-                return total;
-            case 0:  // don't loop forever in case write returns 0.
-                return total;
-            default:
-                total += ret;
-                len -= ret;
-                break;
-        }
-    }
-
-    return total;
-}
-
-void userial_close_reader(void) {
-    // Join the reader thread if it is still running.
-    if (userial_running) {
-        send_event(USERIAL_RX_EXIT);
-        int result = pthread_join(userial_cb.read_thread, NULL);
-        USERIALDBG("%s Joined userial reader thread: %d", __func__, result);
-        if (result)
-            ALOGE("%s failed to join reader thread: %d", __func__, result);
-        return;
-    }
-    ALOGW("%s Already closed userial reader thread", __func__);
-}
-
-void userial_close(void) {
-    assert(bt_hc_cbacks != NULL);
-
-    // Join the reader thread if it's still running.
-    if (userial_running) {
-        send_event(USERIAL_RX_EXIT);
-        int result = pthread_join(userial_cb.read_thread, NULL);
-        if (result)
-            ALOGE("%s failed to join reader thread: %d", __func__, result);
-    }
-
-    // Ask the vendor-specific library to close the serial port.
-    vendor_send_command(BT_VND_OP_USERIAL_CLOSE, NULL);
-
-    // Free all buffers still waiting in the RX queue.
-    // TODO: use list data structure and clean this up.
-    void *buf;
-    while ((buf = utils_dequeue(&userial_cb.rx_q)) != NULL)
-        bt_hc_cbacks->dealloc(buf);
-
-    userial_cb.fd = -1;
-}
diff --git a/hci/src/userial_mct.c b/hci/src/userial_mct.c
deleted file mode 100644
index 53f954e..0000000
--- a/hci/src/userial_mct.c
+++ /dev/null
@@ -1,371 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Filename:      userial_mct.c
- *
- *  Description:   Contains open/read/write/close functions on multi-channels
- *
- ******************************************************************************/
-
-#define LOG_TAG "bt_userial_mct"
-
-#include <utils/Log.h>
-#include <pthread.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <stdio.h>
-#include <sys/socket.h>
-#include "bt_hci_bdroid.h"
-#include "userial.h"
-#include "utils.h"
-#include "vendor.h"
-#include "bt_vendor_lib.h"
-#include "bt_utils.h"
-
-/******************************************************************************
-**  Constants & Macros
-******************************************************************************/
-
-#define USERIAL_DBG TRUE
-
-#ifndef USERIAL_DBG
-#define USERIAL_DBG FALSE
-#endif
-
-#if (USERIAL_DBG == TRUE)
-#define USERIALDBG(param, ...) {ALOGD(param, ## __VA_ARGS__);}
-#else
-#define USERIALDBG(param, ...) {}
-#endif
-
-#define MAX_SERIAL_PORT (USERIAL_PORT_3 + 1)
-
-enum {
-    USERIAL_RX_EXIT,
-};
-
-/******************************************************************************
-**  Externs
-******************************************************************************/
-uint16_t hci_mct_receive_evt_msg(void);
-uint16_t hci_mct_receive_acl_msg(void);
-
-
-/******************************************************************************
-**  Local type definitions
-******************************************************************************/
-
-typedef struct
-{
-    int             fd[CH_MAX];
-    uint8_t         port;
-    pthread_t       read_thread;
-    BUFFER_Q        rx_q;
-    HC_BT_HDR      *p_rx_hdr;
-} tUSERIAL_CB;
-
-/******************************************************************************
-**  Static variables
-******************************************************************************/
-
-static tUSERIAL_CB userial_cb;
-static volatile uint8_t userial_running = 0;
-
-/******************************************************************************
-**  Static functions
-******************************************************************************/
-
-/*****************************************************************************
-**   Socket signal functions to wake up userial_read_thread for termination
-**
-**   creating an unnamed pair of connected sockets
-**      - signal_fds[0]: join fd_set in select call of userial_read_thread
-**      - signal_fds[1]: trigger from userial_close
-*****************************************************************************/
-static int signal_fds[2]={0,1};
-static inline int create_signal_fds(fd_set* set)
-{
-    if(signal_fds[0]==0 && socketpair(AF_UNIX, SOCK_STREAM, 0, signal_fds)<0)
-    {
-        ALOGE("create_signal_sockets:socketpair failed, errno: %d", errno);
-        return -1;
-    }
-    FD_SET(signal_fds[0], set);
-    return signal_fds[0];
-}
-static inline int send_wakeup_signal(char sig_cmd)
-{
-    return send(signal_fds[1], &sig_cmd, sizeof(sig_cmd), 0);
-}
-static inline char reset_signal()
-{
-    char sig_recv = -1;
-    recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL);
-    return sig_recv;
-}
-static inline int is_signaled(fd_set* set)
-{
-    return FD_ISSET(signal_fds[0], set);
-}
-
-/*******************************************************************************
-**
-** Function        userial_evt_read_thread
-**
-** Description     The reading thread on EVT and ACL_IN channels
-**
-** Returns         void *
-**
-*******************************************************************************/
-static void *userial_read_thread(void *arg)
-{
-    UNUSED(arg);
-
-    fd_set input;
-    int n;
-    char reason = 0;
-
-    USERIALDBG("Entering userial_read_thread()");
-
-    userial_running = 1;
-
-    raise_priority_a2dp(TASK_HIGH_USERIAL_READ);
-
-    while (userial_running)
-    {
-        /* Initialize the input fd set */
-        FD_ZERO(&input);
-        FD_SET(userial_cb.fd[CH_EVT], &input);
-        FD_SET(userial_cb.fd[CH_ACL_IN], &input);
-
-        int fd_max = create_signal_fds(&input);
-        fd_max = (fd_max>userial_cb.fd[CH_EVT]) ? fd_max : userial_cb.fd[CH_EVT];
-        fd_max = (fd_max>userial_cb.fd[CH_ACL_IN]) ? fd_max : userial_cb.fd[CH_ACL_IN];
-
-        /* Do the select */
-        n = 0;
-        n = select(fd_max+1, &input, NULL, NULL, NULL);
-        if(is_signaled(&input))
-        {
-            reason = reset_signal();
-            if (reason == USERIAL_RX_EXIT)
-            {
-                ALOGI("exiting userial_read_thread");
-                userial_running = 0;
-                break;
-            }
-        }
-
-        if (n > 0)
-        {
-            /* We might have input */
-            if (FD_ISSET(userial_cb.fd[CH_EVT], &input))
-            {
-                hci_mct_receive_evt_msg();
-            }
-
-            if (FD_ISSET(userial_cb.fd[CH_ACL_IN], &input))
-            {
-                hci_mct_receive_acl_msg();
-            }
-        }
-        else if (n < 0)
-            ALOGW( "select() Failed");
-        else if (n == 0)
-            ALOGW( "Got a select() TIMEOUT");
-    } /* while */
-
-    userial_running = 0;
-    USERIALDBG("Leaving userial_evt_read_thread()");
-    pthread_exit(NULL);
-
-    return NULL;    // Compiler friendly
-}
-
-
-/*****************************************************************************
-**   Userial API Functions
-*****************************************************************************/
-
-/*******************************************************************************
-**
-** Function        userial_init
-**
-** Description     Initializes the userial driver
-**
-*******************************************************************************/
-bool userial_init(void)
-{
-    int idx;
-
-    USERIALDBG("userial_init");
-    memset(&userial_cb, 0, sizeof(tUSERIAL_CB));
-    for (idx=0; idx < CH_MAX; idx++)
-        userial_cb.fd[idx] = -1;
-    utils_queue_init(&(userial_cb.rx_q));
-    return true;
-}
-
-
-/*******************************************************************************
-**
-** Function        userial_open
-**
-** Description     Open Bluetooth device with the port ID
-**
-*******************************************************************************/
-bool userial_open(userial_port_t port)
-{
-    int result;
-
-    USERIALDBG("userial_open(port:%d)", port);
-
-    if (userial_running)
-    {
-        /* Userial is open; close it first */
-        userial_close();
-        utils_delay(50);
-    }
-
-    if (port >= MAX_SERIAL_PORT)
-    {
-        ALOGE("Port > MAX_SERIAL_PORT");
-        return false;
-    }
-
-    result = vendor_send_command(BT_VND_OP_USERIAL_OPEN, &userial_cb.fd);
-    if ((result != 2) && (result != 4))
-    {
-        ALOGE("userial_open: wrong numbers of open fd in vendor lib [%d]!",
-                result);
-        ALOGE("userial_open: HCI MCT expects 2 or 4 open file descriptors");
-        vendor_send_command(BT_VND_OP_USERIAL_CLOSE, NULL);
-        return false;
-    }
-
-    ALOGI("CMD=%d, EVT=%d, ACL_Out=%d, ACL_In=%d", \
-        userial_cb.fd[CH_CMD], userial_cb.fd[CH_EVT], \
-        userial_cb.fd[CH_ACL_OUT], userial_cb.fd[CH_ACL_IN]);
-
-    if ((userial_cb.fd[CH_CMD] == -1) || (userial_cb.fd[CH_EVT] == -1) ||
-        (userial_cb.fd[CH_ACL_OUT] == -1) || (userial_cb.fd[CH_ACL_IN] == -1))
-    {
-        ALOGE("userial_open: failed to open BT transport");
-        vendor_send_command(BT_VND_OP_USERIAL_CLOSE, NULL);
-        return false;
-    }
-
-    userial_cb.port = port;
-
-    /* Start listening thread */
-    if (pthread_create(&userial_cb.read_thread, NULL, userial_read_thread, NULL) != 0)
-    {
-        ALOGE("pthread_create failed!");
-        vendor_send_command(BT_VND_OP_USERIAL_CLOSE, NULL);
-        return false;
-    }
-
-    return true;
-}
-
-/*******************************************************************************
-**
-** Function        userial_read
-**
-** Description     Read data from the userial channel
-**
-** Returns         Number of bytes actually read from the userial port and
-**                 copied into p_data.  This may be less than len.
-**
-*******************************************************************************/
-uint16_t userial_read(uint16_t msg_id, uint8_t *p_buffer, uint16_t len)
-{
-    int ret = -1;
-    int ch_idx = (msg_id == MSG_HC_TO_STACK_HCI_EVT) ? CH_EVT : CH_ACL_IN;
-
-    ret = read(userial_cb.fd[ch_idx], p_buffer, (size_t)len);
-    if (ret <= 0)
-        ALOGW( "userial_read: read() returned %d!", ret);
-
-    return (uint16_t) ((ret >= 0) ? ret : 0);
-}
-
-/*******************************************************************************
-**
-** Function        userial_write
-**
-** Description     Write data to the userial port
-**
-** Returns         Number of bytes actually written to the userial port. This
-**                 may be less than len.
-**
-*******************************************************************************/
-uint16_t userial_write(uint16_t msg_id, const uint8_t *p_data, uint16_t len)
-{
-    int ret, total = 0;
-    int ch_idx = (msg_id == MSG_STACK_TO_HC_HCI_CMD) ? CH_CMD : CH_ACL_OUT;
-
-    while(len != 0)
-    {
-        ret = write(userial_cb.fd[ch_idx], p_data+total, len);
-        total += ret;
-        len -= ret;
-    }
-
-    return ((uint16_t)total);
-}
-
-void userial_close_reader(void) {
-    // Join the reader thread if it is still running.
-    if (userial_running) {
-        send_wakeup_signal(USERIAL_RX_EXIT);
-        int result = pthread_join(userial_cb.read_thread, NULL);
-        USERIALDBG("%s Joined userial reader thread: %d", __func__, result);
-        if (result)
-            ALOGE("%s failed to join reader thread: %d", __func__, result);
-        return;
-    }
-    ALOGW("%s Already closed userial reader thread", __func__);
-}
-
-/*******************************************************************************
-**
-** Function        userial_close
-**
-** Description     Close the userial port
-**
-*******************************************************************************/
-void userial_close(void)
-{
-    int idx, result;
-
-    USERIALDBG("userial_close");
-
-    if (userial_running)
-        send_wakeup_signal(USERIAL_RX_EXIT);
-
-    if ((result=pthread_join(userial_cb.read_thread, NULL)) < 0)
-        ALOGE( "pthread_join() FAILED result:%d", result);
-
-    vendor_send_command(BT_VND_OP_USERIAL_CLOSE, NULL);
-
-    for (idx=0; idx < CH_MAX; idx++)
-        userial_cb.fd[idx] = -1;
-}
diff --git a/hci/src/utils.c b/hci/src/utils.c
deleted file mode 100644
index 85304fa..0000000
--- a/hci/src/utils.c
+++ /dev/null
@@ -1,309 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Filename:      utils.c
- *
- *  Description:   Contains helper functions
- *
- ******************************************************************************/
-
-#include <errno.h>
-#include <pthread.h>
-#include <time.h>
-#include "bt_hci_bdroid.h"
-#include "utils.h"
-
-/******************************************************************************
-**  Static variables
-******************************************************************************/
-
-static pthread_mutex_t utils_mutex;
-
-/*****************************************************************************
-**   UTILS INTERFACE FUNCTIONS
-*****************************************************************************/
-
-/*******************************************************************************
-**
-** Function        utils_init
-**
-** Description     Utils initialization
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_init (void)
-{
-    pthread_mutex_init(&utils_mutex, NULL);
-}
-
-/*******************************************************************************
-**
-** Function        utils_cleanup
-**
-** Description     Utils cleanup
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_cleanup (void)
-{
-    pthread_mutex_destroy(&utils_mutex);
-}
-
-/*******************************************************************************
-**
-** Function        utils_queue_init
-**
-** Description     Initialize the given buffer queue
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_queue_init (BUFFER_Q *p_q)
-{
-    p_q->p_first = p_q->p_last = NULL;
-    p_q->count = 0;
-}
-
-/*******************************************************************************
-**
-** Function        utils_enqueue
-**
-** Description     Enqueue a buffer at the tail of the given queue
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_enqueue (BUFFER_Q *p_q, void *p_buf)
-{
-    HC_BUFFER_HDR_T    *p_hdr;
-
-    p_hdr = (HC_BUFFER_HDR_T *) ((uint8_t *) p_buf - BT_HC_BUFFER_HDR_SIZE);
-
-    pthread_mutex_lock(&utils_mutex);
-
-    if (p_q->p_last)
-    {
-        HC_BUFFER_HDR_T *p_last_hdr = \
-          (HC_BUFFER_HDR_T *)((uint8_t *)p_q->p_last - BT_HC_BUFFER_HDR_SIZE);
-
-        p_last_hdr->p_next = p_hdr;
-    }
-    else
-        p_q->p_first = p_buf;
-
-    p_q->p_last = p_buf;
-    p_q->count++;
-
-    p_hdr->p_next = NULL;
-
-    pthread_mutex_unlock(&utils_mutex);
-}
-/*******************************************************************************
-**
-** Function        utils_dequeue
-**
-** Description     Dequeues a buffer from the head of the given queue
-**
-** Returns         NULL if queue is empty, else buffer
-**
-*******************************************************************************/
-void *utils_dequeue (BUFFER_Q *p_q)
-{
-    pthread_mutex_lock(&utils_mutex);
-    void* p_buf =  utils_dequeue_unlocked(p_q);
-    pthread_mutex_unlock(&utils_mutex);
-    return p_buf;
-}
-
-/*******************************************************************************
-**
-** Function        utils_dequeue_unlocked
-**
-** Description     Dequeues a buffer from the head of the given queue without lock
-**
-** Returns         NULL if queue is empty, else buffer
-**
-*******************************************************************************/
-void *utils_dequeue_unlocked (BUFFER_Q *p_q)
-{
-    HC_BUFFER_HDR_T    *p_hdr;
-
-
-    if (!p_q || !p_q->count)
-    {
-        return (NULL);
-    }
-
-    p_hdr=(HC_BUFFER_HDR_T *)((uint8_t *)p_q->p_first-BT_HC_BUFFER_HDR_SIZE);
-
-    if (p_hdr->p_next)
-        p_q->p_first = ((uint8_t *)p_hdr->p_next + BT_HC_BUFFER_HDR_SIZE);
-    else
-    {
-        p_q->p_first = NULL;
-        p_q->p_last  = NULL;
-    }
-
-    p_q->count--;
-
-    p_hdr->p_next = NULL;
-    return ((uint8_t *)p_hdr + BT_HC_BUFFER_HDR_SIZE);
-}
-
-/*******************************************************************************
-**
-** Function        utils_getnext
-**
-** Description     Return a pointer to the next buffer linked to the given
-**                 buffer
-**
-** Returns         NULL if the given buffer does not point to any next buffer,
-**                 else next buffer address
-**
-*******************************************************************************/
-void *utils_getnext (void *p_buf)
-{
-    HC_BUFFER_HDR_T    *p_hdr;
-
-    p_hdr = (HC_BUFFER_HDR_T *) ((uint8_t *) p_buf - BT_HC_BUFFER_HDR_SIZE);
-
-    if (p_hdr->p_next)
-        return ((uint8_t *)p_hdr->p_next + BT_HC_BUFFER_HDR_SIZE);
-    else
-        return (NULL);
-}
-
-/*******************************************************************************
-**
-** Function        utils_remove_from_queue
-**
-** Description     Dequeue the given buffer from the middle of the given queue
-**
-** Returns         NULL if the given queue is empty, else the given buffer
-**
-*******************************************************************************/
-void *utils_remove_from_queue (BUFFER_Q *p_q, void *p_buf)
-{
-    pthread_mutex_lock(&utils_mutex);
-    p_buf = utils_remove_from_queue_unlocked(p_q, p_buf);
-    pthread_mutex_unlock(&utils_mutex);
-    return p_buf;
-}
-/*******************************************************************************
-**
-** Function        utils_remove_from_queue_unlocked
-**
-** Description     Dequeue the given buffer from the middle of the given queue
-**
-** Returns         NULL if the given queue is empty, else the given buffer
-**
-*******************************************************************************/
-void *utils_remove_from_queue_unlocked (BUFFER_Q *p_q, void *p_buf)
-{
-    HC_BUFFER_HDR_T    *p_prev;
-    HC_BUFFER_HDR_T    *p_buf_hdr;
-
-
-    if (p_buf == p_q->p_first)
-    {
-        return (utils_dequeue_unlocked (p_q));
-    }
-
-    p_buf_hdr = (HC_BUFFER_HDR_T *)((uint8_t *)p_buf - BT_HC_BUFFER_HDR_SIZE);
-    p_prev=(HC_BUFFER_HDR_T *)((uint8_t *)p_q->p_first-BT_HC_BUFFER_HDR_SIZE);
-
-    for ( ; p_prev; p_prev = p_prev->p_next)
-    {
-        /* If the previous points to this one, move the pointers around */
-        if (p_prev->p_next == p_buf_hdr)
-        {
-            p_prev->p_next = p_buf_hdr->p_next;
-
-            /* If we are removing the last guy in the queue, update p_last */
-            if (p_buf == p_q->p_last)
-                p_q->p_last = p_prev + 1;
-
-            /* One less in the queue */
-            p_q->count--;
-
-            /* The buffer is now unlinked */
-            p_buf_hdr->p_next = NULL;
-
-            return (p_buf);
-        }
-    }
-    return (NULL);
-}
-
-/*******************************************************************************
-**
-** Function        utils_delay
-**
-** Description     sleep unconditionally for timeout milliseconds
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_delay (uint32_t timeout)
-{
-    struct timespec delay;
-    int err;
-
-    delay.tv_sec = timeout / 1000;
-    delay.tv_nsec = 1000 * 1000 * (timeout%1000);
-
-    /* [u]sleep can't be used because it uses SIGALRM */
-    do {
-        err = nanosleep(&delay, &delay);
-    } while (err < 0 && errno ==EINTR);
-}
-
-/*******************************************************************************
-**
-** Function        utils_lock
-**
-** Description     application calls this function before entering critical
-**                 section
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_lock (void)
-{
-    pthread_mutex_lock(&utils_mutex);
-}
-
-/*******************************************************************************
-**
-** Function        utils_unlock
-**
-** Description     application calls this function when leaving critical
-**                 section
-**
-** Returns         None
-**
-*******************************************************************************/
-void utils_unlock (void)
-{
-    pthread_mutex_unlock(&utils_mutex);
-}
-
diff --git a/hci/src/vendor.c b/hci/src/vendor.c
index 4bad100..2e220e4 100644
--- a/hci/src/vendor.c
+++ b/hci/src/vendor.c
@@ -20,120 +20,118 @@
 
 #include <assert.h>
 #include <dlfcn.h>
-#include <utils/Log.h>
 
-#include "bt_hci_bdroid.h"
+#include "buffer_allocator.h"
 #include "bt_vendor_lib.h"
-#include "hci.h"
-#include "osi.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "vendor.h"
 
-// TODO: eliminate these three.
-extern tHCI_IF *p_hci_if;
-extern bool fwcfg_acked;
-void lpm_vnd_cback(uint8_t vnd_result);
+#define LAST_VENDOR_OPCODE_VALUE VENDOR_DO_EPILOG
 
 static const char *VENDOR_LIBRARY_NAME = "libbt-vendor.so";
 static const char *VENDOR_LIBRARY_SYMBOL_NAME = "BLUETOOTH_VENDOR_LIB_INTERFACE";
 
+static const vendor_t interface;
+static const allocator_t *buffer_allocator;
+static const hci_t *hci;
+static vendor_cb callbacks[LAST_VENDOR_OPCODE_VALUE + 1];
+
 static void *lib_handle;
-static bt_vendor_interface_t *vendor_interface;
+static bt_vendor_interface_t *lib_interface;
+static const bt_vendor_callbacks_t lib_callbacks;
 
-static void firmware_config_cb(bt_vendor_op_result_t result);
-static void sco_config_cb(bt_vendor_op_result_t result);
-static void low_power_mode_cb(bt_vendor_op_result_t result);
-static void sco_audiostate_cb(bt_vendor_op_result_t result);
-static void *buffer_alloc(int size);
-static void buffer_free(void *buffer);
-static uint8_t transmit_cb(uint16_t opcode, void *buffer, tINT_CMD_CBACK callback);
-static void epilog_cb(bt_vendor_op_result_t result);
+// Interface functions
 
-static const bt_vendor_callbacks_t vendor_callbacks = {
-  sizeof(vendor_callbacks),
-  firmware_config_cb,
-  sco_config_cb,
-  low_power_mode_cb,
-  sco_audiostate_cb,
-  buffer_alloc,
-  buffer_free,
-  transmit_cb,
-  epilog_cb
-};
-
-bool vendor_open(const uint8_t *local_bdaddr) {
+static bool vendor_open(
+    const uint8_t *local_bdaddr,
+    const hci_t *hci_interface) {
   assert(lib_handle == NULL);
+  hci = hci_interface;
 
   lib_handle = dlopen(VENDOR_LIBRARY_NAME, RTLD_NOW);
   if (!lib_handle) {
-    ALOGE("%s unable to open %s: %s", __func__, VENDOR_LIBRARY_NAME, dlerror());
+    LOG_ERROR("%s unable to open %s: %s", __func__, VENDOR_LIBRARY_NAME, dlerror());
     goto error;
   }
 
-  vendor_interface = (bt_vendor_interface_t *)dlsym(lib_handle, VENDOR_LIBRARY_SYMBOL_NAME);
-  if (!vendor_interface) {
-    ALOGE("%s unable to find symbol %s in %s: %s", __func__, VENDOR_LIBRARY_SYMBOL_NAME, VENDOR_LIBRARY_NAME, dlerror());
+  lib_interface = (bt_vendor_interface_t *)dlsym(lib_handle, VENDOR_LIBRARY_SYMBOL_NAME);
+  if (!lib_interface) {
+    LOG_ERROR("%s unable to find symbol %s in %s: %s", __func__, VENDOR_LIBRARY_SYMBOL_NAME, VENDOR_LIBRARY_NAME, dlerror());
     goto error;
   }
 
-  int status = vendor_interface->init(&vendor_callbacks, (unsigned char *)local_bdaddr);
+  LOG_INFO("alloc value %p", lib_callbacks.alloc);
+
+  int status = lib_interface->init(&lib_callbacks, (unsigned char *)local_bdaddr);
   if (status) {
-    ALOGE("%s unable to initialize vendor library: %d", __func__, status);
+    LOG_ERROR("%s unable to initialize vendor library: %d", __func__, status);
     goto error;
   }
 
   return true;
 
 error:;
-  vendor_interface = NULL;
+  lib_interface = NULL;
   if (lib_handle)
     dlclose(lib_handle);
   lib_handle = NULL;
   return false;
 }
 
-void vendor_close(void) {
-  if (vendor_interface)
-    vendor_interface->cleanup();
+static void vendor_close(void) {
+  if (lib_interface)
+    lib_interface->cleanup();
 
   if (lib_handle)
     dlclose(lib_handle);
 
-  vendor_interface = NULL;
+  lib_interface = NULL;
   lib_handle = NULL;
 }
 
-int vendor_send_command(bt_vendor_opcode_t opcode, void *param) {
-  assert(vendor_interface != NULL);
-
-  return vendor_interface->op(opcode, param);
+static int send_command(vendor_opcode_t opcode, void *param) {
+  assert(lib_interface != NULL);
+  return lib_interface->op(opcode, param);
 }
 
+static int send_async_command(vendor_async_opcode_t opcode, void *param) {
+  assert(lib_interface != NULL);
+  return lib_interface->op(opcode, param);
+}
+
+static void set_callback(vendor_async_opcode_t opcode, vendor_cb callback) {
+  callbacks[opcode] = callback;
+}
+
+// Internal functions
+
 // Called back from vendor library when the firmware configuration
 // completes.
 static void firmware_config_cb(bt_vendor_op_result_t result) {
-  assert(bt_hc_cbacks != NULL);
-
-  fwcfg_acked = true;
-
-  bt_hc_postload_result_t status = (result == BT_VND_OP_RESULT_SUCCESS)
-      ? BT_HC_PRELOAD_SUCCESS
-      : BT_HC_PRELOAD_FAIL;
-  bt_hc_cbacks->preload_cb(NULL, status);
+  LOG_INFO("firmware callback");
+  vendor_cb callback = callbacks[VENDOR_CONFIGURE_FIRMWARE];
+  assert(callback != NULL);
+  callback(result == BT_VND_OP_RESULT_SUCCESS);
 }
 
 // Called back from vendor library to indicate status of previous
 // SCO configuration request. This should only happen during the
 // postload process.
-static void sco_config_cb(UNUSED_ATTR bt_vendor_op_result_t result) {
-  assert(p_hci_if != NULL);
-
-  // Continue the rest of the postload process.
-  p_hci_if->get_acl_max_len();
+static void sco_config_cb(bt_vendor_op_result_t result) {
+  LOG_INFO("%s", __func__);
+  vendor_cb callback = callbacks[VENDOR_CONFIGURE_SCO];
+  assert(callback != NULL);
+  callback(result == BT_VND_OP_RESULT_SUCCESS);
 }
 
 // Called back from vendor library to indicate status of previous
 // LPM enable/disable request.
 static void low_power_mode_cb(bt_vendor_op_result_t result) {
-  lpm_vnd_cback(result != BT_VND_OP_RESULT_SUCCESS);
+  LOG_INFO("%s", __func__);
+  vendor_cb callback = callbacks[VENDOR_SET_LPM_MODE];
+  assert(callback != NULL);
+  callback(result == BT_VND_OP_RESULT_SUCCESS);
 }
 
 /******************************************************************************
@@ -151,30 +149,64 @@
 {
     uint8_t status = (result == BT_VND_OP_RESULT_SUCCESS) ? 0 : 1;
 
-    ALOGI("sco_audiostate_cb(status: %d)",status);
+    LOG_INFO("sco_audiostate_cb(status: %d)",status);
 }
 
 // Called by vendor library when it needs an HCI buffer.
-static void *buffer_alloc(int size) {
-  assert(bt_hc_cbacks != NULL);
-  return bt_hc_cbacks->alloc(size);
+static void *buffer_alloc_cb(int size) {
+  return buffer_allocator->alloc(size);
 }
 
 // Called by vendor library when it needs to free a buffer allocated with
-// |buffer_alloc|.
-static void buffer_free(void *buffer) {
-  assert(bt_hc_cbacks != NULL);
-  bt_hc_cbacks->dealloc(buffer);
+// |buffer_alloc_cb|.
+static void buffer_free_cb(void *buffer) {
+  buffer_allocator->free(buffer);
+}
+
+static void transmit_completed_callback(BT_HDR *response, void *context) {
+  // Call back to the vendor library if it provided a callback to call.
+  if (context)
+    ((tINT_CMD_CBACK)context)(response);
 }
 
 // Called back from vendor library when it wants to send an HCI command.
-static uint8_t transmit_cb(uint16_t opcode, void *buffer, tINT_CMD_CBACK callback) {
-  assert(p_hci_if != NULL);
-  return p_hci_if->send_int_cmd(opcode, (HC_BT_HDR *)buffer, callback);
+static uint8_t transmit_cb(UNUSED_ATTR uint16_t opcode, void *buffer, tINT_CMD_CBACK callback) {
+  assert(hci != NULL);
+  hci->transmit_command((BT_HDR *)buffer, transmit_completed_callback, NULL, callback);
+  return true;
 }
 
 // Called back from vendor library when the epilog procedure has
 // completed. It is safe to call vendor_interface->cleanup() after
 // this callback has been received.
-static void epilog_cb(UNUSED_ATTR bt_vendor_op_result_t result) {
+static void epilog_cb(bt_vendor_op_result_t result) {
+  LOG_INFO("%s", __func__);
+  vendor_cb callback = callbacks[VENDOR_DO_EPILOG];
+  assert(callback != NULL);
+  callback(result == BT_VND_OP_RESULT_SUCCESS);
+}
+
+static const bt_vendor_callbacks_t lib_callbacks = {
+  sizeof(lib_callbacks),
+  firmware_config_cb,
+  sco_config_cb,
+  low_power_mode_cb,
+  sco_audiostate_cb,
+  buffer_alloc_cb,
+  buffer_free_cb,
+  transmit_cb,
+  epilog_cb
+};
+
+static const vendor_t interface = {
+  vendor_open,
+  vendor_close,
+  send_command,
+  send_async_command,
+  set_callback,
+};
+
+const vendor_t *vendor_get_interface() {
+  buffer_allocator = buffer_allocator_get_interface();
+  return &interface;
 }
diff --git a/hci/test/hci_hal_h4_test.cpp b/hci/test/hci_hal_h4_test.cpp
new file mode 100644
index 0000000..2c4030d
--- /dev/null
+++ b/hci/test/hci_hal_h4_test.cpp
@@ -0,0 +1,263 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+#include "AllocationTestHarness.h"
+
+extern "C" {
+#include <stdint.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include "hci_hal.h"
+#include "osi.h"
+#include "semaphore.h"
+#include "test_stubs.h"
+#include "vendor.h"
+}
+
+DECLARE_TEST_MODES(
+  init,
+  open,
+  close_fn,
+  transmit,
+  read_synchronous,
+  read_async_reentry,
+  type_byte_only
+);
+
+static char sample_data1[100] = "A point is that which has no part.";
+static char sample_data2[100] = "A line is breadthless length.";
+static char sample_data3[100] = "The ends of a line are points.";
+static char acl_data[100] =     "A straight line is a line which lies evenly with the points on itself.";
+static char sco_data[100] =     "A surface is that which has length and breadth only.";
+static char event_data[100] =   "The edges of a surface are lines.";
+
+static const hci_hal_t *hal;
+static int dummy_serial_fd;
+static int reentry_i = 0;
+
+static semaphore_t *done;
+static semaphore_t *reentry_semaphore;
+
+static void expect_packet_synchronous(serial_data_type_t type, char *packet_data) {
+  int length = strlen(packet_data);
+  for (int i = 0; i < length; i++) {
+    uint8_t byte;
+    EXPECT_EQ((size_t)1, hal->read_data(type, &byte, 1, true));
+    EXPECT_EQ(packet_data[i], byte);
+  }
+
+  hal->packet_finished(type);
+}
+
+STUB_FUNCTION(int, vendor_send_command, (vendor_opcode_t opcode, void *param))
+  DURING(open) AT_CALL(0) {
+    EXPECT_EQ(VENDOR_OPEN_USERIAL, opcode);
+    // Give back the dummy fd and the number 1 to say we opened 1 port
+    ((int *)param)[0] = dummy_serial_fd;
+    return 1;
+  }
+
+  DURING(close_fn) AT_CALL(0) {
+    EXPECT_EQ(VENDOR_CLOSE_USERIAL, opcode);
+    return 0;
+  }
+
+  UNEXPECTED_CALL;
+  return 0;
+}
+
+STUB_FUNCTION(void, data_ready_callback, (serial_data_type_t type))
+  DURING(read_synchronous) {
+    AT_CALL(0) {
+      EXPECT_EQ(DATA_TYPE_ACL, type);
+      expect_packet_synchronous(type, acl_data);
+      return;
+    }
+    AT_CALL(1) {
+      EXPECT_EQ(DATA_TYPE_SCO, type);
+      expect_packet_synchronous(type, sco_data);
+      return;
+    }
+    AT_CALL(2) {
+      EXPECT_EQ(DATA_TYPE_EVENT, type);
+      expect_packet_synchronous(type, event_data);
+      semaphore_post(done);
+      return;
+    }
+  }
+
+  DURING(read_async_reentry) {
+    EXPECT_EQ(DATA_TYPE_ACL, type);
+
+    uint8_t byte;
+    size_t bytes_read;
+    while ((bytes_read = hal->read_data(type, &byte, 1, false)) != 0) {
+      EXPECT_EQ(sample_data3[reentry_i], byte);
+      semaphore_post(reentry_semaphore);
+      reentry_i++;
+      if (reentry_i == (int)strlen(sample_data3)) {
+        hal->packet_finished(type);
+        return;
+      }
+    }
+
+    return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+static void reset_for(TEST_MODES_T next) {
+  RESET_CALL_COUNT(vendor_send_command);
+  RESET_CALL_COUNT(data_ready_callback);
+  CURRENT_TEST_MODE = next;
+}
+
+class HciHalH4Test : public AllocationTestHarness {
+  protected:
+    virtual void SetUp() {
+      AllocationTestHarness::SetUp();
+      hal = hci_hal_h4_get_test_interface(&vendor);
+      vendor.send_command = vendor_send_command;
+      callbacks.data_ready = data_ready_callback;
+
+      socketpair(AF_LOCAL, SOCK_STREAM, 0, sockfd);
+      dummy_serial_fd = sockfd[0];
+      done = semaphore_new(0);
+      thread = thread_new("hal_test");
+
+      reset_for(init);
+      EXPECT_TRUE(hal->init(&callbacks, thread));
+
+      reset_for(open);
+      EXPECT_TRUE(hal->open());
+      EXPECT_CALL_COUNT(vendor_send_command, 1);
+    }
+
+    virtual void TearDown() {
+      reset_for(close_fn);
+      hal->close();
+      EXPECT_CALL_COUNT(vendor_send_command, 1);
+
+      semaphore_free(done);
+      thread_free(thread);
+      AllocationTestHarness::TearDown();
+    }
+
+    int sockfd[2];
+    vendor_t vendor;
+    thread_t *thread;
+    hci_hal_callbacks_t callbacks;
+};
+
+static void expect_socket_data(int fd, char first_byte, char *data) {
+  int length = strlen(data) + 1; // + 1 for data type code
+  int i;
+
+  for (i = 0; i < length; i++) {
+    fd_set read_fds;
+    FD_ZERO(&read_fds);
+    FD_SET(fd, &read_fds);
+    select(fd + 1, &read_fds, NULL, NULL, NULL);
+
+    char byte;
+    read(fd, &byte, 1);
+
+    EXPECT_EQ(i == 0 ? first_byte : data[i - 1], byte);
+  }
+}
+
+static void write_packet(int fd, char first_byte, char *data) {
+  write(fd, &first_byte, 1);
+  write(fd, data, strlen(data));
+}
+
+static void write_packet_reentry(int fd, char first_byte, char *data) {
+  write(fd, &first_byte, 1);
+
+  int length = strlen(data);
+  for (int i = 0; i < length; i++) {
+    write(fd, &data[i], 1);
+    semaphore_wait(reentry_semaphore);
+  }
+}
+
+TEST_F(HciHalH4Test, test_transmit) {
+  reset_for(transmit);
+
+  // Send a command packet
+  hal->transmit_data(DATA_TYPE_COMMAND, (uint8_t *)(sample_data1 + 1), strlen(sample_data1 + 1));
+  expect_socket_data(sockfd[1], DATA_TYPE_COMMAND, sample_data1 + 1);
+
+  // Send an acl packet
+  hal->transmit_data(DATA_TYPE_ACL, (uint8_t *)(sample_data2 + 1), strlen(sample_data2 + 1));
+  expect_socket_data(sockfd[1], DATA_TYPE_ACL, sample_data2 + 1);
+
+  // Send an sco packet
+  hal->transmit_data(DATA_TYPE_SCO, (uint8_t *)(sample_data3 + 1), strlen(sample_data3 + 1));
+  expect_socket_data(sockfd[1], DATA_TYPE_SCO, sample_data3 + 1);
+}
+
+TEST_F(HciHalH4Test, test_read_synchronous) {
+  reset_for(read_synchronous);
+
+  write_packet(sockfd[1], DATA_TYPE_ACL, acl_data);
+  write_packet(sockfd[1], DATA_TYPE_SCO, sco_data);
+  write_packet(sockfd[1], DATA_TYPE_EVENT, event_data);
+
+  // Wait for all data to be received before calling the test good
+  semaphore_wait(done);
+  EXPECT_CALL_COUNT(data_ready_callback, 3);
+}
+
+TEST_F(HciHalH4Test, test_read_async_reentry) {
+  reset_for(read_async_reentry);
+
+  reentry_semaphore = semaphore_new(0);
+  reentry_i = 0;
+
+  write_packet_reentry(sockfd[1], DATA_TYPE_ACL, sample_data3);
+
+  // write_packet_reentry ensures the data has been received
+  semaphore_free(reentry_semaphore);
+}
+
+TEST_F(HciHalH4Test, test_type_byte_only_must_not_signal_data_ready) {
+  reset_for(type_byte_only);
+
+  char byte = DATA_TYPE_ACL;
+  write(sockfd[1], &byte, 1);
+
+  fd_set read_fds;
+
+  // Wait until the byte we wrote was picked up
+  do {
+    FD_ZERO(&read_fds);
+    FD_SET(sockfd[0], &read_fds);
+
+    struct timeval timeout;
+    timeout.tv_sec = 0;
+    timeout.tv_usec = 0;
+
+    select(sockfd[0] + 1, &read_fds, NULL, NULL, &timeout);
+  } while(FD_ISSET(sockfd[0], &read_fds));
+}
diff --git a/hci/test/hci_hal_mct_test.cpp b/hci/test/hci_hal_mct_test.cpp
new file mode 100644
index 0000000..911aabc
--- /dev/null
+++ b/hci/test/hci_hal_mct_test.cpp
@@ -0,0 +1,244 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+#include "AllocationTestHarness.h"
+
+extern "C" {
+#include <stdint.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include "hci_hal.h"
+#include "osi.h"
+#include "semaphore.h"
+#include "test_stubs.h"
+#include "vendor.h"
+}
+
+DECLARE_TEST_MODES(
+  init,
+  open,
+  close_fn,
+  transmit,
+  read_synchronous,
+  read_async_reentry
+);
+
+static char sample_data1[100] = "A point is that which has no part.";
+static char sample_data2[100] = "A line is breadthless length.";
+static char sample_data3[100] = "The ends of a line are points.";
+static char acl_data[100] =     "A straight line is a line which lies evenly with the points on itself.";
+static char event_data[100] =   "The edges of a surface are lines.";
+
+static const hci_hal_t *hal;
+static int command_out_fd;
+static int acl_out_fd;
+static int acl_in_fd;
+static int event_in_fd;
+static int reentry_i = 0;
+
+static semaphore_t *done;
+static semaphore_t *reentry_semaphore;
+
+static void expect_packet_synchronous(serial_data_type_t type, char *packet_data) {
+  int length = strlen(packet_data);
+  for (int i = 0; i < length; i++) {
+    uint8_t byte;
+    EXPECT_EQ((size_t)1, hal->read_data(type, &byte, 1, true));
+    EXPECT_EQ(packet_data[i], byte);
+  }
+
+  hal->packet_finished(type);
+}
+
+STUB_FUNCTION(int, vendor_send_command, (vendor_opcode_t opcode, void *param))
+  DURING(open) AT_CALL(0) {
+    EXPECT_EQ(VENDOR_OPEN_USERIAL, opcode);
+    ((int *)param)[CH_CMD] = command_out_fd;
+    ((int *)param)[CH_ACL_OUT] = acl_out_fd;
+    ((int *)param)[CH_ACL_IN] = acl_in_fd;
+    ((int *)param)[CH_EVT] = event_in_fd;
+    return 4;
+  }
+
+  DURING(close_fn) AT_CALL(0) {
+    EXPECT_EQ(VENDOR_CLOSE_USERIAL, opcode);
+    return 0;
+  }
+
+  UNEXPECTED_CALL;
+  return 0;
+}
+
+STUB_FUNCTION(void, data_ready_callback, (serial_data_type_t type))
+  DURING(read_synchronous) {
+    AT_CALL(0) {
+      EXPECT_EQ(DATA_TYPE_ACL, type);
+      expect_packet_synchronous(type, acl_data);
+      semaphore_post(done);
+      return;
+    }
+    AT_CALL(1) {
+      EXPECT_EQ(DATA_TYPE_EVENT, type);
+      expect_packet_synchronous(type, event_data);
+      semaphore_post(done);
+      return;
+    }
+  }
+
+  DURING(read_async_reentry) {
+    EXPECT_EQ(DATA_TYPE_ACL, type);
+
+    uint8_t byte;
+    size_t bytes_read;
+    while ((bytes_read = hal->read_data(type, &byte, 1, false)) != 0) {
+      EXPECT_EQ(sample_data3[reentry_i], byte);
+      semaphore_post(reentry_semaphore);
+      reentry_i++;
+      if (reentry_i == (int)strlen(sample_data3)) {
+        hal->packet_finished(type);
+        return;
+      }
+    }
+
+    return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+static void reset_for(TEST_MODES_T next) {
+  RESET_CALL_COUNT(vendor_send_command);
+  RESET_CALL_COUNT(data_ready_callback);
+  CURRENT_TEST_MODE = next;
+}
+
+class HciHalMctTest : public AllocationTestHarness {
+  protected:
+    virtual void SetUp() {
+      AllocationTestHarness::SetUp();
+      hal = hci_hal_mct_get_test_interface(&vendor);
+      vendor.send_command = vendor_send_command;
+      callbacks.data_ready = data_ready_callback;
+
+      socketpair(AF_LOCAL, SOCK_STREAM, 0, command_sockfd);
+      socketpair(AF_LOCAL, SOCK_STREAM, 0, event_sockfd);
+      socketpair(AF_LOCAL, SOCK_STREAM, 0, acl_in_sockfd);
+      socketpair(AF_LOCAL, SOCK_STREAM, 0, acl_out_sockfd);
+      command_out_fd = command_sockfd[0];
+      acl_out_fd = acl_out_sockfd[0];
+      acl_in_fd = acl_in_sockfd[0];
+      event_in_fd = event_sockfd[0];
+
+      done = semaphore_new(0);
+      thread = thread_new("hal_test");
+
+      reset_for(init);
+      EXPECT_TRUE(hal->init(&callbacks, thread));
+
+      reset_for(open);
+      EXPECT_TRUE(hal->open());
+      EXPECT_CALL_COUNT(vendor_send_command, 1);
+    }
+
+    virtual void TearDown() {
+      reset_for(close_fn);
+      hal->close();
+      EXPECT_CALL_COUNT(vendor_send_command, 1);
+
+      semaphore_free(done);
+      thread_free(thread);
+      AllocationTestHarness::TearDown();
+    }
+
+    int command_sockfd[2];
+    int event_sockfd[2];
+    int acl_in_sockfd[2];
+    int acl_out_sockfd[2];
+    vendor_t vendor;
+    thread_t *thread;
+    hci_hal_callbacks_t callbacks;
+};
+
+static void expect_socket_data(int fd, char *data) {
+  int length = strlen(data);
+  int i;
+
+  for (i = 0; i < length; i++) {
+    fd_set read_fds;
+    FD_ZERO(&read_fds);
+    FD_SET(fd, &read_fds);
+    select(fd + 1, &read_fds, NULL, NULL, NULL);
+
+    char byte;
+    read(fd, &byte, 1);
+
+    EXPECT_EQ(data[i], byte);
+  }
+}
+
+static void write_packet(int fd, char *data) {
+  write(fd, data, strlen(data));
+}
+
+static void write_packet_reentry(int fd, char *data) {
+  int length = strlen(data);
+  for (int i = 0; i < length; i++) {
+    write(fd, &data[i], 1);
+    semaphore_wait(reentry_semaphore);
+  }
+}
+
+TEST_F(HciHalMctTest, test_transmit) {
+  reset_for(transmit);
+
+  // Send a command packet
+  hal->transmit_data(DATA_TYPE_COMMAND, (uint8_t *)(sample_data1), strlen(sample_data1));
+  expect_socket_data(command_sockfd[1], sample_data1);
+
+  // Send an acl packet
+  hal->transmit_data(DATA_TYPE_ACL, (uint8_t *)(sample_data2), strlen(sample_data2));
+  expect_socket_data(acl_out_sockfd[1], sample_data2);
+}
+
+TEST_F(HciHalMctTest, test_read_synchronous) {
+  reset_for(read_synchronous);
+
+  write_packet(acl_in_sockfd[1], acl_data);
+  semaphore_wait(done);
+
+  write_packet(event_sockfd[1], event_data);
+  semaphore_wait(done);
+
+  EXPECT_CALL_COUNT(data_ready_callback, 2);
+}
+
+TEST_F(HciHalMctTest, test_read_async_reentry) {
+  reset_for(read_async_reentry);
+
+  reentry_semaphore = semaphore_new(0);
+  reentry_i = 0;
+
+  write_packet_reentry(acl_in_sockfd[1], sample_data3);
+
+  // write_packet_reentry ensures the data has been received
+  semaphore_free(reentry_semaphore);
+}
diff --git a/hci/test/hci_layer_test.cpp b/hci/test/hci_layer_test.cpp
new file mode 100644
index 0000000..83ac060
--- /dev/null
+++ b/hci/test/hci_layer_test.cpp
@@ -0,0 +1,753 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+#include "AlarmTestHarness.h"
+
+extern "C" {
+#include <stdint.h>
+
+#include "allocation_tracker.h"
+#include "allocator.h"
+#include "btsnoop.h"
+#include "device/include/controller.h"
+#include "hcimsgs.h"
+#include "hci_hal.h"
+#include "hci_inject.h"
+#include "hci_layer.h"
+#include "low_power_manager.h"
+#include "module.h"
+#include "osi.h"
+#include "packet_fragmenter.h"
+#include "semaphore.h"
+#include "test_stubs.h"
+#include "vendor.h"
+
+extern const module_t hci_module;
+}
+
+DECLARE_TEST_MODES(
+  start_up_async,
+  shut_down,
+  postload,
+  transmit_simple,
+  receive_simple,
+  transmit_command_no_callbacks,
+  transmit_command_command_status,
+  transmit_command_command_complete,
+  ignoring_packets_ignored_packet,
+  ignoring_packets_following_packet
+);
+
+static const char *small_sample_data = "\"It is easy to see,\" replied Don Quixote";
+static const char *command_sample_data = "that thou art not used to this business of adventures; those are giants";
+static const char *ignored_data = "and if thou art afraid, away with thee out of this and betake thyself to prayer";
+static const char *unignored_data = "while I engage them in fierce and unequal combat";
+
+static const char *logging_path = "this/is/a/test/logging/path";
+
+static const hci_t *hci;
+static bdaddr_t test_addr = (bdaddr_t)"testaddress123";
+static const hci_hal_callbacks_t *hal_callbacks;
+static thread_t *internal_thread;
+static vendor_cb firmware_config_callback;
+static vendor_cb sco_config_callback;
+static vendor_cb epilog_callback;
+static semaphore_t *done;
+static const uint16_t test_handle = (0x1992 & 0xCFFF);
+static const uint16_t test_handle_continuation = (0x1992 & 0xCFFF) | 0x1000;
+static int packet_index;
+static unsigned int data_size_sum;
+static BT_HDR *data_to_receive;
+
+static void signal_work_item(UNUSED_ATTR void *context) {
+  semaphore_post(done);
+}
+
+static void flush_thread(thread_t *thread) {
+  // Double flush to ensure we get the next reactor cycle
+  thread_post(thread, signal_work_item, NULL);
+  semaphore_wait(done);
+  thread_post(thread, signal_work_item, NULL);
+  semaphore_wait(done);
+}
+
+// TODO move this to a common packet testing helper
+static BT_HDR *manufacture_packet(uint16_t event, const char *data) {
+  uint16_t data_length = strlen(data);
+  uint16_t size = data_length;
+  if (event == MSG_STACK_TO_HC_HCI_ACL) {
+    size += 4; // 2 for the handle, 2 for the length;
+  }
+
+  BT_HDR *packet = (BT_HDR *)osi_malloc(size + sizeof(BT_HDR));
+  packet->len = size;
+  packet->offset = 0;
+  packet->layer_specific = 0;
+
+  // The command transmit interface adds the event type automatically.
+  // Make sure it works but omitting it here.
+  if (event != MSG_STACK_TO_HC_HCI_CMD)
+    packet->event = event;
+
+  uint8_t *packet_data = packet->data;
+
+  if (event == MSG_STACK_TO_HC_HCI_ACL) {
+    UINT16_TO_STREAM(packet_data, test_handle);
+    UINT16_TO_STREAM(packet_data, data_length);
+  }
+
+  for (int i = 0; i < data_length; i++) {
+    packet_data[i] = data[i];
+  }
+
+  if (event == MSG_STACK_TO_HC_HCI_CMD) {
+    STREAM_SKIP_UINT16(packet_data);
+    UINT8_TO_STREAM(packet_data, data_length - 3);
+  } else if (event == MSG_HC_TO_STACK_HCI_EVT) {
+    STREAM_SKIP_UINT8(packet_data);
+    UINT8_TO_STREAM(packet_data, data_length - 2);
+  }
+
+  return packet;
+}
+
+static void expect_packet(uint16_t event, int max_acl_data_size, const uint8_t *data, uint16_t data_length, const char *expected_data) {
+  int expected_data_offset;
+  int length_to_check;
+
+  if (event == MSG_STACK_TO_HC_HCI_ACL) {
+    uint16_t handle;
+    uint16_t length;
+    STREAM_TO_UINT16(handle, data);
+    STREAM_TO_UINT16(length, data);
+
+    if (packet_index == 0)
+      EXPECT_EQ(test_handle, handle);
+    else
+      EXPECT_EQ(test_handle_continuation, handle);
+
+    int length_remaining = strlen(expected_data) - data_size_sum;
+    int packet_data_length = data_length - HCI_ACL_PREAMBLE_SIZE;
+    EXPECT_EQ(length_remaining, length);
+
+    if (length_remaining < max_acl_data_size)
+      EXPECT_EQ(length, packet_data_length);
+    else
+      EXPECT_EQ(max_acl_data_size, packet_data_length);
+
+    length_to_check = packet_data_length;
+    expected_data_offset = packet_index * max_acl_data_size;
+    packet_index++;
+  } else {
+    length_to_check = strlen(expected_data);
+    expected_data_offset = 0;
+  }
+
+  for (int i = 0; i < length_to_check; i++) {
+    if (event == MSG_STACK_TO_HC_HCI_CMD && (i == 2))
+      EXPECT_EQ(data_length - 3, data[i]);
+    else
+      EXPECT_EQ(expected_data[expected_data_offset + i], data[i]);
+
+    data_size_sum++;
+  }
+}
+
+STUB_FUNCTION(bool, hal_init, (const hci_hal_callbacks_t *callbacks, thread_t *working_thread))
+  DURING(start_up_async) AT_CALL(0) {
+    hal_callbacks = callbacks;
+    internal_thread = working_thread;
+    return true;
+  }
+
+  UNEXPECTED_CALL;
+  return false;
+}
+
+STUB_FUNCTION(bool, hal_open, ())
+  DURING(start_up_async) AT_CALL(0) return true;
+  UNEXPECTED_CALL;
+  return false;
+}
+
+STUB_FUNCTION(void, hal_close, ())
+  DURING(shut_down) AT_CALL(0) return;
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(uint16_t, hal_transmit_data, (serial_data_type_t type, uint8_t *data, uint16_t length))
+  DURING(transmit_simple) AT_CALL(0) {
+    EXPECT_EQ(DATA_TYPE_ACL, type);
+    expect_packet(MSG_STACK_TO_HC_HCI_ACL, 1021, data, length, small_sample_data);
+    return length;
+  }
+
+  DURING(
+      transmit_command_no_callbacks,
+      transmit_command_command_status,
+      transmit_command_command_complete
+    ) AT_CALL(0) {
+    EXPECT_EQ(DATA_TYPE_COMMAND, type);
+    expect_packet(MSG_STACK_TO_HC_HCI_CMD, 1021, data, length, command_sample_data);
+    return length;
+  }
+
+  UNEXPECTED_CALL;
+  return 0;
+}
+
+static size_t replay_data_to_receive(size_t max_size, uint8_t *buffer) {
+  for (size_t i = 0; i < max_size; i++) {
+    if (data_to_receive->offset >= data_to_receive->len)
+      break;
+
+    buffer[i] = data_to_receive->data[data_to_receive->offset++];
+
+    if (i == (max_size - 1))
+      return i + 1; // We return the length, not the index;
+  }
+
+  return 0;
+}
+
+STUB_FUNCTION(size_t, hal_read_data, (serial_data_type_t type, uint8_t *buffer, size_t max_size, UNUSED_ATTR bool block))
+  DURING(receive_simple, ignoring_packets_following_packet) {
+    EXPECT_EQ(DATA_TYPE_ACL, type);
+    return replay_data_to_receive(max_size, buffer);
+  }
+
+  DURING(ignoring_packets_ignored_packet) {
+    EXPECT_EQ(DATA_TYPE_EVENT, type);
+    return replay_data_to_receive(max_size, buffer);
+  }
+
+  DURING(
+      transmit_command_no_callbacks,
+      transmit_command_command_status,
+      transmit_command_command_complete) {
+    EXPECT_EQ(DATA_TYPE_EVENT, type);
+    return replay_data_to_receive(max_size, buffer);
+  }
+
+  UNEXPECTED_CALL;
+  return 0;
+}
+
+STUB_FUNCTION(void, hal_packet_finished, (serial_data_type_t type))
+  DURING(receive_simple, ignoring_packets_following_packet) AT_CALL(0) {
+    EXPECT_EQ(DATA_TYPE_ACL, type);
+    return;
+  }
+
+  DURING(ignoring_packets_ignored_packet) AT_CALL(0) {
+    EXPECT_EQ(DATA_TYPE_EVENT, type);
+    return;
+  }
+
+  DURING(
+      transmit_command_no_callbacks,
+      transmit_command_command_status,
+      transmit_command_command_complete
+    ) AT_CALL(0) {
+    EXPECT_EQ(DATA_TYPE_EVENT, type);
+    return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(bool, hci_inject_open, (
+    UNUSED_ATTR const hci_t *hci_interface))
+  DURING(start_up_async) AT_CALL(0) return true;
+  UNEXPECTED_CALL;
+  return false;
+}
+
+STUB_FUNCTION(void, hci_inject_close, ())
+  DURING(shut_down) AT_CALL(0) return;
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(void, btsnoop_capture, (const BT_HDR *buffer, bool is_received))
+  DURING(transmit_simple) AT_CALL(0) {
+    EXPECT_FALSE(is_received);
+    expect_packet(MSG_STACK_TO_HC_HCI_ACL, 1021, buffer->data + buffer->offset, buffer->len, small_sample_data);
+    packet_index = 0;
+    data_size_sum = 0;
+    return;
+  }
+
+
+  DURING(
+      transmit_command_no_callbacks,
+      transmit_command_command_status,
+      transmit_command_command_complete) {
+    AT_CALL(0) {
+      EXPECT_FALSE(is_received);
+      expect_packet(MSG_STACK_TO_HC_HCI_CMD, 1021, buffer->data + buffer->offset, buffer->len, command_sample_data);
+      packet_index = 0;
+      data_size_sum = 0;
+      return;
+    }
+    AT_CALL(1) {
+      EXPECT_TRUE(is_received);
+      // not super important to verify the contents right now
+      return;
+    }
+  }
+
+  DURING(
+      receive_simple,
+      ignoring_packets_following_packet
+    ) AT_CALL(0) {
+    EXPECT_TRUE(is_received);
+    EXPECT_TRUE(buffer->len == data_to_receive->len);
+    const uint8_t *buffer_base = buffer->data + buffer->offset;
+    const uint8_t *expected_base = data_to_receive->data;
+    for (int i = 0; i < buffer->len; i++) {
+      EXPECT_EQ(expected_base[i], buffer_base[i]);
+    }
+
+    return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(void, low_power_init, (UNUSED_ATTR thread_t *thread))
+  DURING(start_up_async) AT_CALL(0) return;
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(void, low_power_cleanup, ())
+  DURING(shut_down) AT_CALL(0) return;
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(void, low_power_wake_assert, ())
+  DURING(
+      transmit_simple,
+      transmit_command_no_callbacks,
+      transmit_command_command_status,
+      transmit_command_command_complete) {
+    AT_CALL(0) return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(void, low_power_transmit_done, ())
+  DURING(
+      transmit_simple,
+      transmit_command_no_callbacks,
+      transmit_command_command_status,
+      transmit_command_command_complete) {
+    AT_CALL(0) return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(bool, vendor_open, (UNUSED_ATTR const uint8_t *addr, const hci_t *hci_interface))
+  DURING(start_up_async) AT_CALL(0) {
+    //EXPECT_EQ(test_addr, addr); // TODO(zachoverflow): reinstate when address put into module
+    EXPECT_EQ(hci, hci_interface);
+    return true;
+  }
+
+  UNEXPECTED_CALL;
+  return true;
+}
+
+STUB_FUNCTION(void, vendor_close, ())
+  DURING(shut_down) AT_CALL(0) return;
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(void, vendor_set_callback, (vendor_async_opcode_t opcode, UNUSED_ATTR vendor_cb callback))
+  DURING(start_up_async) {
+    AT_CALL(0) {
+      EXPECT_EQ(VENDOR_CONFIGURE_FIRMWARE, opcode);
+      firmware_config_callback = callback;
+      return;
+    }
+    AT_CALL(1) {
+      EXPECT_EQ(VENDOR_CONFIGURE_SCO, opcode);
+      sco_config_callback = callback;
+      return;
+    }
+    AT_CALL(2) {
+      EXPECT_EQ(VENDOR_DO_EPILOG, opcode);
+      epilog_callback = callback;
+      return;
+    }
+  }
+
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(int, vendor_send_command, (vendor_opcode_t opcode, void *param))
+  DURING(start_up_async) {
+    AT_CALL(0) {
+      EXPECT_EQ(VENDOR_CHIP_POWER_CONTROL, opcode);
+      EXPECT_EQ(BT_VND_PWR_OFF, *(int *)param);
+      return 0;
+    }
+    AT_CALL(1) {
+      EXPECT_EQ(VENDOR_CHIP_POWER_CONTROL, opcode);
+      EXPECT_EQ(BT_VND_PWR_ON, *(int *)param);
+      return 0;
+    }
+  }
+
+  DURING(shut_down) AT_CALL(0) {
+    EXPECT_EQ(VENDOR_CHIP_POWER_CONTROL, opcode);
+    EXPECT_EQ(BT_VND_PWR_OFF, *(int *)param);
+    return 0;
+  }
+
+  UNEXPECTED_CALL;
+  return 0;
+}
+
+STUB_FUNCTION(int, vendor_send_async_command, (UNUSED_ATTR vendor_async_opcode_t opcode, UNUSED_ATTR void *param))
+  DURING(start_up_async) AT_CALL(0) {
+    EXPECT_EQ(VENDOR_CONFIGURE_FIRMWARE, opcode);
+    firmware_config_callback(true);
+    return 0;
+  }
+
+  DURING(postload) AT_CALL(0) {
+    EXPECT_EQ(VENDOR_CONFIGURE_SCO, opcode);
+    sco_config_callback(true);
+    return 0;
+  }
+
+  DURING(shut_down) AT_CALL(0) {
+    EXPECT_EQ(VENDOR_DO_EPILOG, opcode);
+    epilog_callback(true);
+    return 0;
+  }
+
+  UNEXPECTED_CALL;
+  return 0;
+}
+
+STUB_FUNCTION(void, command_complete_callback, (BT_HDR *response, UNUSED_ATTR void *context))
+  DURING(transmit_command_command_complete) AT_CALL(0) {
+    osi_free(response);
+    return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(void, command_status_callback, (UNUSED_ATTR uint8_t status, BT_HDR *command, UNUSED_ATTR void *context))
+  DURING(transmit_command_command_status) AT_CALL(0) {
+    osi_free(command);
+    return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(uint16_t, controller_get_acl_data_size_classic, (void))
+  return 2048;
+}
+
+STUB_FUNCTION(uint16_t, controller_get_acl_data_size_ble, (void))
+  return 2048;
+}
+
+STUB_FUNCTION(void *, buffer_allocator_alloc, (size_t size))
+  DURING(ignoring_packets_ignored_packet) {
+    AT_CALL(0)
+      return NULL;
+
+    UNEXPECTED_CALL;
+  }
+
+  return allocator_malloc.alloc(size);
+}
+
+STUB_FUNCTION(void, buffer_allocator_free, (void *ptr))
+  allocator_malloc.free(ptr);
+}
+
+static void reset_for(TEST_MODES_T next) {
+  RESET_CALL_COUNT(vendor_open);
+  RESET_CALL_COUNT(vendor_close);
+  RESET_CALL_COUNT(vendor_set_callback);
+  RESET_CALL_COUNT(vendor_send_command);
+  RESET_CALL_COUNT(vendor_send_async_command);
+  RESET_CALL_COUNT(hal_init);
+  RESET_CALL_COUNT(hal_open);
+  RESET_CALL_COUNT(hal_close);
+  RESET_CALL_COUNT(hal_read_data);
+  RESET_CALL_COUNT(hal_packet_finished);
+  RESET_CALL_COUNT(hal_transmit_data);
+  RESET_CALL_COUNT(btsnoop_capture);
+  RESET_CALL_COUNT(hci_inject_open);
+  RESET_CALL_COUNT(hci_inject_close);
+  RESET_CALL_COUNT(low_power_init);
+  RESET_CALL_COUNT(low_power_cleanup);
+  RESET_CALL_COUNT(low_power_wake_assert);
+  RESET_CALL_COUNT(low_power_transmit_done);
+  RESET_CALL_COUNT(command_complete_callback);
+  RESET_CALL_COUNT(command_status_callback);
+  RESET_CALL_COUNT(controller_get_acl_data_size_classic);
+  RESET_CALL_COUNT(controller_get_acl_data_size_ble);
+  RESET_CALL_COUNT(buffer_allocator_alloc);
+  RESET_CALL_COUNT(buffer_allocator_free);
+  CURRENT_TEST_MODE = next;
+}
+
+class HciLayerTest : public AlarmTestHarness {
+  protected:
+    virtual void SetUp() {
+      AlarmTestHarness::SetUp();
+
+      hci = hci_layer_get_test_interface(
+        &buffer_allocator,
+        &hal,
+        &btsnoop,
+        &hci_inject,
+        packet_fragmenter_get_test_interface(&controller, &allocator_malloc),
+        &vendor,
+        &low_power_manager
+      );
+
+      // Make sure the data dispatcher allocation isn't tracked
+      allocation_tracker_reset();
+      module_management_start();
+
+      packet_index = 0;
+      data_size_sum = 0;
+
+      vendor.open = vendor_open;
+      vendor.close = vendor_close;
+      vendor.set_callback = vendor_set_callback;
+      vendor.send_command = vendor_send_command;
+      vendor.send_async_command = vendor_send_async_command;
+      hal.init = hal_init;
+      hal.open = hal_open;
+      hal.close = hal_close;
+      hal.read_data = hal_read_data;
+      hal.packet_finished = hal_packet_finished;
+      hal.transmit_data = hal_transmit_data;
+      btsnoop.capture = btsnoop_capture;
+      hci_inject.open = hci_inject_open;
+      hci_inject.close = hci_inject_close;
+      low_power_manager.init = low_power_init;
+      low_power_manager.cleanup = low_power_cleanup;
+      low_power_manager.wake_assert = low_power_wake_assert;
+      low_power_manager.transmit_done = low_power_transmit_done;
+      controller.get_acl_data_size_classic = controller_get_acl_data_size_classic;
+      controller.get_acl_data_size_ble = controller_get_acl_data_size_ble;
+      buffer_allocator.alloc = buffer_allocator_alloc;
+      buffer_allocator.free = buffer_allocator_free;
+
+      done = semaphore_new(0);
+
+      reset_for(start_up_async);
+      EXPECT_TRUE(module_start_up(&hci_module));
+
+      EXPECT_CALL_COUNT(vendor_open, 1);
+      EXPECT_CALL_COUNT(hal_init, 1);
+      EXPECT_CALL_COUNT(low_power_init, 1);
+      EXPECT_CALL_COUNT(vendor_set_callback, 3);
+      EXPECT_CALL_COUNT(hal_open, 1);
+      EXPECT_CALL_COUNT(vendor_send_async_command, 1);
+    }
+
+    virtual void TearDown() {
+      reset_for(shut_down);
+      module_shut_down(&hci_module);
+
+      EXPECT_CALL_COUNT(low_power_cleanup, 1);
+      EXPECT_CALL_COUNT(hal_close, 1);
+      EXPECT_CALL_COUNT(vendor_send_command, 1);
+      EXPECT_CALL_COUNT(vendor_close, 1);
+
+      semaphore_free(done);
+      module_management_stop();
+      AlarmTestHarness::TearDown();
+    }
+
+    hci_hal_t hal;
+    btsnoop_t btsnoop;
+    controller_t controller;
+    hci_inject_t hci_inject;
+    vendor_t vendor;
+    low_power_manager_t low_power_manager;
+    allocator_t buffer_allocator;
+};
+
+TEST_F(HciLayerTest, test_postload) {
+  reset_for(postload);
+  hci->do_postload();
+
+  flush_thread(internal_thread);
+  EXPECT_CALL_COUNT(vendor_send_async_command, 1);
+}
+
+TEST_F(HciLayerTest, test_transmit_simple) {
+  reset_for(transmit_simple);
+  BT_HDR *packet = manufacture_packet(MSG_STACK_TO_HC_HCI_ACL, small_sample_data);
+  hci->transmit_downward(MSG_STACK_TO_HC_HCI_ACL, packet);
+
+  flush_thread(internal_thread);
+  EXPECT_CALL_COUNT(hal_transmit_data, 1);
+  EXPECT_CALL_COUNT(btsnoop_capture, 1);
+  EXPECT_CALL_COUNT(low_power_transmit_done, 1);
+  EXPECT_CALL_COUNT(low_power_wake_assert, 1);
+}
+
+TEST_F(HciLayerTest, test_receive_simple) {
+  reset_for(receive_simple);
+  data_to_receive = manufacture_packet(MSG_STACK_TO_HC_HCI_ACL, small_sample_data);
+
+  // Not running on the internal thread, unlike the real hal
+  hal_callbacks->data_ready(DATA_TYPE_ACL);
+  EXPECT_CALL_COUNT(hal_packet_finished, 1);
+  EXPECT_CALL_COUNT(btsnoop_capture, 1);
+
+  osi_free(data_to_receive);
+}
+
+static BT_HDR *manufacture_command_complete(command_opcode_t opcode) {
+  BT_HDR *ret = (BT_HDR *)osi_calloc(sizeof(BT_HDR) + 5);
+  uint8_t *stream = ret->data;
+  UINT8_TO_STREAM(stream, HCI_COMMAND_COMPLETE_EVT);
+  UINT8_TO_STREAM(stream, 3); // length of the event parameters
+  UINT8_TO_STREAM(stream, 1); // the number of commands that can be sent
+  UINT16_TO_STREAM(stream, opcode);
+  ret->len = 5;
+
+  return ret;
+}
+
+static BT_HDR *manufacture_command_status(command_opcode_t opcode) {
+  BT_HDR *ret = (BT_HDR *)osi_calloc(sizeof(BT_HDR) + 6);
+  uint8_t *stream = ret->data;
+  UINT8_TO_STREAM(stream, HCI_COMMAND_STATUS_EVT);
+  UINT8_TO_STREAM(stream, 4); // length of the event parameters
+  UINT8_TO_STREAM(stream, HCI_PENDING); // status
+  UINT8_TO_STREAM(stream, 1); // the number of commands that can be sent
+  UINT16_TO_STREAM(stream, opcode);
+  ret->len = 6;
+
+  return ret;
+}
+
+TEST_F(HciLayerTest, test_transmit_command_no_callbacks) {
+  // Send a test command
+  reset_for(transmit_command_no_callbacks);
+  data_to_receive = manufacture_packet(MSG_STACK_TO_HC_HCI_CMD, command_sample_data);
+  hci->transmit_command(data_to_receive, NULL, NULL, NULL);
+
+  flush_thread(internal_thread);
+  EXPECT_CALL_COUNT(hal_transmit_data, 1);
+  EXPECT_CALL_COUNT(btsnoop_capture, 1);
+  EXPECT_CALL_COUNT(low_power_transmit_done, 1);
+  EXPECT_CALL_COUNT(low_power_wake_assert, 1);
+
+  // Send a response
+  command_opcode_t opcode = *((uint16_t *)command_sample_data);
+  data_to_receive = manufacture_command_complete(opcode);
+
+  hal_callbacks->data_ready(DATA_TYPE_EVENT);
+  EXPECT_CALL_COUNT(hal_packet_finished, 1);
+  EXPECT_CALL_COUNT(btsnoop_capture, 2);
+
+  osi_free(data_to_receive);
+}
+
+TEST_F(HciLayerTest, test_transmit_command_command_status) {
+  // Send a test command
+  reset_for(transmit_command_command_status);
+  data_to_receive = manufacture_packet(MSG_STACK_TO_HC_HCI_CMD, command_sample_data);
+  hci->transmit_command(data_to_receive, command_complete_callback, command_status_callback, NULL);
+
+  flush_thread(internal_thread);
+  EXPECT_CALL_COUNT(hal_transmit_data, 1);
+  EXPECT_CALL_COUNT(btsnoop_capture, 1);
+  EXPECT_CALL_COUNT(low_power_transmit_done, 1);
+  EXPECT_CALL_COUNT(low_power_wake_assert, 1);
+
+  command_opcode_t opcode = *((uint16_t *)command_sample_data);
+
+  // Send status event response
+  data_to_receive = manufacture_command_status(opcode);
+
+  hal_callbacks->data_ready(DATA_TYPE_EVENT);
+  EXPECT_CALL_COUNT(hal_packet_finished, 1);
+  EXPECT_CALL_COUNT(btsnoop_capture, 2);
+  EXPECT_CALL_COUNT(command_status_callback, 1);
+
+  osi_free(data_to_receive);
+}
+
+TEST_F(HciLayerTest, test_transmit_command_command_complete) {
+  // Send a test command
+  reset_for(transmit_command_command_complete);
+  data_to_receive = manufacture_packet(MSG_STACK_TO_HC_HCI_CMD, command_sample_data);
+  hci->transmit_command(data_to_receive, command_complete_callback, command_status_callback, NULL);
+
+  flush_thread(internal_thread);
+  EXPECT_CALL_COUNT(hal_transmit_data, 1);
+  EXPECT_CALL_COUNT(btsnoop_capture, 1);
+  EXPECT_CALL_COUNT(low_power_transmit_done, 1);
+  EXPECT_CALL_COUNT(low_power_wake_assert, 1);
+
+  command_opcode_t opcode = *((uint16_t *)command_sample_data);
+
+  // Send complete event response
+  data_to_receive = manufacture_command_complete(opcode);
+
+  hal_callbacks->data_ready(DATA_TYPE_EVENT);
+  EXPECT_CALL_COUNT(hal_packet_finished, 1);
+  EXPECT_CALL_COUNT(btsnoop_capture, 2);
+  EXPECT_CALL_COUNT(command_complete_callback, 1);
+
+  osi_free(data_to_receive);
+}
+
+TEST_F(HciLayerTest, test_ignoring_packets) {
+  reset_for(ignoring_packets_ignored_packet);
+  data_to_receive = manufacture_packet(MSG_HC_TO_STACK_HCI_EVT, unignored_data);
+
+  hal_callbacks->data_ready(DATA_TYPE_EVENT);
+  EXPECT_CALL_COUNT(buffer_allocator_alloc, 1);
+  EXPECT_CALL_COUNT(hal_packet_finished, 1);
+  EXPECT_CALL_COUNT(btsnoop_capture, 0);
+  osi_free(data_to_receive);
+
+  reset_for(ignoring_packets_following_packet);
+  data_to_receive = manufacture_packet(MSG_STACK_TO_HC_HCI_ACL, ignored_data);
+
+  hal_callbacks->data_ready(DATA_TYPE_ACL);
+  EXPECT_CALL_COUNT(buffer_allocator_alloc, 1);
+  EXPECT_CALL_COUNT(hal_packet_finished, 1);
+  EXPECT_CALL_COUNT(btsnoop_capture, 1);
+  osi_free(data_to_receive);
+}
+
+// TODO(zachoverflow): test post-reassembly better, stub out fragmenter instead of using it
diff --git a/hci/test/low_power_manager_test.cpp b/hci/test/low_power_manager_test.cpp
new file mode 100644
index 0000000..bb18bff
--- /dev/null
+++ b/hci/test/low_power_manager_test.cpp
@@ -0,0 +1,140 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+#include "AlarmTestHarness.h"
+
+extern "C" {
+#include <stdint.h>
+
+#include "low_power_manager.h"
+#include "osi.h"
+#include "semaphore.h"
+#include "test_stubs.h"
+#include "thread.h"
+#include "vendor.h"
+}
+
+DECLARE_TEST_MODES(
+  init,
+  cleanup,
+  enable_disable
+);
+
+static const low_power_manager_t *manager;
+static thread_t *thread;
+static semaphore_t *done;
+
+static vendor_cb low_power_state_callback;
+
+static void flush_work_queue_item(UNUSED_ATTR void *context) {
+  semaphore_post(done);
+}
+
+STUB_FUNCTION(int, vendor_send_command, (vendor_opcode_t opcode, void *param))
+  DURING(init) AT_CALL(0) {
+    EXPECT_EQ(VENDOR_GET_LPM_IDLE_TIMEOUT, opcode);
+    *((uint32_t *)param) = 100;
+    return 0;
+  }
+
+  UNEXPECTED_CALL;
+  return 0;
+}
+
+STUB_FUNCTION(int, vendor_send_async_command, (vendor_async_opcode_t opcode, void *param))
+  DURING(enable_disable) {
+    AT_CALL(0) {
+      EXPECT_EQ(VENDOR_SET_LPM_MODE, opcode);
+      EXPECT_EQ(BT_VND_LPM_ENABLE, *(uint8_t *)param);
+      low_power_state_callback(true);
+      thread_post(thread, flush_work_queue_item, NULL);
+      return 0;
+    }
+    AT_CALL(1) {
+      EXPECT_EQ(VENDOR_SET_LPM_MODE, opcode);
+      EXPECT_EQ(BT_VND_LPM_DISABLE, *(uint8_t *)param);
+      low_power_state_callback(true);
+      thread_post(thread, flush_work_queue_item, NULL);
+      return 0;
+    }
+  }
+
+  UNEXPECTED_CALL;
+  return 0;
+}
+
+STUB_FUNCTION(void, vendor_set_callback, (vendor_async_opcode_t opcode, vendor_cb callback))
+  DURING(init) AT_CALL(0) {
+    EXPECT_EQ(VENDOR_SET_LPM_MODE, opcode);
+    low_power_state_callback = callback;
+    return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+static void reset_for(TEST_MODES_T next) {
+  RESET_CALL_COUNT(vendor_send_command);
+  RESET_CALL_COUNT(vendor_send_async_command);
+  RESET_CALL_COUNT(vendor_set_callback);
+  CURRENT_TEST_MODE = next;
+}
+
+class LowPowerManagerTest : public AlarmTestHarness {
+  protected:
+    virtual void SetUp() {
+      AlarmTestHarness::SetUp();
+      low_power_state_callback = NULL;
+      vendor.send_command = vendor_send_command;
+      vendor.send_async_command = vendor_send_async_command;
+      vendor.set_callback = vendor_set_callback;
+      manager = low_power_manager_get_test_interface(&vendor);
+      thread = thread_new("test_thread");
+      done = semaphore_new(0);
+
+      reset_for(init);
+      manager->init(thread);
+
+      EXPECT_CALL_COUNT(vendor_send_command, 1);
+      EXPECT_CALL_COUNT(vendor_set_callback, 1);
+    }
+
+    virtual void TearDown() {
+      reset_for(cleanup);
+      manager->cleanup();
+
+      semaphore_free(done);
+      thread_free(thread);
+      AlarmTestHarness::TearDown();
+    }
+
+    vendor_t vendor;
+};
+
+TEST_F(LowPowerManagerTest, test_enable_disable) {
+  reset_for(enable_disable);
+  manager->post_command(LPM_ENABLE);
+  semaphore_wait(done);
+
+  manager->post_command(LPM_DISABLE);
+  semaphore_wait(done);
+
+  EXPECT_CALL_COUNT(vendor_send_async_command, 2);
+}
diff --git a/hci/test/packet_fragmenter_test.cpp b/hci/test/packet_fragmenter_test.cpp
new file mode 100644
index 0000000..765b91e
--- /dev/null
+++ b/hci/test/packet_fragmenter_test.cpp
@@ -0,0 +1,378 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+#include "AllocationTestHarness.h"
+
+extern "C" {
+#include <stdint.h>
+
+#include "allocator.h"
+#include "device/include/controller.h"
+#include "hci_internals.h"
+#include "packet_fragmenter.h"
+#include "osi.h"
+#include "test_stubs.h"
+}
+
+DECLARE_TEST_MODES(
+  init,
+  set_data_sizes,
+  no_fragmentation,
+  fragmentation,
+  ble_no_fragmentation,
+  ble_fragmentation,
+  non_acl_passthrough_fragmentation,
+  no_reassembly,
+  reassembly,
+  non_acl_passthrough_reassembly
+);
+
+#define LOCAL_BLE_CONTROLLER_ID 1
+
+static const char *sample_data =
+  "At this point they came in sight of thirty forty windmills that there are on plain, and "
+  "as soon as Don Quixote saw them he said to his squire, \"Fortune is arranging matters "
+  "for us better than we could have shaped our desires ourselves, for look there, friend "
+  "Sancho Panza, where thirty or more monstrous giants present themselves, all of whom I "
+  "mean to engage in battle and slay, and with whose spoils we shall begin to make our "
+  "fortunes; for this is righteous warfare, and it is God's good service to sweep so evil "
+  "a breed from off the face of the earth.\"";
+
+static const char *small_sample_data = "\"What giants?\" said Sancho Panza.";
+static const uint16_t test_handle_start = (0x1992 & 0xCFFF) | 0x2000;
+static const uint16_t test_handle_continuation = (0x1992 & 0xCFFF) | 0x1000;
+static int packet_index;
+static unsigned int data_size_sum;
+
+static const packet_fragmenter_t *fragmenter;
+
+static BT_HDR *manufacture_packet_for_fragmentation(uint16_t event, const char *data) {
+  uint16_t data_length = strlen(data);
+  uint16_t size = data_length;
+  if (event == MSG_STACK_TO_HC_HCI_ACL) {
+    size += 4; // 2 for the handle, 2 for the length;
+  }
+
+  BT_HDR *packet = (BT_HDR *)osi_malloc(size + sizeof(BT_HDR));
+  packet->len = size;
+  packet->offset = 0;
+  packet->event = event;
+  packet->layer_specific = 0;
+  uint8_t *packet_data = packet->data;
+
+  if (event == MSG_STACK_TO_HC_HCI_ACL) {
+    UINT16_TO_STREAM(packet_data, test_handle_start);
+    UINT16_TO_STREAM(packet_data, data_length);
+  }
+
+  memcpy(packet_data, data, data_length);
+  return packet;
+}
+
+static void expect_packet_fragmented(uint16_t event, int max_acl_data_size, BT_HDR *packet, const char *expected_data, bool send_complete) {
+  uint8_t *data = packet->data + packet->offset;
+  int expected_data_offset;
+  int length_to_check;
+
+  if (event == MSG_STACK_TO_HC_HCI_ACL) {
+    uint16_t handle;
+    uint16_t length;
+    STREAM_TO_UINT16(handle, data);
+    STREAM_TO_UINT16(length, data);
+
+    if (packet_index == 0)
+      EXPECT_EQ(test_handle_start, handle);
+    else
+      EXPECT_EQ(test_handle_continuation, handle);
+
+    int length_remaining = strlen(expected_data) - data_size_sum;
+    int packet_data_length = packet->len - HCI_ACL_PREAMBLE_SIZE;
+    EXPECT_EQ(packet_data_length, length);
+
+    if (length_remaining > max_acl_data_size)
+      EXPECT_EQ(max_acl_data_size, packet_data_length);
+
+    length_to_check = packet_data_length;
+    expected_data_offset = packet_index * max_acl_data_size;
+    packet_index++;
+  } else {
+    length_to_check = strlen(expected_data);
+    expected_data_offset = 0;
+  }
+
+  for (int i = 0; i < length_to_check; i++) {
+    EXPECT_EQ(expected_data[expected_data_offset + i], data[i]);
+    data_size_sum++;
+  }
+
+  if (event == MSG_STACK_TO_HC_HCI_ACL)
+    EXPECT_TRUE(send_complete == (data_size_sum == strlen(expected_data)));
+
+  if (send_complete)
+    osi_free(packet);
+}
+
+static void manufacture_packet_and_then_reassemble(uint16_t event, uint16_t acl_size, const char *data) {
+  uint16_t data_length = strlen(data);
+
+  if (event == MSG_HC_TO_STACK_HCI_ACL) {
+    uint16_t total_length = data_length + 2; // 2 for l2cap length;
+    uint16_t length_sent = 0;
+    uint16_t l2cap_length = data_length - 2; // l2cap length field, 2 for the pretend channel id borrowed from the data
+
+    do {
+      int length_to_send = (length_sent + (acl_size - 4) < total_length) ? (acl_size - 4) : (total_length - length_sent);
+      BT_HDR *packet = (BT_HDR *)osi_malloc(length_to_send + 4 + sizeof(BT_HDR));
+      packet->len = length_to_send + 4;
+      packet->offset = 0;
+      packet->event = event;
+      packet->layer_specific = 0;
+
+      uint8_t *packet_data = packet->data;
+      if (length_sent == 0) { // first packet
+        UINT16_TO_STREAM(packet_data, test_handle_start);
+        UINT16_TO_STREAM(packet_data, length_to_send);
+        UINT16_TO_STREAM(packet_data, l2cap_length);
+        memcpy(packet_data, data, length_to_send - 2);
+      } else {
+        UINT16_TO_STREAM(packet_data, test_handle_continuation);
+        UINT16_TO_STREAM(packet_data, length_to_send);
+        memcpy(packet_data, data + length_sent - 2, length_to_send);
+      }
+
+      length_sent += length_to_send;
+      fragmenter->reassemble_and_dispatch(packet);
+    } while (length_sent < total_length);
+  } else {
+    BT_HDR *packet = (BT_HDR *)osi_malloc(data_length + sizeof(BT_HDR));
+    packet->len = data_length;
+    packet->offset = 0;
+    packet->event = event;
+    packet->layer_specific = 0;
+    memcpy(packet->data, data, data_length);
+
+    fragmenter->reassemble_and_dispatch(packet);
+  }
+}
+
+static void expect_packet_reassembled(uint16_t event, BT_HDR *packet, const char *expected_data) {
+  uint16_t expected_data_length = strlen(expected_data);
+  uint8_t *data = packet->data + packet->offset;
+
+  if (event == MSG_HC_TO_STACK_HCI_ACL) {
+    uint16_t handle;
+    uint16_t length;
+    uint16_t l2cap_length;
+    STREAM_TO_UINT16(handle, data);
+    STREAM_TO_UINT16(length, data);
+    STREAM_TO_UINT16(l2cap_length, data);
+
+    EXPECT_EQ(test_handle_start, handle);
+    EXPECT_EQ(expected_data_length + 2, length);
+    EXPECT_EQ(expected_data_length - 2, l2cap_length); // -2 for the pretend channel id
+  }
+
+
+  for (int i = 0; i < expected_data_length; i++) {
+    EXPECT_EQ(expected_data[i], data[i]);
+    data_size_sum++;
+  }
+
+  osi_free(packet);
+}
+
+STUB_FUNCTION(void, fragmented_callback, (BT_HDR *packet, bool send_complete))
+  DURING(no_fragmentation) AT_CALL(0) {
+    expect_packet_fragmented(MSG_STACK_TO_HC_HCI_ACL, 42, packet, small_sample_data, send_complete);
+    return;
+  }
+
+  DURING(fragmentation) {
+    expect_packet_fragmented(MSG_STACK_TO_HC_HCI_ACL, 10, packet, sample_data, send_complete);
+    return;
+  }
+
+  DURING(ble_no_fragmentation) AT_CALL(0) {
+    expect_packet_fragmented(MSG_STACK_TO_HC_HCI_ACL, 42, packet, small_sample_data, send_complete);
+    return;
+  }
+
+  DURING(ble_fragmentation) {
+    expect_packet_fragmented(MSG_STACK_TO_HC_HCI_ACL, 10, packet, sample_data, send_complete);
+    return;
+  }
+
+  DURING(non_acl_passthrough_fragmentation) AT_CALL(0) {
+    expect_packet_fragmented(MSG_STACK_TO_HC_HCI_CMD, 10, packet, sample_data, send_complete);
+    return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(void, reassembled_callback, (BT_HDR *packet))
+  DURING(no_reassembly) AT_CALL(0) {
+    expect_packet_reassembled(MSG_HC_TO_STACK_HCI_ACL, packet, small_sample_data);
+    return;
+  }
+
+  DURING(reassembly) AT_CALL(0) {
+    expect_packet_reassembled(MSG_HC_TO_STACK_HCI_ACL, packet, sample_data);
+    return;
+  }
+
+  DURING(non_acl_passthrough_reassembly) AT_CALL(0) {
+    expect_packet_reassembled(MSG_HC_TO_STACK_HCI_EVT, packet, sample_data);
+    return;
+  }
+
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(void, transmit_finished_callback, (UNUSED_ATTR BT_HDR *packet, UNUSED_ATTR bool sent_all_fragments))
+  UNEXPECTED_CALL;
+}
+
+STUB_FUNCTION(uint16_t, get_acl_data_size_classic, (void))
+  DURING(no_fragmentation,
+         non_acl_passthrough_fragmentation,
+         no_reassembly) return 42;
+  DURING(fragmentation) return 10;
+  DURING(no_reassembly) return 1337;
+
+  UNEXPECTED_CALL;
+  return 0;
+}
+
+STUB_FUNCTION(uint16_t, get_acl_data_size_ble, (void))
+  DURING(ble_no_fragmentation) return 42;
+  DURING(ble_fragmentation) return 10;
+
+  UNEXPECTED_CALL;
+  return 0;
+}
+
+static void reset_for(TEST_MODES_T next) {
+  RESET_CALL_COUNT(fragmented_callback);
+  RESET_CALL_COUNT(reassembled_callback);
+  RESET_CALL_COUNT(transmit_finished_callback);
+  RESET_CALL_COUNT(get_acl_data_size_classic);
+  RESET_CALL_COUNT(get_acl_data_size_ble);
+  CURRENT_TEST_MODE = next;
+}
+
+class PacketFragmenterTest : public AllocationTestHarness {
+  protected:
+    virtual void SetUp() {
+      AllocationTestHarness::SetUp();
+      fragmenter = packet_fragmenter_get_test_interface(
+        &controller,
+        &allocator_malloc);
+
+      packet_index = 0;
+      data_size_sum = 0;
+
+      callbacks.fragmented = fragmented_callback;
+      callbacks.reassembled = reassembled_callback;
+      callbacks.transmit_finished = transmit_finished_callback;
+      controller.get_acl_data_size_classic = get_acl_data_size_classic;
+      controller.get_acl_data_size_ble = get_acl_data_size_ble;
+
+      reset_for(init);
+      fragmenter->init(&callbacks);
+    }
+
+    virtual void TearDown() {
+      fragmenter->cleanup();
+      AllocationTestHarness::TearDown();
+    }
+
+    controller_t controller;
+    packet_fragmenter_callbacks_t callbacks;
+};
+
+TEST_F(PacketFragmenterTest, test_no_fragment_necessary) {
+  reset_for(no_fragmentation);
+  BT_HDR *packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ACL, small_sample_data);
+  fragmenter->fragment_and_dispatch(packet);
+
+  EXPECT_EQ(strlen(small_sample_data), data_size_sum);
+  EXPECT_CALL_COUNT(fragmented_callback, 1);
+}
+
+TEST_F(PacketFragmenterTest, test_fragment_necessary) {
+  reset_for(fragmentation);
+  BT_HDR *packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ACL, sample_data);
+  fragmenter->fragment_and_dispatch(packet);
+
+  EXPECT_EQ(strlen(sample_data), data_size_sum);
+}
+
+TEST_F(PacketFragmenterTest, test_ble_no_fragment_necessary) {
+  reset_for(ble_no_fragmentation);
+  BT_HDR *packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ACL, small_sample_data);
+  packet->event |= LOCAL_BLE_CONTROLLER_ID;
+  fragmenter->fragment_and_dispatch(packet);
+
+  EXPECT_EQ(strlen(small_sample_data), data_size_sum);
+  EXPECT_CALL_COUNT(fragmented_callback, 1);
+}
+
+TEST_F(PacketFragmenterTest, test_ble_fragment_necessary) {
+  reset_for(ble_fragmentation);
+  BT_HDR *packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ACL, sample_data);
+  packet->event |= LOCAL_BLE_CONTROLLER_ID;
+  fragmenter->fragment_and_dispatch(packet);
+
+  EXPECT_EQ(strlen(sample_data), data_size_sum);
+}
+
+TEST_F(PacketFragmenterTest, test_non_acl_passthrough_fragmentation) {
+  reset_for(non_acl_passthrough_fragmentation);
+  BT_HDR *packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_CMD, sample_data);
+  fragmenter->fragment_and_dispatch(packet);
+
+  EXPECT_EQ(strlen(sample_data), data_size_sum);
+  EXPECT_CALL_COUNT(fragmented_callback, 1);
+}
+
+TEST_F(PacketFragmenterTest, test_no_reassembly_necessary) {
+  reset_for(no_reassembly);
+  manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_ACL, 1337, small_sample_data);
+
+  EXPECT_EQ(strlen(small_sample_data), data_size_sum);
+  EXPECT_CALL_COUNT(reassembled_callback, 1);
+}
+
+TEST_F(PacketFragmenterTest, test_reassembly_necessary) {
+  reset_for(reassembly);
+  manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_ACL, 42, sample_data);
+
+  EXPECT_EQ(strlen(sample_data), data_size_sum);
+  EXPECT_CALL_COUNT(reassembled_callback, 1);
+}
+
+TEST_F(PacketFragmenterTest, test_non_acl_passthrough_reasseembly) {
+  reset_for(non_acl_passthrough_reassembly);
+  manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_EVT, 42, sample_data);
+
+  EXPECT_EQ(strlen(sample_data), data_size_sum);
+  EXPECT_CALL_COUNT(reassembled_callback, 1);
+}
diff --git a/include/bt_target.h b/include/bt_target.h
index 66b5f98..f61d2f4 100644
--- a/include/bt_target.h
+++ b/include/bt_target.h
@@ -23,22 +23,6 @@
 #ifndef BUILDCFG
 #define BUILDCFG
 #endif
-#include "data_types.h"
-
-
-#ifndef BTIF_HSAG_SERVICE_NAME
-#define BTIF_HSAG_SERVICE_NAME  ("Headset Gateway")
-#endif
-
-#ifndef BTIF_HFAG_SERVICE_NAME
-#define BTIF_HFAG_SERVICE_NAME  ("Handsfree Gateway")
-#endif
-
-#ifndef BTIF_HF_CLIENT_SERVICE_NAME
-#define BTIF_HF_CLIENT_SERVICE_NAME  ("Handsfree")
-#endif
-
-#ifdef BUILDCFG
 
 #if !defined(HAS_BDROID_BUILDCFG) && !defined(HAS_NO_BDROID_BUILDCFG)
 #error "An Android.mk file did not include bdroid_CFLAGS and possibly not bdorid_C_INCLUDES"
@@ -48,28 +32,13 @@
 #include "bdroid_buildcfg.h"
 #endif
 
-#endif
+#include "bt_types.h"   /* This must be defined AFTER buildcfg.h */
 
 /* Include common GKI definitions used by this platform */
 #include "gki_target.h"
-
-#include "bt_types.h"   /* This must be defined AFTER buildcfg.h */
 #include "dyn_mem.h"    /* defines static and/or dynamic memory for components */
 
-
 //------------------Added from bdroid_buildcfg.h---------------------
-#ifndef UNV_INCLUDED
-#define UNV_INCLUDED FALSE
-#endif
-
-#ifndef GATT_PTS
-#define GATT_PTS FALSE
-#endif
-
-#ifndef L2CAP_INCLUDED
-#define L2CAP_INCLUDED TRUE
-#endif
-
 #ifndef L2CAP_EXTFEA_SUPPORTED_MASK
 #define L2CAP_EXTFEA_SUPPORTED_MASK (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_NO_CRC | L2CAP_EXTFEA_FIXED_CHNLS)
 #endif
@@ -82,30 +51,6 @@
 #define BTA_RFC_MTU_SIZE (L2CAP_MTU_SIZE-L2CAP_MIN_OFFSET-RFCOMM_DATA_OVERHEAD)
 #endif
 
-#ifndef BTA_DUN_MTU
-#define BTA_DUN_MTU BTA_RFC_MTU_SIZE
-#endif
-
-#ifndef BTA_SPP_MTU
-#define BTA_SPP_MTU BTA_RFC_MTU_SIZE
-#endif
-
-#ifndef BTA_FAX_MTU
-#define BTA_FAX_MTU BTA_RFC_MTU_SIZE
-#endif
-
-#ifndef SDP_RAW_PDU_INCLUDED
-#define SDP_RAW_PDU_INCLUDED  TRUE
-#endif
-
-#ifndef GATTS_APPU_USE_GATT_TRACE
-#define GATTS_APPU_USE_GATT_TRACE FALSE
-#endif
-
-#ifndef SMP_HOST_ENCRYPT_INCLUDED
-#define SMP_HOST_ENCRYPT_INCLUDED FALSE
-#endif
-
 #ifndef SBC_NO_PCM_CPY_OPTION
 #define SBC_NO_PCM_CPY_OPTION FALSE
 #endif
@@ -114,35 +59,10 @@
 #define BTA_INCLUDED TRUE
 #endif
 
-#ifndef BTA_AG_INCLUDED
-#define BTA_AG_INCLUDED  TRUE
-#endif
-
-#ifndef BTA_DM_INCLUDED
-#define BTA_DM_INCLUDED TRUE
-#endif
-
-
-#ifndef BTA_DI_INCLUDED
-#define BTA_DI_INCLUDED FALSE
-#endif
-
-#ifndef BTA_BI_INCLUDED
-#define BTA_BI_INCLUDED FALSE
-#endif
-
-#ifndef BTA_SC_INCLUDED
-#define BTA_SC_INCLUDED FALSE
-#endif
-
 #ifndef BTA_PAN_INCLUDED
 #define BTA_PAN_INCLUDED TRUE
 #endif
 
-#ifndef BTA_FS_INCLUDED
-#define BTA_FS_INCLUDED TRUE
-#endif
-
 #ifndef BTA_HH_INCLUDED
 #define BTA_HH_INCLUDED TRUE
 #endif
@@ -175,26 +95,11 @@
 #define BTA_DISABLE_DELAY 200 /* in milliseconds */
 #endif
 
-#ifndef RPC_TRACE_ONLY
-#define RPC_TRACE_ONLY  FALSE
-#endif
-
-#ifndef ANDROID_APP_INCLUDED
-#define ANDROID_APP_INCLUDED  TRUE
-#endif
-
-#ifndef ANDROID_USE_LOGCAT
-#define ANDROID_USE_LOGCAT  TRUE
-#endif
-
-#ifndef LINUX_GKI_INCLUDED
-#define LINUX_GKI_INCLUDED  TRUE
-#endif
-
 // If the next wakeup time is less than this threshold, we should acquire
 // a wakelock instead of setting a wake alarm so we're not bouncing in
 // and out of suspend frequently.
 // in millisecond
+// TODO(zachoverflow): reinstate in alarm code
 #ifndef GKI_TIMER_INTERVAL_FOR_WAKELOCK
 #define GKI_TIMER_INTERVAL_FOR_WAKELOCK 3000
 #endif
@@ -203,34 +108,10 @@
 #define BTA_SYS_TIMER_PERIOD  100
 #endif
 
-#ifndef GKI_SHUTDOWN_EVT
-#define GKI_SHUTDOWN_EVT  APPL_EVT_7
-#endif
-
-#ifndef GKI_PTHREAD_JOINABLE
-#define GKI_PTHREAD_JOINABLE  TRUE
-#endif
-
-#ifndef LINUX_DRV_INCLUDED
-#define LINUX_DRV_INCLUDED  TRUE
-#endif
-
-#ifndef LINUX_OS
-#define LINUX_OS  TRUE
-#endif
-
-#ifndef BTM_APP_DEV_INIT
-#define BTM_APP_DEV_INIT  bte_main_post_reset_init
-#endif
-
 #ifndef SBC_FOR_EMBEDDED_LINUX
 #define SBC_FOR_EMBEDDED_LINUX TRUE
 #endif
 
-#ifndef BTA_DM_REMOTE_DEVICE_NAME_LENGTH
-#define BTA_DM_REMOTE_DEVICE_NAME_LENGTH 248
-#endif
-
 #ifndef AVDT_VERSION
 #define AVDT_VERSION  0x0102
 #endif
@@ -259,19 +140,11 @@
 #define BTA_AV_CO_CP_SCMS_T  FALSE
 #endif
 
-#ifndef AVDT_CONNECT_CP_ONLY
-#define AVDT_CONNECT_CP_ONLY  FALSE
-#endif
-
 /* This feature is used to eanble interleaved scan*/
 #ifndef BTA_HOST_INTERLEAVE_SEARCH
 #define BTA_HOST_INTERLEAVE_SEARCH FALSE
 #endif
 
-#ifndef BT_TRACE_PROTOCOL
-#define BT_TRACE_PROTOCOL  TRUE
-#endif
-
 #ifndef BT_USE_TRACES
 #define BT_USE_TRACES  TRUE
 #endif
@@ -280,30 +153,10 @@
 #define BT_TRACE_BTIF  TRUE
 #endif
 
-#ifndef BTTRC_INCLUDED
-#define BTTRC_INCLUDED  FALSE
-#endif
-
 #ifndef BT_TRACE_VERBOSE
 #define BT_TRACE_VERBOSE  FALSE
 #endif
 
-#ifndef BTTRC_PARSER_INCLUDED
-#define BTTRC_PARSER_INCLUDED  FALSE
-#endif
-
-#ifndef MAX_TRACE_RAM_SIZE
-#define MAX_TRACE_RAM_SIZE  10000
-#endif
-
-#ifndef OBX_INITIAL_TRACE_LEVEL
-#define OBX_INITIAL_TRACE_LEVEL  BT_TRACE_LEVEL_ERROR
-#endif
-
-#ifndef PBAP_ZERO_VCARD_IN_DB
-#define PBAP_ZERO_VCARD_IN_DB  FALSE
-#endif
-
 #ifndef BTA_DM_SDP_DB_SIZE
 #define BTA_DM_SDP_DB_SIZE  8000
 #endif
@@ -329,64 +182,6 @@
 //------------------End added from bdroid_buildcfg.h---------------------
 
 
-
-/******************************************************************************
-**
-** Platform-Specific
-**
-******************************************************************************/
-
-/* API macros for simulator */
-
-#define BTAPI
-
-#ifndef BTE_BSE_WRAPPER
-#ifdef  BTE_SIM_APP
-#undef  BTAPI
-#define BTAPI         __declspec(dllexport)
-#endif
-#endif
-
-#define BT_API          BTAPI
-#define BTU_API         BTAPI
-#define A2D_API         BTAPI
-#define VDP_API         BTAPI
-#define AVDT_API        BTAPI
-#define AVCT_API        BTAPI
-#define AVRC_API        BTAPI
-#define BIP_API         BTAPI
-#define BNEP_API        BTAPI
-#define BPP_API         BTAPI
-#define BTM_API         BTAPI
-#define CTP_API         BTAPI
-#define DUN_API         BTAPI
-#define FTP_API         BTAPI
-#define GAP_API         BTAPI
-#define GOEP_API        BTAPI
-#define HCI_API         BTAPI
-#define HCRP_API        BTAPI
-#define HID_API         BTAPI
-#define HFP_API         BTAPI
-#define HSP2_API        BTAPI
-#define ICP_API         BTAPI
-#define L2C_API         BTAPI
-#define OBX_API         BTAPI
-#define OPP_API         BTAPI
-#define PAN_API         BTAPI
-#define RFC_API         BTAPI
-#define RPC_API         BTAPI
-#define SDP_API         BTAPI
-#define SPP_API         BTAPI
-#define TCS_API         BTAPI
-#define XML_API         BTAPI
-#define BTA_API         BTAPI
-#define SBC_API         BTAPI
-#define MCE_API         BTAPI
-#define MCA_API         BTAPI
-#define GATT_API        BTAPI
-#define SMP_API         BTAPI
-
-
 /******************************************************************************
 **
 ** GKI Buffer Pools
@@ -407,10 +202,6 @@
 #define HCI_ACL_POOL_ID             GKI_POOL_ID_3
 #endif
 
-#ifndef HCI_ACL_POOL_BUF_SIZE
-#define HCI_ACL_POOL_BUF_SIZE       GKI_BUF3_SIZE
-#endif
-
 /* Maximum number of buffers available for ACL receive data. */
 #ifndef HCI_ACL_BUF_MAX
 #define HCI_ACL_BUF_MAX             GKI_BUF3_MAX
@@ -421,11 +212,6 @@
 #define HCI_SCO_POOL_ID             GKI_POOL_ID_6
 #endif
 
-/* Not used. */
-#ifndef HCI_DATA_DESCR_POOL_ID
-#define HCI_DATA_DESCR_POOL_ID      GKI_POOL_ID_0
-#endif
-
 /* Sends SDP data packets. */
 #ifndef SDP_POOL_ID
 #define SDP_POOL_ID                 3
@@ -436,10 +222,6 @@
 #define RFCOMM_CMD_POOL_ID          GKI_POOL_ID_2
 #endif
 
-#ifndef RFCOMM_CMD_POOL_BUF_SIZE
-#define RFCOMM_CMD_POOL_BUF_SIZE    GKI_BUF2_SIZE
-#endif
-
 /* Sends RFCOMM data packets. */
 #ifndef RFCOMM_DATA_POOL_ID
 #define RFCOMM_DATA_POOL_ID         GKI_POOL_ID_3
@@ -475,33 +257,11 @@
 #define BTM_CMD_POOL_ID             GKI_POOL_ID_2
 #endif
 
-#ifndef OBX_CMD_POOL_SIZE
-#define OBX_CMD_POOL_SIZE           GKI_BUF2_SIZE
-#endif
-
-#ifndef OBX_LRG_DATA_POOL_SIZE
-#define OBX_LRG_DATA_POOL_SIZE      GKI_BUF4_SIZE
-#endif
-
-#ifndef OBX_LRG_DATA_POOL_ID
-#define OBX_LRG_DATA_POOL_ID        GKI_POOL_ID_4
-#endif
-
-/* Used for CTP discovery database. */
-#ifndef CTP_SDP_DB_POOL_ID
-#define CTP_SDP_DB_POOL_ID          GKI_POOL_ID_3
-#endif
-
 /* Used to send data to L2CAP. */
 #ifndef GAP_DATA_POOL_ID
 #define GAP_DATA_POOL_ID            GKI_POOL_ID_3
 #endif
 
-/* Used for SPP inquiry and discovery databases. */
-#ifndef SPP_DB_POOL_ID
-#define SPP_DB_POOL_ID              GKI_POOL_ID_3
-#endif
-
 #ifndef SPP_DB_SIZE
 #define SPP_DB_SIZE                 GKI_BUF3_SIZE
 #endif
@@ -516,20 +276,6 @@
 #define RPC_SCRATCH_POOL_ID         GKI_POOL_ID_2
 #endif
 
-/* RPC scratch buffer size (not related to RPC_SCRATCH_POOL_ID) */
-#ifndef RPC_SCRATCH_BUF_SIZE
-#define RPC_SCRATCH_BUF_SIZE        GKI_BUF3_SIZE
-#endif
-
-/* RPC pool for protocol messages */
-#ifndef RPC_MSG_POOL_ID
-#define RPC_MSG_POOL_ID             GKI_POOL_ID_3
-#endif
-
-#ifndef RPC_MSG_POOL_SIZE
-#define RPC_MSG_POOL_SIZE           GKI_BUF3_SIZE
-#endif
-
 /* AVDTP pool for protocol messages */
 #ifndef AVDT_CMD_POOL_ID
 #define AVDT_CMD_POOL_ID            GKI_POOL_ID_2
@@ -546,24 +292,11 @@
 #define PAN_POOL_MAX                (GKI_BUF3_MAX / 4)
 #endif
 
-/* UNV pool for read/write serialization */
-#ifndef UNV_MSG_POOL_ID
-#define UNV_MSG_POOL_ID             GKI_POOL_ID_2
-#endif
-
-#ifndef UNV_MSG_POOL_SIZE
-#define UNV_MSG_POOL_SIZE           GKI_BUF2_SIZE
-#endif
-
 /* AVCTP pool for protocol messages */
 #ifndef AVCT_CMD_POOL_ID
 #define AVCT_CMD_POOL_ID            GKI_POOL_ID_1
 #endif
 
-#ifndef AVCT_META_CMD_POOL_ID
-#define AVCT_META_CMD_POOL_ID       GKI_POOL_ID_2
-#endif
-
 /* AVRCP pool for protocol messages */
 #ifndef AVRC_CMD_POOL_ID
 #define AVRC_CMD_POOL_ID            GKI_POOL_ID_1
@@ -590,11 +323,6 @@
 #define AVRC_BROWSE_POOL_SIZE     GKI_MAX_BUF_SIZE
 #endif
 
-/*  HDP buffer size for the Pulse Oximeter  */
-#ifndef BTA_HL_LRG_DATA_POOL_SIZE
-#define BTA_HL_LRG_DATA_POOL_SIZE      GKI_BUF7_SIZE
-#endif
-
 #ifndef BTA_HL_LRG_DATA_POOL_ID
 #define BTA_HL_LRG_DATA_POOL_ID        GKI_POOL_ID_7
 #endif
@@ -615,21 +343,6 @@
 **
 ******************************************************************************/
 
-/* Sends ACL data received over HCI to the upper stack. */
-#ifndef HCI_ACL_DATA_TO_UPPER
-#define HCI_ACL_DATA_TO_UPPER(p)    {((BT_HDR *)p)->event = BT_EVT_TO_BTU_HCI_ACL; GKI_send_msg (BTU_TASK, BTU_HCI_RCV_MBOX, p);}
-#endif
-
-/* Sends SCO data received over HCI to the upper stack. */
-#ifndef HCI_SCO_DATA_TO_UPPER
-#define HCI_SCO_DATA_TO_UPPER(p)    {((BT_HDR *)p)->event = BT_EVT_TO_BTU_HCI_SCO; GKI_send_msg (BTU_TASK, BTU_HCI_RCV_MBOX, p);}
-#endif
-
-/* Sends an HCI event received over HCI to theupper stack. */
-#ifndef HCI_EVT_TO_UPPER
-#define HCI_EVT_TO_UPPER(p)         {((BT_HDR *)p)->event = BT_EVT_TO_BTU_HCI_EVT; GKI_send_msg (BTU_TASK, BTU_HCI_RCV_MBOX, p);}
-#endif
-
 /* Macro for allocating buffer for HCI commands */
 #ifndef HCI_GET_CMD_BUF
 #if (!defined(HCI_USE_VARIABLE_SIZE_CMD_BUF) || (HCI_USE_VARIABLE_SIZE_CMD_BUF == FALSE))
@@ -646,66 +359,6 @@
 ** HCI Services (H4)
 **
 ******************************************************************************/
-#ifndef HCISU_H4_INCLUDED
-#define HCISU_H4_INCLUDED               TRUE
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-BT_API extern void bte_main_hci_send (BT_HDR *p_msg, UINT16 event);
-#if (HCISU_H4_INCLUDED == TRUE)
-BT_API extern void bte_main_lpm_allow_bt_device_sleep(void);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-/* Sends ACL data received from the upper stack to the BD/EDR HCI transport. */
-#ifndef HCI_ACL_DATA_TO_LOWER
-#define HCI_ACL_DATA_TO_LOWER(p)    bte_main_hci_send((BT_HDR *)(p), BT_EVT_TO_LM_HCI_ACL);
-#endif
-
-#ifndef HCI_BLE_ACL_DATA_TO_LOWER
-#define HCI_BLE_ACL_DATA_TO_LOWER(p)    bte_main_hci_send((BT_HDR *)(p), (UINT16)(BT_EVT_TO_LM_HCI_ACL|LOCAL_BLE_CONTROLLER_ID));
-#endif
-
-/* Sends SCO data received from the upper stack to the HCI transport. */
-#ifndef HCI_SCO_DATA_TO_LOWER
-#define HCI_SCO_DATA_TO_LOWER(p)    bte_main_hci_send((BT_HDR *)(p), BT_EVT_TO_LM_HCI_SCO);
-#endif
-
-/* Sends an HCI command received from the upper stack to the BD/EDR HCI transport. */
-#ifndef HCI_CMD_TO_LOWER
-#define HCI_CMD_TO_LOWER(p)         bte_main_hci_send((BT_HDR *)(p), BT_EVT_TO_LM_HCI_CMD);
-#endif
-
-/* Sends an LM Diagnosic command received from the upper stack to the HCI transport. */
-#ifndef HCI_LM_DIAG_TO_LOWER
-#define HCI_LM_DIAG_TO_LOWER(p)     bte_main_hci_send((BT_HDR *)(p), BT_EVT_TO_LM_DIAG);
-#endif
-
-/* Send HCISU a message to allow BT sleep */
-#ifndef HCI_LP_ALLOW_BT_DEVICE_SLEEP
-#define HCI_LP_ALLOW_BT_DEVICE_SLEEP()       bte_main_lpm_allow_bt_device_sleep()
-#endif
-
-/* If nonzero, the upper-layer sends at most this number of HCI commands to the lower-layer. */
-#ifndef HCI_MAX_SIMUL_CMDS
-#define HCI_MAX_SIMUL_CMDS          0
-#endif
-
-/* Timeout for receiving response to HCI command */
-#ifndef BTU_CMD_CMPL_TIMEOUT
-#define BTU_CMD_CMPL_TIMEOUT        8
-#endif
-
-/* If TRUE, BTU task will check HCISU again when HCI command timer expires */
-#ifndef BTU_CMD_CMPL_TOUT_DOUBLE_CHECK
-#define BTU_CMD_CMPL_TOUT_DOUBLE_CHECK      FALSE
-#endif
 
 /* Use 2 second for low-resolution systems, override to 1 for high-resolution systems */
 #ifndef BT_1SEC_TIMEOUT
@@ -716,7 +369,7 @@
 /* if L2CAP_FCR_INCLUDED is TRUE then it should have 100 millisecond resolution */
 /* if none of them is included then QUICK_TIMER_TICKS_PER_SEC is set to 0 to exclude quick timer */
 #ifndef QUICK_TIMER_TICKS_PER_SEC
-#define QUICK_TIMER_TICKS_PER_SEC   10       /* 10ms timer */
+#define QUICK_TIMER_TICKS_PER_SEC   10       /* 100ms timer */
 #endif
 
 /******************************************************************************
@@ -724,38 +377,12 @@
 ** BTM
 **
 ******************************************************************************/
-/* if set to TRUE, stack will automatically send an HCI reset at start-up. To be
-set to FALSE for advanced start-up / shut-down procedures using USER_HW_ENABLE_API
-and USER_HW_DISABLE_API macros */
-#ifndef BTM_AUTOMATIC_HCI_RESET
-#define BTM_AUTOMATIC_HCI_RESET      FALSE
-#endif
-
-/* Include BTM Discovery database and code. */
-#ifndef BTM_DISCOVERY_INCLUDED
-#define BTM_DISCOVERY_INCLUDED      TRUE
-#endif
-
-/* Include inquiry code. */
-#ifndef BTM_INQUIRY_INCLUDED
-#define BTM_INQUIRY_INCLUDED        TRUE
-#endif
 
 /* Cancel Inquiry on incoming SSP */
 #ifndef BTM_NO_SSP_ON_INQUIRY
 #define BTM_NO_SSP_ON_INQUIRY       FALSE
 #endif
 
-/* Include periodic inquiry code (used when BTM_INQUIRY_INCLUDED is TRUE). */
-#ifndef BTM_PERIODIC_INQ_INCLUDED
-#define BTM_PERIODIC_INQ_INCLUDED   TRUE
-#endif
-
-/* Include security authorization code */
-#ifndef BTM_AUTHORIZATION_INCLUDED
-#define BTM_AUTHORIZATION_INCLUDED  TRUE
-#endif
-
 /* Includes SCO if TRUE */
 #ifndef BTM_SCO_INCLUDED
 #define BTM_SCO_INCLUDED            TRUE       /* TRUE includes SCO code */
@@ -771,11 +398,6 @@
 #define BTM_WBS_INCLUDED            FALSE       /* TRUE includes WBS code */
 #endif
 
-/* Includes PCM2 support if TRUE */
-#ifndef BTM_PCM2_INCLUDED
-#define BTM_PCM2_INCLUDED           FALSE
-#endif
-
 /*  This is used to work around a controller bug that doesn't like Disconnect
 **  issued while there is a role switch in progress
 */
@@ -791,66 +413,11 @@
 #define BTM_SCO_DATA_SIZE_MAX       240
 #endif
 
-/* maximum BTM buffering capacity */
-#ifndef BTM_SCO_MAX_BUF_CAP
-#define BTM_SCO_MAX_BUF_CAP     (BTM_SCO_INIT_XMIT_CREDIT * 4)
-#endif
-
 /* The size in bytes of the BTM inquiry database. */
 #ifndef BTM_INQ_DB_SIZE
 #define BTM_INQ_DB_SIZE             40
 #endif
 
-/* This is set to enable automatic periodic inquiry at startup. */
-#ifndef BTM_ENABLE_AUTO_INQUIRY
-#define BTM_ENABLE_AUTO_INQUIRY     FALSE
-#endif
-
-/* This is set to always try to acquire the remote device name. */
-#ifndef BTM_INQ_GET_REMOTE_NAME
-#define BTM_INQ_GET_REMOTE_NAME     FALSE
-#endif
-
-/* The inquiry duration in 1.28 second units when auto inquiry is enabled. */
-#ifndef BTM_DEFAULT_INQ_DUR
-#define BTM_DEFAULT_INQ_DUR         5
-#endif
-
-/* The inquiry mode when auto inquiry is enabled. */
-#ifndef BTM_DEFAULT_INQ_MODE
-#define BTM_DEFAULT_INQ_MODE        BTM_GENERAL_INQUIRY
-#endif
-
-/* The default periodic inquiry maximum delay when auto inquiry is enabled, in 1.28 second units. */
-#ifndef BTM_DEFAULT_INQ_MAX_DELAY
-#define BTM_DEFAULT_INQ_MAX_DELAY   30
-#endif
-
-/* The default periodic inquiry minimum delay when auto inquiry is enabled, in 1.28 second units. */
-#ifndef BTM_DEFAULT_INQ_MIN_DELAY
-#define BTM_DEFAULT_INQ_MIN_DELAY   20
-#endif
-
-/* The maximum age of entries in inquiry database in seconds ('0' disables feature). */
-#ifndef BTM_INQ_MAX_AGE
-#define BTM_INQ_MAX_AGE             0
-#endif
-
-/* The maximum age of entries in inquiry database based on inquiry response failure ('0' disables feature). */
-#ifndef BTM_INQ_AGE_BY_COUNT
-#define BTM_INQ_AGE_BY_COUNT        0
-#endif
-
-/* TRUE if controller does not support inquiry event filtering. */
-#ifndef BTM_BYPASS_EVENT_FILTERING
-#define BTM_BYPASS_EVENT_FILTERING  FALSE
-#endif
-
-/* TRUE if inquiry filtering is desired from BTM. */
-#ifndef BTM_USE_INQ_RESULTS_FILTER
-#define BTM_USE_INQ_RESULTS_FILTER  TRUE
-#endif
-
 /* The default scan mode */
 #ifndef BTM_DEFAULT_SCAN_TYPE
 #define BTM_DEFAULT_SCAN_TYPE       BTM_SCAN_TYPE_INTERLACED
@@ -861,11 +428,6 @@
 #define BTM_ALLOW_CONN_IF_NONDISCOVER   TRUE
 #endif
 
-/* When connectable mode is set to TRUE, the device will respond to paging. */
-#ifndef BTM_IS_CONNECTABLE
-#define BTM_IS_CONNECTABLE          FALSE
-#endif
-
 /* Sets the Page_Scan_Window:  the length of time that the device is performing a page scan. */
 #ifndef BTM_DEFAULT_CONN_WINDOW
 #define BTM_DEFAULT_CONN_WINDOW     0x0012
@@ -876,16 +438,6 @@
 #define BTM_DEFAULT_CONN_INTERVAL   0x0800
 #endif
 
-/* This is set to automatically perform inquiry scan on startup. */
-#ifndef BTM_IS_DISCOVERABLE
-#define BTM_IS_DISCOVERABLE         FALSE
-#endif
-
-/* When automatic inquiry scan is enabled, this sets the discovery mode. */
-#ifndef BTM_DEFAULT_DISC_MODE
-#define BTM_DEFAULT_DISC_MODE       BTM_GENERAL_DISCOVERABLE
-#endif
-
 /* When automatic inquiry scan is enabled, this sets the inquiry scan window. */
 #ifndef BTM_DEFAULT_DISC_WINDOW
 #define BTM_DEFAULT_DISC_WINDOW     0x0012
@@ -896,36 +448,6 @@
 #define BTM_DEFAULT_DISC_INTERVAL   0x0800
 #endif
 
-/* Sets the period, in seconds, to automatically perform service discovery. */
-#ifndef BTM_AUTO_DISCOVERY_PERIOD
-#define BTM_AUTO_DISCOVERY_PERIOD   0
-#endif
-
-/* The size in bytes of the BTM discovery database (if discovery is included). */
-#ifndef BTM_DISCOVERY_DB_SIZE
-#define BTM_DISCOVERY_DB_SIZE       4000
-#endif
-
-/* Number of milliseconds to delay BTU task startup upon device initialization. */
-#ifndef BTU_STARTUP_DELAY
-#define BTU_STARTUP_DELAY           0
-#endif
-
-/* Whether BTA is included in BTU task. */
-#ifndef BTU_BTA_INCLUDED
-#define BTU_BTA_INCLUDED            TRUE
-#endif
-
-/* Number of seconds to wait to send an HCI Reset command upon device initialization. */
-#ifndef BTM_FIRST_RESET_DELAY
-#define BTM_FIRST_RESET_DELAY       0
-#endif
-
-/* The number of seconds to wait for controller module to reset after issuing an HCI Reset command. */
-#ifndef BTM_AFTER_RESET_TIMEOUT
-#define BTM_AFTER_RESET_TIMEOUT     0
-#endif
-
 /* Default class of device
 * {SERVICE_CLASS, MAJOR_CLASS, MINOR_CLASS}
 *
@@ -986,11 +508,6 @@
 #define BTM_SEC_SERVICE_NAME_LEN    BT_MAX_SERVICE_NAME_LEN
 #endif
 
-/* Maximum number of pending security callback */
-#ifndef BTM_SEC_MAX_CALLBACKS
-#define BTM_SEC_MAX_CALLBACKS       7
-#endif
-
 /* Maximum length of the service name. */
 #ifndef BT_MAX_SERVICE_NAME_LEN
 #define BT_MAX_SERVICE_NAME_LEN     21
@@ -1001,11 +518,6 @@
 #define BTM_ACL_BUF_SIZE            0
 #endif
 
-/* This is set to use the BTM power manager. */
-#ifndef BTM_PWR_MGR_INCLUDED
-#define BTM_PWR_MGR_INCLUDED        TRUE
-#endif
-
 /* The maximum number of clients that can register with the power manager. */
 #ifndef BTM_MAX_PM_RECORDS
 #define BTM_MAX_PM_RECORDS          2
@@ -1021,19 +533,8 @@
 #define BTM_SCO_WAKE_PARKED_LINK    TRUE
 #endif
 
-/* May be set to the the name of a function used for vendor specific chip initialization */
-#ifndef BTM_APP_DEV_INIT
-/* #define BTM_APP_DEV_INIT         myInitFunction() */
-#endif
-
-/* This is set to TRUE if the busy level change event is desired. (replace ACL change event) */
-#ifndef BTM_BUSY_LEVEL_CHANGE_INCLUDED
-#define BTM_BUSY_LEVEL_CHANGE_INCLUDED  TRUE
-#endif
-
 /* If the user does not respond to security process requests within this many seconds,
  * a negative response would be sent automatically.
- * It's recommended to use a value between 30 and OBX_TIMEOUT_VALUE
  * 30 is LMP response timeout value */
 #ifndef BTM_SEC_TIMEOUT_VALUE
 #define BTM_SEC_TIMEOUT_VALUE           35
@@ -1047,27 +548,11 @@
 /******************************************
 **    Lisbon Features
 *******************************************/
-/* This is set to TRUE if the server Extended Inquiry Response feature is desired. */
-/* server sends EIR to client */
-#ifndef BTM_EIR_SERVER_INCLUDED
-#define BTM_EIR_SERVER_INCLUDED         TRUE
-#endif
-
-/* This is set to TRUE if the client Extended Inquiry Response feature is desired. */
-/* client inquiry to server */
-#ifndef BTM_EIR_CLIENT_INCLUDED
-#define BTM_EIR_CLIENT_INCLUDED         TRUE
-#endif
-
 /* This is set to TRUE if the FEC is required for EIR packet. */
 #ifndef BTM_EIR_DEFAULT_FEC_REQUIRED
 #define BTM_EIR_DEFAULT_FEC_REQUIRED    TRUE
 #endif
 
-/* User defined UUID look up table */
-#ifndef BTM_EIR_UUID_LKUP_TBL
-#endif
-
 /* The IO capability of the local device (for Simple Pairing) */
 #ifndef BTM_LOCAL_IO_CAPS
 #define BTM_LOCAL_IO_CAPS               BTM_IO_CAP_IO
@@ -1108,24 +593,12 @@
 #define BTM_BLE_CONFORMANCE_TESTING           FALSE
 #endif
 
-/* Maximum number of consecutive HCI commands  that can time out
-* before  it gets treated as H/w error*/
-#ifndef BTM_MAX_HCI_CMD_TOUT_BEFORE_RESTART
-#define BTM_MAX_HCI_CMD_TOUT_BEFORE_RESTART 2
-#endif
-
 /******************************************************************************
 **
 ** L2CAP
 **
 ******************************************************************************/
 
-/* Flow control and retransmission mode */
-
-#ifndef L2CAP_FCR_INCLUDED
-#define L2CAP_FCR_INCLUDED TRUE
-#endif
-
 /* The maximum number of simultaneous links that L2CAP can support. */
 #ifndef MAX_ACL_CONNECTIONS
 #define MAX_L2CAP_LINKS             7
@@ -1168,21 +641,11 @@
 #define L2CAP_MPS_OVER_BR_EDR       1010
 #endif
 
-/* This is set to enable host flow control. */
-#ifndef L2CAP_HOST_FLOW_CTRL
-#define L2CAP_HOST_FLOW_CTRL        FALSE
-#endif
-
 /* If host flow control enabled, this is the number of buffers the controller can have unacknowledged. */
 #ifndef L2CAP_HOST_FC_ACL_BUFS
 #define L2CAP_HOST_FC_ACL_BUFS      20
 #endif
 
-/* The percentage of the queue size allowed before a congestion event is sent to the L2CAP client (typically 120%). */
-#ifndef L2CAP_FWD_CONG_THRESH
-#define L2CAP_FWD_CONG_THRESH       120
-#endif
-
 /* This is set to enable L2CAP to  take the ACL link out of park mode when ACL data is to be sent. */
 #ifndef L2CAP_WAKE_PARKED_LINK
 #define L2CAP_WAKE_PARKED_LINK      TRUE
@@ -1233,11 +696,6 @@
 #define L2CAP_UCD_CH_PRIORITY               L2CAP_CHNL_PRIORITY_MEDIUM
 #endif
 
-/* Max clients on Unicast Connectionless Data */
-#ifndef L2CAP_MAX_UCD_CLIENTS
-#define L2CAP_MAX_UCD_CLIENTS               5
-#endif
-
 /* Used for features using fixed channels; set to zero if no fixed channels supported (BLE, etc.) */
 /* Excluding L2CAP signaling channel and UCD */
 #ifndef L2CAP_NUM_FIXED_CHNLS
@@ -1263,43 +721,19 @@
 #define L2CAP_NUM_XMIT_BUFFS                HCI_ACL_BUF_MAX
 #endif
 
-/* Used for features using fixed channels; set to zero if no fixed channels supported (BLE, etc.) */
-#ifndef L2CAP_NUM_FIXED_CHNLS
-#define L2CAP_NUM_FIXED_CHNLS               1
-#endif
-
-/* First fixed channel supported */
-#ifndef L2CAP_FIRST_FIXED_CHNL
-#define L2CAP_FIRST_FIXED_CHNL              3
-#endif
-
-#ifndef L2CAP_LAST_FIXED_CHNL
-#define L2CAP_LAST_FIXED_CHNL           (L2CAP_FIRST_FIXED_CHNL + L2CAP_NUM_FIXED_CHNLS - 1)
-#endif
-
 /* used for monitoring eL2CAP data flow */
 #ifndef L2CAP_ERTM_STATS
 #define L2CAP_ERTM_STATS                    FALSE
 #endif
 
-/* USED FOR FCR TEST ONLY:  When TRUE generates bad tx and rx packets */
-#ifndef L2CAP_CORRUPT_ERTM_PKTS
-#define L2CAP_CORRUPT_ERTM_PKTS             FALSE
-#endif
-
 /* Used for conformance testing ONLY:  When TRUE lets scriptwrapper overwrite info response */
 #ifndef L2CAP_CONFORMANCE_TESTING
 #define L2CAP_CONFORMANCE_TESTING           FALSE
 #endif
 
-
 #ifndef TIMER_PARAM_TYPE
-#ifdef  WIN2000
-#define TIMER_PARAM_TYPE    void *
-#else
 #define TIMER_PARAM_TYPE    UINT32
 #endif
-#endif
 
 /******************************************************************************
 **
@@ -1371,9 +805,7 @@
 #ifndef BLE_LLT_INCLUDED
 #define BLE_LLT_INCLUDED    TRUE
 #endif
-#ifndef BTM_DUMO_ADDR_CENTRAL_ENABLED
-#define BTM_DUMO_ADDR_CENTRAL_ENABLED    FALSE
-#endif
+
 #ifndef ATT_INCLUDED
 #define ATT_INCLUDED         TRUE
 #endif
@@ -1382,14 +814,6 @@
 #define ATT_DEBUG           TRUE
 #endif
 
-#ifndef GATT_SERVER_ENABLED
-#define GATT_SERVER_ENABLED          TRUE
-#endif
-
-#ifndef GATT_CLIENT_ENABLED
-#define GATT_CLIENT_ENABLED          TRUE
-#endif
-
 #ifndef BLE_PERIPHERAL_MODE_SUPPORT
 #define BLE_PERIPHERAL_MODE_SUPPORT  TRUE
 #endif
@@ -1420,10 +844,6 @@
 #define GATT_MAX_APPS            32 /* note: 2 apps used internally GATT and GAP */
 #endif
 
-#ifndef GATT_MAX_CL_PROFILES
-#define GATT_MAX_CL_PROFILES        4
-#endif
-
 #ifndef GATT_MAX_PHY_CHANNEL
 #define GATT_MAX_PHY_CHANNEL        7
 #endif
@@ -1495,11 +915,7 @@
 
 /* The maximum number of attributes in each record. */
 #ifndef SDP_MAX_REC_ATTR
-//#if defined(HID_DEV_INCLUDED) && (HID_DEV_INCLUDED==TRUE)
 #define SDP_MAX_REC_ATTR            25
-//#else
-//#define SDP_MAX_REC_ATTR            13
-//#endif
 #endif
 
 #ifndef SDP_MAX_PAD_LEN
@@ -1508,11 +924,6 @@
 
 /* The maximum length, in bytes, of an attribute. */
 #ifndef SDP_MAX_ATTR_LEN
-//#if defined(HID_DEV_INCLUDED) && (HID_DEV_INCLUDED==TRUE)
-//#define SDP_MAX_ATTR_LEN            80
-//#else
-//#define SDP_MAX_ATTR_LEN            100
-//#endif
 #define SDP_MAX_ATTR_LEN            400
 #endif
 
@@ -1571,21 +982,12 @@
 #define SDP_SECURITY_LEVEL          BTM_SEC_NONE
 #endif
 
-/* Device identification feature. */
-#ifndef SDP_DI_INCLUDED
-#define SDP_DI_INCLUDED             TRUE
-#endif
-
 /******************************************************************************
 **
 ** RFCOMM
 **
 ******************************************************************************/
 
-#ifndef RFCOMM_INCLUDED
-#define RFCOMM_INCLUDED             TRUE
-#endif
-
 /* The maximum number of ports supported. */
 #ifndef MAX_RFC_PORTS
 #define MAX_RFC_PORTS               30
@@ -1663,11 +1065,6 @@
 #define PORT_CREDIT_RX_LOW          8
 #endif
 
-/* Test code allowing l2cap FEC on RFCOMM.*/
-#ifndef PORT_ENABLE_L2CAP_FCR_TEST
-#define PORT_ENABLE_L2CAP_FCR_TEST  FALSE
-#endif
-
 /* if application like BTA, Java or script test engine is running on other than BTU thread, */
 /* PORT_SCHEDULE_LOCK shall be defined as GKI_sched_lock() or GKI_disable() */
 #ifndef PORT_SCHEDULE_LOCK
@@ -1682,252 +1079,6 @@
 
 /******************************************************************************
 **
-** TCS
-**
-******************************************************************************/
-
-#ifndef TCS_INCLUDED
-#define TCS_INCLUDED                FALSE
-#endif
-
-/* If set to TRUE, gives lean TCS state machine configuration. */
-#ifndef TCS_LEAN
-#define TCS_LEAN                    FALSE
-#endif
-
-/* To include/exclude point-to-multipoint broadcast SETUP configuration. */
-#ifndef TCS_BCST_SETUP_INCLUDED
-#define TCS_BCST_SETUP_INCLUDED     TRUE
-#endif
-
-/* To include/exclude supplementary services. */
-#ifndef TCS_SUPP_SVCS_INCLUDED
-#define TCS_SUPP_SVCS_INCLUDED      TRUE
-#endif
-
-/* To include/exclude WUG master role. */
-#ifndef TCS_WUG_MASTER_INCLUDED
-#define TCS_WUG_MASTER_INCLUDED     TRUE
-#endif
-
-/* To include/exclude WUG member role. */
-#ifndef TCS_WUG_MEMBER_INCLUDED
-#define TCS_WUG_MEMBER_INCLUDED     TRUE
-#endif
-
-/* Maximum number of WUG members. */
-#ifndef TCS_MAX_WUG_MEMBERS
-#define TCS_MAX_WUG_MEMBERS         7
-#endif
-
-/* Broadcom specific acknowledgement message to ensure fast and robust operation of WUG FIMA procedure. */
-#ifndef TCS_WUG_LISTEN_ACPT_ACK_INCLUDED
-#define TCS_WUG_LISTEN_ACPT_ACK_INCLUDED TRUE
-#endif
-
-/* The number of simultaneous calls supported. */
-#ifndef TCS_MAX_NUM_SIMUL_CALLS
-#define TCS_MAX_NUM_SIMUL_CALLS     3
-#endif
-
-/* The number of devices the device can connect to. */
-#ifndef TCS_MAX_NUM_ACL_CONNS
-#define TCS_MAX_NUM_ACL_CONNS       7
-#endif
-
-/* The maximum length, in bytes, of the company specific information element. */
-#ifndef TCS_MAX_CO_SPEC_LEN
-#define TCS_MAX_CO_SPEC_LEN         40
-#endif
-
-/* The maximum length, in bytes, of the audio control information element . */
-#ifndef TCS_MAX_AUDIO_CTL_LEN
-#define TCS_MAX_AUDIO_CTL_LEN       40
-#endif
-
-/* (Dis)allow EDR ESCO */
-#ifndef TCS_AUDIO_USE_ESCO_EDR
-#define TCS_AUDIO_USE_ESCO_EDR      FALSE
-#endif
-
-/******************************************************************************
-**
-** OBX
-**
-******************************************************************************/
-#ifndef OBX_INCLUDED
-#define OBX_INCLUDED               FALSE
-#endif
-
-#ifndef OBX_CLIENT_INCLUDED
-#define OBX_CLIENT_INCLUDED        TRUE
-#endif
-
-#ifndef OBX_SERVER_INCLUDED
-#define OBX_SERVER_INCLUDED        TRUE
-#endif
-
-/* TRUE to include OBEX authentication/MD5 code */
-#ifndef OBX_MD5_INCLUDED
-#define OBX_MD5_INCLUDED           TRUE
-#endif
-
-/* TRUE to include OBEX authentication/MD5 test code */
-#ifndef OBX_MD5_TEST_INCLUDED
-#define OBX_MD5_TEST_INCLUDED       FALSE
-#endif
-
-/* TRUE to include OBEX 1.4 enhancement (including Obex Over L2CAP) */
-#ifndef OBX_14_INCLUDED
-#define OBX_14_INCLUDED             FALSE
-#endif
-/* MD5 code is required to use OBEX 1.4 features (Reliable session) */
-#if (OBX_MD5_INCLUDED == FALSE)
-#undef OBX_14_INCLUDED
-#define OBX_14_INCLUDED             FALSE
-#endif
-
-/* L2CAP FCR/eRTM mode is required to use OBEX Over L2CAP */
-#if (L2CAP_FCR_INCLUDED == FALSE)
-#undef OBX_14_INCLUDED
-#define OBX_14_INCLUDED             FALSE
-#endif
-
-/* The timeout value (in seconds) for reliable sessions to remain in suspend. 0xFFFFFFFF for no timeout event. */
-#ifndef OBX_SESS_TIMEOUT_VALUE
-#define OBX_SESS_TIMEOUT_VALUE      600
-#endif
-
-/* The idle timeout value. 0 for no timeout event. */
-#ifndef OBX_TIMEOUT_VALUE
-#define OBX_TIMEOUT_VALUE           60
-#endif
-
-/* Timeout value used for disconnect */
-#ifndef OBX_DISC_TOUT_VALUE
-#define OBX_DISC_TOUT_VALUE         5
-#endif
-
-/* The maximum number of registered servers. */
-#ifndef OBX_NUM_SERVERS
-#define OBX_NUM_SERVERS             12
-#endif
-
-/* The maximum number of sessions per registered server. */
-#ifndef OBX_MAX_SR_SESSION
-#define OBX_MAX_SR_SESSION          4
-#endif
-
-/* The maximum number of sessions for all registered servers.
- * (must be equal or bigger than OBX_NUM_SERVERS) */
-#ifndef OBX_NUM_SR_SESSIONS
-#define OBX_NUM_SR_SESSIONS         26
-#endif
-
-/* The maximum number of sessions per registered server.
- * must be less than MAX_BD_CONNECTIONS */
-#ifndef OBX_MAX_SR_SESSION
-#define OBX_MAX_SR_SESSION          4
-#endif
-
-/* The maximum number of suspended sessions per registered servers. */
-#ifndef OBX_MAX_SUSPEND_SESSIONS
-#define OBX_MAX_SUSPEND_SESSIONS    4
-#endif
-
-/* The maximum number of active clients. */
-#ifndef OBX_NUM_CLIENTS
-#define OBX_NUM_CLIENTS             8
-#endif
-
-/* The maximum length of OBEX target header.*/
-#ifndef OBX_MAX_TARGET_LEN
-#define OBX_MAX_TARGET_LEN          16
-#endif
-
-/* The maximum length of authentication challenge realm.*/
-#ifndef OBX_MAX_REALM_LEN
-#define OBX_MAX_REALM_LEN           30
-#endif
-
-/* The maximum of GKI buffer queued at OBX before flow control L2CAP */
-#ifndef OBX_MAX_RX_QUEUE_COUNT
-#define OBX_MAX_RX_QUEUE_COUNT      3
-#endif
-
-/* This option is application when OBX_14_INCLUDED=TRUE
-   Pool ID where to reassemble the SDU.
-   This Pool will allow buffers to be used that are larger than
-   the L2CAP_MAX_MTU. */
-#ifndef OBX_USER_RX_POOL_ID
-#define OBX_USER_RX_POOL_ID     OBX_LRG_DATA_POOL_ID
-#endif
-
-/* This option is application when OBX_14_INCLUDED=TRUE
-   Pool ID where to hold the SDU.
-   This Pool will allow buffers to be used that are larger than
-   the L2CAP_MAX_MTU. */
-#ifndef OBX_USER_TX_POOL_ID
-#define OBX_USER_TX_POOL_ID     OBX_LRG_DATA_POOL_ID
-#endif
-
-/* This option is application when OBX_14_INCLUDED=TRUE
-GKI Buffer Pool ID used to hold MPS segments during SDU reassembly
-*/
-#ifndef OBX_FCR_RX_POOL_ID
-#define OBX_FCR_RX_POOL_ID      HCI_ACL_POOL_ID
-#endif
-
-/* This option is application when OBX_14_INCLUDED=TRUE
-GKI Buffer Pool ID used to hold MPS segments used in (re)transmissions.
-L2CAP_DEFAULT_ERM_POOL_ID is specified to use the HCI ACL data pool.
-Note:  This pool needs to have enough buffers to hold two times the window size negotiated
- in the L2CA_SetFCROptions (2 * tx_win_size)  to allow for retransmissions.
- The size of each buffer must be able to hold the maximum MPS segment size passed in
- L2CA_SetFCROptions plus BT_HDR (8) + HCI preamble (4) + L2CAP_MIN_OFFSET (11 - as of BT 2.1 + EDR Spec).
-*/
-#ifndef OBX_FCR_TX_POOL_ID
-#define OBX_FCR_TX_POOL_ID      HCI_ACL_POOL_ID
-#endif
-
-/* This option is application when OBX_14_INCLUDED=TRUE
-Size of the transmission window when using enhanced retransmission mode. Not used
-in basic and streaming modes. Range: 1 - 63
-*/
-#ifndef OBX_FCR_OPT_TX_WINDOW_SIZE_BR_EDR
-#define OBX_FCR_OPT_TX_WINDOW_SIZE_BR_EDR       20
-#endif
-
-/* This option is application when OBX_14_INCLUDED=TRUE
-Number of transmission attempts for a single I-Frame before taking
-Down the connection. Used In ERTM mode only. Value is Ignored in basic and
-Streaming modes.
-Range: 0, 1-0xFF
-0 - infinite retransmissions
-1 - single transmission
-*/
-#ifndef OBX_FCR_OPT_MAX_TX_B4_DISCNT
-#define OBX_FCR_OPT_MAX_TX_B4_DISCNT    20
-#endif
-
-/* This option is application when OBX_14_INCLUDED=TRUE
-Retransmission Timeout
-Range: Minimum 2000 (2 secs) on BR/EDR when supporting PBF.
- */
-#ifndef OBX_FCR_OPT_RETX_TOUT
-#define OBX_FCR_OPT_RETX_TOUT           2000
-#endif
-
-/* This option is application when OBX_14_INCLUDED=TRUE
-Monitor Timeout
-Range: Minimum 12000 (12 secs) on BR/EDR when supporting PBF.
-*/
-#ifndef OBX_FCR_OPT_MONITOR_TOUT
-#define OBX_FCR_OPT_MONITOR_TOUT        12000
-#endif
-
-/******************************************************************************
-**
 ** BNEP
 **
 ******************************************************************************/
@@ -1936,30 +1087,11 @@
 #define BNEP_INCLUDED               TRUE
 #endif
 
-/* Protocol filtering is an optional feature. Bydefault it will be turned on */
-#ifndef BNEP_SUPPORTS_PROT_FILTERS
-#define BNEP_SUPPORTS_PROT_FILTERS          TRUE
-#endif
-
-/* Multicast filtering is an optional feature. Bydefault it will be turned on */
-#ifndef BNEP_SUPPORTS_MULTI_FILTERS
-#define BNEP_SUPPORTS_MULTI_FILTERS         TRUE
-#endif
-
 /* BNEP status API call is used mainly to get the L2CAP handle */
 #ifndef BNEP_SUPPORTS_STATUS_API
 #define BNEP_SUPPORTS_STATUS_API            TRUE
 #endif
 
-/* This is just a debug function */
-#ifndef BNEP_SUPPORTS_DEBUG_DUMP
-#define BNEP_SUPPORTS_DEBUG_DUMP            TRUE
-#endif
-
-#ifndef BNEP_SUPPORTS_ALL_UUID_LENGTHS
-#define BNEP_SUPPORTS_ALL_UUID_LENGTHS      TRUE    /* Otherwise it will support only 16bit UUIDs */
-#endif
-
 /*
 ** When BNEP connection changes roles after the connection is established
 ** we will do an authentication check again on the new role
@@ -1989,11 +1121,6 @@
 #define BNEP_MTU_SIZE               BNEP_MIN_MTU_SIZE
 #endif
 
-/* Maximum size of user data, in bytes.  */
-#ifndef BNEP_MAX_USER_DATA_SIZE
-#define BNEP_MAX_USER_DATA_SIZE     1500
-#endif
-
 /* Maximum number of buffers allowed in transmit data queue. */
 #ifndef BNEP_MAX_XMITQ_DEPTH
 #define BNEP_MAX_XMITQ_DEPTH        20
@@ -2044,9 +1171,9 @@
 #else
 /* signaling and media channels */
 #define AVDT_NUM_CHANNELS   2
-#endif
+#endif  // AVDT_REPORTING
 
-#endif
+#endif  // AVDT_NUM_CHANNELS
 
 /* Number of transport channels setup by AVDT for all media streams
  * AVDT_NUM_CHANNELS * Number of simultaneous streams.
@@ -2055,7 +1182,6 @@
 #define AVDT_NUM_TC_TBL             6
 #endif
 
-
 /* Maximum size in bytes of the codec capabilities information element. */
 #ifndef AVDT_CODEC_SIZE
 #define AVDT_CODEC_SIZE             10
@@ -2102,7 +1228,6 @@
 #define PAN_SUPPORTS_DEBUG_DUMP             TRUE
 #endif
 
-
 /* Maximum number of PAN connections allowed */
 #ifndef MAX_PAN_CONNS
 #define MAX_PAN_CONNS                    7
@@ -2153,288 +1278,17 @@
 #define PAN_NAP_SECURITY_LEVEL           0
 #endif
 
-
-
-
 /******************************************************************************
 **
 ** GAP
 **
 ******************************************************************************/
 
-#ifndef GAP_INCLUDED
-#define GAP_INCLUDED                TRUE
-#endif
-
-/* This is set to enable use of GAP L2CAP connections. */
-#ifndef GAP_CONN_INCLUDED
-#define GAP_CONN_INCLUDED           TRUE
-#endif
-
-/* This is set to enable posting event for data write */
-#ifndef GAP_CONN_POST_EVT_INCLUDED
-#define GAP_CONN_POST_EVT_INCLUDED  FALSE
-#endif
-
-/* The maximum number of simultaneous GAP L2CAP connections. */
-#ifndef GAP_MAX_CONNECTIONS
-#define GAP_MAX_CONNECTIONS         8
-#endif
-
-/******************************************************************************
-**
-** CTP
-**
-******************************************************************************/
-
-#ifndef CTP_INCLUDED
-#define CTP_INCLUDED                FALSE
-#endif
-
-/* To include CTP gateway functionality or not. */
-#ifndef CTP_GW_INCLUDED
-#define CTP_GW_INCLUDED             TRUE
-#endif
-
-/* The number of terminals supported. */
-#ifndef CTP_MAX_NUM_TLS
-#define CTP_MAX_NUM_TLS             7
-#endif
-
-/* If the controller can not support sniff mode when the SCO is up, set this to FALSE. */
-#ifndef CTP_USE_SNIFF_ON_SCO
-#define CTP_USE_SNIFF_ON_SCO        FALSE
-#endif
-
-/* When ACL link between TL and GW is idle for more than this amount of seconds, the ACL may be put to low power mode. */
-#ifndef CTP_TL_IDLE_TIMEOUT
-#define CTP_TL_IDLE_TIMEOUT         90
-#endif
-
-/* To include CTP terminal functionality or not. */
-#ifndef CTP_TL_INCLUDED
-#define CTP_TL_INCLUDED             TRUE
-#endif
-
-/* To include CTP device discovery functionality or not. */
-#ifndef CTP_DISCOVERY_INCLUDED
-#define CTP_DISCOVERY_INCLUDED      TRUE
-#endif
-
-/* set to TRUE for controllers that do not support multi-point */
-#ifndef CTP_TL_WAIT_DISC
-#define CTP_TL_WAIT_DISC            TRUE
-#endif
-
-/* The CTP inquiry database size. */
-#ifndef CTP_INQ_DB_SIZE
-#define CTP_INQ_DB_SIZE             CTP_DISC_REC_SIZE
-#endif
-
-/* The CTP discovery record size. */
-#ifndef CTP_DISC_REC_SIZE
-#define CTP_DISC_REC_SIZE           60
-#endif
-
-/* CTP TL would try to re-establish L2CAP channel after channel is disconnected for this amount of seconds. */
-#ifndef CTP_GUARD_LINK_LOST
-#define CTP_GUARD_LINK_LOST         1
-#endif
-
-/* The link policy bitmap. */
-#ifndef CTP_DEFAULT_LINK_POLICY
-#define CTP_DEFAULT_LINK_POLICY     0x000F
-#endif
-
-/* The minimum period interval used for the sniff and park modes. */
-#ifndef CTP_DEF_LOWPWR_MIN_PERIOD
-#define CTP_DEF_LOWPWR_MIN_PERIOD   0x100
-#endif
-
-/* The maximum period interval used for the sniff and park modes. */
-#ifndef CTP_DEF_LOWPWR_MAX_PERIOD
-#define CTP_DEF_LOWPWR_MAX_PERIOD   0x1E0
-#endif
-
-/* The number of baseband receive slot sniff attempts. */
-#ifndef CTP_DEF_LOWPWR_ATTEMPT
-#define CTP_DEF_LOWPWR_ATTEMPT      0x200
-#endif
-
-/* The number of baseband receive slots for sniff timeout. */
-#ifndef CTP_DEF_LOWPWR_TIMEOUT
-#define CTP_DEF_LOWPWR_TIMEOUT      0x200
-#endif
-
-/* This is set if CTP is to use park mode. */
-#ifndef CTP_PARK_INCLUDED
-#define CTP_PARK_INCLUDED           TRUE
-#endif
-
-/* This is set if CTP is to use sniff mode. */
-#ifndef CTP_SNIFF_INCLUDED
-#define CTP_SNIFF_INCLUDED          TRUE
-#endif
-
-/* To include CTP data exchange functionality or not. */
-#ifndef CTP_DATA_EXCHG_FEATURE
-#define CTP_DATA_EXCHG_FEATURE      FALSE
-#endif
-
-/* To include CTP GW intercom functionality or not. */
-#ifndef CTP_GW_INTERCOM_FEATURE
-#define CTP_GW_INTERCOM_FEATURE     FALSE
-#endif
-
-/* The MTU size for L2CAP channel. */
-#ifndef CTP_MTU_SIZE
-#define CTP_MTU_SIZE                200
-#endif
-
-/* The L2CAP PSM for the data exchange feature. */
-#ifndef CTP_DATA_EXCHG_PSM
-#define CTP_DATA_EXCHG_PSM          13
-#endif
-
-/* The flush timeout for L2CAP channels. */
-#ifndef CTP_FLUSH_TO
-#define CTP_FLUSH_TO                0xFFFF
-#endif
-
-/* The default service name for CTP. */
-#ifndef CTP_DEFAULT_SERVICE_NAME
-#define CTP_DEFAULT_SERVICE_NAME    "Cordless Telephony"
-#endif
-
-/* The CTP security level. */
-#ifndef CTP_SECURITY_LEVEL
-#define CTP_SECURITY_LEVEL          (BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)
-#endif
-
-/* The number of lines to the external network. */
-#ifndef CTP_MAX_LINES
-#define CTP_MAX_LINES               1
-#endif
-
-/* Test if the number of resources in TCS is consistent with CTP setting. */
-#ifndef CTP_TEST_FULL_TCS
-#define CTP_TEST_FULL_TCS           TRUE
-#endif
-
-/* The default inquiry mode. */
-#ifndef CTP_DEFAULT_INQUIRY_MODE
-#define CTP_DEFAULT_INQUIRY_MODE    BTM_GENERAL_INQUIRY
-#endif
-
-/* The default inquiry duration. */
-#ifndef CTP_DEFAULT_INQ_DURATION
-#define CTP_DEFAULT_INQ_DURATION    4
-#endif
-
-/* The maximum number of inquiry responses. */
-#ifndef CTP_DEFAULT_INQ_MAX_RESP
-#define CTP_DEFAULT_INQ_MAX_RESP    3
-#endif
-
-/* When TL does not create another L2CAP channel within this period of time GW declares that it's "Connected Limited". */
-#ifndef CTP_TL_CONN_TIMEOUT
-#define CTP_TL_CONN_TIMEOUT         5
-#endif
-
-/* The delay for ACL to completely disconnect (for intercom) before sending the connect request to GW. */
-#ifndef CTP_RECONNECT_DELAY
-#define CTP_RECONNECT_DELAY         5
-#endif
-
-/* How many times to retry connection when it has failed. */
-#ifndef CTP_RETRY_ON_CONN_ERR
-#define CTP_RETRY_ON_CONN_ERR       5
-#endif
-
-/******************************************************************************
-**
-** ICP
-**
-******************************************************************************/
-
-#ifndef ICP_INCLUDED
-#define ICP_INCLUDED                FALSE
-#endif
-
-/* The ICP default MTU. */
-#ifndef ICP_MTU_SIZE
-#define ICP_MTU_SIZE                100
-#endif
-
-/* The ICP security level. */
-#ifndef ICP_SECURITY_LEVEL
-#define ICP_SECURITY_LEVEL          BTM_SEC_NONE
-#endif
-
-/* The default service name for ICP. */
-#ifndef ICP_DEFAULT_SERVICE_NAME
-#define ICP_DEFAULT_SERVICE_NAME    "Intercom"
-#endif
-
-/* The flush timeout for L2CAP channels. */
-#ifndef ICP_FLUSH_TO
-#define ICP_FLUSH_TO                0xFFFF
-#endif
-
-/******************************************************************************
-**
-** SPP
-**
-******************************************************************************/
-
-#ifndef SPP_INCLUDED
-#define SPP_INCLUDED                FALSE
-#endif
-
-/* The SPP default MTU. */
-#ifndef SPP_DEFAULT_MTU
-#define SPP_DEFAULT_MTU             127
-#endif
-
-/* The interval, in seconds, that a client tries to reconnect to a service. */
-#ifndef SPP_RETRY_CONN_INTERVAL
-#define SPP_RETRY_CONN_INTERVAL     1
-#endif
-
-/* The SPP discoverable mode: limited or general. */
-#ifndef SPP_DISCOVERABLE_MODE
-#define SPP_DISCOVERABLE_MODE       BTM_GENERAL_DISCOVERABLE
-#endif
-
-/* The maximum number of inquiry results returned in by inquiry procedure. */
-#ifndef SPP_DEF_INQ_MAX_RESP
-#define SPP_DEF_INQ_MAX_RESP        10
-#endif
-
-/* The SPP discovery record size. */
-#ifndef SPP_DISC_REC_SIZE
-#define SPP_DISC_REC_SIZE           60
-#endif
-
-#ifndef SPP_MAX_RECS_PER_DEVICE
-#define SPP_MAX_RECS_PER_DEVICE     (SPP_DB_SIZE / SPP_DISC_REC_SIZE)
-#endif
-
-/* Inquiry duration in 1.28 second units. */
-#ifndef SPP_DEF_INQ_DURATION
-#define SPP_DEF_INQ_DURATION        9
-#endif
-
 /* keep the raw data received from SDP server in database. */
 #ifndef SDP_RAW_DATA_INCLUDED
 #define SDP_RAW_DATA_INCLUDED       TRUE
 #endif
 
-/* TRUE, to allow JV to create L2CAP connection on SDP PSM. */
-#ifndef SDP_FOR_JV_INCLUDED
-#define SDP_FOR_JV_INCLUDED         FALSE
-#endif
-
 /* Inquiry duration in 1.28 second units. */
 #ifndef SDP_DEBUG
 #define SDP_DEBUG                   TRUE
@@ -2442,354 +1296,14 @@
 
 /******************************************************************************
 **
-** HSP2, HFP
-**
-******************************************************************************/
-
-#ifndef HSP2_INCLUDED
-#define HSP2_INCLUDED               FALSE
-#endif
-
-/* Include the ability to perform inquiry for peer devices. */
-#ifndef HSP2_INQUIRY_INCLUDED
-#define HSP2_INQUIRY_INCLUDED       TRUE
-#endif
-
-/* Include Audio Gateway specific code. */
-#ifndef HSP2_AG_INCLUDED
-#define HSP2_AG_INCLUDED            TRUE
-#endif
-
-/* Include Headset Specific Code. */
-#ifndef HSP2_HS_INCLUDED
-#define HSP2_HS_INCLUDED            TRUE
-#endif
-
-/* Include the ability to open an SCO connection for In-Band Ringing. */
-#ifndef HSP2_IB_RING_INCLUDED
-#define HSP2_IB_RING_INCLUDED       TRUE
-#endif
-
-/* Include the ability to repeat a ring. */
-#ifndef HSP2_AG_REPEAT_RING
-#define HSP2_AG_REPEAT_RING         TRUE
-#endif
-
-#ifndef HSP2_APP_CLOSES_ON_CKPD
-#define HSP2_APP_CLOSES_ON_CKPD     FALSE
-#endif
-
-
-/* Include the ability to park a connection. */
-#ifndef HSP2_PARK_INCLUDED
-#define HSP2_PARK_INCLUDED          TRUE
-#endif
-
-/* Include HSP State Machine debug trace messages. */
-#ifndef HSP2_FSM_DEBUG
-#define HSP2_FSM_DEBUG              TRUE
-#endif
-
-/* The Module's Inquiry Scan Window. */
-#ifndef HSP2_INQ_SCAN_WINDOW
-#define HSP2_INQ_SCAN_WINDOW        0
-#endif
-
-/* The Module's Inquiry Scan Interval. */
-#ifndef HSP2_INQ_SCAN_INTERVAL
-#define HSP2_INQ_SCAN_INTERVAL      0
-#endif
-
-/* The Module's Page Scan Interval. */
-#ifndef HSP2_PAGE_SCAN_INTERVAL
-#define HSP2_PAGE_SCAN_INTERVAL     0
-#endif
-
-/* The Module's Page Scan Window. */
-#ifndef HSP2_PAGE_SCAN_WINDOW
-#define HSP2_PAGE_SCAN_WINDOW       0
-#endif
-
-/* The Park Mode's Minimum Beacon Period. */
-#ifndef HSP2_BEACON_MIN_PERIOD
-#define HSP2_BEACON_MIN_PERIOD      450
-#endif
-
-/* The Park Mode's Maximum Beacon Period. */
-#ifndef HSP2_BEACON_MAX_PERIOD
-#define HSP2_BEACON_MAX_PERIOD      500
-#endif
-
-/* The duration of the inquiry in seconds. */
-#ifndef HSP2_INQ_DURATION
-#define HSP2_INQ_DURATION           4
-#endif
-
-/* Maximum number of peer responses during an inquiry. */
-#ifndef HSP2_INQ_MAX_NUM_RESPS
-#define HSP2_INQ_MAX_NUM_RESPS      3
-#endif
-
-/* Maximum number of times to retry an inquiry prior to failure. */
-#ifndef HSP2_MAX_INQ_RETRY
-#define HSP2_MAX_INQ_RETRY          6
-#endif
-
-/* Maximum number of times to retry an RFCOMM connection prior to failure. */
-#ifndef HSP2_MAX_CONN_RETRY
-#define HSP2_MAX_CONN_RETRY         3
-#endif
-
-/* If the connect request failed for authentication reasons, do not retry */
-#ifndef HSP2_NO_RETRY_ON_AUTH_FAIL
-#define HSP2_NO_RETRY_ON_AUTH_FAIL  TRUE
-#endif
-
-/* Maximum number of characters in an HSP2 device name. */
-#ifndef HSP2_MAX_NAME_LEN
-#define HSP2_MAX_NAME_LEN           32
-#endif
-
-/* The minimum speaker and/or microphone gain setting. */
-#ifndef HSP2_MIN_GAIN
-#define HSP2_MIN_GAIN               0
-#endif
-
-/* The maximum speaker and/or microphone setting. */
-#ifndef HSP2_MAX_GAIN
-#define HSP2_MAX_GAIN               15
-#endif
-
-/* The default value to send on an AT+CKPD. */
-#ifndef HSP2_KEYPRESS_DEFAULT
-#define HSP2_KEYPRESS_DEFAULT       200
-#endif
-
-/* Maximum amount a data that can be received per RFCOMM frame. */
-#ifndef HSP2_MAX_RFC_READ_LEN
-#define HSP2_MAX_RFC_READ_LEN       128
-#endif
-
-/* The time in seconds to wait for completion of a partial AT command or response from the peer. */
-#ifndef HSP2_AT_TO_INTERVAL
-#define HSP2_AT_TO_INTERVAL         30
-#endif
-
-/* The time to wait before repeating a ring to a peer Headset. */
-#ifndef HSP2_REPEAT_RING_TO
-#define HSP2_REPEAT_RING_TO         4
-#endif
-
-/* Time to wait for a response for an AT command */
-#ifndef HSP2_AT_RSP_TO
-#define HSP2_AT_RSP_TO              20
-#endif
-
-/* SCO packet type(s) to use (bitmask: see spec), 0 - device default (recommended) */
-#ifndef HSP2_SCO_PKT_TYPES
-#define HSP2_SCO_PKT_TYPES          ((UINT16)0x0000)
-#endif
-
-/* The default settings of the SCO voice link. */
-#ifndef HSP2_DEFAULT_VOICE_SETTINGS
-#define HSP2_DEFAULT_VOICE_SETTINGS (HCI_INP_CODING_LINEAR | HCI_INP_DATA_FMT_2S_COMPLEMENT | HCI_INP_SAMPLE_SIZE_16BIT | HCI_AIR_CODING_FORMAT_CVSD)
-#endif
-
-#ifndef HSP2_MAX_AT_CMD_LENGTH
-#define HSP2_MAX_AT_CMD_LENGTH       16
-#endif
-
-#ifndef HSP2_MAX_AT_VAL_LENGTH
-#if (defined(HFP_INCLUDED) && HFP_INCLUDED == TRUE)
-#define HSP2_MAX_AT_VAL_LENGTH       310
-#else
-#define HSP2_MAX_AT_VAL_LENGTH       5
-#endif
-#endif
-
-
-#ifndef HSP2_SDP_DB_SIZE
-#define HSP2_SDP_DB_SIZE             300
-#endif
-
-
-/******************************************************************************
-**
-** HFP
-**
-******************************************************************************/
-
-#ifndef HFP_INCLUDED
-#define HFP_INCLUDED                FALSE
-#endif
-
-/* Include Audio Gateway specific code. */
-#ifndef HFP_AG_INCLUDED
-#define HFP_AG_INCLUDED             TRUE
-#endif
-
-/* Include Hand Free Specific Code. */
-#ifndef HFP_HF_INCLUDED
-#define HFP_HF_INCLUDED             TRUE
-#endif
-
-/* Use AT interface instead of full blown API */
-#ifndef AT_INTERFACE
-#define AT_INTERFACE            FALSE
-#endif
-
-/* HFP Manages SCO establishement for various procedures */
-#ifndef HFP_SCO_MGMT_INCLUDED
-#define HFP_SCO_MGMT_INCLUDED             TRUE
-#endif
-
-/* CCAP compliant features and behavior desired */
-#ifndef CCAP_COMPLIANCE
-#define CCAP_COMPLIANCE             TRUE
-#endif
-
-/* Caller ID string, part of +CLIP result code */
-#ifndef HFP_MAX_CLIP_INFO
-#define HFP_MAX_CLIP_INFO             45
-#endif
-
-#ifndef HFP_RPT_PEER_INFO_INCLUDED
-#define HFP_RPT_PEER_INFO_INCLUDED  TRUE  /* Reporting of peer features enabled */
-#endif
-
-/******************************************************************************
-**
 ** HID
 **
 ******************************************************************************/
 
-/* HID Device Role Included */
-#ifndef HID_DEV_INCLUDED
-#define HID_DEV_INCLUDED             FALSE
-#endif
-
-#ifndef HID_DEV_PM_INCLUDED
-#define HID_DEV_PM_INCLUDED         TRUE
-#endif
-
-/* The HID Device is a virtual cable */
-#ifndef HID_DEV_VIRTUAL_CABLE
-#define HID_DEV_VIRTUAL_CABLE       TRUE
-#endif
-
-/* The HID device initiates the reconnections */
-#ifndef HID_DEV_RECONN_INITIATE
-#define HID_DEV_RECONN_INITIATE     TRUE
-#endif
-
-/* THe HID device is normally connectable */
-#ifndef HID_DEV_NORMALLY_CONN
-#define HID_DEV_NORMALLY_CONN       FALSE
-#endif
-
-/* The device is battery powered */
-#ifndef HID_DEV_BATTERY_POW
-#define HID_DEV_BATTERY_POW         TRUE
-#endif
-
-/* Device is capable of waking up the host */
-#ifndef HID_DEV_REMOTE_WAKE
-#define HID_DEV_REMOTE_WAKE         TRUE
-#endif
-
-/* Device needs host to close SDP channel after SDP is over */
-#ifndef HID_DEV_SDP_DISABLE
-#define HID_DEV_SDP_DISABLE         TRUE
-#endif
-
-#ifndef HID_DEV_MTU_SIZE
-#define HID_DEV_MTU_SIZE                 64
-#endif
-
-#ifndef HID_DEV_FLUSH_TO
-#define HID_DEV_FLUSH_TO                 0xffff
-#endif
-
-#ifndef HID_DEV_PAGE_SCAN_WIN
-#define HID_DEV_PAGE_SCAN_WIN       (0)
-#endif
-
-#ifndef HID_DEV_PAGE_SCAN_INT
-#define HID_DEV_PAGE_SCAN_INT       (0)
-#endif
-
-#ifndef HID_DEV_MAX_CONN_RETRY
-#define HID_DEV_MAX_CONN_RETRY      (15)
-#endif
-
-#ifndef HID_DEV_REPAGE_WIN
-#define HID_DEV_REPAGE_WIN          (1)
-#endif
-
-#ifndef HID_DEV_SVC_NAME
-#define HID_DEV_SVC_NAME            "HID"
-#endif
-
-#ifndef HID_DEV_SVC_DESCR
-#define HID_DEV_SVC_DESCR           "3-button mouse and keyboard"
-#endif
-
-#ifndef HID_DEV_PROVIDER_NAME
-#define HID_DEV_PROVIDER_NAME       "Widcomm"
-#endif
-
-#ifndef HID_DEV_REL_NUM
-#define HID_DEV_REL_NUM             0x0100
-#endif
-
-#ifndef HID_DEV_PARSER_VER
-#define HID_DEV_PARSER_VER          0x0111
-#endif
-
 #ifndef HID_DEV_SUBCLASS
 #define HID_DEV_SUBCLASS            COD_MINOR_POINTING
 #endif
 
-#ifndef HID_DEV_COUNTRY_CODE
-#define HID_DEV_COUNTRY_CODE        0x33
-#endif
-
-#ifndef HID_DEV_SUP_TOUT
-#define HID_DEV_SUP_TOUT            0x8000
-#endif
-
-#ifndef HID_DEV_NUM_LANGS
-#define HID_DEV_NUM_LANGS           1
-#endif
-
-#ifndef HID_DEV_INACT_TIMEOUT
-#define HID_DEV_INACT_TIMEOUT       60
-#endif
-
-#ifndef HID_DEV_BUSY_MODE_PARAMS
-#define HID_DEV_BUSY_MODE_PARAMS    { 320, 160, 10, 20, HCI_MODE_ACTIVE }
-#endif
-
-#ifndef HID_DEV_IDLE_MODE_PARAMS
-#define HID_DEV_IDLE_MODE_PARAMS    { 320, 160, 10, 20, HCI_MODE_SNIFF }
-#endif
-
-#ifndef HID_DEV_SUSP_MODE_PARAMS
-#define HID_DEV_SUSP_MODE_PARAMS    { 640, 320,  0,    0, HCI_MODE_PARK }
-#endif
-
-#ifndef HID_DEV_MAX_DESCRIPTOR_SIZE
-#define HID_DEV_MAX_DESCRIPTOR_SIZE      128     /* Max descriptor size          */
-#endif
-
-#ifndef HID_DEV_LANGUAGELIST
-#define HID_DEV_LANGUAGELIST             {0x35, 0x06, 0x09, 0x04, 0x09, 0x09, 0x01, 0x00}
-#endif
-
-#ifndef HID_DEV_LINK_SUPERVISION_TO
-#define HID_DEV_LINK_SUPERVISION_TO      0x8000
-#endif
-
 #ifndef HID_CONTROL_POOL_ID
 #define HID_CONTROL_POOL_ID             2
 #endif
@@ -2840,517 +1354,6 @@
 #define HID_HOST_REPAGE_WIN          (2)
 #endif
 
-
-/******************************************************************************
-**
-** DUN and FAX
-**
-******************************************************************************/
-
-#ifndef DUN_INCLUDED
-#define DUN_INCLUDED                FALSE
-#endif
-
-
-/******************************************************************************
-**
-** GOEP
-**
-******************************************************************************/
-
-#ifndef GOEP_INCLUDED
-#define GOEP_INCLUDED               FALSE
-#endif
-
-/* This is set to enable GOEP non-blocking file system access functions. */
-#ifndef GOEP_FS_INCLUDED
-#define GOEP_FS_INCLUDED        FALSE
-#endif
-
-/* GOEP authentication key size. */
-#ifndef GOEP_MAX_AUTH_KEY_SIZE
-#define GOEP_MAX_AUTH_KEY_SIZE      16
-#endif
-
-/* Maximum size of the realm authentication string. */
-#ifndef GOEP_MAX_AUTH_REALM_SIZE
-#define GOEP_MAX_AUTH_REALM_SIZE    16
-#endif
-
-/* Realm Character Set */
-#ifndef GOEP_REALM_CHARSET
-#define GOEP_REALM_CHARSET          0       /* ASCII */
-#endif
-
-/* This is set to the maximum length of path name allowed in the system (_MAX_PATH). */
-#ifndef GOEP_MAX_PATH_SIZE
-#define GOEP_MAX_PATH_SIZE          255
-#endif
-
-/* Specifies whether or not client's user id is required during obex authentication */
-#ifndef GOEP_SERVER_USERID_REQUIRED
-#define GOEP_SERVER_USERID_REQUIRED FALSE
-#endif
-
-/* This is set to the maximum length of file name allowed in the system (_MAX_FNAME). */
-#ifndef GOEP_MAX_FILE_SIZE
-#define GOEP_MAX_FILE_SIZE          128
-#endif
-
-/* Character used as path separator */
-#ifndef GOEP_PATH_SEPARATOR
-#define GOEP_PATH_SEPARATOR         ((char) 0x5c)   /* 0x2f ('/'), or 0x5c ('\') */
-#endif
-
-/******************************************************************************
-**
-** OPP
-**
-******************************************************************************/
-
-#ifndef OPP_INCLUDED
-#define OPP_INCLUDED                FALSE
-#endif
-
-/* This is set to enable OPP client capabilities. */
-#ifndef OPP_CLIENT_INCLUDED
-#define OPP_CLIENT_INCLUDED         FALSE
-#endif
-
-/* This is set to enable OPP server capabilities. */
-#ifndef OPP_SERVER_INCLUDED
-#define OPP_SERVER_INCLUDED         FALSE
-#endif
-
-/* if the optional formating functions are to be included or not */
-#ifndef OPP_FORMAT_INCLUDED
-#define OPP_FORMAT_INCLUDED         FALSE
-#endif
-
-/* Maximum number of client sessions allowed by server */
-#ifndef OPP_MAX_SRVR_SESS
-#define OPP_MAX_SRVR_SESS           3
-#endif
-
-/******************************************************************************
-**
-** FTP
-**
-******************************************************************************/
-
-#ifndef FTP_INCLUDED
-#define FTP_INCLUDED                FALSE
-#endif
-
-/* This is set to enable FTP client capabilities. */
-#ifndef FTP_CLIENT_INCLUDED
-#define FTP_CLIENT_INCLUDED         TRUE
-#endif
-
-/* This is set to enable FTP server capabilities. */
-#ifndef FTP_SERVER_INCLUDED
-#define FTP_SERVER_INCLUDED         TRUE
-#endif
-
-/******************************************************************************
-**
-** XML Parser
-**
-******************************************************************************/
-
-#ifndef XML_STACK_SIZE
-#define XML_STACK_SIZE             7
-#endif
-
-/******************************************************************************
-**
-** BPP Printer
-**
-******************************************************************************/
-#ifndef BPP_DEBUG
-#define BPP_DEBUG            FALSE
-#endif
-
-#ifndef BPP_INCLUDED
-#define BPP_INCLUDED                FALSE
-#endif
-
-#ifndef BPP_SND_INCLUDED
-#define BPP_SND_INCLUDED            FALSE
-#endif
-
-/* Maximum number of senders allowed to connect simultaneously
-** The maximum is 6 or (OBX_NUM_SERVERS / 2), whichever is smaller
-*/
-#ifndef BPP_PR_MAX_CON
-#define BPP_PR_MAX_CON         3
-#endif
-
-/* Service Name. maximum length: 248
-#ifndef BPP_SERVICE_NAME
-#define BPP_SERVICE_NAME            "Basic Printing"
-#endif
- */
-/* Document Format Supported. ASCII comma-delimited list of MIME type:version string
-#ifndef BPP_DOC_FORMAT_SUPPORTED
-#define BPP_DOC_FORMAT_SUPPORTED    "application/vnd.pwg-xhtml-print:1.0,application/vnd.hp-PCL:5E,application/PDF"
-#endif
-
-#ifndef BPP_DOC_FORMAT_SUPPORTED_LEN
-#define BPP_DOC_FORMAT_SUPPORTED_LEN    77
-#endif
- */
-/* Character repertoires.
-#ifndef BPP_CHARACTER_REPERTOIRES
-#define BPP_CHARACTER_REPERTOIRES {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01}
-#endif
- */
-/* XHTML formats.
-#ifndef BPP_XHTML_PRINT_FORMATS
-#define BPP_XHTML_PRINT_FORMATS     "image/gif:89A,image/jpeg"
-#endif
-
-#ifndef BPP_XHTML_PRINT_FORMATS_LEN
-#define BPP_XHTML_PRINT_FORMATS_LEN 24
-#endif
- */
-/* Color supported.
-#ifndef BPP_COLOR_SUPORTED
-#define BPP_COLOR_SUPORTED          FALSE
-#endif
- */
-/* 1284 ID string. First 2 bytes are the length.
-#ifndef BPP_1284ID
-#define BPP_1284ID                  "\x00\x48MANUFACTURER:ACME Manufacturing;COMMAND SET:PCL,MPL;MODEL:LaserBeam \?;"
-#endif
-
-#ifndef BPP_1284ID_LEN
-#define BPP_1284ID_LEN              72
-#endif
- */
-/* Printer name.
-#ifndef BPP_PRINTER_NAME
-#define BPP_PRINTER_NAME            "My Printer"
-#endif
-
-#ifndef BPP_PRINTER_NAME_LEN
-#define BPP_PRINTER_NAME_LEN        10
-#endif
- */
-
-/* Printer location.
-#ifndef BPP_PRINTER_LOCATION
-#define BPP_PRINTER_LOCATION        "Hotel Lobby"
-#endif
-
-#ifndef BPP_PRINTER_LOCATION_LEN
-#define BPP_PRINTER_LOCATION_LEN    11
-#endif
- */
-/* Duplex printing supported.
-#ifndef BPP_DUPLEX_SUPPORTED
-#define BPP_DUPLEX_SUPPORTED        TRUE
-#endif
- */
-
-/* Media types supported.
-#ifndef BPP_MEDIA_TYPES_SUPPORTED
-#define BPP_MEDIA_TYPES_SUPPORTED   "stationary,continuous-long,photographic-high-gloss,cardstock"
-#endif
-
-#ifndef BPP_MEDIA_TYPES_SUPPORTED_LEN
-#define BPP_MEDIA_TYPES_SUPPORTED_LEN   60
-#endif
- */
-/* Maximum media with supported.
-#ifndef BPP_MAX_MEDIA_WIDTH
-#define BPP_MAX_MEDIA_WIDTH         205
-#endif
- */
-/* Maximum media length supported.
-#ifndef BPP_MAX_MEDIA_LENGTH
-#define BPP_MAX_MEDIA_LENGTH        285
-#endif
- */
-/* the maximum string len for the media size of medium loaded */
-#ifndef BPP_MEDIA_SIZE_LEN
-#define BPP_MEDIA_SIZE_LEN          33
-#endif
-
-/* Debug Trace the SOAP object, if TRUE */
-#ifndef BPP_TRACE_XML
-#define BPP_TRACE_XML               TRUE
-#endif
-
-/* in case that the SOAP object does not all come in one OBEX packet,
- * this size of data may be kept in the BPP control block for continuing parsing.
- * The maximum is the size of the biggest GKI buffer (GKI_MAX_BUF_SIZE) */
-#ifndef BPP_SOAP_KEEP_SIZE
-#define BPP_SOAP_KEEP_SIZE          200
-#endif
-
-
-/******************************************************************************
-**
-** BIP
-**
-******************************************************************************/
-#ifndef BIP_INCLUDED
-#define BIP_INCLUDED                FALSE
-#endif
-
-/* TRUE to include imaging initiator */
-#ifndef BIP_INITR_INCLUDED
-#define BIP_INITR_INCLUDED          FALSE
-#endif
-
-/* TRUE to include imaging responder */
-#ifndef BIP_RSPDR_INCLUDED
-#define BIP_RSPDR_INCLUDED          FALSE
-#endif
-
-/* TRUE to include image push feature */
-#ifndef BIP_PUSH_INCLUDED
-#define BIP_PUSH_INCLUDED           TRUE
-#endif
-
-/* TRUE to include image pull feature */
-#ifndef BIP_PULL_INCLUDED
-#define BIP_PULL_INCLUDED           TRUE
-#endif
-
-/* TRUE to include advanced image printing feature */
-#ifndef BIP_PRINTING_INCLUDED
-#define BIP_PRINTING_INCLUDED       TRUE
-#endif
-
-/* TRUE to include automatic archive feature */
-#ifndef BIP_ARCHIVE_INCLUDED
-#define BIP_ARCHIVE_INCLUDED        TRUE
-#endif
-
-/* TRUE to include remote camera feature */
-#ifndef BIP_CAMERA_INCLUDED
-#define BIP_CAMERA_INCLUDED         TRUE
-#endif
-
-/* TRUE to include remote display feature */
-#ifndef BIP_DISPLAY_INCLUDED
-#define BIP_DISPLAY_INCLUDED        TRUE
-#endif
-
-/* TRUE to include sanity check code for API functions */
-#ifndef BIP_SANITY_CHECKS
-#define BIP_SANITY_CHECKS           TRUE
-#endif
-
-/* TRUE to show the received XML object in trace for conformance tests */
-#ifndef BIP_TRACE_XML
-#define BIP_TRACE_XML               TRUE
-#endif
-
-/* in case that the received XML object is not complete, the XML parser state machine needs
- * to keep a copy of the data from the last '<'
- * This macro specifies the maximun amount of data for this purpose */
-#ifndef BIP_XML_CARRY_OVER_LEN
-#define BIP_XML_CARRY_OVER_LEN      100
-#endif
-
-/* minimum 4, maximum is 255. The value should be set to the maximum size of encoding string + 1. JPEG2000.
- * If vendor specific format is supported, it might be bigger than 9 */
-#ifndef BIP_IMG_ENCODE_SIZE
-#define BIP_IMG_ENCODE_SIZE         9
-#endif
-
-/* MIME type: text/plain */
-#ifndef BIP_TYPE_SIZE
-#define BIP_TYPE_SIZE               20
-#endif
-
-/* example: iso-8895-1 */
-#ifndef BIP_CHARSET_SIZE
-#define BIP_CHARSET_SIZE            10
-#endif
-
-/* friendly name */
-#ifndef BIP_FNAME_SIZE
-#define BIP_FNAME_SIZE              20
-#endif
-
-/* service name */
-#ifndef BIP_SNAME_SIZE
-#define BIP_SNAME_SIZE              60
-#endif
-
-/* temporary storage file name(for file system access, may include path) */
-#ifndef BIP_TEMP_NAME_SIZE
-#define BIP_TEMP_NAME_SIZE          200
-#endif
-
-/* image file name */
-#ifndef BIP_IMG_NAME_SIZE
-#define BIP_IMG_NAME_SIZE           200
-#endif
-
-/* attachment file name */
-#ifndef BIP_ATT_NAME_SIZE
-#define BIP_ATT_NAME_SIZE           200
-#endif
-
-/* object (image, attachment, thumbnail) file name (may be used for file system) */
-#ifndef BIP_OBJ_NAME_SIZE
-#define BIP_OBJ_NAME_SIZE           200
-#endif
-
-
-
-/******************************************************************************
-**
-** HCRP
-**
-******************************************************************************/
-
-#ifndef HCRP_INCLUDED
-#define HCRP_INCLUDED               FALSE
-#endif
-
-/* This is set to enable server. */
-#ifndef HCRP_SERVER_INCLUDED
-#define HCRP_SERVER_INCLUDED       FALSE
-#endif
-
-/* This is set to enable client. */
-#ifndef HCRP_CLIENT_INCLUDED
-#define HCRP_CLIENT_INCLUDED        FALSE
-#endif
-
-/* TRUE enables the notification option of the profile. */
-#ifndef HCRP_NOTIFICATION_INCLUDED
-#define HCRP_NOTIFICATION_INCLUDED  TRUE
-#endif
-
-/* TRUE enables the vendor specific option of the profile. */
-#ifndef HCRP_VENDOR_SPEC_INCLUDED
-#define HCRP_VENDOR_SPEC_INCLUDED   TRUE
-#endif
-
-/* TRUE enables state machine traces. */
-#ifndef HCRP_FSM_DEBUG
-#define HCRP_FSM_DEBUG              FALSE
-#endif
-
-/* TRUE enables protocol message traces. */
-#ifndef HCRP_PROTO_DEBUG
-#define HCRP_PROTO_DEBUG            FALSE
-#endif
-
-/* Maximum length used to store the service name (Minimum 1). */
-#ifndef HCRP_MAX_SERVICE_NAME_LEN
-#define HCRP_MAX_SERVICE_NAME_LEN   32
-#endif
-
-/* Maximum length used to store the device name (Minimum 1). */
-#ifndef HCRP_MAX_DEVICE_NAME_LEN
-#define HCRP_MAX_DEVICE_NAME_LEN    32
-#endif
-
-/* Maximum length of device location (Minimum 1) */
-#ifndef HCRP_MAX_DEVICE_LOC_LEN
-#define HCRP_MAX_DEVICE_LOC_LEN     32
-#endif
-
-/* Maximum length used to store the friendly name (Minimum 1). */
-#ifndef HCRP_MAX_FRIENDLY_NAME_LEN
-#define HCRP_MAX_FRIENDLY_NAME_LEN  32
-#endif
-
-/* Maximum length used to store the 1284 id string (Minimum 2 byte length field). */
-#ifndef HCRP_MAX_SDP_1284_ID_LEN
-#define HCRP_MAX_SDP_1284_ID_LEN    128
-#endif
-
-/* Maximum length for parameters to be processed for vendor specific commands. */
-#ifndef HCRP_MAX_VEND_SPEC_LEN
-#define HCRP_MAX_VEND_SPEC_LEN      4
-#endif
-
-/* Number of seconds to wait for 2nd GAP to open. */
-#ifndef HCRP_OPEN_CHAN_TOUT
-#define HCRP_OPEN_CHAN_TOUT         5
-#endif
-
-/* Number of seconds to wait for 2nd GAP to close. */
-#ifndef HCRP_CLOSE_CHAN_TOUT
-#define HCRP_CLOSE_CHAN_TOUT        3
-#endif
-
-/* Number of seconds to wait for the application to respond to a protocol request. */
-#ifndef HCRP_APPL_RSP_TOUT
-#define HCRP_APPL_RSP_TOUT          5
-#endif
-
-/* Number of seconds to wait for the peer device to respond to a protocol request. */
-#ifndef HCRP_CMD_RSP_TOUT
-#define HCRP_CMD_RSP_TOUT           7
-#endif
-
-/* Number of seconds between subsequent credit requests to the server when the send watermark has been exceeded. */
-#ifndef HCRP_CREDIT_REQ_UPDATES
-#define HCRP_CREDIT_REQ_UPDATES     1
-#endif
-
-/* Maximum number of results to return in a HCRP_FindServices search. */
-#ifndef HCRP_MAX_SEARCH_RESULTS
-#define HCRP_MAX_SEARCH_RESULTS     1
-#endif
-
-/* Maximum number of bytes to be reserved for searching for the client's notification record. */
-#ifndef HCRP_MAX_NOTIF_DISC_BUF
-#define HCRP_MAX_NOTIF_DISC_BUF     300
-#endif
-
-/* Maximum number of clients the server will allow to be registered for notifications. */
-#ifndef HCRP_MAX_NOTIF_CLIENTS
-#define HCRP_MAX_NOTIF_CLIENTS      3
-#endif
-
-/* Spec says minimum of two notification retries. */
-#ifndef HCRP_NOTIF_NUM_RETRIES
-#define HCRP_NOTIF_NUM_RETRIES      4
-#endif
-
-/*************************************************************************
-** Definitions for Multi-Client Server HCRP
-** Note: Many of the above HCRP definitions are also used
-** Maximum number of clients allowed to connect simultaneously
-** Must be less than ((GAP_MAX_CONNECTIONS - 1) / 2)
-*/
-#ifndef HCRPM_MAX_CLIENTS
-#define HCRPM_MAX_CLIENTS           3
-#endif
-
-
-/******************************************************************************
-**
-** PAN
-**
-******************************************************************************/
-
-#ifndef PAN_INCLUDED
-#define PAN_INCLUDED                FALSE
-#endif
-
-
-/******************************************************************************
-**
-** SAP
-**
-******************************************************************************/
-
-#ifndef SAP_SERVER_INCLUDED
-#define SAP_SERVER_INCLUDED         FALSE
-#endif
-
 /*************************************************************************
  * A2DP Definitions
  */
@@ -3358,31 +1361,12 @@
 #define A2D_INCLUDED            TRUE
 #endif
 
-/* TRUE to include SBC utility functions */
-#ifndef A2D_SBC_INCLUDED
-#define A2D_SBC_INCLUDED        A2D_INCLUDED
-#endif
-
-/* TRUE to include MPEG-1,2 (mp3) utility functions */
-#ifndef A2D_M12_INCLUDED
-#define A2D_M12_INCLUDED        A2D_INCLUDED
-#endif
-
-/* TRUE to include MPEG-2,4 (aac) utility functions */
-#ifndef A2D_M24_INCLUDED
-#define A2D_M24_INCLUDED        A2D_INCLUDED
-#endif
-
 /******************************************************************************
 **
 ** AVCTP
 **
 ******************************************************************************/
 
-#ifndef AVCT_INCLUDED
-#define AVCT_INCLUDED               TRUE
-#endif
-
 /* Number of simultaneous ACL links to different peer devices. */
 #ifndef AVCT_NUM_LINKS
 #define AVCT_NUM_LINKS              2
@@ -3393,87 +1377,12 @@
 #define AVCT_NUM_CONN               3
 #endif
 
-/* Pool ID where to reassemble the SDU.
-   This Pool allows buffers to be used that are larger than
-   the L2CAP_MAX_MTU. */
-#ifndef AVCT_BR_USER_RX_POOL_ID
-#define AVCT_BR_USER_RX_POOL_ID     HCI_ACL_POOL_ID
-#endif
-
-/* Pool ID where to hold the SDU.
-   This Pool allows buffers to be used that are larger than
-   the L2CAP_MAX_MTU. */
-#ifndef AVCT_BR_USER_TX_POOL_ID
-#define AVCT_BR_USER_TX_POOL_ID     HCI_ACL_POOL_ID
-#endif
-
-/*
-GKI Buffer Pool ID used to hold MPS segments during SDU reassembly
-*/
-#ifndef AVCT_BR_FCR_RX_POOL_ID
-#define AVCT_BR_FCR_RX_POOL_ID      HCI_ACL_POOL_ID
-#endif
-
-/*
-GKI Buffer Pool ID used to hold MPS segments used in (re)transmissions.
-L2CAP_DEFAULT_ERM_POOL_ID is specified to use the HCI ACL data pool.
-Note:  This pool needs to have enough buffers to hold two times the window size negotiated
- in the tL2CAP_FCR_OPTIONS (2 * tx_win_size)  to allow for retransmissions.
- The size of each buffer must be able to hold the maximum MPS segment size passed in
- tL2CAP_FCR_OPTIONS plus BT_HDR (8) + HCI preamble (4) + L2CAP_MIN_OFFSET (11 - as of BT 2.1 + EDR Spec).
-*/
-#ifndef AVCT_BR_FCR_TX_POOL_ID
-#define AVCT_BR_FCR_TX_POOL_ID      HCI_ACL_POOL_ID
-#endif
-
-/* AVCTP Browsing channel FCR Option:
-Size of the transmission window when using enhanced retransmission mode. Not used
-in basic and streaming modes. Range: 1 - 63
-*/
-#ifndef AVCT_BR_FCR_OPT_TX_WINDOW_SIZE
-#define AVCT_BR_FCR_OPT_TX_WINDOW_SIZE      10
-#endif
-
-/* AVCTP Browsing channel FCR Option:
-Number of transmission attempts for a single I-Frame before taking
-Down the connection. Used In ERTM mode only. Value is Ignored in basic and
-Streaming modes.
-Range: 0, 1-0xFF
-0 - infinite retransmissions
-1 - single transmission
-*/
-#ifndef AVCT_BR_FCR_OPT_MAX_TX_B4_DISCNT
-#define AVCT_BR_FCR_OPT_MAX_TX_B4_DISCNT    20
-#endif
-
-/* AVCTP Browsing channel FCR Option: Retransmission Timeout
-The AVRCP specification set a value in the range of 300 - 2000 ms
-Timeout (in msecs) to detect Lost I-Frames. Only used in Enhanced retransmission mode.
-Range: Minimum 2000 (2 secs) when supporting PBF.
- */
-#ifndef AVCT_BR_FCR_OPT_RETX_TOUT
-#define AVCT_BR_FCR_OPT_RETX_TOUT           2000
-#endif
-
-/* AVCTP Browsing channel FCR Option: Monitor Timeout
-The AVRCP specification set a value in the range of 300 - 2000 ms
-Timeout (in msecs) to detect Lost S-Frames. Only used in Enhanced retransmission mode.
-Range: Minimum 12000 (12 secs) when supporting PBF.
-*/
-#ifndef AVCT_BR_FCR_OPT_MONITOR_TOUT
-#define AVCT_BR_FCR_OPT_MONITOR_TOUT        12000
-#endif
-
 /******************************************************************************
 **
 ** AVRCP
 **
 ******************************************************************************/
 
-#ifndef AVRC_INCLUDED
-#define AVRC_INCLUDED               TRUE
-#endif
-
 #ifndef AVRC_METADATA_INCLUDED
 #define AVRC_METADATA_INCLUDED      TRUE
 #endif
@@ -3495,11 +1404,6 @@
 #define MCA_INCLUDED                FALSE
 #endif
 
-/* TRUE to support Clock Synchronization OpCodes */
-#ifndef MCA_SYNC_INCLUDED
-#define MCA_SYNC_INCLUDED           FALSE
-#endif
-
 /* The MTU size for the L2CAP configuration on control channel. 48 is the minimal */
 #ifndef MCA_CTRL_MTU
 #define MCA_CTRL_MTU    60
@@ -3606,41 +1510,6 @@
 
 /******************************************************************************
 **
-** SER
-**
-******************************************************************************/
-
-#ifndef SER_INCLUDED
-#define SER_INCLUDED                FALSE
-#endif
-
-/* Task which runs the serial application. */
-#ifndef SER_TASK
-#define SER_TASK                    BTE_APPL_TASK
-#endif
-
-/* Mailbox used by serial application. */
-#ifndef SER_MBOX
-#define SER_MBOX                    TASK_MBOX_1
-#endif
-
-/* Mailbox mask. */
-#ifndef SER_MBOX_MASK
-#define SER_MBOX_MASK               TASK_MBOX_1_EVT_MASK
-#endif
-
-/* TX path application event. */
-#ifndef SER_TX_PATH_APPL_EVT
-#define SER_TX_PATH_APPL_EVT        EVENT_MASK(APPL_EVT_3)
-#endif
-
-/* RX path application event. */
-#ifndef SER_RX_PATH_APPL_EVT
-#define SER_RX_PATH_APPL_EVT        EVENT_MASK(APPL_EVT_4)
-#endif
-
-/******************************************************************************
-**
 ** Sleep Mode (Low Power Mode)
 **
 ******************************************************************************/
@@ -3651,89 +1520,13 @@
 
 /******************************************************************************
 **
-** RPC
-**
-******************************************************************************/
-
-#ifndef RPC_INCLUDED
-#define RPC_INCLUDED                FALSE
-#endif
-
-/* RPCT task mailbox ID for messages coming from rpcgen code. */
-#ifndef RPCT_MBOX
-#define RPCT_MBOX                   TASK_MBOX_0
-#endif
-
-/* RPCT task event for mailbox. */
-#ifndef RPCT_RPC_MBOX_EVT
-#define RPCT_RPC_MBOX_EVT           TASK_MBOX_0_EVT_MASK
-#endif
-
-/* RPCT task event from driver indicating RX data is ready. */
-#ifndef RPCT_RX_READY_EVT
-#define RPCT_RX_READY_EVT           APPL_EVT_0
-#endif
-
-/* RPCT task event from driver indicating data TX is done. */
-#ifndef RPCT_TX_DONE_EVT
-#define RPCT_TX_DONE_EVT            APPL_EVT_1
-#endif
-
-/* RPCT task event indicating data is in the circular buffer. */
-#ifndef RPCT_UCBUF_EVT
-#define RPCT_UCBUF_EVT              APPL_EVT_2
-#endif
-
-/* Task ID of RPCGEN task. */
-#ifndef RPCGEN_TASK
-#define RPCGEN_TASK                 BTU_TASK
-#endif
-
-/* RPCGEN task event for messages coming from RPCT. */
-#ifndef RPCGEN_MSG_EVT
-#define RPCGEN_MSG_EVT              TASK_MBOX_1_EVT_MASK
-#endif
-
-#ifndef RPCGEN_MSG_MBOX
-#define RPCGEN_MSG_MBOX             TASK_MBOX_1
-#endif
-
-/* Size of circular buffer used to store diagnostic messages. */
-#ifndef RPCT_UCBUF_SIZE
-#define RPCT_UCBUF_SIZE             2000
-#endif
-
-/******************************************************************************
-**
-** SAP - Sample applications
-**
-******************************************************************************/
-
-#ifndef MMI_INCLUDED
-#define MMI_INCLUDED                FALSE
-#endif
-
-/******************************************************************************
-**
 ** APPL - Application Task
 **
 ******************************************************************************/
-/* When TRUE indicates that an application task is to be run */
-#ifndef APPL_INCLUDED
-#define APPL_INCLUDED                TRUE
-#endif
-
-/* When TRUE remote terminal code included (RPC MUST be included) */
-#ifndef RSI_INCLUDED
-#define RSI_INCLUDED                TRUE
-#endif
-
-
 
 #define L2CAP_FEATURE_REQ_ID      73
 #define L2CAP_FEATURE_RSP_ID     173
 
-
 /******************************************************************************
 **
 ** BTA
@@ -3769,37 +1562,6 @@
 
 /******************************************************************************
 **
-** BTE
-**
-******************************************************************************/
-#ifndef BTE_PLATFORM_IDLE
-#define BTE_PLATFORM_IDLE
-#endif
-
-#ifndef BTE_IDLE_TASK_INCLUDED
-#define BTE_IDLE_TASK_INCLUDED FALSE
-#endif
-
-#ifndef BTE_PLATFORM_INITHW
-#define BTE_PLATFORM_INITHW
-#endif
-
-#ifndef BTE_BTA_CODE_INCLUDED
-#define BTE_BTA_CODE_INCLUDED FALSE
-#endif
-
-/******************************************************************************
-**
-** BTTRC
-**
-******************************************************************************/
-/* Whether to parse and display traces-> Platform specific implementation */
-#ifndef BTTRC_DISP
-#define BTTRC_DISP        BTTRC_DispOnInsight
-#endif
-
-/******************************************************************************
-**
 ** Tracing:  Include trace header file here.
 **
 ******************************************************************************/
diff --git a/include/bt_trace.h b/include/bt_trace.h
index 703b582..13942d4 100644
--- a/include/bt_trace.h
+++ b/include/bt_trace.h
@@ -16,25 +16,9 @@
  *
  ******************************************************************************/
 
-/******************************************************************************
- *
- *  This file contains definitions for implementing the
- *  diagnostic trace message service.
- *
- ******************************************************************************/
+#pragma once
 
-#ifndef BT_TRACE_H
-#define BT_TRACE_H
-
-#ifndef BTTRC_INCLUDED
-#define BTTRC_INCLUDED  FALSE
-#endif
-#ifndef BTTRC_PARSER_INCLUDED
-#define BTTRC_PARSER_INCLUDED FALSE
-#endif
-#ifndef MAX_TRACE_RAM_SIZE
-#define MAX_TRACE_RAM_SIZE 10000
-#endif
+static const char BTE_LOGMSG_MODULE[] = "bte_logmsg_module";
 
 /* BTE tracing IDs for debug purposes */
 /* LayerIDs for stack */
@@ -60,14 +44,12 @@
 #define BTTRC_ID_STK_BTM_INQ               20
 #define BTTRC_ID_STK_BTM_SCO               21
 #define BTTRC_ID_STK_BTM_SEC               22
-#define BTTRC_ID_STK_DUN                   23
 #define BTTRC_ID_STK_HID                   24
 #define BTTRC_ID_STK_HSP2                  25
 #define BTTRC_ID_STK_CTP                   26
 #define BTTRC_ID_STK_FTC                   27
 #define BTTRC_ID_STK_FTS                   28
 #define BTTRC_ID_STK_GAP                   29
-#define BTTRC_ID_STK_GOEP                  30
 #define BTTRC_ID_STK_HCRP                  31
 #define BTTRC_ID_STK_ICP                   32
 #define BTTRC_ID_STK_OPC                   33
@@ -92,7 +74,6 @@
 #define BTTRC_ID_STK_SNEP                  52
 #define BTTRC_ID_STK_NDEF                  53
 
-
 /* LayerIDs for BTA */
 #define BTTRC_ID_BTA_ACC                   55         /* Advanced Camera Client */
 #define BTTRC_ID_BTA_AG                    56         /* audio gateway */
@@ -137,125 +118,10 @@
 #define BTTRC_ID_MAX_ID                    BTTRC_ID_BT_PROTOCOL
 // btla-specific --
 #define BTTRC_ID_ALL_LAYERS                0xFF       /* all trace layers */
-typedef UINT8 tBTTRC_LAYER_ID;
-
-/* Trace type definitions. Note that these are mutually exclusive in a trace. This
-means that any trace can be either error,warning,api,event or dbg */
-#define BTTRC_TYPE_ERROR                   0x01       /* Traces for error situation */
-#define BTTRC_TYPE_WARNING	               0x02       /* Traces for warning situation */
-#define BTTRC_TYPE_API                     0x04       /* Traces for API */
-#define BTTRC_TYPE_EVENT                   0x08       /* Traces for EVENT */
-#define BTTRC_TYPE_ACTION                  0x10       /* Traces for Action functions */
-#define BTTRC_TYPE_DBG                     0x20       /* Traces for debugging purpose */
-typedef UINT8 tBTTRC_TYPE;
-
-/* Masks to identify the stack that originated the trace */
-#define BTTRC_TRACE_LITE                   0x80       /* MM Lite stack */
-#define BTTRC_TRACE_EMBD                   0x40       /* Embedded host stack */
-
 /* Parameter datatypes used in Trace APIs */
 #define BTTRC_PARAM_UINT8                  1
 #define BTTRC_PARAM_UINT16                 2
 #define BTTRC_PARAM_UINT32                 3
-typedef UINT8 tBTTRC_PARAM_TYPE;
-
-/* Special token definitions */
-#define BTTRC_TOKEN_SM_STATE               0xFFFF     /* Token indicating the State of a State m/c */
-
-// btla-specific ++
-typedef struct {
-    tBTTRC_LAYER_ID layer_id;
-    tBTTRC_TYPE     type;      /* TODO: use tBTTRC_TYPE instead of "classical level 0-5" */
-} tBTTRC_LEVEL;
-
-typedef UINT8 (tBTTRC_SET_TRACE_LEVEL)( UINT8 );
-
-typedef struct {
-    const tBTTRC_LAYER_ID         layer_id_start;
-    const tBTTRC_LAYER_ID         layer_id_end;
-    tBTTRC_SET_TRACE_LEVEL        *p_f;
-    const char                    *trc_name;
-    UINT8                         trace_level;
-} tBTTRC_FUNC_MAP;
-
-extern tBTTRC_FUNC_MAP bttrc_set_level_map[];
-extern const UINT16 bttrc_map_size;
-extern BT_API tBTTRC_LEVEL * BTA_SysSetTraceLevel( tBTTRC_LEVEL * p_levels );
-// btla-specific --
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* External declaration for appl_trace_level here to avoid to add the declaration in all the files using APPL_TRACExxx macros */
-extern UINT8 appl_trace_level ;
-
-// btla-specific ++
-EXPORT_API extern void BTE_InitTraceLevels( void );
-// btla-specific --
-
-/* Prototype for message logging function. */
-EXPORT_API extern void LogMsg (UINT32 trace_set_mask, const char *fmt_str, ...);
-
-/* Prototype for stack tracing function. */
-EXPORT_API extern void BTTRC_StackTrace0(tBTTRC_LAYER_ID layer_id,
-                                   tBTTRC_TYPE type,
-                                   UINT16 token);
-EXPORT_API extern void BTTRC_StackTrace1(tBTTRC_LAYER_ID layer_id,
-                                   tBTTRC_TYPE type,
-                                   UINT16 token,
-                                   tBTTRC_PARAM_TYPE p1_type, UINT32 p1_val);
-EXPORT_API extern void BTTRC_StackTrace2(tBTTRC_LAYER_ID layer_id,
-                                   tBTTRC_TYPE type,
-                                   UINT16 token,
-                                   tBTTRC_PARAM_TYPE p1_type, UINT32 p1_val,
-                                   tBTTRC_PARAM_TYPE p2_type, UINT32 p2_val);
-EXPORT_API extern void BTTRC_StackTrace3(tBTTRC_LAYER_ID layer_id,
-                                   tBTTRC_TYPE type,
-                                   UINT16 token,
-                                   tBTTRC_PARAM_TYPE p1_type, UINT32 p1_val,
-                                   tBTTRC_PARAM_TYPE p2_type, UINT32 p2_val,
-                                   tBTTRC_PARAM_TYPE p3_type, UINT32 p3_val);
-EXPORT_API extern void BTTRC_StackTrace4(tBTTRC_LAYER_ID layer_id,
-                                   tBTTRC_TYPE type,
-                                   UINT16 token,
-                                   tBTTRC_PARAM_TYPE p1_type, UINT32 p1_val,
-                                   tBTTRC_PARAM_TYPE p2_type, UINT32 p2_val,
-                                   tBTTRC_PARAM_TYPE p3_type, UINT32 p3_val,
-                                   tBTTRC_PARAM_TYPE p4_type, UINT32 p4_val);
-EXPORT_API extern void BTTRC_StackTrace5(tBTTRC_LAYER_ID layer_id,
-                                   tBTTRC_TYPE type,
-                                   UINT16 token,
-                                   tBTTRC_PARAM_TYPE p1_type, UINT32 p1_val,
-                                   tBTTRC_PARAM_TYPE p2_type, UINT32 p2_val,
-                                   tBTTRC_PARAM_TYPE p3_type, UINT32 p3_val,
-                                   tBTTRC_PARAM_TYPE p4_type, UINT32 p4_val,
-                                   tBTTRC_PARAM_TYPE p5_type, UINT32 p5_val);
-EXPORT_API extern void BTTRC_StackTrace6(tBTTRC_LAYER_ID layer_id,
-                                   tBTTRC_TYPE type,
-                                   UINT16 token,
-                                   tBTTRC_PARAM_TYPE p1_type, UINT32 p1_val,
-                                   tBTTRC_PARAM_TYPE p2_type, UINT32 p2_val,
-                                   tBTTRC_PARAM_TYPE p3_type, UINT32 p3_val,
-                                   tBTTRC_PARAM_TYPE p4_type, UINT32 p4_val,
-                                   tBTTRC_PARAM_TYPE p5_type, UINT32 p5_val,
-                                   tBTTRC_PARAM_TYPE p6_type, UINT32 p6_val);
-
-// btla-specific ++
-/* p_levels must be a 0 terminated list ! */
-//EXPORT_API extern tBTTRC_LEVEL * BTA_SysSetTraceLevel( tBTTRC_LEVEL * p_levels );
-// btla-specific --
-
-#ifdef __cplusplus
-}
-#endif
-
-/******************************************************************************
-**
-** Trace configurable parameters
-**
-******************************************************************************/
 
 /* Enables or disables verbose trace information. */
 #ifndef BT_TRACE_VERBOSE
@@ -267,7 +133,6 @@
 #define BT_USE_TRACES       TRUE
 #endif
 
-
 /******************************************************************************
 **
 ** Trace Levels
@@ -356,176 +221,6 @@
 #endif
 // btla-specific --
 
-
-#if (BTTRC_INCLUDED == TRUE)
-/***************************************************************************************/
-/* BTTRC MACROS */
-
-#define BTTRC_EVENT(lid, event, state)   \
-            {BTTRC_StackTrace1(lid, BTTRC_TYPE_EVENT, event, BTTRC_PARAM_UINT8, state);}
-#define BTTRC_ACTION(lid, action)  \
-            {BTTRC_StackTrace0(lid, BTTRC_TYPE_ACTION, action);}
-#define BTTRC_STATE(lid, state)   \
-            {BTTRC_StackTrace1(lid, BTTRC_TYPE_EVENT, BTTRC_TOKEN_SM_STATE, BTTRC_PARAM_UINT8, state);}
-
-#define BTTRC_API0(lid, api)  \
-            {BTTRC_StackTrace0(lid, BTTRC_TYPE_API, api);}
-#define BTTRC_API1(lid, api, p1_t,p1_v)  \
-            {BTTRC_StackTrace1(lid, BTTRC_TYPE_API, api, p1_t,p1_v);}
-#define BTTRC_API2(lid, api, p1_t,p1_v,p2_t,p2_v)  \
-            {BTTRC_StackTrace2(lid, BTTRC_TYPE_API, api, p1_t,p1_v,p2_t,p2_v);}
-#define BTTRC_API3(lid, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v)  \
-            {BTTRC_StackTrace3(lid, BTTRC_TYPE_API, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v);}
-#define BTTRC_API4(lid, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v)  \
-            {BTTRC_StackTrace4(lid, BTTRC_TYPE_API, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v);}
-#define BTTRC_API5(lid, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v)  \
-            {BTTRC_StackTrace5(lid, BTTRC_TYPE_API, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v);}
-#define BTTRC_API6(lid, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v)  \
-            {BTTRC_StackTrace6(lid, BTTRC_TYPE_API, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v);}
-
-
-#define BTTRC_DBG0(lid, dbg)  \
-            {BTTRC_StackTrace0(lid, BTTRC_TYPE_DBG, dbg);}
-#define BTTRC_DBG1(lid, dbg, p1_t,p1_v)  \
-            {BTTRC_StackTrace1(lid, BTTRC_TYPE_DBG, dbg, p1_t,p1_v);}
-#define BTTRC_DBG2(lid, dbg, p1_t,p1_v,p2_t,p2_v)  \
-            {BTTRC_StackTrace2(lid, BTTRC_TYPE_DBG, dbg, p1_t,p1_v,p2_t,p2_v);}
-#define BTTRC_DBG3(lid, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v)  \
-            {BTTRC_StackTrace3(lid, BTTRC_TYPE_DBG, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v);}
-#define BTTRC_DBG4(lid, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v)  \
-            {BTTRC_StackTrace4(lid, BTTRC_TYPE_DBG, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v);}
-#define BTTRC_DBG5(lid, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v)  \
-            {BTTRC_StackTrace5(lid, BTTRC_TYPE_DBG, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v);}
-#define BTTRC_DBG6(lid, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v)  \
-            {BTTRC_StackTrace6(lid, BTTRC_TYPE_DBG, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v);}
-
-/***************************************************************************************/
-/*AVDT MACROS */
-
-#define BTTRC_AVDT_API0(api)   \
-        BTTRC_API0(BTTRC_ID_STK_AVDT, api)
-#define BTTRC_AVDT_API1(api, p1_t, p1_v) \
-        BTTRC_API1(BTTRC_ID_STK_AVDT, api, p1_t, p1_v)
-#define BTTRC_AVDT_API2(api, p1_t, p1_v, p2_t, p2_v) \
-        BTTRC_API2(BTTRC_ID_STK_AVDT, api, p1_t, p1_v, p2_t, p2_v)
-/***************************************************************************************/
-/*AVDT_SCB MACROS */
-
-#define BTTRC_AVDT_SCB_EVENT(event, state)   \
-            BTTRC_EVENT(BTTRC_ID_AVDT_SCB, event, state)
-#define BTTRC_AVDT_SCB_ACTION(action)  \
-            BTTRC_ACTION(BTTRC_ID_AVDT_SCB, action)
-#define BTTRC_AVDT_SCB_STATE(next_state)   \
-            BTTRC_STATE(BTTRC_ID_AVDT_SCB, next_state)
-
-#define BTTRC_AVDT_SCB_DBG0(dbg)  \
-            BTTRC_DBG0(BTTRC_ID_AVDT_SCB, dbg)
-#define BTTRC_AVDT_SCB_DBG1(dbg, p1_t,p1_v)  \
-            BTTRC_DBG1(BTTRC_ID_AVDT_SCB, dbg, p1_t,p1_v)
-#define BTTRC_AVDT_SCB_DBG2(dbg, p1_t,p1_v,p2_t,p2_v)  \
-            BTTRC_DBG2(BTTRC_ID_AVDT_SCB, dbg, p1_t,p1_v,p2_t,p2_v)
-#define BTTRC_AVDT_SCB_DBG3(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v)  \
-            BTTRC_DBG3(BTTRC_ID_AVDT_SCB, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v)
-#define BTTRC_AVDT_SCB_DBG4(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v)  \
-            BTTRC_DBG4(BTTRC_ID_AVDT_SCB, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v)
-#define BTTRC_AVDT_SCB_DBG5(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v)  \
-            BTTRC_DBG5(BTTRC_ID_AVDT_SCB, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v)
-#define BTTRC_AVDT_SCB_DBG6(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v)  \
-            BTTRC_DBG6(BTTRC_ID_AVDT_SCB, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v)
-/***************************************************************************************/
-/*AVDT_CCB MACROS */
-
-#define BTTRC_AVDT_CCB_EVENT(event, state)   \
-            BTTRC_EVENT(BTTRC_ID_AVDT_CCB, event, state)
-#define BTTRC_AVDT_CCB_ACTION(action)  \
-            BTTRC_ACTION(BTTRC_ID_AVDT_CCB, action)
-#define BTTRC_AVDT_CCB_STATE(next_state)   \
-            BTTRC_STATE(BTTRC_ID_AVDT_CCB, next_state)
-
-#define BTTRC_AVDT_CCB_DBG0(dbg)  \
-            BTTRC_DBG0(BTTRC_ID_AVDT_CCB, dbg)
-#define BTTRC_AVDT_CCB_DBG1(dbg, p1_t,p1_v)  \
-            BTTRC_DBG1(BTTRC_ID_AVDT_CCB, dbg, p1_t,p1_v)
-#define BTTRC_AVDT_CCB_DBG2(dbg, p1_t,p1_v,p2_t,p2_v)  \
-            BTTRC_DBG2(BTTRC_ID_AVDT_CCB, dbg, p1_t,p1_v,p2_t,p2_v)
-#define BTTRC_AVDT_CCB_DBG3(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v)  \
-            BTTRC_DBG3(BTTRC_ID_AVDT_CCB, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v)
-#define BTTRC_AVDT_CCB_DBG4(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v)  \
-            BTTRC_DBG4(BTTRC_ID_AVDT_CCB, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v)
-#define BTTRC_AVDT_CCB_DBG5(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v)  \
-            BTTRC_DBG5(BTTRC_ID_AVDT_CCB, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v)
-#define BTTRC_AVDT_CCB_DBG6(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v)  \
-            BTTRC_DBG6(BTTRC_ID_AVDT_CCB, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v)
-/***************************************************************************************/
-
-#else /*BTTRC_INCLUDED*/
-
-/***************************************************************************************/
-/* BTTRC MACROS */
-
-#define BTTRC_EVENT(lid, event, state)
-#define BTTRC_ACTION(lid, action)
-#define BTTRC_STATE(lid, state)
-
-#define BTTRC_API0(lid, api)
-#define BTTRC_API1(lid, api, p1_t, p1_v)
-#define BTTRC_API2(lid, api, p1_t, p1_v, p2_t, p2_v)
-#define BTTRC_API3(lid, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v)
-#define BTTRC_API4(lid, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v)
-#define BTTRC_API5(lid, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v)
-#define BTTRC_API6(lid, api, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v)
-
-
-#define BTTRC_DBG0(lid, dbg)
-#define BTTRC_DBG1(lid, dbg, p1_t,p1_v)
-#define BTTRC_DBG2(lid, dbg, p1_t,p1_v,p2_t,p2_v)
-#define BTTRC_DBG3(lid, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v)
-#define BTTRC_DBG4(lid, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v)
-#define BTTRC_DBG5(lid, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v)
-#define BTTRC_DBG6(lid, dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v)
-
-/***************************************************************************************/
-/*AVDT MACROS */
-#define BTTRC_AVDT_API0(api)
-#define BTTRC_AVDT_API1(api, p1_t,p1_v)
-#define BTTRC_AVDT_API2(api, p1_t,p1_v,p2_t,p2_v)
-/***************************************************************************************/
-/*AVDT_SCB MACROS */
-
-#define BTTRC_AVDT_SCB_EVENT(event, state)
-#define BTTRC_AVDT_SCB_ACTION(action)
-#define BTTRC_AVDT_SCB_STATE(next_state)
-
-#define BTTRC_AVDT_SCB_DBG0(dbg)
-#define BTTRC_AVDT_SCB_DBG1(dbg, p1_t,p1_v)
-#define BTTRC_AVDT_SCB_DBG2(dbg, p1_t,p1_v,p2_t,p2_v)
-#define BTTRC_AVDT_SCB_DBG3(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v)
-#define BTTRC_AVDT_SCB_DBG4(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v)
-#define BTTRC_AVDT_SCB_DBG5(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v)
-#define BTTRC_AVDT_SCB_DBG6(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v)
-
-/***************************************************************************************/
-/*AVDT_CCB MACROS */
-
-#define BTTRC_AVDT_CCB_EVENT(event, state)
-#define BTTRC_AVDT_CCB_ACTION(action)
-#define BTTRC_AVDT_CCB_STATE(next_state)
-
-#define BTTRC_AVDT_CCB_DBG0(dbg)
-#define BTTRC_AVDT_CCB_DBG1(dbg, p1_t,p1_v)
-#define BTTRC_AVDT_CCB_DBG2(dbg, p1_t,p1_v,p2_t,p2_v)
-#define BTTRC_AVDT_CCB_DBG3(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v)
-#define BTTRC_AVDT_CCB_DBG4(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v)
-#define BTTRC_AVDT_CCB_DBG5(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v)
-#define BTTRC_AVDT_CCB_DBG6(dbg, p1_t,p1_v,p2_t,p2_v,p3_t,p3_v,p4_t,p4_v,p5_t,p5_v,p6_t,p6_v)
-
-/***************************************************************************************/
-
-#endif /*BTTRC_INCLUDED*/
-
-
-#if (BT_USE_TRACES == TRUE)
-
 #define BT_TRACE(l,t,...)                        LogMsg((TRACE_CTRL_GENERAL | (l) | TRACE_ORG_STACK | (t)), ##__VA_ARGS__)
 #define BT_ERROR_TRACE(l,...)                    LogMsg(TRACE_CTRL_GENERAL | (l) | TRACE_ORG_STACK | TRACE_TYPE_ERROR, ##__VA_ARGS__)
 
@@ -656,142 +351,6 @@
 #define SMP_TRACE_EVENT(...)                     {if (smp_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_TRACE(TRACE_LAYER_SMP, TRACE_TYPE_EVENT, ##__VA_ARGS__);}
 #define SMP_TRACE_DEBUG(...)                     {if (smp_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_TRACE(TRACE_LAYER_SMP, TRACE_TYPE_DEBUG, ##__VA_ARGS__);}
 
-/* END OF USE TRACES */
-#else
-
-#define BT_TRACE(l,t,...)
-#define BT_BT_ERROR_TRACE(l,...)
-
-/* Define tracing for the HCI unit
-*/
-#define HCI_TRACE_ERROR(...)
-#define HCI_TRACE_WARNING(...)
-#define HCI_TRACE_EVENT(...)
-#define HCI_TRACE_DEBUG(...)
-
-
-/* Define tracing for BTM
-*/
-#define BTM_TRACE_ERROR(...)
-#define BTM_TRACE_WARNING(...)
-#define BTM_TRACE_API(...)
-#define BTM_TRACE_EVENT(...)
-#define BTM_TRACE_DEBUG(...)
-
-
-/* Define tracing for the L2CAP unit
-*/
-#define L2CAP_TRACE_ERROR(...)
-#define L2CAP_TRACE_WARNING(...)
-#define L2CAP_TRACE_API(...)
-#define L2CAP_TRACE_EVENT(...)
-#define L2CAP_TRACE_DEBUG(...)
-
-/* Define tracing for the SDP unit
-*/
-#define SDP_TRACE_ERROR(...)
-#define SDP_TRACE_WARNING(...)
-#define SDP_TRACE_API(...)
-#define SDP_TRACE_EVENT(...)
-#define SDP_TRACE_DEBUG(...)
-
-/* Define tracing for the RFCOMM unit
-*/
-#define RFCOMM_TRACE_ERROR(...)
-#define RFCOMM_TRACE_WARNING(...)
-#define RFCOMM_TRACE_API(...)
-#define RFCOMM_TRACE_EVENT(...)
-#define RFCOMM_TRACE_DEBUG(...)
-
-/* Generic Access Profile traces */
-#define GAP_TRACE_ERROR(...)
-#define GAP_TRACE_EVENT(...)
-#define GAP_TRACE_API(...)
-#define GAP_TRACE_WARNING(...)
-
-/* define traces for HID Host */
-#define HIDH_TRACE_ERROR(...)
-#define HIDH_TRACE_WARNING(...)
-#define HIDH_TRACE_API(...)
-#define HIDH_TRACE_EVENT(...)
-#define HIDH_TRACE_DEBUG(...)
-
-/* define traces for BNEP */
-
-#define BNEP_TRACE_ERROR(...)
-#define BNEP_TRACE_WARNING(...)
-#define BNEP_TRACE_API(...)
-#define BNEP_TRACE_EVENT(...)
-#define BNEP_TRACE_DEBUG(...)
-
-/* define traces for PAN */
-
-#define PAN_TRACE_ERROR(...)
-#define PAN_TRACE_WARNING(...)
-#define PAN_TRACE_API(...)
-#define PAN_TRACE_EVENT(...)
-#define PAN_TRACE_DEBUG(...)
-
-/* Define tracing for the A2DP profile
-*/
-#define A2D_TRACE_ERROR(...)
-#define A2D_TRACE_WARNING(...)
-#define A2D_TRACE_EVENT(...)
-#define A2D_TRACE_DEBUG(...)
-#define A2D_TRACE_API(...)
-
-/* AVDTP
-*/
-#define AVDT_TRACE_ERROR(...)
-#define AVDT_TRACE_WARNING(...)
-#define AVDT_TRACE_EVENT(...)
-#define AVDT_TRACE_DEBUG(...)
-#define AVDT_TRACE_API(...)
-
-/* Define tracing for the AVCTP protocol
-*/
-#define AVCT_TRACE_ERROR(...)
-#define AVCT_TRACE_WARNING(...)
-#define AVCT_TRACE_EVENT(...)
-#define AVCT_TRACE_DEBUG(...)
-#define AVCT_TRACE_API(...)
-
-/* Define tracing for the AVRCP profile
-*/
-#define AVRC_TRACE_ERROR(...)
-#define AVRC_TRACE_WARNING(...)
-#define AVRC_TRACE_EVENT(...)
-#define AVRC_TRACE_DEBUG(...)
-#define AVRC_TRACE_API(...)
-
-/* MCAP
-*/
-#define MCA_TRACE_ERROR(...)
-#define MCA_TRACE_WARNING(...)
-#define MCA_TRACE_EVENT(...)
-#define MCA_TRACE_DEBUG(...)
-#define MCA_TRACE_API(...)
-
-/* Define tracing for the GATT
-*/
-#define GATT_TRACE_ERROR(...)
-#define GATT_TRACE_WARNING(...)
-#define GATT_TRACE_API(...)
-#define GATT_TRACE_EVENT(...)
-#define GATT_TRACE_DEBUG(...)
-
-/* Define tracing for the SMP unit
-*/
-#define SMP_TRACE_ERROR(...)
-#define SMP_TRACE_WARNING(...)
-#define SMP_TRACE_API(...)
-#define SMP_TRACE_EVENT(...)
-#define SMP_TRACE_DEBUG(...)
-
-#endif
-
-#if (BT_TRACE_BTIF == TRUE)
-
 extern UINT8 btif_trace_level;
 
 /* define traces for application */
@@ -802,21 +361,6 @@
 #define BTIF_TRACE_DEBUG(...)                    {if (btif_trace_level >= BT_TRACE_LEVEL_DEBUG) LogMsg(TRACE_CTRL_GENERAL | TRACE_LAYER_NONE | TRACE_ORG_APPL | TRACE_TYPE_DEBUG, ##__VA_ARGS__);}
 #define BTIF_TRACE_VERBOSE(...)                  {if (btif_trace_level >= BT_TRACE_LEVEL_VERBOSE) LogMsg(TRACE_CTRL_GENERAL | TRACE_LAYER_NONE | TRACE_ORG_APPL | TRACE_TYPE_DEBUG, ##__VA_ARGS__);}
 
-#else
-/* define traces for Application */
-
-#define BTIF_TRACE_ERROR(...)
-#define BTIF_TRACE_WARNING(...)
-#define BTIF_TRACE_API(...)
-#define BTIF_TRACE_EVENT(...)
-#define BTIF_TRACE_DEBUG(...)
-#define BTIF_TRACE_VERBOSE(...)
-
-#endif
-
-
-#if (BT_USE_TRACES == TRUE || BT_TRACE_APPL == TRUE)
-
 /* define traces for application */
 #define APPL_TRACE_ERROR(...)                    {if (appl_trace_level >= BT_TRACE_LEVEL_ERROR) LogMsg(TRACE_CTRL_GENERAL | TRACE_LAYER_NONE | TRACE_ORG_APPL | TRACE_TYPE_ERROR, ##__VA_ARGS__);}
 #define APPL_TRACE_WARNING(...)                  {if (appl_trace_level >= BT_TRACE_LEVEL_WARNING) LogMsg(TRACE_CTRL_GENERAL | TRACE_LAYER_NONE | TRACE_ORG_APPL | TRACE_TYPE_WARNING, ##__VA_ARGS__);}
@@ -825,21 +369,8 @@
 #define APPL_TRACE_DEBUG(...)                    {if (appl_trace_level >= BT_TRACE_LEVEL_DEBUG) LogMsg(TRACE_CTRL_GENERAL | TRACE_LAYER_NONE | TRACE_ORG_APPL | TRACE_TYPE_DEBUG, ##__VA_ARGS__);}
 #define APPL_TRACE_VERBOSE(...)                  {if (appl_trace_level >= BT_TRACE_LEVEL_VERBOSE) LogMsg(TRACE_CTRL_GENERAL | TRACE_LAYER_NONE | TRACE_ORG_APPL | TRACE_TYPE_DEBUG, ##__VA_ARGS__);}
 
-#else
-/* define traces for Application */
-
-#define APPL_TRACE_ERROR(...)
-#define APPL_TRACE_WARNING(...)
-#define APPL_TRACE_API(...)
-#define APPL_TRACE_EVENT(...)
-#define APPL_TRACE_DEBUG(...)
-#define APPL_TRACE_VERBOSE(...)
-
-#endif
-
 /* Simplified Trace Helper Macro
 */
-#if (BT_USE_TRACES == TRUE)
 #define bdld(fmt, ...) \
     do{\
         if((MY_LOG_LEVEL) >= BT_TRACE_LEVEL_DEBUG) \
@@ -863,10 +394,25 @@
         if(((MY_LOG_LEVEL) >= BT_TRACE_LEVEL_ERROR) && !(assert_if)) \
             LogMsg((MY_LOG_LAYER) | TRACE_TYPE_ERROR, "%s(L%d): assert failed: " #assert_if, __FUNCTION__, __LINE__); \
     }while(0)
-#else
-#define bdld(fmt, ...)  ((void)0) /*Empty statement as placeholder*/
-#define bdlw(fmt, ...)  ((void)0)
-#define bdle(fmt, ...)  ((void)0)
-#define bdla(assert_if) ((void)0)
-#endif
-#endif /* BT_TRACE_H */
+
+typedef UINT8 tBTTRC_PARAM_TYPE;
+typedef UINT8 tBTTRC_LAYER_ID;
+typedef UINT8 tBTTRC_TYPE;
+
+typedef struct {
+    tBTTRC_LAYER_ID layer_id;
+    tBTTRC_TYPE     type;      /* TODO: use tBTTRC_TYPE instead of "classical level 0-5" */
+} tBTTRC_LEVEL;
+
+typedef UINT8 (tBTTRC_SET_TRACE_LEVEL)( UINT8 );
+
+typedef struct {
+    const tBTTRC_LAYER_ID         layer_id_start;
+    const tBTTRC_LAYER_ID         layer_id_end;
+    tBTTRC_SET_TRACE_LEVEL        *p_f;
+    const char                    *trc_name;
+    UINT8                         trace_level;
+} tBTTRC_FUNC_MAP;
+
+/* External declaration for appl_trace_level here to avoid to add the declaration in all the files using APPL_TRACExxx macros */
+extern UINT8 appl_trace_level;
diff --git a/include/bte_appl.h b/include/bte_appl.h
index cf0baed..4850250 100644
--- a/include/bte_appl.h
+++ b/include/bte_appl.h
@@ -22,52 +22,7 @@
  *
  ******************************************************************************/
 
-#ifndef BTE_APPL_H
-#define BTE_APPL_H
-
-#include "btm_int.h"
-#include "bta_api.h"
-#include "bta_sys.h"
-#include "bte.h"
-
-/* Maximum length for serial port device name */
-#ifndef BTE_APPL_MAX_USERIAL_DEV_NAME
-#define BTE_APPL_MAX_USERIAL_DEV_NAME       (256)
-#endif
-#ifndef BTAPP_AHF_API_SUPPORT
-#define BTAPP_AHF_API_SUPPORT FALSE
-#endif
-
-/* BTA APP_IDs */
-#define UI_DM_ID    1
-#define UI_PRM_ID   20
-/* this defines the enabled BTA modules. client may not be defined as those are enabled at run time.
- * they are defined for completeness. please check with bta_sys.h for new modules.
- * BTA_ID_DM serves as flag for BTA_EnableBluetooth()
- * BTA_ID_RES can be used to fs ID in bte_appl.
- */
-
-#define BTAPP_NUM_ID_BLOCKS ((BTA_ID_MAX/32)+1)        /* number of 32 bit required to store one bit per
-                                                            btapp id */
-
-#define BTAPP_APPL_MAIL_EVENT(x)  (x<<8)    /* define bte_appl task mail box event. LSB contains
-                                                BTA_ID_xxx (see bta_sys.h) */
-#define BTAPP_APPL_MAIL_EVT       0xff00    /* high byte contains bitmap of application module event */
-
-/* helper macro to copy BTA callack data y into message buffer x, for event data structure z */
-#define MEMCPY_APPL_MSG(x, y, z)  memcpy( (void *)(((UINT8 *)x)+sizeof(BT_HDR)), (void *)y, sizeof(z) )
-
-/* Event masks for BTE_APPL_TASK */
-#define BTE_APPL_STARTUP_EVT    EVENT_MASK(APPL_EVT_0)      /* Bluetooth has started */
-#define BTE_APPL_SHUTDOWN_EVT   EVENT_MASK(APPL_EVT_1)      /* Bluetooth is shutting down */
-#define BTE_APPL_SOCKET_RX_EVT  EVENT_MASK(APPL_EVT_2)      /* Socket data ready to be read */
-#define BTE_APPL_DBUS_RX_EVT    EVENT_MASK(APPL_EVT_3)      /* DBUS message ready to be read */
-#define BTE_APPL_BTA_ENABLE_EVT EVENT_MASK(APPL_EVT_4)      /* BTA Enabled event */
-
-
-/* Application configuration */
-#define BTE_APPL_PATCHRAM_PATH_MAXLEN   128
-#define BTE_APPL_CONTACTS_DB_PATH       256
+#pragma once
 
 typedef struct {
 #if ((BLE_INCLUDED == TRUE) && (SMP_INCLUDED == TRUE))
@@ -80,101 +35,3 @@
 } tBTE_APPL_CFG;
 
 extern tBTE_APPL_CFG bte_appl_cfg;
-
-typedef struct {
-    pthread_mutex_t     mutex;  /* mutex to protect below signal condition */
-    pthread_cond_t      cond;   /* signal event */
-} tBTAPP_SEMAPHORE;
-
-/* helper functions to handle pthread conditions event from outside GKI */
-extern void bte_create_semaphore( tBTAPP_SEMAPHORE * p_sema );
-extern void bte_wait_semaphore( tBTAPP_SEMAPHORE * p_sema, unsigned msecs_to );
-extern void bte_signal_semaphore( tBTAPP_SEMAPHORE * p_sema );
-extern void bte_destroy_semaphore( tBTAPP_SEMAPHORE * p_sema );
-
-/* global application control block storing global application states and variables */
-typedef struct tBTE_APPL_CB_tag {
-    sigset_t            signal_handler_set;        /* signal handler set used by signal handler thread */
-#if ( TRUE == BTE_RESET_BAUD_ON_BT_DISABLE )
-    tBTAPP_SEMAPHORE    shutdown_semaphore;   /* used to sync with  terminate handler initated ops */
-#endif
-    BOOLEAN amp_enabled;                        /* TRUE if AMP is in use */
-} tBTE_APPL_CB;
-
-extern tBTE_APPL_CB bte_appl_cb;
-
-/* Exports the application task */
-extern void BTE_appl_task(UINT32 params);
-extern int BTAPP_enable_bta( const UINT32 bta_module_state[BTAPP_NUM_ID_BLOCKS], int includingFM );
-extern int BTAPP_disable_bta( const UINT32 bta_module_state[BTAPP_NUM_ID_BLOCKS], int includingFM );
-
-extern UINT8 appl_trace_level;
-#define BT_PCM_CLK_IDX 1
-#ifndef BT_PCM_DEF_CLK
-#define BT_PCM_DEF_CLK 4       /* defaults to 2048khz PCM clk */
-#endif
-#define BT_PCM_SYNC_MS_ROLE_IDX 3
-#define BT_PCM_CLK_MS_ROLE_IDX  4
-#ifndef BT_PCM_DEF_ROLE
-#define BT_PCM_DEF_ROLE    0x00     /* assume slave as default */
-#endif
-
-/* helper macros to set, clear and get current BTA module id in a 32bit ARRAY!! */
-/* set bit id to 1 in UINT32 a[] NO RANGE CHECK!*/
-#define BTAPP_SET_BTA_MOD(id, a)    { a[id/32] |= (UINT32)(1<<(id % 32)); }
-
-/* set bit id to 0 (cleared) in UINT32 a[] NO RANGE CHECK */
-#define BTAPP_CLEAR_BTA_MOD(id, a)  { a[id/32] &= (UINT32)!(1<<(id % 32)); }
-
-/* tests if bit id is 1 in UINT32 a[] NO RANGE CHECK */
-#define BTAPP_BTA_MOD_IS_SET(id, a) (a[id/32] & (UINT32)(1<<(id % 32)))
-
-/* update this list either via btld.txt or directly here by adding the new profiles as per bta_sys.h.
- * each xxx_LISTx may only contain 32 bits */
-#ifndef BTAPP_BTA_MODULES_LIST0
-#define BTAPP_BTA_MODULES_LIST0 (\
-        ( 1<<BTA_ID_DM ) | \
-        ( 1<<BTA_ID_DG ) | \
-        ( 1<<BTA_ID_AG ) | \
-        ( 1<<BTA_ID_OPC )| \
-        ( 1<<BTA_ID_OPS )| \
-        ( 1<<BTA_ID_FTS )| \
-        ( 1<<BTA_ID_PAN )| \
-        ( 1<<BTA_ID_PR ) | \
-        ( 1<<BTA_ID_SC)  | \
-        ( 1<<BTA_ID_AV ) | \
-        ( 1<<BTA_ID_HH ) | \
-        ( 1<<BTA_ID_PBS) | \
-        ( 1<<BTA_ID_FMTX)| \
-        ( 1<<BTA_ID_JV) | \
-        ( 1<<BTA_ID_MSE) \
-        )
-#endif
-
-#define BTAPP_LIST1_BLOCK 32    /* next 32 bit block */
-#ifndef BTAPP_BTA_MODULES_LIST1
-#define BTAPP_BTA_MODULES_LIST1 (\
-        ( 1<<(BTA_ID_MAX-BTAPP_LIST1_BLOCK) ) | \
-        ( 1<<(BTA_ID_MSE-BTAPP_LIST1_BLOCK) ) | \
-        0 \
-        )
-#endif
-/* for future GPS etc support. goes int LIST1 above */
-#if 0
-    ( 1<<(BTA_ID_SSR-BTAPP_LIST1_BLOCK) ) \
-    ( 1<<(BTA_ID_MSE-BTAPP_LIST1_BLOCK) ) \
-    ( 1<<(BTA_ID_MCE-BTAPP_LIST1_BLOCK) )
-#endif
-
-/* used application init default in bte_main.c, bte_appl_cfg */
-#ifndef BTAPP_DEFAULT_MODULES
-#if (1==BTAPP_NUM_ID_BLOCKS)
-#define BTAPP_DEFAULT_MODULES {BTAPP_BTA_MODULES_LIST0} /* max 32 modules IDs */
-#elif (2==BTAPP_NUM_ID_BLOCKS)
-#define BTAPP_DEFAULT_MODULES {BTAPP_BTA_MODULES_LIST0, BTAPP_BTA_MODULES_LIST1} /* 64 module IDs max */
-#else
-#error "Define more BTAPP_BTA_MODULES_LISTx"
-#endif
-#endif
-
-#endif  /* BTE_APPL_H */
diff --git a/include/gki_target.h b/include/gki_target.h
index d71c268..1d35c25 100644
--- a/include/gki_target.h
+++ b/include/gki_target.h
@@ -15,119 +15,8 @@
  *  limitations under the License.
  *
  ******************************************************************************/
-#ifndef GKI_TARGET_H
-#define GKI_TARGET_H
 
-/* Operating System Selection */
-#ifndef BTE_SIM_APP
-#define _GKI_ARM
-#define _GKI_STANDALONE
-#else
-#define _BT_WIN32
-#endif
-
-/* define prefix for exporting APIs from libraries */
-#define EXPORT_API
-
-#ifndef BTE_BSE_WRAPPER
-#ifdef  BTE_SIM_APP
-#undef  EXPORT_API
-#define EXPORT_API  __declspec(dllexport)
-#endif
-#endif
-
-#define GKI_API EXPORT_API
-#define UDRV_API EXPORT_API
-
-#ifndef GKI_DEBUG
-#define GKI_DEBUG FALSE
-#endif
-
-
-#if defined (GKI_DEBUG) && (GKI_DEBUG == TRUE)
-#define GKI_TRACE(fmt, ...)     ALOGI ("%s: " fmt, __FUNCTION__, ## __VA_ARGS__)
-#else
-#define GKI_TRACE(fmt, ...)
-#endif
-
-/******************************************************************************
-**
-** Task configuration
-**
-******************************************************************************/
-
-/* Definitions of task IDs for inter-task messaging */
-#ifndef BTU_TASK
-#define BTU_TASK                0
-#endif
-
-#ifndef BTIF_TASK
-#define BTIF_TASK               1
-#endif
-
-#ifndef A2DP_MEDIA_TASK
-#define A2DP_MEDIA_TASK         2
-#endif
-
-/* The number of GKI tasks in the software system. */
-#ifndef GKI_MAX_TASKS
-#define GKI_MAX_TASKS               3
-#endif
-
-/******************************************************************************
-**
-** Timer configuration
-**
-******************************************************************************/
-
-/* The number of GKI timers in the software system. */
-#ifndef GKI_NUM_TIMERS
-#define GKI_NUM_TIMERS              4
-#endif
-
-/* A conversion value for translating ticks to calculate GKI timer.  */
-#ifndef TICKS_PER_SEC
-#define TICKS_PER_SEC               100
-#endif
-
-/************************************************************************
-**  Utility macros converting ticks to time with user define OS ticks per sec
-**/
-#ifndef GKI_MS_TO_TICKS
-#define GKI_MS_TO_TICKS(x)   ((x) / (1000 / TICKS_PER_SEC))
-#endif
-
-#ifndef GKI_SECS_TO_TICKS
-#define GKI_SECS_TO_TICKS(x)   ((x) * (TICKS_PER_SEC))
-#endif
-
-#ifndef GKI_TICKS_TO_MS
-#define GKI_TICKS_TO_MS(x)   ((x) * 1000 / TICKS_PER_SEC)
-#endif
-
-#ifndef GKI_TICKS_TO_SECS
-#define GKI_TICKS_TO_SECS(x)   ((x) / TICKS_PER_SEC)
-#endif
-
-
-
-/* TICK per second from OS (OS dependent change this macro accordingly to various OS) */
-#ifndef OS_TICKS_PER_SEC
-#define OS_TICKS_PER_SEC               1000
-#endif
-
-/************************************************************************
-**  Utility macros converting ticks to time with user define OS ticks per sec
-**/
-
-#ifndef GKI_OS_TICKS_TO_MS
-#define GKI_OS_TICKS_TO_MS(x)   ((x) * 1000 / OS_TICKS_PER_SEC)
-#endif
-
-
-#ifndef GKI_OS_TICKS_TO_SECS
-#define GKI_OS_TICKS_TO_SECS(x)   ((x) / OS_TICKS_PER_SEC))
-#endif
+#pragma once
 
 /******************************************************************************
 **
@@ -135,11 +24,6 @@
 **
 ******************************************************************************/
 
-/* TRUE if GKI uses dynamic buffers. */
-#ifndef GKI_USE_DYNAMIC_BUFFERS
-#define GKI_USE_DYNAMIC_BUFFERS     FALSE
-#endif
-
 /* The size of the buffers in pool 0. */
 #ifndef GKI_BUF0_SIZE
 #define GKI_BUF0_SIZE               64
@@ -147,7 +31,7 @@
 
 /* The number of buffers in buffer pool 0. */
 #ifndef GKI_BUF0_MAX
-#define GKI_BUF0_MAX                48
+#define GKI_BUF0_MAX                96
 #endif
 
 /* The ID of buffer pool 0. */
@@ -162,7 +46,7 @@
 
 /* The number of buffers in buffer pool 1. */
 #ifndef GKI_BUF1_MAX
-#define GKI_BUF1_MAX                26
+#define GKI_BUF1_MAX                52
 #endif
 
 /* The ID of buffer pool 1. */
@@ -177,7 +61,7 @@
 
 /* The number of buffers in buffer pool 2. */
 #ifndef GKI_BUF2_MAX
-#define GKI_BUF2_MAX                45
+#define GKI_BUF2_MAX                90
 #endif
 
 /* The ID of buffer pool 2. */
@@ -192,7 +76,7 @@
 
 /* The number of buffers in buffer pool 3. */
 #ifndef GKI_BUF3_MAX
-#define GKI_BUF3_MAX                200
+#define GKI_BUF3_MAX                400
 #endif
 
 /* The ID of buffer pool 3. */
@@ -210,13 +94,7 @@
 #define GKI_MAX_BUF_SIZE_POOL_ID    GKI_POOL_ID_3
 #endif
 
-/* RESERVED buffer pool for OBX */
-/* Ideally there should be 1 buffer for each instance for RX data, and some number
-of TX buffers based on active instances. OBX will only use these if packet size
-requires it. In most cases the large packets are used in only one direction so
-the other direction will use smaller buffers.
-Devices with small amount of RAM should limit the number of active obex objects.
-*/
+/* Pool 4 is unused */
 /* The size of the buffers in pool 4. */
 #ifndef GKI_BUF4_SIZE
 #define GKI_BUF4_SIZE               (8080+26)
@@ -224,7 +102,7 @@
 
 /* The number of buffers in buffer pool 4. */
 #ifndef GKI_BUF4_MAX
-#define GKI_BUF4_MAX                (OBX_NUM_SERVERS + OBX_NUM_CLIENTS)
+#define GKI_BUF4_MAX                0
 #endif
 
 /* The ID of buffer pool 4. */
@@ -239,7 +117,6 @@
 If BLE_INCLUDED is FALSE then Pool ID 8 is uncessary and set the following to 8, otherwise set to 9
 POOL_ID 9 is a public pool meant for large buffer needs such as SDP_DB
 */
-// btla-specific ++
 #ifndef GKI_NUM_FIXED_BUF_POOLS
 #define GKI_NUM_FIXED_BUF_POOLS     10
 #endif
@@ -249,12 +126,6 @@
 /* Setting POOL_ID 9 as a public pool meant for large buffers such as SDP_DB */
 #define GKI_DEF_BUFPOOL_PERM_MASK   0xfdf0
 #endif
-// btla-specific --
-
-/* The number of fixed and dynamic buffer pools */
-#ifndef GKI_NUM_TOTAL_BUF_POOLS
-#define GKI_NUM_TOTAL_BUF_POOLS     10
-#endif
 
 /* The following is intended to be a reserved pool for L2CAP
 Flow control and retransmissions and intentionally kept out
@@ -280,31 +151,6 @@
 #define GKI_BUF5_SIZE               748
 #endif
 
-/* The buffer corruption check flag. */
-#ifndef GKI_ENABLE_BUF_CORRUPTION_CHECK
-#define GKI_ENABLE_BUF_CORRUPTION_CHECK TRUE
-#endif
-
-/* The GKI severe error macro. */
-#ifndef GKI_SEVERE
-#define GKI_SEVERE(code)
-#endif
-
-/* TRUE if GKI includes debug functionality. */
-#ifndef GKI_DEBUG
-#define GKI_DEBUG                   FALSE
-#endif
-
-/* Maximum number of exceptions logged. */
-#ifndef GKI_MAX_EXCEPTION
-#define GKI_MAX_EXCEPTION           8
-#endif
-
-/* Maximum number of chars stored for each exception message. */
-#ifndef GKI_MAX_EXCEPTION_MSGLEN
-#define GKI_MAX_EXCEPTION_MSGLEN    64
-#endif
-
 /* The following is intended to be a reserved pool for SCO
 over HCI data and intentionally kept out of order */
 
@@ -371,7 +217,6 @@
 #define GKI_BUF8_MAX                30
 #endif
 
-// btla-specific ++
 /* The following pool is  meant for large allocations such as SDP_DB */
 #ifndef GKI_POOL_ID_9
 #define GKI_POOL_ID_9              9
@@ -384,17 +229,10 @@
 #ifndef GKI_BUF9_MAX
 #define GKI_BUF9_MAX           5
 #endif
-// btla-specific --
 
-#ifdef __cplusplus
-extern "C"
-{
+/* The number of fixed and dynamic buffer pools */
+#ifndef GKI_NUM_TOTAL_BUF_POOLS
+#define GKI_NUM_TOTAL_BUF_POOLS     10
 #endif
 
-EXPORT_API extern void LogMsg (UINT32 trace_set_mask, const char *fmt_str, ...);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif  /* GKI_TARGET_H */
+void LogMsg (UINT32 trace_set_mask, const char *fmt_str, ...);
diff --git a/test/suite/support/property.h b/include/stack_config.h
similarity index 62%
copy from test/suite/support/property.h
copy to include/stack_config.h
index a8b77c7..a4262c5 100644
--- a/test/suite/support/property.h
+++ b/include/stack_config.h
@@ -18,15 +18,19 @@
 
 #pragma once
 
-#include "base.h"
+#include <stdbool.h>
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+#include "config.h"
+#include "module.h"
 
-const char *property_extract_name(const bt_property_t *property);
+static const char STACK_CONFIG_MODULE[] = "stack_config_module";
 
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
+typedef struct {
+  const char *(*get_btsnoop_log_path)(void);
+  bool (*get_btsnoop_turned_on)(void);
+  bool (*get_btsnoop_should_save_last)(void);
+  bool (*get_trace_config_enabled)(void);
+  config_t *(*get_all)(void);
+} stack_config_t;
 
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+const stack_config_t *stack_config_get_interface();
diff --git a/main/Android.mk b/main/Android.mk
index 3357b8e..631204b 100644
--- a/main/Android.mk
+++ b/main/Android.mk
@@ -1,4 +1,4 @@
-LOCAL_PATH := $(call my-dir)
+LOCAL_PATH:= $(call my-dir)
 
 #
 # Bluetooth HW module
@@ -11,58 +11,59 @@
 	../btif/src/bluetooth.c
 
 # platform specific
-LOCAL_SRC_FILES += \
-	bte_conf.c \
+LOCAL_SRC_FILES+= \
+	bte_main.c \
 	bte_init.c \
 	bte_logmsg.c \
-	bte_main.c
+	bte_conf.c \
+	stack_config.c
 
 # BTIF
 LOCAL_SRC_FILES += \
-	../btif/src/btif_av.c \
-	../btif/src/btif_config.c \
-	../btif/src/btif_config_util.cpp \
-	../btif/src/btif_core.c \
-	../btif/src/btif_dm.c \
-	../btif/src/btif_gatt.c \
-	../btif/src/btif_gatt_client.c \
-	../btif/src/btif_gatt_multi_adv_util.c \
-	../btif/src/btif_gatt_server.c \
-	../btif/src/btif_gatt_test.c \
-	../btif/src/btif_gatt_util.c \
-	../btif/src/btif_hf.c \
-	../btif/src/btif_hf_client.c \
-	../btif/src/btif_hh.c \
-	../btif/src/btif_hl.c \
-	../btif/src/btif_mce.c \
-	../btif/src/btif_media_task.c \
-	../btif/src/btif_pan.c \
-	../btif/src/btif_profile_queue.c \
-	../btif/src/btif_rc.c \
-	../btif/src/btif_sm.c \
-	../btif/src/btif_sock.c \
-	../btif/src/btif_sock_rfc.c \
-	../btif/src/btif_sock_sdp.c \
-	../btif/src/btif_sock_thread.c \
-	../btif/src/btif_sock_util.c \
-	../btif/src/btif_storage.c \
-	../btif/src/btif_util.c
+    ../btif/src/btif_av.c \
+    ../btif/src/btif_config.c \
+    ../btif/src/btif_config_transcode.cpp \
+    ../btif/src/btif_core.c \
+    ../btif/src/btif_dm.c \
+    ../btif/src/btif_gatt.c \
+    ../btif/src/btif_gatt_client.c \
+    ../btif/src/btif_gatt_multi_adv_util.c \
+    ../btif/src/btif_gatt_server.c \
+    ../btif/src/btif_gatt_test.c \
+    ../btif/src/btif_gatt_util.c \
+    ../btif/src/btif_hf.c \
+    ../btif/src/btif_hf_client.c \
+    ../btif/src/btif_hh.c \
+    ../btif/src/btif_hl.c \
+    ../btif/src/btif_mce.c \
+    ../btif/src/btif_media_task.c \
+    ../btif/src/btif_pan.c \
+    ../btif/src/btif_profile_queue.c \
+    ../btif/src/btif_rc.c \
+    ../btif/src/btif_sm.c \
+    ../btif/src/btif_sock.c \
+    ../btif/src/btif_sock_rfc.c \
+    ../btif/src/btif_sock_sco.c \
+    ../btif/src/btif_sock_sdp.c \
+    ../btif/src/btif_sock_thread.c \
+    ../btif/src/btif_sock_util.c \
+    ../btif/src/btif_storage.c \
+    ../btif/src/btif_util.c \
+    ../btif/src/stack_manager.c
 
 # callouts
-LOCAL_SRC_FILES += \
-	../btif/co/bta_ag_co.c \
-	../btif/co/bta_av_co.c \
-	../btif/co/bta_dm_co.c \
-	../btif/co/bta_fs_co.c \
-	../btif/co/bta_gattc_co.c \
-	../btif/co/bta_gatts_co.c \
-	../btif/co/bta_hh_co.c \
-	../btif/co/bta_hl_co.c \
-	../btif/co/bta_pan_co.c \
-	../btif/co/bta_sys_co.c
+LOCAL_SRC_FILES+= \
+    ../btif/co/bta_ag_co.c \
+    ../btif/co/bta_dm_co.c \
+    ../btif/co/bta_av_co.c \
+    ../btif/co/bta_hh_co.c \
+    ../btif/co/bta_hl_co.c \
+    ../btif/co/bta_pan_co.c \
+    ../btif/co/bta_gattc_co.c \
+    ../btif/co/bta_gatts_co.c \
 
 # sbc encoder
-LOCAL_SRC_FILES += \
+LOCAL_SRC_FILES+= \
 	../embdrv/sbc/encoder/srce/sbc_analysis.c \
 	../embdrv/sbc/encoder/srce/sbc_dct.c \
 	../embdrv/sbc/encoder/srce/sbc_dct_coeffs.c \
@@ -72,13 +73,15 @@
 	../embdrv/sbc/encoder/srce/sbc_encoder.c \
 	../embdrv/sbc/encoder/srce/sbc_packing.c \
 
-LOCAL_SRC_FILES += \
+LOCAL_SRC_FILES+= \
 	../udrv/ulinux/uipc.c
 
-LOCAL_C_INCLUDES += . \
+LOCAL_C_INCLUDES+= . \
+	$(LOCAL_PATH)/../ \
 	$(LOCAL_PATH)/../bta/include \
 	$(LOCAL_PATH)/../bta/sys \
 	$(LOCAL_PATH)/../bta/dm \
+	$(LOCAL_PATH)/../btcore/include \
 	$(LOCAL_PATH)/../osi/include \
 	$(LOCAL_PATH)/../gki/common \
 	$(LOCAL_PATH)/../gki/ulinux \
@@ -96,6 +99,7 @@
 	$(LOCAL_PATH)/../btif/co \
 	$(LOCAL_PATH)/../hci/include\
 	$(LOCAL_PATH)/../vnd/include \
+	$(LOCAL_PATH)/../brcm/include \
 	$(LOCAL_PATH)/../embdrv/sbc/encoder/include \
 	$(LOCAL_PATH)/../embdrv/sbc/decoder/include \
 	$(LOCAL_PATH)/../audio_a2dp_hw \
@@ -107,41 +111,44 @@
 LOCAL_CONLYFLAGS := -std=c99
 
 ifeq ($(TARGET_PRODUCT), full_crespo)
-	LOCAL_CFLAGS += -DTARGET_CRESPO
+     LOCAL_CFLAGS += -DTARGET_CRESPO
 endif
 ifeq ($(TARGET_PRODUCT), full_crespo4g)
-	LOCAL_CFLAGS += -DTARGET_CRESPO
+     LOCAL_CFLAGS += -DTARGET_CRESPO
 endif
 ifeq ($(TARGET_PRODUCT), full_maguro)
-	LOCAL_CFLAGS += -DTARGET_MAGURO
+     LOCAL_CFLAGS += -DTARGET_MAGURO
 endif
 
 LOCAL_SHARED_LIBRARIES := \
-	libcutils \
-	libdl \
-	liblog \
-	libpower
+    libcutils \
+    libdl \
+    liblog \
+    libpower \
 
 LOCAL_STATIC_LIBRARIES := \
-	libbt-brcm_bta \
-	libbt-brcm_gki \
-	libbt-brcm_stack \
-	libbt-hci \
-	libbt-utils \
-	libbt-qcom_sbc_decoder \
-	libosi \
-	libtinyxml2 \
-	libbt-qcom_sbc_decoder
+    libbt-brcm_bta \
+    libbt-brcm_gki \
+    libbt-brcm_stack \
+    libbtdevice \
+    libbt-hci \
+    libbt-utils \
+    libbtcore \
+    libosi \
+    libtinyxml2 \
+    libbt-qcom_sbc_decoder
 
 LOCAL_MODULE := bluetooth.default
 LOCAL_MODULE_RELATIVE_PATH := hw
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE_CLASS := SHARED_LIBRARIES
 LOCAL_REQUIRED_MODULES := \
-	auto_pair_devlist.conf \
-	bt_did.conf \
-	bt_stack.conf \
-	libbt-vendor
+    auto_pair_devlist.conf \
+    bt_did.conf \
+    bt_stack.conf \
+    libbt-hci \
+    libbt-vendor
+
 LOCAL_MULTILIB := 32
 
 LOCAL_CLANG_CFLAGS := -Wno-error=gnu-variable-sized-type-not-at-end
diff --git a/main/bte_conf.c b/main/bte_conf.c
index 63ace86..75738e1 100644
--- a/main/bte_conf.c
+++ b/main/bte_conf.c
@@ -16,44 +16,15 @@
  *
  ******************************************************************************/
 
-#define LOG_TAG "bte_conf"
+#define LOG_TAG "bt_bte_conf"
 
 #include <assert.h>
 #include <stdio.h>
 #include <string.h>
-#include <utils/Log.h>
 
 #include "bta_api.h"
-#include "config.h"
-
-// TODO: eliminate these global variables.
-extern char hci_logfile[256];
-extern BOOLEAN hci_logging_enabled;
-extern BOOLEAN hci_save_log;
-extern BOOLEAN trace_conf_enabled;
-void bte_trace_conf_config(const config_t *config);
-
-// Reads the stack configuration file and populates global variables with
-// the contents of the file.
-void bte_load_conf(const char *path) {
-  assert(path != NULL);
-
-  ALOGI("%s attempt to load stack conf from %s", __func__, path);
-
-  config_t *config = config_new(path);
-  if (!config) {
-    ALOGI("%s file >%s< not found", __func__, path);
-    return;
-  }
-
-  strlcpy(hci_logfile, config_get_string(config, CONFIG_DEFAULT_SECTION, "BtSnoopFileName", ""), sizeof(hci_logfile));
-  hci_logging_enabled = config_get_bool(config, CONFIG_DEFAULT_SECTION, "BtSnoopLogOutput", false);
-  hci_save_log = config_get_bool(config, CONFIG_DEFAULT_SECTION, "BtSnoopSaveLog", false);
-  trace_conf_enabled = config_get_bool(config, CONFIG_DEFAULT_SECTION, "TraceConf", false);
-
-  bte_trace_conf_config(config);
-  config_free(config);
-}
+#include "osi/include/config.h"
+#include "osi/include/log.h"
 
 #if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
 extern int btm_ble_tx_power[BTM_BLE_ADV_TX_POWER_MAX + 1];
@@ -61,11 +32,11 @@
 {
   assert(path != NULL);
 
-  ALOGI("%s attempt to load ble stack conf from %s", __func__, path);
+  LOG_INFO("%s attempt to load ble stack conf from %s", __func__, path);
 
   config_t *config = config_new(path);
   if (!config) {
-    ALOGI("%s file >%s< not found", __func__, path);
+    LOG_INFO("%s file >%s< not found", __func__, path);
     return;
   }
 
@@ -73,7 +44,7 @@
   if(*ble_adv_tx_power) {
     sscanf(ble_adv_tx_power, "%d,%d,%d,%d,%d", btm_ble_tx_power, btm_ble_tx_power + 1, btm_ble_tx_power + 2,
                                                btm_ble_tx_power + 3, btm_ble_tx_power + 4);
-    ALOGI("loaded btm_ble_tx_power: %d, %d, %d, %d, %d", (char)btm_ble_tx_power[0], (char)btm_ble_tx_power[1],
+    LOG_INFO("loaded btm_ble_tx_power: %d, %d, %d, %d, %d", (char)btm_ble_tx_power[0], (char)btm_ble_tx_power[1],
                                         btm_ble_tx_power[2], btm_ble_tx_power[3], btm_ble_tx_power[4]);
   }
   config_free(config);
@@ -87,7 +58,7 @@
 
     config_t *config = config_new(p_path);
     if (!config) {
-        ALOGE("%s unable to load DID config '%s'.", __func__, p_path);
+        LOG_ERROR("%s unable to load DID config '%s'.", __func__, p_path);
         return;
     }
 
@@ -96,7 +67,7 @@
         snprintf(section_name, sizeof(section_name), "DID%d", i);
 
         if (!config_has_section(config, section_name)) {
-            ALOGD("%s no section named %s.", __func__, section_name);
+            LOG_DEBUG("%s no section named %s.", __func__, section_name);
             break;
         }
 
@@ -112,23 +83,23 @@
 
         if (record.vendor_id_source != DI_VENDOR_ID_SOURCE_BTSIG &&
             record.vendor_id_source != DI_VENDOR_ID_SOURCE_USBIF) {
-            ALOGE("%s invalid vendor id source %d; ignoring DID record %d.", __func__, record.vendor_id_source, i);
+            LOG_ERROR("%s invalid vendor id source %d; ignoring DID record %d.", __func__, record.vendor_id_source, i);
             continue;
         }
 
-        ALOGD("Device ID record %d : %s", i, (record.primary_record ? "primary" : "not primary"));
-        ALOGD("  vendorId            = %04x", record.vendor);
-        ALOGD("  vendorIdSource      = %04x", record.vendor_id_source);
-        ALOGD("  product             = %04x", record.product);
-        ALOGD("  version             = %04x", record.version);
-        ALOGD("  clientExecutableURL = %s", record.client_executable_url);
-        ALOGD("  serviceDescription  = %s", record.service_description);
-        ALOGD("  documentationURL    = %s", record.documentation_url);
+        LOG_DEBUG("Device ID record %d : %s", i, (record.primary_record ? "primary" : "not primary"));
+        LOG_DEBUG("  vendorId            = %04x", record.vendor);
+        LOG_DEBUG("  vendorIdSource      = %04x", record.vendor_id_source);
+        LOG_DEBUG("  product             = %04x", record.product);
+        LOG_DEBUG("  version             = %04x", record.version);
+        LOG_DEBUG("  clientExecutableURL = %s", record.client_executable_url);
+        LOG_DEBUG("  serviceDescription  = %s", record.service_description);
+        LOG_DEBUG("  documentationURL    = %s", record.documentation_url);
 
         uint32_t record_handle;
         tBTA_STATUS status = BTA_DmSetLocalDiRecord(&record, &record_handle);
         if (status != BTA_SUCCESS) {
-            ALOGE("%s unable to set device ID record %d: error %d.", __func__, i, status);
+            LOG_ERROR("%s unable to set device ID record %d: error %d.", __func__, i, status);
         }
     }
 
diff --git a/main/bte_init.c b/main/bte_init.c
index 3e3c1ad..e212f39 100644
--- a/main/bte_init.c
+++ b/main/bte_init.c
@@ -31,111 +31,28 @@
 #endif
 
 /* Include initialization functions definitions */
-#if (defined(RFCOMM_INCLUDED) && RFCOMM_INCLUDED == TRUE)
 #include "port_api.h"
-#endif
-
-#if (defined(TCS_INCLUDED) && TCS_INCLUDED == TRUE)
-#include "tcs_api.h"
-#endif
-
-#if (defined(OBX_INCLUDED) && OBX_INCLUDED == TRUE)
-#include "obx_api.h"
-#endif
 
 #if (defined(BNEP_INCLUDED) && BNEP_INCLUDED == TRUE)
 #include "bnep_api.h"
 #endif
 
-#if (defined(GAP_INCLUDED) && GAP_INCLUDED == TRUE)
 #include "gap_api.h"
-#endif
-
-#if ((defined(CTP_INCLUDED) && CTP_INCLUDED == TRUE))
-#include "ctp_api.h"
-#endif
-
-#if ((defined(ICP_INCLUDED) && ICP_INCLUDED == TRUE))
-#include "icp_api.h"
-#endif
-
-#if (defined(SPP_INCLUDED) && SPP_INCLUDED == TRUE)
-#include "spp_api.h"
-#endif
-
-#if (defined(DUN_INCLUDED) && DUN_INCLUDED == TRUE)
-#include "dun_api.h"
-#endif
-
-#if (defined(GOEP_INCLUDED) &&  GOEP_INCLUDED == TRUE)
-#include "goep_util.h"
-#endif /* GOEP included */
-
-#if (defined(FTP_INCLUDED) && FTP_INCLUDED == TRUE)
-#include "ftp_api.h"
-#endif /* FTP */
-
-#if (defined(OPP_INCLUDED) && OPP_INCLUDED == TRUE)
-#include "opp_api.h"
-#endif /* OPP */
-
-#if (defined(BIP_INCLUDED) && BIP_INCLUDED == TRUE)
-#include "bip_api.h"
-#endif
-
-#if (defined(BTU_BTA_INCLUDED) && BTU_BTA_INCLUDED == TRUE)
-#if (defined(BTA_BI_INCLUDED) && BTA_BI_INCLUDED == TRUE)
-#include "bta_bi_api.h"
-#endif
-#endif
-
-#if (defined(HFP_INCLUDED) && HFP_INCLUDED == TRUE)
-#include "hfp_api.h"
-#endif
-
-#if ((defined(HSP2_INCLUDED) && HSP2_INCLUDED == TRUE)) || \
-    ((defined(HFP_INCLUDED) && HFP_INCLUDED == TRUE))
-#include "hsp2_api.h"
-#endif
-
-#if (defined(HCRP_INCLUDED) && HCRP_INCLUDED == TRUE)
-#if (defined(HCRP_CLIENT_INCLUDED) && HCRP_CLIENT_INCLUDED == TRUE)
-#include "hcrp_api.h"
-#endif
-#if (defined(HCRP_SERVER_INCLUDED) && HCRP_SERVER_INCLUDED == TRUE)
-#include "hcrpm_api.h"
-#endif
-#endif
-
-#if (defined(BPP_INCLUDED) && BPP_INCLUDED == TRUE)
-#include "bpp_api.h"
-#endif
 
 #if (defined(PAN_INCLUDED) && PAN_INCLUDED == TRUE)
 #include "pan_api.h"
 #endif
 
-#if (defined(AVRC_INCLUDED) && AVRC_INCLUDED == TRUE)
 #include "avrc_api.h"
-#endif
 
 #if (defined(A2D_INCLUDED) && A2D_INCLUDED == TRUE)
 #include "a2d_api.h"
 #endif
 
-
-#if (defined(HID_DEV_INCLUDED) && HID_DEV_INCLUDED == TRUE)
-#include "hidd_api.h"
-#endif
-
 #if (defined(HID_HOST_INCLUDED) && HID_HOST_INCLUDED == TRUE)
 #include "hidh_api.h"
 #endif
 
-#if (defined(SAP_SERVER_INCLUDED) && SAP_SERVER_INCLUDED == TRUE)
-#include "sap_api.h"
-#endif  /* SAP_SERVER_INCLUDED */
-
 #if (defined(MCA_INCLUDED) && MCA_INCLUDED == TRUE)
 #include "mca_api.h"
 #endif
@@ -147,20 +64,12 @@
 #endif
 #endif
 
-// btla-specific ++
 /***** BTA Modules ******/
 #if BTA_INCLUDED == TRUE && BTA_DYNAMIC_MEMORY == TRUE
 #include "bta_api.h"
 #include "bta_sys.h"
 
-#if BTA_AC_INCLUDED == TRUE
-#include "bta_acs_int.h"
-#include "bta_acc_int.h"
-#endif
-
-#if BTA_AG_INCLUDED == TRUE
 #include "bta_ag_int.h"
-#endif
 
 #if BTA_HS_INCLUDED == TRUE
 #include "bta_hs_int.h"
@@ -168,50 +77,6 @@
 
 #include "bta_dm_int.h"
 
-#if BTA_DG_INCLUDED == TRUE
-#include "bta_dg_api.h"
-#include "bta_dg_int.h"
-#endif
-
-#if BTA_FT_INCLUDED == TRUE
-#include "bta_ftc_int.h"
-#include "bta_fts_int.h"
-#endif
-
-#if BTA_PBC_INCLUDED == TRUE
-#include "bta_pbc_int.h"
-#endif
-
-#if BTA_PBS_INCLUDED == TRUE
-#include "bta_pbs_int.h"
-#endif
-
-#if BTA_OP_INCLUDED == TRUE
-#include "bta_opc_int.h"
-#include "bta_ops_int.h"
-#endif
-
-#if BTA_SS_INCLUDED==TRUE
-#include "bta_ss_int.h"
-#endif
-
-#if BTA_CT_INCLUDED==TRUE
-#include "bta_ct_int.h"
-#endif
-
-#if BTA_CG_INCLUDED==TRUE
-#include "bta_cg_int.h"
-#endif
-
-#if BTA_BI_INCLUDED==TRUE
-#include "bta_bic_int.h"
-#include "bta_bis_int.h"
-#endif
-
-#if BTA_PR_INCLUDED==TRUE
-#include "bta_pr_int.h"
-#endif
-
 #if BTA_AR_INCLUDED==TRUE
 #include "bta_ar_int.h"
 #endif
@@ -219,39 +84,15 @@
 #include "bta_av_int.h"
 #endif
 
-#if BTA_SC_INCLUDED==TRUE
-#include "bta_sc_int.h"
-#endif
-
-#if BTA_HD_INCLUDED==TRUE
-#include "bta_hd_int.h"
-#endif
-
 #if BTA_HH_INCLUDED==TRUE
 #include "bta_hh_int.h"
 #endif
 
-#if BTA_FM_INCLUDED==TRUE
-#include "bta_fm_int.h"
-#endif
-
-#if BTA_FMTX_INCLUDED==TRUE
-#include "bta_fmtx_int.h"
-#endif
-
 #if BTA_JV_INCLUDED==TRUE
 #include "bta_jv_int.h"
 tBTA_JV_CB *bta_jv_cb_ptr = NULL;
 #endif
 
-#if BTA_MCE_INCLUDED == TRUE
-#include "bta_mce_int.h"
-#endif
-
-#if BTA_MSE_INCLUDED == TRUE
-#include "bta_mse_int.h"
-#endif
-
 #if BTA_HL_INCLUDED == TRUE
 #include "bta_hl_int.h"
 #endif
@@ -271,7 +112,6 @@
 #include "bta_prm_int.h"
 
 #endif /* BTA_INCLUDED */
-// btla-specific --
 
 /*****************************************************************************
 **                          F U N C T I O N S                                *
@@ -292,83 +132,11 @@
 ** Returns          void
 **
 ******************************************************************************/
-BT_API void BTE_InitStack(void)
+void BTE_InitStack(void)
 {
 /* Initialize the optional stack components */
-
-/****************************
-** RFCOMM and its profiles **
-*****************************/
-#if (defined(RFCOMM_INCLUDED) && RFCOMM_INCLUDED == TRUE)
     RFCOMM_Init();
 
-#if (defined(SPP_INCLUDED) && SPP_INCLUDED == TRUE)
-    SPP_Init();
-#endif  /* SPP */
-
-#if (defined(DUN_INCLUDED) && DUN_INCLUDED == TRUE)
-    DUN_Init();
-#endif  /* DUN */
-
-#if (defined(HSP2_INCLUDED) && HSP2_INCLUDED == TRUE)
-    HSP2_Init();
-#endif  /* HSP2 */
-
-#if (defined(HFP_INCLUDED) && HFP_INCLUDED == TRUE)
-    HFP_Init();
-#endif  /* HFP */
-
-/**************************
-** OBEX and its profiles **
-***************************/
-#if (defined(OBX_INCLUDED) && OBX_INCLUDED == TRUE)
-    OBX_Init();
-#if (defined(BIP_INCLUDED) && BIP_INCLUDED == TRUE)
-    BIP_Init();
-#if (defined(BTU_BTA_INCLUDED) && BTU_BTA_INCLUDED == TRUE)
-#if (defined(BTA_BI_INCLUDED) && BTA_BI_INCLUDED == TRUE)
-    BTA_BicInit();
-#endif  /* BTA BI */
-#endif
-#endif  /* BIP */
-
-#if (defined(GOEP_INCLUDED) && GOEP_INCLUDED == TRUE)
-    GOEP_Init();
-#endif /* GOEP */
-
-
-#if (defined(FTP_INCLUDED) && FTP_INCLUDED == TRUE)
-    FTP_Init();
-#endif
-#if (defined(OPP_INCLUDED) && OPP_INCLUDED == TRUE)
-    OPP_Init();
-#endif
-
-#if (defined(BPP_INCLUDED) && BPP_INCLUDED == TRUE)
-    BPP_Init();
-#endif  /* BPP */
-#endif  /* OBX */
-
-
-#endif  /* RFCOMM Included */
-
-/*************************
-** TCS and its profiles **
-**************************/
-#if (defined(TCS_INCLUDED) && TCS_INCLUDED == TRUE)
-    TCS_Init();
-
-#if (defined(CTP_INCLUDED) && CTP_INCLUDED == TRUE)
-    CTP_Init();
-#endif /* CTP_INCLUDED */
-
-#if (defined(ICP_INCLUDED) && ICP_INCLUDED == TRUE)
-    ICP_Init();
-#endif /* ICP_INCLUDED */
-
-#endif /* TCS_INCLUDED */
-
-
 /**************************
 ** BNEP and its profiles **
 ***************************/
@@ -389,122 +157,44 @@
 #endif  /* AADP */
 
 
-#if (defined(AVRC_INCLUDED) && AVRC_INCLUDED == TRUE)
     AVRC_Init();
-#endif
 
 
 /***********
 ** Others **
 ************/
-#if (defined(GAP_INCLUDED) && GAP_INCLUDED == TRUE)
     GAP_Init();
-#endif  /* GAP Included */
 
-#if (defined(HCRP_INCLUDED) && HCRP_INCLUDED == TRUE)
-#if (defined(HCRP_CLIENT_INCLUDED) && HCRP_CLIENT_INCLUDED == TRUE)
-    HCRP_Init();
-#endif
-#if (defined(HCRP_SERVER_INCLUDED) && HCRP_SERVER_INCLUDED == TRUE)
-    HCRPM_Init();
-#endif
-#endif  /* HCRP Included */
-
-#if (defined(SAP_SERVER_INCLUDED) && SAP_SERVER_INCLUDED == TRUE)
-    SAP_Init();
-#endif  /* SAP_SERVER_INCLUDED */
-
-#if (defined(HID_DEV_INCLUDED) && HID_DEV_INCLUDED == TRUE)
-    HID_DevInit();
-#endif
 #if (defined(HID_HOST_INCLUDED) && HID_HOST_INCLUDED == TRUE)
     HID_HostInit();
 #endif
 
 #if (defined(MCA_INCLUDED) && MCA_INCLUDED == TRUE)
     MCA_Init();
-#endif  /* SAP_SERVER_INCLUDED */
+#endif
 
 /****************
 ** BTA Modules **
 *****************/
-// btla-specific ++
 #if (BTA_INCLUDED == TRUE && BTA_DYNAMIC_MEMORY == TRUE)
     memset((void*)bta_sys_cb_ptr, 0, sizeof(tBTA_SYS_CB));
     memset((void*)bta_dm_cb_ptr, 0, sizeof(tBTA_DM_CB));
     memset((void*)bta_dm_search_cb_ptr, 0, sizeof(tBTA_DM_SEARCH_CB));
     memset((void*)bta_dm_di_cb_ptr, 0, sizeof(tBTA_DM_DI_CB));
     memset((void*)bta_prm_cb_ptr, 0, sizeof(tBTA_PRM_CB));
-
-#if BTA_AC_INCLUDED == TRUE
-    memset((void*)bta_acc_cb_ptr, 0, sizeof(tBTA_ACC_CB));
-    memset((void*)bta_acs_cb_ptr, 0, sizeof(tBTA_ACS_CB));
-#endif
-#if BTA_AG_INCLUDED == TRUE
     memset((void*)bta_ag_cb_ptr, 0, sizeof(tBTA_AG_CB));
-#endif
 #if BTA_HS_INCLUDED == TRUE
     memset((void*)bta_hs_cb_ptr, 0, sizeof(tBTA_HS_CB));
 #endif
-#if BTA_DG_INCLUDED == TRUE
-    memset((void*)bta_dg_cb_ptr, 0, sizeof(tBTA_DG_CB));
-#endif
-#if BTA_FT_INCLUDED==TRUE
-    memset((void*)bta_ftc_cb_ptr, 0, sizeof(tBTA_FTC_CB));
-    memset((void*)bta_fts_cb_ptr, 0, sizeof(tBTA_FTS_CB));
-#endif
-#if BTA_PBC_INCLUDED==TRUE
-    memset((void*)bta_pbc_cb_ptr, 0, sizeof(tBTA_PBC_CB));
-#endif
-#if BTA_PBS_INCLUDED==TRUE
-    memset((void*)bta_pbs_cb_ptr, 0, sizeof(tBTA_PBS_CB));
-#endif
-#if BTA_OP_INCLUDED==TRUE
-    memset((void*)bta_opc_cb_ptr, 0, sizeof(tBTA_OPC_CB));
-    memset((void*)bta_ops_cb_ptr, 0, sizeof(tBTA_OPS_CB));
-#endif
-#if BTA_SS_INCLUDED==TRUE
-    memset((void*)bta_ss_cb_ptr, 0, sizeof(tBTA_SS_CB));
-#endif
-#if BTA_CT_INCLUDED==TRUE
-    memset((void*)bta_ct_cb_ptr, 0, sizeof(tBTA_CT_CB));
-#endif
-#if BTA_CG_INCLUDED==TRUE
-    memset((void*)bta_cg_cb_ptr, 0, sizeof(tBTA_CG_CB));
-#endif
-#if BTA_BI_INCLUDED==TRUE
-    memset((void *)bta_bic_cb_ptr, 0, sizeof(tBTA_BIC_CB));
-    memset((void *)bta_bis_cb_ptr, 0, sizeof(tBTA_BIS_CB));
-#endif
 #if BTA_AR_INCLUDED==TRUE
     memset((void *)bta_ar_cb_ptr, 0, sizeof(tBTA_AR_CB));
 #endif
 #if BTA_AV_INCLUDED==TRUE
     memset((void *)bta_av_cb_ptr, 0, sizeof(tBTA_AV_CB));
 #endif
-#if BTA_PR_INCLUDED==TRUE
-    memset((void *)bta_pr_cb_ptr, 0, sizeof(tBTA_PR_CB));
-#endif
-#if BTA_SC_INCLUDED==TRUE
-    memset((void *)bta_sc_cb_ptr, 0, sizeof(tBTA_SC_CB));
-#endif
-#if BTA_HD_INCLUDED==TRUE
-    memset((void *)bta_hd_cb_ptr, 0, sizeof(tBTA_HD_CB));
-#endif
 #if BTA_HH_INCLUDED==TRUE
     memset((void *)bta_hh_cb_ptr, 0, sizeof(tBTA_HH_CB));
 #endif
-#if BTA_FM_INCLUDED==TRUE
-    memset((void *)bta_fm_cb_ptr, 0, sizeof(tBTA_FM_CB));
-#endif
-#if BTA_FMTX_INCLUDED==TRUE
-    memset((void *)bta_fmtx_cb_ptr, 0, sizeof(tBTA_FMTX_CB));
-#endif
-#if 0
-#if BTA_JV_INCLUDED==TRUE
-    memset((void *)bta_jv_cb_ptr, 0, sizeof(tBTA_JV_CB));
-#endif
-#endif
 #if BTA_HL_INCLUDED==TRUE
     memset((void *)bta_hl_cb_ptr, 0, sizeof(tBTA_HL_CB));
 #endif
@@ -517,5 +207,5 @@
 #endif
 
 #endif /* BTA_INCLUDED == TRUE */
-// btla-specific --
+
 }
diff --git a/main/bte_logmsg.c b/main/bte_logmsg.c
index c9fc17e..3258f47 100644
--- a/main/bte_logmsg.c
+++ b/main/bte_logmsg.c
@@ -16,76 +16,39 @@
  *
  ******************************************************************************/
 
-/******************************************************************************
- *
- *  Contains the LogMsg wrapper routines for BTE.  It routes calls the
- *  appropriate application's LogMsg equivalent.
- *
- ******************************************************************************/
-
 #include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdarg.h>
+#include <sys/time.h>
+#include <time.h>
 
-#include "config.h"
-#include "gki.h"
 #include "bte.h"
-
-#include "bte_appl.h"
-
-#if MMI_INCLUDED == TRUE
-#include "mmi.h"
-#endif
-
-/* always enable trace framework */
-
+#include "bta_api.h"
 #include "btu.h"
+#include "osi/include/config.h"
+#include "gki.h"
 #include "l2c_api.h"
-#if (RFCOMM_INCLUDED==TRUE)
+#include "osi/include/log.h"
+#include "stack_config.h"
+
 #include "port_api.h"
-#endif
-#if (OBX_INCLUDED==TRUE)
-#include "obx_api.h"
-#endif
-#if (AVCT_INCLUDED==TRUE)
-#include "avct_api.h"
-#endif
 #if (AVDT_INCLUDED==TRUE)
 #include "avdt_api.h"
 #endif
-#if (AVRC_INCLUDED==TRUE)
 #include "avrc_api.h"
-#endif
 #if (AVDT_INCLUDED==TRUE)
 #include "avdt_api.h"
 #endif
 #if (A2D_INCLUDED==TRUE)
 #include "a2d_api.h"
 #endif
-#if (BIP_INCLUDED==TRUE)
-#include "bip_api.h"
-#endif
 #if (BNEP_INCLUDED==TRUE)
 #include "bnep_api.h"
 #endif
-#if (BPP_INCLUDED==TRUE)
-#include "bpp_api.h"
-#endif
 #include "btm_api.h"
-#if (DUN_INCLUDED==TRUE)
-#include "dun_api.h"
-#endif
-#if (GAP_INCLUDED==TRUE)
 #include "gap_api.h"
-#endif
-#if (GOEP_INCLUDED==TRUE)
-#include "goep_util.h"
-#endif
-#if (HCRP_INCLUDED==TRUE)
-#include "hcrp_api.h"
-#endif
 #if (PAN_INCLUDED==TRUE)
 #include "pan_api.h"
 #endif
@@ -96,88 +59,11 @@
 #include "smp_api.h"
 #endif
 
-    /* LayerIDs for BTA, currently everything maps onto appl_trace_level */
-#if (BTA_INCLUDED==TRUE)
-#include "bta_api.h"
-#endif
-
-
-#if defined(__CYGWIN__) || defined(__linux__)
-#undef RPC_INCLUDED
-#define RPC_INCLUDED TRUE
-
-#include <sys/time.h>
-#include <time.h>
-
-#if (defined(ANDROID_USE_LOGCAT) && (ANDROID_USE_LOGCAT==TRUE))
-const char * const bt_layer_tags[] = {
-    "bt-btif",
-    "bt-usb",
-    "bt-serial",
-    "bt-socket",
-    "bt-rs232",
-    "bt-lc",
-    "bt-lm",
-    "bt-hci",
-    "bt-l2cap",
-    "bt-rfcomm",
-    "bt-sdp",
-    "bt-tcs",
-    "bt-obex",
-    "bt-btm",
-    "bt-gap",
-    "bt-dun",
-    "bt-goep",
-    "bt-icp",
-    "bt-hsp2",
-    "bt-spp",
-    "bt-ctp",
-    "bt-bpp",
-    "bt-hcrp",
-    "bt-ftp",
-    "bt-opp",
-    "bt-btu",
-    "bt-gki",
-    "bt-bnep",
-    "bt-pan",
-    "bt-hfp",
-    "bt-hid",
-    "bt-bip",
-    "bt-avp",
-    "bt-a2d",
-    "bt-sap",
-    "bt-amp",
-    "bt-mca",
-    "bt-att",
-    "bt-smp",
-    "bt-nfc",
-    "bt-nci",
-    "bt-idep",
-    "bt-ndep",
-    "bt-llcp",
-    "bt-rw",
-    "bt-ce",
-    "bt-snep",
-    "bt-ndef",
-    "bt-nfa",
-};
-
-#ifndef LINUX_NATIVE
-#include <cutils/log.h>
 #define LOGI0(t,s) __android_log_write(ANDROID_LOG_INFO, t, s)
 #define LOGD0(t,s) __android_log_write(ANDROID_LOG_DEBUG, t, s)
 #define LOGW0(t,s) __android_log_write(ANDROID_LOG_WARN, t, s)
 #define LOGE0(t,s) __android_log_write(ANDROID_LOG_ERROR, t, s)
 
-#else
-#undef ANDROID_USE_LOGCAT
-#endif
-
-#endif
-
-
-//#include "btl_cfg.h"
-#define BTL_GLOBAL_PROP_TRC_FLAG "TRC_BTAPP"
 #ifndef DEFAULT_CONF_TRACE_LEVEL
 #define DEFAULT_CONF_TRACE_LEVEL BT_TRACE_LEVEL_WARNING
 #endif
@@ -185,356 +71,192 @@
 #ifndef BTE_LOG_BUF_SIZE
 #define BTE_LOG_BUF_SIZE  1024
 #endif
+
 #define BTE_LOG_MAX_SIZE  (BTE_LOG_BUF_SIZE - 12)
 
-
-//#define BTE_MAP_TRACE_LEVEL FALSE
-/* map by default BTE trace levels onto android trace levels */
-#ifndef BTE_MAP_TRACE_LEVEL
-#define BTE_MAP_TRACE_LEVEL TRUE
-#endif
-
-// #define BTE_ANDROID_INTERNAL_TIMESTAMP TRUE
-/* by default no internal timestamp. adb logcate -v time allows having timestamps */
-#ifndef BTE_ANDROID_INTERNAL_TIMESTAMP
-#define BTE_ANDROID_INTERNAL_TIMESTAMP FALSE
-#endif
-#if (BTE_ANDROID_INTERNAL_TIMESTAMP==TRUE)
-#define MSG_BUFFER_OFFSET strlen(buffer)
-#else
 #define MSG_BUFFER_OFFSET 0
+
+/* LayerIDs for BTA, currently everything maps onto appl_trace_level */
+static const char * const bt_layer_tags[] = {
+  "bt_btif",
+  "bt_usb",
+  "bt_serial",
+  "bt_socket",
+  "bt_rs232",
+  "bt_lc",
+  "bt_lm",
+  "bt_hci",
+  "bt_l2cap",
+  "bt_rfcomm",
+  "bt_sdp",
+  "bt_tcs",
+  "bt_obex",
+  "bt_btm",
+  "bt_gap",
+  "UNUSED",
+  "UNUSED",
+  "bt_icp",
+  "bt_hsp2",
+  "bt_spp",
+  "bt_ctp",
+  "bt_bpp",
+  "bt_hcrp",
+  "bt_ftp",
+  "bt_opp",
+  "bt_btu",
+  "bt_gki",
+  "bt_bnep",
+  "bt_pan",
+  "bt_hfp",
+  "bt_hid",
+  "bt_bip",
+  "bt_avp",
+  "bt_a2d",
+  "bt_sap",
+  "bt_amp",
+  "bt_mca",
+  "bt_att",
+  "bt_smp",
+  "bt_nfc",
+  "bt_nci",
+  "bt_idep",
+  "bt_ndep",
+  "bt_llcp",
+  "bt_rw",
+  "bt_ce",
+  "bt_snep",
+  "bt_ndef",
+  "bt_nfa",
+};
+static uint8_t BTAPP_SetTraceLevel(uint8_t new_level);
+static uint8_t BTIF_SetTraceLevel(uint8_t new_level);
+static uint8_t BTU_SetTraceLevel(uint8_t new_level);
+
+/* make sure list is order by increasing layer id!!! */
+static tBTTRC_FUNC_MAP bttrc_set_level_map[] = {
+  {BTTRC_ID_STK_BTU, BTTRC_ID_STK_HCI, BTU_SetTraceLevel, "TRC_HCI", DEFAULT_CONF_TRACE_LEVEL},
+  {BTTRC_ID_STK_L2CAP, BTTRC_ID_STK_L2CAP, L2CA_SetTraceLevel, "TRC_L2CAP", DEFAULT_CONF_TRACE_LEVEL},
+  {BTTRC_ID_STK_RFCOMM, BTTRC_ID_STK_RFCOMM_DATA, PORT_SetTraceLevel, "TRC_RFCOMM", DEFAULT_CONF_TRACE_LEVEL},
+#if (AVDT_INCLUDED==TRUE)
+  {BTTRC_ID_STK_AVDT, BTTRC_ID_STK_AVDT, AVDT_SetTraceLevel, "TRC_AVDT", DEFAULT_CONF_TRACE_LEVEL},
+#endif
+  {BTTRC_ID_STK_AVRC, BTTRC_ID_STK_AVRC, AVRC_SetTraceLevel, "TRC_AVRC", DEFAULT_CONF_TRACE_LEVEL},
+#if (AVDT_INCLUDED==TRUE)
+  //{BTTRC_ID_AVDT_SCB, BTTRC_ID_AVDT_CCB, NULL, "TRC_AVDT_SCB", DEFAULT_CONF_TRACE_LEVEL},
+#endif
+#if (A2D_INCLUDED==TRUE)
+  {BTTRC_ID_STK_A2D, BTTRC_ID_STK_A2D, A2D_SetTraceLevel, "TRC_A2D", DEFAULT_CONF_TRACE_LEVEL},
+#endif
+#if (BNEP_INCLUDED==TRUE)
+  {BTTRC_ID_STK_BNEP, BTTRC_ID_STK_BNEP, BNEP_SetTraceLevel, "TRC_BNEP", DEFAULT_CONF_TRACE_LEVEL},
+#endif
+  {BTTRC_ID_STK_BTM_ACL, BTTRC_ID_STK_BTM_SEC, BTM_SetTraceLevel, "TRC_BTM", DEFAULT_CONF_TRACE_LEVEL},
+  {BTTRC_ID_STK_GAP, BTTRC_ID_STK_GAP, GAP_SetTraceLevel, "TRC_GAP", DEFAULT_CONF_TRACE_LEVEL},
+#if (PAN_INCLUDED==TRUE)
+  {BTTRC_ID_STK_PAN, BTTRC_ID_STK_PAN, PAN_SetTraceLevel, "TRC_PAN", DEFAULT_CONF_TRACE_LEVEL},
+#endif
+  {BTTRC_ID_STK_SDP, BTTRC_ID_STK_SDP, SDP_SetTraceLevel, "TRC_SDP", DEFAULT_CONF_TRACE_LEVEL},
+#if (BLE_INCLUDED==TRUE)
+  {BTTRC_ID_STK_GATT, BTTRC_ID_STK_GATT, GATT_SetTraceLevel, "TRC_GATT", DEFAULT_CONF_TRACE_LEVEL},
+  {BTTRC_ID_STK_SMP, BTTRC_ID_STK_SMP, SMP_SetTraceLevel, "TRC_SMP", DEFAULT_CONF_TRACE_LEVEL},
 #endif
 
-//#define DBG_TRACE
+  /* LayerIDs for BTA, currently everything maps onto appl_trace_level.
+   */
+  {BTTRC_ID_BTA_ACC, BTTRC_ID_BTAPP, BTAPP_SetTraceLevel, "TRC_BTAPP", DEFAULT_CONF_TRACE_LEVEL},
+  {BTTRC_ID_BTA_ACC, BTTRC_ID_BTAPP, BTIF_SetTraceLevel, "TRC_BTIF", DEFAULT_CONF_TRACE_LEVEL},
 
-#if defined( DBG_TRACE )
-#define DBG_TRACE_API0( m ) BT_TRACE( TRACE_LAYER_HCI, TRACE_TYPE_API, m )
-#define DBG_TRACE_WARNING2( m, p0, p1 ) BT_TRACE( TRACE_LAYER_BTM, (TRACE_ORG_APPL|TRACE_TYPE_WARNING), m, p0, p1 )
-#else
-#define DBG_TRACE_API0( m )
-#define DBG_TRACE_WARNING2( m, p0, p1 )
-#endif
-#define DBG_TRACE_DEBUG2( m, p0, p1 ) BT_TRACE( TRACE_LAYER_BTM, (TRACE_ORG_APPL|TRACE_TYPE_DEBUG), m, p0, p1 )
+  {0, 0, NULL, NULL, DEFAULT_CONF_TRACE_LEVEL}
+};
 
-void
-LogMsg(UINT32 trace_set_mask, const char *fmt_str, ...)
-{
-	static char buffer[BTE_LOG_BUF_SIZE];
-    int trace_layer = TRACE_GET_LAYER(trace_set_mask);
-    if (trace_layer >= TRACE_LAYER_MAX_NUM)
-        trace_layer = 0;
+static const UINT16 bttrc_map_size = sizeof(bttrc_set_level_map)/sizeof(tBTTRC_FUNC_MAP);
 
-	va_list ap;
-#if (BTE_ANDROID_INTERNAL_TIMESTAMP==TRUE)
-	struct timeval tv;
-	struct timezone tz;
-	struct tm *tm;
-	time_t t;
+void LogMsg(uint32_t trace_set_mask, const char *fmt_str, ...) {
+  static char buffer[BTE_LOG_BUF_SIZE];
+  int trace_layer = TRACE_GET_LAYER(trace_set_mask);
+  if (trace_layer >= TRACE_LAYER_MAX_NUM)
+    trace_layer = 0;
 
-	gettimeofday(&tv, &tz);
-	time(&t);
-	tm = localtime(&t);
+  va_list ap;
+  va_start(ap, fmt_str);
+  vsnprintf(&buffer[MSG_BUFFER_OFFSET], BTE_LOG_MAX_SIZE, fmt_str, ap);
+  va_end(ap);
 
-    sprintf(buffer, "%02d:%02d:%02d.%03d ", tm->tm_hour, tm->tm_min, tm->tm_sec,
-        tv.tv_usec / 1000);
-#endif
-	va_start(ap, fmt_str);
-	vsnprintf(&buffer[MSG_BUFFER_OFFSET], BTE_LOG_MAX_SIZE, fmt_str, ap);
-	va_end(ap);
-
-#if (defined(ANDROID_USE_LOGCAT) && (ANDROID_USE_LOGCAT==TRUE))
-#if (BTE_MAP_TRACE_LEVEL==TRUE)
-    switch ( TRACE_GET_TYPE(trace_set_mask) )
-    {
-        case TRACE_TYPE_ERROR:
-            LOGE0(bt_layer_tags[trace_layer], buffer);
-            break;
-        case TRACE_TYPE_WARNING:
-            LOGW0(bt_layer_tags[trace_layer], buffer);
-            break;
-        case TRACE_TYPE_API:
-        case TRACE_TYPE_EVENT:
-            LOGI0(bt_layer_tags[trace_layer], buffer);
-            break;
-        case TRACE_TYPE_DEBUG:
-            LOGD0(bt_layer_tags[trace_layer], buffer);
-            break;
-        default:
-            LOGE0(bt_layer_tags[trace_layer], buffer);      /* we should never get this */
-            break;
-    }
-#else
-    LOGI0(bt_layer_tags[trace_layer], buffer);
-#endif
-#else
-	write(2, buffer, strlen(buffer));
-	write(2, "\n", 1);
-#endif
-}
-
-void
-ScrLog(UINT32 trace_set_mask, const char *fmt_str, ...)
-{
-	static char buffer[BTE_LOG_BUF_SIZE];
-
-	va_list ap;
-	struct timeval tv;
-	struct timezone tz;
-	struct tm *tm;
-	time_t t;
-    int trace_layer = TRACE_GET_LAYER(trace_set_mask);
-    if (trace_layer >= TRACE_LAYER_MAX_NUM)
-        trace_layer = 0;
-	gettimeofday(&tv, &tz);
-	time(&t);
-	tm = localtime(&t);
-
-        sprintf(buffer, "%02d:%02d:%02d.%03ld ", tm->tm_hour, tm->tm_min, tm->tm_sec,
-        tv.tv_usec / 1000);
-
-	va_start(ap, fmt_str);
-	vsnprintf(&buffer[strlen(buffer)], BTE_LOG_MAX_SIZE, fmt_str, ap);
-	va_end(ap);
-
-#if (defined(ANDROID_USE_LOGCAT) && (ANDROID_USE_LOGCAT==TRUE))
-    LOGI0(bt_layer_tags[trace_layer], buffer);
-#else
-	write(2, buffer, strlen(buffer));
-	write(2, "\n", 1);
-#endif
-}
-
-/* this function should go into BTAPP_DM for example */
-BT_API UINT8 BTAPP_SetTraceLevel( UINT8 new_level )
-{
-    if (new_level != 0xFF)
-        appl_trace_level = new_level;
-
-    return (appl_trace_level);
-}
-
-BT_API UINT8 BTIF_SetTraceLevel( UINT8 new_level )
-{
-    if (new_level != 0xFF)
-        btif_trace_level = new_level;
-
-    return (btif_trace_level);
-}
-
-BTU_API UINT8 BTU_SetTraceLevel( UINT8 new_level )
-{
-    if (new_level != 0xFF)
-        btu_cb.trace_level = new_level;
-
-    return (btu_cb.trace_level);
-}
-
-BOOLEAN trace_conf_enabled = FALSE;
-
-void bte_trace_conf(const char *p_conf_name, const char *p_conf_value)
-{
-    tBTTRC_FUNC_MAP *p_f_map = (tBTTRC_FUNC_MAP *) &bttrc_set_level_map[0];
-
-    while (p_f_map->trc_name != NULL)
-    {
-        if (strcmp(p_f_map->trc_name, (const char *)p_conf_name) == 0)
-        {
-            p_f_map->trace_level = (UINT8) atoi(p_conf_value);
-            break;
-        }
-        p_f_map++;
-    }
-}
-
-void bte_trace_conf_config(const config_t *config) {
-  assert(config != NULL);
-
-  for (tBTTRC_FUNC_MAP *functions = &bttrc_set_level_map[0]; functions->trc_name; ++functions) {
-    int value = config_get_int(config, CONFIG_DEFAULT_SECTION, functions->trc_name, -1);
-    if (value != -1)
-      functions->trace_level = value;
+  switch ( TRACE_GET_TYPE(trace_set_mask) ) {
+    case TRACE_TYPE_ERROR:
+      LOGE0(bt_layer_tags[trace_layer], buffer);
+      break;
+    case TRACE_TYPE_WARNING:
+      LOGW0(bt_layer_tags[trace_layer], buffer);
+      break;
+    case TRACE_TYPE_API:
+    case TRACE_TYPE_EVENT:
+      LOGI0(bt_layer_tags[trace_layer], buffer);
+      break;
+    case TRACE_TYPE_DEBUG:
+      LOGD0(bt_layer_tags[trace_layer], buffer);
+      break;
+    default:
+      LOGE0(bt_layer_tags[trace_layer], buffer);      /* we should never get this */
+      break;
   }
 }
 
-/********************************************************************************
- **
- **    Function Name:    BTA_SysSetTraceLevel
- **
- **    Purpose:          set or reads the different Trace Levels of layer IDs (see bt_trace.h,
- **                      BTTRC_ID_xxxx
- **
- **    Input Parameters: Array with trace layers to set to a given level or read. a layer ID of 0
- **                      defines the end of the list
- **                      WARNING: currently type should be 0-5! or FF for reading!!!!
- **
- **    Returns:
- **                      input array with trace levels for given layer id
- **
- *********************************************************************************/
-BT_API tBTTRC_LEVEL * BTA_SysSetTraceLevel(tBTTRC_LEVEL * p_levels)
-{
-    const tBTTRC_FUNC_MAP *p_f_map;
-    tBTTRC_LEVEL *p_l = p_levels;
+/* this function should go into BTAPP_DM for example */
+static uint8_t BTAPP_SetTraceLevel(uint8_t new_level) {
+  if (new_level != 0xFF)
+    appl_trace_level = new_level;
 
-    DBG_TRACE_API0( "BTA_SysSetTraceLevel()" );
-
-    while (0 != p_l->layer_id)
-    {
-        p_f_map = &bttrc_set_level_map[0];
-
-        while (0 != p_f_map->layer_id_start)
-        {
-            printf("BTA_SysSetTraceLevel - trace id in map start = %d end= %d,  paramter id = %d\r\n", p_f_map->layer_id_start, p_f_map->layer_id_end, p_l->layer_id );
-            /* as p_f_map is ordered by increasing layer id, go to next map entry as long end id
-             * is smaller */
-            //if (p_f_map->layer_id_end < p_l->layer_id)
-            //{
-                //p_f_map++;
-            //}
-            //else
-            {
-                /* check if layer_id actually false into a range or if it is note existing in the  map */
-                if ((NULL != p_f_map->p_f) && (p_f_map->layer_id_start <= p_l->layer_id) && (p_f_map->layer_id_end >= p_l->layer_id) )
-                {
-                    DBG_TRACE_DEBUG2( "BTA_SysSetTraceLevel( id:%d, level:%d ): setting/reading",
-                            p_l->layer_id, p_l->type );
-                    p_l->type = p_f_map->p_f(p_l->type);
-                    break;
-                }
-                else
-                {
-                    DBG_TRACE_WARNING2( "BTA_SysSetTraceLevel( id:%d, level:%d ): MISSING Set function OR ID in map!",
-                            p_l->layer_id, p_l->type );
-                }
-                /* set/read next trace level by getting out ot map loop */
-                //p_l++;
-                //break;
-            }
-            p_f_map++;
-        }
-        //if (0 == p_f_map->layer_id_start)
-        {
-            DBG_TRACE_WARNING2( "BTA_SysSetTraceLevel( id:%d, level:%d ): ID NOT FOUND in map. Skip to next",
-                    p_l->layer_id, p_l->type );
-            p_l++;
-        }
-    }
-
-    return p_levels;
-} /* BTA_SysSetTraceLevel() */
-
-/* make sure list is order by increasing layer id!!! */
-tBTTRC_FUNC_MAP bttrc_set_level_map[] = {
-    {BTTRC_ID_STK_BTU, BTTRC_ID_STK_HCI, BTU_SetTraceLevel, "TRC_HCI", DEFAULT_CONF_TRACE_LEVEL},
-    {BTTRC_ID_STK_L2CAP, BTTRC_ID_STK_L2CAP, L2CA_SetTraceLevel, "TRC_L2CAP", DEFAULT_CONF_TRACE_LEVEL},
-#if (RFCOMM_INCLUDED==TRUE)
-    {BTTRC_ID_STK_RFCOMM, BTTRC_ID_STK_RFCOMM_DATA, PORT_SetTraceLevel, "TRC_RFCOMM", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (OBX_INCLUDED==TRUE)
-    {BTTRC_ID_STK_OBEX, BTTRC_ID_STK_OBEX, OBX_SetTraceLevel, "TRC_OBEX", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (AVCT_INCLUDED==TRUE)
-    //{BTTRC_ID_STK_AVCT, BTTRC_ID_STK_AVCT, NULL, "TRC_AVCT", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (AVDT_INCLUDED==TRUE)
-    {BTTRC_ID_STK_AVDT, BTTRC_ID_STK_AVDT, AVDT_SetTraceLevel, "TRC_AVDT", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (AVRC_INCLUDED==TRUE)
-    {BTTRC_ID_STK_AVRC, BTTRC_ID_STK_AVRC, AVRC_SetTraceLevel, "TRC_AVRC", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (AVDT_INCLUDED==TRUE)
-    //{BTTRC_ID_AVDT_SCB, BTTRC_ID_AVDT_CCB, NULL, "TRC_AVDT_SCB", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (A2D_INCLUDED==TRUE)
-    {BTTRC_ID_STK_A2D, BTTRC_ID_STK_A2D, A2D_SetTraceLevel, "TRC_A2D", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (BIP_INCLUDED==TRUE)
-    {BTTRC_ID_STK_BIP, BTTRC_ID_STK_BIP, BIP_SetTraceLevel, "TRC_BIP", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (BNEP_INCLUDED==TRUE)
-    {BTTRC_ID_STK_BNEP, BTTRC_ID_STK_BNEP, BNEP_SetTraceLevel, "TRC_BNEP", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (BPP_INCLUDED==TRUE)
-    {BTTRC_ID_STK_BPP, BTTRC_ID_STK_BPP, BPP_SetTraceLevel, "TRC_BPP", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-    {BTTRC_ID_STK_BTM_ACL, BTTRC_ID_STK_BTM_SEC, BTM_SetTraceLevel, "TRC_BTM", DEFAULT_CONF_TRACE_LEVEL},
-#if (DUN_INCLUDED==TRUE)
-    {BTTRC_ID_STK_DUN, BTTRC_ID_STK_DUN, DUN_SetTraceLevel, "TRC_DUN", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (GAP_INCLUDED==TRUE)
-    {BTTRC_ID_STK_GAP, BTTRC_ID_STK_GAP, GAP_SetTraceLevel, "TRC_GAP", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (GOEP_INCLUDED==TRUE)
-    {BTTRC_ID_STK_GOEP, BTTRC_ID_STK_GOEP, GOEP_SetTraceLevel, "TRC_GOEP", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (HCRP_INCLUDED==TRUE)
-    {BTTRC_ID_STK_HCRP, BTTRC_ID_STK_HCRP, HCRP_SetTraceLevel, "TRC_HCRP", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (PAN_INCLUDED==TRUE)
-    {BTTRC_ID_STK_PAN, BTTRC_ID_STK_PAN, PAN_SetTraceLevel, "TRC_PAN", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-#if (SAP_SERVER_INCLUDED==TRUE)
-    {BTTRC_ID_STK_SAP, BTTRC_ID_STK_SAP, NULL, "TRC_SAP", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-    {BTTRC_ID_STK_SDP, BTTRC_ID_STK_SDP, SDP_SetTraceLevel, "TRC_SDP", DEFAULT_CONF_TRACE_LEVEL},
-#if (BLE_INCLUDED==TRUE)
-    {BTTRC_ID_STK_GATT, BTTRC_ID_STK_GATT, GATT_SetTraceLevel, "TRC_GATT", DEFAULT_CONF_TRACE_LEVEL},
-    {BTTRC_ID_STK_SMP, BTTRC_ID_STK_SMP, SMP_SetTraceLevel, "TRC_SMP", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-
-#if (BTA_INCLUDED==TRUE)
-    /* LayerIDs for BTA, currently everything maps onto appl_trace_level.
-     * BTL_GLOBAL_PROP_TRC_FLAG serves as flag in conf.
-     */
-    {BTTRC_ID_BTA_ACC, BTTRC_ID_BTAPP, BTAPP_SetTraceLevel, BTL_GLOBAL_PROP_TRC_FLAG, DEFAULT_CONF_TRACE_LEVEL},
-#endif
-
-#if (BT_TRACE_BTIF == TRUE)
-    {BTTRC_ID_BTA_ACC, BTTRC_ID_BTAPP, BTIF_SetTraceLevel, "TRC_BTIF", DEFAULT_CONF_TRACE_LEVEL},
-#endif
-
-    {0, 0, NULL, NULL, DEFAULT_CONF_TRACE_LEVEL}
-};
-
-const UINT16 bttrc_map_size = sizeof(bttrc_set_level_map)/sizeof(tBTTRC_FUNC_MAP);
-#endif
-
-/********************************************************************************
- **
- **    Function Name:     BTE_InitTraceLevels
- **
- **    Purpose:           This function can be used to set the boot time reading it from the
- **                       platform.
- **                       WARNING: it is called under BTU context and it blocks the BTU task
- **                       till it returns (sync call)
- **
- **    Input Parameters:  None, platform to provide levels
- **    Returns:
- **                       Newly set levels, if any!
- **
- *********************************************************************************/
-BT_API void BTE_InitTraceLevels( void )
-{
-    /* read and set trace levels by calling the different XXX_SetTraceLevel().
-     */
-#if ( BT_USE_TRACES==TRUE )
-    if (trace_conf_enabled == TRUE)
-    {
-        tBTTRC_FUNC_MAP *p_f_map = (tBTTRC_FUNC_MAP *) &bttrc_set_level_map[0];
-
-        while (p_f_map->trc_name != NULL)
-        {
-            ALOGI("BTE_InitTraceLevels -- %s", p_f_map->trc_name);
-
-            if (p_f_map->p_f)
-                p_f_map->p_f(p_f_map->trace_level);
-
-            p_f_map++;
-        }
-    }
-    else
-    {
-        ALOGI("[bttrc] using compile default trace settings");
-    }
-#endif
+  return appl_trace_level;
 }
+
+static uint8_t BTIF_SetTraceLevel(uint8_t new_level) {
+  if (new_level != 0xFF)
+    btif_trace_level = new_level;
+
+  return btif_trace_level;
+}
+
+static uint8_t BTU_SetTraceLevel(uint8_t new_level) {
+  if (new_level != 0xFF)
+    btu_cb.trace_level = new_level;
+
+  return btu_cb.trace_level;
+}
+
+static void load_levels_from_config(const config_t *config) {
+  assert(config != NULL);
+
+  for (tBTTRC_FUNC_MAP *functions = &bttrc_set_level_map[0]; functions->trc_name; ++functions) {
+    LOG_INFO("BTE_InitTraceLevels -- %s", functions->trc_name);
+    int value = config_get_int(config, CONFIG_DEFAULT_SECTION, functions->trc_name, -1);
+    if (value != -1)
+      functions->trace_level = value;
+
+    if (functions->p_f)
+      functions->p_f(functions->trace_level);
+  }
+}
+
+static future_t *init(void) {
+  const stack_config_t *stack_config = stack_config_get_interface();
+  if (!stack_config->get_trace_config_enabled()) {
+    LOG_INFO("[bttrc] using compile default trace settings");
+    return NULL;
+  }
+
+  load_levels_from_config(stack_config->get_all());
+  return NULL;
+}
+
+const module_t bte_logmsg_module = {
+  .name = BTE_LOGMSG_MODULE,
+  .init = init,
+  .start_up = NULL,
+  .shut_down = NULL,
+  .clean_up = NULL,
+  .dependencies = {
+    STACK_CONFIG_MODULE,
+    NULL
+  }
+};
diff --git a/main/bte_main.c b/main/bte_main.c
index 74983e5..de62232 100755
--- a/main/bte_main.c
+++ b/main/bte_main.c
@@ -23,131 +23,66 @@
  *  Description:   Contains BTE core stack initialization and shutdown code
  *
  ******************************************************************************/
-#include <fcntl.h>
-#include <stdlib.h>
-#include <assert.h>
-#include <signal.h>
-#include <string.h>
-#include <time.h>
-#include <hardware/bluetooth.h>
 
-#include "gki.h"
-#include "bd.h"
-#include "btu.h"
-#include "bte.h"
+#define LOG_TAG "bt_main"
+
+#include <assert.h>
+#include <cutils/properties.h>
+#include <fcntl.h>
+#include <hardware/bluetooth.h>
+#include <pthread.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <time.h>
+
+#include "osi/include/alarm.h"
 #include "bta_api.h"
-#include "bt_utils.h"
 #include "bt_hci_bdroid.h"
+#include "bte.h"
+#include "btif_common.h"
+#include "btu.h"
+#include "btsnoop.h"
+#include "bt_utils.h"
+#include "btcore/include/counter.h"
+#include "osi/include/fixed_queue.h"
+#include "osi/include/future.h"
+#include "gki.h"
+#include "osi/include/hash_functions.h"
+#include "osi/include/hash_map.h"
+#include "hci_layer.h"
+#include "btcore/include/module.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "stack_config.h"
+#include "osi/include/thread.h"
 
 /*******************************************************************************
 **  Constants & Macros
 *******************************************************************************/
 
-/* Run-time configuration file */
-#ifndef BTE_STACK_CONF_FILE
-#define BTE_STACK_CONF_FILE "/etc/bluetooth/bt_stack.conf"
-#endif
 /* Run-time configuration file for BLE*/
 #ifndef BTE_BLE_STACK_CONF_FILE
 #define BTE_BLE_STACK_CONF_FILE "/etc/bluetooth/ble_stack.conf"
 #endif
 
-/* if not specified in .txt file then use this as default  */
-#ifndef HCI_LOGGING_FILENAME
-#define HCI_LOGGING_FILENAME  "/data/misc/bluedroid/btsnoop_hci.log"
-#endif
-
-/* Stack preload process timeout period  */
-#ifndef PRELOAD_START_TIMEOUT_MS
-#define PRELOAD_START_TIMEOUT_MS 3000  // 3 seconds
-#endif
-
-/* Stack preload process maximum retry attempts  */
-#ifndef PRELOAD_MAX_RETRY_ATTEMPTS
-#define PRELOAD_MAX_RETRY_ATTEMPTS 0
-#endif
-
-/*******************************************************************************
-**  Local type definitions
-*******************************************************************************/
-/* Preload retry control block */
-typedef struct
-{
-    int     retry_counts;
-    BOOLEAN timer_created;
-    timer_t timer_id;
-} bt_preload_retry_cb_t;
-
 /******************************************************************************
 **  Variables
 ******************************************************************************/
-BOOLEAN hci_logging_enabled = FALSE;    /* by default, turn hci log off */
-BOOLEAN hci_logging_config = FALSE;    /* configured from bluetooth framework */
-BOOLEAN hci_save_log = FALSE; /* save a copy of the log before starting again */
-char hci_logfile[256] = HCI_LOGGING_FILENAME;
 
 /*******************************************************************************
 **  Static variables
 *******************************************************************************/
-static bt_hc_interface_t *bt_hc_if=NULL;
-static const bt_hc_callbacks_t hc_callbacks;
-static BOOLEAN lpm_enabled = FALSE;
-static bt_preload_retry_cb_t preload_retry_cb;
-// Lock to serialize cleanup requests from upper layer.
-static pthread_mutex_t cleanup_lock;
+static const hci_t *hci;
 
 /*******************************************************************************
 **  Static functions
 *******************************************************************************/
-static void bte_main_in_hw_init(void);
-static void bte_hci_enable(void);
-static void bte_hci_disable(void);
-static void preload_start_wait_timer(void);
-static void preload_stop_wait_timer(void);
 
 /*******************************************************************************
 **  Externs
 *******************************************************************************/
-BTU_API extern UINT32 btu_task (UINT32 param);
-BTU_API extern void BTE_Init (void);
-BT_API extern void BTE_LoadStack(void);
-BT_API void BTE_UnloadStack(void);
-extern void scru_flip_bda (BD_ADDR dst, const BD_ADDR src);
-extern void bte_load_conf(const char *p_path);
 extern void bte_load_ble_conf(const char *p_path);
-extern bt_bdaddr_t btif_local_bd_addr;
-
-
-/*******************************************************************************
-**                        System Task Configuration
-*******************************************************************************/
-
-/* bluetooth protocol stack (BTU) task */
-#ifndef BTE_BTU_STACK_SIZE
-#define BTE_BTU_STACK_SIZE       0//0x2000         /* In bytes */
-#endif
-#define BTE_BTU_TASK_STR        ((INT8 *) "BTU")
-UINT32 bte_btu_stack[(BTE_BTU_STACK_SIZE + 3) / 4];
-
-/******************************************************************************
-**
-** Function         bte_main_in_hw_init
-**
-** Description      Internal helper function for chip hardware init
-**
-** Returns          None
-**
-******************************************************************************/
-static void bte_main_in_hw_init(void)
-{
-    if ( (bt_hc_if = (bt_hc_interface_t *) bt_hc_get_interface()) \
-         == NULL)
-    {
-        APPL_TRACE_ERROR("!!! Failed to get BtHostControllerInterface !!!");
-    }
-
-    memset(&preload_retry_cb, 0, sizeof(bt_preload_retry_cb_t));
-}
+fixed_queue_t *btu_hci_msg_queue;
 
 /******************************************************************************
 **
@@ -160,23 +95,26 @@
 ******************************************************************************/
 void bte_main_boot_entry(void)
 {
-    /* initialize OS */
-    GKI_init();
+    module_init(get_module(GKI_MODULE));
+    module_init(get_module(COUNTER_MODULE));
 
-    bte_main_in_hw_init();
+    hci = hci_layer_get_interface();
+    if (!hci)
+      LOG_ERROR("%s could not get hci layer interface.", __func__);
 
-    bte_load_conf(BTE_STACK_CONF_FILE);
+    btu_hci_msg_queue = fixed_queue_new(SIZE_MAX);
+    if (btu_hci_msg_queue == NULL) {
+      LOG_ERROR("%s unable to allocate hci message queue.", __func__);
+      return;
+    }
+
+    data_dispatcher_register_default(hci->event_dispatcher, btu_hci_msg_queue);
+    hci->set_data_queue(btu_hci_msg_queue);
+
 #if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
     bte_load_ble_conf(BTE_BLE_STACK_CONF_FILE);
 #endif
-
-#if (BTTRC_INCLUDED == TRUE)
-    /* Initialize trace feature */
-    BTTRC_TraceInit(MAX_TRACE_RAM_SIZE, &BTE_TraceLogBuf[0], BTTRC_METHOD_RAM);
-#endif
-
-    pthread_mutex_init(&cleanup_lock, NULL);
-
+    module_init(get_module(STACK_CONFIG_MODULE));
 }
 
 /******************************************************************************
@@ -190,9 +128,16 @@
 ******************************************************************************/
 void bte_main_shutdown()
 {
-    pthread_mutex_destroy(&cleanup_lock);
+    data_dispatcher_register_default(hci_layer_get_interface()->event_dispatcher, NULL);
+    hci->set_data_queue(NULL);
+    fixed_queue_free(btu_hci_msg_queue, NULL);
 
-    GKI_shutdown();
+    btu_hci_msg_queue = NULL;
+
+    module_clean_up(get_module(STACK_CONFIG_MODULE));
+
+    module_clean_up(get_module(COUNTER_MODULE));
+    module_clean_up(get_module(GKI_MODULE));
 }
 
 /******************************************************************************
@@ -209,18 +154,10 @@
 {
     APPL_TRACE_DEBUG("%s", __FUNCTION__);
 
-    /* Initialize BTE control block */
-    BTE_Init();
+    module_start_up(get_module(BTSNOOP_MODULE));
+    module_start_up(get_module(HCI_MODULE));
 
-    lpm_enabled = FALSE;
-
-    GKI_create_task((TASKPTR)btu_task, BTU_TASK, BTE_BTU_TASK_STR,
-                    (UINT16 *) ((UINT8 *)bte_btu_stack + BTE_BTU_STACK_SIZE),
-                    sizeof(bte_btu_stack));
-
-    bte_hci_enable();
-
-    GKI_run();
+    BTU_StartUp();
 }
 
 /******************************************************************************
@@ -237,203 +174,10 @@
 {
     APPL_TRACE_DEBUG("%s", __FUNCTION__);
 
-    preload_stop_wait_timer();
-    bte_hci_disable();
-    GKI_destroy_task(BTU_TASK);
-}
+    module_shut_down(get_module(HCI_MODULE));
+    module_shut_down(get_module(BTSNOOP_MODULE));
 
-/******************************************************************************
-**
-** Function         bte_main_config_hci_logging
-**
-** Description      enable or disable HIC snoop logging
-**
-** Returns          None
-**
-******************************************************************************/
-void bte_main_config_hci_logging(BOOLEAN enable, BOOLEAN bt_disabled)
-{
-    int old = (hci_logging_enabled == TRUE) || (hci_logging_config == TRUE);
-    int new;
-
-    if (enable) {
-        hci_logging_config = TRUE;
-    } else {
-        hci_logging_config = FALSE;
-    }
-
-    new = (hci_logging_enabled == TRUE) || (hci_logging_config == TRUE);
-
-    if ((old == new) || bt_disabled || (bt_hc_if == NULL)) {
-        return;
-    }
-
-    bt_hc_if->logging(new ? BT_HC_LOGGING_ON : BT_HC_LOGGING_OFF, hci_logfile, hci_save_log);
-}
-
-/******************************************************************************
-**
-** Function         bte_hci_enable
-**
-** Description      Enable HCI & Vendor modules
-**
-** Returns          None
-**
-******************************************************************************/
-static void bte_hci_enable(void)
-{
-    APPL_TRACE_DEBUG("%s", __FUNCTION__);
-
-    preload_start_wait_timer();
-
-    if (bt_hc_if)
-    {
-        int result = bt_hc_if->init(&hc_callbacks, btif_local_bd_addr.address);
-        APPL_TRACE_EVENT("libbt-hci init returns %d", result);
-
-        assert(result == BT_HC_STATUS_SUCCESS);
-
-        if (hci_logging_enabled == TRUE || hci_logging_config == TRUE)
-            bt_hc_if->logging(BT_HC_LOGGING_ON, hci_logfile, hci_save_log);
-
-#if (defined (BT_CLEAN_TURN_ON_DISABLED) && BT_CLEAN_TURN_ON_DISABLED == TRUE)
-        APPL_TRACE_DEBUG("%s  Not Turninig Off the BT before Turninig ON", __FUNCTION__);
-
-        /* Do not power off the chip before powering on  if BT_CLEAN_TURN_ON_DISABLED flag
-         is defined and set to TRUE to avoid below mentioned issue.
-
-         Wingray kernel driver maintains a combined  counter to keep track of
-         BT-Wifi state. Invoking  set_power(BT_HC_CHIP_PWR_OFF) when the BT is already
-         in OFF state causes this counter to be incorrectly decremented and results in undesired
-         behavior of the chip.
-
-         This is only a workaround and when the issue is fixed in the kernel this work around
-         should be removed. */
-#else
-        /* toggle chip power to ensure we will reset chip in case
-           a previous stack shutdown wasn't completed gracefully */
-        bt_hc_if->set_power(BT_HC_CHIP_PWR_OFF);
-#endif
-        bt_hc_if->set_power(BT_HC_CHIP_PWR_ON);
-
-        bt_hc_if->preload(NULL);
-    }
-}
-
-/******************************************************************************
-**
-** Function         bte_hci_disable
-**
-** Description      Disable HCI & Vendor modules
-**
-** Returns          None
-**
-******************************************************************************/
-static void bte_hci_disable(void)
-{
-    APPL_TRACE_DEBUG("%s", __FUNCTION__);
-
-    if (!bt_hc_if)
-        return;
-
-    // Cleanup is not thread safe and must be protected.
-    pthread_mutex_lock(&cleanup_lock);
-
-    if (hci_logging_enabled == TRUE ||  hci_logging_config == TRUE)
-        bt_hc_if->logging(BT_HC_LOGGING_OFF, hci_logfile, hci_save_log);
-    bt_hc_if->cleanup();
-
-    pthread_mutex_unlock(&cleanup_lock);
-}
-
-/*******************************************************************************
-**
-** Function        preload_wait_timeout
-**
-** Description     Timeout thread of preload watchdog timer
-**
-** Returns         None
-**
-*******************************************************************************/
-static void preload_wait_timeout(union sigval arg)
-{
-    UNUSED(arg);
-
-    APPL_TRACE_ERROR("...preload_wait_timeout (retried:%d/max-retry:%d)...",
-                        preload_retry_cb.retry_counts,
-                        PRELOAD_MAX_RETRY_ATTEMPTS);
-
-    if (preload_retry_cb.retry_counts++ < PRELOAD_MAX_RETRY_ATTEMPTS)
-    {
-        bte_hci_disable();
-        GKI_delay(100);
-        bte_hci_enable();
-    }
-    else
-    {
-        /* Notify BTIF_TASK that the init procedure had failed*/
-        GKI_send_event(BTIF_TASK, BT_EVT_HARDWARE_INIT_FAIL);
-    }
-}
-
-/*******************************************************************************
-**
-** Function        preload_start_wait_timer
-**
-** Description     Launch startup watchdog timer
-**
-** Returns         None
-**
-*******************************************************************************/
-static void preload_start_wait_timer(void)
-{
-    int status;
-    struct itimerspec ts;
-    struct sigevent se;
-    UINT32 timeout_ms = PRELOAD_START_TIMEOUT_MS;
-
-    if (preload_retry_cb.timer_created == FALSE)
-    {
-        se.sigev_notify = SIGEV_THREAD;
-        se.sigev_value.sival_ptr = &preload_retry_cb.timer_id;
-        se.sigev_notify_function = preload_wait_timeout;
-        se.sigev_notify_attributes = NULL;
-
-        status = timer_create(CLOCK_MONOTONIC, &se, &preload_retry_cb.timer_id);
-
-        if (status == 0)
-            preload_retry_cb.timer_created = TRUE;
-    }
-
-    if (preload_retry_cb.timer_created == TRUE)
-    {
-        ts.it_value.tv_sec = timeout_ms/1000;
-        ts.it_value.tv_nsec = 1000000*(timeout_ms%1000);
-        ts.it_interval.tv_sec = 0;
-        ts.it_interval.tv_nsec = 0;
-
-        status = timer_settime(preload_retry_cb.timer_id, 0, &ts, 0);
-        if (status == -1)
-            APPL_TRACE_ERROR("Failed to fire preload watchdog timer");
-    }
-}
-
-/*******************************************************************************
-**
-** Function        preload_stop_wait_timer
-**
-** Description     Stop preload watchdog timer
-**
-** Returns         None
-**
-*******************************************************************************/
-static void preload_stop_wait_timer(void)
-{
-    if (preload_retry_cb.timer_created == TRUE)
-    {
-        timer_delete(preload_retry_cb.timer_id);
-        preload_retry_cb.timer_created = FALSE;
-    }
+    BTU_ShutDown();
 }
 
 /******************************************************************************
@@ -447,8 +191,7 @@
 ******************************************************************************/
 void bte_main_postload_cfg(void)
 {
-    if (bt_hc_if)
-        bt_hc_if->postload(NULL);
+    hci->do_postload();
 }
 
 #if (defined(HCILP_INCLUDED) && HCILP_INCLUDED == TRUE)
@@ -463,14 +206,7 @@
 ******************************************************************************/
 void bte_main_enable_lpm(BOOLEAN enable)
 {
-    int result = -1;
-
-    if (bt_hc_if)
-        result = bt_hc_if->lpm( \
-        (enable == TRUE) ? BT_HC_LPM_ENABLE : BT_HC_LPM_DISABLE \
-        );
-
-    APPL_TRACE_EVENT("HC lib lpm enable=%d return %d", enable, result);
+    hci->send_low_power_command(enable ? LPM_ENABLE : LPM_DISABLE);
 }
 
 /******************************************************************************
@@ -484,12 +220,7 @@
 ******************************************************************************/
 void bte_main_lpm_allow_bt_device_sleep()
 {
-    int result = -1;
-
-    if ((bt_hc_if) && (lpm_enabled == TRUE))
-        result = bt_hc_if->lpm(BT_HC_LPM_WAKE_DEASSERT);
-
-    APPL_TRACE_DEBUG("HC lib lpm deassertion return %d", result);
+    hci->send_low_power_command(LPM_WAKE_DEASSERT);
 }
 
 /******************************************************************************
@@ -503,75 +234,10 @@
 ******************************************************************************/
 void bte_main_lpm_wake_bt_device()
 {
-    int result = -1;
-
-    if ((bt_hc_if) && (lpm_enabled == TRUE))
-        result = bt_hc_if->lpm(BT_HC_LPM_WAKE_ASSERT);
-
-    APPL_TRACE_DEBUG("HC lib lpm assertion return %d", result);
+    hci->send_low_power_command(LPM_WAKE_ASSERT);
 }
 #endif  // HCILP_INCLUDED
 
-
-/* NOTICE:
- *  Definitions for audio state structure, this type needs to match to
- *  the bt_vendor_op_audio_state_t type defined in bt_vendor_lib.h
- */
-typedef struct {
-    UINT16  handle;
-    UINT16  peer_codec;
-    UINT16  state;
-} bt_hc_audio_state_t;
-
-struct bt_audio_state_tag {
-    BT_HDR hdr;
-    bt_hc_audio_state_t audio;
-};
-
-/******************************************************************************
-**
-** Function         set_audio_state
-**
-** Description      Sets audio state on controller state for SCO (PCM, WBS, FM)
-**
-** Parameters       handle: codec related handle for SCO: sco cb idx, unused for
-**                  codec: BTA_AG_CODEC_MSBC, BTA_AG_CODEC_CSVD or FM codec
-**                  state: codec state, eg. BTA_AG_CO_AUD_STATE_SETUP
-**                  param: future extensions, e.g. call-in structure/event.
-**
-** Returns          None
-**
-******************************************************************************/
-int set_audio_state(UINT16 handle, UINT16 codec, UINT8 state, void *param)
-{
-    struct bt_audio_state_tag *p_msg;
-    int result = -1;
-
-    APPL_TRACE_API("set_audio_state(handle: %d, codec: 0x%x, state: %d)", handle,
-                    codec, state);
-    if (NULL != param)
-        APPL_TRACE_WARNING("set_audio_state() non-null param not supported");
-    p_msg = (struct bt_audio_state_tag *)GKI_getbuf(sizeof(*p_msg));
-    if (!p_msg)
-        return result;
-    p_msg->audio.handle = handle;
-    p_msg->audio.peer_codec = codec;
-    p_msg->audio.state = state;
-
-    p_msg->hdr.event = MSG_CTRL_TO_HC_CMD | (MSG_SUB_EVT_MASK & BT_HC_AUDIO_STATE);
-    p_msg->hdr.len = sizeof(p_msg->audio);
-    p_msg->hdr.offset = 0;
-    /* layer_specific shall contain return path event! for BTA events!
-     * 0 means no return message is expected. */
-    p_msg->hdr.layer_specific = 0;
-       if (bt_hc_if)
-       {
-        bt_hc_if->tx_cmd((TRANSAC)p_msg, (char *)(&p_msg->audio), sizeof(*p_msg));
-        }
-    return result;
-}
-
-
 /******************************************************************************
 **
 ** Function         bte_main_hci_send
@@ -590,16 +256,13 @@
 
     p_msg->event = event;
 
+    counter_add("main.tx.packets", 1);
+    counter_add("main.tx.bytes", p_msg->len);
 
     if((sub_event == LOCAL_BR_EDR_CONTROLLER_ID) || \
        (sub_event == LOCAL_BLE_CONTROLLER_ID))
     {
-        if (bt_hc_if)
-            bt_hc_if->transmit_buf((TRANSAC)p_msg, \
-                                       (char *) (p_msg + 1), \
-                                        p_msg->len);
-        else
-            GKI_freebuf(p_msg);
+        hci->transmit_downward(event, p_msg);
     }
     else
     {
@@ -607,240 +270,3 @@
         GKI_freebuf(p_msg);
     }
 }
-
-/******************************************************************************
-**
-** Function         bte_main_post_reset_init
-**
-** Description      BTE MAIN API - This function is mapped to BTM_APP_DEV_INIT
-**                  and shall be automatically called from BTE after HCI_Reset
-**
-** Returns          None
-**
-******************************************************************************/
-void bte_main_post_reset_init()
-{
-    BTM_ContinueReset();
-}
-
-/*****************************************************************************
-**
-**   libbt-hci Callback Functions
-**
-*****************************************************************************/
-
-/******************************************************************************
-**
-** Function         preload_cb
-**
-** Description      HOST/CONTROLLER LIB CALLBACK API - This function is called
-**                  when the libbt-hci completed stack preload process
-**
-** Returns          None
-**
-******************************************************************************/
-static void preload_cb(TRANSAC transac, bt_hc_preload_result_t result)
-{
-    UNUSED(transac);
-
-    APPL_TRACE_EVENT("HC preload_cb %d [0:SUCCESS 1:FAIL]", result);
-
-    if (result == BT_HC_PRELOAD_SUCCESS)
-    {
-        preload_stop_wait_timer();
-
-        /* notify BTU task that libbt-hci is ready */
-        GKI_send_event(BTU_TASK, BT_EVT_PRELOAD_CMPL);
-    }
-}
-
-/******************************************************************************
-**
-** Function         postload_cb
-**
-** Description      HOST/CONTROLLER LIB CALLBACK API - This function is called
-**                  when the libbt-hci lib completed stack postload process
-**
-** Returns          None
-**
-******************************************************************************/
-static void postload_cb(TRANSAC transac, bt_hc_postload_result_t result)
-{
-    UNUSED(transac);
-
-    APPL_TRACE_EVENT("HC postload_cb %d", result);
-}
-
-/******************************************************************************
-**
-** Function         lpm_cb
-**
-** Description      HOST/CONTROLLER LIB CALLBACK API - This function is called
-**                  back from the libbt-hci to indicate the current LPM state
-**
-** Returns          None
-**
-******************************************************************************/
-static void lpm_cb(bt_hc_lpm_request_result_t result)
-{
-    APPL_TRACE_EVENT("HC lpm_result_cb %d", result);
-    lpm_enabled = (result == BT_HC_LPM_ENABLED) ? TRUE : FALSE;
-}
-
-/******************************************************************************
-**
-** Function         hostwake_ind
-**
-** Description      HOST/CONTROLLER LIB CALLOUT API - This function is called
-**                  from the libbt-hci to indicate the HostWake event
-**
-** Returns          None
-**
-******************************************************************************/
-static void hostwake_ind(bt_hc_low_power_event_t event)
-{
-    APPL_TRACE_EVENT("HC hostwake_ind %d", event);
-}
-
-/******************************************************************************
-**
-** Function         alloc
-**
-** Description      HOST/CONTROLLER LIB CALLOUT API - This function is called
-**                  from the libbt-hci to request for data buffer allocation
-**
-** Returns          NULL / pointer to allocated buffer
-**
-******************************************************************************/
-static char *alloc(int size)
-{
-    BT_HDR *p_hdr = NULL;
-
-    /*
-    APPL_TRACE_DEBUG("HC alloc size=%d", size);
-    */
-
-    /* Requested buffer size cannot exceed GKI_MAX_BUF_SIZE. */
-    if (size > GKI_MAX_BUF_SIZE)
-    {
-         APPL_TRACE_ERROR("HCI DATA SIZE %d greater than MAX %d",
-                           size, GKI_MAX_BUF_SIZE);
-         return NULL;
-    }
-
-    p_hdr = (BT_HDR *) GKI_getbuf ((UINT16) size);
-
-    if (p_hdr == NULL)
-    {
-        APPL_TRACE_WARNING("alloc returns NO BUFFER! (sz %d)", size);
-    }
-
-    return ((char *) p_hdr);
-}
-
-/******************************************************************************
-**
-** Function         dealloc
-**
-** Description      HOST/CONTROLLER LIB CALLOUT API - This function is called
-**                  from the libbt-hci to release the data buffer allocated
-**                  through the alloc call earlier
-**
-**                  Bluedroid libbt-hci library uses 'transac' parameter to
-**                  pass data-path buffer/packet across bt_hci_lib interface
-**                  boundary.
-**
-******************************************************************************/
-static void dealloc(TRANSAC transac)
-{
-    GKI_freebuf(transac);
-}
-
-/******************************************************************************
-**
-** Function         data_ind
-**
-** Description      HOST/CONTROLLER LIB CALLOUT API - This function is called
-**                  from the libbt-hci to pass in the received HCI packets
-**
-**                  The core stack is responsible for releasing the data buffer
-**                  passed in from the libbt-hci once the core stack has done
-**                  with it.
-**
-**                  Bluedroid libbt-hci library uses 'transac' parameter to
-**                  pass data-path buffer/packet across bt_hci_lib interface
-**                  boundary. The 'p_buf' and 'len' parameters are not intended
-**                  to be used here but might point to data portion in data-
-**                  path buffer and length of valid data respectively.
-**
-** Returns          bt_hc_status_t
-**
-******************************************************************************/
-static int data_ind(TRANSAC transac, char *p_buf, int len)
-{
-    UNUSED(p_buf);
-    UNUSED(len);
-
-    /*
-    APPL_TRACE_DEBUG("HC data_ind event=0x%04X (len=%d)", p_msg->event, len);
-    */
-
-    GKI_send_msg (BTU_TASK, BTU_HCI_RCV_MBOX, transac);
-    return BT_HC_STATUS_SUCCESS;
-}
-
-/******************************************************************************
-**
-** Function         tx_result
-**
-** Description      HOST/CONTROLLER LIB CALLBACK API - This function is called
-**                  from the libbt-hci once it has processed/sent the prior data
-**                  buffer which core stack passed to it through transmit_buf
-**                  call earlier.
-**
-**                  The core stack is responsible for releasing the data buffer
-**                  if it has been completedly processed.
-**
-**                  Bluedroid libbt-hci library uses 'transac' parameter to
-**                  pass data-path buffer/packet across bt_hci_lib interface
-**                  boundary. The 'p_buf' is not intended to be used here
-**                  but might point to data portion in data-path buffer.
-**
-** Returns          bt_hc_status_t
-**
-******************************************************************************/
-static int tx_result(TRANSAC transac, char *p_buf, bt_hc_transmit_result_t result)
-{
-    UNUSED(p_buf);
-    /*
-    APPL_TRACE_DEBUG("HC tx_result %d (event=%04X)", result, \
-                      ((BT_HDR *)transac)->event);
-    */
-
-    if (result == BT_HC_TX_FRAGMENT)
-    {
-        GKI_send_msg (BTU_TASK, BTU_HCI_RCV_MBOX, transac);
-    }
-    else
-    {
-        GKI_freebuf(transac);
-    }
-
-    return BT_HC_STATUS_SUCCESS;
-}
-
-/*****************************************************************************
-**   The libbt-hci Callback Functions Table
-*****************************************************************************/
-static const bt_hc_callbacks_t hc_callbacks = {
-    sizeof(bt_hc_callbacks_t),
-    preload_cb,
-    postload_cb,
-    lpm_cb,
-    hostwake_ind,
-    alloc,
-    dealloc,
-    data_ind,
-    tx_result
-};
-
diff --git a/main/stack_config.c b/main/stack_config.c
new file mode 100644
index 0000000..6e1431e
--- /dev/null
+++ b/main/stack_config.c
@@ -0,0 +1,99 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_stack_config"
+
+#include <assert.h>
+
+#include "osi/include/future.h"
+#include "stack_config.h"
+#include "osi/include/log.h"
+
+const char *BTSNOOP_LOG_PATH_KEY = "BtSnoopFileName";
+const char *BTSNOOP_TURNED_ON_KEY = "BtSnoopLogOutput";
+const char *BTSNOOP_SHOULD_SAVE_LAST_KEY = "BtSnoopSaveLog";
+const char *TRACE_CONFIG_ENABLED_KEY = "TraceConf";
+
+static config_t *config;
+
+// Module lifecycle functions
+
+static future_t *init() {
+  const char *path = "/etc/bluetooth/bt_stack.conf";
+  assert(path != NULL);
+
+  LOG_INFO("%s attempt to load stack conf from %s", __func__, path);
+
+  config = config_new(path);
+  if (!config) {
+    LOG_INFO("%s file >%s< not found", __func__, path);
+    return future_new_immediate(FUTURE_FAIL);
+  }
+
+  return future_new_immediate(FUTURE_SUCCESS);
+}
+
+static future_t *clean_up() {
+  config_free(config);
+  return future_new_immediate(FUTURE_SUCCESS);
+}
+
+const module_t stack_config_module = {
+  .name = STACK_CONFIG_MODULE,
+  .init = init,
+  .start_up = NULL,
+  .shut_down = NULL,
+  .clean_up = clean_up,
+  .dependencies = {
+    NULL
+  }
+};
+
+// Interface functions
+
+static const char *get_btsnoop_log_path(void) {
+  return config_get_string(config, CONFIG_DEFAULT_SECTION, BTSNOOP_LOG_PATH_KEY, "/data/misc/bluedroid/btsnoop_hci.log");
+}
+
+static bool get_btsnoop_turned_on(void) {
+  return config_get_bool(config, CONFIG_DEFAULT_SECTION, BTSNOOP_TURNED_ON_KEY, false);
+}
+
+static bool get_btsnoop_should_save_last(void) {
+  return config_get_bool(config, CONFIG_DEFAULT_SECTION, BTSNOOP_SHOULD_SAVE_LAST_KEY, false);
+}
+
+static bool get_trace_config_enabled(void) {
+  return config_get_bool(config, CONFIG_DEFAULT_SECTION, TRACE_CONFIG_ENABLED_KEY, false);
+}
+
+static config_t *get_all(void) {
+  return config;
+}
+
+const stack_config_t interface = {
+  get_btsnoop_log_path,
+  get_btsnoop_turned_on,
+  get_btsnoop_should_save_last,
+  get_trace_config_enabled,
+  get_all
+};
+
+const stack_config_t *stack_config_get_interface() {
+  return &interface;
+}
diff --git a/osi/Android.mk b/osi/Android.mk
index 91f76ef..c299f3a 100644
--- a/osi/Android.mk
+++ b/osi/Android.mk
@@ -1,17 +1,47 @@
+ ##############################################################################
+ #
+ #  Copyright (C) 2014 Google, Inc.
+ #
+ #  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.
+ #
+ ##############################################################################
+
 LOCAL_PATH := $(call my-dir)
 
 include $(CLEAR_VARS)
 
 LOCAL_C_INCLUDES := \
-    $(LOCAL_PATH)/include
+    $(LOCAL_PATH)/include \
+    $(LOCAL_PATH)/..
 
 LOCAL_SRC_FILES := \
     ./src/alarm.c \
+    ./src/allocation_tracker.c \
+    ./src/allocator.c \
+    ./src/array.c \
+    ./src/buffer.c \
     ./src/config.c \
+    ./src/data_dispatcher.c \
+    ./src/eager_reader.c \
     ./src/fixed_queue.c \
+    ./src/future.c \
+    ./src/hash_functions.c \
+    ./src/hash_map.c \
     ./src/list.c \
+    ./src/non_repeating_timer.c \
     ./src/reactor.c \
     ./src/semaphore.c \
+    ./src/socket.c \
     ./src/thread.c
 
 LOCAL_CFLAGS := -std=c99 -Wall -Werror
@@ -27,17 +57,27 @@
 include $(CLEAR_VARS)
 
 LOCAL_C_INCLUDES := \
-    $(LOCAL_PATH)/include
+    $(LOCAL_PATH)/include \
+    $(LOCAL_PATH)/..
 
 LOCAL_SRC_FILES := \
+    ./test/AlarmTestHarness.cpp \
+    ./test/AllocationTestHarness.cpp \
     ./test/alarm_test.cpp \
+    ./test/allocation_tracker_test.cpp \
+    ./test/array_test.cpp \
+    ./test/atomic_test.cpp \
     ./test/config_test.cpp \
+    ./test/data_dispatcher_test.cpp \
+    ./test/eager_reader_test.cpp \
+    ./test/future_test.cpp \
+    ./test/hash_map_test.cpp \
     ./test/list_test.cpp \
     ./test/reactor_test.cpp \
     ./test/thread_test.cpp
 
 LOCAL_CFLAGS := -Wall -Werror
-LOCAL_MODULE := ositests
+LOCAL_MODULE := net_test_osi
 LOCAL_MODULE_TAGS := tests
 LOCAL_SHARED_LIBRARIES := liblog
 LOCAL_STATIC_LIBRARIES := libosi
diff --git a/osi/include/alarm.h b/osi/include/alarm.h
index 7e687ba..b27e9a4 100644
--- a/osi/include/alarm.h
+++ b/osi/include/alarm.h
@@ -18,6 +18,8 @@
 
 #pragma once
 
+#include <stdint.h>
+
 typedef struct alarm_t alarm_t;
 typedef uint64_t period_ms_t;
 
@@ -40,6 +42,10 @@
 // |alarm| and |cb| may not be NULL.
 void alarm_set(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data);
 
+// Like alarm_set, except the alarm repeats every |period| ms until it is cancelled or
+// freed or |alarm_set| is called to set it non-periodically.
+void alarm_set_periodic(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data);
+
 // This function cancels the |alarm| if it was previously set. When this call
 // returns, the caller has a guarantee that the callback is not in progress and
 // will not be called if it hasn't already been called. This function is idempotent.
diff --git a/osi/include/allocation_tracker.h b/osi/include/allocation_tracker.h
new file mode 100644
index 0000000..fb9781b
--- /dev/null
+++ b/osi/include/allocation_tracker.h
@@ -0,0 +1,56 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stddef.h>
+
+typedef struct allocation_tracker_t allocation_tracker_t;
+typedef uint8_t allocator_id_t;
+
+// Initialize the allocation tracker. If you do not call this function,
+// the allocation tracker functions do nothing but are still safe to call.
+void allocation_tracker_init(void);
+
+// Reset the allocation tracker. Don't call this in the normal course of
+// operations. Useful mostly for testing.
+void allocation_tracker_reset(void);
+
+// Expects that there are no allocations at the time of this call. Dumps
+// information about unfreed allocations to the log. Returns the amount of
+// unallocated memory.
+size_t allocation_tracker_expect_no_allocations(void);
+
+// Notify the tracker of a new allocation belonging to |allocator_id|.
+// If |ptr| is NULL, this function does nothing. |requested_size| is the
+// size of the allocation without any canaries. The caller must allocate
+// enough memory for canaries; the total allocation size can be determined
+// by calling |allocation_tracker_resize_for_canary|. Returns |ptr| offset
+// to the the beginning of the uncanaried region.
+void *allocation_tracker_notify_alloc(allocator_id_t allocator_id, void *ptr, size_t requested_size);
+
+// Notify the tracker of an allocation that is being freed. |ptr| must be a
+// pointer returned by a call to |allocation_tracker_notify_alloc| with the
+// same |allocator_id|. If |ptr| is NULL, this function does nothing. Returns
+// |ptr| offset to the real beginning of the allocation including any canary
+// space.
+void *allocation_tracker_notify_free(allocator_id_t allocator_id, void *ptr);
+
+// Get the full size for an allocation, taking into account the size of canaries.
+size_t allocation_tracker_resize_for_canary(size_t size);
diff --git a/test/suite/support/property.h b/osi/include/allocator.h
similarity index 62%
copy from test/suite/support/property.h
copy to osi/include/allocator.h
index a8b77c7..0de4727 100644
--- a/test/suite/support/property.h
+++ b/osi/include/allocator.h
@@ -18,15 +18,22 @@
 
 #pragma once
 
-#include "base.h"
+#include <stddef.h>
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+typedef void *(*alloc_fn)(size_t size);
+typedef void (*free_fn)(void *ptr);
 
-const char *property_extract_name(const bt_property_t *property);
+typedef struct {
+  alloc_fn alloc;
+  free_fn  free;
+} allocator_t;
 
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
+// allocator_t abstractions for the osi_*alloc and osi_free functions
+extern const allocator_t allocator_malloc;
+extern const allocator_t allocator_calloc;
 
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+char *osi_strdup(const char *str);
+
+void *osi_malloc(size_t size);
+void *osi_calloc(size_t size);
+void osi_free(void *ptr);
diff --git a/osi/include/array.h b/osi/include/array.h
new file mode 100644
index 0000000..06b93f6
--- /dev/null
+++ b/osi/include/array.h
@@ -0,0 +1,57 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+typedef struct array_t array_t;
+
+// Returns a new array object that stores elements of size |element_size|. The returned
+// object must be freed with |array_free|. |element_size| must be greater than 0. Returns
+// NULL on failure.
+array_t *array_new(size_t element_size);
+
+// Frees an array that was allocated with |array_new|. |array| may be NULL.
+void array_free(array_t *array);
+
+// Returns a pointer to the first stored element in |array|. |array| must not be NULL.
+void *array_ptr(const array_t *array);
+
+// Returns a pointer to the |index|th element of |array|. |index| must be less than
+// the array's length. |array| must not be NULL.
+void *array_at(const array_t *array, size_t index);
+
+// Returns the number of elements stored in |array|. |array| must not be NULL.
+size_t array_length(const array_t *array);
+
+// Inserts an element to the end of |array| by value. For example, a caller
+// may simply call array_append_value(array, 5) instead of storing 5 into a
+// variable and then inserting by pointer. Although |value| is a uint32_t,
+// only the lowest |element_size| bytes will be stored. |array| must not be
+// NULL. Returns true if the element could be inserted into the array, false
+// on error.
+bool array_append_value(array_t *array, uint32_t value);
+
+// Inserts an element to the end of |array|. The value pointed to by |data| must
+// be at least |element_size| bytes long and will be copied into the array. Neither
+// |array| nor |data| may be NULL. Returns true if the element could be inserted into
+// the array, false on error.
+bool array_append_ptr(array_t *array, void *data);
diff --git a/osi/include/atomic.h b/osi/include/atomic.h
new file mode 100644
index 0000000..beac2f1
--- /dev/null
+++ b/osi/include/atomic.h
@@ -0,0 +1,115 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+
+// Set of atomic operations to work on data structures.
+// The atomic type data should only be manipulated by these functions.
+// This uses the gcc built in functions.
+//  gcc doc section 6.50 "Built-in functions for memory model aware atomic operations"
+//
+// Data types:
+// atomic_<name>_t
+//
+// e.g.
+//  atomic_s32_t for a signed 32 bit integer.
+//  atomic_u32_t for an unsigned 32 bit integer.
+//
+// Functions:
+// atomic_<operation>_<name>(atomic_t *, ...)
+//
+// e.g.
+//  uint32_t atomic_dec_prefix_u32(volatile atomic_u32_t *atomic)
+//
+// The prefix/postfix classification corresponds which value is returned
+// from the function call, the old or the new one.
+
+#if defined(GCC_VERSION) && GCC_VERSION < 40700
+#warning "Atomics not supported"
+#endif
+
+#define ATOMIC_TYPE(name, type) \
+  struct atomic_##name { \
+    type _val; \
+}; \
+typedef struct atomic_##name atomic_##name##_t;
+
+#define ATOMIC_STORE(name, type, sz) \
+inline void atomic_store_##name(volatile atomic_##name##_t *atomic, type val) { \
+  __atomic_store_##sz(&atomic->_val, val, __ATOMIC_SEQ_CST); \
+}
+
+#define ATOMIC_LOAD(name, type, sz) \
+inline type atomic_load_##name(volatile atomic_##name##_t *atomic) { \
+  return __atomic_load_##sz(&atomic->_val, __ATOMIC_SEQ_CST); \
+}
+
+// Returns value after operation, e.g. new value
+#define ATOMIC_INC_PREFIX(name, type, sz) \
+inline type atomic_inc_prefix_##name(volatile atomic_##name##_t *atomic) { \
+  return __atomic_add_fetch_##sz(atomic, 1, __ATOMIC_SEQ_CST); \
+}
+
+// Returns value after operation, e.g. new value
+#define ATOMIC_DEC_PREFIX(name, type, sz) \
+inline type atomic_dec_prefix_##name(volatile atomic_##name##_t *atomic) { \
+  return __atomic_sub_fetch_##sz(atomic, 1, __ATOMIC_SEQ_CST); \
+}
+
+// Returns value before operation, e.g. old value
+#define ATOMIC_INC_POSTFIX(name, type, sz) \
+inline type atomic_inc_postfix_##name(volatile atomic_##name##_t *atomic) { \
+  return __atomic_fetch_add_##sz(atomic, 1, __ATOMIC_SEQ_CST); \
+}
+
+// Returns value before operation, e.g. old value
+#define ATOMIC_DEC_POSTFIX(name, type, sz) \
+inline type atomic_dec_postfix_##name(volatile atomic_##name##_t *atomic) { \
+  return __atomic_fetch_sub_##sz(atomic, 1, __ATOMIC_SEQ_CST); \
+}
+
+// Returns value after operation, e.g. new value
+#define ATOMIC_ADD(name, type, sz) \
+inline type atomic_add_##name(volatile atomic_##name##_t *atomic, type val) { \
+  return __atomic_add_fetch_##sz(atomic, val, __ATOMIC_SEQ_CST); \
+}
+
+// Returns value after operation, e.g. new value
+#define ATOMIC_SUB(name, type, sz) \
+inline type atomic_sub_##name(volatile atomic_##name##_t *atomic, type val) { \
+  return __atomic_sub_fetch_##sz(atomic, val, __ATOMIC_SEQ_CST); \
+}
+
+#define ATOMIC_MAKE(name, type, sz) \
+  ATOMIC_TYPE(name, type) \
+  ATOMIC_STORE(name, type, sz) \
+  ATOMIC_LOAD(name, type, sz) \
+  ATOMIC_INC_PREFIX(name, type, sz) \
+  ATOMIC_DEC_PREFIX(name, type, sz) \
+  ATOMIC_INC_POSTFIX(name, type, sz) \
+  ATOMIC_DEC_POSTFIX(name, type, sz) \
+  ATOMIC_ADD(name, type, sz) \
+  ATOMIC_SUB(name, type, sz)
+
+ATOMIC_MAKE(s32, int32_t, 4)
+ATOMIC_MAKE(u32, uint32_t, 4)
+ATOMIC_MAKE(s64, int64_t, 8)
+ATOMIC_MAKE(u64, uint64_t, 8)
diff --git a/osi/include/buffer.h b/osi/include/buffer.h
new file mode 100644
index 0000000..51d23a5
--- /dev/null
+++ b/osi/include/buffer.h
@@ -0,0 +1,56 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stddef.h>
+
+typedef struct buffer_t buffer_t;
+
+// Returns a new buffer of |size| bytes. Returns NULL if a buffer could not be
+// allocated. |size| must be non-zero. The caller must release this buffer with
+// |buffer_free|.
+buffer_t *buffer_new(size_t size);
+
+// Creates a new reference to the buffer |buf|. A reference is indistinguishable
+// from the original: writes to the original will be reflected in the reference
+// and vice versa. In other words, this function creates an alias to |buf|. The
+// caller must release the returned buffer with |buffer_free|. Note that releasing
+// the returned buffer does not release |buf|. |buf| must not be NULL.
+buffer_t *buffer_new_ref(const buffer_t *buf);
+
+// Creates a new reference to the last |slice_size| bytes of |buf|. See
+// |buffer_new_ref| for a description of references. |slice_size| must be
+// greater than 0 and may be at most |buffer_length|
+// (0 < slice_size <= buffer_length). |buf| must not be NULL.
+buffer_t *buffer_new_slice(const buffer_t *buf, size_t slice_size);
+
+// Frees a buffer object. |buf| may be NULL.
+void buffer_free(buffer_t *buf);
+
+// Returns a pointer to a writeable memory region for |buf|. All references
+// and slices that share overlapping bytes will also be written to when
+// writing to the returned pointer. The caller may safely write up to
+// |buffer_length| consecutive bytes starting at the address returned by
+// this function. |buf| must not be NULL.
+void *buffer_ptr(const buffer_t *buf);
+
+// Returns the length of the writeable memory region referred to by |buf|.
+// |buf| must not be NULL.
+size_t buffer_length(const buffer_t *buf);
diff --git a/osi/include/config.h b/osi/include/config.h
index 5e45003..ab3096d 100644
--- a/osi/include/config.h
+++ b/osi/include/config.h
@@ -14,6 +14,7 @@
 //   not exist. In other words, |config_has_section| will return false for
 //   empty sections.
 // - Duplicate keys in a section will overwrite previous values.
+// - All strings are case sensitive.
 
 #include <stdbool.h>
 
@@ -21,8 +22,13 @@
 // a section.
 #define CONFIG_DEFAULT_SECTION "Global"
 
-struct config_t;
 typedef struct config_t config_t;
+typedef struct config_section_node_t config_section_node_t;
+
+// Creates a new config object with no entries (i.e. not backed by a file).
+// This function returns a config object or NULL on error. Clients must call
+// |config_free| on the returned handle when it is no longer required.
+config_t *config_new_empty(void);
 
 // Loads the specified file and returns a handle to the config file. If there
 // was a problem loading the file or allocating memory, this function returns
@@ -76,3 +82,46 @@
 // not already exist, this function creates them. |config|, |section|, |key|, and
 // |value| must not be NULL.
 void config_set_string(config_t *config, const char *section, const char *key, const char *value);
+
+// Removes |section| from the |config| (and, as a result, all keys in the section).
+// Returns true if |section| was found and removed from |config|, false otherwise.
+// Neither |config| nor |section| may be NULL.
+bool config_remove_section(config_t *config, const char *section);
+
+// Removes one specific |key| residing in |section| of the |config|. Returns true
+// if the section and key were found and the key was removed, false otherwise.
+// None of |config|, |section|, or |key| may be NULL.
+bool config_remove_key(config_t *config, const char *section, const char *key);
+
+// Returns an iterator to the first section in the config file. If there are no
+// sections, the iterator will equal the return value of |config_section_end|.
+// The returned pointer must be treated as an opaque handle and must not be freed.
+// The iterator is invalidated on any config mutating operation. |config| may not
+// be NULL.
+const config_section_node_t *config_section_begin(const config_t *config);
+
+// Returns an iterator to one past the last section in the config file. It does not
+// represent a valid section, but can be used to determine if all sections have been
+// iterated over. The returned pointer must be treated as an opaque handle and must
+// not be freed and must not be iterated on (must not call |config_section_next| on
+// it). |config| may not be NULL.
+const config_section_node_t *config_section_end(const config_t *config);
+
+// Moves |iter| to the next section. If there are no more sections, |iter| will
+// equal the value of |config_section_end|. |iter| may not be NULL and must be
+// a pointer returned by either |config_section_begin| or |config_section_next|.
+const config_section_node_t *config_section_next(const config_section_node_t *iter);
+
+// Returns the name of the section referred to by |iter|. The returned pointer is
+// owned by the config module and must not be freed by the caller. The pointer will
+// remain valid until |config_free| is called. |iter| may not be NULL and must not
+// equal the value returned by |config_section_end|.
+const char *config_section_name(const config_section_node_t *iter);
+
+// Saves |config| to a file given by |filename|. Note that this could be a destructive
+// operation: if |filename| already exists, it will be overwritten. The config
+// module does not preserve comments or formatting so if a config file was opened
+// with |config_new| and subsequently overwritten with |config_save|, all comments
+// and special formatting in the original file will be lost. Neither |config| nor
+// |filename| may be NULL.
+bool config_save(const config_t *config, const char *filename);
diff --git a/osi/include/data_dispatcher.h b/osi/include/data_dispatcher.h
new file mode 100644
index 0000000..78e0874
--- /dev/null
+++ b/osi/include/data_dispatcher.h
@@ -0,0 +1,56 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "fixed_queue.h"
+
+#define DISPATCHER_NAME_MAX 16
+
+typedef struct data_dispatcher_t data_dispatcher_t;
+typedef uint32_t data_dispatcher_type_t;
+
+// Creates a new data dispatcher object, with the given name.
+// The returned object must be freed by calling |data_dispatcher_free|.
+// Returns NULL on failure. |name| may not be NULL.
+data_dispatcher_t *data_dispatcher_new(const char *name);
+
+// Frees a data dispatcher object created by |data_dispatcher_new|.
+// |data_dispatcher| may be NULL.
+void data_dispatcher_free(data_dispatcher_t *dispatcher);
+
+// Registers |type| and |queue| with the data dispatcher so that data
+// sent under |type| ends up in |queue|. If |type| is already registered,
+// it is replaced. If |queue| is NULL, the existing registration is
+// removed, if it exists. |dispatcher| may not be NULL.
+void data_dispatcher_register(data_dispatcher_t *dispatcher, data_dispatcher_type_t type, fixed_queue_t *queue);
+
+// Registers a default queue to send data to when there is not a specific
+// type/queue relationship registered. If a default queue is already registered,
+// it is replaced. If |queue| is NULL, the existing registration is
+// removed, if it exists. |dispatcher| may not be NULL.
+void data_dispatcher_register_default(data_dispatcher_t *dispatcher, fixed_queue_t *queue);
+
+// Dispatches |data| to the queue registered for |type|. If no such registration
+// exists, it is dispatched to the default queue if it exists.
+// Neither |dispatcher| nor |data| may be NULL.
+// Returns true if data dispatch was successful.
+bool data_dispatcher_dispatch(data_dispatcher_t *dispatcher, data_dispatcher_type_t type, void *data);
diff --git a/osi/include/eager_reader.h b/osi/include/eager_reader.h
new file mode 100644
index 0000000..3bf1e6e
--- /dev/null
+++ b/osi/include/eager_reader.h
@@ -0,0 +1,63 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#include "allocator.h"
+
+typedef struct eager_reader_t eager_reader_t;
+typedef struct reactor_t reactor_t;
+
+typedef void (*eager_reader_cb)(eager_reader_t *reader, void *context);
+
+// Creates a new eager reader object, which pulls data from |fd_to_read| into
+// buffers of size |buffer_size| allocated using |allocator|, and has an
+// internal read thread named |thread_name|. The returned object must be freed using
+// |eager_reader_free|. |fd_to_read| must be valid, |buffer_size| and |max_buffer_count|
+// must be greater than zero. |allocator| and |thread_name| may not be NULL.
+eager_reader_t *eager_reader_new(
+  int fd_to_read,
+  const allocator_t *allocator,
+  size_t buffer_size,
+  size_t max_buffer_count,
+  const char *thread_name
+);
+
+// Frees an eager reader object, and associated internal resources.
+// |reader| may be NULL.
+void eager_reader_free(eager_reader_t *reader);
+
+// Registers |reader| with the |reactor|. When the reader has data
+// |read_cb| will be called. The |context| parameter is passed, untouched, to |read_cb|.
+// Neither |reader|, nor |reactor|, nor |read_cb| may be NULL. |context| may be NULL.
+void eager_reader_register(eager_reader_t *reader, reactor_t *reactor, eager_reader_cb read_cb, void *context);
+
+// Unregisters |reader| from whichever reactor it is registered with, if any. This
+// function is idempotent.
+void eager_reader_unregister(eager_reader_t *reader);
+
+// Reads up to |max_size| bytes into |buffer|. If |block| is true, blocks until
+// |max_size| bytes are read. Otherwise only reads from currently available bytes.
+// NOT SAFE FOR READING FROM MULTIPLE THREADS
+// but you should probably only be reading from one thread anyway,
+// otherwise the byte stream probably doesn't make sense.
+size_t eager_reader_read(eager_reader_t *reader, uint8_t *buffer, size_t max_size, bool block);
diff --git a/osi/include/fixed_queue.h b/osi/include/fixed_queue.h
index a3b896c..5c32ac7 100644
--- a/osi/include/fixed_queue.h
+++ b/osi/include/fixed_queue.h
@@ -22,8 +22,10 @@
 
 struct fixed_queue_t;
 typedef struct fixed_queue_t fixed_queue_t;
+typedef struct reactor_t reactor_t;
 
 typedef void (*fixed_queue_free_cb)(void *data);
+typedef void (*fixed_queue_cb)(fixed_queue_t *queue, void *context);
 
 // Creates a new fixed queue with the given |capacity|. If more elements than
 // |capacity| are added to the queue, the caller is blocked until space is
@@ -35,6 +37,14 @@
 // blocked on it) results in undefined behaviour.
 void fixed_queue_free(fixed_queue_t *queue, fixed_queue_free_cb free_cb);
 
+// Returns a value indicating whether the given |queue| is empty. |queue| may
+// not be NULL.
+bool fixed_queue_is_empty(fixed_queue_t *queue);
+
+// Returns the maximum number of elements this queue may hold. |queue| may
+// not be NULL.
+size_t fixed_queue_capacity(fixed_queue_t *queue);
+
 // Enqueues the given |data| into the |queue|. The caller will be blocked
 // if nore more space is available in the queue. Neither |queue| nor |data|
 // may be NULL.
@@ -57,6 +67,11 @@
 // NULL.
 void *fixed_queue_try_dequeue(fixed_queue_t *queue);
 
+// Returns the first element from |queue|, if present, without dequeuing it.
+// This function will never block the caller. Returns NULL if there are no elements
+// in the queue. |queue| may not be NULL.
+void *fixed_queue_try_peek(fixed_queue_t *queue);
+
 // This function returns a valid file descriptor. Callers may perform one
 // operation on the fd: select(2). If |select| indicates that the file
 // descriptor is readable, the caller may call |fixed_queue_enqueue| without
@@ -70,3 +85,13 @@
 // blocking. The caller must not close the returned file descriptor. |queue|
 // may not be NULL.
 int fixed_queue_get_dequeue_fd(const fixed_queue_t *queue);
+
+// Registers |queue| with |reactor| for dequeue operations. When there is an element
+// in the queue, ready_cb will be called. The |context| parameter is passed, untouched,
+// to the callback routine. Neither |queue|, nor |reactor|, nor |read_cb| may be NULL.
+// |context| may be NULL.
+void fixed_queue_register_dequeue(fixed_queue_t *queue, reactor_t *reactor, fixed_queue_cb ready_cb, void *context);
+
+// Unregisters the dequeue ready callback for |queue| from whichever reactor
+// it is registered with, if any. This function is idempotent.
+void fixed_queue_unregister_dequeue(fixed_queue_t *queue);
diff --git a/osi/include/future.h b/osi/include/future.h
new file mode 100644
index 0000000..d1bbd64
--- /dev/null
+++ b/osi/include/future.h
@@ -0,0 +1,41 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+typedef struct future_t future_t;
+
+#define FUTURE_SUCCESS ((void *)1)
+#define FUTURE_FAIL ((void *)0)
+
+// Constructs a new future_t object. Returns NULL on failure.
+future_t *future_new(void);
+
+// Constructs a new future_t object with an immediate |value|. No waiting will
+// occur in the call to |future_await| because the value is already present.
+// Returns NULL on failure.
+future_t *future_new_immediate(void *value);
+
+// Signals that the |future| is ready, passing |value| back to the context
+// waiting for the result. Must only be called once for every future.
+// |future| may not be NULL.
+void future_ready(future_t *future, void *value);
+
+// Waits for the |future| to be ready. Returns the value set in |future_ready|.
+// Frees the future before return. |future| may not be NULL.
+void *future_await(future_t *async_result);
diff --git a/test/suite/support/property.h b/osi/include/hash_functions.h
similarity index 62%
copy from test/suite/support/property.h
copy to osi/include/hash_functions.h
index a8b77c7..ad7d095 100644
--- a/test/suite/support/property.h
+++ b/osi/include/hash_functions.h
@@ -18,15 +18,13 @@
 
 #pragma once
 
-#include "base.h"
+#include "hash_map.h"
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+hash_index_t hash_function_naive(const void *key);
 
-const char *property_extract_name(const bt_property_t *property);
+hash_index_t hash_function_integer(const void *key);
 
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
+// Hashes a pointer based only on its address value
+hash_index_t hash_function_pointer(const void *key);
 
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+hash_index_t hash_function_string(const void *key);
diff --git a/osi/include/hash_map.h b/osi/include/hash_map.h
new file mode 100644
index 0000000..3d06dd7
--- /dev/null
+++ b/osi/include/hash_map.h
@@ -0,0 +1,107 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+
+struct hash_map_t;
+typedef struct hash_map_t hash_map_t;
+
+typedef struct hash_map_entry_t {
+  const void *key;
+  void *data;
+  const hash_map_t *hash_map;
+} hash_map_entry_t;
+
+typedef size_t hash_index_t;
+
+// Takes a key structure and returns a hash value.
+typedef hash_index_t (*hash_index_fn)(const void *key);
+typedef bool (*hash_map_iter_cb)(hash_map_entry_t *hash_entry, void *context);
+
+typedef bool (*key_equality_fn)(const void *x, const void *y);
+
+typedef void (*key_free_fn)(void *data);
+typedef void (*data_free_fn)(void *data);
+
+// Returns a new, empty hash_map. Returns NULL if not enough memory could be allocated
+// for the hash_map structure. The returned hash_map must be freed with |hash_map_free|.
+// The |num_bucket| specifies the number of hashable buckets for the map and must not
+// be zero.  The |hash_fn| specifies a hash function to be used and must not be NULL.
+// The |key_fn| and |data_fn| are called whenever a hash_map element is removed from
+// the hash_map. They can be used to release resources held by the hash_map element,
+// e.g.  memory or file descriptor.  |key_fn| and |data_fn| may be NULL if no cleanup
+// is necessary on element removal. |equality_fn| is used to check for key equality.
+// If |equality_fn| is NULL, default pointer equality is used.
+hash_map_t *hash_map_new(
+    size_t size,
+    hash_index_fn hash_fn,
+    key_free_fn key_fn,
+    data_free_fn data_fn,
+    key_equality_fn equality_fn);
+
+// Frees the hash_map. This function accepts NULL as an argument, in which case it
+// behaves like a no-op.
+void hash_map_free(hash_map_t *hash_map);
+
+// Returns true if the hash_map is empty (has no elements), false otherwise.
+// Note that a NULL |hash_map| is not the same as an empty |hash_map|. This function
+// does not accept a NULL |hash_map|.
+bool hash_map_is_empty(const hash_map_t *hash_map);
+
+// Returns the number of elements in the hash map.  This function does not accept a
+// NULL |hash_map|.
+size_t hash_map_size(const hash_map_t *hash_map);
+
+// Returns the number of buckets in the hash map.  This function does not accept a
+// NULL |hash_map|.
+size_t hash_map_num_buckets(const hash_map_t *hash_map);
+
+// Returns true if the hash_map has a valid entry for the presented key.
+// This function does not accept a NULL |hash_map|.
+bool hash_map_has_key(const hash_map_t *hash_map, const void *key);
+
+// Returns the element indexed by |key| in the hash_map without removing it. |hash_map|
+// may not be NULL.  Returns NULL if no entry indexed by |key|.
+void *hash_map_get(const hash_map_t *hash_map, const void *key);
+
+// Sets the value |data| indexed by |key| into the |hash_map|. Neither |data| nor
+// |hash_map| may be NULL.  This function does not make copies of |data| nor |key|
+// so the pointers must remain valid at least until the element is removed from the
+// hash_map or the hash_map is freed.  Returns true if |data| could be set, false
+// otherwise (e.g. out of memory).
+bool hash_map_set(hash_map_t *hash_map, const void *key, void *data);
+
+// Removes data indexed by |key| from the hash_map. |hash_map| may not be NULL.
+// If |key_fn| or |data_fn| functions were specified in |hash_map_new|, they
+// will be called back with |key| or |data| respectively. This function returns true
+// if |key| was found in the hash_map and removed, false otherwise.
+bool hash_map_erase(hash_map_t *hash_map, const void *key);
+
+// Removes all elements in the hash_map. Calling this function will return the hash_map
+// to the same state it was in after |hash_map_new|. |hash_map| may not be NULL.
+void hash_map_clear(hash_map_t *hash_map);
+
+// Iterates through the entire |hash_map| and calls |callback| for each data
+// element and passes through the |context| argument. If the hash_map is
+// empty, |callback| will never be called. It is not safe to mutate the
+// hash_map inside the callback. Neither |hash_map| nor |callback| may be NULL.
+// If |callback| returns false, the iteration loop will immediately exit.
+void hash_map_foreach(hash_map_t *hash_map, hash_map_iter_cb callback, void *context);
diff --git a/osi/include/list.h b/osi/include/list.h
index 56cb739..da38c2f 100644
--- a/osi/include/list.h
+++ b/osi/include/list.h
@@ -12,27 +12,91 @@
 typedef void (*list_free_cb)(void *data);
 typedef bool (*list_iter_cb)(void *data);
 
-// Lifecycle.
+// Returns a new, empty list. Returns NULL if not enough memory could be allocated
+// for the list structure. The returned list must be freed with |list_free|. The
+// |callback| specifies a function to be called whenever a list element is removed
+// from the list. It can be used to release resources held by the list element, e.g.
+// memory or file descriptor. |callback| may be NULL if no cleanup is necessary on
+// element removal.
 list_t *list_new(list_free_cb callback);
+
+// Frees the list. This function accepts NULL as an argument, in which case it
+// behaves like a no-op.
 void list_free(list_t *list);
 
-// Accessors.
+// Returns true if |list| is empty (has no elements), false otherwise.
+// |list| may not be NULL.
 bool list_is_empty(const list_t *list);
+
+// Returns true if the list contains |data|, false otherwise.
+// |list| may not be NULL.
+bool list_contains(const list_t *list, const void *data);
+
+// Returns the length of the |list|. |list| may not be NULL.
 size_t list_length(const list_t *list);
+
+// Returns the first element in the list without removing it. |list| may not
+// be NULL or empty.
 void *list_front(const list_t *list);
+
+// Returns the last element in the list without removing it. |list| may not
+// be NULL or empty.
 void *list_back(const list_t *list);
 
-// Mutators.
+// Inserts |data| after |prev_node| in |list|. |data|, |list|, and |prev_node|
+// may not be NULL. This function does not make a copy of |data| so the pointer
+// must remain valid at least until the element is removed from the list or the
+// list is freed. Returns true if |data| could be inserted, false otherwise
+// (e.g. out of memory).
 bool list_insert_after(list_t *list, list_node_t *prev_node, void *data);
+
+// Inserts |data| at the beginning of |list|. Neither |data| nor |list| may be NULL.
+// This function does not make a copy of |data| so the pointer must remain valid
+// at least until the element is removed from the list or the list is freed.
+// Returns true if |data| could be inserted, false otherwise (e.g. out of memory).
 bool list_prepend(list_t *list, void *data);
+
+// Inserts |data| at the end of |list|. Neither |data| nor |list| may be NULL.
+// This function does not make a copy of |data| so the pointer must remain valid
+// at least until the element is removed from the list or the list is freed.
+// Returns true if |data| could be inserted, false otherwise (e.g. out of memory).
 bool list_append(list_t *list, void *data);
+
+// Removes |data| from the list. Neither |list| nor |data| may be NULL. If |data|
+// is inserted multiple times in the list, this function will only remove the first
+// instance. If a free function was specified in |list_new|, it will be called back
+// with |data|. This function returns true if |data| was found in the list and removed,
+// false otherwise.
 bool list_remove(list_t *list, void *data);
+
+// Removes all elements in the list. Calling this function will return the list to the
+// same state it was in after |list_new|. |list| may not be NULL.
 void list_clear(list_t *list);
 
-// Iteration.
+// Iterates through the entire |list| and calls |callback| for each data element.
+// If the list is empty, |callback| will never be called. It is safe to mutate the
+// list inside the callback. If an element is added before the node being visited,
+// there will be no callback for the newly-inserted node. Neither |list| nor
+// |callback| may be NULL.
 void list_foreach(const list_t *list, list_iter_cb callback);
 
+// Returns an iterator to the first element in |list|. |list| may not be NULL.
+// The returned iterator is valid as long as it does not equal the value returned
+// by |list_end|.
 list_node_t *list_begin(const list_t *list);
+
+// Returns an iterator that points past the end of the list. In other words,
+// this function returns the value of an invalid iterator for the given list.
+// When an iterator has the same value as what's returned by this function, you
+// may no longer call |list_next| with the iterator. |list| may not be NULL.
 list_node_t *list_end(const list_t *list);
+
+// Given a valid iterator |node|, this function returns the next value for the
+// iterator. If the returned value equals the value returned by |list_end|, the
+// iterator has reached the end of the list and may no longer be used for any
+// purpose.
 list_node_t *list_next(const list_node_t *node);
+
+// Returns the value stored at the location pointed to by the iterator |node|.
+// |node| must not equal the value returned by |list_end|.
 void *list_node(const list_node_t *node);
diff --git a/test/suite/support/property.h b/osi/include/log.h
similarity index 61%
copy from test/suite/support/property.h
copy to osi/include/log.h
index a8b77c7..a5de1cf 100644
--- a/test/suite/support/property.h
+++ b/osi/include/log.h
@@ -18,15 +18,10 @@
 
 #pragma once
 
-#include "base.h"
+#include <cutils/log.h>
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
-
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+#define LOG_VERBOSE(...) ALOGV(__VA_ARGS__)
+#define LOG_DEBUG(...)   ALOGD(__VA_ARGS__)
+#define LOG_INFO(...)    ALOGI(__VA_ARGS__)
+#define LOG_WARN(...)    ALOGW(__VA_ARGS__)
+#define LOG_ERROR(...)   ALOGE(__VA_ARGS__)
diff --git a/osi/include/non_repeating_timer.h b/osi/include/non_repeating_timer.h
new file mode 100644
index 0000000..de8aabf
--- /dev/null
+++ b/osi/include/non_repeating_timer.h
@@ -0,0 +1,48 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+
+#include "alarm.h"
+
+typedef struct non_repeating_timer_t non_repeating_timer_t;
+
+// Creates a new non repeating timer of |duration| with callback |cb|. |cb| will be
+// called back in the context of an upspecified thread, and may not be NULL. |data|
+// is a context variable for the callback and may be NULL. The returned object must
+// be freed by calling |non_repeating_timer_free|. Returns NULL on failure.
+non_repeating_timer_t *non_repeating_timer_new(period_ms_t duration, alarm_callback_t cb, void *data);
+
+// Frees a non repeating timer created by |non_repeating_timer_new|. |timer| may be
+// NULL. If the timer is currently running, it will be cancelled. It is not safe to
+// call |non_repeating_timer_free| from inside the callback of a non repeating timer.
+void non_repeating_timer_free(non_repeating_timer_t *timer);
+
+// Restarts the non repeating timer. If it is currently running, the timer is reset.
+// |timer| may not be NULL.
+void non_repeating_timer_restart(non_repeating_timer_t *timer);
+
+// Restarts the non repeating timer if |condition| is true, otherwise ensures it is
+// not running. |timer| may not be NULL.
+void non_repeating_timer_restart_if(non_repeating_timer_t *timer, bool condition);
+
+// Cancels the non repeating timer if it is currently running. All the semantics of
+// |alarm_cancel| apply here. |timer| may not be NULL.
+void non_repeating_timer_cancel(non_repeating_timer_t *timer);
diff --git a/osi/include/osi.h b/osi/include/osi.h
index 6b38e9b..c035bf8 100644
--- a/osi/include/osi.h
+++ b/osi/include/osi.h
@@ -5,5 +5,18 @@
 
 #define UNUSED_ATTR __attribute__((unused))
 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
+#define INVALID_FD (-1)
+
+#define CONCAT(a, b) a##b
+
+// Use during compile time to check conditional values
+// NOTE: The the failures will present as a generic error
+// "error: initialization makes pointer from integer without a cast"
+// but the file and line number will present the condition that
+// failed.
+#define DUMMY_COUNTER(c) CONCAT(__osi_dummy_, c)
+#define DUMMY_PTR DUMMY_COUNTER(__COUNTER__)
+
+#define COMPILE_ASSERT(x) char * DUMMY_PTR = !(x)
 
 typedef uint32_t timeout_t;
diff --git a/osi/include/reactor.h b/osi/include/reactor.h
index eeb538d..100c762 100644
--- a/osi/include/reactor.h
+++ b/osi/include/reactor.h
@@ -26,37 +26,16 @@
 // This module implements the Reactor pattern.
 // See http://en.wikipedia.org/wiki/Reactor_pattern for details.
 
-struct reactor_t;
 typedef struct reactor_t reactor_t;
-
-struct reactor_object_t;
 typedef struct reactor_object_t reactor_object_t;
 
-// Enumerates the types of events a reactor object is interested
-// in responding to.
-typedef enum {
-  REACTOR_INTEREST_READ  = 1,
-  REACTOR_INTEREST_WRITE = 2,
-  REACTOR_INTEREST_READ_WRITE = 3,
-} reactor_interest_t;
-
 // Enumerates the reasons a reactor has stopped.
 typedef enum {
   REACTOR_STATUS_STOP,     // |reactor_stop| was called.
-  REACTOR_STATUS_TIMEOUT,  // a timeout was specified and the reactor timed out.
   REACTOR_STATUS_ERROR,    // there was an error during the operation.
   REACTOR_STATUS_DONE,     // the reactor completed its work (for the _run_once* variants).
 } reactor_status_t;
 
-struct reactor_object_t {
-  void *context;                       // a context that's passed back to the *_ready functions.
-  int fd;                              // the file descriptor to monitor for events.
-  reactor_interest_t interest;         // the event types to monitor the file descriptor for.
-
-  void (*read_ready)(void *context);   // function to call when the file descriptor becomes readable.
-  void (*write_ready)(void *context);  // function to call when the file descriptor becomes writeable.
-};
-
 // Creates a new reactor object. Returns NULL on failure. The returned object
 // must be freed by calling |reactor_free|.
 reactor_t *reactor_new(void);
@@ -72,18 +51,32 @@
 // becomes ready. |reactor| may not be NULL.
 reactor_status_t reactor_run_once(reactor_t *reactor);
 
-// Same as |reactor_run_once| with a bounded wait time in case no object becomes ready.
-reactor_status_t reactor_run_once_timeout(reactor_t *reactor, timeout_t timeout_ms);
-
 // Immediately unblocks the reactor. This function is safe to call from any thread.
 // |reactor| may not be NULL.
 void reactor_stop(reactor_t *reactor);
 
-// Registers an object with the reactor. |obj| is neither copied nor is its ownership transferred
-// so the pointer must remain valid until it is unregistered with |reactor_unregister|. Neither
-// |reactor| nor |obj| may be NULL.
-void reactor_register(reactor_t *reactor, reactor_object_t *obj);
+// Registers a file descriptor with the reactor. The file descriptor, |fd|, must be valid
+// when this function is called and its ownership is not transferred to the reactor. The
+// |context| variable is a user-defined opaque handle that is passed back to the |read_ready|
+// and |write_ready| functions. It is not copied or even dereferenced by the reactor so it
+// may contain any value including NULL. The |read_ready| and |write_ready| arguments are
+// optional and may be NULL. This function returns an opaque object that represents the
+// file descriptor's registration with the reactor. When the caller is no longer interested
+// in events on the |fd|, it must free the returned object by calling |reactor_unregister|.
+reactor_object_t *reactor_register(reactor_t *reactor,
+    int fd, void *context,
+    void (*read_ready)(void *context),
+    void (*write_ready)(void *context));
 
-// Unregisters a previously registered object with the |reactor|. Neither |reactor| nor |obj|
-// may be NULL.
-void reactor_unregister(reactor_t *reactor, reactor_object_t *obj);
+// Changes the subscription mode for the file descriptor represented by |object|. If the
+// caller has already registered a file descriptor with a reactor, has a valid |object|,
+// and decides to change the |read_ready| and/or |write_ready| callback routines, they
+// can call this routine. Returns true if the subscription was changed, false otherwise.
+// |object| may not be NULL, |read_ready| and |write_ready| may be NULL.
+bool reactor_change_registration(reactor_object_t *object,
+    void (*read_ready)(void *context),
+    void (*write_ready)(void *context));
+
+// Unregisters a previously registered file descriptor with its reactor. |obj| may not be NULL.
+// |obj| is invalid after calling this function so the caller must drop all references to it.
+void reactor_unregister(reactor_object_t *obj);
diff --git a/osi/include/socket.h b/osi/include/socket.h
new file mode 100644
index 0000000..e2d0888
--- /dev/null
+++ b/osi/include/socket.h
@@ -0,0 +1,100 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+typedef struct reactor_t reactor_t;
+typedef struct socket_t socket_t;
+typedef uint16_t port_t;
+
+typedef void (*socket_cb)(socket_t *socket, void *context);
+
+// Returns a new socket object. The socket is in an idle, disconnected state when
+// it is returned by this function. The returned object must be freed by calling
+// |socket_free|. Returns NULL on failure.
+socket_t *socket_new(void);
+
+// Returns a new socket object backed by |fd|. The socket object is in whichever
+// state |fd| is in when it was passed to this function. The returned object must
+// be freed by calling |socket_free|. Returns NULL on failure. If this function
+// is successful, ownership of |fd| is transferred and the caller must not close it.
+socket_t *socket_new_from_fd(int fd);
+
+// Frees a socket object created by |socket_new| or |socket_accept|. |socket| may
+// be NULL. If the socket was connected, it will be disconnected.
+void socket_free(socket_t *socket);
+
+// Puts |socket| in listening mode for incoming TCP connections on the specified
+// |port|. Returns true on success, false on failure (e.g. |port| is bound by
+// another socket). |socket| may not be NULL.
+bool socket_listen(const socket_t *socket, port_t port);
+
+// Blocks on a listening socket, |socket|, until a client connects to it. Returns
+// a connected socket on success, NULL on failure. The returned object must be
+// freed by calling |socket_free|. |socket| may not be NULL.
+socket_t *socket_accept(const socket_t *socket);
+
+// Reads up to |count| bytes from |socket| into |buf|. This function will not
+// block. This function returns a positive integer representing the number
+// of bytes copied into |buf| on success, 0 if the socket has disconnected,
+// and -1 on error. This function may return a value less than |count| if not
+// enough data is currently available. If this function returns -1, errno will also
+// be set (see recv(2) for possible errno values). If there were no bytes available
+// to be read, this function returns -1 and sets errno to EWOULDBLOCK. Neither
+// |socket| nor |buf| may be NULL.
+ssize_t socket_read(const socket_t *socket, void *buf, size_t count);
+
+// Writes up to |count| bytes from |buf| into |socket|. This function will not
+// block. Returns a positive integer representing the number of bytes written
+// to |socket| on success, 0 if the socket has disconnected, and -1 on error. This
+// function may return a value less than |count| if writing more bytes would result
+// in blocking. If this function returns -1, errno will also be set (see send(2) for
+// possible errno values). If no bytes could be written without blocking, this
+// function will return -1 and set errno to EWOULDBLOCK. Neither |socket| nor |buf|
+// may be NULL.
+ssize_t socket_write(const socket_t *socket, const void *buf, size_t count);
+
+// This function performs the same write operation as |socket_write| and also
+// sends the file descriptor |fd| over the socket to a remote process. Ownership
+// of |fd| transfers to this function and the descriptor must not be used any longer.
+// If |fd| is INVALID_FD, this function behaves the same as |socket_write|.
+ssize_t socket_write_and_transfer_fd(const socket_t *socket, const void *buf, size_t count, int fd);
+
+// Returns the number of bytes that can be read from |socket| without blocking. On error,
+// this function returns -1. |socket| may not be NULL.
+//
+// Note: this function should not be part of the socket interface. It is only provided as
+//       a stop-gap until we can refactor away code that depends on a priori knowledge of
+//       the byte count. Do not use this function unless you need it while refactoring
+//       legacy bluedroid code.
+ssize_t socket_bytes_available(const socket_t *socket);
+
+// Registers |socket| with the |reactor|. When the socket becomes readable, |read_cb|
+// will be called. When the socket becomes writeable, |write_cb| will be called. The
+// |context| parameter is passed, untouched, to each of the callback routines. Neither
+// |socket| nor |reactor| may be NULL. |read_cb|, |write_cb|, and |context| may be NULL.
+void socket_register(socket_t *socket, reactor_t *reactor, void *context, socket_cb read_cb, socket_cb write_cb);
+
+// Unregisters |socket| from whichever reactor it is registered with, if any. This
+// function is idempotent.
+void socket_unregister(socket_t *socket);
diff --git a/osi/include/thread.h b/osi/include/thread.h
index c78c5e3..def4aa5 100644
--- a/osi/include/thread.h
+++ b/osi/include/thread.h
@@ -18,8 +18,12 @@
 
 #pragma once
 
+#include <stdbool.h>
+#include <stdlib.h>
+
 #define THREAD_NAME_MAX 16
 
+typedef struct reactor_t reactor_t;
 typedef struct thread_t thread_t;
 typedef void (*thread_fn)(void *context);
 
@@ -30,11 +34,19 @@
 // be NULL.
 thread_t *thread_new(const char *name);
 
+// Similar to |thread_new| but creates with a given queue |size|.
+thread_t *thread_new_sized(const char *name, size_t size);
+
 // Frees the given |thread|. If the thread is still running, it is stopped
 // and the calling thread will block until |thread| terminates. |thread|
 // may be NULL.
 void thread_free(thread_t *thread);
 
+// Waits for |thread_stop|. Upon returning, the only other operations a caller
+// may perform on |thread| are |thread_free| and |thread_join|. |thread_join|
+// is idempotent and may be called from any thread. |thread| may not be NULL.
+void thread_join(thread_t *thread);
+
 // Call |func| with the argument |context| on |thread|. This function typically
 // does not block unless there are an excessive number of functions posted to
 // |thread| that have not been dispatched yet. Neither |thread| nor |func| may
@@ -46,5 +58,11 @@
 // |thread| may not be NULL.
 void thread_stop(thread_t *thread);
 
+// Returns true if the current thread is the same as the one represented by |thread|.
+// |thread| may not be NULL.
+bool thread_is_self(const thread_t *thread);
+
+reactor_t *thread_get_reactor(const thread_t *thread);
+
 // Returns the name of the given |thread|. |thread| may not be NULL.
 const char *thread_name(const thread_t *thread);
diff --git a/osi/src/alarm.c b/osi/src/alarm.c
index ed288f6..1ce58bc 100644
--- a/osi/src/alarm.c
+++ b/osi/src/alarm.c
@@ -26,11 +26,14 @@
 #include <string.h>
 #include <signal.h>
 #include <time.h>
-#include <utils/Log.h>
 
-#include "alarm.h"
-#include "list.h"
-#include "osi.h"
+#include "osi/include/alarm.h"
+#include "osi/include/allocator.h"
+#include "osi/include/list.h"
+#include "osi/include/log.h"
+#include "osi/include/osi.h"
+#include "osi/include/semaphore.h"
+#include "osi/include/thread.h"
 
 struct alarm_t {
   // The lock is held while the callback for this alarm is being executed.
@@ -39,7 +42,10 @@
   // a guarantee to its caller that the callback will not be in progress when it
   // returns.
   pthread_mutex_t callback_lock;
+  period_ms_t created;
+  period_ms_t period;
   period_ms_t deadline;
+  bool is_periodic;
   alarm_callback_t callback;
   void *data;
 };
@@ -62,10 +68,17 @@
 static timer_t timer;
 static bool timer_set;
 
+// All alarm callbacks are dispatched from |callback_thread|
+static thread_t *callback_thread;
+static semaphore_t *alarm_expired;
+
 static bool lazy_initialize(void);
 static period_ms_t now(void);
+static void alarm_set_internal(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data, bool is_periodic);
+static void schedule_next_instance(alarm_t *alarm, bool force_reschedule);
+static void reschedule_root_alarm(void);
 static void timer_callback(void *data);
-static void reschedule(void);
+static void callback_dispatch(void *context);
 
 alarm_t *alarm_new(void) {
   // Make sure we have a list we can insert alarms into.
@@ -75,9 +88,9 @@
   pthread_mutexattr_t attr;
   pthread_mutexattr_init(&attr);
 
-  alarm_t *ret = calloc(1, sizeof(alarm_t));
+  alarm_t *ret = osi_calloc(sizeof(alarm_t));
   if (!ret) {
-    ALOGE("%s unable to allocate memory for alarm.", __func__);
+    LOG_ERROR("%s unable to allocate memory for alarm.", __func__);
     goto error;
   }
 
@@ -85,13 +98,13 @@
   // within the callback function of the alarm.
   int error = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
   if (error) {
-    ALOGE("%s unable to create a recursive mutex: %s", __func__, strerror(error));
+    LOG_ERROR("%s unable to create a recursive mutex: %s", __func__, strerror(error));
     goto error;
   }
 
   error = pthread_mutex_init(&ret->callback_lock, &attr);
   if (error) {
-    ALOGE("%s unable to initialize mutex: %s", __func__, strerror(error));
+    LOG_ERROR("%s unable to initialize mutex: %s", __func__, strerror(error));
     goto error;
   }
 
@@ -100,7 +113,7 @@
 
 error:;
   pthread_mutexattr_destroy(&attr);
-  free(ret);
+  osi_free(ret);
   return NULL;
 }
 
@@ -110,42 +123,32 @@
 
   alarm_cancel(alarm);
   pthread_mutex_destroy(&alarm->callback_lock);
-  free(alarm);
+  osi_free(alarm);
+}
+
+void alarm_set(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data) {
+  alarm_set_internal(alarm, deadline, cb, data, false);
+}
+
+void alarm_set_periodic(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data) {
+  alarm_set_internal(alarm, period, cb, data, true);
 }
 
 // Runs in exclusion with alarm_cancel and timer_callback.
-void alarm_set(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data) {
+static void alarm_set_internal(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data, bool is_periodic) {
   assert(alarms != NULL);
   assert(alarm != NULL);
   assert(cb != NULL);
 
   pthread_mutex_lock(&monitor);
 
-  // If the alarm is currently set and it's at the start of the list,
-  // we'll need to re-schedule since we've adjusted the earliest deadline.
-  bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
-  if (alarm->callback)
-    list_remove(alarms, alarm);
-
-  alarm->deadline = now() + deadline;
+  alarm->created = now();
+  alarm->is_periodic = is_periodic;
+  alarm->period = period;
   alarm->callback = cb;
   alarm->data = data;
 
-  // Add it into the timer list sorted by deadline (earliest deadline first).
-  if (list_is_empty(alarms))
-    list_prepend(alarms, alarm);
-  else
-    for (list_node_t *node = list_begin(alarms); node != list_end(alarms); node = list_next(node)) {
-      list_node_t *next = list_next(node);
-      if (next == list_end(alarms) || ((alarm_t *)list_node(next))->deadline >= alarm->deadline) {
-        list_insert_after(alarms, node, alarm);
-        break;
-      }
-    }
-
-  // If the new alarm has the earliest deadline, we need to re-evaluate our schedule.
-  if (needs_reschedule || (!list_is_empty(alarms) && list_front(alarms) == alarm))
-    reschedule();
+  schedule_next_instance(alarm, false);
 
   pthread_mutex_unlock(&monitor);
 }
@@ -164,7 +167,7 @@
   alarm->data = NULL;
 
   if (needs_reschedule)
-    reschedule();
+    reschedule_root_alarm();
 
   pthread_mutex_unlock(&monitor);
 
@@ -180,10 +183,32 @@
 
   alarms = list_new(NULL);
   if (!alarms) {
-    ALOGE("%s unable to allocate alarm list.", __func__);
+    LOG_ERROR("%s unable to allocate alarm list.", __func__);
     return false;
   }
 
+  struct sigevent sigevent;
+  memset(&sigevent, 0, sizeof(sigevent));
+  sigevent.sigev_notify = SIGEV_THREAD;
+  sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
+  if (timer_create(CLOCK_ID, &sigevent, &timer) == -1) {
+    LOG_ERROR("%s unable to create timer: %s", __func__, strerror(errno));
+    return false;
+  }
+
+  alarm_expired = semaphore_new(0);
+  if (!alarm_expired) {
+    LOG_ERROR("%s unable to create alarm expired semaphore", __func__);
+    return false;
+  }
+
+  callback_thread = thread_new("alarm_callbacks");
+  if (!callback_thread) {
+    LOG_ERROR("%s unable to create alarm callback thread.", __func__);
+    return false;
+  }
+
+  thread_post(callback_thread, callback_dispatch, NULL);
   return true;
 }
 
@@ -192,95 +217,145 @@
 
   struct timespec ts;
   if (clock_gettime(CLOCK_ID, &ts) == -1) {
-    ALOGE("%s unable to get current time: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to get current time: %s", __func__, strerror(errno));
     return 0;
   }
 
   return (ts.tv_sec * 1000LL) + (ts.tv_nsec / 1000000LL);
 }
 
-// Warning: this function is called in the context of an unknown thread.
-// As a result, it must be thread-safe relative to other operations on
-// the alarm list.
-static void timer_callback(void *ptr) {
-  alarm_t *alarm = (alarm_t *)ptr;
-  assert(alarm != NULL);
+// Must be called with monitor held
+static void schedule_next_instance(alarm_t *alarm, bool force_reschedule) {
+  // If the alarm is currently set and it's at the start of the list,
+  // we'll need to re-schedule since we've adjusted the earliest deadline.
+  bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
+  if (alarm->callback)
+    list_remove(alarms, alarm);
 
-  pthread_mutex_lock(&monitor);
+  // Calculate the next deadline for this alarm
+  period_ms_t just_now = now();
+  period_ms_t ms_into_period = alarm->is_periodic ? ((just_now - alarm->created) % alarm->period) : 0;
+  alarm->deadline = just_now + (alarm->period - ms_into_period);
 
-  bool alarm_valid = list_remove(alarms, alarm);
-  alarm_callback_t callback = alarm->callback;
-  void *data = alarm->data;
+  // Add it into the timer list sorted by deadline (earliest deadline first).
+  if (list_is_empty(alarms) || ((alarm_t *)list_front(alarms))->deadline >= alarm->deadline)
+    list_prepend(alarms, alarm);
+  else
+    for (list_node_t *node = list_begin(alarms); node != list_end(alarms); node = list_next(node)) {
+      list_node_t *next = list_next(node);
+      if (next == list_end(alarms) || ((alarm_t *)list_node(next))->deadline >= alarm->deadline) {
+        list_insert_after(alarms, node, alarm);
+        break;
+      }
+    }
 
-  alarm->deadline = 0;
-  alarm->callback = NULL;
-  alarm->data = NULL;
-
-  reschedule();
-
-  // The alarm was cancelled before we got to it. Release the monitor
-  // lock and exit right away since there's nothing left to do.
-  if (!alarm_valid) {
-    pthread_mutex_unlock(&monitor);
-    return;
-  }
-
-  // Downgrade lock.
-  pthread_mutex_lock(&alarm->callback_lock);
-  pthread_mutex_unlock(&monitor);
-
-  callback(data);
-
-  pthread_mutex_unlock(&alarm->callback_lock);
+  // If the new alarm has the earliest deadline, we need to re-evaluate our schedule.
+  if (force_reschedule || needs_reschedule || (!list_is_empty(alarms) && list_front(alarms) == alarm))
+    reschedule_root_alarm();
 }
 
 // NOTE: must be called with monitor lock.
-static void reschedule(void) {
+static void reschedule_root_alarm(void) {
   assert(alarms != NULL);
 
-  if (timer_set) {
-    timer_delete(timer);
-    timer_set = false;
-  }
+  // If used in a zeroed state, disarms the timer
+  struct itimerspec wakeup_time;
+  memset(&wakeup_time, 0, sizeof(wakeup_time));
 
-  if (list_is_empty(alarms)) {
-    bt_os_callouts->release_wake_lock(WAKE_LOCK_ID);
-    return;
-  }
+  if (list_is_empty(alarms))
+    goto done;
 
   alarm_t *next = list_front(alarms);
-  int64_t next_exp = next->deadline - now();
-  if (next_exp < TIMER_INTERVAL_FOR_WAKELOCK_IN_MS) {
-    int status = bt_os_callouts->acquire_wake_lock(WAKE_LOCK_ID);
-    if (status != BT_STATUS_SUCCESS) {
-      ALOGE("%s unable to acquire wake lock: %d", __func__, status);
-      return;
+  int64_t next_expiration = next->deadline - now();
+  if (next_expiration < TIMER_INTERVAL_FOR_WAKELOCK_IN_MS) {
+    if (!timer_set) {
+      int status = bt_os_callouts->acquire_wake_lock(WAKE_LOCK_ID);
+      if (status != BT_STATUS_SUCCESS) {
+        LOG_ERROR("%s unable to acquire wake lock: %d", __func__, status);
+        goto done;
+      }
     }
 
-    struct sigevent sigevent;
-    memset(&sigevent, 0, sizeof(sigevent));
-    sigevent.sigev_notify = SIGEV_THREAD;
-    sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
-    sigevent.sigev_value.sival_ptr = next;
-    if (timer_create(CLOCK_ID, &sigevent, &timer) == -1) {
-      ALOGE("%s unable to create timer: %s", __func__, strerror(errno));
-      return;
-    }
-
-    struct itimerspec wakeup_time;
-    memset(&wakeup_time, 0, sizeof(wakeup_time));
     wakeup_time.it_value.tv_sec = (next->deadline / 1000);
     wakeup_time.it_value.tv_nsec = (next->deadline % 1000) * 1000000LL;
-    if (timer_settime(timer, TIMER_ABSTIME, &wakeup_time, NULL) == -1) {
-      ALOGE("%s unable to set timer: %s", __func__, strerror(errno));
-      timer_delete(timer);
-      return;
-    }
-    timer_set = true;
   } else {
-    if (!bt_os_callouts->set_wake_alarm(next_exp, true, timer_callback, next))
-      ALOGE("%s unable to set wake alarm for %" PRId64 "ms.", __func__, next_exp);
+    if (!bt_os_callouts->set_wake_alarm(next_expiration, true, timer_callback, NULL))
+      LOG_ERROR("%s unable to set wake alarm for %" PRId64 "ms.", __func__, next_expiration);
+  }
 
+done:
+  timer_set = wakeup_time.it_value.tv_sec != 0 || wakeup_time.it_value.tv_nsec != 0;
+  if (!timer_set) {
     bt_os_callouts->release_wake_lock(WAKE_LOCK_ID);
   }
+
+  if (timer_settime(timer, TIMER_ABSTIME, &wakeup_time, NULL) == -1)
+    LOG_ERROR("%s unable to set timer: %s", __func__, strerror(errno));
+
+  // If next expiration was in the past (e.g. short timer that got context switched)
+  // then the timer might have diarmed itself. Detect this case and work around it
+  // by manually signalling the |alarm_expired| semaphore.
+  //
+  // It is possible that the timer was actually super short (a few milliseconds)
+  // and the timer expired normally before we called |timer_gettime|. Worst case,
+  // |alarm_expired| is signaled twice for that alarm. Nothing bad should happen in
+  // that case though since the callback dispatch function checks to make sure the
+  // timer at the head of the list actually expired.
+  if (timer_set) {
+    struct itimerspec time_to_expire;
+    timer_gettime(timer, &time_to_expire);
+    if (time_to_expire.it_value.tv_sec == 0 && time_to_expire.it_value.tv_nsec == 0) {
+      LOG_ERROR("%s alarm expiration too close for posix timers, switching to guns", __func__);
+      semaphore_post(alarm_expired);
+    }
+  }
+}
+
+// Callback function for wake alarms and our posix timer
+static void timer_callback(UNUSED_ATTR void *ptr) {
+  semaphore_post(alarm_expired);
+}
+
+// Function running on |callback_thread| that dispatches alarm callbacks upon
+// alarm expiration, which is signaled using |alarm_expired|.
+static void callback_dispatch(UNUSED_ATTR void *context) {
+  while (true) {
+    semaphore_wait(alarm_expired);
+    pthread_mutex_lock(&monitor);
+
+    alarm_t *alarm;
+
+    // Take into account that the alarm may get cancelled before we get to it.
+    // We're done here if there are no alarms or the alarm at the front is in
+    // the future. Release the monitor lock and exit right away since there's
+    // nothing left to do.
+    if (list_is_empty(alarms) || (alarm = list_front(alarms))->deadline > now()) {
+      reschedule_root_alarm();
+      pthread_mutex_unlock(&monitor);
+      continue;
+    }
+
+    list_remove(alarms, alarm);
+
+    alarm_callback_t callback = alarm->callback;
+    void *data = alarm->data;
+
+    if (alarm->is_periodic) {
+      schedule_next_instance(alarm, true);
+    } else {
+      reschedule_root_alarm();
+
+      alarm->deadline = 0;
+      alarm->callback = NULL;
+      alarm->data = NULL;
+    }
+
+    // Downgrade lock.
+    pthread_mutex_lock(&alarm->callback_lock);
+    pthread_mutex_unlock(&monitor);
+
+    callback(data);
+
+    pthread_mutex_unlock(&alarm->callback_lock);
+  }
 }
diff --git a/osi/src/allocation_tracker.c b/osi/src/allocation_tracker.c
new file mode 100644
index 0000000..baa820b
--- /dev/null
+++ b/osi/src/allocation_tracker.c
@@ -0,0 +1,179 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_osi_allocation_tracker"
+
+#include <assert.h>
+#include <pthread.h>
+#include <stdint.h>
+
+#include "osi/include/allocation_tracker.h"
+#include "osi/include/allocator.h"
+#include "osi/include/hash_functions.h"
+#include "osi/include/hash_map.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+
+typedef struct {
+  uint8_t allocator_id;
+  void *ptr;
+  size_t size;
+  bool freed;
+} allocation_t;
+
+// Hidden constructor for hash map for our use only. Everything else should use the
+// normal interface.
+hash_map_t *hash_map_new_internal(
+    size_t size,
+    hash_index_fn hash_fn,
+    key_free_fn key_fn,
+    data_free_fn,
+    key_equality_fn equality_fn,
+    const allocator_t *zeroed_allocator);
+
+static bool allocation_entry_freed_checker(hash_map_entry_t *entry, void *context);
+static void *untracked_calloc(size_t size);
+
+static const size_t allocation_hash_map_size = 1024;
+static const char *canary = "tinybird";
+static const allocator_t untracked_calloc_allocator = {
+  untracked_calloc,
+  free
+};
+
+static size_t canary_size;
+static hash_map_t *allocations;
+static pthread_mutex_t lock;
+
+void allocation_tracker_init(void) {
+  if (allocations)
+    return;
+
+  canary_size = strlen(canary);
+
+  pthread_mutex_init(&lock, NULL);
+  allocations = hash_map_new_internal(
+    allocation_hash_map_size,
+    hash_function_pointer,
+    NULL,
+    free,
+    NULL,
+    &untracked_calloc_allocator);
+}
+
+// Test function only. Do not call in the normal course of operations.
+void allocation_tracker_uninit(void) {
+  hash_map_free(allocations);
+  allocations = NULL;
+}
+
+void allocation_tracker_reset(void) {
+  if (!allocations)
+    return;
+
+  hash_map_clear(allocations);
+}
+
+size_t allocation_tracker_expect_no_allocations(void) {
+  if (!allocations)
+    return 0;
+
+  pthread_mutex_lock(&lock);
+
+  size_t unfreed_memory_size = 0;
+  hash_map_foreach(allocations, allocation_entry_freed_checker, &unfreed_memory_size);
+
+  pthread_mutex_unlock(&lock);
+
+  return unfreed_memory_size;
+}
+
+void *allocation_tracker_notify_alloc(uint8_t allocator_id, void *ptr, size_t requested_size) {
+  if (!allocations || !ptr)
+    return ptr;
+
+  char *return_ptr = (char *)ptr;
+
+  return_ptr += canary_size;
+
+  pthread_mutex_lock(&lock);
+
+  allocation_t *allocation = (allocation_t *)hash_map_get(allocations, return_ptr);
+  if (allocation) {
+    assert(allocation->freed); // Must have been freed before
+  } else {
+    allocation = (allocation_t *)calloc(1, sizeof(allocation_t));
+    hash_map_set(allocations, return_ptr, allocation);
+  }
+
+  allocation->allocator_id = allocator_id;
+  allocation->freed = false;
+  allocation->size = requested_size;
+  allocation->ptr = return_ptr;
+
+  pthread_mutex_unlock(&lock);
+
+  // Add the canary on both sides
+  memcpy(return_ptr - canary_size, canary, canary_size);
+  memcpy(return_ptr + requested_size, canary, canary_size);
+
+  return return_ptr;
+}
+
+void *allocation_tracker_notify_free(uint8_t allocator_id, void *ptr) {
+  if (!allocations || !ptr)
+    return ptr;
+
+  pthread_mutex_lock(&lock);
+
+  allocation_t *allocation = (allocation_t *)hash_map_get(allocations, ptr);
+  assert(allocation);                               // Must have been tracked before
+  assert(!allocation->freed);                       // Must not be a double free
+  assert(allocation->allocator_id == allocator_id); // Must be from the same allocator
+  allocation->freed = true;
+
+  const char *beginning_canary = ((char *)ptr) - canary_size;
+  const char *end_canary = ((char *)ptr) + allocation->size;
+
+  for (size_t i = 0; i < canary_size; i++) {
+    assert(beginning_canary[i] == canary[i]);
+    assert(end_canary[i] == canary[i]);
+  }
+
+  pthread_mutex_unlock(&lock);
+
+  return ((char *)ptr) - canary_size;
+}
+
+size_t allocation_tracker_resize_for_canary(size_t size) {
+  return (!allocations) ? size : size + (2 * canary_size);
+}
+
+static bool allocation_entry_freed_checker(hash_map_entry_t *entry, void *context) {
+  allocation_t *allocation = (allocation_t *)entry->data;
+  if (!allocation->freed) {
+    *((size_t *)context) += allocation->size; // Report back the unfreed byte count
+    LOG_ERROR("%s found unfreed allocation. address: 0x%x size: %d bytes", __func__, (uintptr_t)allocation->ptr, allocation->size);
+  }
+
+  return true;
+}
+
+static void *untracked_calloc(size_t size) {
+  return calloc(size, 1);
+}
diff --git a/osi/src/allocator.c b/osi/src/allocator.c
new file mode 100644
index 0000000..cd291b0
--- /dev/null
+++ b/osi/src/allocator.c
@@ -0,0 +1,69 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <stdlib.h>
+
+#include "osi/include/allocator.h"
+#include "osi/include/allocation_tracker.h"
+
+static const allocator_id_t alloc_allocator_id = 42;
+
+char *osi_strdup(const char *str) {
+  size_t size = strlen(str) + 1;  // + 1 for the null terminator
+  size_t real_size = allocation_tracker_resize_for_canary(size);
+
+  char *new_string = allocation_tracker_notify_alloc(
+    alloc_allocator_id,
+    malloc(real_size),
+    size);
+  if (!new_string)
+    return NULL;
+
+  memcpy(new_string, str, size);
+  return new_string;
+}
+
+void *osi_malloc(size_t size) {
+  size_t real_size = allocation_tracker_resize_for_canary(size);
+  return allocation_tracker_notify_alloc(
+    alloc_allocator_id,
+    malloc(real_size),
+    size);
+}
+
+void *osi_calloc(size_t size) {
+  size_t real_size = allocation_tracker_resize_for_canary(size);
+  return allocation_tracker_notify_alloc(
+    alloc_allocator_id,
+    calloc(1, real_size),
+    size);
+}
+
+void osi_free(void *ptr) {
+  free(allocation_tracker_notify_free(alloc_allocator_id, ptr));
+}
+
+const allocator_t allocator_malloc = {
+  osi_malloc,
+  osi_free
+};
+
+const allocator_t allocator_calloc = {
+  osi_calloc,
+  osi_free
+};
diff --git a/osi/src/array.c b/osi/src/array.c
new file mode 100644
index 0000000..fb11887
--- /dev/null
+++ b/osi/src/array.c
@@ -0,0 +1,111 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_osi_array"
+
+#include <assert.h>
+
+#include "osi/include/allocator.h"
+#include "osi/include/array.h"
+#include "osi/include/log.h"
+
+struct array_t {
+  size_t element_size;
+  size_t length;
+  size_t capacity;
+  uint8_t *data;
+  uint8_t internal_storage[];
+};
+
+static bool grow(array_t *array);
+
+static const size_t INTERNAL_ELEMENTS = 16;
+
+array_t *array_new(size_t element_size) {
+  assert(element_size > 0);
+
+  array_t *array = osi_calloc(sizeof(array_t) + element_size * INTERNAL_ELEMENTS);
+  if (!array) {
+    LOG_ERROR("%s unable to allocate memory for array with elements of size %zu.", __func__, element_size);
+    return NULL;
+  }
+
+  array->element_size = element_size;
+  array->capacity = INTERNAL_ELEMENTS;
+  array->data = array->internal_storage;
+  return array;
+}
+
+void array_free(array_t *array) {
+  if (!array)
+    return;
+
+  if (array->data != array->internal_storage)
+    free(array->data);
+
+  osi_free(array);
+}
+
+void *array_ptr(const array_t *array) {
+  return array_at(array, 0);
+}
+
+void *array_at(const array_t *array, size_t index) {
+  assert(array != NULL);
+  assert(index < array->length);
+  return array->data + (index * array->element_size);
+}
+
+size_t array_length(const array_t *array) {
+  assert(array != NULL);
+  return array->length;
+}
+
+bool array_append_value(array_t *array, uint32_t value) {
+  return array_append_ptr(array, &value);
+}
+
+bool array_append_ptr(array_t *array, void *data) {
+  assert(array != NULL);
+  assert(data != NULL);
+
+  if (array->length == array->capacity && !grow(array)) {
+    LOG_ERROR("%s unable to grow array past current capacity of %zu elements of size %zu.", __func__, array->capacity, array->element_size);
+    return false;
+  }
+
+  ++array->length;
+  memcpy(array_at(array, array->length - 1), data, array->element_size);
+  return true;
+}
+
+static bool grow(array_t *array) {
+  const size_t new_capacity = array->capacity + (array->capacity / 2);
+  const bool is_moving = (array->data == array->internal_storage);
+
+  void *new_data = realloc(is_moving ? NULL : array->data, new_capacity * array->element_size);
+  if (!new_data)
+    return false;
+
+  if (is_moving)
+    memcpy(new_data, array->internal_storage, array->length * array->element_size);
+
+  array->data = new_data;
+  array->capacity = new_capacity;
+  return true;
+}
diff --git a/osi/src/buffer.c b/osi/src/buffer.c
new file mode 100644
index 0000000..ebf51aa
--- /dev/null
+++ b/osi/src/buffer.c
@@ -0,0 +1,99 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_osi_buffer"
+
+#include <assert.h>
+#include <stdint.h>
+
+#include "osi/include/allocator.h"
+#include "osi/include/buffer.h"
+#include "osi/include/log.h"
+
+struct buffer_t {
+  buffer_t *root;
+  size_t refcount;
+  size_t length;
+  uint8_t data[];
+};
+
+buffer_t *buffer_new(size_t size) {
+  assert(size > 0);
+
+  buffer_t *buffer = osi_calloc(sizeof(buffer_t) + size);
+  if (!buffer) {
+    LOG_ERROR("%s unable to allocate buffer of %zu bytes.", __func__, size);
+    return NULL;
+  }
+
+  buffer->root = buffer;
+  buffer->refcount = 1;
+  buffer->length = size;
+
+  return buffer;
+}
+
+buffer_t *buffer_new_ref(const buffer_t *buf) {
+  assert(buf != NULL);
+  return buffer_new_slice(buf, buf->length);
+}
+
+buffer_t *buffer_new_slice(const buffer_t *buf, size_t slice_size) {
+  assert(buf != NULL);
+  assert(slice_size > 0);
+  assert(slice_size <= buf->length);
+
+  buffer_t *ret = osi_calloc(sizeof(buffer_t));
+  if (!ret) {
+    LOG_ERROR("%s unable to allocate new buffer for slice of length %zu.", __func__, slice_size);
+    return NULL;
+  }
+
+  ret->root = buf->root;
+  ret->refcount = SIZE_MAX;
+  ret->length = slice_size;
+
+  ++buf->root->refcount;
+
+  return ret;
+}
+
+void buffer_free(buffer_t *buffer) {
+  if (!buffer)
+    return;
+
+  if (buffer->root != buffer) {
+    // We're a leaf node. Delete the root node if we're the last referent.
+    if (--buffer->root->refcount == 0)
+      osi_free(buffer->root);
+    osi_free(buffer);
+  } else if (--buffer->refcount == 0) {
+    // We're a root node. Roots are only deleted when their refcount goes to 0.
+    osi_free(buffer);
+  }
+}
+
+void *buffer_ptr(const buffer_t *buf) {
+  assert(buf != NULL);
+  return buf->root->data + buf->root->length - buf->length;
+}
+
+size_t buffer_length(const buffer_t *buf) {
+  assert(buf != NULL);
+  return buf->length;
+}
diff --git a/osi/src/config.c b/osi/src/config.c
index f13f961..a98faa2 100644
--- a/osi/src/config.c
+++ b/osi/src/config.c
@@ -1,3 +1,21 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
 #define LOG_TAG "bt_osi_config"
 
 #include <assert.h>
@@ -6,10 +24,11 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <utils/Log.h>
 
-#include "config.h"
-#include "list.h"
+#include "osi/include/allocator.h"
+#include "osi/include/config.h"
+#include "osi/include/list.h"
+#include "osi/include/log.h"
 
 typedef struct {
   char *key;
@@ -25,6 +44,9 @@
   list_t *sections;
 };
 
+// Empty definition; this type is aliased to list_node_t.
+struct config_section_iter_t {};
+
 static void config_parse(FILE *fp, config_t *config);
 
 static section_t *section_new(const char *name);
@@ -35,27 +57,41 @@
 static void entry_free(void *ptr);
 static entry_t *entry_find(const config_t *config, const char *section, const char *key);
 
-config_t *config_new(const char *filename) {
-  assert(filename != NULL);
-
-  FILE *fp = fopen(filename, "rt");
-  if (!fp) {
-    ALOGE("%s unable to open file '%s': %s", __func__, filename, strerror(errno));
-    return NULL;
-  }
-
-  config_t *config = calloc(1, sizeof(config_t));
+config_t *config_new_empty(void) {
+  config_t *config = osi_calloc(sizeof(config_t));
   if (!config) {
-    ALOGE("%s unable to allocate memory for config_t.", __func__);
-    fclose(fp);
-    return NULL;
+    LOG_ERROR("%s unable to allocate memory for config_t.", __func__);
+    goto error;
   }
 
   config->sections = list_new(section_free);
+  if (!config->sections) {
+    LOG_ERROR("%s unable to allocate list for sections.", __func__);
+    goto error;
+  }
+
+  return config;
+
+error:;
+  config_free(config);
+  return NULL;
+}
+
+config_t *config_new(const char *filename) {
+  assert(filename != NULL);
+
+  config_t *config = config_new_empty();
+  if (!config)
+    return NULL;
+
+  FILE *fp = fopen(filename, "rt");
+  if (!fp) {
+    LOG_ERROR("%s unable to open file '%s': %s", __func__, filename, strerror(errno));
+    config_free(config);
+    return NULL;
+  }
   config_parse(fp, config);
-
   fclose(fp);
-
   return config;
 }
 
@@ -64,7 +100,7 @@
     return;
 
   list_free(config->sections);
-  free(config);
+  osi_free(config);
 }
 
 bool config_has_section(const config_t *config, const char *section) {
@@ -153,8 +189,8 @@
   for (const list_node_t *node = list_begin(sec->entries); node != list_end(sec->entries); node = list_next(node)) {
     entry_t *entry = list_node(node);
     if (!strcmp(entry->key, key)) {
-      free(entry->value);
-      entry->value = strdup(value);
+      osi_free(entry->value);
+      entry->value = osi_strdup(value);
       return;
     }
   }
@@ -163,6 +199,103 @@
   list_append(sec->entries, entry);
 }
 
+bool config_remove_section(config_t *config, const char *section) {
+  assert(config != NULL);
+  assert(section != NULL);
+
+  section_t *sec = section_find(config, section);
+  if (!sec)
+    return false;
+
+  return list_remove(config->sections, sec);
+}
+
+bool config_remove_key(config_t *config, const char *section, const char *key) {
+  assert(config != NULL);
+  assert(section != NULL);
+  assert(key != NULL);
+
+  section_t *sec = section_find(config, section);
+  entry_t *entry = entry_find(config, section, key);
+  if (!sec || !entry)
+    return false;
+
+  return list_remove(sec->entries, entry);
+}
+
+const config_section_node_t *config_section_begin(const config_t *config) {
+  assert(config != NULL);
+  return (const config_section_node_t *)list_begin(config->sections);
+}
+
+const config_section_node_t *config_section_end(const config_t *config) {
+  assert(config != NULL);
+  return (const config_section_node_t *)list_end(config->sections);
+}
+
+const config_section_node_t *config_section_next(const config_section_node_t *node) {
+  assert(node != NULL);
+  return (const config_section_node_t *)list_next((const list_node_t *)node);
+}
+
+const char *config_section_name(const config_section_node_t *node) {
+  assert(node != NULL);
+  const list_node_t *lnode = (const list_node_t *)node;
+  const section_t *section = (const section_t *)list_node(lnode);
+  return section->name;
+}
+
+bool config_save(const config_t *config, const char *filename) {
+  assert(config != NULL);
+  assert(filename != NULL);
+  assert(*filename != '\0');
+
+  char *temp_filename = osi_calloc(strlen(filename) + 5);
+  if (!temp_filename) {
+    LOG_ERROR("%s unable to allocate memory for filename.", __func__);
+    return false;
+  }
+
+  strcpy(temp_filename, filename);
+  strcat(temp_filename, ".new");
+
+  FILE *fp = fopen(temp_filename, "wt");
+  if (!fp) {
+    LOG_ERROR("%s unable to write file '%s': %s", __func__, temp_filename, strerror(errno));
+    goto error;
+  }
+
+  for (const list_node_t *node = list_begin(config->sections); node != list_end(config->sections); node = list_next(node)) {
+    const section_t *section = (const section_t *)list_node(node);
+    fprintf(fp, "[%s]\n", section->name);
+
+    for (const list_node_t *enode = list_begin(section->entries); enode != list_end(section->entries); enode = list_next(enode)) {
+      const entry_t *entry = (const entry_t *)list_node(enode);
+      fprintf(fp, "%s = %s\n", entry->key, entry->value);
+    }
+
+    // Only add a separating newline if there are more sections.
+    if (list_next(node) != list_end(config->sections))
+      fputc('\n', fp);
+  }
+
+  fflush(fp);
+  fclose(fp);
+
+  if (rename(temp_filename, filename) == -1) {
+    LOG_ERROR("%s unable to commit file '%s': %s", __func__, filename, strerror(errno));
+    goto error;
+  }
+
+  osi_free(temp_filename);
+  return true;
+
+error:;
+  unlink(temp_filename);
+  osi_free(temp_filename);
+  return false;
+}
+
 static char *trim(char *str) {
   while (isspace(*str))
     ++str;
@@ -198,7 +331,7 @@
     if (*line_ptr == '[') {
       size_t len = strlen(line_ptr);
       if (line_ptr[len - 1] != ']') {
-        ALOGD("%s unterminated section name on line %d.", __func__, line_num);
+        LOG_DEBUG("%s unterminated section name on line %d.", __func__, line_num);
         continue;
       }
       strncpy(section, line_ptr + 1, len - 2);
@@ -206,7 +339,7 @@
     } else {
       char *split = strchr(line_ptr, '=');
       if (!split) {
-        ALOGD("%s no key/value separator found on line %d.", __func__, line_num);
+        LOG_DEBUG("%s no key/value separator found on line %d.", __func__, line_num);
         continue;
       }
 
@@ -217,11 +350,11 @@
 }
 
 static section_t *section_new(const char *name) {
-  section_t *section = calloc(1, sizeof(section_t));
+  section_t *section = osi_calloc(sizeof(section_t));
   if (!section)
     return NULL;
 
-  section->name = strdup(name);
+  section->name = osi_strdup(name);
   section->entries = list_new(entry_free);
   return section;
 }
@@ -231,8 +364,9 @@
     return;
 
   section_t *section = ptr;
-  free(section->name);
+  osi_free(section->name);
   list_free(section->entries);
+  osi_free(section);
 }
 
 static section_t *section_find(const config_t *config, const char *section) {
@@ -246,12 +380,12 @@
 }
 
 static entry_t *entry_new(const char *key, const char *value) {
-  entry_t *entry = calloc(1, sizeof(entry_t));
+  entry_t *entry = osi_calloc(sizeof(entry_t));
   if (!entry)
     return NULL;
 
-  entry->key = strdup(key);
-  entry->value = strdup(value);
+  entry->key = osi_strdup(key);
+  entry->value = osi_strdup(value);
   return entry;
 }
 
@@ -260,8 +394,9 @@
     return;
 
   entry_t *entry = ptr;
-  free(entry->key);
-  free(entry->value);
+  osi_free(entry->key);
+  osi_free(entry->value);
+  osi_free(entry);
 }
 
 static entry_t *entry_find(const config_t *config, const char *section, const char *key) {
diff --git a/osi/src/data_dispatcher.c b/osi/src/data_dispatcher.c
new file mode 100644
index 0000000..4f27f8a
--- /dev/null
+++ b/osi/src/data_dispatcher.c
@@ -0,0 +1,106 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_osi_data_dispatcher"
+
+#include <assert.h>
+
+#include "osi/include/allocator.h"
+#include "osi/include/data_dispatcher.h"
+#include "osi/include/hash_functions.h"
+#include "osi/include/hash_map.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+
+#define DEFAULT_TABLE_BUCKETS 10
+
+struct data_dispatcher_t {
+  char *name;
+  hash_map_t *dispatch_table;
+  fixed_queue_t *default_queue; // We don't own this queue
+};
+
+data_dispatcher_t *data_dispatcher_new(const char *name) {
+  assert(name != NULL);
+
+  data_dispatcher_t *ret = osi_calloc(sizeof(data_dispatcher_t));
+  if (!ret) {
+    LOG_ERROR("%s unable to allocate memory for new data dispatcher.", __func__);
+    goto error;
+  }
+
+  ret->dispatch_table = hash_map_new(DEFAULT_TABLE_BUCKETS, hash_function_naive, NULL, NULL, NULL);
+  if (!ret->dispatch_table) {
+    LOG_ERROR("%s unable to create dispatch table.", __func__);
+    goto error;
+  }
+
+  ret->name = osi_strdup(name);
+  if (!ret->name) {
+    LOG_ERROR("%s unable to duplicate provided name.", __func__);
+    goto error;
+  }
+
+  return ret;
+
+error:;
+  data_dispatcher_free(ret);
+  return NULL;
+}
+
+void data_dispatcher_free(data_dispatcher_t *dispatcher) {
+  if (!dispatcher)
+    return;
+
+  hash_map_free(dispatcher->dispatch_table);
+
+  if (dispatcher->name)
+    osi_free(dispatcher->name);
+
+  osi_free(dispatcher);
+}
+
+void data_dispatcher_register(data_dispatcher_t *dispatcher, data_dispatcher_type_t type, fixed_queue_t *queue) {
+  assert(dispatcher != NULL);
+
+  hash_map_erase(dispatcher->dispatch_table, (void *)type);
+  if (queue)
+    hash_map_set(dispatcher->dispatch_table, (void *)type, queue);
+}
+
+void data_dispatcher_register_default(data_dispatcher_t *dispatcher, fixed_queue_t *queue) {
+  assert(dispatcher != NULL);
+
+  dispatcher->default_queue = queue;
+}
+
+bool data_dispatcher_dispatch(data_dispatcher_t *dispatcher, data_dispatcher_type_t type, void *data) {
+  assert(dispatcher != NULL);
+  assert(data != NULL);
+
+  fixed_queue_t *queue = hash_map_get(dispatcher->dispatch_table, (void *)type);
+  if (!queue)
+    queue = dispatcher->default_queue;
+
+  if (queue)
+    fixed_queue_enqueue(queue, data);
+  else
+    LOG_WARN("%s has no handler for type (%d) in data dispatcher named: %s", __func__, type, dispatcher->name);
+
+  return queue != NULL;
+}
diff --git a/osi/src/eager_reader.c b/osi/src/eager_reader.c
new file mode 100644
index 0000000..f121754
--- /dev/null
+++ b/osi/src/eager_reader.c
@@ -0,0 +1,251 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_osi_eager_reader"
+
+#include <assert.h>
+#include <errno.h>
+#include <stddef.h>
+#include <sys/eventfd.h>
+
+#include "osi/include/allocator.h"
+#include "osi/include/eager_reader.h"
+#include "osi/include/fixed_queue.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/reactor.h"
+#include "osi/include/thread.h"
+
+#if !defined(EFD_SEMAPHORE)
+#  define EFD_SEMAPHORE (1 << 0)
+#endif
+
+typedef struct {
+  size_t length;
+  size_t offset;
+  uint8_t data[];
+} data_buffer_t;
+
+struct eager_reader_t {
+  int bytes_available_fd; // semaphore mode eventfd which counts the number of available bytes
+  int inbound_fd;
+
+  const allocator_t *allocator;
+  size_t buffer_size;
+  fixed_queue_t *buffers;
+  data_buffer_t *current_buffer;
+
+  thread_t *inbound_read_thread;
+  reactor_object_t *inbound_read_object;
+
+  reactor_object_t *outbound_registration;
+  eager_reader_cb outbound_read_ready;
+  void *outbound_context;
+};
+
+static bool has_byte(const eager_reader_t *reader);
+static void inbound_data_waiting(void *context);
+static void internal_outbound_read_ready(void *context);
+
+eager_reader_t *eager_reader_new(
+    int fd_to_read,
+    const allocator_t *allocator,
+    size_t buffer_size,
+    size_t max_buffer_count,
+    const char *thread_name) {
+
+  assert(fd_to_read != INVALID_FD);
+  assert(allocator != NULL);
+  assert(buffer_size > 0);
+  assert(max_buffer_count > 0);
+  assert(thread_name != NULL && *thread_name != '\0');
+
+  eager_reader_t *ret = osi_calloc(sizeof(eager_reader_t));
+  if (!ret) {
+    LOG_ERROR("%s unable to allocate memory for new eager_reader.", __func__);
+    goto error;
+  }
+
+  ret->allocator = allocator;
+  ret->inbound_fd = fd_to_read;
+
+  ret->bytes_available_fd = eventfd(0, EFD_SEMAPHORE);
+  if (ret->bytes_available_fd == INVALID_FD) {
+    LOG_ERROR("%s unable to create output reading semaphore.", __func__);
+    goto error;
+  }
+
+  ret->buffer_size = buffer_size;
+
+  ret->buffers = fixed_queue_new(max_buffer_count);
+  if (!ret->buffers) {
+    LOG_ERROR("%s unable to create buffers queue.", __func__);
+    goto error;
+  }
+
+  ret->inbound_read_thread = thread_new(thread_name);
+  if (!ret->inbound_read_thread) {
+    LOG_ERROR("%s unable to make reading thread.", __func__);
+    goto error;
+  }
+
+  ret->inbound_read_object = reactor_register(
+    thread_get_reactor(ret->inbound_read_thread),
+    fd_to_read,
+    ret,
+    inbound_data_waiting,
+    NULL
+  );
+
+  return ret;
+
+error:;
+  eager_reader_free(ret);
+  return NULL;
+}
+
+void eager_reader_free(eager_reader_t *reader) {
+  if (!reader)
+    return;
+
+  eager_reader_unregister(reader);
+
+  // Only unregister from the input if we actually did register
+  if (reader->inbound_read_object)
+    reactor_unregister(reader->inbound_read_object);
+
+  if (reader->bytes_available_fd != INVALID_FD)
+    close(reader->bytes_available_fd);
+
+  // Free the current buffer, because it's not in the queue
+  // and won't be freed below
+  if (reader->current_buffer)
+    reader->allocator->free(reader->current_buffer);
+
+  fixed_queue_free(reader->buffers, reader->allocator->free);
+  thread_free(reader->inbound_read_thread);
+  osi_free(reader);
+}
+
+void eager_reader_register(eager_reader_t *reader, reactor_t *reactor, eager_reader_cb read_cb, void *context) {
+  assert(reader != NULL);
+  assert(reactor != NULL);
+  assert(read_cb != NULL);
+
+  // Make sure the reader isn't currently registered.
+  eager_reader_unregister(reader);
+
+  reader->outbound_read_ready = read_cb;
+  reader->outbound_context = context;
+  reader->outbound_registration = reactor_register(reactor, reader->bytes_available_fd, reader, internal_outbound_read_ready, NULL);
+}
+
+void eager_reader_unregister(eager_reader_t *reader) {
+  assert(reader != NULL);
+
+  if (reader->outbound_registration) {
+    reactor_unregister(reader->outbound_registration);
+    reader->outbound_registration = NULL;
+  }
+}
+
+// SEE HEADER FOR THREAD SAFETY NOTE
+size_t eager_reader_read(eager_reader_t *reader, uint8_t *buffer, size_t max_size, bool block) {
+  assert(reader != NULL);
+  assert(buffer != NULL);
+
+  size_t bytes_read = 0;
+
+  while (bytes_read < max_size) {
+    if (!block && !has_byte(reader))
+      return bytes_read;
+
+    eventfd_t value;
+    if (eventfd_read(reader->bytes_available_fd, &value) == -1)
+      LOG_ERROR("%s unable to read semaphore for output data.", __func__);
+
+    if (!reader->current_buffer)
+      reader->current_buffer = fixed_queue_dequeue(reader->buffers);
+
+    buffer[bytes_read] = reader->current_buffer->data[reader->current_buffer->offset];
+    reader->current_buffer->offset++;
+    bytes_read++;
+
+    // Prep for next byte
+    if (reader->current_buffer->offset >= reader->current_buffer->length) {
+      reader->allocator->free(reader->current_buffer);
+      reader->current_buffer = NULL;
+    }
+  }
+
+  return bytes_read;
+}
+
+static bool has_byte(const eager_reader_t *reader) {
+  assert(reader != NULL);
+
+  fd_set read_fds;
+  FD_ZERO(&read_fds);
+  FD_SET(reader->bytes_available_fd, &read_fds);
+
+  // Immediate timeout
+  struct timeval timeout;
+  timeout.tv_sec = 0;
+  timeout.tv_usec = 0;
+
+  select(reader->bytes_available_fd + 1, &read_fds, NULL, NULL, &timeout);
+  return FD_ISSET(reader->bytes_available_fd, &read_fds);
+}
+
+static void inbound_data_waiting(void *context) {
+  eager_reader_t *reader = (eager_reader_t *)context;
+
+  data_buffer_t *buffer = (data_buffer_t *)reader->allocator->alloc(reader->buffer_size + sizeof(data_buffer_t));
+  if (!buffer) {
+    LOG_ERROR("%s couldn't aquire memory for inbound data buffer.", __func__);
+    return;
+  }
+
+  buffer->length = 0;
+  buffer->offset = 0;
+
+  int bytes_read = read(reader->inbound_fd, buffer->data, reader->buffer_size);
+  if (bytes_read > 0) {
+    // Save the data for later
+    buffer->length = bytes_read;
+    fixed_queue_enqueue(reader->buffers, buffer);
+
+    // Tell consumers data is available by incrementing
+    // the semaphore by the number of bytes we just read
+    eventfd_write(reader->bytes_available_fd, bytes_read);
+  } else {
+    if (bytes_read == 0)
+      LOG_WARN("%s fd said bytes existed, but none were found.", __func__);
+    else
+      LOG_WARN("%s unable to read from file descriptor: %s", __func__, strerror(errno));
+
+    reader->allocator->free(buffer);
+  }
+}
+
+static void internal_outbound_read_ready(void *context) {
+  assert(context != NULL);
+
+  eager_reader_t *reader = (eager_reader_t *)context;
+  reader->outbound_read_ready(reader, reader->outbound_context);
+}
diff --git a/osi/src/fixed_queue.c b/osi/src/fixed_queue.c
index b27659c..c83c516 100644
--- a/osi/src/fixed_queue.c
+++ b/osi/src/fixed_queue.c
@@ -20,10 +20,12 @@
 #include <pthread.h>
 #include <stdlib.h>
 
-#include "fixed_queue.h"
-#include "list.h"
-#include "osi.h"
-#include "semaphore.h"
+#include "osi/include/allocator.h"
+#include "osi/include/fixed_queue.h"
+#include "osi/include/list.h"
+#include "osi/include/osi.h"
+#include "osi/include/semaphore.h"
+#include "osi/include/reactor.h"
 
 struct fixed_queue_t {
   list_t *list;
@@ -31,13 +33,22 @@
   semaphore_t *dequeue_sem;
   pthread_mutex_t lock;
   size_t capacity;
-};
+
+  reactor_object_t *dequeue_object;
+  fixed_queue_cb dequeue_ready;
+  void *dequeue_context;
+} fixed_queue_t;
+
+static void internal_dequeue_ready(void *context);
 
 fixed_queue_t *fixed_queue_new(size_t capacity) {
-  fixed_queue_t *ret = calloc(1, sizeof(fixed_queue_t));
+  fixed_queue_t *ret = osi_calloc(sizeof(fixed_queue_t));
   if (!ret)
     goto error;
 
+  pthread_mutex_init(&ret->lock, NULL);
+  ret->capacity = capacity;
+
   ret->list = list_new(NULL);
   if (!ret->list)
     goto error;
@@ -50,19 +61,10 @@
   if (!ret->dequeue_sem)
     goto error;
 
-  pthread_mutex_init(&ret->lock, NULL);
-  ret->capacity = capacity;
-
   return ret;
 
 error:;
-  if (ret) {
-    list_free(ret->list);
-    semaphore_free(ret->enqueue_sem);
-    semaphore_free(ret->dequeue_sem);
-  }
-
-  free(ret);
+  fixed_queue_free(ret, NULL);
   return NULL;
 }
 
@@ -70,6 +72,8 @@
   if (!queue)
     return;
 
+  fixed_queue_unregister_dequeue(queue);
+
   if (free_cb)
     for (const list_node_t *node = list_begin(queue->list); node != list_end(queue->list); node = list_next(node))
       free_cb(list_node(node));
@@ -78,7 +82,23 @@
   semaphore_free(queue->enqueue_sem);
   semaphore_free(queue->dequeue_sem);
   pthread_mutex_destroy(&queue->lock);
-  free(queue);
+  osi_free(queue);
+}
+
+bool fixed_queue_is_empty(fixed_queue_t *queue) {
+  assert(queue != NULL);
+
+  pthread_mutex_lock(&queue->lock);
+  bool is_empty = list_is_empty(queue->list);
+  pthread_mutex_unlock(&queue->lock);
+
+  return is_empty;
+}
+
+size_t fixed_queue_capacity(fixed_queue_t *queue) {
+  assert(queue != NULL);
+
+  return queue->capacity;
 }
 
 void fixed_queue_enqueue(fixed_queue_t *queue, void *data) {
@@ -140,6 +160,17 @@
   return ret;
 }
 
+void *fixed_queue_try_peek(fixed_queue_t *queue) {
+  assert(queue != NULL);
+
+  pthread_mutex_lock(&queue->lock);
+  // Because protected by the lock, the empty and front calls are atomic and not a race condition
+  void *ret = list_is_empty(queue->list) ? NULL : list_front(queue->list);
+  pthread_mutex_unlock(&queue->lock);
+
+  return ret;
+}
+
 int fixed_queue_get_dequeue_fd(const fixed_queue_t *queue) {
   assert(queue != NULL);
   return semaphore_get_fd(queue->dequeue_sem);
@@ -149,3 +180,38 @@
   assert(queue != NULL);
   return semaphore_get_fd(queue->enqueue_sem);
 }
+
+void fixed_queue_register_dequeue(fixed_queue_t *queue, reactor_t *reactor, fixed_queue_cb ready_cb, void *context) {
+  assert(queue != NULL);
+  assert(reactor != NULL);
+  assert(ready_cb != NULL);
+
+  // Make sure we're not already registered
+  fixed_queue_unregister_dequeue(queue);
+
+  queue->dequeue_ready = ready_cb;
+  queue->dequeue_context = context;
+  queue->dequeue_object = reactor_register(
+    reactor,
+    fixed_queue_get_dequeue_fd(queue),
+    queue,
+    internal_dequeue_ready,
+    NULL
+  );
+}
+
+void fixed_queue_unregister_dequeue(fixed_queue_t *queue) {
+  assert(queue != NULL);
+
+  if (queue->dequeue_object) {
+    reactor_unregister(queue->dequeue_object);
+    queue->dequeue_object = NULL;
+  }
+}
+
+static void internal_dequeue_ready(void *context) {
+  assert(context != NULL);
+
+  fixed_queue_t *queue = context;
+  queue->dequeue_ready(queue, queue->dequeue_context);
+}
diff --git a/osi/src/future.c b/osi/src/future.c
new file mode 100644
index 0000000..be140ad
--- /dev/null
+++ b/osi/src/future.c
@@ -0,0 +1,99 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_osi_future"
+
+#include <assert.h>
+
+#include "osi/include/allocator.h"
+#include "osi/include/future.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/semaphore.h"
+
+struct future_t {
+  bool ready_can_be_called;
+  semaphore_t *semaphore; // NULL semaphore means immediate future
+  void *result;
+};
+
+static void future_free(future_t *future);
+
+future_t *future_new(void) {
+  future_t *ret = osi_calloc(sizeof(future_t));
+  if (!ret) {
+    LOG_ERROR("%s unable to allocate memory for return value.", __func__);
+    goto error;
+  }
+
+  ret->semaphore = semaphore_new(0);
+  if (!ret->semaphore) {
+    LOG_ERROR("%s unable to allocate memory for the semaphore.", __func__);
+    goto error;
+  }
+
+  ret->ready_can_be_called = true;
+  return ret;
+error:;
+  future_free(ret);
+  return NULL;
+}
+
+future_t *future_new_immediate(void *value) {
+  future_t *ret = osi_calloc(sizeof(future_t));
+  if (!ret) {
+    LOG_ERROR("%s unable to allocate memory for return value.", __func__);
+    goto error;
+  }
+
+  ret->result = value;
+  ret->ready_can_be_called = false;
+ return ret;
+error:;
+  future_free(ret);
+  return NULL;
+}
+
+void future_ready(future_t *future, void *value) {
+  assert(future != NULL);
+  assert(future->ready_can_be_called);
+
+  future->ready_can_be_called = false;
+  future->result = value;
+  semaphore_post(future->semaphore);
+}
+
+void *future_await(future_t *future) {
+  assert(future != NULL);
+
+  // If the future is immediate, it will not have a semaphore
+  if (future->semaphore)
+    semaphore_wait(future->semaphore);
+
+  void *result = future->result;
+  future_free(future);
+  return result;
+}
+
+static void future_free(future_t *future) {
+  if (!future)
+    return;
+
+  semaphore_free(future->semaphore);
+  osi_free(future);
+}
diff --git a/osi/src/hash_functions.c b/osi/src/hash_functions.c
new file mode 100644
index 0000000..e7e7cef
--- /dev/null
+++ b/osi/src/hash_functions.c
@@ -0,0 +1,42 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <string.h>
+
+#include "osi/include/hash_functions.h"
+
+hash_index_t hash_function_naive(const void *key) {
+  return (hash_index_t)key;
+}
+
+hash_index_t hash_function_integer(const void *key) {
+  return ((hash_index_t)key) * 2654435761;
+}
+
+hash_index_t hash_function_pointer(const void *key) {
+  return ((hash_index_t)key) * 2654435761;
+}
+
+hash_index_t hash_function_string(const void *key) {
+  hash_index_t hash = 5381;
+  const char *name = (const char *)key;
+  size_t string_len = strlen(name);
+  for (size_t i = 0; i < string_len; ++i)
+    hash = ((hash << 5) + hash ) + name[i];
+  return hash;
+}
diff --git a/osi/src/hash_map.c b/osi/src/hash_map.c
new file mode 100644
index 0000000..6d36ec3
--- /dev/null
+++ b/osi/src/hash_map.c
@@ -0,0 +1,245 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <assert.h>
+#include <list.h>
+#include <hash_map.h>
+
+#include "osi/include/allocator.h"
+
+struct hash_map_t;
+
+typedef struct hash_map_bucket_t {
+  list_t *list;
+} hash_map_bucket_t;
+
+typedef struct hash_map_t {
+  hash_map_bucket_t *bucket;
+  size_t num_bucket;
+  size_t hash_size;
+  hash_index_fn hash_fn;
+  key_free_fn key_fn;
+  data_free_fn data_fn;
+  const allocator_t *allocator;
+  key_equality_fn keys_are_equal;
+} hash_map_t;
+
+// Hidden constructor for list, only to be used by us.
+list_t *list_new_internal(list_free_cb callback, const allocator_t *zeroed_allocator);
+
+static void bucket_free_(void *data);
+static bool default_key_equality(const void *x, const void *y);
+static hash_map_entry_t *find_bucket_entry_(list_t *hash_bucket_list,
+    const void *key);
+
+// Hidden constructor, only to be used by the allocation tracker. Behaves the same as
+// |hash_map_new|, except you get to specify the allocator.
+hash_map_t *hash_map_new_internal(
+    size_t num_bucket,
+    hash_index_fn hash_fn,
+    key_free_fn key_fn,
+    data_free_fn data_fn,
+    key_equality_fn equality_fn,
+    const allocator_t *zeroed_allocator) {
+  assert(hash_fn != NULL);
+  assert(num_bucket > 0);
+  assert(zeroed_allocator != NULL);
+
+  hash_map_t *hash_map = zeroed_allocator->alloc(sizeof(hash_map_t));
+  if (hash_map == NULL)
+    return NULL;
+
+  hash_map->hash_fn = hash_fn;
+  hash_map->key_fn = key_fn;
+  hash_map->data_fn = data_fn;
+  hash_map->allocator = zeroed_allocator;
+  hash_map->keys_are_equal = equality_fn ? equality_fn : default_key_equality;
+
+  hash_map->num_bucket = num_bucket;
+  hash_map->bucket = zeroed_allocator->alloc(sizeof(hash_map_bucket_t) * num_bucket);
+  if (hash_map->bucket == NULL) {
+    zeroed_allocator->free(hash_map);
+    return NULL;
+  }
+  return hash_map;
+}
+
+hash_map_t *hash_map_new(
+    size_t num_bucket,
+    hash_index_fn hash_fn,
+    key_free_fn key_fn,
+    data_free_fn data_fn,
+    key_equality_fn equality_fn) {
+  return hash_map_new_internal(num_bucket, hash_fn, key_fn, data_fn, equality_fn, &allocator_calloc);
+}
+
+void hash_map_free(hash_map_t *hash_map) {
+  if (hash_map == NULL)
+    return;
+  hash_map_clear(hash_map);
+  hash_map->allocator->free(hash_map->bucket);
+  hash_map->allocator->free(hash_map);
+}
+
+bool hash_map_is_empty(const hash_map_t *hash_map) {
+  assert(hash_map != NULL);
+  return (hash_map->hash_size == 0);
+}
+
+size_t hash_map_size(const hash_map_t *hash_map) {
+  assert(hash_map != NULL);
+  return hash_map->hash_size;
+}
+
+size_t hash_map_num_buckets(const hash_map_t *hash_map) {
+  assert(hash_map != NULL);
+  return hash_map->num_bucket;
+}
+
+bool hash_map_has_key(const hash_map_t *hash_map, const void *key) {
+  assert(hash_map != NULL);
+
+  hash_index_t hash_key = hash_map->hash_fn(key) % hash_map->num_bucket;
+  list_t *hash_bucket_list = hash_map->bucket[hash_key].list;
+
+  hash_map_entry_t *hash_map_entry = find_bucket_entry_(hash_bucket_list, key);
+  return (hash_map_entry != NULL);
+}
+
+bool hash_map_set(hash_map_t *hash_map, const void *key, void *data) {
+  assert(hash_map != NULL);
+  assert(data != NULL);
+
+  hash_index_t hash_key = hash_map->hash_fn(key) % hash_map->num_bucket;
+
+  if (hash_map->bucket[hash_key].list == NULL) {
+    hash_map->bucket[hash_key].list = list_new_internal(bucket_free_, hash_map->allocator);
+    if (hash_map->bucket[hash_key].list == NULL)
+        return false;
+  }
+  list_t *hash_bucket_list = hash_map->bucket[hash_key].list;
+
+  hash_map_entry_t *hash_map_entry = find_bucket_entry_(hash_bucket_list, key);
+
+  if (hash_map_entry) {
+    // Calls hash_map callback to delete the hash_map_entry.
+    bool rc = list_remove(hash_bucket_list, hash_map_entry);
+    assert(rc == true);
+  } else {
+    hash_map->hash_size++;
+  }
+  hash_map_entry = hash_map->allocator->alloc(sizeof(hash_map_entry_t));
+  if (hash_map_entry == NULL)
+    return false;
+
+  hash_map_entry->key = key;
+  hash_map_entry->data = data;
+  hash_map_entry->hash_map = hash_map;
+
+  return list_append(hash_bucket_list, hash_map_entry);
+}
+
+bool hash_map_erase(hash_map_t *hash_map, const void *key) {
+  assert(hash_map != NULL);
+
+  hash_index_t hash_key = hash_map->hash_fn(key) % hash_map->num_bucket;
+  list_t *hash_bucket_list = hash_map->bucket[hash_key].list;
+
+  hash_map_entry_t *hash_map_entry = find_bucket_entry_(hash_bucket_list, key);
+  if (hash_map_entry == NULL) {
+    return false;
+  }
+
+  hash_map->hash_size--;
+
+  return list_remove(hash_bucket_list, hash_map_entry);
+}
+
+void *hash_map_get(const hash_map_t *hash_map, const void *key) {
+  assert(hash_map != NULL);
+
+  hash_index_t hash_key = hash_map->hash_fn(key) % hash_map->num_bucket;
+  list_t *hash_bucket_list = hash_map->bucket[hash_key].list;
+
+  hash_map_entry_t *hash_map_entry = find_bucket_entry_(hash_bucket_list, key);
+  if (hash_map_entry != NULL)
+    return hash_map_entry->data;
+
+  return NULL;
+}
+
+void hash_map_clear(hash_map_t *hash_map) {
+  assert(hash_map != NULL);
+
+  for (hash_index_t i = 0; i < hash_map->num_bucket; i++){
+    if (hash_map->bucket[i].list == NULL)
+      continue;
+    list_free(hash_map->bucket[i].list);
+    hash_map->bucket[i].list = NULL;
+  }
+}
+
+void hash_map_foreach(hash_map_t *hash_map, hash_map_iter_cb callback, void *context) {
+  assert(hash_map != NULL);
+  assert(callback != NULL);
+
+  for (hash_index_t i = 0; i < hash_map->num_bucket; ++i){
+    if (hash_map->bucket[i].list == NULL)
+      continue;
+    for (const list_node_t *iter = list_begin(hash_map->bucket[i].list);
+        iter != list_end(hash_map->bucket[i].list);
+        iter = list_next(iter)) {
+       hash_map_entry_t *hash_map_entry = (hash_map_entry_t *)list_node(iter);
+       if (!callback(hash_map_entry, context))
+        return;
+    }
+  }
+}
+
+static void bucket_free_(void *data) {
+  assert(data != NULL);
+  hash_map_entry_t *hash_map_entry = (hash_map_entry_t *)data;
+  const hash_map_t *hash_map = hash_map_entry->hash_map;
+
+  if (hash_map->key_fn)
+    hash_map->key_fn((void *)hash_map_entry->key);
+  if (hash_map->data_fn)
+    hash_map->data_fn(hash_map_entry->data);
+  hash_map->allocator->free(hash_map_entry);
+}
+
+static hash_map_entry_t * find_bucket_entry_(list_t *hash_bucket_list,
+    const void *key) {
+
+  if (hash_bucket_list == NULL)
+    return NULL;
+
+  for (const list_node_t *iter = list_begin(hash_bucket_list);
+      iter != list_end(hash_bucket_list);
+      iter = list_next(iter)) {
+    hash_map_entry_t *hash_map_entry = (hash_map_entry_t *)list_node(iter);
+    if (hash_map_entry->hash_map->keys_are_equal(hash_map_entry->key, key)) {
+      return hash_map_entry;
+    }
+  }
+  return NULL;
+}
+
+static bool default_key_equality(const void *x, const void *y) {
+  return x == y;
+}
diff --git a/osi/src/list.c b/osi/src/list.c
index bfdbb1a..75f948e 100644
--- a/osi/src/list.c
+++ b/osi/src/list.c
@@ -1,7 +1,8 @@
 #include <assert.h>
 
-#include "list.h"
-#include "osi.h"
+#include "osi/include/allocator.h"
+#include "osi/include/list.h"
+#include "osi/include/osi.h"
 
 struct list_node_t {
   struct list_node_t *next;
@@ -13,48 +14,57 @@
   list_node_t *tail;
   size_t length;
   list_free_cb free_cb;
-};
+  const allocator_t *allocator;
+} list_t;
 
 static list_node_t *list_free_node_(list_t *list, list_node_t *node);
 
-// Returns a new, empty list. Returns NULL if not enough memory could be allocated
-// for the list structure. The returned list must be freed with |list_free|. The
-// |callback| specifies a function to be called whenever a list element is removed
-// from the list. It can be used to release resources held by the list element, e.g.
-// memory or file descriptor. |callback| may be NULL if no cleanup is necessary on
-// element removal.
-list_t *list_new(list_free_cb callback) {
-  list_t *list = (list_t *)calloc(sizeof(list_t), 1);
-  if (list)
-    list->free_cb = callback;
+// Hidden constructor, only to be used by the hash map for the allocation tracker.
+// Behaves the same as |list_new|, except you get to specify the allocator.
+list_t *list_new_internal(list_free_cb callback, const allocator_t *zeroed_allocator) {
+  list_t *list = (list_t *)zeroed_allocator->alloc(sizeof(list_t));
+  if (!list)
+    return NULL;
+
+  list->free_cb = callback;
+  list->allocator = zeroed_allocator;
   return list;
 }
 
-// Frees the list. This function accepts NULL as an argument, in which case it
-// behaves like a no-op.
-void list_free(list_t *list) {
-  if (list != NULL)
-    list_clear(list);
-
-  free(list);
+list_t *list_new(list_free_cb callback) {
+  return list_new_internal(callback, &allocator_calloc);
 }
 
-// Returns true if the list is empty (has no elements), false otherwise.
-// Note that a NULL list is not the same as an empty list. This function
-// does not accept a NULL list.
+void list_free(list_t *list) {
+  if (!list)
+    return;
+
+  list_clear(list);
+  list->allocator->free(list);
+}
+
 bool list_is_empty(const list_t *list) {
   assert(list != NULL);
   return (list->length == 0);
 }
 
-// Returns the length of the list. This function does not accept a NULL list.
+bool list_contains(const list_t *list, const void *data) {
+  assert(list != NULL);
+  assert(data != NULL);
+
+  for (const list_node_t *node = list_begin(list); node != list_end(list); node = list_next(node)) {
+    if (list_node(node) == data)
+      return true;
+  }
+
+  return false;
+}
+
 size_t list_length(const list_t *list) {
   assert(list != NULL);
   return list->length;
 }
 
-// Returns the first element in the list without removing it. |list| may not
-// be NULL or empty.
 void *list_front(const list_t *list) {
   assert(list != NULL);
   assert(!list_is_empty(list));
@@ -62,8 +72,6 @@
   return list->head->data;
 }
 
-// Returns the last element in the list without removing it. |list| may not
-// be NULL or empty.
 void *list_back(const list_t *list) {
   assert(list != NULL);
   assert(!list_is_empty(list));
@@ -73,10 +81,10 @@
 
 bool list_insert_after(list_t *list, list_node_t *prev_node, void *data) {
   assert(list != NULL);
-  assert(node != NULL);
+  assert(prev_node != NULL);
   assert(data != NULL);
 
-  list_node_t *node = (list_node_t *)malloc(sizeof(list_node_t));
+  list_node_t *node = (list_node_t *)list->allocator->alloc(sizeof(list_node_t));
   if (!node)
     return false;
 
@@ -89,15 +97,11 @@
   return true;
 }
 
-// Inserts |data| at the beginning of |list|. Neither |data| nor |list| may be NULL.
-// This function does not make a copy of |data| so the pointer must remain valid
-// at least until the element is removed from the list or the list is freed.
-// Returns true if |data| could be inserted, false otherwise (e.g. out of memory).
 bool list_prepend(list_t *list, void *data) {
   assert(list != NULL);
   assert(data != NULL);
 
-  list_node_t *node = (list_node_t *)malloc(sizeof(list_node_t));
+  list_node_t *node = (list_node_t *)list->allocator->alloc(sizeof(list_node_t));
   if (!node)
     return false;
   node->next = list->head;
@@ -109,15 +113,11 @@
   return true;
 }
 
-// Inserts |data| at the end of |list|. Neither |data| nor |list| may be NULL.
-// This function does not make a copy of |data| so the pointer must remain valid
-// at least until the element is removed from the list or the list is freed.
-// Returns true if |data| could be inserted, false otherwise (e.g. out of memory).
 bool list_append(list_t *list, void *data) {
   assert(list != NULL);
   assert(data != NULL);
 
-  list_node_t *node = (list_node_t *)malloc(sizeof(list_node_t));
+  list_node_t *node = (list_node_t *)list->allocator->alloc(sizeof(list_node_t));
   if (!node)
     return false;
   node->next = NULL;
@@ -133,11 +133,6 @@
   return true;
 }
 
-// Removes |data| from the list. Neither |list| nor |data| may be NULL. If |data|
-// is inserted multiple times in the list, this function will only remove the first
-// instance. If a free function was specified in |list_new|, it will be called back
-// with |data|. This function returns true if |data| was found in the list and removed,
-// false otherwise.
 bool list_remove(list_t *list, void *data) {
   assert(list != NULL);
   assert(data != NULL);
@@ -164,8 +159,6 @@
   return false;
 }
 
-// Removes all elements in the list. Calling this function will return the list to the
-// same state it was in after |list_new|. |list| may not be NULL.
 void list_clear(list_t *list) {
   assert(list != NULL);
   for (list_node_t *node = list->head; node; )
@@ -175,11 +168,6 @@
   list->length = 0;
 }
 
-// Iterates through the entire |list| and calls |callback| for each data element.
-// If the list is empty, |callback| will never be called. It is safe to mutate the
-// list inside the callback. If an element is added before the node being visited,
-// there will be no callback for the newly-inserted node. Neither |list| nor
-// |callback| may be NULL.
 void list_foreach(const list_t *list, list_iter_cb callback) {
   assert(list != NULL);
   assert(callback != NULL);
@@ -191,34 +179,21 @@
   }
 }
 
-// Returns an iterator to the first element in |list|. |list| may not be NULL.
-// The returned iterator is valid as long as it does not equal the value returned
-// by |list_end|.
 list_node_t *list_begin(const list_t *list) {
   assert(list != NULL);
   return list->head;
 }
 
-// Returns an iterator that points past the end of the list. In other words,
-// this function returns the value of an invalid iterator for the given list.
-// When an iterator has the same value as what's returned by this function, you
-// may no longer call |list_next| with the iterator. |list| may not be NULL.
 list_node_t *list_end(UNUSED_ATTR const list_t *list) {
   assert(list != NULL);
   return NULL;
 }
 
-// Given a valid iterator |node|, this function returns the next value for the
-// iterator. If the returned value equals the value returned by |list_end|, the
-// iterator has reached the end of the list and may no longer be used for any
-// purpose.
 list_node_t *list_next(const list_node_t *node) {
   assert(node != NULL);
   return node->next;
 }
 
-// Returns the value stored at the location pointed to by the iterator |node|.
-// |node| must not equal the value returned by |list_end|.
 void *list_node(const list_node_t *node) {
   assert(node != NULL);
   return node->data;
@@ -232,7 +207,7 @@
 
   if (list->free_cb)
     list->free_cb(node->data);
-  free(node);
+  list->allocator->free(node);
   --list->length;
 
   return next;
diff --git a/osi/src/non_repeating_timer.c b/osi/src/non_repeating_timer.c
new file mode 100644
index 0000000..e5e95d4
--- /dev/null
+++ b/osi/src/non_repeating_timer.c
@@ -0,0 +1,74 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <assert.h>
+
+#include "osi/include/allocator.h"
+#include "osi/include/osi.h"
+#include "osi/include/non_repeating_timer.h"
+
+struct non_repeating_timer_t {
+  alarm_t *alarm;
+  period_ms_t duration;
+  alarm_callback_t callback;
+  void *data;
+};
+
+non_repeating_timer_t *non_repeating_timer_new(period_ms_t duration, alarm_callback_t cb, void *data) {
+  assert(cb != NULL);
+
+  non_repeating_timer_t *ret = osi_calloc(sizeof(non_repeating_timer_t));
+
+  ret->alarm = alarm_new();
+  if (!ret->alarm)
+    goto error;
+
+  ret->duration = duration;
+  ret->callback = cb;
+  ret->data = data;
+
+  return ret;
+error:;
+  non_repeating_timer_free(ret);
+  return NULL;
+}
+
+void non_repeating_timer_free(non_repeating_timer_t *timer) {
+  if (!timer)
+    return;
+
+  alarm_free(timer->alarm);
+  osi_free(timer);
+}
+
+void non_repeating_timer_restart(non_repeating_timer_t *timer) {
+  non_repeating_timer_restart_if(timer, true);
+}
+
+void non_repeating_timer_restart_if(non_repeating_timer_t *timer, bool condition) {
+  assert(timer != NULL);
+  if (condition)
+    alarm_set(timer->alarm, timer->duration, timer->callback, timer->data);
+  else
+    non_repeating_timer_cancel(timer);
+}
+
+void non_repeating_timer_cancel(non_repeating_timer_t *timer) {
+  assert(timer != NULL);
+  alarm_cancel(timer->alarm);
+}
diff --git a/osi/src/reactor.c b/osi/src/reactor.c
index 0faff6d..968fe4b 100644
--- a/osi/src/reactor.c
+++ b/osi/src/reactor.c
@@ -20,47 +20,84 @@
 
 #include <assert.h>
 #include <errno.h>
+#include <pthread.h>
 #include <stdlib.h>
-#include <string.h>
+#include <sys/epoll.h>
 #include <sys/eventfd.h>
-#include <sys/select.h>
-#include <utils/Log.h>
 
-#include "list.h"
-#include "reactor.h"
+#include "osi/include/allocator.h"
+#include "osi/include/list.h"
+#include "osi/include/log.h"
+#include "osi/include/reactor.h"
 
 #if !defined(EFD_SEMAPHORE)
 #  define EFD_SEMAPHORE (1 << 0)
 #endif
 
 struct reactor_t {
+  int epoll_fd;
   int event_fd;
-  list_t *objects;
+  pthread_mutex_t list_lock;  // protects invalidation_list.
+  list_t *invalidation_list;  // reactor objects that have been unregistered.
+  pthread_t run_thread;       // the pthread on which reactor_run is executing.
+  bool is_running;            // indicates whether |run_thread| is valid.
+  bool object_removed;
 };
 
-static reactor_status_t run_reactor(reactor_t *reactor, int iterations, struct timeval *tv);
+struct reactor_object_t {
+  int fd;                              // the file descriptor to monitor for events.
+  void *context;                       // a context that's passed back to the *_ready functions.
+  reactor_t *reactor;                  // the reactor instance this object is registered with.
+  pthread_mutex_t lock;                // protects the lifetime of this object and all variables.
+
+  void (*read_ready)(void *context);   // function to call when the file descriptor becomes readable.
+  void (*write_ready)(void *context);  // function to call when the file descriptor becomes writeable.
+};
+
+static reactor_status_t run_reactor(reactor_t *reactor, int iterations);
+
+static const size_t MAX_EVENTS = 64;
+static const eventfd_t EVENT_REACTOR_STOP = 1;
 
 reactor_t *reactor_new(void) {
-  reactor_t *ret = (reactor_t *)calloc(1, sizeof(reactor_t));
+  reactor_t *ret = (reactor_t *)osi_calloc(sizeof(reactor_t));
   if (!ret)
     return NULL;
 
-  ret->event_fd = eventfd(0, EFD_SEMAPHORE);
-  if (ret->event_fd == -1) {
-    ALOGE("%s unable to create eventfd: %s", __func__, strerror(errno));
+  ret->epoll_fd = INVALID_FD;
+  ret->event_fd = INVALID_FD;
+
+  ret->epoll_fd = epoll_create(MAX_EVENTS);
+  if (ret->epoll_fd == INVALID_FD) {
+    LOG_ERROR("%s unable to create epoll instance: %s", __func__, strerror(errno));
     goto error;
   }
 
-  ret->objects = list_new(NULL);
-  if (!ret->objects)
+  ret->event_fd = eventfd(0, 0);
+  if (ret->event_fd == INVALID_FD) {
+    LOG_ERROR("%s unable to create eventfd: %s", __func__, strerror(errno));
     goto error;
+  }
+
+  pthread_mutex_init(&ret->list_lock, NULL);
+  ret->invalidation_list = list_new(NULL);
+  if (!ret->invalidation_list) {
+    LOG_ERROR("%s unable to allocate object invalidation list.", __func__);
+    goto error;
+  }
+
+  struct epoll_event event = { 0 };
+  event.events = EPOLLIN;
+  event.data.ptr = NULL;
+  if (epoll_ctl(ret->epoll_fd, EPOLL_CTL_ADD, ret->event_fd, &event) == -1) {
+    LOG_ERROR("%s unable to register eventfd with epoll set: %s", __func__, strerror(errno));
+    goto error;
+  }
 
   return ret;
 
 error:;
-  list_free(ret->objects);
-  close(ret->event_fd);
-  free(ret);
+  reactor_free(ret);
   return NULL;
 }
 
@@ -68,108 +105,186 @@
   if (!reactor)
     return;
 
-  list_free(reactor->objects);
+  list_free(reactor->invalidation_list);
   close(reactor->event_fd);
-  free(reactor);
+  close(reactor->epoll_fd);
+  osi_free(reactor);
 }
 
 reactor_status_t reactor_start(reactor_t *reactor) {
   assert(reactor != NULL);
-  return run_reactor(reactor, 0, NULL);
+  return run_reactor(reactor, 0);
 }
 
 reactor_status_t reactor_run_once(reactor_t *reactor) {
   assert(reactor != NULL);
-  return run_reactor(reactor, 1, NULL);
-}
-
-reactor_status_t reactor_run_once_timeout(reactor_t *reactor, timeout_t timeout_ms) {
-  assert(reactor != NULL);
-
-  struct timeval tv;
-  tv.tv_sec = timeout_ms / 1000;
-  tv.tv_usec = (timeout_ms % 1000) * 1000;
-  return run_reactor(reactor, 1, &tv);
+  return run_reactor(reactor, 1);
 }
 
 void reactor_stop(reactor_t *reactor) {
   assert(reactor != NULL);
 
-  eventfd_write(reactor->event_fd, 1);
+  eventfd_write(reactor->event_fd, EVENT_REACTOR_STOP);
 }
 
-void reactor_register(reactor_t *reactor, reactor_object_t *obj) {
+reactor_object_t *reactor_register(reactor_t *reactor,
+    int fd, void *context,
+    void (*read_ready)(void *context),
+    void (*write_ready)(void *context)) {
   assert(reactor != NULL);
+  assert(fd != INVALID_FD);
+
+  reactor_object_t *object = (reactor_object_t *)osi_calloc(sizeof(reactor_object_t));
+  if (!object) {
+    LOG_ERROR("%s unable to allocate reactor object: %s", __func__, strerror(errno));
+    return NULL;
+  }
+
+  object->reactor = reactor;
+  object->fd = fd;
+  object->context = context;
+  object->read_ready = read_ready;
+  object->write_ready = write_ready;
+  pthread_mutex_init(&object->lock, NULL);
+
+  struct epoll_event event = { 0 };
+  event.events = 0;
+  if (read_ready)
+    event.events |= (EPOLLIN | EPOLLRDHUP);
+  if (write_ready)
+    event.events |= EPOLLOUT;
+  event.data.ptr = object;
+
+  if (epoll_ctl(reactor->epoll_fd, EPOLL_CTL_ADD, fd, &event) == -1) {
+    LOG_ERROR("%s unable to register fd %d to epoll set: %s", __func__, fd, strerror(errno));
+    pthread_mutex_destroy(&object->lock);
+    osi_free(object);
+    return NULL;
+  }
+
+  return object;
+}
+
+bool reactor_change_registration(reactor_object_t *object,
+    void (*read_ready)(void *context),
+    void (*write_ready)(void *context)) {
+  assert(object != NULL);
+
+  struct epoll_event event = { 0 };
+  event.events = 0;
+  if (read_ready)
+    event.events |= (EPOLLIN | EPOLLRDHUP);
+  if (write_ready)
+    event.events |= EPOLLOUT;
+  event.data.ptr = object;
+
+  if (epoll_ctl(object->reactor->epoll_fd, EPOLL_CTL_MOD, object->fd, &event) == -1) {
+    LOG_ERROR("%s unable to modify interest set for fd %d: %s", __func__, object->fd, strerror(errno));
+    return false;
+  }
+
+  pthread_mutex_lock(&object->lock);
+  object->read_ready = read_ready;
+  object->write_ready = write_ready;
+  pthread_mutex_unlock(&object->lock);
+
+  return true;
+}
+
+void reactor_unregister(reactor_object_t *obj) {
   assert(obj != NULL);
 
-  list_append(reactor->objects, obj);
+  reactor_t *reactor = obj->reactor;
+
+  if (epoll_ctl(reactor->epoll_fd, EPOLL_CTL_DEL, obj->fd, NULL) == -1)
+    LOG_ERROR("%s unable to unregister fd %d from epoll set: %s", __func__, obj->fd, strerror(errno));
+
+  if (reactor->is_running && pthread_equal(pthread_self(), reactor->run_thread)) {
+    reactor->object_removed = true;
+    return;
+  }
+
+  pthread_mutex_lock(&reactor->list_lock);
+  list_append(reactor->invalidation_list, obj);
+  pthread_mutex_unlock(&reactor->list_lock);
+
+  // Taking the object lock here makes sure a callback for |obj| isn't
+  // currently executing. The reactor thread must then either be before
+  // the callbacks or after. If after, we know that the object won't be
+  // referenced because it has been taken out of the epoll set. If before,
+  // it won't be referenced because the reactor thread will check the
+  // invalidation_list and find it in there. So by taking this lock, we
+  // are waiting until the reactor thread drops all references to |obj|.
+  // One the wait completes, we can unlock and destroy |obj| safely.
+  pthread_mutex_lock(&obj->lock);
+  pthread_mutex_unlock(&obj->lock);
+  pthread_mutex_destroy(&obj->lock);
+  osi_free(obj);
 }
 
-void reactor_unregister(reactor_t *reactor, reactor_object_t *obj) {
-  assert(reactor != NULL);
-  assert(obj != NULL);
-
-  list_remove(reactor->objects, obj);
-}
-
-// Runs the reactor loop for a maximum of |iterations| with the given timeout, |tv|.
+// Runs the reactor loop for a maximum of |iterations|.
 // 0 |iterations| means loop forever.
-// NULL |tv| means no timeout (block until an event occurs).
 // |reactor| may not be NULL.
-static reactor_status_t run_reactor(reactor_t *reactor, int iterations, struct timeval *tv) {
+static reactor_status_t run_reactor(reactor_t *reactor, int iterations) {
   assert(reactor != NULL);
 
-  for (int i = 0; iterations == 0 || i < iterations; ++i) {
-    fd_set read_set;
-    fd_set write_set;
-    FD_ZERO(&read_set);
-    FD_ZERO(&write_set);
-    FD_SET(reactor->event_fd, &read_set);
+  reactor->run_thread = pthread_self();
+  reactor->is_running = true;
 
-    int max_fd = reactor->event_fd;
-    for (const list_node_t *iter = list_begin(reactor->objects); iter != list_end(reactor->objects); iter = list_next(iter)) {
-      reactor_object_t *object = (reactor_object_t *)list_node(iter);
-      int fd = object->fd;
-      reactor_interest_t interest = object->interest;
-      if (interest & REACTOR_INTEREST_READ)
-        FD_SET(fd, &read_set);
-      if (interest & REACTOR_INTEREST_WRITE)
-        FD_SET(fd, &write_set);
-      if (fd > max_fd)
-        max_fd = fd;
-    }
+  struct epoll_event events[MAX_EVENTS];
+  for (int i = 0; iterations == 0 || i < iterations; ++i) {
+    pthread_mutex_lock(&reactor->list_lock);
+    list_clear(reactor->invalidation_list);
+    pthread_mutex_unlock(&reactor->list_lock);
 
     int ret;
     do {
-      ret = select(max_fd + 1, &read_set, &write_set, NULL, tv);
+      ret = epoll_wait(reactor->epoll_fd, events, MAX_EVENTS, -1);
     } while (ret == -1 && errno == EINTR);
 
     if (ret == -1) {
-      ALOGE("%s error in select: %s", __func__, strerror(errno));
+      LOG_ERROR("%s error in epoll_wait: %s", __func__, strerror(errno));
+      reactor->is_running = false;
       return REACTOR_STATUS_ERROR;
     }
 
-    if (ret == 0)
-      return REACTOR_STATUS_TIMEOUT;
-
-    if (FD_ISSET(reactor->event_fd, &read_set)) {
-      eventfd_t value;
-      eventfd_read(reactor->event_fd, &value);
-      return REACTOR_STATUS_STOP;
-    }
-
-    for (const list_node_t *iter = list_begin(reactor->objects); ret > 0 && iter != list_end(reactor->objects); iter = list_next(iter)) {
-      reactor_object_t *object = (reactor_object_t *)list_node(iter);
-      int fd = object->fd;
-      if (FD_ISSET(fd, &read_set)) {
-        object->read_ready(object->context);
-        --ret;
+    for (int j = 0; j < ret; ++j) {
+      // The event file descriptor is the only one that registers with
+      // a NULL data pointer. We use the NULL to identify it and break
+      // out of the reactor loop.
+      if (events[j].data.ptr == NULL) {
+        eventfd_t value;
+        eventfd_read(reactor->event_fd, &value);
+        reactor->is_running = false;
+        return REACTOR_STATUS_STOP;
       }
-      if (FD_ISSET(fd, &write_set)) {
+
+      reactor_object_t *object = (reactor_object_t *)events[j].data.ptr;
+
+      pthread_mutex_lock(&reactor->list_lock);
+      if (list_contains(reactor->invalidation_list, object)) {
+        pthread_mutex_unlock(&reactor->list_lock);
+        continue;
+      }
+
+      // Downgrade the list lock to an object lock.
+      pthread_mutex_lock(&object->lock);
+      pthread_mutex_unlock(&reactor->list_lock);
+
+      reactor->object_removed = false;
+      if (events[j].events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && object->read_ready)
+        object->read_ready(object->context);
+      if (!reactor->object_removed && events[j].events & EPOLLOUT && object->write_ready)
         object->write_ready(object->context);
-        --ret;
+      pthread_mutex_unlock(&object->lock);
+
+      if (reactor->object_removed) {
+        pthread_mutex_destroy(&object->lock);
+        osi_free(object);
       }
     }
   }
+
+  reactor->is_running = false;
   return REACTOR_STATUS_DONE;
 }
diff --git a/osi/src/semaphore.c b/osi/src/semaphore.c
index a56ecaf..5ee9926 100644
--- a/osi/src/semaphore.c
+++ b/osi/src/semaphore.c
@@ -16,7 +16,7 @@
  *
  ******************************************************************************/
 
-#define LOG_TAG "osi_semaphore"
+#define LOG_TAG "bt_osi_semaphore"
 
 #include <assert.h>
 #include <errno.h>
@@ -24,9 +24,11 @@
 #include <malloc.h>
 #include <string.h>
 #include <sys/eventfd.h>
-#include <utils/Log.h>
 
-#include "semaphore.h"
+#include "osi/include/allocator.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/semaphore.h"
 
 #if !defined(EFD_SEMAPHORE)
 #  define EFD_SEMAPHORE (1 << 0)
@@ -37,12 +39,12 @@
 };
 
 semaphore_t *semaphore_new(unsigned int value) {
-  semaphore_t *ret = malloc(sizeof(semaphore_t));
+  semaphore_t *ret = osi_malloc(sizeof(semaphore_t));
   if (ret) {
     ret->fd = eventfd(value, EFD_SEMAPHORE);
-    if (ret->fd == -1) {
-      ALOGE("%s unable to allocate semaphore: %s", __func__, strerror(errno));
-      free(ret);
+    if (ret->fd == INVALID_FD) {
+      LOG_ERROR("%s unable to allocate semaphore: %s", __func__, strerror(errno));
+      osi_free(ret);
       ret = NULL;
     }
   }
@@ -50,31 +52,34 @@
 }
 
 void semaphore_free(semaphore_t *semaphore) {
-  if (semaphore->fd != -1)
+  if (!semaphore)
+    return;
+
+  if (semaphore->fd != INVALID_FD)
     close(semaphore->fd);
-  free(semaphore);
+  osi_free(semaphore);
 }
 
 void semaphore_wait(semaphore_t *semaphore) {
   assert(semaphore != NULL);
-  assert(semaphore->fd != -1);
+  assert(semaphore->fd != INVALID_FD);
 
   uint64_t value;
   if (eventfd_read(semaphore->fd, &value) == -1)
-    ALOGE("%s unable to wait on semaphore: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to wait on semaphore: %s", __func__, strerror(errno));
 }
 
 bool semaphore_try_wait(semaphore_t *semaphore) {
   assert(semaphore != NULL);
-  assert(semaphore->fd != -1);
+  assert(semaphore->fd != INVALID_FD);
 
   int flags = fcntl(semaphore->fd, F_GETFL);
   if (flags == -1) {
-    ALOGE("%s unable to get flags for semaphore fd: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to get flags for semaphore fd: %s", __func__, strerror(errno));
     return false;
   }
   if (fcntl(semaphore->fd, F_SETFL, flags | O_NONBLOCK) == -1) {
-    ALOGE("%s unable to set O_NONBLOCK for semaphore fd: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to set O_NONBLOCK for semaphore fd: %s", __func__, strerror(errno));
     return false;
   }
 
@@ -83,20 +88,20 @@
     return false;
 
   if (fcntl(semaphore->fd, F_SETFL, flags) == -1)
-    ALOGE("%s unable to resetore flags for semaphore fd: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to resetore flags for semaphore fd: %s", __func__, strerror(errno));
   return true;
 }
 
 void semaphore_post(semaphore_t *semaphore) {
   assert(semaphore != NULL);
-  assert(semaphore->fd != -1);
+  assert(semaphore->fd != INVALID_FD);
 
   if (eventfd_write(semaphore->fd, 1ULL) == -1)
-    ALOGE("%s unable to post to semaphore: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to post to semaphore: %s", __func__, strerror(errno));
 }
 
 int semaphore_get_fd(const semaphore_t *semaphore) {
   assert(semaphore != NULL);
-  assert(semaphore->fd != -1);
+  assert(semaphore->fd != INVALID_FD);
   return semaphore->fd;
 }
diff --git a/osi/src/socket.c b/osi/src/socket.c
new file mode 100644
index 0000000..8841d56
--- /dev/null
+++ b/osi/src/socket.c
@@ -0,0 +1,229 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_osi_socket"
+
+#include <asm/ioctls.h>
+#include <assert.h>
+#include <errno.h>
+#include <netinet/in.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "osi/include/allocator.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "osi/include/reactor.h"
+#include "osi/include/socket.h"
+
+struct socket_t {
+  int fd;
+  reactor_object_t *reactor_object;
+  socket_cb read_ready;
+  socket_cb write_ready;
+  void *context;                     // Not owned, do not free.
+};
+
+static void internal_read_ready(void *context);
+static void internal_write_ready(void *context);
+
+socket_t *socket_new(void) {
+  socket_t *ret = (socket_t *)osi_calloc(sizeof(socket_t));
+  if (!ret) {
+    LOG_ERROR("%s unable to allocate memory for socket.", __func__);
+    goto error;
+  }
+
+  ret->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (ret->fd == INVALID_FD) {
+    LOG_ERROR("%s unable to create socket: %s", __func__, strerror(errno));
+    goto error;
+  }
+
+  int enable = 1;
+  if (setsockopt(ret->fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) {
+    LOG_ERROR("%s unable to set SO_REUSEADDR: %s", __func__, strerror(errno));
+    goto error;
+  }
+
+  return ret;
+
+error:;
+  if (ret)
+    close(ret->fd);
+  osi_free(ret);
+  return NULL;
+}
+
+socket_t *socket_new_from_fd(int fd) {
+  assert(fd != INVALID_FD);
+
+  socket_t *ret = (socket_t *)osi_calloc(sizeof(socket_t));
+  if (!ret) {
+    LOG_ERROR("%s unable to allocate memory for socket.", __func__);
+    return NULL;
+  }
+
+  ret->fd = fd;
+  return ret;
+}
+
+void socket_free(socket_t *socket) {
+  if (!socket)
+    return;
+
+  socket_unregister(socket);
+  close(socket->fd);
+  osi_free(socket);
+}
+
+bool socket_listen(const socket_t *socket, port_t port) {
+  assert(socket != NULL);
+
+  struct sockaddr_in addr;
+  addr.sin_family = AF_INET;
+  addr.sin_addr.s_addr = 0;
+  addr.sin_port = htons(port);
+  if (bind(socket->fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
+    LOG_ERROR("%s unable to bind socket to port %u: %s", __func__, port, strerror(errno));
+    return false;
+  }
+
+  if (listen(socket->fd, 10) == -1) {
+    LOG_ERROR("%s unable to listen on port %u: %s", __func__, port, strerror(errno));
+    return false;
+  }
+
+  return true;
+}
+
+socket_t *socket_accept(const socket_t *socket) {
+  assert(socket != NULL);
+
+  int fd = accept(socket->fd, NULL, NULL);
+  if (fd == INVALID_FD) {
+    LOG_ERROR("%s unable to accept socket: %s", __func__, strerror(errno));
+    return NULL;
+  }
+
+  socket_t *ret = (socket_t *)osi_calloc(sizeof(socket_t));
+  if (!ret) {
+    close(fd);
+    LOG_ERROR("%s unable to allocate memory for socket.", __func__);
+    return NULL;
+  }
+
+  ret->fd = fd;
+  return ret;
+}
+
+ssize_t socket_read(const socket_t *socket, void *buf, size_t count) {
+  assert(socket != NULL);
+  assert(buf != NULL);
+
+  return recv(socket->fd, buf, count, MSG_DONTWAIT);
+}
+
+ssize_t socket_write(const socket_t *socket, const void *buf, size_t count) {
+  assert(socket != NULL);
+  assert(buf != NULL);
+
+  return send(socket->fd, buf, count, MSG_DONTWAIT);
+}
+
+ssize_t socket_write_and_transfer_fd(const socket_t *socket, const void *buf, size_t count, int fd) {
+  assert(socket != NULL);
+  assert(buf != NULL);
+
+  if (fd == INVALID_FD)
+    return socket_write(socket, buf, count);
+
+  struct msghdr msg;
+  struct iovec iov;
+  char control_buf[CMSG_SPACE(sizeof(int))];
+
+  iov.iov_base = (void *)buf;
+  iov.iov_len = count;
+
+  msg.msg_iov = &iov;
+  msg.msg_iovlen = 1;
+  msg.msg_control = control_buf;
+  msg.msg_controllen = sizeof(control_buf);
+  msg.msg_name = NULL;
+  msg.msg_namelen = 0;
+
+  struct cmsghdr *header = CMSG_FIRSTHDR(&msg);
+  header->cmsg_level = SOL_SOCKET;
+  header->cmsg_type = SCM_RIGHTS;
+  header->cmsg_len = CMSG_LEN(sizeof(int));
+  *(int *)CMSG_DATA(header) = fd;
+
+  ssize_t ret = sendmsg(socket->fd, &msg, MSG_DONTWAIT);
+  close(fd);
+  return ret;
+}
+
+ssize_t socket_bytes_available(const socket_t *socket) {
+  assert(socket != NULL);
+
+  int size = 0;
+  if (ioctl(socket->fd, FIONREAD, &size) == -1)
+    return -1;
+  return size;
+}
+
+void socket_register(socket_t *socket, reactor_t *reactor, void *context, socket_cb read_cb, socket_cb write_cb) {
+  assert(socket != NULL);
+
+  // Make sure the socket isn't currently registered.
+  socket_unregister(socket);
+
+  socket->read_ready = read_cb;
+  socket->write_ready = write_cb;
+  socket->context = context;
+
+  void (*read_fn)(void *) = (read_cb != NULL) ? internal_read_ready : NULL;
+  void (*write_fn)(void *) = (write_cb != NULL) ? internal_write_ready : NULL;
+
+  socket->reactor_object = reactor_register(reactor, socket->fd, socket, read_fn, write_fn);
+}
+
+void socket_unregister(socket_t *socket) {
+  assert(socket != NULL);
+
+  if (socket->reactor_object)
+    reactor_unregister(socket->reactor_object);
+  socket->reactor_object = NULL;
+}
+
+static void internal_read_ready(void *context) {
+  assert(context != NULL);
+
+  socket_t *socket = (void *)context;
+  socket->read_ready(socket, socket->context);
+}
+
+static void internal_write_ready(void *context) {
+  assert(context != NULL);
+
+  socket_t *socket = (void *)context;
+  socket->write_ready(socket, socket->context);
+}
diff --git a/osi/src/thread.c b/osi/src/thread.c
index 3090528..98e93e8 100644
--- a/osi/src/thread.c
+++ b/osi/src/thread.c
@@ -16,7 +16,7 @@
  *
  ******************************************************************************/
 
-#define LOG_TAG "osi_thread"
+#define LOG_TAG "bt_osi_thread"
 
 #include <assert.h>
 #include <errno.h>
@@ -25,14 +25,16 @@
 #include <string.h>
 #include <sys/prctl.h>
 #include <sys/types.h>
-#include <utils/Log.h>
 
-#include "fixed_queue.h"
-#include "reactor.h"
-#include "semaphore.h"
-#include "thread.h"
+#include "osi/include/allocator.h"
+#include "osi/include/fixed_queue.h"
+#include "osi/include/log.h"
+#include "osi/include/reactor.h"
+#include "osi/include/semaphore.h"
+#include "osi/include/thread.h"
 
 struct thread_t {
+  bool is_joined;
   pthread_t pthread;
   pid_t tid;
   char name[THREAD_NAME_MAX + 1];
@@ -54,13 +56,13 @@
 static void *run_thread(void *start_arg);
 static void work_queue_read_cb(void *context);
 
-static const size_t WORK_QUEUE_CAPACITY = 128;
+static const size_t DEFAULT_WORK_QUEUE_CAPACITY = 128;
 
-thread_t *thread_new(const char *name) {
+thread_t *thread_new_sized(const char *name, size_t work_queue_capacity) {
   assert(name != NULL);
+  assert(work_queue_capacity != 0);
 
-  // Start is on the stack, but we use a semaphore, so it's safe
-  thread_t *ret = calloc(1, sizeof(thread_t));
+  thread_t *ret = osi_calloc(sizeof(thread_t));
   if (!ret)
     goto error;
 
@@ -68,10 +70,11 @@
   if (!ret->reactor)
     goto error;
 
-  ret->work_queue = fixed_queue_new(WORK_QUEUE_CAPACITY);
+  ret->work_queue = fixed_queue_new(work_queue_capacity);
   if (!ret->work_queue)
     goto error;
 
+  // Start is on the stack, but we use a semaphore, so it's safe
   struct start_arg start;
   start.start_sem = semaphore_new(0);
   if (!start.start_sem)
@@ -83,28 +86,45 @@
   pthread_create(&ret->pthread, NULL, run_thread, &start);
   semaphore_wait(start.start_sem);
   semaphore_free(start.start_sem);
+
   if (start.error)
     goto error;
+
   return ret;
 
 error:;
   if (ret) {
-    fixed_queue_free(ret->work_queue, free);
+    fixed_queue_free(ret->work_queue, osi_free);
     reactor_free(ret->reactor);
   }
-  free(ret);
+  osi_free(ret);
   return NULL;
 }
 
+thread_t *thread_new(const char *name) {
+  return thread_new_sized(name, DEFAULT_WORK_QUEUE_CAPACITY);
+}
+
 void thread_free(thread_t *thread) {
   if (!thread)
     return;
 
   thread_stop(thread);
-  pthread_join(thread->pthread, NULL);
-  fixed_queue_free(thread->work_queue, free);
+  thread_join(thread);
+
+  fixed_queue_free(thread->work_queue, osi_free);
   reactor_free(thread->reactor);
-  free(thread);
+  osi_free(thread);
+}
+
+void thread_join(thread_t *thread) {
+  assert(thread != NULL);
+
+  // TODO(zachoverflow): use a compare and swap when ready
+  if (!thread->is_joined) {
+    thread->is_joined = true;
+    pthread_join(thread->pthread, NULL);
+  }
 }
 
 bool thread_post(thread_t *thread, thread_fn func, void *context) {
@@ -117,9 +137,9 @@
 
   // Queue item is freed either when the queue itself is destroyed
   // or when the item is removed from the queue for dispatch.
-  work_item_t *item = (work_item_t *)malloc(sizeof(work_item_t));
+  work_item_t *item = (work_item_t *)osi_malloc(sizeof(work_item_t));
   if (!item) {
-    ALOGE("%s unable to allocate memory: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to allocate memory: %s", __func__, strerror(errno));
     return false;
   }
   item->func = func;
@@ -133,6 +153,16 @@
   reactor_stop(thread->reactor);
 }
 
+bool thread_is_self(const thread_t *thread) {
+  assert(thread != NULL);
+  return !!pthread_equal(pthread_self(), thread->pthread);
+}
+
+reactor_t *thread_get_reactor(const thread_t *thread) {
+  assert(thread != NULL);
+  return thread->reactor;
+}
+
 const char *thread_name(const thread_t *thread) {
   assert(thread != NULL);
   return thread->name;
@@ -147,7 +177,7 @@
   assert(thread != NULL);
 
   if (prctl(PR_SET_NAME, (unsigned long)thread->name) == -1) {
-    ALOGE("%s unable to set thread name: %s", __func__, strerror(errno));
+    LOG_ERROR("%s unable to set thread name: %s", __func__, strerror(errno));
     start->error = errno;
     semaphore_post(start->start_sem);
     return NULL;
@@ -156,29 +186,27 @@
 
   semaphore_post(start->start_sem);
 
-  reactor_object_t work_queue_object;
-  work_queue_object.context = thread->work_queue;
-  work_queue_object.fd = fixed_queue_get_dequeue_fd(thread->work_queue);
-  work_queue_object.interest = REACTOR_INTEREST_READ;
-  work_queue_object.read_ready = work_queue_read_cb;
+  int fd = fixed_queue_get_dequeue_fd(thread->work_queue);
+  void *context = thread->work_queue;
 
-  reactor_register(thread->reactor, &work_queue_object);
+  reactor_object_t *work_queue_object = reactor_register(thread->reactor, fd, context, work_queue_read_cb, NULL);
   reactor_start(thread->reactor);
+  reactor_unregister(work_queue_object);
 
   // Make sure we dispatch all queued work items before exiting the thread.
   // This allows a caller to safely tear down by enqueuing a teardown
   // work item and then joining the thread.
   size_t count = 0;
   work_item_t *item = fixed_queue_try_dequeue(thread->work_queue);
-  while (item && count <= WORK_QUEUE_CAPACITY) {
+  while (item && count <= fixed_queue_capacity(thread->work_queue)) {
     item->func(item->context);
-    free(item);
+    osi_free(item);
     item = fixed_queue_try_dequeue(thread->work_queue);
     ++count;
   }
 
-  if (count > WORK_QUEUE_CAPACITY)
-    ALOGD("%s growing event queue on shutdown.", __func__);
+  if (count > fixed_queue_capacity(thread->work_queue))
+    LOG_DEBUG("%s growing event queue on shutdown.", __func__);
 
   return NULL;
 }
@@ -189,5 +217,5 @@
   fixed_queue_t *queue = (fixed_queue_t *)context;
   work_item_t *item = fixed_queue_dequeue(queue);
   item->func(item->context);
-  free(item);
+  osi_free(item);
 }
diff --git a/osi/test/AlarmTestHarness.cpp b/osi/test/AlarmTestHarness.cpp
new file mode 100644
index 0000000..a5f8d9c
--- /dev/null
+++ b/osi/test/AlarmTestHarness.cpp
@@ -0,0 +1,96 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+#include <hardware/bluetooth.h>
+#include <unistd.h>
+
+#include "AlarmTestHarness.h"
+
+extern "C" {
+#include "alarm.h"
+#include "allocation_tracker.h"
+}
+
+static timer_t timer;
+static alarm_cb saved_callback;
+static void *saved_data;
+static AlarmTestHarness *current_harness;
+
+static void timer_callback(void *) {
+  saved_callback(saved_data);
+}
+
+void AlarmTestHarness::SetUp() {
+  AllocationTestHarness::SetUp();
+
+  // Make sure the alarm list is initialized, and the base list
+  // allocation isn't taken into account.
+  alarm_free(alarm_new());
+  allocation_tracker_reset();
+
+  current_harness = this;
+  TIMER_INTERVAL_FOR_WAKELOCK_IN_MS = 100;
+  lock_count = 0;
+
+  struct sigevent sigevent;
+  memset(&sigevent, 0, sizeof(sigevent));
+  sigevent.sigev_notify = SIGEV_THREAD;
+  sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
+  sigevent.sigev_value.sival_ptr = NULL;
+  timer_create(CLOCK_BOOTTIME, &sigevent, &timer);
+}
+
+void AlarmTestHarness::TearDown() {
+  timer_delete(timer);
+  AllocationTestHarness::TearDown();
+}
+
+static bool set_wake_alarm(uint64_t delay_millis, bool, alarm_cb cb, void *data) {
+  saved_callback = cb;
+  saved_data = data;
+
+  struct itimerspec wakeup_time;
+  memset(&wakeup_time, 0, sizeof(wakeup_time));
+  wakeup_time.it_value.tv_sec = (delay_millis / 1000);
+  wakeup_time.it_value.tv_nsec = (delay_millis % 1000) * 1000000LL;
+  timer_settime(timer, 0, &wakeup_time, NULL);
+  return true;
+}
+
+static int acquire_wake_lock(const char *) {
+  if (!current_harness->lock_count)
+    current_harness->lock_count = 1;
+  return BT_STATUS_SUCCESS;
+}
+
+static int release_wake_lock(const char *) {
+  if (current_harness->lock_count)
+    current_harness->lock_count = 0;
+  return BT_STATUS_SUCCESS;
+}
+
+static bt_os_callouts_t stub = {
+  sizeof(bt_os_callouts_t),
+  set_wake_alarm,
+  acquire_wake_lock,
+  release_wake_lock,
+};
+
+bt_os_callouts_t *bt_os_callouts = &stub;
+
diff --git a/test/suite/support/property.h b/osi/test/AlarmTestHarness.h
similarity index 62%
copy from test/suite/support/property.h
copy to osi/test/AlarmTestHarness.h
index a8b77c7..d4146bb 100644
--- a/test/suite/support/property.h
+++ b/osi/test/AlarmTestHarness.h
@@ -18,15 +18,15 @@
 
 #pragma once
 
-#include "base.h"
+#include "AllocationTestHarness.h"
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+extern int64_t TIMER_INTERVAL_FOR_WAKELOCK_IN_MS;
 
-const char *property_extract_name(const bt_property_t *property);
+class AlarmTestHarness : public AllocationTestHarness {
+  protected:
+    virtual void SetUp();
+    virtual void TearDown();
 
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+  public:
+    int lock_count;
+};
diff --git a/test/suite/support/property.h b/osi/test/AllocationTestHarness.cpp
similarity index 60%
copy from test/suite/support/property.h
copy to osi/test/AllocationTestHarness.cpp
index a8b77c7..0132c73 100644
--- a/test/suite/support/property.h
+++ b/osi/test/AllocationTestHarness.cpp
@@ -16,17 +16,19 @@
  *
  ******************************************************************************/
 
-#pragma once
+#include <gtest/gtest.h>
 
-#include "base.h"
+#include "osi/test/AllocationTestHarness.h"
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+extern "C" {
+#include "osi/include/allocation_tracker.h"
+}
 
-const char *property_extract_name(const bt_property_t *property);
+void AllocationTestHarness::SetUp() {
+  allocation_tracker_init();
+  allocation_tracker_reset();
+}
 
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+void AllocationTestHarness::TearDown() {
+  EXPECT_EQ(0U, allocation_tracker_expect_no_allocations()) << "not all memory freed";
+}
diff --git a/test/suite/support/property.h b/osi/test/AllocationTestHarness.h
similarity index 61%
copy from test/suite/support/property.h
copy to osi/test/AllocationTestHarness.h
index a8b77c7..b906936 100644
--- a/test/suite/support/property.h
+++ b/osi/test/AllocationTestHarness.h
@@ -18,15 +18,8 @@
 
 #pragma once
 
-#include "base.h"
-
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
-
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+class AllocationTestHarness : public ::testing::Test {
+  protected:
+    virtual void SetUp();
+    virtual void TearDown();
+};
diff --git a/osi/test/alarm_test.cpp b/osi/test/alarm_test.cpp
index d08cf6d..287d408 100644
--- a/osi/test/alarm_test.cpp
+++ b/osi/test/alarm_test.cpp
@@ -1,6 +1,24 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
 #include <gtest/gtest.h>
-#include <hardware/bluetooth.h>
-#include <unistd.h>
+
+#include "AlarmTestHarness.h"
 
 extern "C" {
 #include "alarm.h"
@@ -8,14 +26,8 @@
 #include "semaphore.h"
 }
 
-extern int64_t TIMER_INTERVAL_FOR_WAKELOCK_IN_MS;
-
 static semaphore_t *semaphore;
 static int cb_counter;
-static int lock_count;
-static timer_t timer;
-static alarm_cb saved_callback;
-static void *saved_data;
 
 static const uint64_t EPSILON_MS = 5;
 
@@ -23,29 +35,18 @@
   usleep(ms * 1000);
 }
 
-static void timer_callback(void *) {
-  saved_callback(saved_data);
-}
-
-class AlarmTest : public ::testing::Test {
+class AlarmTest : public AlarmTestHarness {
   protected:
     virtual void SetUp() {
-      TIMER_INTERVAL_FOR_WAKELOCK_IN_MS = 100;
+      AlarmTestHarness::SetUp();
       cb_counter = 0;
-      lock_count = 0;
 
       semaphore = semaphore_new(0);
-
-      struct sigevent sigevent;
-      memset(&sigevent, 0, sizeof(sigevent));
-      sigevent.sigev_notify = SIGEV_THREAD;
-      sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
-      sigevent.sigev_value.sival_ptr = NULL;
-      timer_create(CLOCK_BOOTTIME, &sigevent, &timer);
     }
 
     virtual void TearDown() {
-      timer_delete(timer);
+      semaphore_free(semaphore);
+      AlarmTestHarness::TearDown();
     }
 };
 
@@ -54,46 +55,9 @@
   semaphore_post(semaphore);
 }
 
-static bool set_wake_alarm(uint64_t delay_millis, bool, alarm_cb cb, void *data) {
-  saved_callback = cb;
-  saved_data = data;
-
-  struct itimerspec wakeup_time;
-  memset(&wakeup_time, 0, sizeof(wakeup_time));
-  wakeup_time.it_value.tv_sec = (delay_millis / 1000);
-  wakeup_time.it_value.tv_nsec = (delay_millis % 1000) * 1000000LL;
-  timer_settime(timer, 0, &wakeup_time, NULL);
-  return true;
-}
-
-static int acquire_wake_lock(const char *) {
-  if (!lock_count)
-    lock_count = 1;
-  return BT_STATUS_SUCCESS;
-}
-
-static int release_wake_lock(const char *) {
-  if (lock_count)
-    lock_count = 0;
-  return BT_STATUS_SUCCESS;
-}
-
-static bt_os_callouts_t stub = {
-  sizeof(bt_os_callouts_t),
-  set_wake_alarm,
-  acquire_wake_lock,
-  release_wake_lock,
-};
-
-bt_os_callouts_t *bt_os_callouts = &stub;
-
-TEST_F(AlarmTest, test_new_simple) {
+TEST_F(AlarmTest, test_new_free_simple) {
   alarm_t *alarm = alarm_new();
   ASSERT_TRUE(alarm != NULL);
-}
-
-TEST_F(AlarmTest, test_free_simple) {
-  alarm_t *alarm = alarm_new();
   alarm_free(alarm);
 }
 
diff --git a/osi/test/allocation_tracker_test.cpp b/osi/test/allocation_tracker_test.cpp
new file mode 100644
index 0000000..052d468
--- /dev/null
+++ b/osi/test/allocation_tracker_test.cpp
@@ -0,0 +1,60 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+extern "C" {
+#include "allocation_tracker.h"
+
+void allocation_tracker_uninit(void);
+}
+
+static const allocator_id_t allocator_id = 5;
+
+TEST(AllocationTrackerTest, test_uninit_no_bad_effects) {
+  void *dummy_allocation = malloc(4);
+
+  // Ensure uninitialized state (previous tests may have called init)
+  allocation_tracker_uninit();
+
+  EXPECT_EQ(4U, allocation_tracker_resize_for_canary(4));
+  allocation_tracker_notify_alloc(allocator_id, dummy_allocation, 4);
+  EXPECT_EQ(0U, allocation_tracker_expect_no_allocations()); // should not have registered an allocation
+  allocation_tracker_notify_free(allocator_id, dummy_allocation);
+  EXPECT_EQ(0U, allocation_tracker_expect_no_allocations());
+
+  free(dummy_allocation);
+}
+
+TEST(AllocationTrackerTest, test_canaries_on) {
+  allocation_tracker_uninit();
+  allocation_tracker_init();
+
+  size_t with_canary_size = allocation_tracker_resize_for_canary(4);
+  EXPECT_TRUE(with_canary_size > 4);
+
+  void *dummy_allocation = malloc(with_canary_size);
+  void *useable_ptr = allocation_tracker_notify_alloc(allocator_id, dummy_allocation, 4);
+  EXPECT_TRUE(useable_ptr > dummy_allocation);
+  EXPECT_EQ(4U, allocation_tracker_expect_no_allocations()); // should have registered the allocation
+  void *freeable_ptr = allocation_tracker_notify_free(allocator_id, useable_ptr);
+  EXPECT_EQ(dummy_allocation, freeable_ptr);
+  EXPECT_EQ(0U, allocation_tracker_expect_no_allocations());
+
+  free(dummy_allocation);
+}
diff --git a/osi/test/array_test.cpp b/osi/test/array_test.cpp
new file mode 100644
index 0000000..1a815d1
--- /dev/null
+++ b/osi/test/array_test.cpp
@@ -0,0 +1,77 @@
+#include <gtest/gtest.h>
+
+#include "AllocationTestHarness.h"
+
+extern "C" {
+#include "array.h"
+}
+
+class ArrayTest : public AllocationTestHarness {};
+
+TEST_F(ArrayTest, test_new_free_simple) {
+  array_t *array = array_new(4);
+  ASSERT_TRUE(array != NULL);
+  array_free(array);
+}
+
+TEST_F(ArrayTest, test_free_null) {
+  array_free(NULL);
+}
+
+TEST_F(ArrayTest, test_invalid_ptr) {
+  array_t *array = array_new(4);
+  EXPECT_DEATH(array_ptr(array), "");
+  array_free(array);
+}
+
+TEST_F(ArrayTest, test_invalid_at) {
+  array_t *array = array_new(4);
+  EXPECT_DEATH(array_at(array, 1), "");
+  array_free(array);
+}
+
+TEST_F(ArrayTest, test_append_value) {
+  array_t *array = array_new(sizeof(int));
+  for (int i = 0; i < 100; ++i) {
+    array_append_value(array, i * i);
+  }
+  for (int i = 0; i < 100; ++i) {
+    EXPECT_EQ(*(int *)array_at(array, i), i * i);
+  }
+  array_free(array);
+}
+
+TEST_F(ArrayTest, test_append_ptr) {
+  int items[100];
+  array_t *array = array_new(sizeof(int));
+  for (int i = 0; i < 100; ++i) {
+    items[i] = i * i;
+    array_append_ptr(array, &items[i]);
+  }
+  for (int i = 0; i < 100; ++i) {
+    EXPECT_EQ(*(int *)array_at(array, i), i * i);
+  }
+  array_free(array);
+}
+
+TEST_F(ArrayTest, test_large_element) {
+  char strings[][128] = {
+    "string 1",
+    "string 2",
+    "string 3",
+    "string 4",
+    "string 5",
+    "string 6",
+    "string 7",
+    "string 8",
+  };
+
+  array_t *array = array_new(128);
+  for (int i = 0; i < 100; ++i) {
+    array_append_ptr(array, strings[i % 8]);
+  }
+  for (int i = 0; i < 100; ++i) {
+    EXPECT_TRUE(!memcmp(array_at(array, i), strings[i % 8], 128));
+  }
+  array_free(array);
+}
diff --git a/osi/test/atomic_test.cpp b/osi/test/atomic_test.cpp
new file mode 100644
index 0000000..b0039ab
--- /dev/null
+++ b/osi/test/atomic_test.cpp
@@ -0,0 +1,278 @@
+#include <gtest/gtest.h>
+
+extern "C" {
+#include "atomic.h"
+}
+
+const static size_t ATOMIC_DATA_MAX = 2;
+const static int ATOMIC_MAX_THREADS = 20;
+
+struct atomic_test_s32_s {
+  pthread_t pthread_id;
+  int thread_num;
+  int max_val;
+  atomic_s32_t *data;
+};
+
+void *atomic_thread(void *context) {
+  struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context;
+  for (int i = 0; i < at->max_val; i++) {
+    usleep(1);
+    atomic_inc_prefix_s32(&at->data[i]);
+  }
+  return NULL;
+}
+
+void *atomic_thread_inc_dec(void *context) {
+  struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context;
+  for (int i = 0; i < at->max_val; i++) {
+    usleep(1);
+    atomic_inc_prefix_s32(&at->data[i]);
+    usleep(1);
+    atomic_dec_prefix_s32(&at->data[i]);
+  }
+  return NULL;
+}
+
+TEST(AtomicTest, test_store_load_s32) {
+  atomic_s32_t data;
+
+  atomic_store_s32(&data, -1);
+  EXPECT_EQ(-1, atomic_load_s32(&data));
+
+  atomic_store_s32(&data, 0);
+  EXPECT_EQ(0, atomic_load_s32(&data));
+
+  atomic_store_s32(&data, 1);
+  EXPECT_EQ(1, atomic_load_s32(&data));
+
+  atomic_store_s32(&data, 2);
+  EXPECT_EQ(2, atomic_load_s32(&data));
+}
+
+TEST(AtomicTest, test_store_load_u32) {
+  atomic_u32_t data;
+
+  atomic_store_u32(&data, -1);
+  EXPECT_EQ((uint32_t)-1, atomic_load_u32(&data));
+
+  atomic_store_u32(&data, 0);
+  EXPECT_EQ((uint32_t)0, atomic_load_u32(&data));
+
+  atomic_store_u32(&data, 1);
+  EXPECT_EQ((uint32_t)1, atomic_load_u32(&data));
+
+  atomic_store_u32(&data, 2);
+  EXPECT_EQ((uint32_t)2, atomic_load_u32(&data));
+}
+
+TEST(AtomicTest, test_inc_dec_s32) {
+  atomic_s32_t data;
+
+  atomic_store_s32(&data, 0);
+  EXPECT_EQ(0, atomic_load_s32(&data));
+
+  int32_t val = atomic_inc_prefix_s32(&data);
+  EXPECT_EQ(1, atomic_load_s32(&data));
+  EXPECT_EQ(1, val);
+
+  val = atomic_inc_prefix_s32(&data);
+  EXPECT_EQ(2, atomic_load_s32(&data));
+  EXPECT_EQ(2, val);
+
+  val = atomic_inc_prefix_s32(&data);
+  EXPECT_EQ(3, atomic_load_s32(&data));
+  EXPECT_EQ(3, val);
+
+  val = atomic_dec_prefix_s32(&data);
+  EXPECT_EQ(2, val);
+
+  val = atomic_dec_prefix_s32(&data);
+  EXPECT_EQ(1, val);
+  val = atomic_dec_prefix_s32(&data);
+  EXPECT_EQ(0, val);
+  val = atomic_dec_prefix_s32(&data);
+  EXPECT_EQ(-1, val);
+}
+
+TEST(AtomicTest, test_inc_dec_u32) {
+  atomic_u32_t data;
+
+  atomic_store_u32(&data, 0);
+  EXPECT_EQ((unsigned)0, atomic_load_u32(&data));
+
+  uint32_t val = atomic_inc_prefix_u32(&data);
+  EXPECT_EQ((unsigned)1, atomic_load_u32(&data));
+  EXPECT_EQ((unsigned)1, val);
+
+  val = atomic_inc_prefix_u32(&data);
+  EXPECT_EQ((unsigned)2, atomic_load_u32(&data));
+  EXPECT_EQ((unsigned)2, val);
+
+  val = atomic_inc_prefix_u32(&data);
+  EXPECT_EQ((unsigned)3, atomic_load_u32(&data));
+  EXPECT_EQ((unsigned)3, val);
+
+  val = atomic_dec_prefix_u32(&data);
+  EXPECT_EQ((unsigned)2, val);
+
+  val = atomic_dec_prefix_u32(&data);
+  EXPECT_EQ((unsigned)1, val);
+  val = atomic_dec_prefix_u32(&data);
+  EXPECT_EQ((unsigned)0, val);
+  val = atomic_dec_prefix_u32(&data);
+  EXPECT_EQ((unsigned)-1, val);
+}
+
+TEST(AtomicTest, test_atomic_inc_thread) {
+  struct atomic_test_s32_s atomic_test[ATOMIC_MAX_THREADS];
+  atomic_s32_t data[ATOMIC_DATA_MAX];
+
+  memset(&atomic_test, 0, sizeof(atomic_test));
+  memset(data, 0, sizeof(data));
+
+  for (unsigned int i = 0; i < ATOMIC_DATA_MAX; i++) {
+    EXPECT_EQ(0, data[i]._val);
+  }
+
+  for (int i = 0; i < ATOMIC_MAX_THREADS; i++) {
+    atomic_test[i].thread_num = i;
+    atomic_test[i].max_val = ATOMIC_DATA_MAX;
+    atomic_test[i].data = data;
+    pthread_create(&atomic_test[i].pthread_id, NULL, atomic_thread, &atomic_test[i]);
+  }
+
+  for (int i = 0; i < ATOMIC_MAX_THREADS; i++) {
+    int rc = pthread_join(atomic_test[i].pthread_id, NULL);
+    EXPECT_EQ(0, rc);
+  }
+
+  for (unsigned int i = 0; i < ATOMIC_DATA_MAX; i++) {
+    EXPECT_EQ(1 * ATOMIC_MAX_THREADS, data[i]._val);
+  }
+}
+
+TEST(AtomicTest, test_atomic_inc_thread_single) {
+  struct atomic_test_s32_s atomic_test[ATOMIC_MAX_THREADS];
+  atomic_s32_t data;
+
+  memset(&atomic_test, 0, sizeof(atomic_test));
+  memset(&data, 0, sizeof(data));
+
+  EXPECT_EQ(0, data._val);
+
+  for (int i = 0; i < ATOMIC_MAX_THREADS; i++) {
+    atomic_test[i].thread_num = i;
+    atomic_test[i].max_val = 1;
+    atomic_test[i].data = &data;
+    pthread_create(&atomic_test[i].pthread_id, NULL, atomic_thread_inc_dec, &atomic_test[i]);
+  }
+
+  for (int i = 0; i < ATOMIC_MAX_THREADS; i++) {
+    int rc = pthread_join(atomic_test[i].pthread_id, NULL);
+    EXPECT_EQ(0, rc);
+  }
+  EXPECT_EQ(0, data._val);
+}
+
+TEST(AtomicTest, test_store_load_s64) {
+  atomic_s64_t data;
+
+  atomic_store_s64(&data, -1);
+  EXPECT_EQ(-1, atomic_load_s64(&data));
+
+  atomic_store_s64(&data, 0);
+  EXPECT_EQ(0, atomic_load_s64(&data));
+
+  atomic_store_s64(&data, 1);
+  EXPECT_EQ(1, atomic_load_s64(&data));
+
+  atomic_store_s64(&data, 2);
+  EXPECT_EQ(2, atomic_load_s64(&data));
+}
+
+TEST(AtomicTest, test_inc_dec_s64) {
+  atomic_s64_t data;
+
+  atomic_store_s64(&data, 0);
+  EXPECT_EQ(0, atomic_load_s64(&data));
+
+  int64_t val = atomic_inc_prefix_s64(&data);
+  EXPECT_EQ(1, atomic_load_s64(&data));
+  EXPECT_EQ(1, val);
+
+  val = atomic_inc_prefix_s64(&data);
+  EXPECT_EQ(2, atomic_load_s64(&data));
+  EXPECT_EQ(2, val);
+
+  val = atomic_inc_prefix_s64(&data);
+  EXPECT_EQ(3, atomic_load_s64(&data));
+  EXPECT_EQ(3, val);
+
+  val = atomic_dec_prefix_s64(&data);
+  EXPECT_EQ(2, val);
+
+  val = atomic_dec_prefix_s64(&data);
+  EXPECT_EQ(1, val);
+  val = atomic_dec_prefix_s64(&data);
+  EXPECT_EQ(0, val);
+  val = atomic_dec_prefix_s64(&data);
+  EXPECT_EQ(-1, val);
+
+  // Mutating using postfix.
+  val = atomic_inc_postfix_s64(&data);
+  EXPECT_EQ(0, atomic_load_s64(&data));
+  EXPECT_EQ(-1, val);
+
+  val = atomic_inc_postfix_s64(&data);
+  EXPECT_EQ(1, atomic_load_s64(&data));
+  EXPECT_EQ(0, val);
+
+  val = atomic_inc_postfix_s64(&data);
+  EXPECT_EQ(2, atomic_load_s64(&data));
+  EXPECT_EQ(1, val);
+
+  val = atomic_dec_postfix_s64(&data);
+  EXPECT_EQ(2, val);
+
+  val = atomic_dec_postfix_s64(&data);
+  EXPECT_EQ(1, val);
+  val = atomic_dec_postfix_s64(&data);
+  EXPECT_EQ(0, val);
+  val = atomic_dec_postfix_s64(&data);
+  EXPECT_EQ(-1, val);
+  EXPECT_EQ(-2, atomic_load_s64(&data));
+}
+
+TEST(AtomicTest, test_add_sub_u64) {
+  atomic_u64_t data;
+
+  atomic_store_u64(&data, 0);
+  EXPECT_EQ((unsigned)0, atomic_load_u64(&data));
+
+  uint64_t val = atomic_add_u64(&data, 0xffff);
+  EXPECT_EQ((unsigned)0xffff, atomic_load_u64(&data));
+  EXPECT_EQ((unsigned)0xffff, val);
+
+  val = atomic_add_u64(&data, 0xffff);
+  EXPECT_EQ((unsigned)(2 * 0xffff), atomic_load_u64(&data));
+  EXPECT_EQ((unsigned)(2 * 0xffff), val);
+
+  val = atomic_add_u64(&data, 0xffff);
+  EXPECT_EQ((unsigned)(3 * 0xffff), atomic_load_u64(&data));
+  EXPECT_EQ((unsigned)(3 * 0xffff), val);
+  EXPECT_NE((unsigned)(3 * 0xfff0), val);
+
+  val = atomic_sub_u64(&data, 0xffff);
+  EXPECT_EQ((unsigned)(2 * 0xffff), val);
+
+  val = atomic_sub_u64(&data, 0);
+  EXPECT_EQ((unsigned)(2 * 0xffff), val);
+  val = atomic_sub_u64(&data, 0xffff);
+  EXPECT_EQ((unsigned)(1 * 0xffff), val);
+
+  val = atomic_sub_u64(&data, 0xffff);
+  EXPECT_EQ((unsigned)0, val);
+}
+
+
diff --git a/osi/test/config_test.cpp b/osi/test/config_test.cpp
index 1ce199d..70e5a24 100644
--- a/osi/test/config_test.cpp
+++ b/osi/test/config_test.cpp
@@ -1,5 +1,7 @@
 #include <gtest/gtest.h>
 
+#include "AllocationTestHarness.h"
+
 extern "C" {
 #include "config.h"
 }
@@ -46,18 +48,26 @@
 version = 0x1436                                                                     \n\
 ";
 
-class ConfigTest : public ::testing::Test {
+class ConfigTest : public AllocationTestHarness {
   protected:
     virtual void SetUp() {
+      AllocationTestHarness::SetUp();
       FILE *fp = fopen(CONFIG_FILE, "wt");
       fwrite(CONFIG_FILE_CONTENT, 1, sizeof(CONFIG_FILE_CONTENT), fp);
       fclose(fp);
     }
 };
 
+TEST_F(ConfigTest, config_new_empty) {
+  config_t *config = config_new_empty();
+  EXPECT_TRUE(config != NULL);
+  config_free(config);
+}
+
 TEST_F(ConfigTest, config_new_no_file) {
   config_t *config = config_new("/meow");
   EXPECT_TRUE(config == NULL);
+  config_free(config);
 }
 
 TEST_F(ConfigTest, config_new) {
@@ -111,3 +121,70 @@
   EXPECT_EQ(config_get_int(config, "DID", "primaryRecord", 123), 123);
   config_free(config);
 }
+
+TEST_F(ConfigTest, config_remove_section) {
+  config_t *config = config_new(CONFIG_FILE);
+  EXPECT_TRUE(config_remove_section(config, "DID"));
+  EXPECT_FALSE(config_has_section(config, "DID"));
+  EXPECT_FALSE(config_has_key(config, "DID", "productId"));
+  config_free(config);
+}
+
+TEST_F(ConfigTest, config_remove_section_missing) {
+  config_t *config = config_new(CONFIG_FILE);
+  EXPECT_FALSE(config_remove_section(config, "not a section"));
+  config_free(config);
+}
+
+TEST_F(ConfigTest, config_remove_key) {
+  config_t *config = config_new(CONFIG_FILE);
+  EXPECT_EQ(config_get_int(config, "DID", "productId", 999), 0x1200);
+  EXPECT_TRUE(config_remove_key(config, "DID", "productId"));
+  EXPECT_FALSE(config_has_key(config, "DID", "productId"));
+  config_free(config);
+}
+
+TEST_F(ConfigTest, config_remove_key_missing) {
+  config_t *config = config_new(CONFIG_FILE);
+  EXPECT_EQ(config_get_int(config, "DID", "productId", 999), 0x1200);
+  EXPECT_TRUE(config_remove_key(config, "DID", "productId"));
+  EXPECT_EQ(config_get_int(config, "DID", "productId", 999), 999);
+  config_free(config);
+}
+
+TEST_F(ConfigTest, config_section_begin) {
+  config_t *config = config_new(CONFIG_FILE);
+  const config_section_node_t *section = config_section_begin(config);
+  EXPECT_TRUE(section != NULL);
+  const char *section_name = config_section_name(section);
+  EXPECT_TRUE(section != NULL);
+  EXPECT_TRUE(!strcmp(section_name, CONFIG_DEFAULT_SECTION));
+  config_free(config);
+}
+
+TEST_F(ConfigTest, config_section_next) {
+  config_t *config = config_new(CONFIG_FILE);
+  const config_section_node_t *section = config_section_begin(config);
+  EXPECT_TRUE(section != NULL);
+  section = config_section_next(section);
+  EXPECT_TRUE(section != NULL);
+  const char *section_name = config_section_name(section);
+  EXPECT_TRUE(section != NULL);
+  EXPECT_TRUE(!strcmp(section_name, "DID"));
+  config_free(config);
+}
+
+TEST_F(ConfigTest, config_section_end) {
+  config_t *config = config_new(CONFIG_FILE);
+  const config_section_node_t * section = config_section_begin(config);
+  section = config_section_next(section);
+  section = config_section_next(section);
+  EXPECT_EQ(section, config_section_end(config));
+  config_free(config);
+}
+
+TEST_F(ConfigTest, config_save_basic) {
+  config_t *config = config_new(CONFIG_FILE);
+  EXPECT_TRUE(config_save(config, CONFIG_FILE));
+  config_free(config);
+}
diff --git a/osi/test/data_dispatcher_test.cpp b/osi/test/data_dispatcher_test.cpp
new file mode 100644
index 0000000..b00cfb7
--- /dev/null
+++ b/osi/test/data_dispatcher_test.cpp
@@ -0,0 +1,251 @@
+#include <gtest/gtest.h>
+
+#include "AllocationTestHarness.h"
+
+extern "C" {
+#include "data_dispatcher.h"
+#include "fixed_queue.h"
+#include "osi.h"
+}
+
+#define DUMMY_TYPE_0 34
+#define DUMMY_TYPE_1 42
+#define TYPE_EDGE_CASE_ZERO 0
+#define TYPE_EDGE_CASE_MAX INT_MAX
+
+#define DUMMY_QUEUE_SIZE 10
+
+class DataDispatcherTest : public AllocationTestHarness {};
+
+static char dummy_data_0[42] = "please test your code";
+static char dummy_data_1[42] = "testing is good for your sanity";
+
+TEST_F(DataDispatcherTest, test_new_free_simple) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+  ASSERT_TRUE(dispatcher != NULL);
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_single_to_nowhere) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+  EXPECT_FALSE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_0, dummy_data_0));
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_single_to_single) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+
+  // Register a queue
+  fixed_queue_t *dummy_queue = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_0, dummy_queue);
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  // Send data to the queue
+  EXPECT_TRUE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_0, dummy_data_0));
+
+  // Did we get it?
+  EXPECT_FALSE(fixed_queue_is_empty(dummy_queue));
+  EXPECT_STREQ(dummy_data_0, (char *)fixed_queue_try_dequeue(dummy_queue));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  fixed_queue_free(dummy_queue, NULL);
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_single_to_multiple) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+
+  // Register two queues
+  fixed_queue_t *dummy_queue0 = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  fixed_queue_t *dummy_queue1 = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_0, dummy_queue0);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_1, dummy_queue1);
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue0));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue1));
+
+  // Send data to one of them
+  EXPECT_TRUE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_0, dummy_data_0));
+
+  // Did we get it?
+  EXPECT_FALSE(fixed_queue_is_empty(dummy_queue0));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue1));
+  EXPECT_STREQ(dummy_data_0, (char *)fixed_queue_try_dequeue(dummy_queue0));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue0));
+
+  fixed_queue_free(dummy_queue0, NULL);
+  fixed_queue_free(dummy_queue1, NULL);
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_single_to_default) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+
+  // Register two queues, a default and a typed one
+  fixed_queue_t *dummy_queue = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  fixed_queue_t *default_queue = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_0, dummy_queue);
+  data_dispatcher_register_default(dispatcher, default_queue);
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+  EXPECT_TRUE(fixed_queue_is_empty(default_queue));
+
+  // Send data to nowhere
+  EXPECT_TRUE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_1, dummy_data_1));
+
+  // Did we get it?
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+  EXPECT_FALSE(fixed_queue_is_empty(default_queue));
+  EXPECT_STREQ(dummy_data_1, (char *)fixed_queue_try_dequeue(default_queue));
+  EXPECT_TRUE(fixed_queue_is_empty(default_queue));
+
+  fixed_queue_free(dummy_queue, NULL);
+  fixed_queue_free(default_queue, NULL);
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_multiple_to_single) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+
+  // Register a queue
+  fixed_queue_t *dummy_queue = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_0, dummy_queue);
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  // Send data to the queue
+  EXPECT_TRUE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_0, dummy_data_0));
+  EXPECT_TRUE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_0, dummy_data_1));
+
+  // Did we get it?
+  EXPECT_FALSE(fixed_queue_is_empty(dummy_queue));
+  EXPECT_STREQ(dummy_data_0, (char *)fixed_queue_try_dequeue(dummy_queue));
+  EXPECT_FALSE(fixed_queue_is_empty(dummy_queue));
+  EXPECT_STREQ(dummy_data_1, (char *)fixed_queue_try_dequeue(dummy_queue));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  fixed_queue_free(dummy_queue, NULL);
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_multiple_to_multiple) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+
+  // Register two queues
+  fixed_queue_t *dummy_queue0 = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  fixed_queue_t *dummy_queue1 = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_0, dummy_queue0);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_1, dummy_queue1);
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue0));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue1));
+
+  // Send data to both of them
+  EXPECT_TRUE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_0, dummy_data_0));
+  EXPECT_TRUE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_1, dummy_data_1));
+
+  // Did we get it?
+  EXPECT_FALSE(fixed_queue_is_empty(dummy_queue0));
+  EXPECT_FALSE(fixed_queue_is_empty(dummy_queue1));
+  EXPECT_STREQ(dummy_data_0, (char *)fixed_queue_try_dequeue(dummy_queue0));
+  EXPECT_STREQ(dummy_data_1, (char *)fixed_queue_try_dequeue(dummy_queue1));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue0));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue1));
+
+  fixed_queue_free(dummy_queue0, NULL);
+  fixed_queue_free(dummy_queue1, NULL);
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_single_to_single_reregistered) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+
+  // Register a queue, then reregister
+  fixed_queue_t *dummy_queue = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  fixed_queue_t *dummy_queue_reregistered = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_0, dummy_queue);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_0, dummy_queue_reregistered);
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue_reregistered));
+
+  // Send data to the queue
+  EXPECT_TRUE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_0, dummy_data_0));
+
+  // Did we get it?
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+  EXPECT_FALSE(fixed_queue_is_empty(dummy_queue_reregistered));
+  EXPECT_STREQ(dummy_data_0, (char *)fixed_queue_try_dequeue(dummy_queue_reregistered));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue_reregistered));
+
+  fixed_queue_free(dummy_queue, NULL);
+  fixed_queue_free(dummy_queue_reregistered, NULL);
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_single_to_reregistered_null) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+
+  // Register a queue
+  fixed_queue_t *dummy_queue = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_0, dummy_queue);
+  data_dispatcher_register(dispatcher, DUMMY_TYPE_0, NULL);
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  EXPECT_FALSE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_0, dummy_data_0));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  fixed_queue_free(dummy_queue, NULL);
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_single_to_default_reregistered_null) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+
+  // Register a queue
+  fixed_queue_t *dummy_queue = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  data_dispatcher_register_default(dispatcher, dummy_queue);
+  data_dispatcher_register_default(dispatcher, NULL);
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  EXPECT_FALSE(data_dispatcher_dispatch(dispatcher, DUMMY_TYPE_0, dummy_data_0));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  fixed_queue_free(dummy_queue, NULL);
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_edge_zero) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+
+  // Register a queue
+  fixed_queue_t *dummy_queue = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  data_dispatcher_register(dispatcher, TYPE_EDGE_CASE_ZERO, dummy_queue);
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  // Send data to the queue
+  EXPECT_TRUE(data_dispatcher_dispatch(dispatcher, TYPE_EDGE_CASE_ZERO, dummy_data_0));
+
+  // Did we get it?
+  EXPECT_FALSE(fixed_queue_is_empty(dummy_queue));
+  EXPECT_STREQ(dummy_data_0, (char *)fixed_queue_try_dequeue(dummy_queue));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  fixed_queue_free(dummy_queue, NULL);
+  data_dispatcher_free(dispatcher);
+}
+
+TEST_F(DataDispatcherTest, test_dispatch_edge_max) {
+  data_dispatcher_t *dispatcher = data_dispatcher_new("test_dispatcher");
+
+  // Register a queue
+  fixed_queue_t *dummy_queue = fixed_queue_new(DUMMY_QUEUE_SIZE);
+  data_dispatcher_register(dispatcher, TYPE_EDGE_CASE_MAX, dummy_queue);
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  // Send data to the queue
+  EXPECT_TRUE(data_dispatcher_dispatch(dispatcher, TYPE_EDGE_CASE_MAX, dummy_data_0));
+
+  // Did we get it?
+  EXPECT_FALSE(fixed_queue_is_empty(dummy_queue));
+  EXPECT_STREQ(dummy_data_0, (char *)fixed_queue_try_dequeue(dummy_queue));
+  EXPECT_TRUE(fixed_queue_is_empty(dummy_queue));
+
+  fixed_queue_free(dummy_queue, NULL);
+  data_dispatcher_free(dispatcher);
+}
diff --git a/osi/test/eager_reader_test.cpp b/osi/test/eager_reader_test.cpp
new file mode 100644
index 0000000..ad00e17
--- /dev/null
+++ b/osi/test/eager_reader_test.cpp
@@ -0,0 +1,147 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+#include "AllocationTestHarness.h"
+
+extern "C" {
+#include <stdint.h>
+#include <unistd.h>
+
+#include "allocator.h"
+#include "eager_reader.h"
+#include "osi.h"
+#include "semaphore.h"
+#include "thread.h"
+}
+
+#define BUFFER_SIZE 32
+
+static const char *small_data = "white chocolate lindor truffles";
+static const char *large_data =
+  "Let him make him examine and thoroughly sift everything he reads, and "
+  "lodge nothing in his fancy upon simple authority and upon trust. "
+  "Aristotle's principles will then be no more principles to him, than those "
+  "of Epicurus and the Stoics: let this diversity of opinions be propounded "
+  "to, and laid before him; he will himself choose, if he be able; if not, "
+  "he will remain in doubt. "
+  ""
+  "   \"Che non men the saver, dubbiar m' aggrata.\" "
+  "   [\"I love to doubt, as well as to know.\"--Dante, Inferno, xi. 93] "
+  ""
+  "for, if he embrace the opinions of Xenophon and Plato, by his own reason, "
+  "they will no more be theirs, but become his own.  Who follows another, "
+  "follows nothing, finds nothing, nay, is inquisitive after nothing. "
+  ""
+  "   \"Non sumus sub rege; sibi quisque se vindicet.\" "
+  "   [\"We are under no king; let each vindicate himself.\" --Seneca, Ep.,33] "
+  ""
+  "let him, at least, know that he knows.  it will be necessary that he "
+  "imbibe their knowledge, not that he be corrupted with their precepts; "
+  "and no matter if he forget where he had his learning, provided he know "
+  "how to apply it to his own use.  truth and reason are common to every "
+  "one, and are no more his who spake them first, than his who speaks them "
+  "after: 'tis no more according to plato, than according to me, since both "
+  "he and i equally see and understand them.  bees cull their several sweets "
+  "from this flower and that blossom, here and there where they find them, "
+  "but themselves afterwards make the honey, which is all and purely their "
+  "own, and no more thyme and marjoram: so the several fragments he borrows "
+  "from others, he will transform and shuffle together to compile a work "
+  "that shall be absolutely his own; that is to say, his judgment: "
+  "his instruction, labour and study, tend to nothing else but to form that. ";
+
+static semaphore_t *done;
+
+class EagerReaderTest : public AllocationTestHarness {
+  protected:
+    virtual void SetUp() {
+      AllocationTestHarness::SetUp();
+      pipe(pipefd);
+      done = semaphore_new(0);
+    }
+
+    virtual void TearDown() {
+      semaphore_free(done);
+      AllocationTestHarness::TearDown();
+    }
+
+    int pipefd[2];
+};
+
+static void expect_data(eager_reader_t *reader, void *context) {
+  char *data = (char *)context;
+  int length = strlen(data);
+
+  for (int i = 0; i < length; i++) {
+    uint8_t byte;
+    EXPECT_EQ((size_t)1, eager_reader_read(reader, &byte, 1, true));
+    EXPECT_EQ(data[i], byte);
+  }
+
+  semaphore_post(done);
+}
+
+static void expect_data_multibyte(eager_reader_t *reader, void *context) {
+  char *data = (char *)context;
+  int length = strlen(data);
+
+  for (int i = 0; i < length;) {
+    uint8_t buffer[28];
+    int bytes_to_read = (length - i) > 28 ? 28 : (length - i);
+    int bytes_read = eager_reader_read(reader, buffer, bytes_to_read, false);
+    EXPECT_EQ(bytes_to_read, bytes_read);
+    for (int j = 0; j < bytes_read && i < length; j++, i++) {
+      EXPECT_EQ(data[i], buffer[j]);
+    }
+  }
+
+  semaphore_post(done);
+}
+
+TEST_F(EagerReaderTest, test_new_free_simple) {
+  eager_reader_t *reader = eager_reader_new(pipefd[0], &allocator_malloc, BUFFER_SIZE, SIZE_MAX, "test_thread");
+  ASSERT_TRUE(reader != NULL);
+  eager_reader_free(reader);
+}
+
+TEST_F(EagerReaderTest, test_small_data) {
+  eager_reader_t *reader = eager_reader_new(pipefd[0], &allocator_malloc, BUFFER_SIZE, SIZE_MAX, "test_thread");
+
+  thread_t *read_thread = thread_new("read_thread");
+  eager_reader_register(reader, thread_get_reactor(read_thread), expect_data, (void *)small_data);
+
+  write(pipefd[1], small_data, strlen(small_data));
+
+  semaphore_wait(done);
+  eager_reader_free(reader);
+  thread_free(read_thread);
+}
+
+TEST_F(EagerReaderTest, test_large_data_multibyte) {
+  eager_reader_t *reader = eager_reader_new(pipefd[0], &allocator_malloc, BUFFER_SIZE, SIZE_MAX, "test_thread");
+
+  thread_t *read_thread = thread_new("read_thread");
+  eager_reader_register(reader, thread_get_reactor(read_thread), expect_data_multibyte, (void *)large_data);
+
+  write(pipefd[1], large_data, strlen(large_data));
+
+  semaphore_wait(done);
+  eager_reader_free(reader);
+  thread_free(read_thread);
+}
diff --git a/osi/test/future_test.cpp b/osi/test/future_test.cpp
new file mode 100644
index 0000000..880f892
--- /dev/null
+++ b/osi/test/future_test.cpp
@@ -0,0 +1,54 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+#include "AllocationTestHarness.h"
+
+extern "C" {
+#include "future.h"
+#include "osi.h"
+#include "thread.h"
+}
+
+static const char *pass_back_data0 = "fancy a sandwich? it's a fancy sandwich";
+static const char *pass_back_data1 = "what kind of ice cream truck plays the worst christmas song of all time?";
+
+class FutureTest : public AllocationTestHarness {};
+
+static void post_to_future(void *context) {
+  future_ready((future_t *)context, (void *)pass_back_data0);
+}
+
+TEST_F(FutureTest, test_future_non_immediate) {
+  future_t *future = future_new();
+  ASSERT_TRUE(future != NULL);
+
+  thread_t *worker_thread = thread_new("worker thread");
+  thread_post(worker_thread, post_to_future, future);
+
+  EXPECT_EQ(pass_back_data0, future_await(future));
+
+  thread_free(worker_thread);
+}
+
+TEST_F(FutureTest, test_future_immediate) {
+  future_t *future = future_new_immediate((void *)pass_back_data1);
+  ASSERT_TRUE(future != NULL);
+  EXPECT_EQ(pass_back_data1, future_await(future));
+}
diff --git a/osi/test/hash_map_test.cpp b/osi/test/hash_map_test.cpp
new file mode 100644
index 0000000..086b414
--- /dev/null
+++ b/osi/test/hash_map_test.cpp
@@ -0,0 +1,202 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <gtest/gtest.h>
+
+#include "AllocationTestHarness.h"
+
+extern "C" {
+#include "hash_map.h"
+#include "osi.h"
+}
+
+class HashMapTest : public AllocationTestHarness {};
+
+hash_index_t hash_map_fn00(const void *key) {
+  hash_index_t hash_key = (hash_index_t)key;
+  return hash_key;
+}
+
+static size_t g_key_free;
+void key_free_fn00(UNUSED_ATTR void *data) {
+  g_key_free++;
+}
+
+static size_t g_data_free;
+void data_free_fn00(UNUSED_ATTR void *data) {
+  g_data_free++;
+}
+
+TEST_F(HashMapTest, test_new_free_simple) {
+  hash_map_t *hash_map = hash_map_new(5, hash_map_fn00, NULL, NULL, NULL);
+  ASSERT_TRUE(hash_map != NULL);
+  hash_map_free(hash_map);
+}
+
+TEST_F(HashMapTest, test_insert_simple) {
+  hash_map_t *hash_map = hash_map_new(5, hash_map_fn00, NULL, NULL, NULL);
+  ASSERT_TRUE(hash_map != NULL);
+
+  struct {
+    const char *key;
+    const char *data;
+  } data[] = {
+    { "0", "zero" },
+    { "1", "one" },
+    { "2", "two" },
+    { "3", "three" },
+  };
+
+  size_t data_sz = sizeof(data)/sizeof(data[0]);
+
+  for (size_t i = 0; i < data_sz; i++) {
+    EXPECT_EQ(i, hash_map_size(hash_map));
+    hash_map_set(hash_map, data[i].key, (void*)data[i].data);
+    EXPECT_EQ(i + 1, hash_map_size(hash_map));
+  }
+
+  EXPECT_EQ(data_sz, hash_map_size(hash_map));
+
+  for (size_t i = 0; i < data_sz; i++) {
+    char *val = (char *)hash_map_get(hash_map, data[i].key);
+    EXPECT_STREQ(data[i].data, val);
+  }
+  EXPECT_EQ(data_sz, hash_map_size(hash_map));
+
+  hash_map_free(hash_map);
+}
+
+TEST_F(HashMapTest, test_insert_same) {
+  hash_map_t *hash_map = hash_map_new(5, hash_map_fn00, NULL, NULL, NULL);
+  ASSERT_TRUE(hash_map != NULL);
+
+  struct {
+    const char *key;
+    const char *data;
+  } data[] = {
+    { "0", "zero" },
+    { "0", "one" },
+    { "0", "two" },
+    { "0", "three" },
+  };
+
+  size_t data_sz = sizeof(data)/sizeof(data[0]);
+
+  for (size_t i = 0; i < data_sz; i++) {
+    hash_map_set(hash_map, data[i].key, (void*)data[i].data);
+    EXPECT_EQ(1U, hash_map_size(hash_map));
+  }
+
+  EXPECT_EQ(1U, hash_map_size(hash_map));
+
+  for (size_t i = 0; i < data_sz; i++) {
+    char *val = (char *)hash_map_get(hash_map, data[i].key);
+    EXPECT_STREQ(data[data_sz - 1].data, val);
+  }
+
+  hash_map_free(hash_map);
+}
+
+TEST_F(HashMapTest, test_functions) {
+  hash_map_t *hash_map = hash_map_new(5, hash_map_fn00, key_free_fn00, data_free_fn00, NULL);
+  ASSERT_TRUE(hash_map != NULL);
+
+  struct {
+    const char *key;
+    const char *data;
+  } data[] = {
+    { "0", "zero" },
+    { "1", "one" },
+    { "2", "two" },
+    { "3", "three" },
+  };
+
+  g_data_free = 0;
+  g_key_free = 0;
+
+  size_t data_sz = sizeof(data)/sizeof(data[0]);
+
+  for (size_t i = 0; i < data_sz; i++) {
+    EXPECT_EQ(hash_map_size(hash_map), i);
+    hash_map_set(hash_map, data[i].key, (void*)data[i].data);
+  }
+
+  EXPECT_EQ(data_sz, hash_map_size(hash_map));
+  EXPECT_EQ((size_t)0, g_data_free);
+  EXPECT_EQ((size_t)0, g_key_free);
+
+  for (size_t i = 0; i < data_sz; i++) {
+    char *val = (char *)hash_map_get(hash_map, data[i].key);
+    EXPECT_TRUE(val != NULL);
+    EXPECT_STREQ(data[i].data, val);
+    hash_map_erase(hash_map, (void*)data[i].key);
+    EXPECT_EQ(i + 1, g_data_free);
+    EXPECT_EQ(i + 1, g_key_free);
+  }
+
+  hash_map_free(hash_map);
+}
+
+struct hash_test_iter_data_s {
+  const char *key;
+  const char *data;
+} hash_test_iter_data[] = {
+  { "0", "zero" },
+  { "1", "one" },
+  { "2", "two" },
+  { "3", "three" },
+  { "elephant", "big" },
+  { "fox", "medium" },
+  { "gerbil", "small" },
+};
+
+bool hash_test_iter_ro_cb(hash_map_entry_t *hash_map_entry, void *context) {
+  const char *key = (const char *)hash_map_entry->key;
+  char *data = (char *)hash_map_entry->data;
+  EXPECT_TRUE(data != NULL);
+
+  size_t hash_test_iter_data_sz = sizeof(hash_test_iter_data)/sizeof(hash_test_iter_data[0]);
+  size_t i;
+  for (i = 0; i < hash_test_iter_data_sz; i++) {
+    if (!strcmp(hash_test_iter_data[i].key, key))
+      break;
+  }
+  EXPECT_NE(hash_test_iter_data_sz, i);
+  EXPECT_EQ(NULL, context);
+  EXPECT_STREQ(hash_test_iter_data[i].data, data);
+  return true;
+}
+
+TEST_F(HashMapTest, test_iter) {
+  hash_map_t *hash_map = hash_map_new(5, hash_map_fn00, key_free_fn00, data_free_fn00, NULL);
+  ASSERT_TRUE(hash_map != NULL);
+  g_data_free = 0;
+  g_key_free = 0;
+
+  size_t hash_test_iter_data_sz = sizeof(hash_test_iter_data)/sizeof(hash_test_iter_data[0]);
+
+  for (size_t i = 0; i < hash_test_iter_data_sz; i++) {
+    EXPECT_EQ(hash_map_size(hash_map), i);
+    hash_map_set(hash_map, hash_test_iter_data[i].key, (void*)hash_test_iter_data[i].data);
+  }
+
+  void *context = NULL;
+  hash_map_foreach(hash_map, hash_test_iter_ro_cb, context);
+
+  hash_map_free(hash_map);
+}
diff --git a/osi/test/list_test.cpp b/osi/test/list_test.cpp
index d874b4b..6301e7e 100644
--- a/osi/test/list_test.cpp
+++ b/osi/test/list_test.cpp
@@ -1,39 +1,38 @@
 #include <gtest/gtest.h>
 
+#include "AllocationTestHarness.h"
+
 extern "C" {
 #include "list.h"
 #include "osi.h"
 }
 
-TEST(ListTest, test_new_simple) {
+class ListTest : public AllocationTestHarness {};
+
+TEST_F(ListTest, test_new_free_simple) {
   list_t *list = list_new(NULL);
   ASSERT_TRUE(list != NULL);
-}
-
-TEST(ListTest, test_free_simple) {
-  // In this test we just verify that list_free is callable with a valid list.
-  list_t *list = list_new(NULL);
   list_free(list);
 }
 
-TEST(ListTest, test_free_null) {
+TEST_F(ListTest, test_free_null) {
   // In this test we just verify that list_free is callable with NULL.
   list_free(NULL);
 }
 
-TEST(ListTest, test_empty_list_is_empty) {
+TEST_F(ListTest, test_empty_list_is_empty) {
   list_t *list = list_new(NULL);
   EXPECT_TRUE(list_is_empty(list));
   list_free(list);
 }
 
-TEST(ListTest, test_empty_list_has_no_length) {
+TEST_F(ListTest, test_empty_list_has_no_length) {
   list_t *list = list_new(NULL);
   EXPECT_EQ(list_length(list), 0U);
   list_free(list);
 }
 
-TEST(ListTest, test_simple_list_prepend) {
+TEST_F(ListTest, test_simple_list_prepend) {
   list_t *list = list_new(NULL);
   EXPECT_TRUE(list_prepend(list, &list));
   EXPECT_FALSE(list_is_empty(list));
@@ -41,7 +40,7 @@
   list_free(list);
 }
 
-TEST(ListTest, test_simple_list_append) {
+TEST_F(ListTest, test_simple_list_append) {
   list_t *list = list_new(NULL);
   EXPECT_TRUE(list_append(list, &list));
   EXPECT_FALSE(list_is_empty(list));
@@ -49,7 +48,7 @@
   list_free(list);
 }
 
-TEST(ListTest, test_list_remove_found) {
+TEST_F(ListTest, test_list_remove_found) {
   list_t *list = list_new(NULL);
   list_append(list, &list);
   EXPECT_TRUE(list_remove(list, &list));
@@ -58,7 +57,7 @@
   list_free(list);
 }
 
-TEST(ListTest, test_list_remove_not_found) {
+TEST_F(ListTest, test_list_remove_not_found) {
   int x;
   list_t *list = list_new(NULL);
   list_append(list, &list);
@@ -68,7 +67,7 @@
   list_free(list);
 }
 
-TEST(ListTest, test_list_front) {
+TEST_F(ListTest, test_list_front) {
   int x[] = { 1, 2, 3, 4, 5 };
   list_t *list = list_new(NULL);
 
@@ -80,7 +79,7 @@
   list_free(list);
 }
 
-TEST(ListTest, test_list_back) {
+TEST_F(ListTest, test_list_back) {
   int x[] = { 1, 2, 3, 4, 5 };
   list_t *list = list_new(NULL);
 
@@ -92,7 +91,7 @@
   list_free(list);
 }
 
-TEST(ListTest, test_list_clear) {
+TEST_F(ListTest, test_list_clear) {
   int x[] = { 1, 2, 3, 4, 5 };
   list_t *list = list_new(NULL);
 
@@ -106,7 +105,7 @@
   list_free(list);
 }
 
-TEST(ListTest, test_list_append_multiple) {
+TEST_F(ListTest, test_list_append_multiple) {
   int x[] = { 1, 2, 3, 4, 5 };
   list_t *list = list_new(NULL);
 
@@ -120,7 +119,7 @@
   list_free(list);
 }
 
-TEST(ListTest, test_list_prepend_multiple) {
+TEST_F(ListTest, test_list_prepend_multiple) {
   int x[] = { 1, 2, 3, 4, 5 };
   list_t *list = list_new(NULL);
 
@@ -134,13 +133,13 @@
   list_free(list);
 }
 
-TEST(ListTest, test_list_begin_empty_list) {
+TEST_F(ListTest, test_list_begin_empty_list) {
   list_t *list = list_new(NULL);
   EXPECT_EQ(list_begin(list), list_end(list));
   list_free(list);
 }
 
-TEST(ListTest, test_list_next) {
+TEST_F(ListTest, test_list_next) {
   list_t *list = list_new(NULL);
   list_append(list, &list);
   EXPECT_NE(list_begin(list), list_end(list));
diff --git a/osi/test/reactor_test.cpp b/osi/test/reactor_test.cpp
index 4a9fb21..6e3a009 100644
--- a/osi/test/reactor_test.cpp
+++ b/osi/test/reactor_test.cpp
@@ -1,12 +1,17 @@
 #include <gtest/gtest.h>
 #include <pthread.h>
+#include <sys/eventfd.h>
 #include <sys/time.h>
 #include <unistd.h>
 
+#include "AllocationTestHarness.h"
+
 extern "C" {
 #include "reactor.h"
 }
 
+class ReactorTest : public AllocationTestHarness {};
+
 static pthread_t thread;
 static volatile bool thread_running;
 
@@ -29,30 +34,24 @@
   pthread_join(thread, NULL);
 }
 
-static uint64_t get_timestamp(void) {
-  struct timeval tv;
-  gettimeofday(&tv, NULL);
-  return tv.tv_sec * 1000 + tv.tv_usec / 1000;
-}
-
-TEST(ReactorTest, reactor_new) {
+TEST_F(ReactorTest, reactor_new) {
   reactor_t *reactor = reactor_new();
   EXPECT_TRUE(reactor != NULL);
   reactor_free(reactor);
 }
 
-TEST(ReactorTest, reactor_free_null) {
+TEST_F(ReactorTest, reactor_free_null) {
   reactor_free(NULL);
 }
 
-TEST(ReactorTest, reactor_stop_start) {
+TEST_F(ReactorTest, reactor_stop_start) {
   reactor_t *reactor = reactor_new();
   reactor_stop(reactor);
   reactor_start(reactor);
   reactor_free(reactor);
 }
 
-TEST(ReactorTest, reactor_repeated_stop_start) {
+TEST_F(ReactorTest, reactor_repeated_stop_start) {
   reactor_t *reactor = reactor_new();
   for (int i = 0; i < 10; ++i) {
     reactor_stop(reactor);
@@ -61,21 +60,7 @@
   reactor_free(reactor);
 }
 
-TEST(ReactorTest, reactor_multi_stop_start) {
-  reactor_t *reactor = reactor_new();
-
-  reactor_stop(reactor);
-  reactor_stop(reactor);
-  reactor_stop(reactor);
-
-  reactor_start(reactor);
-  reactor_start(reactor);
-  reactor_start(reactor);
-
-  reactor_free(reactor);
-}
-
-TEST(ReactorTest, reactor_start_wait_stop) {
+TEST_F(ReactorTest, reactor_start_wait_stop) {
   reactor_t *reactor = reactor_new();
 
   spawn_reactor_thread(reactor);
@@ -89,13 +74,46 @@
   reactor_free(reactor);
 }
 
-TEST(ReactorTest, reactor_run_once_timeout) {
+typedef struct {
+  reactor_t *reactor;
+  reactor_object_t *object;
+} unregister_arg_t;
+
+static void unregister_cb(void *context) {
+  unregister_arg_t *arg = (unregister_arg_t *)context;
+  reactor_unregister(arg->object);
+  reactor_stop(arg->reactor);
+}
+
+TEST_F(ReactorTest, reactor_unregister_from_callback) {
   reactor_t *reactor = reactor_new();
 
-  uint64_t start = get_timestamp();
-  reactor_status_t status = reactor_run_once_timeout(reactor, 50);
-  EXPECT_GE(get_timestamp() - start, static_cast<uint64_t>(50));
-  EXPECT_EQ(status, REACTOR_STATUS_TIMEOUT);
+  int fd = eventfd(0, 0);
+  unregister_arg_t arg;
+  arg.reactor = reactor;
+  arg.object = reactor_register(reactor, fd, &arg, unregister_cb, NULL);
+  spawn_reactor_thread(reactor);
+  eventfd_write(fd, 1);
 
+  join_reactor_thread();
+
+  close(fd);
+  reactor_free(reactor);
+}
+
+TEST_F(ReactorTest, reactor_unregister_from_separate_thread) {
+  reactor_t *reactor = reactor_new();
+
+  int fd = eventfd(0, 0);
+
+  reactor_object_t *object = reactor_register(reactor, fd, NULL, NULL, NULL);
+  spawn_reactor_thread(reactor);
+  usleep(50 * 1000);
+  reactor_unregister(object);
+
+  reactor_stop(reactor);
+  join_reactor_thread();
+
+  close(fd);
   reactor_free(reactor);
 }
diff --git a/osi/test/test_stubs.h b/osi/test/test_stubs.h
new file mode 100644
index 0000000..dc38926
--- /dev/null
+++ b/osi/test/test_stubs.h
@@ -0,0 +1,99 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+// Helper macros for stubbing out functions and modules for testing.
+
+// Stub out a function, with call counting and mode awareness
+#define STUB_FUNCTION(ret, name, params) \
+  UNUSED_ATTR static int name##_callcount; \
+  static ret name params { \
+    UNUSED_ATTR int _local_callcount = name##_callcount; \
+    name##_callcount++;
+
+// Expect a certain number of calls to the specified stub function
+#define EXPECT_CALL_COUNT(name, count) \
+  EXPECT_EQ((count), (name##_callcount)) << "expected " #name " to be called " #count " times"
+
+// Reset the call count for the specificed stub function
+#define RESET_CALL_COUNT(name) ((name##_callcount) = 0)
+
+// Use this in a stub function to catch unexpected calls.
+// Prints out a nice message including the call count, the
+// stub function name, and the mode index (sadly no mode name)
+#define UNEXPECTED_CALL EXPECT_TRUE(false) \
+  << "unexpected call " << _local_callcount \
+  << " to " << __func__ \
+  << " during mode " << (int)_current_mode
+
+#define MODE_IS(mode) (_current_mode == (mode))
+
+// Macro selection helpers
+#define OVERLOAD_CAT(A, B) A##B
+#define OVERLOAD_SELECT(NAME, NUM) OVERLOAD_CAT(NAME##_, NUM)
+#define OVERLOAD_GET_COUNT(_1, _2, _3, _4, _5, _6, COUNT, ...) COUNT
+#define OVERLOAD_VA_SIZE(...) OVERLOAD_GET_COUNT(__VA_ARGS__, 6, 5, 4, 3, 2, 1)
+#define OVERLOAD_OF(NAME, ...) OVERLOAD_SELECT(NAME, OVERLOAD_VA_SIZE(__VA_ARGS__))(__VA_ARGS__)
+
+// Use this to branch stub function execution to a specific mode or modes.
+// Treat it like an if statement. For example:
+//
+// DURING(dinner) EXPECT_EQ(bread_pudding, food);
+// DURING(midday_snack, midnight_snack) EXPECT_EQ(chocolate, food);
+#define DURING(...) OVERLOAD_OF(DURING, __VA_ARGS__)
+
+#define DURING_1(mode0) \
+  if (MODE_IS(mode0))
+#define DURING_2(mode0, mode1) \
+  if (MODE_IS(mode0) || MODE_IS(mode1))
+#define DURING_3(mode0, mode1, mode2) \
+  if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2))
+#define DURING_4(mode0, mode1, mode2, mode3) \
+  if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2) || MODE_IS(mode3))
+#define DURING_5(mode0, mode1, mode2, mode3, mode4) \
+  if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2) || MODE_IS(mode3) || MODE_IS(mode4))
+#define DURING_6(mode0, mode1, mode2, mode3, mode4, mode5) \
+  if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2) || MODE_IS(mode3) || MODE_IS(mode4) || MODE_IS(mode5))
+
+// Use this to branch stub function exeuction to a specific call
+// count index (zero based). Treat it like an if statement.
+// Usually most helpful following a DURING clause. For example:
+//
+// DURING (breakfast) AT_CALL(0) EXPECT_EQ(bacon, food);
+//
+// or
+//
+// DURING (three_course_meal) {
+//   AT_CALL(0) EXPECT_EQ(shrimp_cocktail, food);
+//   AT_CALL(1) EXPECT_EQ(bacon_wrapped_bacon, food);
+//   AT_CALL(1) EXPECT_EQ(chocolate_covered_fake_blueberries, food);
+// }
+#define AT_CALL(index) \
+  if (_local_callcount == index)
+
+// Declare all the available test modes for the DURING clauses
+// For example:
+//
+// DECLARE_TEST_MODES(breakfast, lunch, dinner);
+#define DECLARE_TEST_MODES(...) \
+  typedef enum { __VA_ARGS__ } _test_modes_t; \
+  static _test_modes_t _current_mode;
+
+// Get the current test mode
+#define CURRENT_TEST_MODE _current_mode
+
+#define TEST_MODES_T _test_modes_t
diff --git a/osi/test/thread_test.cpp b/osi/test/thread_test.cpp
index edbc005..e626c73 100644
--- a/osi/test/thread_test.cpp
+++ b/osi/test/thread_test.cpp
@@ -1,35 +1,60 @@
 #include <gtest/gtest.h>
 
+#include "AllocationTestHarness.h"
+
 extern "C" {
+#include <sys/select.h>
+
+#include "reactor.h"
+#include "semaphore.h"
 #include "thread.h"
 #include "osi.h"
 }
 
-TEST(ThreadTest, test_new_simple) {
+class ThreadTest : public AllocationTestHarness {};
+
+TEST_F(ThreadTest, test_new_simple) {
   thread_t *thread = thread_new("test_thread");
   ASSERT_TRUE(thread != NULL);
   thread_free(thread);
 }
 
-TEST(ThreadTest, test_free_simple) {
+TEST_F(ThreadTest, test_free_simple) {
   thread_t *thread = thread_new("test_thread");
   thread_free(thread);
 }
 
-TEST(ThreadTest, test_name) {
+TEST_F(ThreadTest, test_name) {
   thread_t *thread = thread_new("test_name");
   ASSERT_STREQ(thread_name(thread), "test_name");
   thread_free(thread);
 }
 
-TEST(ThreadTest, test_long_name) {
+TEST_F(ThreadTest, test_long_name) {
   thread_t *thread = thread_new("0123456789abcdef");
   ASSERT_STREQ("0123456789abcdef", thread_name(thread));
   thread_free(thread);
 }
 
-TEST(ThreadTest, test_very_long_name) {
+TEST_F(ThreadTest, test_very_long_name) {
   thread_t *thread = thread_new("0123456789abcdefg");
   ASSERT_STREQ("0123456789abcdef", thread_name(thread));
   thread_free(thread);
 }
+
+static void thread_is_self_fn(void *context) {
+  thread_t *thread = (thread_t *)context;
+  EXPECT_TRUE(thread_is_self(thread));
+}
+
+TEST_F(ThreadTest, test_thread_is_self) {
+  thread_t *thread = thread_new("test_thread");
+  thread_post(thread, thread_is_self_fn, thread);
+  thread_free(thread);
+}
+
+TEST_F(ThreadTest, test_thread_is_not_self) {
+  thread_t *thread = thread_new("test_thread");
+  EXPECT_FALSE(thread_is_self(thread));
+  thread_free(thread);
+}
diff --git a/profile/Android.mk b/profile/Android.mk
new file mode 100644
index 0000000..5683d7f
--- /dev/null
+++ b/profile/Android.mk
@@ -0,0 +1,41 @@
+ ##############################################################################
+ #
+ #  Copyright (C) 2014 Google, Inc.
+ #
+ #  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.
+ #
+ ##############################################################################
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_C_INCLUDES := \
+    $(LOCAL_PATH)/.. \
+    $(LOCAL_PATH)/include \
+    $(LOCAL_PATH)/../btcore/include \
+    $(LOCAL_PATH)/../include \
+    $(LOCAL_PATH)/../osi/include \
+    $(bdroid_C_INCLUDES)
+
+LOCAL_SRC_FILES := \
+    src/manager.c
+
+LOCAL_CFLAGS := $(bdroid_CFLAGS)
+LOCAL_CONLYFLAGS := $(bdroid_CONLYFLAGS)
+LOCAL_MODULE := libbtprofile
+LOCAL_MODULE_TAGS := optional
+LOCAL_SHARED_LIBRARIES := libc liblog
+LOCAL_MODULE_CLASS := STATIC_LIBRARIES
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/profile/include/manager.h b/profile/include/manager.h
new file mode 100644
index 0000000..587369f
--- /dev/null
+++ b/profile/include/manager.h
@@ -0,0 +1,41 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+static const char PROFILE_MANAGER_MODULE[] = "profile_manager_module";
+
+typedef enum {
+  PROFILE_POWER_ACTIVE,
+  PROFILE_POWER_HOLD,
+  PROFILE_POWER_SNIFF,
+  PROFILE_POWER_PARK
+} profile_power_level_t;
+
+typedef struct profile_t {
+  const char *name;
+  profile_power_level_t lowest_acceptable_power_mode;
+  bool in_use;
+} profile_t;
+
+// Registers a given Bluetooth |profile| with the manager.
+void profile_register(const profile_t *profile);
+
+// Looks up a previously registered profile by |name|. If no profile was
+// registered by the given |name|, then this function returns NULL.
+const profile_t *profile_by_name(const char *name);
diff --git a/profile/src/manager.c b/profile/src/manager.c
new file mode 100644
index 0000000..9e56b65
--- /dev/null
+++ b/profile/src/manager.c
@@ -0,0 +1,87 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_profile_manager"
+
+#include <assert.h>
+#include <stdbool.h>
+
+#include "btcore/include/module.h"
+#include "profile/include/manager.h"
+#include "osi/include/future.h"
+#include "osi/include/hash_functions.h"
+#include "osi/include/hash_map.h"
+#include "osi/include/log.h"
+#include "osi/include/osi.h"
+
+static const size_t number_of_profile_buckets = 15;
+
+static bool initialized;
+static hash_map_t *profile_map;
+
+// Lifecycle management functions
+
+static future_t *init(void) {
+  profile_map = hash_map_new(
+    number_of_profile_buckets,
+    hash_function_string,
+    NULL,
+    NULL,
+    NULL);
+
+  initialized = true;
+  return NULL;
+}
+
+static future_t *clean_up(void) {
+  initialized = false;
+
+  hash_map_free(profile_map);
+  profile_map = NULL;
+
+  return NULL;
+}
+
+const module_t profile_manager_module = {
+  .name = PROFILE_MANAGER_MODULE,
+  .init = init,
+  .start_up = NULL,
+  .shut_down = NULL,
+  .clean_up = clean_up,
+  .dependencies = {
+    NULL
+  }
+};
+
+// Interface functions
+
+void profile_register(const profile_t *profile) {
+  assert(initialized);
+  assert(profile != NULL);
+  assert(profile->name != NULL);
+  assert(!hash_map_has_key(profile_map, profile->name));
+
+  hash_map_set(profile_map, profile->name, (void *) profile);
+}
+
+const profile_t *profile_by_name(const char *name) {
+  assert(initialized);
+  assert(name != NULL);
+
+  return (profile_t *)hash_map_get(profile_map, name);
+}
diff --git a/stack/Android.mk b/stack/Android.mk
index 73ffdf8..518188e 100644
--- a/stack/Android.mk
+++ b/stack/Android.mk
@@ -17,11 +17,15 @@
                    $(LOCAL_PATH)/sdp \
                    $(LOCAL_PATH)/smp \
                    $(LOCAL_PATH)/srvc \
+                   $(LOCAL_PATH)/../btcore/include \
                    $(LOCAL_PATH)/../vnd/include \
                    $(LOCAL_PATH)/../vnd/ble \
+                   $(LOCAL_PATH)/../btif/include \
+                   $(LOCAL_PATH)/../hci/include \
                    $(LOCAL_PATH)/../include \
                    $(LOCAL_PATH)/../gki/common \
                    $(LOCAL_PATH)/../gki/ulinux \
+                   $(LOCAL_PATH)/../osi/include \
                    $(LOCAL_PATH)/../udrv/include \
                    $(LOCAL_PATH)/../rpc/include \
                    $(LOCAL_PATH)/../hcis \
@@ -29,6 +33,7 @@
                    $(LOCAL_PATH)/../bta/include \
                    $(LOCAL_PATH)/../bta/sys \
                    $(LOCAL_PATH)/../utils/include \
+                   $(LOCAL_PATH)/../ \
                    $(bdroid_C_INCLUDES) \
 
 LOCAL_CFLAGS += $(bdroid_CFLAGS) -std=c99
@@ -144,15 +149,15 @@
     ./l2cap/l2c_csm.c \
     ./l2cap/l2c_link.c \
     ./l2cap/l2c_ble.c \
+    ./l2cap/l2cap_client.c \
     ./gap/gap_api.c \
     ./gap/gap_ble.c \
-    ./gap/gap_conn.c \
-    ./gap/gap_utils.c \
     ../vnd/ble/vendor_ble.c
 
 LOCAL_MODULE := libbt-brcm_stack
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE_CLASS := STATIC_LIBRARIES
+LOCAL_STATIC_LIBRARIES := libbt-hci
 LOCAL_SHARED_LIBRARIES := libcutils libc
 LOCAL_MULTILIB := 32
 # gnu-variable-sized-type-not-at-end is needed for a variable-size header in
diff --git a/stack/a2dp/a2d_int.h b/stack/a2dp/a2d_int.h
index 4aaa083..84e109b 100644
--- a/stack/a2dp/a2d_int.h
+++ b/stack/a2dp/a2d_int.h
@@ -67,14 +67,14 @@
 ** Main Control Block
 *******************************************************************************/
 #if A2D_DYNAMIC_MEMORY == FALSE
-A2D_API extern tA2D_CB  a2d_cb;
+extern tA2D_CB  a2d_cb;
 #else
-A2D_API extern tA2D_CB *a2d_cb_ptr;
+extern tA2D_CB *a2d_cb_ptr;
 #define a2d_cb (*a2d_cb_ptr)
 #endif
 
 /* Used only for conformance testing */
-A2D_API extern void a2d_set_avdt_sdp_ver (UINT16 avdt_sdp_ver);
+extern void a2d_set_avdt_sdp_ver (UINT16 avdt_sdp_ver);
 
 #ifdef __cplusplus
 }
diff --git a/stack/a2dp/a2d_sbc.c b/stack/a2dp/a2d_sbc.c
index 3858b4a..4b786b4 100644
--- a/stack/a2dp/a2d_sbc.c
+++ b/stack/a2dp/a2d_sbc.c
@@ -24,14 +24,13 @@
  ******************************************************************************/
 
 #include "bt_target.h"
+
 #include <string.h>
 #include "a2d_api.h"
 #include "a2d_int.h"
 #include "a2d_sbc.h"
 #include "bt_utils.h"
 
-#if (A2D_SBC_INCLUDED == TRUE)
-
 /*************************************************************************************************
  * SBC descramble code
  * Purpose: to tie the SBC code with BTE/mobile stack code,
@@ -280,14 +279,13 @@
 {
     tA2D_STATUS status;
     UINT8   losc;
-    UINT8   mt;
 
     if( p_ie == NULL || p_info == NULL)
         status = A2D_INVALID_PARAMS;
     else
     {
         losc    = *p_info++;
-        mt      = *p_info++;
+        *p_info++;
         /* If the function is called for the wrong Media Type or Media Codec Type */
         if(losc != A2D_SBC_INFO_LEN || *p_info != A2D_MEDIA_CT_SBC)
             status = A2D_WRONG_CODEC;
@@ -399,57 +397,3 @@
     }
 }
 
-#else /* A2D_SBC_INCLUDED == TRUE */
-
-void A2D_SbcChkFrInit(UINT8 *p_pkt)
-{
-    UNUSED(p_pkt);
-}
-
-void A2D_SbcDescramble(UINT8 *p_pkt, UINT16 len)
-{
-    UNUSED(p_pkt);
-    UNUSED(len);
-}
-
-tA2D_STATUS A2D_BldSbcInfo(UINT8 media_type, tA2D_SBC_CIE *p_ie,
-                           UINT8 *p_result)
-{
-    UNUSED(media_type);
-    UNUSED(p_ie);
-    UNUSED(p_result);
-    return A2D_FAIL;
-}
-
-tA2D_STATUS A2D_ParsSbcInfo(tA2D_SBC_CIE *p_ie, UINT8 *p_info,
-                            BOOLEAN for_caps)
-{
-    UNUSED(p_ie);
-    UNUSED(p_info);
-    UNUSED(for_caps);
-    return A2D_FAIL;
-}
-
-void A2D_BldSbcMplHdr(UINT8 *p_dst, BOOLEAN frag, BOOLEAN start,
-                      BOOLEAN last, UINT8 num)
-{
-    UNUSED(p_dst);
-    UNUSED(frag);
-    UNUSED(start);
-    UNUSED(last);
-    UNUSED(num);
-}
-
-void A2D_ParsSbcMplHdr(UINT8 *p_src, BOOLEAN *p_frag,
-                       BOOLEAN *p_start, BOOLEAN *p_last,
-                       UINT8 *p_num)
-{
-    UNUSED(p_src);
-    UNUSED(p_frag);
-    UNUSED(p_start);
-    UNUSED(p_last);
-    UNUSED(p_num);
-}
-
-
-#endif /* A2D_SBC_INCLUDED == TRUE */
diff --git a/stack/avct/avct_api.c b/stack/avct/avct_api.c
index 5b27cc8..5ee9282 100644
--- a/stack/avct/avct_api.c
+++ b/stack/avct/avct_api.c
@@ -23,7 +23,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "gki.h"
diff --git a/stack/avct/avct_ccb.c b/stack/avct/avct_ccb.c
index f2c821c..e0f87de 100644
--- a/stack/avct/avct_ccb.c
+++ b/stack/avct/avct_ccb.c
@@ -24,7 +24,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "avct_api.h"
 #include "avct_int.h"
diff --git a/stack/avct/avct_int.h b/stack/avct/avct_int.h
index b93c032..29300a5 100644
--- a/stack/avct/avct_int.h
+++ b/stack/avct/avct_int.h
@@ -218,9 +218,9 @@
 
 /* Main control block */
 #if AVCT_DYNAMIC_MEMORY == FALSE
-AVCT_API extern tAVCT_CB avct_cb;
+extern tAVCT_CB avct_cb;
 #else
-AVCT_API extern tAVCT_CB *avct_cb_ptr;
+extern tAVCT_CB *avct_cb_ptr;
 #define avct_cb (*avct_cb_ptr)
 #endif
 
@@ -235,5 +235,3 @@
 #endif
 
 #endif /* AVCT_INT_H */
-
-
diff --git a/stack/avct/avct_l2c.c b/stack/avct/avct_l2c.c
index bb01e89..815fa4b 100644
--- a/stack/avct/avct_l2c.c
+++ b/stack/avct/avct_l2c.c
@@ -23,7 +23,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "avct_api.h"
diff --git a/stack/avct/avct_lcb.c b/stack/avct/avct_lcb.c
index 6c8fd2e..eabb8aa 100644
--- a/stack/avct/avct_lcb.c
+++ b/stack/avct/avct_lcb.c
@@ -24,7 +24,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "avct_api.h"
diff --git a/stack/avct/avct_lcb_act.c b/stack/avct/avct_lcb_act.c
index 2240d39..589af0b 100644
--- a/stack/avct/avct_lcb_act.c
+++ b/stack/avct/avct_lcb_act.c
@@ -23,7 +23,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "avct_api.h"
@@ -636,7 +636,7 @@
             pkt_type = AVCT_PKT_TYPE_END;
         }
     }
-    AVCT_TRACE_DEBUG ("avct_lcb_send_msg tx_q_count:%d", p_lcb->tx_q.count);
+    AVCT_TRACE_DEBUG ("avct_lcb_send_msg tx_q_count:%d", GKI_queue_length(&p_lcb->tx_q));
     return;
 }
 
@@ -692,6 +692,7 @@
 
     /* parse header byte */
     AVCT_PRS_HDR(p, label, type, cr_ipid);
+    UNUSED(type);
 
     /* check for invalid cr_ipid */
     if (cr_ipid == AVCT_CR_IPID_INVALID)
diff --git a/stack/avdt/avdt_ad.c b/stack/avdt/avdt_ad.c
index 4686887..45e6b36 100644
--- a/stack/avdt/avdt_ad.c
+++ b/stack/avdt/avdt_ad.c
@@ -22,8 +22,10 @@
  *
  ******************************************************************************/
 
+#include <assert.h>
 #include <string.h>
-#include "data_types.h"
+
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "avdt_api.h"
@@ -31,7 +33,6 @@
 #include "avdt_int.h"
 #include "l2c_api.h"
 #include "l2cdefs.h"
-#include "wcassert.h"
 
 
 /*******************************************************************************
@@ -245,7 +246,7 @@
         }
     }
 
-    WC_ASSERT(i != AVDT_NUM_TC_TBL);
+    assert(i != AVDT_NUM_TC_TBL);
 
     return p_tbl;
 }
@@ -276,7 +277,7 @@
     }
 
     /* sanity check */
-    WC_ASSERT(i != AVDT_NUM_TC_TBL);
+    assert(i != AVDT_NUM_TC_TBL);
 
     /* initialize entry */
     p_tbl->peer_mtu = L2CAP_DEFAULT_MTU;
diff --git a/stack/avdt/avdt_api.c b/stack/avdt/avdt_api.c
index f18c556..96bff75 100644
--- a/stack/avdt/avdt_api.c
+++ b/stack/avdt/avdt_api.c
@@ -24,7 +24,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "avdt_api.h"
 #include "avdtc_api.h"
@@ -34,10 +34,6 @@
 #include "btu.h"
 
 
-#if (defined BTTRC_INCLUDED && BTTRC_INCLUDED == TRUE)
-#include "bttrc_str_ids.h"
-#endif
-
 /* Control block for AVDT */
 #if AVDT_DYNAMIC_MEMORY == FALSE
 tAVDT_CB avdt_cb;
@@ -112,9 +108,6 @@
 *******************************************************************************/
 void AVDT_Register(tAVDT_REG *p_reg, tAVDT_CTRL_CBACK *p_cback)
 {
-
-    BTTRC_AVDT_API0(AVDT_TRACE_API_REGISTER);
-
     /* register PSM with L2CAP */
     L2CA_Register(AVDT_PSM, (tL2CAP_APPL_INFO *) &avdt_l2c_appl);
 
@@ -142,11 +135,6 @@
     avdt_scb_init();
     avdt_ccb_init();
     avdt_ad_init();
-#if defined(AVDT_INITIAL_TRACE_LEVEL)
-    avdt_cb.trace_level = AVDT_INITIAL_TRACE_LEVEL;
-#else
-    avdt_cb.trace_level = BT_TRACE_LEVEL_NONE;
-#endif
 
     /* copy registration struct */
     memcpy(&avdt_cb.rcb, p_reg, sizeof(tAVDT_REG));
@@ -168,8 +156,6 @@
 *******************************************************************************/
 void AVDT_Deregister(void)
 {
-    BTTRC_AVDT_API0(AVDT_TRACE_API_DEREGISTER);
-
     /* deregister PSM with L2CAP */
     L2CA_Deregister(AVDT_PSM);
 }
@@ -255,8 +241,6 @@
     UINT16      result = AVDT_SUCCESS;
     tAVDT_SCB   *p_scb;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_CREATESTREAM);
-
     /* Verify parameters; if invalid, return failure */
     if (((p_cs->cfg.psc_mask & (~AVDT_PSC)) != 0) || (p_cs->p_ctrl_cback == NULL))
     {
@@ -293,9 +277,6 @@
     UINT16      result = AVDT_SUCCESS;
     tAVDT_SCB   *p_scb;
 
-
-    BTTRC_AVDT_API0(AVDT_TRACE_API_REMOVESTREAM);
-
     /* look up scb */
     if ((p_scb = avdt_scb_by_hdl(handle)) == NULL)
     {
@@ -342,8 +323,6 @@
     UINT16          result = AVDT_SUCCESS;
     tAVDT_CCB_EVT   evt;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_DISCOVER_REQ);
-
     /* find channel control block for this bd addr; if none, allocate one */
     if ((p_ccb = avdt_ccb_by_bd(bd_addr)) == NULL)
     {
@@ -448,8 +427,6 @@
 {
     tAVDT_CCB_API_GETCAP    getcap;
 
-    BTTRC_AVDT_API1(AVDT_TRACE_API_GETCAP_REQ, BTTRC_PARAM_UINT8, seid);
-
     getcap.single.seid = seid;
     getcap.single.sig_id = AVDT_SIG_GETCAP;
     getcap.p_cfg = p_cfg;
@@ -485,8 +462,6 @@
 {
     tAVDT_CCB_API_GETCAP    getcap;
 
-    BTTRC_AVDT_API1(AVDT_TRACE_API_GET_ALLCAP_REQ, BTTRC_PARAM_UINT8, seid);
-
     getcap.single.seid = seid;
     getcap.single.sig_id = AVDT_SIG_GET_ALLCAP;
     getcap.p_cfg = p_cfg;
@@ -511,8 +486,6 @@
     UINT16          result = AVDT_SUCCESS;
     tAVDT_SCB_EVT   evt;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_DELAY_REPORT);
-
     /* map handle to scb */
     if ((p_scb = avdt_scb_by_hdl(handle)) == NULL)
     {
@@ -549,9 +522,6 @@
     UINT16          result = AVDT_SUCCESS;
     tAVDT_SCB_EVT   evt;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_OPEN_REQ);
-
-
     /* verify SEID */
     if ((seid < AVDT_SEID_MIN) || (seid > AVDT_SEID_MAX))
     {
@@ -603,8 +573,6 @@
     UINT16          result = AVDT_SUCCESS;
     UINT8           event_code;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_CONFIG_RSP);
-
     /* map handle to scb */
     if ((p_scb = avdt_scb_by_hdl(handle)) == NULL)
     {
@@ -658,8 +626,6 @@
     UINT16          result = AVDT_SUCCESS;
     int             i;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_START_REQ);
-
     if ((num_handles == 0) || (num_handles > AVDT_NUM_SEPS))
     {
         result = AVDT_BAD_PARAMS;
@@ -716,8 +682,6 @@
     UINT16          result = AVDT_SUCCESS;
     int             i;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_SUSPEND_REQ);
-
     if ((num_handles == 0) || (num_handles > AVDT_NUM_SEPS))
     {
         result = AVDT_BAD_PARAMS;
@@ -772,8 +736,6 @@
     tAVDT_SCB       *p_scb;
     UINT16          result = AVDT_SUCCESS;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_CLOSE_REQ);
-
     /* map handle to scb */
     if ((p_scb = avdt_scb_by_hdl(handle)) == NULL)
     {
@@ -810,8 +772,6 @@
     UINT16          result = AVDT_SUCCESS;
     tAVDT_SCB_EVT   evt;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_RECONFIG_REQ);
-
     /* map handle to scb */
     if ((p_scb = avdt_scb_by_hdl(handle)) == NULL)
     {
@@ -847,8 +807,6 @@
     tAVDT_SCB_EVT   evt;
     UINT16          result = AVDT_SUCCESS;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_RECONFIG_RSP);
-
     /* map handle to scb */
     if ((p_scb = avdt_scb_by_hdl(handle)) == NULL)
     {
@@ -886,8 +844,6 @@
     UINT16          result = AVDT_SUCCESS;
     tAVDT_SCB_EVT   evt;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_SECURITY_REQ);
-
     /* map handle to scb */
     if ((p_scb = avdt_scb_by_hdl(handle)) == NULL)
     {
@@ -924,8 +880,6 @@
     UINT16          result = AVDT_SUCCESS;
     tAVDT_SCB_EVT   evt;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_SECURITY_RSP);
-
     /* map handle to scb */
     if ((p_scb = avdt_scb_by_hdl(handle)) == NULL)
     {
@@ -985,8 +939,6 @@
     tAVDT_SCB_EVT   evt;
     UINT16          result = AVDT_SUCCESS;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_WRITE_REQ);
-
     /* map handle to scb */
     if ((p_scb = avdt_scb_by_hdl(handle)) == NULL)
     {
@@ -1066,8 +1018,6 @@
     UINT16          result = AVDT_SUCCESS;
     tAVDT_CCB_EVT   evt;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_CONNECT_REQ);
-
     /* find channel control block for this bd addr; if none, allocate one */
     if ((p_ccb = avdt_ccb_by_bd(bd_addr)) == NULL)
     {
@@ -1113,9 +1063,6 @@
     UINT16          result = AVDT_SUCCESS;
     tAVDT_CCB_EVT   evt;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_DISCONNECT_REQ);
-
-
     /* find channel control block for this bd addr; if none, error */
     if ((p_ccb = avdt_ccb_by_bd(bd_addr)) == NULL)
     {
@@ -1157,8 +1104,6 @@
         lcid = avdt_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][tcid].lcid;
     }
 
-    BTTRC_AVDT_API1(AVDT_TRACE_API_GET_L2CAP_CHAN, BTTRC_PARAM_UINT16, lcid);
-
     return (lcid);
 }
 
@@ -1189,8 +1134,6 @@
         lcid = avdt_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][tcid].lcid;
     }
 
-    BTTRC_AVDT_API1(AVDT_TRACE_API_GET_SIGNAL_CHAN, BTTRC_PARAM_UINT16, lcid);
-
     return (lcid);
 }
 
@@ -1216,16 +1159,14 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_WriteDataReq(UINT8 handle, UINT8 *p_data, UINT32 data_len,
-                                     UINT32 time_stamp, UINT8 m_pt, UINT8 marker)
+extern UINT16 AVDT_WriteDataReq(UINT8 handle, UINT8 *p_data, UINT32 data_len,
+                                UINT32 time_stamp, UINT8 m_pt, UINT8 marker)
 {
 
     tAVDT_SCB       *p_scb;
     tAVDT_SCB_EVT   evt;
     UINT16          result = AVDT_SUCCESS;
 
-    BTTRC_AVDT_API1(AVDT_TRACE_API_WRITE_DATA_REQ, BTTRC_PARAM_UINT32, data_len);
-
     do
     {
         /* check length of media frame */
@@ -1304,13 +1245,11 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_SetMediaBuf(UINT8 handle, UINT8 *p_buf, UINT32 buf_len)
+extern UINT16 AVDT_SetMediaBuf(UINT8 handle, UINT8 *p_buf, UINT32 buf_len)
 {
     tAVDT_SCB       *p_scb;
     UINT16          result = AVDT_SUCCESS;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_SET_MEDIABUF);
-
     /* map handle to scb */
     if ((p_scb = avdt_scb_by_hdl(handle)) == NULL)
     {
@@ -1357,8 +1296,6 @@
     UINT32  ssrc;
     UINT16  len;
 
-    BTTRC_AVDT_API0(AVDT_TRACE_API_SEND_REPORT);
-
     /* map handle to scb && verify parameters */
     if (((p_scb = avdt_scb_by_hdl(handle)) != NULL)
      && (p_scb->p_ccb != NULL)
@@ -1484,4 +1421,3 @@
 
     return (avdt_cb.trace_level);
 }
-
diff --git a/stack/avdt/avdt_ccb.c b/stack/avdt/avdt_ccb.c
index 2a10ef8..09ed39a 100644
--- a/stack/avdt/avdt_ccb.c
+++ b/stack/avdt/avdt_ccb.c
@@ -24,7 +24,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "avdt_api.h"
@@ -304,14 +304,12 @@
 #if AVDT_DEBUG == TRUE
     AVDT_TRACE_EVENT("CCB ccb=%d event=%s state=%s", avdt_ccb_to_idx(p_ccb), avdt_ccb_evt_str[event], avdt_ccb_st_str[p_ccb->state]);
 #endif
-    BTTRC_AVDT_CCB_EVENT(event, p_ccb->state);
 
     /* look up the state table for the current state */
     state_table = avdt_ccb_st_tbl[p_ccb->state];
 
     /* set next state */
     if (p_ccb->state != state_table[event][AVDT_CCB_NEXT_STATE]) {
-        BTTRC_AVDT_CCB_STATE(state_table[event][AVDT_CCB_NEXT_STATE]);
         p_ccb->state = state_table[event][AVDT_CCB_NEXT_STATE];
     }
 
@@ -320,7 +318,6 @@
     {
         if ((action = state_table[event][i]) != AVDT_CCB_IGNORE)
         {
-            BTTRC_AVDT_CCB_ACTION(action);
             (*avdt_cb.p_ccb_act[action])(p_ccb, p_data);
         }
         else
diff --git a/stack/avdt/avdt_ccb_act.c b/stack/avdt/avdt_ccb_act.c
index d87dbb1..b1ef12e 100644
--- a/stack/avdt/avdt_ccb_act.c
+++ b/stack/avdt/avdt_ccb_act.c
@@ -24,7 +24,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "avdt_api.h"
diff --git a/stack/avdt/avdt_int.h b/stack/avdt/avdt_int.h
index e9752c2..fb1b313 100644
--- a/stack/avdt/avdt_int.h
+++ b/stack/avdt/avdt_int.h
@@ -32,12 +32,8 @@
 #include "btm_api.h"
 
 #ifndef AVDT_DEBUG
-#if (!defined BTTRC_INCLUDED || BTTRC_INCLUDED == FALSE)
-#define AVDT_DEBUG  TRUE
-#else
 #define AVDT_DEBUG  FALSE
 #endif
-#endif
 
 /*****************************************************************************
 ** constants
@@ -727,9 +723,9 @@
 ** Main Control Block
 *******************************************************************************/
 #if AVDT_DYNAMIC_MEMORY == FALSE
-AVDT_API extern tAVDT_CB  avdt_cb;
+extern tAVDT_CB  avdt_cb;
 #else
-AVDT_API extern tAVDT_CB *avdt_cb_ptr;
+extern tAVDT_CB *avdt_cb_ptr;
 #define avdt_cb (*avdt_cb_ptr)
 #endif
 
diff --git a/stack/avdt/avdt_l2c.c b/stack/avdt/avdt_l2c.c
index c13b5b4..dbdfc08 100644
--- a/stack/avdt/avdt_l2c.c
+++ b/stack/avdt/avdt_l2c.c
@@ -23,7 +23,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "avdt_api.h"
@@ -356,6 +356,8 @@
     /* look up info for this channel */
     if ((p_tbl = avdt_ad_tc_tbl_by_lcid(lcid)) != NULL)
     {
+        p_tbl->lcid = lcid;
+
         /* if in correct state */
         if (p_tbl->state == AVDT_AD_ST_CFG)
         {
diff --git a/stack/avdt/avdt_msg.c b/stack/avdt/avdt_msg.c
index 2f38c3a..4a28b0d 100644
--- a/stack/avdt/avdt_msg.c
+++ b/stack/avdt/avdt_msg.c
@@ -27,7 +27,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "avdt_api.h"
@@ -1719,6 +1719,8 @@
     /* parse the message header */
     AVDT_MSG_PRS_HDR(p, label, pkt_type, msg_type);
 
+    UNUSED(pkt_type);
+
     /* AVDT_TRACE_DEBUG("msg_type=%d", msg_type); */
     /* set up label and ccb_idx in message hdr */
     msg.hdr.label = label;
diff --git a/stack/avdt/avdt_scb.c b/stack/avdt/avdt_scb.c
index 8eb5cc2..f5f5b5a 100644
--- a/stack/avdt/avdt_scb.c
+++ b/stack/avdt/avdt_scb.c
@@ -24,7 +24,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "avdt_api.h"
@@ -531,8 +531,6 @@
 #if AVDT_DEBUG == TRUE
     AVDT_TRACE_EVENT("SCB hdl=%d event=%d/%s state=%s", avdt_scb_to_hdl(p_scb), event, avdt_scb_evt_str[event], avdt_scb_st_str[p_scb->state]);
 #endif
-    BTTRC_AVDT_SCB_EVENT(event, p_scb->state);
-
     /* set current event */
     p_scb->curr_evt = event;
 
@@ -541,7 +539,6 @@
 
     /* set next state */
     if (p_scb->state != state_table[event][AVDT_SCB_NEXT_STATE]) {
-        BTTRC_AVDT_SCB_STATE(state_table[event][AVDT_SCB_NEXT_STATE]);
         p_scb->state = state_table[event][AVDT_SCB_NEXT_STATE];
     }
 
@@ -550,7 +547,6 @@
     {
         if ((action = state_table[event][i]) != AVDT_SCB_IGNORE)
         {
-            BTTRC_AVDT_SCB_ACTION(action);
             (*avdt_cb.p_scb_act[action])(p_scb, p_data);
         }
         else
@@ -734,41 +730,36 @@
     int         i;
     tAVDT_SCB   *p_scb;
     UINT8       nsc_mask;
-    UINT8       chk_state;
     UINT8       ret = 0;
 
     AVDT_TRACE_DEBUG("avdt_scb_verify state %d", state);
     /* set nonsupported command mask */
     /* translate public state into private state */
     nsc_mask = 0;
-    chk_state = AVDT_SCB_STREAM_ST;
-    switch(state)
-    {
-    case AVDT_VERIFY_SUSPEND:
-        nsc_mask = AVDT_NSC_SUSPEND;
-        break;
-    case AVDT_VERIFY_OPEN:
-    case AVDT_VERIFY_START:
-        chk_state = AVDT_SCB_OPEN_ST;
-        break;
-    }
+    if (state == AVDT_VERIFY_SUSPEND)
+      nsc_mask = AVDT_NSC_SUSPEND;
 
     /* verify every scb */
-    for (i = 0; i < num_seid; i++)
+    for (i = 0, *p_err_code = 0; i < num_seid && *p_err_code == 0; i++)
     {
         if ((p_scb = avdt_scb_by_hdl(p_seid[i])) == NULL)
-        {
             *p_err_code = AVDT_ERR_BAD_STATE;
-            break;
-        }
-        else if ((p_scb->state != chk_state) || (p_scb->p_ccb != p_ccb))
-        {
+        else if (p_scb->p_ccb != p_ccb)
             *p_err_code = AVDT_ERR_BAD_STATE;
-            break;
-        }
         else if (p_scb->cs.nsc_mask & nsc_mask)
-        {
             *p_err_code = AVDT_ERR_NSC;
+
+        switch (state) {
+          case AVDT_VERIFY_OPEN:
+          case AVDT_VERIFY_START:
+            if (p_scb->state != AVDT_SCB_OPEN_ST && p_scb->state != AVDT_SCB_STREAM_ST)
+              *p_err_code = AVDT_ERR_BAD_STATE;
+            break;
+
+          case AVDT_VERIFY_SUSPEND:
+          case AVDT_VERIFY_STREAMING:
+            if (p_scb->state != AVDT_SCB_STREAM_ST)
+              *p_err_code = AVDT_ERR_BAD_STATE;
             break;
         }
     }
@@ -777,8 +768,7 @@
     {
         ret = p_seid[i];
     }
-    AVDT_TRACE_DEBUG("avdt_scb_verify state %d, nsc_mask0x%x, ret: %d",
-        chk_state, nsc_mask, ret);
+
     return ret;
 }
 
diff --git a/stack/avdt/avdt_scb_act.c b/stack/avdt/avdt_scb_act.c
index 72dd3cd..3ab1c26 100644
--- a/stack/avdt/avdt_scb_act.c
+++ b/stack/avdt/avdt_scb_act.c
@@ -24,7 +24,7 @@
  ******************************************************************************/
 
 #include <string.h>
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "avdt_api.h"
@@ -247,7 +247,6 @@
     UINT8   marker;
     UINT16  seq;
     UINT32  time_stamp;
-    UINT32  ssrc;
     UINT16  offset;
     UINT16  ex_len;
     UINT8   pad_len = 0;
@@ -259,7 +258,9 @@
     AVDT_MSG_PRS_M_PT(p, m_pt, marker);
     BE_STREAM_TO_UINT16(seq, p);
     BE_STREAM_TO_UINT32(time_stamp, p);
-    BE_STREAM_TO_UINT32(ssrc, p);
+    p += 4;
+
+    UNUSED(o_v);
 
     /* skip over any csrc's in packet */
     p += o_cc * 4;
@@ -336,7 +337,6 @@
     UINT8   *p_start = p;
     UINT32  ssrc;
     UINT8   o_v, o_p, o_cc;
-    UINT16  pkt_len;
     AVDT_REPORT_TYPE    pt;
     tAVDT_REPORT_DATA   report, *p_rpt;
 
@@ -347,9 +347,12 @@
         /* parse report packet header */
         AVDT_MSG_PRS_RPT_OCTET1(p, o_v, o_p, o_cc);
         pt = *p++;
-        BE_STREAM_TO_UINT16(pkt_len, p);
+        p += 2;
         BE_STREAM_TO_UINT32(ssrc, p);
 
+        UNUSED(o_p);
+        UNUSED(o_v);
+
         switch(pt)
         {
         case AVDT_RTCP_PT_SR:   /* the packet type - SR (Sender Report) */
@@ -573,6 +576,9 @@
             BE_STREAM_TO_UINT32(time_stamp, p_payload);
             BE_STREAM_TO_UINT32(ssrc, p_payload);
 
+            UNUSED(o_v);
+            UNUSED(ssrc);
+
             /* skip over any csrc's in packet */
             p_payload += o_cc * 4;
 
@@ -1421,7 +1427,7 @@
     BT_HDR          *p_frag;
 
     AVDT_TRACE_WARNING("avdt_scb_snd_stream_close c:%d, off:%d",
-        p_scb->frag_q.count, p_scb->frag_off);
+        GKI_queue_length(&p_scb->frag_q), p_scb->frag_off);
     /* clean fragments queue */
     while((p_frag = (BT_HDR*)GKI_dequeue (&p_scb->frag_q)) != NULL)
          GKI_freebuf(p_frag);
diff --git a/stack/avrc/avrc_api.c b/stack/avrc/avrc_api.c
index 04f59a0..dbebb99 100644
--- a/stack/avrc/avrc_api.c
+++ b/stack/avrc/avrc_api.c
@@ -21,12 +21,12 @@
  *  Interface to AVRCP mandatory commands
  *
  ******************************************************************************/
+#include <assert.h>
 #include <string.h>
 
 #include "gki.h"
 #include "avrc_api.h"
 #include "avrc_int.h"
-#include "wcassert.h"
 
 /*****************************************************************************
 **  Global data
@@ -805,8 +805,8 @@
     BT_HDR  *p_cmd = NULL;
     UINT8   *p_data;
 
-    WC_ASSERT(p_msg != NULL);
-    WC_ASSERT(AVRC_CMD_POOL_SIZE > (AVRC_MIN_CMD_LEN+p_msg->pass_len));
+    assert(p_msg != NULL);
+    assert(AVRC_CMD_POOL_SIZE > (AVRC_MIN_CMD_LEN+p_msg->pass_len));
 
     if ((p_cmd = (BT_HDR *) GKI_getpoolbuf(AVRC_CMD_POOL_ID)) != NULL)
     {
@@ -1084,7 +1084,7 @@
 UINT16 AVRC_PassCmd(UINT8 handle, UINT8 label, tAVRC_MSG_PASS *p_msg)
 {
     BT_HDR *p_buf;
-    WC_ASSERT(p_msg != NULL);
+    assert(p_msg != NULL);
     if (p_msg)
     {
         p_msg->hdr.ctype    = AVRC_CMD_CTRL;
@@ -1123,7 +1123,7 @@
 UINT16 AVRC_PassRsp(UINT8 handle, UINT8 label, tAVRC_MSG_PASS *p_msg)
 {
     BT_HDR *p_buf;
-    WC_ASSERT(p_msg != NULL);
+    assert(p_msg != NULL);
     if (p_msg)
     {
         p_buf = avrc_pass_msg(p_msg);
diff --git a/stack/avrc/avrc_int.h b/stack/avrc/avrc_int.h
index 33eebdc..36bb0c5 100644
--- a/stack/avrc/avrc_int.h
+++ b/stack/avrc/avrc_int.h
@@ -138,9 +138,9 @@
 ** Main Control Block
 *******************************************************************************/
 #if AVRC_DYNAMIC_MEMORY == FALSE
-AVRC_API extern tAVRC_CB  avrc_cb;
+extern tAVRC_CB  avrc_cb;
 #else
-AVRC_API extern tAVRC_CB *avrc_cb_ptr;
+extern tAVRC_CB *avrc_cb_ptr;
 #define avrc_cb (*avrc_cb_ptr)
 #endif
 
@@ -156,4 +156,3 @@
 #endif
 
 #endif /* AVRC_INT_H */
-
diff --git a/stack/avrc/avrc_opt.c b/stack/avrc/avrc_opt.c
index ff79155..28a3f1a 100644
--- a/stack/avrc/avrc_opt.c
+++ b/stack/avrc/avrc_opt.c
@@ -21,15 +21,13 @@
  *  Interface to AVRCP optional commands
  *
  ******************************************************************************/
+#include <assert.h>
 #include <string.h>
 
 #include "gki.h"
 #include "avrc_api.h"
 #include "avrc_int.h"
 
-#include "wcassert.h"
-
-
 /******************************************************************************
 **
 ** Function         avrc_vendor_msg
@@ -51,13 +49,13 @@
     BT_HDR  *p_cmd;
     UINT8   *p_data;
 
-    WC_ASSERT(p_msg != NULL);
+    assert(p_msg != NULL);
 
 #if AVRC_METADATA_INCLUDED == TRUE
-    WC_ASSERT(AVRC_META_CMD_POOL_SIZE > (AVRC_MIN_CMD_LEN+p_msg->vendor_len));
+    assert(AVRC_META_CMD_POOL_SIZE > (AVRC_MIN_CMD_LEN+p_msg->vendor_len));
     if ((p_cmd = (BT_HDR *) GKI_getpoolbuf(AVRC_META_CMD_POOL_ID)) != NULL)
 #else
-    WC_ASSERT(AVRC_CMD_POOL_SIZE > (AVRC_MIN_CMD_LEN+p_msg->vendor_len));
+    assert(AVRC_CMD_POOL_SIZE > (AVRC_MIN_CMD_LEN+p_msg->vendor_len));
     if ((p_cmd = (BT_HDR *) GKI_getpoolbuf(AVRC_CMD_POOL_ID)) != NULL)
 #endif
     {
diff --git a/stack/bnep/bnep_api.c b/stack/bnep/bnep_api.c
index b1d8c7c..76bffca 100644
--- a/stack/bnep/bnep_api.c
+++ b/stack/bnep/bnep_api.c
@@ -83,7 +83,6 @@
         return BNEP_SECURITY_FAIL;
 
     bnep_cb.profile_registered  = TRUE;
-    BTM_GetLocalDeviceAddr (bnep_cb.my_bda);
     return BNEP_SUCCESS;
 }
 
@@ -151,11 +150,6 @@
     if (src_uuid->len != dst_uuid->len)
         return BNEP_CONN_FAILED_UUID_SIZE;
 
-#if (!defined (BNEP_SUPPORTS_ALL_UUID_LENGTHS) || BNEP_SUPPORTS_ALL_UUID_LENGTHS == FALSE)
-    if (src_uuid->len != 2)
-        return BNEP_CONN_FAILED_UUID_SIZE;
-#endif
-
     if (!p_bcb)
     {
         if ((p_bcb = bnepu_allocate_bcb (p_rem_bda)) == NULL)
@@ -432,7 +426,7 @@
     }
 
     /* Check transmit queue */
-    if (p_bcb->xmit_q.count >= BNEP_MAX_XMITQ_DEPTH)
+    if (GKI_queue_length(&p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH)
     {
         GKI_freebuf (p_buf);
         return (BNEP_Q_SIZE_EXCEEDED);
@@ -538,7 +532,7 @@
     }
 
     /* Check transmit queue */
-    if (p_bcb->xmit_q.count >= BNEP_MAX_XMITQ_DEPTH)
+    if (GKI_queue_length(&p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH)
         return (BNEP_Q_SIZE_EXCEEDED);
 
     /* Get a buffer to copy teh data into */
@@ -586,7 +580,6 @@
                                       UINT16 *p_start_array,
                                       UINT16 *p_end_array)
 {
-#if (defined (BNEP_SUPPORTS_PROT_FILTERS) && BNEP_SUPPORTS_PROT_FILTERS == TRUE)
     UINT16          xx;
     tBNEP_CONN     *p_bcb;
 
@@ -619,9 +612,6 @@
     bnepu_send_peer_our_filters (p_bcb);
 
     return (BNEP_SUCCESS);
-#else
-    return (BNEP_SET_FILTER_FAIL);
-#endif
 }
 
 
@@ -649,7 +639,6 @@
                                        UINT8 *p_start_array,
                                        UINT8 *p_end_array)
 {
-#if (defined (BNEP_SUPPORTS_MULTI_FILTERS) && BNEP_SUPPORTS_MULTI_FILTERS == TRUE)
     UINT16          xx;
     tBNEP_CONN     *p_bcb;
 
@@ -685,28 +674,6 @@
     bnepu_send_peer_our_multi_filters (p_bcb);
 
     return (BNEP_SUCCESS);
-#else
-    return (BNEP_SET_FILTER_FAIL);
-#endif
-}
-
-
-/*******************************************************************************
-**
-** Function         BNEP_GetMyBdAddr
-**
-** Description      This function returns a pointer to the local device BD address.
-**                  If the BD address has not been read yet, it returns NULL.
-**
-** Returns          the BD address
-**
-*******************************************************************************/
-UINT8 *BNEP_GetMyBdAddr (void)
-{
-    if (bnep_cb.got_my_bd_addr)
-        return (bnep_cb.my_bda);
-    else
-        return (NULL);
 }
 
 /*******************************************************************************
@@ -762,7 +729,7 @@
     p_status->con_status            = BNEP_STATUS_CONNECTED;
     p_status->l2cap_cid             = p_bcb->l2cap_cid;
     p_status->rem_mtu_size          = p_bcb->rem_mtu_size;
-    p_status->xmit_q_depth          = p_bcb->xmit_q.count;
+    p_status->xmit_q_depth          = GKI_queue_length(&p_bcb->xmit_q);
     p_status->sent_num_filters      = p_bcb->sent_num_filters;
     p_status->sent_mcast_filters    = p_bcb->sent_mcast_filters;
     p_status->rcvd_num_filters      = p_bcb->rcvd_num_filters;
diff --git a/stack/bnep/bnep_int.h b/stack/bnep/bnep_int.h
index 0c435ef..5322e50 100644
--- a/stack/bnep/bnep_int.h
+++ b/stack/bnep/bnep_int.h
@@ -183,8 +183,6 @@
     TIMER_LIST_ENT          bnep_tle;
     BOOLEAN                 profile_registered;             /* TRUE when we got our BD addr */
     UINT8                   trace_level;
-    BOOLEAN                 got_my_bd_addr;         /* TRUE when we got our BD addr */
-    BD_ADDR                 my_bda;                 /* BD Address of this device    */
 
 } tBNEP_CB;
 
@@ -195,9 +193,9 @@
 /* Global BNEP data
 */
 #if BNEP_DYNAMIC_MEMORY == FALSE
-BNEP_API extern tBNEP_CB  bnep_cb;
+extern tBNEP_CB  bnep_cb;
 #else
-BNEP_API extern tBNEP_CB  *bnep_cb_ptr;
+extern tBNEP_CB  *bnep_cb_ptr;
 #define bnep_cb (*bnep_cb_ptr)
 #endif
 
@@ -241,7 +239,6 @@
 extern tBNEP_RESULT bnep_is_packet_allowed (tBNEP_CONN *p_bcb, BD_ADDR p_dest_addr, UINT16 protocol,
                                                     BOOLEAN fw_ext_present, UINT8 *p_data);
 extern UINT32      bnep_get_uuid32 (tBT_UUID *src_uuid);
-extern void        bnep_dump_status (void);
 
 
 
@@ -251,4 +248,3 @@
 
 
 #endif
-
diff --git a/stack/bnep/bnep_main.c b/stack/bnep/bnep_main.c
index 62fa316..b298840 100644
--- a/stack/bnep/bnep_main.c
+++ b/stack/bnep/bnep_main.c
@@ -43,6 +43,8 @@
 #include "bnep_int.h"
 #include "bt_utils.h"
 
+#include "device/include/controller.h"
+
 
 /********************************************************************************/
 /*                       G L O B A L    B N E P       D A T A                   */
@@ -65,8 +67,6 @@
 static void bnep_data_ind (UINT16 l2cap_cid, BT_HDR *p_msg);
 static void bnep_congestion_ind (UINT16 lcid, BOOLEAN is_congested);
 
-static void bnep_read_addr_cb (void *p_bda);
-
 
 /*******************************************************************************
 **
@@ -508,12 +508,11 @@
             ** with unknown control extension headers then those should be processed
             ** according to complain/ignore law
             */
-            UINT8       ext, length, *p_data;
+            UINT8       ext, length;
             UINT16      org_len, new_len;
             /* parse the extension headers and process unknown control headers */
             org_len = rem_len;
             new_len = 0;
-            p_data  = p;
             do {
 
                 ext     = *p++;
@@ -639,7 +638,7 @@
         p_src_addr = (UINT8 *) p_bcb->rem_bda;
 
     if (!p_dst_addr)
-        p_dst_addr = (UINT8 *) bnep_cb.my_bda;
+        p_dst_addr = (UINT8 *) controller_get_interface()->get_address();
 
     /* check whether there are any extensions to be forwarded */
     if (ext_type)
@@ -677,13 +676,6 @@
 
     if (!p_tle->param)
     {
-        if (!bnep_cb.got_my_bd_addr)
-        {
-            if (BTM_IsDeviceUp())
-                BTM_ReadLocalDeviceAddr (bnep_read_addr_cb);
-
-            btu_start_timer (&bnep_cb.bnep_tle, BTU_TTYPE_BNEP, 2);
-        }
         return;
     }
 
@@ -734,7 +726,6 @@
 
         bnepu_release_bcb (p_bcb);
     }
-#if (defined (BNEP_SUPPORTS_PROT_FILTERS) && BNEP_SUPPORTS_PROT_FILTERS == TRUE)
     else if (p_bcb->con_flags & BNEP_FLAGS_FILTER_RESP_PEND)
     {
         if (p_bcb->re_transmits++ != BNEP_MAX_RETRANSMITS)
@@ -754,8 +745,6 @@
             return;
         }
     }
-#endif
-#if (defined (BNEP_SUPPORTS_MULTI_FILTERS) && BNEP_SUPPORTS_MULTI_FILTERS == TRUE)
     else if (p_bcb->con_flags & BNEP_FLAGS_MULTI_RESP_PEND)
     {
         if (p_bcb->re_transmits++ != BNEP_MAX_RETRANSMITS)
@@ -775,7 +764,6 @@
             return;
         }
     }
-#endif
 }
 
 
@@ -810,31 +798,3 @@
     if (bnep_cb.p_conn_state_cb)
         (*bnep_cb.p_conn_state_cb) (p_bcb->handle, p_bcb->rem_bda, BNEP_SUCCESS, is_role_change);
 }
-
-
-/*******************************************************************************
-**
-** Function         bnep_read_addr_cb
-**
-** Description      This function is called by BTM when the local BD address
-**                  is read. It saves the BD address, and flags it as read.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void bnep_read_addr_cb (void *p_bda)
-{
-    UINT8 *bda = (UINT8 *)p_bda;
-    if (p_bda &&
-            (bda[0] | bda[1] | bda[2] | bda[3] | bda[4] | bda[5]) != 0)
-    {
-        /* Save my BD address */
-        memcpy (bnep_cb.my_bda, p_bda, BD_ADDR_LEN);
-
-        bnep_cb.got_my_bd_addr = TRUE;
-    }
-    else
-        /* Retry after a couple seconds */
-        btu_start_timer (&bnep_cb.bnep_tle, BTU_TTYPE_BNEP, 2);
-}
-
diff --git a/stack/bnep/bnep_utils.c b/stack/bnep/bnep_utils.c
index 92061d0..8c76b00 100644
--- a/stack/bnep/bnep_utils.c
+++ b/stack/bnep/bnep_utils.c
@@ -30,6 +30,7 @@
 #include "btu.h"
 #include "btm_int.h"
 #include "bt_utils.h"
+#include "device/include/controller.h"
 
 
 /********************************************************************************/
@@ -152,7 +153,7 @@
     p_bcb->p_pending_data   = NULL;
 
     /* Free transmit queue */
-    while (p_bcb->xmit_q.count)
+    while (!GKI_queue_is_empty(&p_bcb->xmit_q))
     {
         GKI_freebuf (GKI_dequeue (&p_bcb->xmit_q));
     }
@@ -196,7 +197,6 @@
         UINT16_TO_BE_STREAM (p, p_bcb->dst_uuid.uu.uuid16);
         UINT16_TO_BE_STREAM (p, p_bcb->src_uuid.uu.uuid16);
     }
-#if (defined (BNEP_SUPPORTS_ALL_UUID_LENGTHS) && BNEP_SUPPORTS_ALL_UUID_LENGTHS == TRUE)
     else if (p_bcb->dst_uuid.len == 4)
     {
         UINT32_TO_BE_STREAM (p, p_bcb->dst_uuid.uu.uuid32);
@@ -209,7 +209,6 @@
         memcpy (p, p_bcb->src_uuid.uu.uuid128, p_bcb->dst_uuid.len);
         p += p_bcb->dst_uuid.len;
     }
-#endif
 
     p_buf->len = (UINT16)(p - p_start);
 
@@ -267,7 +266,6 @@
 *******************************************************************************/
 void bnepu_send_peer_our_filters (tBNEP_CONN *p_bcb)
 {
-#if (defined (BNEP_SUPPORTS_PROT_FILTERS) && BNEP_SUPPORTS_PROT_FILTERS == TRUE)
     BT_HDR      *p_buf;
     UINT8       *p;
     UINT16      xx;
@@ -304,7 +302,6 @@
 
     /* Start timer waiting for setup response */
     btu_start_timer (&p_bcb->conn_tle, BTU_TTYPE_BNEP, BNEP_FILTER_SET_TIMEOUT);
-#endif
 }
 
 
@@ -319,7 +316,6 @@
 *******************************************************************************/
 void bnepu_send_peer_our_multi_filters (tBNEP_CONN *p_bcb)
 {
-#if (defined (BNEP_SUPPORTS_MULTI_FILTERS) && BNEP_SUPPORTS_MULTI_FILTERS == TRUE)
     BT_HDR      *p_buf;
     UINT8       *p;
     UINT16      xx;
@@ -358,7 +354,6 @@
 
     /* Start timer waiting for setup response */
     btu_start_timer (&p_bcb->conn_tle, BTU_TTYPE_BNEP, BNEP_FILTER_SET_TIMEOUT);
-#endif
 }
 
 
@@ -455,7 +450,7 @@
     BNEP_TRACE_EVENT ("BNEP - bnepu_check_send_packet for CID: 0x%x", p_bcb->l2cap_cid);
     if (p_bcb->con_flags & BNEP_FLAGS_L2CAP_CONGESTED)
     {
-        if (p_bcb->xmit_q.count >= BNEP_MAX_XMITQ_DEPTH)
+        if (GKI_queue_length(&p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH)
         {
             BNEP_TRACE_EVENT ("BNEP - congested, dropping buf, CID: 0x%x", p_bcb->l2cap_cid);
 
@@ -487,19 +482,20 @@
 void bnepu_build_bnep_hdr (tBNEP_CONN *p_bcb, BT_HDR *p_buf, UINT16 protocol,
                            UINT8 *p_src_addr, UINT8 *p_dest_addr, BOOLEAN fw_ext_present)
 {
+    const controller_t *controller = controller_get_interface();
     UINT8    ext_bit, *p = (UINT8 *)NULL;
     UINT8    type = BNEP_FRAME_COMPRESSED_ETHERNET;
 
     ext_bit = fw_ext_present ? 0x80 : 0x00;
 
-    if ((p_src_addr) && (memcmp (p_src_addr, bnep_cb.my_bda, BD_ADDR_LEN)))
+    if ((p_src_addr) && (memcmp (p_src_addr, &controller->get_address()->address, BD_ADDR_LEN)))
         type = BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY;
 
     if (memcmp (p_dest_addr, p_bcb->rem_bda, BD_ADDR_LEN))
         type = (type == BNEP_FRAME_COMPRESSED_ETHERNET) ? BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY : BNEP_FRAME_GENERAL_ETHERNET;
 
     if (!p_src_addr)
-        p_src_addr = (UINT8 *)bnep_cb.my_bda;
+        p_src_addr = (UINT8 *)controller->get_address();
 
     switch (type)
     {
@@ -635,7 +631,6 @@
             return;
         }
     }
-#if (defined (BNEP_SUPPORTS_ALL_UUID_LENGTHS) && BNEP_SUPPORTS_ALL_UUID_LENGTHS == TRUE)
     else if (p_bcb->dst_uuid.len == 4)
     {
         BE_STREAM_TO_UINT32 (p_bcb->src_uuid.uu.uuid32, p_setup);
@@ -648,7 +643,6 @@
         memcpy (p_bcb->dst_uuid.uu.uuid128, p_setup, p_bcb->dst_uuid.len);
         p_setup += p_bcb->dst_uuid.len;
     }
-#endif
     else
     {
         BNEP_TRACE_ERROR ("BNEP - Bad UID len %d in ConnReq", p_bcb->dst_uuid.len);
@@ -900,7 +894,6 @@
 *******************************************************************************/
 void bnepu_process_peer_filter_set (tBNEP_CONN *p_bcb, UINT8 *p_filters, UINT16 len)
 {
-#if (defined (BNEP_SUPPORTS_PROT_FILTERS) && BNEP_SUPPORTS_PROT_FILTERS == TRUE)
     UINT16      num_filters = 0;
     UINT16      xx, resp_code = BNEP_FILTER_CRL_OK;
     UINT16      start, end;
@@ -964,9 +957,6 @@
     }
 
     bnepu_send_peer_filter_rsp (p_bcb, resp_code);
-#else
-    bnepu_send_peer_filter_rsp (p_bcb, BNEP_FILTER_CRL_UNSUPPORTED);
-#endif
 }
 
 
@@ -982,7 +972,6 @@
 *******************************************************************************/
 void bnepu_process_peer_filter_rsp (tBNEP_CONN *p_bcb, UINT8 *p_data)
 {
-#if (defined (BNEP_SUPPORTS_PROT_FILTERS) && BNEP_SUPPORTS_PROT_FILTERS == TRUE)
     UINT16          resp_code;
     tBNEP_RESULT    result;
 
@@ -1015,13 +1004,8 @@
 
     if (bnep_cb.p_filter_ind_cb)
         (*bnep_cb.p_filter_ind_cb) (p_bcb->handle, FALSE, result, 0, NULL);
-
-    return;
-#endif
 }
 
-
-
 /*******************************************************************************
 **
 ** Function         bnepu_process_multicast_filter_rsp
@@ -1034,7 +1018,6 @@
 *******************************************************************************/
 void bnepu_process_multicast_filter_rsp (tBNEP_CONN *p_bcb, UINT8 *p_data)
 {
-#if (defined (BNEP_SUPPORTS_MULTI_FILTERS) && BNEP_SUPPORTS_MULTI_FILTERS == TRUE)
     UINT16          resp_code;
     tBNEP_RESULT    result;
 
@@ -1067,13 +1050,8 @@
 
     if (bnep_cb.p_mfilter_ind_cb)
         (*bnep_cb.p_mfilter_ind_cb) (p_bcb->handle, FALSE, result, 0, NULL);
-
-    return;
-#endif
 }
 
-
-
 /*******************************************************************************
 **
 ** Function         bnepu_process_peer_multicast_filter_set
@@ -1087,7 +1065,6 @@
 *******************************************************************************/
 void bnepu_process_peer_multicast_filter_set (tBNEP_CONN *p_bcb, UINT8 *p_filters, UINT16 len)
 {
-#if (defined (BNEP_SUPPORTS_MULTI_FILTERS) && BNEP_SUPPORTS_MULTI_FILTERS == TRUE)
     UINT16          resp_code = BNEP_FILTER_CRL_OK;
     UINT16          num_filters, xx;
     UINT8           *p_temp_filters, null_bda[BD_ADDR_LEN] = {0,0,0,0,0,0};
@@ -1154,9 +1131,6 @@
 
     if (bnep_cb.p_mfilter_ind_cb)
         (*bnep_cb.p_mfilter_ind_cb) (p_bcb->handle, TRUE, 0, len, p_filters);
-#else
-    bnepu_send_peer_multicast_filter_rsp (p_bcb, BNEP_FILTER_CRL_UNSUPPORTED);
-#endif
 }
 
 
@@ -1319,7 +1293,6 @@
                                      BOOLEAN fw_ext_present,
                                      UINT8 *p_data)
 {
-#if (defined (BNEP_SUPPORTS_PROT_FILTERS) && BNEP_SUPPORTS_PROT_FILTERS == TRUE)
     if (p_bcb->rcvd_num_filters)
     {
         UINT16          i, proto;
@@ -1357,9 +1330,7 @@
             return BNEP_IGNORE_CMD;
         }
     }
-#endif
 
-#if (defined (BNEP_SUPPORTS_MULTI_FILTERS) && BNEP_SUPPORTS_MULTI_FILTERS == TRUE)
     /* Ckeck for multicast address filtering */
     if ((p_dest_addr[0] & 0x01) &&
         p_bcb->rcvd_mcast_filters)
@@ -1390,15 +1361,10 @@
             return BNEP_IGNORE_CMD;
         }
     }
-#endif
 
     return BNEP_SUCCESS;
 }
 
-
-
-
-
 /*******************************************************************************
 **
 ** Function         bnep_get_uuid32
@@ -1423,45 +1389,3 @@
         return result;
     }
 }
-
-
-
-
-/*******************************************************************************
-**
-** Function         bnep_dump_status
-**
-** Description      This function dumps the bnep control block and connection
-**                  blocks information
-**
-** Returns          none
-**
-*******************************************************************************/
-void bnep_dump_status (void)
-{
-#if (defined (BNEP_SUPPORTS_DEBUG_DUMP) && BNEP_SUPPORTS_DEBUG_DUMP == TRUE)
-    UINT16          i;
-    char            buff[200];
-    tBNEP_CONN     *p_bcb;
-
-    BNEP_TRACE_DEBUG ("BNEP my BD Addr %x.%x.%x.%x.%x.%x",
-        bnep_cb.my_bda[0], bnep_cb.my_bda[1], bnep_cb.my_bda[2],
-        bnep_cb.my_bda[3], bnep_cb.my_bda[4], bnep_cb.my_bda[5]);
-    BNEP_TRACE_DEBUG ("profile registered %d, trace %d, got_my_bd_addr %d",
-        bnep_cb.profile_registered, bnep_cb.trace_level, bnep_cb.got_my_bd_addr);
-
-    for (i = 0, p_bcb = bnep_cb.bcb; i < BNEP_MAX_CONNECTIONS; i++, p_bcb++)
-    {
-        sprintf (buff, "%d state %d, flags 0x%x, cid %d, pfilts %d, mfilts %d, src 0x%x, dst 0x%x, BD %x.%x.%x.%x.%x.%x",
-            i, p_bcb->con_state, p_bcb->con_flags, p_bcb->l2cap_cid,
-            p_bcb->rcvd_num_filters, p_bcb->rcvd_mcast_filters,
-            p_bcb->src_uuid.uu.uuid16, p_bcb->dst_uuid.uu.uuid16,
-            p_bcb->rem_bda[0], p_bcb->rem_bda[1], p_bcb->rem_bda[2],
-            p_bcb->rem_bda[3], p_bcb->rem_bda[4], p_bcb->rem_bda[5]);
-
-        BNEP_TRACE_DEBUG (buff);
-    }
-#endif
-}
-
-
diff --git a/stack/btm/btm_acl.c b/stack/btm/btm_acl.c
index 9b2c990..ba3e94b 100644
--- a/stack/btm/btm_acl.c
+++ b/stack/btm/btm_acl.c
@@ -30,6 +30,7 @@
 
 #include "bt_types.h"
 #include "bt_target.h"
+#include "device/include/controller.h"
 #include "gki.h"
 #include "hcimsgs.h"
 #include "btu.h"
@@ -37,7 +38,6 @@
 #include "btm_int.h"
 #include "l2c_int.h"
 #include "hcidefs.h"
-#include "bd.h"
 #include "bt_utils.h"
 
 static void btm_read_remote_features (UINT16 handle);
@@ -62,15 +62,9 @@
     BTM_TRACE_DEBUG ("btm_acl_init");
 #if 0  /* cleared in btm_init; put back in if called from anywhere else! */
     memset (&btm_cb.acl_db, 0, sizeof (btm_cb.acl_db));
-#if RFCOMM_INCLUDED == TRUE
     memset (btm_cb.btm_scn, 0, BTM_MAX_SCN);          /* Initialize the SCN usage to FALSE */
-#endif
     btm_cb.btm_def_link_policy     = 0;
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     btm_cb.p_bl_changed_cb         = NULL;
-#else
-    btm_cb.p_acl_changed_cb        = NULL;
-#endif
 #endif
 
     /* Initialize nonzero defaults */
@@ -254,18 +248,13 @@
 #endif
                 {
                     p->conn_addr_type = BLE_ADDR_PUBLIC;
-                    BTM_GetLocalDeviceAddr(p->conn_addr);
+                    memcpy(p->conn_addr, controller_get_interface()->get_address()->address, BD_ADDR_LEN);
                 }
             }
 #endif
-            p->restore_pkt_types = 0;   /* Only exists while SCO is active */
             p->switch_role_state = BTM_ACL_SWKEY_STATE_IDLE;
 
-#if BTM_PWR_MGR_INCLUDED == FALSE
-            p->mode             = BTM_ACL_MODE_NORMAL;
-#else
             btm_pm_sm_alloc(xx);
-#endif /* BTM_PWR_MGR_INCLUDED == FALSE */
 
             memcpy (p->remote_addr, bda, BD_ADDR_LEN);
 
@@ -325,7 +314,7 @@
                     &p->active_remote_addr_type);
 #endif
 
-                if (HCI_LE_SLAVE_INIT_FEAT_EXC_SUPPORTED(btm_cb.devcb.local_le_features)
+                if (HCI_LE_SLAVE_INIT_FEAT_EXC_SUPPORTED(controller_get_interface()->get_features_ble()->as_array)
                     || link_role == HCI_ROLE_MASTER)
                 {
                     btsnd_hcic_ble_read_remote_feat(p->hci_handle);
@@ -387,13 +376,10 @@
 void btm_acl_removed (BD_ADDR bda, tBT_TRANSPORT transport)
 {
     tACL_CONN   *p;
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     tBTM_BL_EVENT_DATA  evt_data;
-#endif
 #if (defined BLE_INCLUDED && BLE_INCLUDED == TRUE)
     tBTM_SEC_DEV_REC *p_dev_rec=NULL;
 #endif
-
     BTM_TRACE_DEBUG ("btm_acl_removed");
     p = btm_bda_to_acl(bda, transport);
     if (p != (tACL_CONN *)NULL)
@@ -409,7 +395,6 @@
             p->link_up_issued = FALSE;
 
             /* If anyone cares, tell him database changed */
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
             if (btm_cb.p_bl_changed_cb)
             {
                 evt_data.event = BTM_BL_DISCN_EVT;
@@ -422,14 +407,6 @@
             }
 
             btm_acl_update_busy_level (BTM_BLI_ACL_DOWN_EVT);
-#else
-            if (btm_cb.p_acl_changed_cb)
-#if BLE_INCLUDED == TRUE
-                (*btm_cb.p_acl_changed_cb) (bda, NULL, NULL, NULL, FALSE, p->hci_handle, p->transport);
-#else
-                (*btm_cb.p_acl_changed_cb) (bda, NULL, NULL, NULL, FALSE);
-#endif
-#endif
         }
 
 #if (defined BLE_INCLUDED && BLE_INCLUDED == TRUE)
@@ -503,7 +480,6 @@
     }
 }
 
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
 /*******************************************************************************
 **
 ** Function         btm_acl_update_busy_level
@@ -524,18 +500,9 @@
     {
         case BTM_BLI_ACL_UP_EVT:
             BTM_TRACE_DEBUG ("BTM_BLI_ACL_UP_EVT");
-            btm_cb.num_acl++;
             break;
         case BTM_BLI_ACL_DOWN_EVT:
-            if (btm_cb.num_acl)
-            {
-                btm_cb.num_acl--;
-                BTM_TRACE_DEBUG ("BTM_BLI_ACL_DOWN_EVT", btm_cb.num_acl);
-            }
-            else
-            {
-                BTM_TRACE_ERROR ("BTM_BLI_ACL_DOWN_EVT issued, but num_acl already zero !!!");
-            }
+            BTM_TRACE_DEBUG ("BTM_BLI_ACL_DOWN_EVT");
             break;
         case BTM_BLI_PAGE_EVT:
             BTM_TRACE_DEBUG ("BTM_BLI_PAGE_EVT");
@@ -567,7 +534,7 @@
     if (btm_cb.is_paging || btm_cb.is_inquiry)
         busy_level = 10;
     else
-        busy_level = (UINT8)btm_cb.num_acl;
+        busy_level = BTM_GetNumAclLinks();
 
     if ((busy_level != btm_cb.busy_level) ||(old_inquiry_state != btm_cb.is_inquiry))
     {
@@ -580,8 +547,6 @@
         }
     }
 }
-#endif
-
 
 /*******************************************************************************
 **
@@ -634,11 +599,9 @@
 #if BTM_SCO_INCLUDED == TRUE
     BOOLEAN    is_sco_active;
 #endif
-#if BTM_PWR_MGR_INCLUDED == TRUE
     tBTM_STATUS  status;
     tBTM_PM_MODE pwr_mode;
     tBTM_PM_PWR_MD settings;
-#endif
 #if (BT_USE_TRACES == TRUE)
     BD_ADDR_PTR  p_bda;
 #endif
@@ -647,7 +610,7 @@
                     remote_bd_addr[3], remote_bd_addr[4], remote_bd_addr[5]);
 
     /* Make sure the local device supports switching */
-    if (!(HCI_SWITCH_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0])))
+    if (!controller_get_interface()->supports_master_slave_role_switch())
         return(BTM_MODE_UNSUPPORTED);
 
     if (btm_cb.devcb.p_switch_role_cb && p_cb)
@@ -684,24 +647,6 @@
         return(BTM_BUSY);
     }
 
-    /* Cannot switch role while parked or sniffing */
-#if BTM_PWR_MGR_INCLUDED == FALSE
-    if (p->mode == HCI_MODE_PARK)
-    {
-        if (!btsnd_hcic_exit_park_mode (p->hci_handle))
-            return(BTM_NO_RESOURCES);
-
-        p->switch_role_state = BTM_ACL_SWKEY_STATE_MODE_CHANGE;
-    }
-    else if (p->mode == HCI_MODE_SNIFF)
-    {
-        if (!btsnd_hcic_exit_sniff_mode (p->hci_handle))
-            return(BTM_NO_RESOURCES);
-
-        p->switch_role_state = BTM_ACL_SWKEY_STATE_MODE_CHANGE;
-    }
-#else   /* power manager is in use */
-
     if ((status = BTM_ReadPowerMode(p->remote_addr, &pwr_mode)) != BTM_SUCCESS)
         return(status);
 
@@ -716,7 +661,6 @@
 
         p->switch_role_state = BTM_ACL_SWKEY_STATE_MODE_CHANGE;
     }
-#endif
     /* some devices do not support switch while encryption is on */
     else
     {
@@ -765,163 +709,6 @@
 
 /*******************************************************************************
 **
-** Function         BTM_ChangeLinkKey
-**
-** Description      This function is called to change the link key of the
-**                  connection.
-**
-** Returns          BTM_CMD_STARTED if command issued to controller.
-**                  BTM_NO_RESOURCES if couldn't allocate memory to issue command
-**                  BTM_UNKNOWN_ADDR if no active link with bd addr specified
-**                  BTM_BUSY if the previous command is not completed
-**
-*******************************************************************************/
-tBTM_STATUS BTM_ChangeLinkKey (BD_ADDR remote_bd_addr, tBTM_CMPL_CB *p_cb)
-{
-    tACL_CONN   *p;
-    tBTM_SEC_DEV_REC  *p_dev_rec = NULL;
-#if BTM_PWR_MGR_INCLUDED == TRUE
-    tBTM_STATUS  status;
-    tBTM_PM_MODE pwr_mode;
-    tBTM_PM_PWR_MD settings;
-#endif
-    BTM_TRACE_DEBUG ("BTM_ChangeLinkKey");
-    if ((p = btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR)) == NULL)
-        return(BTM_UNKNOWN_ADDR);
-
-    /* Ignore change link key request if the previsous request has not completed */
-    if (p->change_key_state != BTM_ACL_SWKEY_STATE_IDLE)
-    {
-        BTM_TRACE_DEBUG ("Link key change request declined since the previous request"
-                          " for this device has not completed ");
-        return(BTM_BUSY);
-    }
-
-    memset (&btm_cb.devcb.chg_link_key_ref_data, 0, sizeof(tBTM_CHANGE_KEY_CMPL));
-
-    /* Cannot change key while parked */
-#if BTM_PWR_MGR_INCLUDED == FALSE
-    if (p->mode == HCI_MODE_PARK)
-    {
-        if (!btsnd_hcic_exit_park_mode (p->hci_handle))
-            return(BTM_NO_RESOURCES);
-
-        p->change_key_state = BTM_ACL_SWKEY_STATE_MODE_CHANGE;
-    }
-#else   /* power manager is in use */
-
-
-    if ((status = BTM_ReadPowerMode(p->remote_addr, &pwr_mode)) != BTM_SUCCESS)
-        return(status);
-
-    /* Wake up the link if in park before attempting to change link keys */
-    if (pwr_mode == BTM_PM_MD_PARK)
-    {
-        memset( (void*)&settings, 0, sizeof(settings));
-        settings.mode = BTM_PM_MD_ACTIVE;
-        status = BTM_SetPowerMode (BTM_PM_SET_ONLY_ID, p->remote_addr, &settings);
-        if (status != BTM_CMD_STARTED)
-            return(BTM_WRONG_MODE);
-
-        p->change_key_state = BTM_ACL_SWKEY_STATE_MODE_CHANGE;
-    }
-#endif
-    /* some devices do not support change of link key while encryption is on */
-    else if (((p_dev_rec = btm_find_dev (remote_bd_addr)) != NULL)
-             && ((p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED) != 0) && !BTM_EPR_AVAILABLE(p))
-    {
-        /* bypass turning off encryption if switch role is already doing it */
-        if (p->encrypt_state != BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF)
-        {
-            if (!btsnd_hcic_set_conn_encrypt (p->hci_handle, FALSE))
-                return(BTM_NO_RESOURCES);
-            else
-                p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF;
-        }
-
-        p->change_key_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF;
-    }
-    else    /* Ok to initiate change of link key */
-    {
-        if (!btsnd_hcic_change_link_key (p->hci_handle))
-            return(BTM_NO_RESOURCES);
-
-        p->change_key_state = BTM_ACL_SWKEY_STATE_IN_PROGRESS;
-    }
-
-    /* Initialize return structure in case request fails */
-    memcpy (btm_cb.devcb.chg_link_key_ref_data.remote_bd_addr, remote_bd_addr,
-            BD_ADDR_LEN);
-    btm_cb.devcb.p_chg_link_key_cb = p_cb;
-    return(BTM_CMD_STARTED);
-}
-
-/*******************************************************************************
-**
-** Function         btm_acl_link_key_change
-**
-** Description      This function is called to when a change link key event
-**                  is received.
-**
-*******************************************************************************/
-void btm_acl_link_key_change (UINT16 handle, UINT8 status)
-{
-    tBTM_CHANGE_KEY_CMPL *p_data;
-    tACL_CONN            *p;
-    UINT8                xx;
-    BTM_TRACE_DEBUG ("btm_acl_link_key_change");
-    /* Look up the connection by handle and set the current mode */
-    xx = btm_handle_to_acl_index(handle);
-
-    /* don't assume that we can never get a bad hci_handle */
-    if (xx >= MAX_L2CAP_LINKS)
-        return;
-
-    p_data = &btm_cb.devcb.chg_link_key_ref_data;
-    p = &btm_cb.acl_db[xx];
-    p_data->hci_status = status;
-
-    /* if switching state is switching we need to turn encryption on */
-    /* if idle, we did not change encryption */
-    if (p->change_key_state == BTM_ACL_SWKEY_STATE_SWITCHING)
-    {
-        /* Make sure there's not also a role switch going on before re-enabling */
-        if (p->switch_role_state != BTM_ACL_SWKEY_STATE_SWITCHING)
-        {
-            if (btsnd_hcic_set_conn_encrypt (p->hci_handle, TRUE))
-            {
-                p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_ON;
-                p->change_key_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_ON;
-                return;
-            }
-        }
-        else    /* Set the state and wait for change link key */
-        {
-            p->change_key_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_ON;
-            return;
-        }
-    }
-
-    /* Set the switch_role_state to IDLE since the reply received from HCI */
-    /* regardless of its result either success or failed. */
-    if (p->change_key_state == BTM_ACL_SWKEY_STATE_IN_PROGRESS)
-    {
-        p->change_key_state = BTM_ACL_SWKEY_STATE_IDLE;
-        p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
-    }
-
-    if (btm_cb.devcb.p_chg_link_key_cb)
-    {
-        (*btm_cb.devcb.p_chg_link_key_cb)((void *)p_data);
-        btm_cb.devcb.p_chg_link_key_cb = NULL;
-    }
-
-    BTM_TRACE_ERROR("Change Link Key Complete Event: Handle 0x%02x, HCI Status 0x%02x",
-                     handle, p_data->hci_status);
-}
-
-/*******************************************************************************
-**
 ** Function         btm_acl_encrypt_change
 **
 ** Description      This function is when encryption of the connection is
@@ -937,9 +724,7 @@
     tACL_CONN *p;
     UINT8     xx;
     tBTM_SEC_DEV_REC  *p_dev_rec;
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     tBTM_BL_ROLE_CHG_DATA   evt;
-#endif
 
     BTM_TRACE_DEBUG ("btm_acl_encrypt_change handle=%d status=%d encr_enabl=%d",
                       handle, status, encr_enable);
@@ -987,7 +772,6 @@
         p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
         btm_acl_report_role_change(btm_cb.devcb.switch_role_ref_data.hci_status, p->remote_addr);
 
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
         /* if role change event is registered, report it now */
         if (btm_cb.p_bl_changed_cb && (btm_cb.bl_evt_mask & BTM_BL_ROLE_CHG_MASK))
         {
@@ -1000,7 +784,6 @@
             BTM_TRACE_DEBUG("Role Switch Event: new_role 0x%02x, HCI Status 0x%02x, rs_st:%d",
                              evt.new_role, evt.hci_status, p->switch_role_state);
         }
-#endif
 
 #if BTM_DISC_DURING_RS == TRUE
         /* If a disconnect is pending, issue it now that role switch has completed */
@@ -1017,45 +800,6 @@
         }
 #endif
     }
-
-
-    /* Process Change Link Key if active */
-    if (p->change_key_state == BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF)
-    {
-        /* if encryption turn off failed we still will try to change link key */
-        if (encr_enable)
-        {
-            p->change_key_state = BTM_ACL_SWKEY_STATE_IDLE;
-            p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
-        }
-        else
-        {
-            p->encrypt_state = BTM_ACL_ENCRYPT_STATE_TEMP_FUNC;
-            p->change_key_state = BTM_ACL_SWKEY_STATE_SWITCHING;
-        }
-
-        if (!btsnd_hcic_change_link_key (p->hci_handle))
-        {
-            p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
-            p->change_key_state = BTM_ACL_SWKEY_STATE_IDLE;
-            if (btm_cb.devcb.p_chg_link_key_cb)
-            {
-                (*btm_cb.devcb.p_chg_link_key_cb)(&btm_cb.devcb.chg_link_key_ref_data);
-                btm_cb.devcb.p_chg_link_key_cb = NULL;
-            }
-        }
-    }
-    /* Finished enabling Encryption after changing link key */
-    else if (p->change_key_state == BTM_ACL_SWKEY_STATE_ENCRYPTION_ON)
-    {
-        p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
-        p->change_key_state = BTM_ACL_SWKEY_STATE_IDLE;
-        if (btm_cb.devcb.p_chg_link_key_cb)
-        {
-            (*btm_cb.devcb.p_chg_link_key_cb)(&btm_cb.devcb.chg_link_key_ref_data);
-            btm_cb.devcb.p_chg_link_key_cb = NULL;
-        }
-    }
 }
 /*******************************************************************************
 **
@@ -1149,104 +893,6 @@
     btsnd_hcic_write_def_policy_set(settings);
 }
 
-
-/*******************************************************************************
-**
-** Function         BTM_ReadLinkPolicy
-**
-** Description      This function is called to read the link policy settings.
-**                  The address of link policy results are returned in the callback.
-**                  (tBTM_LNK_POLICY_RESULTS)
-**
-** Returns          status of the operation
-**
-*******************************************************************************/
-tBTM_STATUS BTM_ReadLinkPolicy (BD_ADDR remote_bda, tBTM_CMPL_CB *p_cb)
-{
-    tACL_CONN   *p;
-
-    BTM_TRACE_API ("BTM_ReadLinkPolicy: RemBdAddr: %02x%02x%02x%02x%02x%02x",
-                    remote_bda[0], remote_bda[1], remote_bda[2],
-                    remote_bda[3], remote_bda[4], remote_bda[5]);
-
-    /* If someone already waiting on the version, do not allow another */
-    if (btm_cb.devcb.p_rlinkp_cmpl_cb)
-        return(BTM_BUSY);
-
-    p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
-    if (p != (tACL_CONN *)NULL)
-    {
-        btu_start_timer (&btm_cb.devcb.rlinkp_timer, BTU_TTYPE_BTM_ACL, BTM_DEV_REPLY_TIMEOUT);
-        btm_cb.devcb.p_rlinkp_cmpl_cb = p_cb;
-
-        if (!btsnd_hcic_read_policy_set (p->hci_handle))
-        {
-            btu_stop_timer (&btm_cb.devcb.rlinkp_timer);
-            btm_cb.devcb.p_rlinkp_cmpl_cb = NULL;
-            return(BTM_NO_RESOURCES);
-        }
-
-        return(BTM_CMD_STARTED);
-    }
-
-    /* If here, no BD Addr found */
-    return(BTM_UNKNOWN_ADDR);
-}
-
-
-/*******************************************************************************
-**
-** Function         btm_read_link_policy_complete
-**
-** Description      This function is called when the command complete message
-**                  is received from the HCI for the read local link policy request.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_link_policy_complete (UINT8 *p)
-{
-    tBTM_CMPL_CB            *p_cb = btm_cb.devcb.p_rlinkp_cmpl_cb;
-    tBTM_LNK_POLICY_RESULTS  lnkpol;
-    UINT16                   handle;
-    tACL_CONN               *p_acl_cb = &btm_cb.acl_db[0];
-    UINT16                   index;
-    BTM_TRACE_DEBUG ("btm_read_link_policy_complete");
-    btu_stop_timer (&btm_cb.devcb.rlinkp_timer);
-
-    /* If there was a callback address for read local version, call it */
-    btm_cb.devcb.p_rlinkp_cmpl_cb = NULL;
-
-    if (p_cb)
-    {
-        STREAM_TO_UINT8  (lnkpol.hci_status, p);
-
-        if (lnkpol.hci_status == HCI_SUCCESS)
-        {
-            lnkpol.status = BTM_SUCCESS;
-
-            STREAM_TO_UINT16 (handle, p);
-
-            STREAM_TO_UINT16 (lnkpol.settings, p);
-
-            /* Search through the list of active channels for the correct BD Addr */
-            for (index = 0; index < MAX_L2CAP_LINKS; index++, p_acl_cb++)
-            {
-                if ((p_acl_cb->in_use) && (handle == p_acl_cb->hci_handle))
-                {
-                    memcpy (lnkpol.rem_bda, p_acl_cb->remote_addr, BD_ADDR_LEN);
-                    break;
-                }
-            }
-        }
-        else
-            lnkpol.status = BTM_ERR_PROCESSING;
-
-        (*p_cb)(&lnkpol);
-    }
-}
-
-
 /*******************************************************************************
 **
 ** Function         btm_read_remote_version_complete
@@ -1333,11 +979,8 @@
 void btm_process_remote_ext_features_page (tACL_CONN *p_acl_cb, tBTM_SEC_DEV_REC *p_dev_rec,
                                            UINT8 page_idx)
 {
-    UINT16            handle;
     UINT8             req_pend;
 
-    handle = p_acl_cb->hci_handle;
-
     memcpy (p_dev_rec->features[page_idx], p_acl_cb->peer_lmp_features[page_idx],
             HCI_FEATURE_BYTES_PER_PAGE);
 
@@ -1486,7 +1129,7 @@
                     HCI_FEATURE_BYTES_PER_PAGE);
 
     if ((HCI_LMP_EXTENDED_SUPPORTED(p_acl_cb->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0])) &&
-        (HCI_READ_REMOTE_EXT_FEATURES_SUPPORTED(btm_cb.devcb.supported_cmds)))
+        (controller_get_interface()->supports_reading_remote_extended_features()))
     {
         /* if the remote controller has extended features and local controller supports
         ** HCI_Read_Remote_Extended_Features command then start reading these feature starting
@@ -1517,13 +1160,13 @@
 void btm_read_remote_ext_features_complete (UINT8 *p)
 {
     tACL_CONN   *p_acl_cb;
-    UINT8       status, page_num, max_page;
+    UINT8       page_num, max_page;
     UINT16      handle;
     UINT8       acl_idx;
 
     BTM_TRACE_DEBUG ("btm_read_remote_ext_features_complete");
 
-    STREAM_TO_UINT8  (status, p);
+    ++p;
     STREAM_TO_UINT16 (handle, p);
     STREAM_TO_UINT8  (page_num, p);
     STREAM_TO_UINT8  (max_page, p);
@@ -1611,9 +1254,7 @@
 *******************************************************************************/
 void btm_establish_continue (tACL_CONN *p_acl_cb)
 {
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
         tBTM_BL_EVENT_DATA  evt_data;
-#endif
         BTM_TRACE_DEBUG ("btm_establish_continue");
 #if (!defined(BTM_BYPASS_EXTRA_ACL_SETUP) || BTM_BYPASS_EXTRA_ACL_SETUP == FALSE)
 #if (defined BLE_INCLUDED && BLE_INCLUDED == TRUE)
@@ -1632,7 +1273,6 @@
         p_acl_cb->link_up_issued = TRUE;
 
         /* If anyone cares, tell him database changed */
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
         if (btm_cb.p_bl_changed_cb)
         {
             evt_data.event = BTM_BL_CONN_EVT;
@@ -1648,26 +1288,6 @@
             (*btm_cb.p_bl_changed_cb)(&evt_data);
         }
         btm_acl_update_busy_level (BTM_BLI_ACL_UP_EVT);
-#else
-        if (btm_cb.p_acl_changed_cb)
-#if BLE_INCLUDED == TRUE
-            (*btm_cb.p_acl_changed_cb) (p_acl_cb->remote_addr,
-                                        p_acl_cb->remote_dc,
-                                        p_acl_cb->remote_name,
-                                        p_acl_cb->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0],
-                                        TRUE,
-                                        p_acl_cb->hci_handle,
-                                        p_acl_cb->transport);
-#else
-            (*btm_cb.p_acl_changed_cb) (p_acl_cb->remote_addr,
-                                        p_acl_cb->remote_dc,
-                                        p_acl_cb->remote_name,
-                                        p_acl_cb->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0],
-                                        TRUE);
-#endif
-
-#endif
-
 }
 
 
@@ -1748,351 +1368,6 @@
 
 /*******************************************************************************
 **
-** Function         BTM_RegForLstoEvt
-**
-** Description      register for the HCI "Link Supervision Timeout Change" event
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTM_RegForLstoEvt (tBTM_LSTO_CBACK *p_cback)
-{
-    BTM_TRACE_DEBUG ("BTM_RegForLstoEvt");
-    btm_cb.p_lsto_cback = p_cback;
-}
-
-/*******************************************************************************
-**
-** Function         btm_proc_lsto_evt
-**
-** Description      process the HCI "Link Supervision Timeout Change" event
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_proc_lsto_evt(UINT16 handle, UINT16 timeout)
-{
-    UINT8 xx;
-
-    BTM_TRACE_DEBUG ("btm_proc_lsto_evt");
-    if (btm_cb.p_lsto_cback)
-    {
-        /* Look up the connection by handle and set the current mode */
-        xx = btm_handle_to_acl_index(handle);
-
-        /* don't assume that we can never get a bad hci_handle */
-        if (xx < MAX_L2CAP_LINKS)
-        {
-            (*btm_cb.p_lsto_cback)(btm_cb.acl_db[xx].remote_addr, timeout);
-        }
-    }
-}
-
-#if BTM_PWR_MGR_INCLUDED == FALSE
-/*******************************************************************************
-**
-** Function         BTM_SetHoldMode
-**
-** Description      This function is called to set a connection into hold mode.
-**                  A check is made if the connection is in sniff or park mode,
-**                  and if yes, the hold mode is ignored.
-**
-** Returns          status of the operation
-**
-*******************************************************************************/
-tBTM_STATUS BTM_SetHoldMode (BD_ADDR remote_bda, UINT16 min_interval, UINT16 max_interval)
-{
-    tACL_CONN   *p;
-
-    BTM_TRACE_DEBUG ("BTM_SetHoldMode");
-    /* First, check if hold mode is supported */
-    if (!HCI_HOLD_MODE_SUPPORTED(BTM_ReadLocalFeatures()))
-        return(BTM_MODE_UNSUPPORTED);
-
-    p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
-    if (p != (tACL_CONN *)NULL)
-    {
-        /* If the connection is in park or sniff mode, forget about holding it */
-        if (p->mode != BTM_ACL_MODE_NORMAL)
-            return(BTM_SUCCESS);
-
-        if (!btsnd_hcic_hold_mode (p->hci_handle, max_interval, min_interval))
-            return(BTM_NO_RESOURCES);
-
-        return(BTM_CMD_STARTED);
-    }
-
-    /* If here, no BD Addr found */
-    return(BTM_UNKNOWN_ADDR);
-}
-
-
-/*******************************************************************************
-**
-** Function         BTM_SetSniffMode
-**
-** Description      This function is called to set a connection into sniff mode.
-**                  A check is made if the connection is already in sniff or park
-**                  mode, and if yes, the sniff mode is ignored.
-**
-** Returns          status of the operation
-**
-*******************************************************************************/
-tBTM_STATUS BTM_SetSniffMode (BD_ADDR remote_bda, UINT16 min_period, UINT16 max_period,
-                              UINT16 attempt, UINT16 timeout)
-{
-    tACL_CONN   *p;
-    BTM_TRACE_DEBUG ("BTM_SetSniffMode");
-    /* First, check if sniff mode is supported */
-    if (!HCI_SNIFF_MODE_SUPPORTED(BTM_ReadLocalFeatures()))
-        return(BTM_MODE_UNSUPPORTED);
-
-    p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
-    if (p != (tACL_CONN *)NULL)
-    {
-        /* If the connection is in park mode, forget about sniffing it */
-        if (p->mode != BTM_ACL_MODE_NORMAL)
-            return(BTM_WRONG_MODE);
-
-        if (!btsnd_hcic_sniff_mode (p->hci_handle, max_period,
-                                    min_period, attempt, timeout))
-            return(BTM_NO_RESOURCES);
-
-        return(BTM_CMD_STARTED);
-    }
-
-    /* If here, no BD Addr found */
-    return(BTM_UNKNOWN_ADDR);
-}
-
-
-
-
-/*******************************************************************************
-**
-** Function         BTM_CancelSniffMode
-**
-** Description      This function is called to put a connection out of sniff mode.
-**                  A check is made if the connection is already in sniff mode,
-**                  and if not, the cancel sniff mode is ignored.
-**
-** Returns          status of the operation
-**
-*******************************************************************************/
-tBTM_STATUS BTM_CancelSniffMode (BD_ADDR remote_bda)
-{
-    tACL_CONN   *p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
-    BTM_TRACE_DEBUG ("BTM_CancelSniffMode ");
-    if (p == (tACL_CONN *)NULL)
-        return(BTM_UNKNOWN_ADDR);
-
-    /* If the connection is not in sniff mode, cannot cancel */
-    if (p->mode != BTM_ACL_MODE_SNIFF)
-        return(BTM_WRONG_MODE);
-
-    if (!btsnd_hcic_exit_sniff_mode (p->hci_handle))
-        return(BTM_NO_RESOURCES);
-
-    return(BTM_CMD_STARTED);
-}
-
-
-/*******************************************************************************
-**
-** Function         BTM_SetParkMode
-**
-** Description      This function is called to set a connection into park mode.
-**                  A check is made if the connection is already in sniff or park
-**                  mode, and if yes, the park mode is ignored.
-**
-** Returns          status of the operation
-**
-*******************************************************************************/
-tBTM_STATUS BTM_SetParkMode (BD_ADDR remote_bda, UINT16 beacon_min_period, UINT16 beacon_max_period)
-{
-    tACL_CONN   *p;
-
-    BTM_TRACE_DEBUG ("BTM_SetParkMode");
-    /* First, check if park mode is supported */
-    if (!HCI_PARK_MODE_SUPPORTED(BTM_ReadLocalFeatures()))
-        return(BTM_MODE_UNSUPPORTED);
-
-    p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
-    if (p != (tACL_CONN *)NULL)
-    {
-        /* If the connection is in sniff mode, forget about parking it */
-        if (p->mode != BTM_ACL_MODE_NORMAL)
-            return(BTM_WRONG_MODE);
-
-        /* no park mode if SCO exists -- CR#1982, 1.1 errata 1124
-           command status event should be returned /w error code 0x0C "Command Disallowed"
-           Let LM do this.
-        */
-        if (!btsnd_hcic_park_mode (p->hci_handle,
-                                   beacon_max_period, beacon_min_period))
-            return(BTM_NO_RESOURCES);
-
-        return(BTM_CMD_STARTED);
-    }
-
-    /* If here, no BD Addr found */
-    return(BTM_UNKNOWN_ADDR);
-}
-
-/*******************************************************************************
-**
-** Function         BTM_CancelParkMode
-**
-** Description      This function is called to put a connection out of park mode.
-**                  A check is made if the connection is already in park mode,
-**                  and if not, the cancel sniff mode is ignored.
-**
-** Returns          status of the operation
-**
-*******************************************************************************/
-tBTM_STATUS BTM_CancelParkMode (BD_ADDR remote_bda)
-{
-    tACL_CONN   *p;
-
-    BTM_TRACE_DEBUG ("BTM_CancelParkMode");
-    p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
-    if (p != (tACL_CONN *)NULL)
-    {
-        /* If the connection is not in park mode, cannot cancel */
-        if (p->mode != BTM_ACL_MODE_PARK)
-            return(BTM_WRONG_MODE);
-
-        if (!btsnd_hcic_exit_park_mode (p->hci_handle))
-            return(BTM_NO_RESOURCES);
-
-        return(BTM_CMD_STARTED);
-    }
-
-    /* If here, no BD Addr found */
-    return(BTM_UNKNOWN_ADDR);
-}
-#endif /* BTM_PWR_MGR_INCLUDED == FALSE */
-
-
-/*******************************************************************************
-**
-** Function         BTM_SetPacketTypes
-**
-** Description      This function is set the packet types used for a specific
-**                  ACL connection,
-**
-** Returns          status of the operation
-**
-*******************************************************************************/
-tBTM_STATUS BTM_SetPacketTypes (BD_ADDR remote_bda, UINT16 pkt_types)
-{
-    tACL_CONN   *p;
-    BTM_TRACE_DEBUG ("BTM_SetPacketTypes");
-
-    if ((p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR)) != NULL)
-        return(btm_set_packet_types (p, pkt_types));
-
-    /* If here, no BD Addr found */
-    return(BTM_UNKNOWN_ADDR);
-}
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadPacketTypes
-**
-** Description      This function is set the packet types used for a specific
-**                  ACL connection,
-**
-** Returns          packet types supported for the connection, or 0 if no BD address
-**
-*******************************************************************************/
-UINT16 BTM_ReadPacketTypes (BD_ADDR remote_bda)
-{
-    tACL_CONN   *p;
-
-    BTM_TRACE_DEBUG ("BTM_ReadPacketTypes");
-    p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
-    if (p != (tACL_CONN *)NULL)
-    {
-        return(p->pkt_types_mask);
-    }
-
-    /* If here, no BD Addr found */
-    return(0);
-}
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadAclMode
-**
-** Description      This returns the current mode for a specific
-**                  ACL connection.
-**
-** Input Param      remote_bda - device address of desired ACL connection
-**
-** Output Param     p_mode - address where the current mode is copied into.
-**                          BTM_ACL_MODE_NORMAL
-**                          BTM_ACL_MODE_HOLD
-**                          BTM_ACL_MODE_SNIFF
-**                          BTM_ACL_MODE_PARK
-**                          (valid only if return code is BTM_SUCCESS)
-**
-** Returns          BTM_SUCCESS if successful,
-**                  BTM_UNKNOWN_ADDR if bd addr is not active or bad
-**
-*******************************************************************************/
-#if BTM_PWR_MGR_INCLUDED == FALSE
-tBTM_STATUS BTM_ReadAclMode (BD_ADDR remote_bda, UINT8 *p_mode)
-{
-    tACL_CONN   *p;
-
-    BTM_TRACE_API ("BTM_ReadAclMode: RemBdAddr: %02x%02x%02x%02x%02x%02x",
-                    remote_bda[0], remote_bda[1], remote_bda[2],
-                    remote_bda[3], remote_bda[4], remote_bda[5]);
-
-    p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
-    if (p != (tACL_CONN *)NULL)
-    {
-        *p_mode = p->mode;
-        return(BTM_SUCCESS);
-    }
-
-    /* If here, no BD Addr found */
-    return(BTM_UNKNOWN_ADDR);
-}
-#endif /* BTM_PWR_MGR_INCLUDED == FALSE */
-
-/*******************************************************************************
-**
-** Function         BTM_ReadClockOffset
-**
-** Description      This returns the clock offset for a specific
-**                  ACL connection.
-**
-** Input Param      remote_bda - device address of desired ACL connection
-**
-** Returns          clock-offset or 0 if unknown
-**
-*******************************************************************************/
-UINT16 BTM_ReadClockOffset (BD_ADDR remote_bda)
-{
-    tACL_CONN   *p;
-
-    BTM_TRACE_API ("BTM_ReadClockOffset: RemBdAddr: %02x%02x%02x%02x%02x%02x",
-                    remote_bda[0], remote_bda[1], remote_bda[2],
-                    remote_bda[3], remote_bda[4], remote_bda[5]);
-
-    if ( (p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR)) != NULL)
-        return(p->clock_offset);
-
-    /* If here, no BD Addr found */
-    return(0);
-}
-
-/*******************************************************************************
-**
 ** Function         BTM_IsAclConnectionUp
 **
 ** Description      This function is called to check if an ACL connection exists
@@ -2131,48 +1406,15 @@
 *******************************************************************************/
 UINT16 BTM_GetNumAclLinks (void)
 {
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
-    return(UINT16)btm_cb.num_acl;
-#else
-    tACL_CONN   *p = &btm_cb.acl_db[0];
-    UINT16      xx, yy;
-    BTM_TRACE_DEBUG ("BTM_GetNumAclLinks");
-    for (xx = yy = 0; xx < MAX_L2CAP_LINKS; xx++, p++)
+    uint16_t num_acl = 0;
+
+    for (uint16_t i = 0; i < MAX_L2CAP_LINKS; ++i)
     {
-        if (p->in_use)
-            yy++;
+        if (btm_cb.acl_db[i].in_use)
+            ++num_acl;
     }
 
-    return(yy);
-#endif
-}
-
-/*******************************************************************************
-**
-** Function         BTM_GetNumLeLinks
-**
-** Description      This function is called to count the number of
-**                   LE ACL links that are active.
-**
-** Returns          UINT16  Number of active LE links
-**
-*******************************************************************************/
-UINT16 BTM_GetNumLeLinks (void)
-{
-    UINT16 yy = 0;
-
-#if BLE_INCLUDED == TRUE
-    tACL_CONN   *p = &btm_cb.acl_db[0];
-    UINT16      xx;
-    BTM_TRACE_DEBUG ("BTM_GetNumLeLinks");
-    for (xx = yy = 0; xx < MAX_L2CAP_LINKS; xx++, p++)
-    {
-        if  ((p->in_use) &&(p->transport == BT_TRANSPORT_LE))
-            yy++;
-    }
-#endif
-
-    return(yy);
+    return num_acl;
 }
 
 /*******************************************************************************
@@ -2217,49 +1459,6 @@
     return(0xFFFF);
 }
 
-#if BTM_PWR_MGR_INCLUDED == FALSE
-/*******************************************************************************
-**
-** Function         btm_process_mode_change
-**
-** Description      This function is called when an HCI mode change event occurs.
-**
-** Input Parms      hci_status - status of the event (HCI_SUCCESS if no errors)
-**                  hci_handle - connection handle associated with the change
-**                  mode - HCI_MODE_ACTIVE, HCI_MODE_HOLD, HCI_MODE_SNIFF, or HCI_MODE_PARK
-**                  interval - number of baseband slots (meaning depends on mode)
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_process_mode_change (UINT8 hci_status, UINT16 hci_handle, UINT8 mode, UINT16 interval)
-{
-    tACL_CONN        *p;
-    UINT8             xx;
-    BTM_TRACE_DEBUG ("btm_process_mode_change");
-    if (hci_status != HCI_SUCCESS)
-    {
-        BTM_TRACE_WARNING ("BTM: HCI Mode Change Error Status: 0x%02x", hci_status);
-    }
-
-    /* Look up the connection by handle and set the current mode */
-    xx = btm_handle_to_acl_index(hci_handle);
-
-    /* don't assume that we can never get a bad hci_handle */
-    if (xx >= MAX_L2CAP_LINKS)
-        return;
-
-    p = &btm_cb.acl_db[xx];
-
-    /* If status is not success mode does not mean anything */
-    if (hci_status == HCI_SUCCESS)
-        p->mode = mode;
-
-    /* If mode change was because of an active role switch or change link key */
-    btm_cont_rswitch_or_chglinkkey(p, btm_find_dev(p->remote_addr), hci_status);
-}
-#endif /* BTM_PWR_MGR_INCLUDED == FALSE */
-
 /*******************************************************************************
 **
 ** Function         btm_process_clk_off_comp_evt
@@ -2300,9 +1499,7 @@
     tACL_CONN               *p = btm_bda_to_acl(p_bda, BT_TRANSPORT_BR_EDR);
     tBTM_ROLE_SWITCH_CMPL   *p_data = &btm_cb.devcb.switch_role_ref_data;
     tBTM_SEC_DEV_REC        *p_dev_rec;
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     tBTM_BL_ROLE_CHG_DATA   evt;
-#endif
 
     BTM_TRACE_DEBUG ("btm_acl_role_changed");
     /* Ignore any stray events */
@@ -2343,18 +1540,9 @@
     /* if idle, we did not change encryption */
     if (p->switch_role_state == BTM_ACL_SWKEY_STATE_SWITCHING)
     {
-        /* Make sure there's not also a change link key going on before re-enabling */
-        if (p->change_key_state != BTM_ACL_SWKEY_STATE_SWITCHING)
+        if (btsnd_hcic_set_conn_encrypt (p->hci_handle, TRUE))
         {
-            if (btsnd_hcic_set_conn_encrypt (p->hci_handle, TRUE))
-            {
-                p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_ON;
-                p->switch_role_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_ON;
-                return;
-            }
-        }
-        else    /* Set the state and wait for change link key */
-        {
+            p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_ON;
             p->switch_role_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_ON;
             return;
         }
@@ -2371,7 +1559,6 @@
     /* if role switch complete is needed, report it now */
     btm_acl_report_role_change(hci_status, bd_addr);
 
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     /* if role change event is registered, report it now */
     if (btm_cb.p_bl_changed_cb && (btm_cb.bl_evt_mask & BTM_BL_ROLE_CHG_MASK))
     {
@@ -2384,7 +1571,6 @@
 
     BTM_TRACE_DEBUG("Role Switch Event: new_role 0x%02x, HCI Status 0x%02x, rs_st:%d",
                      p_data->role, p_data->hci_status, p->switch_role_state);
-#endif
 
 #if BTM_DISC_DURING_RS == TRUE
     /* If a disconnect is pending, issue it now that role switch has completed */
@@ -2404,7 +1590,6 @@
 
 }
 
-#if (RFCOMM_INCLUDED==TRUE)
 /*******************************************************************************
 **
 ** Function         BTM_AllocateSCN
@@ -2482,51 +1667,6 @@
         return(FALSE);      /* Illegal SCN passed in */
 }
 
-#else
-
-/* Make dummy functions for the RPC to link against */
-UINT8 BTM_AllocateSCN(void)
-{
-    return(0);
-}
-
-BOOLEAN BTM_FreeSCN(UINT8 scn)
-{
-    return(FALSE);
-}
-
-#endif
-
-
-/*******************************************************************************
-**
-** Function         btm_acl_timeout
-**
-** Description      This function is called when a timer list entry expires.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_acl_timeout (TIMER_LIST_ENT  *p_tle)
-{
-    UINT32 timer_type = p_tle->param;
-
-    BTM_TRACE_DEBUG ("btm_acl_timeout");
-    if (timer_type == TT_DEV_RLNKP)
-    {
-        tBTM_CMPL_CB            *p_cb = btm_cb.devcb.p_rlinkp_cmpl_cb;
-        tBTM_LNK_POLICY_RESULTS  lnkpol;
-
-        lnkpol.status = BTM_ERR_PROCESSING;
-        lnkpol.settings = 0;
-
-        btm_cb.devcb.p_rlinkp_cmpl_cb = NULL;
-
-        if (p_cb)
-            (*p_cb)(&lnkpol);
-    }
-}
-
 /*******************************************************************************
 **
 ** Function         btm_set_packet_types
@@ -2547,15 +1687,8 @@
                       btm_cb.btm_acl_pkt_types_supported);
 
     /* OR in any exception packet types if at least 2.0 version of spec */
-    if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_2_0)
-    {
-        temp_pkt_types |= ((pkt_types & BTM_ACL_EXCEPTION_PKTS_MASK) |
-                           (btm_cb.btm_acl_pkt_types_supported & BTM_ACL_EXCEPTION_PKTS_MASK));
-    }
-    else
-    {
-        temp_pkt_types &= (~BTM_ACL_EXCEPTION_PKTS_MASK);
-    }
+    temp_pkt_types |= ((pkt_types & BTM_ACL_EXCEPTION_PKTS_MASK) |
+                       (btm_cb.btm_acl_pkt_types_supported & BTM_ACL_EXCEPTION_PKTS_MASK));
 
     /* Exclude packet types not supported by the peer */
     btm_acl_chk_peer_pkt_type_support (p, &temp_pkt_types);
@@ -2593,7 +1726,7 @@
     else
     {
         /* Special case for when info for the local device is requested */
-        if (memcmp (btm_cb.devcb.local_addr, addr, BD_ADDR_LEN) == 0)
+        if (memcmp (controller_get_interface()->get_address(), addr, BD_ADDR_LEN) == 0)
         {
             pkt_types = btm_cb.btm_acl_pkt_types_supported;
         }
@@ -2750,7 +1883,6 @@
 ** Returns          BTM_SUCCESS if successfully registered, otherwise error
 **
 *******************************************************************************/
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
 tBTM_STATUS BTM_RegBusyLevelNotif (tBTM_BL_CHANGE_CB *p_cb, UINT8 *p_level,
                                    tBTM_BL_EVENT_MASK evt_mask)
 {
@@ -2769,28 +1901,6 @@
 
     return(BTM_SUCCESS);
 }
-#else
-/*******************************************************************************
-**
-** Function         BTM_AclRegisterForChanges
-**
-** Returns          This function is called to register a callback for when the
-**                  ACL database changes, i.e. new entry or entry deleted.
-**
-*******************************************************************************/
-tBTM_STATUS BTM_AclRegisterForChanges (tBTM_ACL_DB_CHANGE_CB *p_cb)
-{
-    BTM_TRACE_DEBUG ("BTM_AclRegisterForChanges");
-    if (!p_cb)
-        btm_cb.p_acl_changed_cb = NULL;
-    else if (btm_cb.p_acl_changed_cb)
-        return(BTM_BUSY);
-    else
-        btm_cb.p_acl_changed_cb = p_cb;
-
-    return(BTM_SUCCESS);
-}
-#endif
 
 /*******************************************************************************
 **
@@ -3264,25 +2374,23 @@
 
 /*******************************************************************************
 **
-** Function         btm_cont_rswitch_or_chglinkkey
+** Function         btm_cont_rswitch
 **
 ** Description      This function is called to continue processing an active
-**                  role switch or change of link key procedure.  It first
-**                  disables encryption if enabled and EPR is not supported
+**                  role switch. It first disables encryption if enabled and
+**                  EPR is not supported
 **
 ** Returns          void
 **
 *******************************************************************************/
-void btm_cont_rswitch_or_chglinkkey (tACL_CONN *p, tBTM_SEC_DEV_REC *p_dev_rec,
+void btm_cont_rswitch (tACL_CONN *p, tBTM_SEC_DEV_REC *p_dev_rec,
                                      UINT8 hci_status)
 {
     BOOLEAN sw_ok = TRUE;
-    BOOLEAN chlk_ok = TRUE;
-    BTM_TRACE_DEBUG ("btm_cont_rswitch_or_chglinkkey ");
+    BTM_TRACE_DEBUG ("btm_cont_rswitch");
     /* Check to see if encryption needs to be turned off if pending
        change of link key or role switch */
-    if (p->switch_role_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE ||
-        p->change_key_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE)
+    if (p->switch_role_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE)
     {
         /* Must turn off Encryption first if necessary */
         /* Some devices do not support switch or change of link key while encryption is on */
@@ -3294,18 +2402,12 @@
                 p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF;
                 if (p->switch_role_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE)
                     p->switch_role_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF;
-
-                if (p->change_key_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE)
-                    p->change_key_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF;
             }
             else
             {
                 /* Error occurred; set states back to Idle */
                 if (p->switch_role_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE)
                     sw_ok = FALSE;
-
-                if (p->change_key_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE)
-                    chlk_ok = FALSE;
             }
         }
         else    /* Encryption not used or EPR supported, continue with switch
@@ -3320,12 +2422,6 @@
 #endif
                 sw_ok = btsnd_hcic_switch_role (p->remote_addr, (UINT8)!p->link_role);
             }
-
-            if (p->change_key_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE)
-            {
-                p->switch_role_state = BTM_ACL_SWKEY_STATE_IN_PROGRESS;
-                chlk_ok = btsnd_hcic_change_link_key (p->hci_handle);
-            }
         }
 
         if (!sw_ok)
@@ -3333,17 +2429,6 @@
             p->switch_role_state = BTM_ACL_SWKEY_STATE_IDLE;
             btm_acl_report_role_change(hci_status, p->remote_addr);
         }
-
-        if (!chlk_ok)
-        {
-            p->change_key_state = BTM_ACL_SWKEY_STATE_IDLE;
-            if (btm_cb.devcb.p_chg_link_key_cb)
-            {
-                btm_cb.devcb.chg_link_key_ref_data.hci_status = hci_status;
-                (*btm_cb.devcb.p_chg_link_key_cb)(&btm_cb.devcb.chg_link_key_ref_data);
-                btm_cb.devcb.p_chg_link_key_cb = NULL;
-            }
-        }
     }
 }
 
@@ -3401,19 +2486,6 @@
 
 /*******************************************************************************
 **
-** Function         btm_acl_set_discing
-**
-** Description      set discing to the given value
-**
-*******************************************************************************/
-void  btm_acl_set_discing (BOOLEAN discing)
-{
-    BTM_TRACE_DEBUG ("btm_acl_set_discing");
-    btm_cb.discing = discing;
-}
-
-/*******************************************************************************
-**
 ** Function         btm_acl_paging
 **
 ** Description      send a paging command or queue it in btm_cb
@@ -3470,15 +2542,11 @@
 ** Description      Send connection collision event to upper layer if registered
 **
 ** Returns          TRUE if sent out to upper layer,
-**                  FALSE if BTM_BUSY_LEVEL_CHANGE_INCLUDED == FALSE, or no one
-**                  needs the notification.
-**
-**          Note: Function only used if BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE
+**                  FALSE if no one needs the notification.
 **
 *******************************************************************************/
 BOOLEAN  btm_acl_notif_conn_collision (BD_ADDR bda)
 {
-#if (BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     tBTM_BL_EVENT_DATA  evt_data;
 
     /* Report possible collision to the upper layer. */
@@ -3499,9 +2567,6 @@
     }
     else
         return FALSE;
-#else
-    return FALSE;
-#endif
 }
 
 
@@ -3521,31 +2586,27 @@
     if (!HCI_5_SLOT_PACKETS_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
         *p_pkt_type &= ~(BTM_ACL_PKT_TYPES_MASK_DH5 + BTM_ACL_PKT_TYPES_MASK_DM5);
 
-    /* If HCI version > 2.0, then also check EDR packet types */
-    if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_2_0)
+    /* 2 and 3 MPS support? */
+    if (!HCI_EDR_ACL_2MPS_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+        /* Not supported. Add 'not_supported' mask for all 2MPS packet types */
+        *p_pkt_type |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH1 + BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 +
+                            BTM_ACL_PKT_TYPES_MASK_NO_2_DH5);
+
+    if (!HCI_EDR_ACL_3MPS_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+        /* Not supported. Add 'not_supported' mask for all 3MPS packet types */
+        *p_pkt_type |= (BTM_ACL_PKT_TYPES_MASK_NO_3_DH1 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH3 +
+                            BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
+
+    /* EDR 3 and 5 slot support? */
+    if (HCI_EDR_ACL_2MPS_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0])
+     || HCI_EDR_ACL_3MPS_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
     {
-        /* 2 and 3 MPS support? */
-        if (!HCI_EDR_ACL_2MPS_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-            /* Not supported. Add 'not_supported' mask for all 2MPS packet types */
-            *p_pkt_type |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH1 + BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 +
-                                BTM_ACL_PKT_TYPES_MASK_NO_2_DH5);
+        if (!HCI_3_SLOT_EDR_ACL_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+            /* Not supported. Add 'not_supported' mask for all 3-slot EDR packet types */
+            *p_pkt_type |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH3);
 
-        if (!HCI_EDR_ACL_3MPS_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-            /* Not supported. Add 'not_supported' mask for all 3MPS packet types */
-            *p_pkt_type |= (BTM_ACL_PKT_TYPES_MASK_NO_3_DH1 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH3 +
-                                BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
-
-        /* EDR 3 and 5 slot support? */
-        if (HCI_EDR_ACL_2MPS_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0])
-         || HCI_EDR_ACL_3MPS_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-        {
-            if (!HCI_3_SLOT_EDR_ACL_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-                /* Not supported. Add 'not_supported' mask for all 3-slot EDR packet types */
-                *p_pkt_type |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH3);
-
-            if (!HCI_5_SLOT_EDR_ACL_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-                /* Not supported. Add 'not_supported' mask for all 5-slot EDR packet types */
-                *p_pkt_type |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH5 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
-        }
+        if (!HCI_5_SLOT_EDR_ACL_SUPPORTED(p->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+            /* Not supported. Add 'not_supported' mask for all 5-slot EDR packet types */
+            *p_pkt_type |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH5 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
     }
 }
diff --git a/stack/btm/btm_ble.c b/stack/btm/btm_ble.c
index 1552c4e..d28f6f2 100644
--- a/stack/btm/btm_ble.c
+++ b/stack/btm/btm_ble.c
@@ -39,6 +39,8 @@
 #include "bt_utils.h"
 
 #include "vendor_ble.h"
+#define LOG_TAG "bt_btm_ble"
+#include "osi/include/log.h"
 
 #if SMP_INCLUDED == TRUE
 extern BOOLEAN AES_CMAC ( BT_OCTET16 key, UINT8 *input, UINT16 length, UINT16 tlen, UINT8 *p_signature);
@@ -1509,13 +1511,13 @@
 {
     UINT8   *p = (UINT8 *)p_data;
     tBTM_SEC_DEV_REC    *match_rec = (tBTM_SEC_DEV_REC *) p_rec;
-    UINT8       role, status, bda_type;
+    UINT8       role, bda_type;
     UINT16      handle;
     BD_ADDR     bda;
     UINT16      conn_interval, conn_latency, conn_timeout;
     BOOLEAN     match = FALSE;
 
-    STREAM_TO_UINT8   (status, p);
+    ++p;
     STREAM_TO_UINT16   (handle, p);
     STREAM_TO_UINT8    (role, p);
     STREAM_TO_UINT8    (bda_type, p);
@@ -1526,11 +1528,11 @@
 
     handle = HCID_GET_HANDLE (handle);
 
-    BTM_TRACE_EVENT ("btm_ble_resolve_random_addr_master_cmpl");
+    BTM_TRACE_EVENT ("%s", __func__);
 
     if (match_rec)
     {
-        BTM_TRACE_ERROR("Random match");
+        LOG_INFO("%s matched and resolved random address", __func__);
         match = TRUE;
         match_rec->ble.active_addr_type = BTM_BLE_ADDR_RRA;
         memcpy(match_rec->ble.cur_rand_addr, bda, BD_ADDR_LEN);
@@ -1538,7 +1540,7 @@
     }
     else
     {
-        BTM_TRACE_ERROR("Random unmatch");
+        LOG_INFO("%s unable to match and resolve random address", __func__);
     }
 
     btm_ble_connected(bda, handle, HCI_ENCRYPT_MODE_DISABLED, role, bda_type, match);
@@ -1746,6 +1748,11 @@
                 p_dev_rec->sec_flags |= BTM_SEC_LE_AUTHENTICATED;
 
             case SMP_SEC_REQUEST_EVT:
+                if (event == SMP_SEC_REQUEST_EVT && btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
+                {
+                    BTM_TRACE_DEBUG("%s: Ignoring SMP Security request", __func__);
+                    break;
+                }
                 memcpy (btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN);
                 p_dev_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING;
                 btm_cb.pairing_flags |= BTM_PAIR_FLAGS_LE_ACTIVE;
@@ -1800,10 +1807,13 @@
                     BTM_TRACE_DEBUG ("btm_cb.pairing_bda %02x:%02x:%02x:%02x:%02x:%02x",
                                       btm_cb.pairing_bda[0], btm_cb.pairing_bda[1], btm_cb.pairing_bda[2],
                                       btm_cb.pairing_bda[3], btm_cb.pairing_bda[4], btm_cb.pairing_bda[5]);
-
-                    memset (btm_cb.pairing_bda, 0xff, BD_ADDR_LEN);
-                    btm_cb.pairing_state = BTM_PAIR_STATE_IDLE;
-                    btm_cb.pairing_flags = 0;
+                    /* Reset btm state only if the callback address matches pairing address*/
+                    if(memcmp(bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) == 0)
+                    {
+                        memset (btm_cb.pairing_bda, 0xff, BD_ADDR_LEN);
+                        btm_cb.pairing_state = BTM_PAIR_STATE_IDLE;
+                        btm_cb.pairing_flags = 0;
+                    }
                 }
                 break;
 
diff --git a/stack/btm/btm_ble_adv_filter.c b/stack/btm/btm_ble_adv_filter.c
index 0784b02..ea87383 100644
--- a/stack/btm/btm_ble_adv_filter.c
+++ b/stack/btm/btm_ble_adv_filter.c
@@ -16,6 +16,8 @@
  *
  ******************************************************************************/
 
+#define LOG_TAG "bt_btm_ble"
+
 #include <string.h>
 #include "bt_target.h"
 
@@ -28,6 +30,7 @@
 #include "hcidefs.h"
 #include "btm_ble_api.h"
 #include "vendor_ble.h"
+#include "device/include/controller.h"
 
 #define BTM_BLE_ADV_FILT_META_HDR_LENGTH 3
 #define BTM_BLE_ADV_FILT_FEAT_SELN_LEN 13
@@ -253,7 +256,8 @@
 
     if (evt_len < 3 || evt_len > 4)
     {
-        BTM_TRACE_ERROR("cannot interpret APCF callback status = %d, length = %d", status, evt_len);
+      BTM_TRACE_ERROR("%s cannot interpret APCF callback status = %d, length = %d",
+          __func__, status, evt_len);
         btm_ble_advfilt_deq_op_q(&action, &ocf, &cb_evt, &ref_value, &p_scan_cfg_cback,
                                  &p_filt_param_cback);
         return;
@@ -1301,9 +1305,6 @@
         btm_ble_adv_filt_cb.p_addr_filter_count =
             (tBTM_BLE_PF_COUNT*) GKI_getbuf( sizeof(tBTM_BLE_PF_COUNT) * cmn_ble_vsc_cb.max_filter);
     }
-
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
-        return;
 }
 
 /*******************************************************************************
diff --git a/stack/btm/btm_ble_batchscan.c b/stack/btm/btm_ble_batchscan.c
index b2181c8..7ed61dc 100644
--- a/stack/btm/btm_ble_batchscan.c
+++ b/stack/btm/btm_ble_batchscan.c
@@ -25,6 +25,7 @@
 #include "bt_utils.h"
 #include "btu.h"
 #include "btm_int.h"
+#include "device/include/controller.h"
 #include "hcimsgs.h"
 
 #if (BLE_INCLUDED == TRUE)
@@ -612,7 +613,7 @@
         ble_batchscan_cb.cur_state, ref_value, batch_scan_full_max, batch_scan_trunc_max,
         batch_scan_notify_threshold);
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
     BTM_BleGetVendorCapabilities(&cmn_ble_vsc_cb);
@@ -685,7 +686,7 @@
     BTM_TRACE_EVENT (" BTM_BleEnableBatchScan: %d, %d, %d, %d, %d, %d",
         scan_mode, scan_interval, scan_window, addr_type, discard_rule, ref_value);
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
     BTM_BleGetVendorCapabilities(&cmn_ble_vsc_cb);
@@ -759,7 +760,7 @@
     tBTM_BLE_VSC_CB cmn_ble_vsc_cb;
     BTM_TRACE_EVENT (" BTM_BleDisableBatchScan");
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
     BTM_BleGetVendorCapabilities(&cmn_ble_vsc_cb);
@@ -805,7 +806,7 @@
 
     BTM_TRACE_EVENT (" BTM_BleReadScanReports; %d, %d", scan_mode, ref_value);
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
     BTM_BleGetVendorCapabilities(&cmn_ble_vsc_cb);
@@ -863,7 +864,7 @@
 {
     tBTM_BLE_VSC_CB cmn_ble_vsc_cb;
     BTM_TRACE_EVENT (" BTM_BleTrackAdvertiser");
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
     BTM_BleGetVendorCapabilities(&cmn_ble_vsc_cb);
diff --git a/stack/btm/btm_ble_bgconn.c b/stack/btm/btm_ble_bgconn.c
index b33aa2e..2fabe23 100644
--- a/stack/btm/btm_ble_bgconn.c
+++ b/stack/btm/btm_ble_bgconn.c
@@ -705,7 +705,7 @@
     tBTM_BLE_CONN_REQ *p_req;
     BOOLEAN     rt = FALSE;
 
-    if ( btm_cb.ble_ctr_cb.conn_pending_q.count )
+    if (!GKI_queue_is_empty(&btm_cb.ble_ctr_cb.conn_pending_q))
     {
         p_req = (tBTM_BLE_CONN_REQ*)GKI_dequeue (&btm_cb.ble_ctr_cb.conn_pending_q);
 
diff --git a/stack/btm/btm_ble_gap.c b/stack/btm/btm_ble_gap.c
index 902c776..c3b140e 100644
--- a/stack/btm/btm_ble_gap.c
+++ b/stack/btm/btm_ble_gap.c
@@ -31,10 +31,9 @@
 #include "btm_int.h"
 #include "btm_ble_api.h"
 #include "btu.h"
+#include "device/include/controller.h"
 #include "hcimsgs.h"
-#if (GAP_INCLUDED == TRUE)
 #include "gap_api.h"
-#endif
 
 #if BLE_INCLUDED == TRUE
 #include "l2c_int.h"
@@ -44,6 +43,8 @@
 #include "gatt_int.h"
 
 #include "btm_ble_int.h"
+#define LOG_TAG "bt_btm_ble"
+#include "osi/include/log.h"
 
 #define BTM_BLE_NAME_SHORT                  0x01
 #define BTM_BLE_NAME_CMPL                   0x02
@@ -255,7 +256,7 @@
 
     BTM_TRACE_EVENT ("BTM_BleUpdateAdvFilterPolicy");
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return;
 
     if (p_cb->afp != adv_policy)
@@ -306,7 +307,7 @@
 
     BTM_TRACE_EVENT ("BTM_BleObserve : scan_type:%d",btm_cb.btm_inq_vars.scan_type);
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
     if (start)
@@ -380,7 +381,7 @@
     tBTM_BLE_INQ_CB *p_cb = &btm_cb.ble_ctr_cb.inq_var;
     UINT8 evt_type = p_cb->scan_rsp ? BTM_BLE_DISCOVER_EVT: BTM_BLE_NON_CONNECT_EVT;
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
 #ifdef  BTM_BLE_PC_ADV_TEST_MODE
@@ -494,7 +495,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB *p_cmn_vsc_cb)
+extern void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB *p_cmn_vsc_cb)
 {
     BTM_TRACE_DEBUG("BTM_BleGetVendorCapabilities");
 
@@ -515,7 +516,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK  *p_vsc_cback)
+extern void BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK  *p_vsc_cback)
 {
     if (TRUE == btm_cb.cmn_ble_vsc_cb.values_read)
         return;
@@ -610,7 +611,7 @@
 ** Returns          Max multi adv instance count
 **
 *******************************************************************************/
-BTM_API extern UINT8  BTM_BleMaxMultiAdvInstanceCount()
+extern UINT8  BTM_BleMaxMultiAdvInstanceCount()
 {
     return btm_cb.cmn_ble_vsc_cb.adv_inst_max < BTM_BLE_MULTI_ADV_MAX ?
         btm_cb.cmn_ble_vsc_cb.adv_inst_max : BTM_BLE_MULTI_ADV_MAX;
@@ -693,7 +694,7 @@
     BOOLEAN started = TRUE;
 
     BTM_TRACE_EVENT ("BTM_BleSetBgConnType ");
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return FALSE;
 
     if (btm_cb.ble_ctr_cb.bg_conn_type != bg_conn_type)
@@ -802,7 +803,7 @@
     tBTM_BLE_INQ_CB *p_cb = &btm_cb.ble_ctr_cb.inq_var;
 
     BTM_TRACE_EVENT ("BTM_BleSetConnMode is_directed = %d ", is_directed);
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
     p_cb->directed_conn = is_directed;
@@ -882,7 +883,7 @@
 
     BTM_TRACE_EVENT ("BTM_BleSetAdvParams");
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
     if (!BTM_BLE_VALID_PRAM(adv_int_min, BTM_BLE_ADV_INT_MIN, BTM_BLE_ADV_INT_MAX) ||
@@ -943,7 +944,7 @@
     tBTM_BLE_INQ_CB *p_cb = &btm_cb.ble_ctr_cb.inq_var;
 
     BTM_TRACE_EVENT ("BTM_BleReadAdvParams ");
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return ;
 
     *adv_int_min = p_cb->adv_interval_min;
@@ -976,7 +977,7 @@
     tBTM_BLE_INQ_CB *p_cb = &btm_cb.ble_ctr_cb.inq_var;
 
     BTM_TRACE_EVENT (" BTM_BleSetScanParams");
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return ;
 
     if (BTM_BLE_VALID_PRAM(scan_interval, BTM_BLE_SCAN_INT_MIN, BTM_BLE_SCAN_INT_MAX) &&
@@ -1018,7 +1019,7 @@
 
     BTM_TRACE_EVENT (" BTM_BleWriteScanRsp");
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
     memset(rsp_data, 0, BTM_BLE_AD_DATA_LEN);
@@ -1058,7 +1059,7 @@
 
     BTM_TRACE_EVENT ("BTM_BleWriteAdvData ");
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ILLEGAL_VALUE;
 
     memset(p_cb_data, 0, sizeof(tBTM_BLE_LOCAL_ADV_DATA));
@@ -1468,12 +1469,12 @@
         flag &= ~BTM_BLE_BREDR_NOT_SPT;
 
     /* if local controller support, mark both controller and host support in flag */
-    if (HCI_SIMUL_LE_BREDR_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+    if (controller_get_interface()->supports_simultaneous_le_bredr())
         flag |= (BTM_BLE_DMT_CONTROLLER_SPT|BTM_BLE_DMT_HOST_SPT);
     else
         flag &= ~(BTM_BLE_DMT_CONTROLLER_SPT|BTM_BLE_DMT_HOST_SPT);
 
-    BTM_TRACE_DEBUG("disc_mode %04x", disc_mode);
+    LOG_DEBUG("disc_mode %04x", disc_mode);
     /* update discoverable flag */
     if (disc_mode & BTM_BLE_LIMITED_DISCOVERABLE)
     {
@@ -1783,7 +1784,7 @@
 {
     tBTM_INQUIRY_VAR_ST      *p_inq = &btm_cb.btm_inq_vars;
 
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (!controller_get_interface()->supports_ble())
         return BTM_ERR_PROCESSING;
 
     if (p_cur &&
@@ -2527,12 +2528,12 @@
 
     if ((result = btm_ble_is_discoverable(bda, evt_type, p)) == 0)
     {
-        BTM_TRACE_ERROR("discard adv pkt");
+      LOG_WARN("%s device is no longer discoverable so discarding advertising packet pkt",
+          __func__);
         return;
     }
     if (!update)
         result &= ~BTM_BLE_INQ_RESULT;
-#if BTM_USE_INQ_RESULTS_FILTER == TRUE
     /* If the number of responses found and limited, issue a cancel inquiry */
     if (p_inq->inqparms.max_resps &&
         p_inq->inq_cmpl_info.num_resp == p_inq->inqparms.max_resps)
@@ -2551,12 +2552,9 @@
 
             btm_ble_stop_inquiry();
 
-#if BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE
             btm_acl_update_busy_level (BTM_BLI_INQ_DONE_EVT);
-#endif
         }
     }
-#endif
     /* background connection in selective connection mode */
     if (btm_cb.ble_ctr_cb.bg_conn_type == BTM_BLE_CONN_SELECTIVE)
     {
@@ -3134,7 +3132,9 @@
     mask = btm_le_state_combo_tbl[0][request_state - 1][0];
     offset = btm_le_state_combo_tbl[0][request_state-1][1];
 
-    if (!BTM_LE_STATES_SUPPORTED(btm_cb.devcb.le_supported_states, mask, offset))
+    const uint8_t *ble_supported_states = controller_get_interface()->get_ble_supported_states();
+
+    if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, mask, offset))
     {
         BTM_TRACE_ERROR("state requested not supported: %d", request_state);
         return rt;
@@ -3152,7 +3152,7 @@
 
             if (mask != 0 && offset != 0)
             {
-                if (!BTM_LE_STATES_SUPPORTED(btm_cb.devcb.le_supported_states, mask, offset))
+                if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, mask, offset))
                 {
                     rt = FALSE;
                     break;
diff --git a/stack/btm/btm_ble_int.h b/stack/btm/btm_ble_int.h
index 2512d33..4741ca7 100644
--- a/stack/btm/btm_ble_int.h
+++ b/stack/btm/btm_ble_int.h
@@ -413,11 +413,11 @@
 extern void btm_ble_refresh_rra(BD_ADDR pseudo_bda, BD_ADDR rra);
 
 #if BTM_BLE_CONFORMANCE_TESTING == TRUE
-BT_API extern void btm_ble_set_no_disc_if_pair_fail (BOOLEAN disble_disc);
-BT_API extern void btm_ble_set_test_mac_value (BOOLEAN enable, UINT8 *p_test_mac_val);
-BT_API extern void btm_ble_set_test_local_sign_cntr_value(BOOLEAN enable, UINT32 test_local_sign_cntr);
-BT_API extern void btm_set_random_address(BD_ADDR random_bda);
-BT_API extern void btm_ble_set_keep_rfu_in_auth_req(BOOLEAN keep_rfu);
+extern void btm_ble_set_no_disc_if_pair_fail (BOOLEAN disble_disc);
+extern void btm_ble_set_test_mac_value (BOOLEAN enable, UINT8 *p_test_mac_val);
+extern void btm_ble_set_test_local_sign_cntr_value(BOOLEAN enable, UINT32 test_local_sign_cntr);
+extern void btm_set_random_address(BD_ADDR random_bda);
+extern void btm_ble_set_keep_rfu_in_auth_req(BOOLEAN keep_rfu);
 #endif
 
 
diff --git a/stack/btm/btm_ble_multi_adv.c b/stack/btm/btm_ble_multi_adv.c
index 1ca6cd3..0ad97c4 100644
--- a/stack/btm/btm_ble_multi_adv.c
+++ b/stack/btm/btm_ble_multi_adv.c
@@ -17,7 +17,9 @@
  ******************************************************************************/
 
 #include <string.h>
+
 #include "bt_target.h"
+#include "device/include/controller.h"
 
 #if (BLE_INCLUDED == TRUE)
 #include "bt_types.h"
@@ -125,12 +127,14 @@
     switch (subcode)
     {
         case BTM_BLE_MULTI_ADV_ENB:
-        BTM_TRACE_DEBUG("BTM_BLE_MULTI_ADV_ENB status = %d", status);
-        if (status != HCI_SUCCESS)
         {
-            btm_multi_adv_cb.p_adv_inst[inst_id-1].inst_id = 0;
+            BTM_TRACE_DEBUG("BTM_BLE_MULTI_ADV_ENB status = %d", status);
+
+            /* Mark as not in use here, if instance cannot be enabled */
+            if (HCI_SUCCESS != status && BTM_BLE_MULTI_ADV_ENB_EVT == cb_evt)
+                btm_multi_adv_cb.p_adv_inst[inst_id-1].in_use = FALSE;
+            break;
         }
-        break;
 
         case BTM_BLE_MULTI_ADV_SET_PARAM:
         {
@@ -260,7 +264,7 @@
 #endif
     {
         UINT8_TO_STREAM  (pp, BLE_ADDR_PUBLIC);
-        BDADDR_TO_STREAM (pp, btm_cb.devcb.local_addr);
+        BDADDR_TO_STREAM (pp, controller_get_interface()->get_address()->address);
     }
 
     BTM_TRACE_EVENT (" btm_ble_multi_adv_set_params,Min %d, Max %d,adv_type %d",
@@ -325,7 +329,9 @@
     UINT8           param[BTM_BLE_MULTI_ADV_SET_RANDOM_ADDR_LEN], *pp = param;
     tBTM_STATUS     rt;
 
-    BTM_TRACE_EVENT (" btm_ble_multi_adv_set_random_addr");
+    BTM_TRACE_EVENT ("%s-BD_ADDR:%02x-%02x-%02x-%02x-%02x-%02x,inst_id:%d",
+                      __FUNCTION__, random_addr[5], random_addr[4], random_addr[3], random_addr[2],
+                      random_addr[1], random_addr[0], p_inst->inst_id);
 
     memset(param, 0, BTM_BLE_MULTI_ADV_SET_RANDOM_ADDR_LEN);
 
@@ -408,12 +414,13 @@
             p_inst->rpa[5] = output.param_buf[0];
             p_inst->rpa[4] = output.param_buf[1];
             p_inst->rpa[3] = output.param_buf[2];
+        }
 
-            if (p_inst->inst_id != 0 && (p_inst->inst_id < BTM_BleMaxMultiAdvInstanceCount()))
-            {
-                /* set it to controller */
-                btm_ble_multi_adv_write_rpa(p_inst, p_inst->rpa);
-            }
+        if (p_inst->inst_id != BTM_BLE_MULTI_ADV_DEFAULT_STD &&
+            p_inst->inst_id < BTM_BleMaxMultiAdvInstanceCount())
+        {
+            /* set it to controller */
+            btm_ble_multi_adv_write_rpa(p_inst, p_inst->rpa);
         }
     }
 #endif
@@ -468,7 +475,7 @@
 {
     tBTM_BLE_MULTI_ADV_INST *p_inst = &btm_multi_adv_cb.p_adv_inst[inst_id - 1];
 
-    if (p_inst->inst_id != 0)
+    if (TRUE == p_inst->in_use)
     {
         if (p_inst->adv_evt != BTM_BLE_CONNECT_DIR_EVT)
             btm_ble_enable_multi_adv (TRUE, p_inst->inst_id, 0);
@@ -476,7 +483,7 @@
           /* mark directed adv as disabled if adv has been stopped */
         {
             (p_inst->p_cback)(BTM_BLE_MULTI_ADV_DISABLE_EVT,p_inst->inst_id,p_inst->p_ref,0);
-             p_inst->inst_id = 0;
+             p_inst->in_use = FALSE;
         }
      }
 }
@@ -499,8 +506,13 @@
 
     for (i = 0; i <  BTM_BleMaxMultiAdvInstanceCount() - 1; i ++, p_inst++)
     {
+        p_inst->in_use = FALSE;
         if (enable)
+        {
+            /* Setup the instance ID before configuring the RPA */
+            p_inst->inst_id = i + 1;
             btm_ble_multi_adv_configure_rpa (p_inst);
+        }
         else
             btu_stop_timer_oneshot(&p_inst->raddr_timer_ent);
     }
@@ -544,10 +556,9 @@
 
     for (i = 0; i <  BTM_BleMaxMultiAdvInstanceCount() - 1; i ++, p_inst++)
     {
-        if (p_inst->inst_id == 0)
+        if (FALSE == p_inst->in_use)
         {
-            p_inst->inst_id = i + 1;
-
+            p_inst->in_use = TRUE;
             /* configure adv parameter */
             if (p_params)
                 rt = btm_ble_multi_adv_set_params(p_inst, p_params, 0);
@@ -570,7 +581,7 @@
 
             if (BTM_CMD_STARTED != rt)
             {
-                p_inst->inst_id = 0;
+                p_inst->in_use = FALSE;
                 BTM_TRACE_ERROR("BTM_BleEnableAdvInstance failed");
             }
             break;
@@ -609,7 +620,7 @@
         inst_id != BTM_BLE_MULTI_ADV_DEFAULT_STD &&
         p_params != NULL)
     {
-        if (p_inst->inst_id == 0)
+        if (FALSE == p_inst->in_use)
         {
             BTM_TRACE_DEBUG("adv instance %d is not active", inst_id);
             return BTM_WRONG_MODE;
@@ -715,7 +726,7 @@
          {
             btm_ble_multi_adv_configure_rpa(&btm_multi_adv_cb.p_adv_inst[inst_id-1]);
             btu_stop_timer(&btm_multi_adv_cb.p_adv_inst[inst_id-1].raddr_timer_ent);
-            btm_multi_adv_cb.p_adv_inst[inst_id-1].inst_id = 0;
+            btm_multi_adv_cb.p_adv_inst[inst_id-1].in_use = FALSE;
          }
      }
     return rt;
@@ -732,7 +743,7 @@
 void btm_ble_multi_adv_vse_cback(UINT8 len, UINT8 *p)
 {
     UINT8   sub_event;
-    UINT8   adv_inst, reason, conn_handle, idx;
+    UINT8   adv_inst, conn_handle, idx;
 
     /* Check if this is a BLE RSSI vendor specific event */
     STREAM_TO_UINT8(sub_event, p);
@@ -742,7 +753,7 @@
     if ((sub_event == HCI_VSE_SUBCODE_BLE_MULTI_ADV_ST_CHG) && (len >= 4))
     {
         STREAM_TO_UINT8(adv_inst, p);
-        STREAM_TO_UINT8(reason, p);
+        ++p;
         STREAM_TO_UINT16(conn_handle, p);
 
         if ((idx = btm_handle_to_acl_index(conn_handle)) != MAX_L2CAP_LINKS)
diff --git a/stack/btm/btm_dev.c b/stack/btm/btm_dev.c
index f60282f..d3d0481 100644
--- a/stack/btm/btm_dev.c
+++ b/stack/btm/btm_dev.c
@@ -28,6 +28,7 @@
 #include <stddef.h>
 
 #include "bt_types.h"
+#include "device/include/controller.h"
 #include "gki.h"
 #include "hcimsgs.h"
 #include "btu.h"
@@ -295,15 +296,6 @@
         /* update conn params, use default value for background connection params */
         memset(&p_dev_rec->conn_params, 0xff, sizeof(tBTM_LE_CONN_PRAMS));
 #endif
-
-#if BTM_INQ_GET_REMOTE_NAME == TRUE
-        if (p_inq_info->remote_name_state == BTM_INQ_RMT_NAME_DONE)
-        {
-            BCM_STRNCPY_S ((char *)p_dev_rec->sec_bd_name, sizeof (p_dev_rec->sec_bd_name),
-                     (char *)p_inq_info->remote_name, BTM_MAX_REM_BD_NAME_LEN);
-            p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN;
-        }
-#endif
     }
     else
     {
@@ -371,7 +363,7 @@
         return(FALSE);
 #endif
     p_dev_rec = btm_find_dev (bd_addr);
-    if (p_dev_rec && HCI_SWITCH_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+    if (p_dev_rec && controller_get_interface()->supports_master_slave_role_switch())
     {
         if (HCI_SWITCH_SUPPORTED(p_dev_rec->features[HCI_EXT_FEATURES_PAGE_0]))
         {
diff --git a/stack/btm/btm_devctl.c b/stack/btm/btm_devctl.c
index f001c5f..03ed726 100644
--- a/stack/btm/btm_devctl.c
+++ b/stack/btm/btm_devctl.c
@@ -23,6 +23,7 @@
  *
  ******************************************************************************/
 
+#include <assert.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
@@ -30,40 +31,25 @@
 
 #include "bt_types.h"
 #include "bt_utils.h"
-#include "hcimsgs.h"
-#include "btu.h"
 #include "btm_int.h"
+#include "btu.h"
+#include "device/include/controller.h"
+#include "hci_layer.h"
+#include "hcimsgs.h"
 #include "l2c_int.h"
+#include "btcore/include/module.h"
+#include "osi/include/thread.h"
 
 #if BLE_INCLUDED == TRUE
 #include "gatt_int.h"
-
 #endif /* BLE_INCLUDED */
 
-/* BTM_APP_DEV_INIT should be defined if additional controller initialization is
-**      needed by the application to be performed after the HCI reset
-*/
-#ifdef BTM_APP_DEV_INIT
-extern void BTM_APP_DEV_INIT(void);
-#endif
-
-#ifdef BTA_PRM_CHECK_FW_VER
-extern BOOLEAN BTA_PRM_CHECK_FW_VER(UINT8 *p);
-#endif
-
-#ifndef TT_DEV_RESET_MASK
-#define TT_DEV_RESET_MASK 0xff
-#endif
+extern thread_t *bt_workqueue_thread;
 
 /********************************************************************************/
 /*                 L O C A L    D A T A    D E F I N I T I O N S                */
 /********************************************************************************/
 
-/* The default class of device. */
-#ifndef BTM_INIT_CLASS_OF_DEVICE
-#define BTM_INIT_CLASS_OF_DEVICE    "\x00\x1F\x00"
-#endif
-
 #ifndef BTM_DEV_RESET_TIMEOUT
 #define BTM_DEV_RESET_TIMEOUT   4
 #endif
@@ -73,59 +59,11 @@
 
 #define BTM_INFO_TIMEOUT        5   /* 5 seconds for info response */
 
-/* After Reset a timeout can be specified in the target.h for specific targets
- * that may require additional time to reset
- * otherwise no timeout is required
-*/
-#ifndef BTM_AFTER_RESET_TIMEOUT
-#define BTM_AFTER_RESET_TIMEOUT 0
-#endif
-
-/* Internal baseband so the parameters such as local features, version etc. are known
-so there is no need to issue HCI commands and wait for responses at BTM initialization */
-#ifndef BTM_INTERNAL_BB
-#define BTM_INTERNAL_BB FALSE
-#endif
-
-/* The local version information in the format specified in the HCI read local version
-response message */
-#ifndef BTM_INTERNAL_LOCAL_VER
-#define BTM_INTERNAL_LOCAL_VER {0x00, 0x01, 0x05, 0x81, 0x01, 0x30, 0x00, 0x40, 0x8D}
-#endif
-
-/* The local features information in the format specified in the HCI read local features
-response message */
-#ifndef BTM_INTERNAL_LOCAL_FEA
-#define BTM_INTERNAL_LOCAL_FEA {0x00, 0xFF, 0xF9, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}
-#endif
-
-#ifndef BTM_SET_DEV_NAME_UPON_RESET
-#define BTM_SET_DEV_NAME_UPON_RESET TRUE
-#endif
-
-/* host SCO buffer size */
-#ifndef BTM_SCO_HOST_BUF_SIZE
-#define BTM_SCO_HOST_BUF_SIZE       0xff
-#endif
-
 /********************************************************************************/
 /*              L O C A L    F U N C T I O N     P R O T O T Y P E S            */
 /********************************************************************************/
-static void btm_dev_reset (void);
-static void btm_after_reset_hold_complete (void);
-static void btm_continue_reset (void);
 
-static void btm_get_local_ext_features (UINT8 page_number);
 static void btm_decode_ext_features_page (UINT8 page_number, const BD_FEATURES p_features);
-static void btm_read_all_lmp_features_complete (UINT8 max_page_number);
-static void btm_set_lmp_features_host_may_support (UINT8 max_page_number);
-static void btm_get_local_features (void);
-static void btm_issue_host_support_for_lmp_features (void);
-static void btm_read_local_supported_cmds (UINT8 local_controller_id);
-
-#if BLE_INCLUDED == TRUE
-static void btm_read_ble_local_supported_features (void);
-#endif
 
 /*******************************************************************************
 **
@@ -149,7 +87,6 @@
 
     btm_cb.devcb.reset_timer.param  = (TIMER_PARAM_TYPE)TT_DEV_RESET;
     btm_cb.devcb.rln_timer.param    = (TIMER_PARAM_TYPE)TT_DEV_RLN;
-    btm_cb.devcb.rlinkp_timer.param = (TIMER_PARAM_TYPE)TT_DEV_RLNKP;
 
     btm_cb.btm_acl_pkt_types_supported = BTM_ACL_PKT_TYPES_MASK_DH1 + BTM_ACL_PKT_TYPES_MASK_DM1 +
                                          BTM_ACL_PKT_TYPES_MASK_DH3 + BTM_ACL_PKT_TYPES_MASK_DM3 +
@@ -161,23 +98,6 @@
                                          BTM_SCO_PKT_TYPES_MASK_EV3 +
                                          BTM_SCO_PKT_TYPES_MASK_EV4 +
                                          BTM_SCO_PKT_TYPES_MASK_EV5;
-
-    btm_cb.first_disabled_channel = 0xff; /* To allow disabling 0th channel alone */
-    btm_cb.last_disabled_channel = 0xff; /* To allow disabling 0th channel alone */
-
-#if (BTM_AUTOMATIC_HCI_RESET == TRUE)
-
-#if (BTM_FIRST_RESET_DELAY > 0)
-    btm_cb.devcb.state = BTM_DEV_STATE_WAIT_RESET_CMPLT;
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL, BTM_FIRST_RESET_DELAY);
-#else
-    btm_dev_reset();
-#endif
-
-#else
-   BTM_TRACE_EVENT ("BTM_AUTOMATIC_HCI_RESET is FALSE, so skip btm reset for now");
-#endif
-
 }
 
 
@@ -208,15 +128,6 @@
             (*p_cb)((void *) NULL);
     }
 
-    if (btm_cb.devcb.p_rlinkp_cmpl_cb)
-    {
-        p_cb = btm_cb.devcb.p_rlinkp_cmpl_cb;
-        btm_cb.devcb.p_rlinkp_cmpl_cb = NULL;
-
-        if (p_cb)
-            (*p_cb)((void *) &status);
-    }
-
     if (btm_cb.devcb.p_rssi_cmpl_cb)
     {
         p_cb = btm_cb.devcb.p_rssi_cmpl_cb;
@@ -227,73 +138,71 @@
     }
 }
 
+static void reset_complete(void *result) {
+  assert(result == FUTURE_SUCCESS);
+  const controller_t *controller = controller_get_interface();
 
+  /* Tell L2CAP that all connections are gone */
+  l2cu_device_reset ();
 
-/*******************************************************************************
-**
-** Function         btm_dev_absent
-**
-** Description      This function is called by when it is detected that the
-**                  device is not connected any more.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_dev_absent (void)
-{
-    btm_cb.devcb.state = BTM_DEV_STATE_WAIT_RESET_CMPLT;
+  /* Clear current security state */
+  for (int devinx = 0; devinx < BTM_SEC_MAX_DEVICE_RECORDS; devinx++) {
+    btm_cb.sec_dev_rec[devinx].sec_state = BTM_SEC_STATE_IDLE;
+  }
 
-    btm_db_reset ();
-    btm_inq_db_reset();
+  /* After the reset controller should restore all parameters to defaults. */
+  btm_cb.btm_inq_vars.inq_counter       = 1;
+  btm_cb.btm_inq_vars.inq_scan_window   = HCI_DEF_INQUIRYSCAN_WINDOW;
+  btm_cb.btm_inq_vars.inq_scan_period   = HCI_DEF_INQUIRYSCAN_INTERVAL;
+  btm_cb.btm_inq_vars.inq_scan_type     = HCI_DEF_SCAN_TYPE;
 
-    /* If anyone wants device status notifications, give him one */
-    btm_report_device_status (BTM_DEV_STATUS_DOWN);
+  btm_cb.btm_inq_vars.page_scan_window  = HCI_DEF_PAGESCAN_WINDOW;
+  btm_cb.btm_inq_vars.page_scan_period  = HCI_DEF_PAGESCAN_INTERVAL;
+  btm_cb.btm_inq_vars.page_scan_type    = HCI_DEF_SCAN_TYPE;
 
-    btu_stop_timer (&btm_cb.devcb.reset_timer);
+#if (BLE_INCLUDED == TRUE)
+  btm_cb.ble_ctr_cb.conn_state = BLE_CONN_IDLE;
+  btm_cb.ble_ctr_cb.bg_dev_num = 0;
+  btm_cb.ble_ctr_cb.bg_conn_type = BTM_BLE_CONN_NONE;
+  btm_cb.ble_ctr_cb.p_select_cback = NULL;
+  memset(&btm_cb.ble_ctr_cb.bg_dev_list, 0, (sizeof(tBTM_LE_BG_CONN_DEV)*BTM_BLE_MAX_BG_CONN_DEV_NUM));
+  gatt_reset_bgdev_list();
+  btm_ble_multi_adv_init();
+#endif
+
+  btm_pm_reset();
+
+  l2c_link_processs_num_bufs(controller->get_acl_buffer_count_classic());
+#if (BLE_INCLUDED == TRUE)
+  if (controller->supports_ble()) {
+    l2c_link_processs_ble_num_bufs(controller->get_acl_buffer_count_ble());
+  }
+#endif
+
+  BTM_SetPinType (btm_cb.cfg.pin_type, btm_cb.cfg.pin_code, btm_cb.cfg.pin_code_len);
+
+  for (int i = 0; i <= controller->get_last_features_classic_index(); i++) {
+    btm_decode_ext_features_page(i, controller->get_features_classic(i)->as_array);
+  }
+
+  btm_report_device_status(BTM_DEV_STATUS_UP);
 }
 
+// TODO(zachoverflow): remove this function
+void BTM_DeviceReset (UNUSED_ATTR tBTM_CMPL_CB *p_cb) {
+  /* Flush all ACL connections */
+  btm_acl_device_down();
 
-/*******************************************************************************
-**
-** Function         BTM_DeviceReset
-**
-** Description      This function is called to reset the HCI.  Callback function
-**                  if provided is called when startup of the device is
-**                  completed.
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTM_DeviceReset (tBTM_CMPL_CB *p_cb)
-{
-    tBTM_STATUS status;
+  /* Clear the callback, so application would not hang on reset */
+  btm_db_reset();
 
-    /* If device is already resetting, do not allow another */
-    if ((!btm_cb.devcb.p_reset_cmpl_cb) || (btm_cb.devcb.p_reset_cmpl_cb == p_cb))
-    {
-        /* Flush all ACL connections */
-        btm_acl_device_down();
-
-        /* Clear the callback, so application would not hang on reset */
-        btm_db_reset();
-
-        /* Save address of the completion routine, if provided */
-        btm_cb.devcb.p_reset_cmpl_cb = p_cb;
-
-        btm_dev_reset ();
-    }
-    else
-    {
-        /* pass an error to the bad callback, another one was already provided */
-        if (p_cb)
-        {
-            status = BTM_ILLEGAL_VALUE;
-            p_cb (&status);
-        }
-    }
+  module_start_up_callbacked_wrapper(
+    get_module(CONTROLLER_MODULE),
+    bt_workqueue_thread,
+    reset_complete
+  );
 }
 
-
 /*******************************************************************************
 **
 ** Function         BTM_IsDeviceUp
@@ -305,286 +214,7 @@
 *******************************************************************************/
 BOOLEAN BTM_IsDeviceUp (void)
 {
-    return ((BOOLEAN) (btm_cb.devcb.state == BTM_DEV_STATE_READY));
-}
-
-/*******************************************************************************
-**
-** Function         BTM_SetAfhChannels
-**
-** Description      This function is called disable channels
-**
-** Returns          tBTM_STATUS
-**
-*******************************************************************************/
-tBTM_STATUS BTM_SetAfhChannels (UINT8 first, UINT8 last)
-{
-    BTM_TRACE_API ("BTM_SetAfhChannels first: %d (%d) last: %d (%d)",
-                       first, btm_cb.first_disabled_channel, last,
-                       btm_cb.last_disabled_channel);
-
-    /* Make sure the local device supports the feature before sending */
-    if ((!HCI_LMP_AFH_CAP_MASTR_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))   &&
-        (!HCI_LMP_AFH_CLASS_SLAVE_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0])) &&
-        (!HCI_LMP_AFH_CLASS_MASTR_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0])))
-        return (BTM_MODE_UNSUPPORTED);
-
-    if (!BTM_IsDeviceUp())
-        return (BTM_WRONG_MODE);
-
-    if ((btm_cb.first_disabled_channel != first)
-     || (btm_cb.last_disabled_channel  != last))
-    {
-        if (btsnd_hcic_set_afh_channels (first, last))
-        {
-            btm_cb.first_disabled_channel = first;
-            btm_cb.last_disabled_channel  = last;
-        }
-        else
-            return (BTM_NO_RESOURCES);
-    }
-    return (BTM_SUCCESS);
-}
-
-/*******************************************************************************
-**
-** Function         BTM_SetAfhChannelAssessment
-**
-** Description      This function is called to set the channel assessment mode on or off
-**
-** Returns          none
-**
-*******************************************************************************/
-tBTM_STATUS BTM_SetAfhChannelAssessment (BOOLEAN enable_or_disable)
-{
-    /* whatever app wants if device is not 1.2 scan type should be STANDARD */
-    if (!HCI_LMP_AFH_CAP_SLAVE_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-     return (BTM_MODE_UNSUPPORTED);
-
-    if (!btsnd_hcic_write_afh_channel_assessment_mode (enable_or_disable))
-        return (BTM_NO_RESOURCES);
-
-    return (BTM_SUCCESS);
-}
-
-/*******************************************************************************
-**
-** Function         BTM_ContinueReset
-**
-** Description      This function is called by the application to continue
-**                  initialization after the application has completed its
-**                  vendor specific sequence.  It is only used when
-**                  BTM_APP_DEV_INIT is defined in target.h.
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTM_ContinueReset (void)
-{
-#ifdef BTM_APP_DEV_INIT
-    btm_continue_reset();
-#endif
-}
-
-/*******************************************************************************
-**
-** Function         btm_dev_reset
-**
-** Description      Local function called to send a reset command
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btm_dev_reset (void)
-{
-    btm_cb.devcb.state = BTM_DEV_STATE_WAIT_RESET_CMPLT;
-
-    /* flush out the command complete queue and command transmit queue */
-    btu_hcif_flush_cmd_queue();
-
-    /* Start reset timer.  When timer expires we will send first command */
-    /* from the setup sequence */
-
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL,
-                     BTM_DEV_RESET_TIMEOUT);
-    btsnd_hcic_reset (LOCAL_BR_EDR_CONTROLLER_ID);
-}
-
-
-/*******************************************************************************
-**
-** Function         btm_get_hci_buf_size
-**
-** Description      Local function called to send a read buffer size command
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_get_hci_buf_size (void)
-{
-
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL, BTM_DEV_REPLY_TIMEOUT);
-
-    /* Send a Read Buffer Size message to the Host Controller. */
-    btsnd_hcic_read_buffer_size ();
-
-}
-#if BLE_INCLUDED == TRUE
-/*******************************************************************************
-**
-** Function         btm_read_ble_wl_size
-**
-** Description      Local function called to send a read BLE buffer size command
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_ble_wl_size(void)
-{
-    BTM_TRACE_DEBUG("btm_read_ble_wl_size ");
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL, BTM_DEV_REPLY_TIMEOUT);
-
-    /* Send a Read Buffer Size message to the Host Controller. */
-    btsnd_hcic_ble_read_white_list_size();
-}
-/*******************************************************************************
-**
-** Function         btm_get_ble_buffer_size
-**
-** Description      Local function called to send a read BLE buffer size command
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_get_ble_buffer_size(void)
-{
-    BTM_TRACE_DEBUG("btm_get_ble_buffer_size ");
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL, BTM_DEV_REPLY_TIMEOUT);
-
-    /* Send a Read Buffer Size message to the Host Controller. */
-    btsnd_hcic_ble_read_buffer_size ();
-}
-
-/*******************************************************************************
-**
-** Function         btm_read_ble_local_supported_features
-**
-** Description      Local function called to send a read BLE local supported
-**                  features command
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btm_read_ble_local_supported_features(void)
-{
-    BTM_TRACE_DEBUG("btm_read_ble_local_supported_features ");
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL, BTM_DEV_REPLY_TIMEOUT);
-
-    /* Send a Read Local Supported Features message to the Host Controller. */
-    btsnd_hcic_ble_read_local_spt_feat ();
-}
-
-/*******************************************************************************
-**
-** Function         btm_read_ble_local_supported_states
-**
-** Description      Local function called to send a read BLE local supported
-**                  features command
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btm_read_ble_local_supported_states(void)
-{
-    BTM_TRACE_DEBUG("btm_read_ble_local_supported_states ");
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL, BTM_DEV_REPLY_TIMEOUT);
-
-    /* Send a Read Local Supported states message to the Host Controller. */
-    btsnd_hcic_ble_read_supported_states ();
-}
-#endif
-/*******************************************************************************
-**
-** Function         btm_get_local_version
-**
-** Description      Local function called to send a read local version to controller
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_get_local_version (void)
-{
-
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL, BTM_DEV_REPLY_TIMEOUT);
-
-    /* Send a Read Local Version message to the Host Controller. */
-    btsnd_hcic_read_local_ver (LOCAL_BR_EDR_CONTROLLER_ID);
-    btsnd_hcic_read_bd_addr ();
-
-#if BTM_PWR_MGR_INCLUDED == TRUE
-        btm_pm_reset();
-#endif
-
-}
-
-/*******************************************************************************
-**
-** Function         btm_read_local_supported_cmds
-**
-** Description      Local function called to send a read local supported commands
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btm_read_local_supported_cmds (UINT8 local_controller_id)
-{
-    BTM_TRACE_DEBUG("Start reading local supported commands");
-
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL, BTM_DEV_REPLY_TIMEOUT);
-
-    btsnd_hcic_read_local_supported_cmds(local_controller_id);
-}
-
-/*******************************************************************************
-**
-** Function         btm_get_local_features
-**
-** Description      Local function called to send a read local features
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btm_get_local_features (void)
-{
-    /* If this BT controller supports Read Extended Feature */
-    if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_2_0)
-    {
-        btm_get_local_ext_features(HCI_EXT_FEATURES_PAGE_0);
-    }
-    /* else, if this is a very old BT controller */
-    else
-{
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL, BTM_DEV_REPLY_TIMEOUT);
-
-        /* Just read the basic features (legacy HCI command) */
-    btsnd_hcic_read_local_features ();
-}
-}
-
-/*******************************************************************************
-**
-** Function         btm_get_local_ext_features
-**
-** Description      Local function called to send a read local extended features
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btm_get_local_ext_features (UINT8 page_number)
-{
-    btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL, BTM_DEV_REPLY_TIMEOUT);
-
-    btsnd_hcic_read_local_ext_features(page_number);
+    return controller_get_interface()->get_is_ready();
 }
 
 /*******************************************************************************
@@ -600,12 +230,7 @@
 {
     TIMER_PARAM_TYPE timer_type = (TIMER_PARAM_TYPE)p_tle->param;
 
-    if ((timer_type & TT_DEV_RESET_MASK) == TT_DEV_RESET)
-    {
-        /* Call device reset as long as there is timeout*/
-        btm_dev_reset();
-    }
-    else if (timer_type == (TIMER_PARAM_TYPE)TT_DEV_RLN)
+    if (timer_type == (TIMER_PARAM_TYPE)TT_DEV_RLN)
     {
         tBTM_CMPL_CB  *p_cb = btm_cb.devcb.p_rln_cmpl_cb;
 
@@ -618,364 +243,6 @@
 
 /*******************************************************************************
 **
-** Function         btm_reset_complete
-**
-** Description      This function is called when command complete for HCI_Reset
-**                  is received.  It does not make sense to send next command
-**                  because device is resetting after command complete is
-**                  received.  Just start timer and set required state.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_reset_complete (void)
-{
-    int devinx;
-
-    BTM_TRACE_EVENT ("btm_reset_complete");
-
-    /* Handle if btm initiated the reset */
-    if (btm_cb.devcb.state == BTM_DEV_STATE_WAIT_RESET_CMPLT)
-    {
-        /* Tell L2CAP that all connections are gone */
-        l2cu_device_reset ();
-
-        /* Clear current security state */
-        for (devinx = 0; devinx < BTM_SEC_MAX_DEVICE_RECORDS; devinx++)
-        {
-            btm_cb.sec_dev_rec[devinx].sec_state = BTM_SEC_STATE_IDLE;
-        }
-
-        /* After the reset controller should restore all parameters to defaults. */
-        btm_cb.btm_inq_vars.inq_counter       = 1;
-        btm_cb.btm_inq_vars.inq_scan_window   = HCI_DEF_INQUIRYSCAN_WINDOW;
-        btm_cb.btm_inq_vars.inq_scan_period   = HCI_DEF_INQUIRYSCAN_INTERVAL;
-        btm_cb.btm_inq_vars.inq_scan_type     = HCI_DEF_SCAN_TYPE;
-
-        btm_cb.btm_inq_vars.page_scan_window  = HCI_DEF_PAGESCAN_WINDOW;
-        btm_cb.btm_inq_vars.page_scan_period  = HCI_DEF_PAGESCAN_INTERVAL;
-        btm_cb.btm_inq_vars.page_scan_type    = HCI_DEF_SCAN_TYPE;
-
-#if (BTM_AFTER_RESET_TIMEOUT > 0)
-        btu_start_timer (&btm_cb.devcb.reset_timer, BTU_TTYPE_BTM_DEV_CTL,
-                         BTM_AFTER_RESET_TIMEOUT);
-#else
-        btm_cb.devcb.state = BTM_DEV_STATE_WAIT_AFTER_RESET;
-        btm_after_reset_hold_complete();
-#endif
-
-#if (BLE_INCLUDED == TRUE)
-     btm_cb.ble_ctr_cb.conn_state = BLE_CONN_IDLE;
-     btm_cb.ble_ctr_cb.bg_dev_num = 0;
-     btm_cb.ble_ctr_cb.bg_conn_type = BTM_BLE_CONN_NONE;
-     btm_cb.ble_ctr_cb.p_select_cback = NULL;
-     memset(&btm_cb.ble_ctr_cb.bg_dev_list, 0, (sizeof(tBTM_LE_BG_CONN_DEV)*BTM_BLE_MAX_BG_CONN_DEV_NUM));
-     gatt_reset_bgdev_list();
-#endif
-    }
-}
-
-/*******************************************************************************
-**
-** Function         btm_continue_reset
-**
-** Description      This function is called when wait period expired after
-**                  device reset or called by the application to continue
-**                  initialization after the application has completed its
-**                  vendor specific sequence.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_continue_reset (void)
-{
-
-    /* Reinitialize the default class of device */
-#if BTM_INTERNAL_BB == TRUE
-    btsnd_hcic_read_bd_addr ();
-#if BTM_PWR_MGR_INCLUDED == TRUE
-    btm_pm_reset();
-#endif
-#endif
-
-    btm_get_hci_buf_size ();
-
-    /* default device class */
-    BTM_SetDeviceClass((UINT8 *) BTM_INIT_CLASS_OF_DEVICE);
-
-#if (BTM_MAX_LOC_BD_NAME_LEN > 0) && (BTM_SET_DEV_NAME_UPON_RESET == TRUE)
-    BTM_SetLocalDeviceName(btm_cb.cfg.bd_name);
-#endif
-
-    BTM_SetPinType (btm_cb.cfg.pin_type, btm_cb.cfg.pin_code, btm_cb.cfg.pin_code_len);
-}
-
-/*******************************************************************************
-**
-** Function         btm_after_reset_hold_complete
-**
-** Description      This function is called when wait period expired after
-**                  device reset.  Continue intitialization
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_after_reset_hold_complete (void)
-{
-#ifdef BTM_APP_DEV_INIT
-    btu_stop_timer(&btm_cb.devcb.reset_timer);
-    BTM_APP_DEV_INIT();
-#else
-    btm_continue_reset();
-#endif
-}
-
-
-/*******************************************************************************
-**
-** Function         btm_read_hci_buf_size_complete
-**
-** Description      This function is called when command complete for
-**                  get HCI buffer size is received.  Start timer and send
-**                  read local features request
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_hci_buf_size_complete (UINT8 *p, UINT16 evt_len)
-{
-    UINT8       status;
-    UINT8       lm_sco_buf_size;
-    UINT16      lm_num_acl_bufs;
-    UINT16      lm_num_sco_bufs;
-    UINT16      acl_buf_size;
-    UNUSED(evt_len);
-
-    STREAM_TO_UINT8  (status, p);
-    if (status == HCI_SUCCESS)
-    {
-        STREAM_TO_UINT16 (btu_cb.hcit_acl_data_size, p);
-        STREAM_TO_UINT8  (lm_sco_buf_size,   p);
-        STREAM_TO_UINT16 (lm_num_acl_bufs,   p);
-        STREAM_TO_UINT16 (lm_num_sco_bufs,   p);
-
-        btu_cb.hcit_acl_pkt_size = btu_cb.hcit_acl_data_size + HCI_DATA_PREAMBLE_SIZE;
-
-        l2c_link_processs_num_bufs (lm_num_acl_bufs);
-
-#if BTM_ACL_BUF_SIZE > 0
-        acl_buf_size = (BTM_ACL_BUF_SIZE < L2CAP_MTU_SIZE) ? BTM_ACL_BUF_SIZE : L2CAP_MTU_SIZE;
-#else
-        acl_buf_size = L2CAP_MTU_SIZE;
-#endif
-        /* Tell the controller what our buffer sizes are. ?? Need SCO info */
-        btsnd_hcic_set_host_buf_size (acl_buf_size, BTM_SCO_HOST_BUF_SIZE, L2CAP_HOST_FC_ACL_BUFS, 10);
-
-#if L2CAP_HOST_FLOW_CTRL == TRUE
-        btsnd_hcic_set_host_flow_ctrl (HCI_HOST_FLOW_CTRL_ACL_ON);
-#endif
-    }
-
-    /* Set the device into connectable and/or discoverable mode (if configured to do so) */
-#if BTM_IS_CONNECTABLE == TRUE
-    (void) BTM_SetConnectability (BTM_CONNECTABLE, BTM_DEFAULT_CONN_WINDOW, BTM_DEFAULT_CONN_INTERVAL);
-#endif
-
-#if BTM_IS_DISCOVERABLE == TRUE
-    (void) BTM_SetDiscoverability (BTM_DEFAULT_DISC_MODE, BTM_DEFAULT_DISC_WINDOW, BTM_DEFAULT_DISC_INTERVAL);
-#endif
-
-#if BTM_INTERNAL_BB == TRUE
-    {
-        UINT8 buf[9] = BTM_INTERNAL_LOCAL_VER;
-        btm_read_local_version_complete( buf, 9 );
-    }
-#else
-    btm_get_local_version ();
-#endif
-}
-
-#if (BLE_INCLUDED == TRUE)
-/*******************************************************************************
-**
-** Function         btm_read_ble_buf_size_complete
-**
-** Description      This function is called when command complete for
-**                  get HCI buffer size is received.  Start timer and send
-**                  read local supported features request
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_ble_buf_size_complete (UINT8 *p, UINT16 evt_len)
-{
-    UINT8       status;
-    UINT16      lm_num_le_bufs;
-    UNUSED(evt_len);
-
-    BTM_TRACE_DEBUG("btm_read_ble_buf_size_complete ");
-    STREAM_TO_UINT8  (status, p);
-    if (status == HCI_SUCCESS)
-    {
-        STREAM_TO_UINT16 (btu_cb.hcit_ble_acl_data_size, p);
-        STREAM_TO_UINT8 (lm_num_le_bufs,   p);
-
-        if (btu_cb.hcit_ble_acl_data_size == 0)
-            btu_cb.hcit_ble_acl_data_size = btu_cb.hcit_acl_data_size;
-
-        btu_cb.hcit_ble_acl_pkt_size = btu_cb.hcit_ble_acl_data_size + HCI_DATA_PREAMBLE_SIZE;
-
-        l2c_link_processs_ble_num_bufs (lm_num_le_bufs);
-    }
-    btm_read_ble_local_supported_states();
-}
-/*******************************************************************************
-**
-** Function         btm_read_ble_local_supported_states_complete
-**
-** Description      This function is called when command complete for
-**                  Read LE Local Supported states complete is received.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_ble_local_supported_states_complete (UINT8 *p, UINT16 evt_len)
-{
-    UINT8       status;
-
-    UNUSED(evt_len);
-    BTM_TRACE_DEBUG("btm_read_ble_local_supported_states_complete ");
-
-    btu_stop_timer (&btm_cb.devcb.reset_timer);
-
-    STREAM_TO_UINT8  (status, p);
-    if (status == HCI_SUCCESS)
-    {
-        STREAM_TO_ARRAY(&btm_cb.devcb.le_supported_states, p, BTM_LE_SUPPORT_STATE_SIZE);
-    }
-    else
-    {
-        BTM_TRACE_WARNING ("btm_read_ble_local_supported_features_complete status = %d", status);
-    }
-
-    btm_read_ble_local_supported_features();
-}
-
-/*******************************************************************************
-**
-** Function         btm_read_ble_local_supported_features_complete
-**
-** Description      This function is called when command complete for
-**                  Read LE Local Supported Features is received.  Start timer and send
-**                  read LMP local features request
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_ble_local_supported_features_complete (UINT8 *p, UINT16 evt_len)
-{
-    UINT8       status;
-    UNUSED(evt_len);
-
-    BTM_TRACE_DEBUG("btm_read_ble_local_supported_features_complete ");
-
-    btu_stop_timer (&btm_cb.devcb.reset_timer);
-
-    STREAM_TO_UINT8  (status, p);
-    if (status == HCI_SUCCESS)
-    {
-        STREAM_TO_ARRAY(&btm_cb.devcb.local_le_features, p, HCI_FEATURE_BYTES_PER_PAGE);
-    }
-    else
-    {
-        BTM_TRACE_WARNING ("btm_read_ble_local_supported_features_complete status = %d", status);
-    }
-
-    btsnd_hcic_ble_set_evt_mask((UINT8 *)HCI_BLE_EVENT_MASK_DEF);
-
-#if BTM_INTERNAL_BB == TRUE
-    {
-        UINT8 buf[9] = BTM_INTERNAL_LOCAL_FEA;
-        btm_read_local_features_complete( buf, 9 );
-    }
-#else
-
-    /* get local feature if BRCM specific feature is not included  */
-    btm_reset_ctrlr_complete();
-#endif
-
-}
-
-/*******************************************************************************
-**
-** Function         btm_read_white_list_size_complete
-**
-** Description      This function read the current white list size.
-*******************************************************************************/
-void btm_read_white_list_size_complete(UINT8 *p, UINT16 evt_len)
-{
-    UINT8       status;
-    UNUSED(evt_len);
-
-    BTM_TRACE_DEBUG("btm_read_white_list_size_complete ");
-    STREAM_TO_UINT8  (status, p);
-
-    if (status == HCI_SUCCESS)
-    {
-        STREAM_TO_UINT8(btm_cb.ble_ctr_cb.max_filter_entries, p);
-        btm_cb.ble_ctr_cb.num_empty_filter = btm_cb.ble_ctr_cb.max_filter_entries;
-    }
-    /* write LE host support and simultatunous LE supported */
-    btsnd_hcic_ble_write_host_supported(BTM_BLE_HOST_SUPPORT, BTM_BLE_SIMULTANEOUS_HOST);
-
-    btm_get_ble_buffer_size();
-}
-
-#endif
-/*******************************************************************************
-**
-** Function         btm_read_local_version_complete
-**
-** Description      This function is called when local BD Addr read complete
-**                  message is received from the HCI.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_local_version_complete (UINT8 *p, UINT16 evt_len)
-{
-    tBTM_VERSION_INFO   *p_vi = &btm_cb.devcb.local_version;
-    UINT8                status;
-    UNUSED(evt_len);
-
-#ifdef BTA_PRM_CHECK_FW_VER
-    if(BTA_PRM_CHECK_FW_VER(p))
-        return;
-#endif
-
-    STREAM_TO_UINT8  (status, p);
-    if (status == HCI_SUCCESS)
-    {
-
-        STREAM_TO_UINT8  (p_vi->hci_version, p);
-        STREAM_TO_UINT16 (p_vi->hci_revision, p);
-        STREAM_TO_UINT8  (p_vi->lmp_version, p);
-        STREAM_TO_UINT16 (p_vi->manufacturer, p);
-        STREAM_TO_UINT16 (p_vi->lmp_subversion, p);
-    }
-
-    if (p_vi->hci_version >= HCI_PROTO_VERSION_1_2)
-    {
-        btm_read_local_supported_cmds(LOCAL_BR_EDR_CONTROLLER_ID);
-    }
-    else
-    {
-        btm_get_local_features ();
-    }
-}
-
-/*******************************************************************************
-**
 ** Function         btm_decode_ext_features_page
 **
 ** Description      This function is decodes a features page.
@@ -985,6 +252,9 @@
 *******************************************************************************/
 static void btm_decode_ext_features_page (UINT8 page_number, const UINT8 *p_features)
 {
+    UINT8 last;
+    UINT8 first;
+
     BTM_TRACE_DEBUG ("btm_decode_ext_features_page page: %d", page_number);
     switch (page_number)
     {
@@ -1003,37 +273,32 @@
             btm_cb.btm_acl_pkt_types_supported |= (BTM_ACL_PKT_TYPES_MASK_DH5 +
                                                    BTM_ACL_PKT_TYPES_MASK_DM5);
 
-        /* _NO_X_DXX masks are reserved before ver 2.0.
-           Set them only for later versions of controller */
-        if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_2_0)
+        /* Add in EDR related ACL types */
+        if (!HCI_EDR_ACL_2MPS_SUPPORTED(p_features))
         {
-            /* Add in EDR related ACL types */
-            if (!HCI_EDR_ACL_2MPS_SUPPORTED(p_features))
-            {
-                btm_cb.btm_acl_pkt_types_supported |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH1 +
-                                                       BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 +
-                                                       BTM_ACL_PKT_TYPES_MASK_NO_2_DH5);
-            }
+            btm_cb.btm_acl_pkt_types_supported |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH1 +
+                                                   BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 +
+                                                   BTM_ACL_PKT_TYPES_MASK_NO_2_DH5);
+        }
 
-            if (!HCI_EDR_ACL_3MPS_SUPPORTED(p_features))
-            {
-                btm_cb.btm_acl_pkt_types_supported |= (BTM_ACL_PKT_TYPES_MASK_NO_3_DH1 +
-                                                       BTM_ACL_PKT_TYPES_MASK_NO_3_DH3 +
+        if (!HCI_EDR_ACL_3MPS_SUPPORTED(p_features))
+        {
+            btm_cb.btm_acl_pkt_types_supported |= (BTM_ACL_PKT_TYPES_MASK_NO_3_DH1 +
+                                                   BTM_ACL_PKT_TYPES_MASK_NO_3_DH3 +
+                                                   BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
+        }
+
+        /* Check to see if 3 and 5 slot packets are available */
+        if (HCI_EDR_ACL_2MPS_SUPPORTED(p_features) ||
+            HCI_EDR_ACL_3MPS_SUPPORTED(p_features))
+        {
+            if (!HCI_3_SLOT_EDR_ACL_SUPPORTED(p_features))
+                btm_cb.btm_acl_pkt_types_supported |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 +
+                                                       BTM_ACL_PKT_TYPES_MASK_NO_3_DH3);
+
+            if (!HCI_5_SLOT_EDR_ACL_SUPPORTED(p_features))
+                btm_cb.btm_acl_pkt_types_supported |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH5 +
                                                        BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
-            }
-
-            /* Check to see if 3 and 5 slot packets are available */
-            if (HCI_EDR_ACL_2MPS_SUPPORTED(p_features) ||
-                HCI_EDR_ACL_3MPS_SUPPORTED(p_features))
-            {
-                if (!HCI_3_SLOT_EDR_ACL_SUPPORTED(p_features))
-                    btm_cb.btm_acl_pkt_types_supported |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 +
-                                                           BTM_ACL_PKT_TYPES_MASK_NO_3_DH3);
-
-                if (!HCI_5_SLOT_EDR_ACL_SUPPORTED(p_features))
-                    btm_cb.btm_acl_pkt_types_supported |= (BTM_ACL_PKT_TYPES_MASK_NO_2_DH5 +
-                                                           BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
-            }
         }
 
         BTM_TRACE_DEBUG("Local supported ACL packet types: 0x%04x",
@@ -1159,444 +424,6 @@
 
 /*******************************************************************************
 **
-** Function         btm_reset_ctrlr_complete
-**
-** Description      This is the last step of BR/EDR controller startup sequence.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_reset_ctrlr_complete ()
-{
-    tBTM_DEVCB     *p_devcb = &btm_cb.devcb;
-    tBTM_CMPL_CB   *p_cb = p_devcb->p_reset_cmpl_cb;
-    BOOLEAN         found = FALSE;
-    UINT8           i, j, max_page_number;
-
-    btu_stop_timer (&btm_cb.devcb.reset_timer);
-
-    /* find the highest feature page number which contains non-zero bits */
-    for (i = HCI_EXT_FEATURES_PAGE_MAX; ; i--)
-    {
-        for (j = 0; j < HCI_FEATURE_BYTES_PER_PAGE; j++)
-        {
-            if (p_devcb->local_lmp_features[i][j] != 0)
-            {
-                found = TRUE;
-                break;
-            }
-        }
-        if (found || !i)
-        {
-             break;
-        }
-    }
-
-    if (!found)
-        BTM_TRACE_WARNING ("btm_reset_ctrlr_complete: NONE of local controller features is set");
-
-    max_page_number = i;
-
-    BTM_TRACE_DEBUG ("btm_reset_ctrlr_complete: max_page_number: %d", max_page_number);
-
-    /*
-    * Set State to Ready (needs to be done before btm_decode_ext_features_page
-    * to allow it to send some HCI configuration commands)
-    */
-    p_devcb->state = BTM_DEV_STATE_READY;
-
-    /* For every received/saved feature page */
-    for (i = 0; i <= max_page_number; i++)
-    {
-        /* Decode the saved Feature Page */
-        btm_decode_ext_features_page(i, p_devcb->local_lmp_features[i]);
-    }
-
-    /* If there was a callback address for reset complete, reset it */
-    p_devcb->p_reset_cmpl_cb = NULL;
-
-    /* If anyone wants device status notifications, give him one */
-    btm_report_device_status(BTM_DEV_STATUS_UP);
-
-    /* Reset sequence is complete. If this was an application originated */
-    /* reset, tell him its done.                                         */
-    if (p_cb)
-        (*p_cb)((void *) NULL);
-}
-
-/*******************************************************************************
-**
-** Function         btm_issue_host_support_for_lmp_features
-**
-** Description      This function:
-**                  - issues commands to set host supported LMP features (one at
-**                    a time);
-**                  - after this is done it issues command to re-read LMP features
-**                    page 1;
-**                  - after this is done it calls the last step of BR/EDR
-**                    controller startup sequence.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btm_issue_host_support_for_lmp_features (void)
-{
-    BTM_TRACE_DEBUG("btm_issue_host_support_for_lmp_features lmp_features_host_may_support: 0x%02x", btm_cb.devcb.lmp_features_host_may_support);
-
-    if (btm_cb.devcb.lmp_features_host_may_support & BTM_HOST_MAY_SUPP_SSP)
-    {
-        btsnd_hcic_write_simple_pairing_mode(HCI_SP_MODE_ENABLED);
-        return;
-    }
-
-#if (BLE_INCLUDED == TRUE)
-    if (btm_cb.devcb.lmp_features_host_may_support & BTM_HOST_MAY_SUPP_LE)
-    {
-        if (btm_cb.devcb.lmp_features_host_may_support & BTM_HOST_MAY_SUPP_SIMULT_BR_LE)
-        {
-            btsnd_hcic_ble_write_host_supported(BTM_BLE_HOST_SUPPORT, BTM_BLE_SIMULTANEOUS_HOST);
-        }
-        else
-        {
-            btsnd_hcic_ble_write_host_supported(BTM_BLE_HOST_SUPPORT, 0);
-        }
-        return;
-    }
-#endif
-
-    if (btm_cb.devcb.lmp_features_host_may_support & BTM_RE_READ_1ST_PAGE)
-    {
-        btm_get_local_ext_features(HCI_EXT_FEATURES_PAGE_1);
-        return;
-    }
-
-    if (!btm_cb.devcb.lmp_features_host_may_support)
-    {
-#if BLE_INCLUDED == TRUE
-        if (HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
-        {
-            btm_read_ble_wl_size();
-        }
-        else
-#elif BTM_INTERNAL_BB == TRUE
-        {
-            UINT8 buf[9] = BTM_INTERNAL_LOCAL_FEA;
-            btm_read_local_features_complete( buf, 9 );
-        }
-#endif
-        {
-            btm_reset_ctrlr_complete();
-        }
-        return;
-    }
-
-    BTM_TRACE_ERROR("%s lmp_features_host_may_support: 0x%02x. This is unexpected.",__FUNCTION__,
-                      btm_cb.devcb.lmp_features_host_may_support);
-}
-
-/*******************************************************************************
-**
-** Function         btm_set_lmp_features_host_may_support
-**
-** Description      This function is called after all LMP features provided by
-**                  controller are read. It sets the mask that indicates LMP
-**                  features the host may support based on LMP features supported
-**                  by controller.
-**                  Example:
-**                  Host may set SSP (host support) bit only if SSP (controller
-**                  support) bit is set by controller.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btm_set_lmp_features_host_may_support (UINT8 max_page_number)
-{
-    btm_cb.devcb.lmp_features_host_may_support = 0;
-
-    /* LMP page 0 is always read */
-    if (HCI_SIMPLE_PAIRING_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-    {
-        /* host may support SSP */
-        btm_cb.devcb.lmp_features_host_may_support |= BTM_HOST_MAY_SUPP_SSP;
-    }
-
-#if (BLE_INCLUDED == TRUE)
-    if (HCI_LE_SPT_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-    {
-        /* host may support LE */
-        btm_cb.devcb.lmp_features_host_may_support |= BTM_HOST_MAY_SUPP_LE;
-
-        if (HCI_SIMUL_LE_BREDR_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-        {
-            /* host may support BR/EDR and LE simultaneously */
-            btm_cb.devcb.lmp_features_host_may_support |= BTM_HOST_MAY_SUPP_SIMULT_BR_LE;
-        }
-    }
-#endif
-
-    if (max_page_number >= HCI_EXT_FEATURES_PAGE_1)
-    {
-        /* nothing yet for HCI_EXT_FEATURES_PAGE_1 */
-    }
-
-    if (max_page_number >= HCI_EXT_FEATURES_PAGE_1)
-    {
-        /* nothing yet for HCI_EXT_FEATURES_PAGE_2 */
-    }
-
-    if (btm_cb.devcb.lmp_features_host_may_support)
-        btm_cb.devcb.lmp_features_host_may_support |= BTM_RE_READ_1ST_PAGE;
-}
-
-/*******************************************************************************
-**
-** Function         btm_read_all_lmp_features_complete
-**
-** Description      This function is called after all LMP features provided by
-**                  controller are read.
-**                  It works with controller supported LMP features which host
-**                  may support too.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btm_read_all_lmp_features_complete (UINT8 max_page_number)
-{
-    btm_set_lmp_features_host_may_support(max_page_number);
-
-    btm_issue_host_support_for_lmp_features();
-}
-
-/*******************************************************************************
-**
-** Function         btm_read_local_features_complete
-**
-** Description      This function is called when local supported features read
-**                  is complete.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_local_features_complete (UINT8 *p, UINT16 evt_len)
-{
-    tBTM_DEVCB     *p_devcb = &btm_cb.devcb;
-    UINT8           status;
-    UNUSED(evt_len);
-
-    btu_stop_timer (&p_devcb->reset_timer);
-
-    STREAM_TO_UINT8  (status, p);
-    if (status == HCI_SUCCESS)
-    {
-        /* Save the Feature Page 0 */
-        STREAM_TO_ARRAY(p_devcb->local_lmp_features[0],
-                p, HCI_FEATURE_BYTES_PER_PAGE);
-
-        if ((HCI_LMP_EXTENDED_SUPPORTED(p_devcb->local_lmp_features[HCI_EXT_FEATURES_PAGE_0])) &&
-            (HCI_READ_LOCAL_EXT_FEATURES_SUPPORTED(p_devcb->supported_cmds)))
-        {
-            /* if local controller has extended features and supports
-            **HCI_Read_Local_Extended_Features command,
-            ** then start reading these feature starting with extended features page 1 */
-            BTM_TRACE_DEBUG ("Start reading local extended features");
-            btm_get_local_ext_features(HCI_EXT_FEATURES_PAGE_1);
-        }
-        else
-        {
-            btm_read_all_lmp_features_complete (HCI_EXT_FEATURES_PAGE_0);
-        }
-    }
-}
-
-/*******************************************************************************
-**
-** Function         btm_read_local_ext_features_complete
-**
-** Description      This function is called when read local extended features
-**                  command complete message is received from the HCI.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_local_ext_features_complete (UINT8 *p, UINT16 evt_len)
-{
-    UINT8           status;
-    UINT8           page_number;
-    UINT8           page_number_max;
-    UNUSED(evt_len);
-
-    btu_stop_timer (&btm_cb.devcb.reset_timer);
-
-    STREAM_TO_UINT8 (status, p);
-
-    if (status != HCI_SUCCESS)
-    {
-        BTM_TRACE_WARNING("btm_read_local_ext_features_complete status = 0x%02X", status);
-        btm_read_all_lmp_features_complete (HCI_EXT_FEATURES_PAGE_0);
-        return;
-    }
-
-    /* Extract Page number */
-    STREAM_TO_UINT8  (page_number, p);
-
-    /* Extract Page number Max */
-    STREAM_TO_UINT8  (page_number_max, p);
-
-    if (page_number > HCI_EXT_FEATURES_PAGE_MAX)
-    {
-        BTM_TRACE_ERROR("btm_read_local_ext_features_complete page=%d unknown",
-                page_number);
-        return;
-    }
-
-    /* Save the extended features Page received */
-    STREAM_TO_ARRAY(btm_cb.devcb.local_lmp_features[page_number],
-            p, HCI_FEATURE_BYTES_PER_PAGE);
-
-    /* If this is re-read of the 1-st extended page after host supported LMP features are set */
-    if ((page_number == HCI_EXT_FEATURES_PAGE_1) &&
-        (btm_cb.devcb.lmp_features_host_may_support == BTM_RE_READ_1ST_PAGE))
-    {
-        btm_cb.devcb.lmp_features_host_may_support &= ~BTM_RE_READ_1ST_PAGE;
-        btm_issue_host_support_for_lmp_features();
-        return;
-    }
-
-    /* If this is the last page supported by the local BT controller OR */
-    /* if this is the last page supported by the Host */
-    if ((page_number == page_number_max) ||
-        (page_number == HCI_EXT_FEATURES_PAGE_MAX))
-    {
-        BTM_TRACE_DEBUG("BTM reached last extended features page (%d)", page_number);
-        btm_read_all_lmp_features_complete(page_number);
-    }
-    /* Else (another page must be read) */
-    else
-    {
-        /* Read the next features page */
-        page_number++;
-        BTM_TRACE_DEBUG("BTM reads next extended features page (%d)", page_number);
-        btm_get_local_ext_features(page_number);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         btm_read_local_supported_cmds_complete
-**
-** Description      This function is called when local supported commands read
-**                  is complete.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_local_supported_cmds_complete (UINT8 *p)
-{
-    tBTM_DEVCB     *p_devcb = &btm_cb.devcb;
-    UINT8           status;
-
-    btu_stop_timer (&(p_devcb->reset_timer));
-
-    STREAM_TO_UINT8  (status, p);
-    BTM_TRACE_DEBUG("btm_read_local_supported_cmds_complete status (0x%02x)", status);
-
-    if (status == HCI_SUCCESS)
-    {
-        /* Save the supported commands bit mask */
-        STREAM_TO_ARRAY(p_devcb->supported_cmds, p, HCI_NUM_SUPP_COMMANDS_BYTES);
-    }
-
-    btm_get_local_features();
-}
-
-/*******************************************************************************
-**
-** Function         btm_write_simple_paring_mode_complete
-**
-** Description      This function is called when the command complete message
-**                  is received from the HCI for the write simple pairing mode
-**                  command.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_write_simple_paring_mode_complete (UINT8 *p)
-{
-    UINT8   status;
-
-    STREAM_TO_UINT8 (status, p);
-
-    if (status != HCI_SUCCESS)
-    {
-        BTM_TRACE_WARNING("btm_write_simple_paring_mode_complete status: 0x%02x", status);
-    }
-
-    if (btm_cb.devcb.lmp_features_host_may_support & BTM_HOST_MAY_SUPP_SSP)
-    {
-        btm_cb.devcb.lmp_features_host_may_support &= ~BTM_HOST_MAY_SUPP_SSP;
-        btm_issue_host_support_for_lmp_features();
-    }
-}
-
-/*******************************************************************************
-**
-** Function         btm_write_le_host_supported_complete
-**
-** Description      This function is called when the command complete message
-**                  is received from the HCI for the write LE host supported
-**                  command.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_write_le_host_supported_complete (UINT8 *p)
-{
-    UINT8   status;
-
-    STREAM_TO_UINT8 (status, p);
-
-    if (status != HCI_SUCCESS)
-    {
-        BTM_TRACE_WARNING("btm_write_le_host_supported_complete status: 0x%02x", status);
-    }
-
-    if (btm_cb.devcb.lmp_features_host_may_support & BTM_HOST_MAY_SUPP_LE)
-    {
-        btm_cb.devcb.lmp_features_host_may_support &= ~BTM_HOST_MAY_SUPP_LE;
-        if (btm_cb.devcb.lmp_features_host_may_support & BTM_HOST_MAY_SUPP_SIMULT_BR_LE)
-        {
-            btm_cb.devcb.lmp_features_host_may_support &= ~BTM_HOST_MAY_SUPP_SIMULT_BR_LE;
-        }
-        btm_issue_host_support_for_lmp_features();
-    }
-}
-
-/*******************************************************************************
-**
-** Function         btm_get_voice_coding_support
-**
-** Description      This function is provides a way to get the voice coding schemes
-**                  supported the device.
-**
-** Returns          A bit mask - Bit 0 if set indicates CVSD support
-**                               Bit 1 if set indicates PCM A-law support
-**                               Bit 2 if set indicates PCM Mu-law support
-**
-*******************************************************************************/
-
-UINT8 btm_get_voice_coding_support( void )
-{
-    UINT8 code = 0;
-
-    if( HCI_LMP_CVSD_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]) ) code |= 0x01 ;
-    if( HCI_LMP_A_LAW_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]) ) code |= 0x02 ;
-    if( HCI_LMP_U_LAW_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]) )  code |= 0x04 ;
-
-    return code ;
-}
-
-/*******************************************************************************
-**
 ** Function         BTM_SetLocalDeviceName
 **
 ** Description      This function is called to set the local device name.
@@ -1611,8 +438,7 @@
     if (!p_name || !p_name[0] || (strlen ((char *)p_name) > BD_NAME_LEN))
         return (BTM_ILLEGAL_VALUE);
 
-    if (btm_cb.devcb.state == BTM_DEV_STATE_WAIT_RESET_CMPLT ||
-        btm_cb.devcb.state == BTM_DEV_STATE_WAIT_AFTER_RESET)
+    if (!controller_get_interface()->get_is_ready())
         return (BTM_DEV_RESET);
 
 #if BTM_MAX_LOC_BD_NAME_LEN > 0
@@ -1717,87 +543,6 @@
     }
 }
 
-
-/*******************************************************************************
-**
-** Function         BTM_GetLocalDeviceAddr
-**
-** Description      This function is called to read the local device address
-**
-** Returns          void
-**                  the local device address is copied into bd_addr
-**
-*******************************************************************************/
-void BTM_GetLocalDeviceAddr (BD_ADDR bd_addr)
-{
-    memcpy (bd_addr, btm_cb.devcb.local_addr, BD_ADDR_LEN);
-}
-
-/*******************************************************************************
-**
-** Function         BTM_ReadLocalDeviceAddr
-**
-** Description      This function is called to read the local device address
-**
-** Returns          status of the operation
-**
-*******************************************************************************/
-tBTM_STATUS BTM_ReadLocalDeviceAddr (tBTM_CMPL_CB *p_cb)
-{
-    if(p_cb)
-        (*p_cb)(btm_cb.devcb.local_addr);
-
-    return (BTM_SUCCESS);
-}
-
-
-/*******************************************************************************
-**
-** Function         btm_read_local_addr_complete
-**
-** Description      This function is called when local BD Addr read complete
-**                  message is received from the HCI.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_local_addr_complete (UINT8 *p, UINT16 evt_len)
-{
-    UINT8           status;
-    UNUSED(evt_len);
-
-    STREAM_TO_UINT8  (status, p);
-
-    if (status == HCI_SUCCESS)
-    {
-        STREAM_TO_BDADDR (btm_cb.devcb.local_addr, p);
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadLocalVersion
-**
-** Description      This function is called to read the local device version
-**
-** Returns          status of the operation
-**
-*******************************************************************************/
-tBTM_STATUS BTM_ReadLocalVersion (tBTM_VERSION_INFO *p_vers)
-{
-    /* Make sure the device has retrieved the info (not being reset) */
-    if (btm_cb.devcb.state < BTM_DEV_STATE_READY)
-        return (BTM_DEV_RESET);
-
-    *p_vers = btm_cb.devcb.local_version;
-
-    return (BTM_SUCCESS);
-}
-
-
-
-
 /*******************************************************************************
 **
 ** Function         BTM_SetDeviceClass
@@ -1814,8 +559,7 @@
 
     memcpy (btm_cb.devcb.dev_class, dev_class, DEV_CLASS_LEN);
 
-    if (btm_cb.devcb.state == BTM_DEV_STATE_WAIT_RESET_CMPLT ||
-        btm_cb.devcb.state == BTM_DEV_STATE_WAIT_AFTER_RESET)
+    if (!controller_get_interface()->get_is_ready())
         return (BTM_DEV_RESET);
 
     if (!btsnd_hcic_write_dev_class (dev_class))
@@ -1849,43 +593,11 @@
 ** Returns          pointer to the local features string
 **
 *******************************************************************************/
+// TODO(zachoverflow): get rid of this function
 UINT8 *BTM_ReadLocalFeatures (void)
 {
-    return (btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]);
-}
-
-/*******************************************************************************
-**
-** Function         BTM_ReadLocalExtendedFeatures
-**
-** Description      This function is called to read the local extended features
-**
-** Returns          pointer to the local extended features mask or NULL if bad
-**                  page
-**
-*******************************************************************************/
-UINT8 *BTM_ReadLocalExtendedFeatures (UINT8 page_number)
-{
-    if (page_number <= HCI_EXT_FEATURES_PAGE_MAX)
-        return (btm_cb.devcb.local_lmp_features[page_number]);
-
-    BTM_TRACE_ERROR("Warning: BTM_ReadLocalExtendedFeatures page %d unknown",
-            page_number);
-    return NULL;
-}
-
-/*******************************************************************************
-**
-** Function         BTM_ReadBrcmFeatures
-**
-** Description      This function is called to read the Broadcom specific features
-**
-** Returns          pointer to the Broadcom features string
-**
-*******************************************************************************/
-UINT8 *BTM_ReadBrcmFeatures (void)
-{
-    return (btm_cb.devcb.brcm_features);
+    // Discarding const modifier for now, until this function dies
+    return (UINT8 *)controller_get_interface()->get_features_classic(0)->as_array;
 }
 
 /*******************************************************************************
@@ -2157,11 +869,11 @@
     }
 
     /* mask off all of event from controller */
-    if (!btsnd_hcic_set_event_mask(LOCAL_BR_EDR_CONTROLLER_ID,
-                                   (UINT8 *)"\x00\x00\x00\x00\x00\x00\x00\x00"))
-    {
-        return BTM_NO_RESOURCES;
-    }
+    hci_layer_get_interface()->transmit_command(
+      hci_packet_factory_get_interface()->make_set_event_mask((const bt_event_mask_t *)("\x00\x00\x00\x00\x00\x00\x00\x00")),
+      NULL,
+      NULL,
+      NULL);
 
     /* Send the HCI command */
     if (btsnd_hcic_enable_test_mode ())
@@ -2172,106 +884,6 @@
 
 /*******************************************************************************
 **
-** Function         btm_get_hci_version
-**
-** Description      Local function called to retrieve the current HCI version
-**
-** Returns          Bluetooth HCI Version returned by the controller
-**
-*******************************************************************************/
-UINT8 btm_get_hci_version (void)
-{
-    return (btm_cb.devcb.local_version.hci_version);
-}
-
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadStoredLinkKey
-**
-** Description      This function is called to obtain link key for the specified
-**                  device from the NVRAM storage attached to the Bluetooth
-**                  controller.
-**
-** Parameters:      bd_addr      - Address of the device
-**                  p_cb         - Call back function to be called to return
-**                                 the results
-**
-*******************************************************************************/
-tBTM_STATUS BTM_ReadStoredLinkKey (BD_ADDR bd_addr,	tBTM_CMPL_CB *p_cb)
-{
-    BD_ADDR local_bd_addr;
-    BOOLEAN read_all_flag = FALSE;
-
-    /* Check if the previous command is completed */
-    if (btm_cb.devcb.p_stored_link_key_cmpl_cb)
-        return (BTM_BUSY);
-
-    if (!bd_addr)
-    {
-        /* This is to read all the link keys */
-        read_all_flag = TRUE;
-
-        /* We don't care the BD address. Just pass a non zero pointer */
-        bd_addr = local_bd_addr;
-    }
-
-    BTM_TRACE_EVENT ("BTM: BTM_ReadStoredLinkKey: Read_All: %s",
-                        read_all_flag ? "TRUE" : "FALSE");
-
-    /* Send the HCI command */
-    btm_cb.devcb.p_stored_link_key_cmpl_cb = p_cb;
-    if (btsnd_hcic_read_stored_key (bd_addr, read_all_flag))
-        return (BTM_SUCCESS);
-    else
-        return (BTM_NO_RESOURCES);
-
-}
-
-
-/*******************************************************************************
-**
-** Function         BTM_WriteStoredLinkKey
-**
-** Description      This function is called to write link keys for the specified
-**                  device addresses to the NVRAM storage attached to the Bluetooth
-**                  controller.
-**
-** Parameters:      num_keys     - Number of link keys
-**                  bd_addr      - Addresses of the devices
-**                  link_key     - Link Keys to be stored
-**                  p_cb         - Call back function to be called to return
-**                                 the results
-**
-*******************************************************************************/
-tBTM_STATUS BTM_WriteStoredLinkKey (UINT8 num_keys,
-                                    BD_ADDR *bd_addr,
-                                    LINK_KEY *link_key,
-                                    tBTM_CMPL_CB *p_cb)
-{
-    /* Check if the previous command is completed */
-    if (btm_cb.devcb.p_stored_link_key_cmpl_cb)
-        return (BTM_BUSY);
-
-    BTM_TRACE_EVENT ("BTM: BTM_WriteStoredLinkKey: num_keys: %d", num_keys);
-
-    /* Check the maximum number of link keys */
-    if(num_keys > HCI_MAX_NUM_OF_LINK_KEYS_PER_CMMD)
-        num_keys = HCI_MAX_NUM_OF_LINK_KEYS_PER_CMMD;
-
-    /* Send the HCI command */
-    btm_cb.devcb.p_stored_link_key_cmpl_cb = p_cb;
-    if (btsnd_hcic_write_stored_key (num_keys, bd_addr, link_key))
-        return (BTM_SUCCESS);
-    else
-        return (BTM_NO_RESOURCES);
-
-}
-
-
-/*******************************************************************************
-**
 ** Function         BTM_DeleteStoredLinkKey
 **
 ** Description      This function is called to delete link key for the specified
@@ -2314,82 +926,6 @@
         return (BTM_SUCCESS);
 }
 
-
-/*******************************************************************************
-**
-** Function         btm_read_stored_link_key_complete
-**
-** Description      This function is called when the command complete message
-**                  is received from the HCI for the read stored link key command.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_read_stored_link_key_complete (UINT8 *p)
-{
-    tBTM_CMPL_CB      *p_cb = btm_cb.devcb.p_stored_link_key_cmpl_cb;
-    tBTM_READ_STORED_LINK_KEY_COMPLETE  result;
-
-    /* If there was a callback registered for read stored link key, call it */
-    btm_cb.devcb.p_stored_link_key_cmpl_cb = NULL;
-
-    if (p_cb)
-    {
-        /* Set the call back event to indicate command complete */
-        result.event = BTM_CB_EVT_READ_STORED_LINK_KEYS;
-
-        /* Extract the result fields from the HCI event if status is success */
-        STREAM_TO_UINT8  (result.status, p);
-        if (result.status == HCI_SUCCESS)
-        {
-            STREAM_TO_UINT16 (result.max_keys, p);
-            STREAM_TO_UINT16 (result.read_keys, p);
-        }
-        else
-        {
-            BTM_TRACE_WARNING("Read stored link key status %d", result.status);
-            result.max_keys = 0;
-            result.read_keys = 0;
-        }
-        /* Call the call back and pass the result */
-        (*p_cb)(&result);
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         btm_write_stored_link_key_complete
-**
-** Description      This function is called when the command complete message
-**                  is received from the HCI for the write stored link key command.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_write_stored_link_key_complete (UINT8 *p)
-{
-    tBTM_CMPL_CB       *p_cb = btm_cb.devcb.p_stored_link_key_cmpl_cb;
-    tBTM_WRITE_STORED_LINK_KEY_COMPLETE  result;
-
-    /* If there was a callback registered for read stored link key, call it */
-    btm_cb.devcb.p_stored_link_key_cmpl_cb = NULL;
-
-    if (p_cb)
-    {
-        /* Set the call back event to indicate command complete */
-        result.event = BTM_CB_EVT_WRITE_STORED_LINK_KEYS;
-
-        /* Extract the result fields from the HCI event */
-        STREAM_TO_UINT8 (result.status, p);
-        STREAM_TO_UINT8 (result.num_keys, p);
-
-        /* Call the call back and pass the result */
-        (*p_cb)(&result);
-    }
-}
-
-
 /*******************************************************************************
 **
 ** Function         btm_delete_stored_link_key_complete
@@ -2422,49 +958,6 @@
     }
 }
 
-
-/*******************************************************************************
-**
-** Function         btm_return_link_keys_evt
-**
-** Description      This function is called when the return link keys event
-**                  is received from the HCI for the read stored link key command.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_return_link_keys_evt (tBTM_RETURN_LINK_KEYS_EVT *result)
-{
-    tBTM_CMPL_CB  *p_cb = btm_cb.devcb.p_stored_link_key_cmpl_cb;
-    UINT8          i, *p, *p1;
-    UINT8          bd_addr[BD_ADDR_LEN];
-    UINT8          link_key[LINK_KEY_LEN];
-
-    /* Call the call back to pass the link keys to application */
-    if (p_cb)
-    {
-        /* Change the BD addr and Link key in to big endian order */
-        p = (UINT8 *)(result + 1);
-        for (i=0; i<result->num_keys; i++)
-        {
-            /* Initialize the backup pointer */
-            p1 = p;
-
-            /* Extract the BD Addr and Link Key */
-            REVERSE_STREAM_TO_ARRAY(bd_addr, p1, BD_ADDR_LEN);
-            REVERSE_STREAM_TO_ARRAY(link_key, p1, LINK_KEY_LEN);
-
-            /* Write the BD Addr and Link Key back in big endian format */
-            ARRAY_TO_STREAM(p, bd_addr, BD_ADDR_LEN);
-            ARRAY_TO_STREAM(p, link_key, LINK_KEY_LEN);
-        }
-
-        (*p_cb)(result);
-    }
-}
-
-
-
 /*******************************************************************************
 **
 ** Function         btm_report_device_status
diff --git a/stack/btm/btm_inq.c b/stack/btm/btm_inq.c
index 4cabf25..5311436 100644
--- a/stack/btm/btm_inq.c
+++ b/stack/btm/btm_inq.c
@@ -31,6 +31,7 @@
 #include <stddef.h>
 
 #include "bt_types.h"
+#include "device/include/controller.h"
 #include "gki.h"
 #include "hcimsgs.h"
 #include "btu.h"
@@ -50,8 +51,6 @@
 static const LAP general_inq_lap = {0x9e,0x8b,0x33};
 static const LAP limited_inq_lap = {0x9e,0x8b,0x00};
 
-#if (( BTM_EIR_CLIENT_INCLUDED == TRUE )||( BTM_EIR_SERVER_INCLUDED == TRUE ))
-#ifndef BTM_EIR_UUID_LKUP_TBL
 const UINT16 BTM_EIR_UUID_LKUP_TBL[BTM_EIR_MAX_SERVICES] =
 {
     UUID_SERVCLASS_SERVICE_DISCOVERY_SERVER,
@@ -124,20 +123,6 @@
     UUID_SERVCLASS_HDP_SOURCE,
     UUID_SERVCLASS_HDP_SINK
 };
-#else
-/*
-If customized UUID look-up table needs to be used,
-the followings should be defined in bdroid_buildcfg.h.
-BTM_EIR_UUID_LKUP_TBL = <customized UUID list>
-BTM_EIR_MAX_SERVICES = <number of UUID in list>
-*/
-#if (BTM_EIR_MAX_SERVICES == 0)
-const UINT16 BTM_EIR_UUID_LKUP_TBL[];
-#else
-extern UINT16 BTM_EIR_UUID_LKUP_TBL[BTM_EIR_MAX_SERVICES];
-#endif
-#endif
-#endif /* BTM_EIR_UUID_LKUP_TBL*/
 
 /********************************************************************************/
 /*              L O C A L    F U N C T I O N     P R O T O T Y P E S            */
@@ -146,15 +131,11 @@
 static tBTM_STATUS  btm_set_inq_event_filter (UINT8 filter_cond_type, tBTM_INQ_FILT_COND *p_filt_cond);
 static void         btm_clr_inq_result_flt (void);
 
-#if ((BTM_EIR_SERVER_INCLUDED == TRUE)||(BTM_EIR_CLIENT_INCLUDED == TRUE))
 static UINT8        btm_convert_uuid_to_eir_service( UINT16 uuid16 );
-#endif
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
 static void         btm_set_eir_uuid( UINT8 *p_eir, tBTM_INQ_RESULTS *p_results );
 static UINT8       *btm_eir_get_uuid_list( UINT8 *p_eir, UINT8 uuid_size,
                                            UINT8 *p_num_uuid, UINT8 *p_uuid_list_type );
 static UINT16       btm_convert_uuid_to_uuid16( UINT8 *p_uuid, UINT8 uuid_size );
-#endif
 
 /*******************************************************************************
 **
@@ -185,7 +166,7 @@
 
     BTM_TRACE_API ("BTM_SetDiscoverability");
 #if (BLE_INCLUDED == TRUE && BLE_INCLUDED == TRUE)
-    if (HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (controller_get_interface()->supports_ble())
     {
         if (btm_ble_set_discoverability((UINT16)(inq_mode))
                             == BTM_SUCCESS)
@@ -202,7 +183,7 @@
         return (BTM_ILLEGAL_VALUE);
 
     /* Make sure the controller is active */
-    if (btm_cb.devcb.state < BTM_DEV_STATE_READY)
+    if (!controller_get_interface()->get_is_ready())
         return (BTM_DEV_RESET);
 
     /* If the window and/or interval is '0', set to default values */
@@ -316,7 +297,7 @@
         return (BTM_ILLEGAL_VALUE);
 
     /* whatever app wants if device is not 1.2 scan type should be STANDARD */
-    if (!HCI_LMP_INTERLACED_INQ_SCAN_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+    if (!controller_get_interface()->supports_interlaced_inquiry_scan())
      return (BTM_MODE_UNSUPPORTED);
 
     /* Check for scan type if configuration has been changed */
@@ -353,7 +334,7 @@
         return (BTM_ILLEGAL_VALUE);
 
     /* whatever app wants if device is not 1.2 scan type should be STANDARD */
-    if (!HCI_LMP_INTERLACED_PAGE_SCAN_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+    if (!controller_get_interface()->supports_interlaced_inquiry_scan())
      return (BTM_MODE_UNSUPPORTED);
 
     /* Check for scan type if configuration has been changed */
@@ -389,6 +370,7 @@
 *******************************************************************************/
 tBTM_STATUS BTM_SetInquiryMode (UINT8 mode)
 {
+    const controller_t *controller = controller_get_interface();
     BTM_TRACE_API ("BTM_SetInquiryMode");
     if (mode == BTM_INQ_RESULT_STANDARD)
     {
@@ -396,16 +378,14 @@
     }
     else if (mode == BTM_INQ_RESULT_WITH_RSSI)
     {
-    if (!HCI_LMP_INQ_RSSI_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-        return (BTM_MODE_UNSUPPORTED);
-    }
-#if (( BTM_EIR_CLIENT_INCLUDED == TRUE )||( BTM_EIR_SERVER_INCLUDED == TRUE ))
-    else if (mode == BTM_INQ_RESULT_EXTENDED)
-    {
-        if (!HCI_EXT_INQ_RSP_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+        if (!controller->supports_rssi_with_inquiry_results())
             return (BTM_MODE_UNSUPPORTED);
     }
-#endif
+    else if (mode == BTM_INQ_RESULT_EXTENDED)
+    {
+        if (!controller->supports_extended_inquiry_response())
+            return (BTM_MODE_UNSUPPORTED);
+    }
     else
         return (BTM_ILLEGAL_VALUE);
 
@@ -523,14 +503,6 @@
                             (BTM_LIMITED_INQUIRY_ACTIVE | BTM_PERIODIC_INQUIRY_ACTIVE) :
                             (BTM_GENERAL_INQUIRY_ACTIVE | BTM_PERIODIC_INQUIRY_ACTIVE));
 
-#if (defined(BTM_BYPASS_EVENT_FILTERING) && BTM_BYPASS_EVENT_FILTERING == TRUE)
-    BTM_TRACE_WARNING("BTM: Bypassing event filtering...");
-
-    p_inq->state = BTM_INQ_ACTIVE_STATE;
-    p_inq->inqfilt_active = FALSE;
-    btm_initiate_inquiry (p_inq);
-    status = BTM_CMD_STARTED;
-#else
     /* If a filter is specified, then save it for later and clear the current filter.
        The setting of the filter is done upon completion of clearing of the previous
        filter.
@@ -552,7 +524,6 @@
 
     }
 
-#endif
     return (status);
 }
 
@@ -622,7 +593,7 @@
     BTM_TRACE_API ("BTM_SetConnectability");
 
 #if (BLE_INCLUDED == TRUE && BLE_INCLUDED == TRUE)
-    if (HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+    if (controller_get_interface()->supports_ble())
     {
         if (btm_ble_set_connectability(page_mode) != BTM_SUCCESS)
         {
@@ -639,7 +610,7 @@
         return (BTM_ILLEGAL_VALUE);
 
     /* Make sure the controller is active */
-    if (btm_cb.devcb.state < BTM_DEV_STATE_READY)
+    if (!controller_get_interface()->get_is_ready())
         return (BTM_DEV_RESET);
 
     /* If the window and/or interval is '0', set to default values */
@@ -803,12 +774,10 @@
 #endif
         }
 
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
         /* Do not send the BUSY_LEVEL event yet. Wait for the cancel_complete event
          * and then send the BUSY_LEVEL event
          * btm_acl_update_busy_level (BTM_BLI_INQ_DONE_EVT);
          */
-#endif
 
          p_inq->inq_counter++;
          btm_clr_inq_result_flt();
@@ -946,7 +915,7 @@
         BTM_TRACE_API("BTM:Starting LE Scan with duration %d and activeMode:0x%02x",
                        p_inqparms->duration, (p_inqparms->mode & BTM_BLE_INQUIRY_MASK));
 #endif
-        if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+        if (!controller_get_interface()->supports_ble())
         {
             p_inq->inqparms.mode &= ~ BTM_BLE_INQUIRY_MASK;
             status = BTM_ILLEGAL_VALUE;
@@ -997,12 +966,6 @@
     {
         p_inq->inq_active = (p_inqparms->mode & BTM_BR_INQUIRY_MASK);
 #endif
-#if (defined(BTM_BYPASS_EVENT_FILTERING) && BTM_BYPASS_EVENT_FILTERING == TRUE)
-    BTM_TRACE_WARNING("BTM: Bypassing event filtering...");
-    p_inq->inqfilt_active = FALSE;
-    btm_initiate_inquiry (p_inq);
-    status = BTM_CMD_STARTED;
-#else
     /* If a filter is specified, then save it for later and clear the current filter.
        The setting of the filter is done upon completion of clearing of the previous
        filter.
@@ -1030,7 +993,6 @@
     if ((status = btm_set_inq_event_filter (p_inqparms->filter_cond_type,
                                             &p_inqparms->filter_cond)) != BTM_CMD_STARTED)
         p_inq->state = BTM_INQ_INACTIVE_STATE;
-#endif
 
 #if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE)
         if (p_inq->next_state==BTM_NO_INTERLEAVING)
@@ -1093,10 +1055,6 @@
     if ((p_i = btm_inq_db_find (remote_bda)) != NULL)
     {
         p_cur = &p_i->inq_info;
-
-#if (BTM_INQ_GET_REMOTE_NAME == TRUE)
-        p_cur->remote_name_state = BTM_INQ_RMT_NAME_EMPTY;
-#endif
     }
     BTM_TRACE_API ("no device found in inquiry db");
 
@@ -1158,71 +1116,6 @@
 
 /*******************************************************************************
 **
-** Function         BTM_InqFirstResult
-**
-** Description      This function looks through the inquiry database for the first
-**                  used entrysince the LAST inquiry. This is used in conjunction
-**                  with BTM_InqNext by applications as a way to walk through the
-**                  inquiry results database.
-**
-** Returns          pointer to first in-use entry, or NULL if DB is empty
-**
-*******************************************************************************/
-tBTM_INQ_INFO *BTM_InqFirstResult (void)
-{
-    UINT16       xx;
-    tINQ_DB_ENT  *p_ent = btm_cb.btm_inq_vars.inq_db;
-    UINT32       cur_inq_count = btm_cb.btm_inq_vars.inq_counter - 1;
-
-    for (xx = 0; xx < BTM_INQ_DB_SIZE; xx++, p_ent++)
-    {
-        if (p_ent->in_use && p_ent->inq_count == cur_inq_count)
-            return (&p_ent->inq_info);
-    }
-
-    /* If here, no used entry found */
-    return ((tBTM_INQ_INFO *)NULL);
-}
-
-
-/*******************************************************************************
-**
-** Function         BTM_InqNextResult
-**
-** Description      This function looks through the inquiry database for the next
-**                  used entrysince the LAST inquiry. If the input parameter is NULL,
-**                  the first entry is returned.
-**
-** Returns          pointer to next in-use entry, or NULL if no more found.
-**
-*******************************************************************************/
-tBTM_INQ_INFO *BTM_InqNextResult (tBTM_INQ_INFO *p_cur)
-{
-    tINQ_DB_ENT  *p_ent;
-    UINT16        inx;
-    UINT32        cur_inq_count = btm_cb.btm_inq_vars.inq_counter - 1;
-
-    if (p_cur)
-    {
-        p_ent = (tINQ_DB_ENT *) ((UINT8 *)p_cur - offsetof (tINQ_DB_ENT, inq_info));
-        inx = (UINT16)((p_ent - btm_cb.btm_inq_vars.inq_db) + 1);
-
-        for (p_ent = &btm_cb.btm_inq_vars.inq_db[inx]; inx < BTM_INQ_DB_SIZE; inx++, p_ent++)
-        {
-            if (p_ent->in_use && p_ent->inq_count == cur_inq_count)
-                return (&p_ent->inq_info);
-        }
-
-        /* If here, more entries found */
-        return ((tBTM_INQ_INFO *)NULL);
-    }
-    else
-        return (BTM_InqDbFirst());
-}
-
-
-/*******************************************************************************
-**
 ** Function         BTM_InqDbRead
 **
 ** Description      This function looks through the inquiry database for a match
@@ -1234,20 +1127,14 @@
 *******************************************************************************/
 tBTM_INQ_INFO *BTM_InqDbRead (BD_ADDR p_bda)
 {
-    UINT16       xx;
-    tINQ_DB_ENT  *p_ent = btm_cb.btm_inq_vars.inq_db;
-
     BTM_TRACE_API ("BTM_InqDbRead: bd addr [%02x%02x%02x%02x%02x%02x]",
                p_bda[0], p_bda[1], p_bda[2], p_bda[3], p_bda[4], p_bda[5]);
 
-    for (xx = 0; xx < BTM_INQ_DB_SIZE; xx++, p_ent++)
-    {
-        if ((p_ent->in_use) && (!memcmp (p_ent->inq_info.results.remote_bd_addr, p_bda, BD_ADDR_LEN)))
-            return (&p_ent->inq_info);
-    }
+    tINQ_DB_ENT *p_ent = btm_inq_db_find(p_bda);
+    if (!p_ent)
+      return NULL;
 
-    /* If here, not found */
-    return ((tBTM_INQ_INFO *)NULL);
+    return &p_ent->inq_info;
 }
 
 
@@ -1342,67 +1229,6 @@
     return (BTM_SUCCESS);
 }
 
-
-/*******************************************************************************
-**
-** Function         BTM_ReadNumInqDbEntries
-**
-** Returns          This function returns the number of entries in the inquiry database.
-**
-*******************************************************************************/
-UINT8 BTM_ReadNumInqDbEntries (void)
-{
-    UINT8         num_entries;
-    UINT8         num_results;
-    tINQ_DB_ENT  *p_ent = btm_cb.btm_inq_vars.inq_db;
-
-    for (num_entries = 0, num_results = 0; num_entries < BTM_INQ_DB_SIZE; num_entries++, p_ent++)
-    {
-        if (p_ent->in_use)
-            num_results++;
-    }
-
-    return (num_results);
-}
-
-
-/*******************************************************************************
-**
-** Function         BTM_InquiryRegisterForChanges
-**
-** Returns          This function is called to register a callback for when the
-**                  inquiry database changes, i.e. new entry or entry deleted.
-**
-*******************************************************************************/
-tBTM_STATUS  BTM_InquiryRegisterForChanges (tBTM_INQ_DB_CHANGE_CB *p_cb)
-{
-    if (!p_cb)
-        btm_cb.btm_inq_vars.p_inq_change_cb = NULL;
-    else if (btm_cb.btm_inq_vars.p_inq_change_cb)
-        return (BTM_BUSY);
-    else
-        btm_cb.btm_inq_vars.p_inq_change_cb = p_cb;
-
-    return (BTM_SUCCESS);
-}
-
-
-/*******************************************************************************
-**
-** Function         BTM_SetInquiryFilterCallback
-**
-** Description      Host can register to be asked whenever an inquiry result
-**                  is received.  If host does not like the device no name
-**                  request is issued for the device
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTM_SetInquiryFilterCallback (tBTM_FILTER_CB *p_callback)
-{
-    btm_cb.p_inq_filter_cb = p_callback;
-}
-
 /*******************************************************************************
 **
 ** Function         BTM_ReadInquiryRspTxPower
@@ -1433,31 +1259,7 @@
     else
         return (BTM_CMD_STARTED);
 }
-/*******************************************************************************
-**
-** Function         BTM_WriteInquiryTxPower
-**
-** Description      This command is used to write the inquiry transmit power level
-**                  used to transmit the inquiry (ID) data packets. The Controller
-**                  should use the supported TX power level closest to the Tx_Power
-**                  parameter.
-**
-** Returns          BTM_SUCCESS if successful
-**
-*******************************************************************************/
-tBTM_STATUS  BTM_WriteInquiryTxPower (INT8 tx_power)
-{
-    tBTM_STATUS status = BTM_SUCCESS;
 
-    if (tx_power < BTM_MIN_INQ_TX_POWER || tx_power > BTM_MAX_INQ_TX_POWER)
-    {
-        status = BTM_ILLEGAL_VALUE;
-    }
-    else if (!btsnd_hcic_write_inq_tx_power(tx_power))
-        status = BTM_NO_RESOURCES;
-
-    return status;
-}
 /*********************************************************************************
 **********************************************************************************
 **                                                                              **
@@ -1651,12 +1453,6 @@
                 (!memcmp (p_ent->inq_info.results.remote_bd_addr, p_bda, BD_ADDR_LEN)))
             {
                 p_ent->in_use = FALSE;
-#if (BTM_INQ_GET_REMOTE_NAME == TRUE)
-                p_ent->inq_info.remote_name_state = BTM_INQ_RMT_NAME_EMPTY;
-#endif
-
-                if (btm_cb.btm_inq_vars.p_inq_change_cb)
-                    (*btm_cb.btm_inq_vars.p_inq_change_cb) (&p_ent->inq_info, FALSE);
             }
         }
     }
@@ -1679,7 +1475,6 @@
 *******************************************************************************/
 static void btm_clr_inq_result_flt (void)
 {
-#if BTM_USE_INQ_RESULTS_FILTER == TRUE
     tBTM_INQUIRY_VAR_ST *p_inq = &btm_cb.btm_inq_vars;
 
     if (p_inq->p_bd_db)
@@ -1689,7 +1484,6 @@
     }
     p_inq->num_bd_entries = 0;
     p_inq->max_bd_entries = 0;
-#endif
 }
 
 /*******************************************************************************
@@ -1704,7 +1498,6 @@
 *******************************************************************************/
 BOOLEAN btm_inq_find_bdaddr (BD_ADDR p_bda)
 {
-#if BTM_USE_INQ_RESULTS_FILTER == TRUE
     tBTM_INQUIRY_VAR_ST *p_inq = &btm_cb.btm_inq_vars;
     tINQ_BDADDR         *p_db = &p_inq->p_bd_db[0];
     UINT16       xx;
@@ -1727,7 +1520,6 @@
         p_inq->num_bd_entries++;
     }
 
-#endif
     /* If here, New Entry */
     return (FALSE);
 }
@@ -1783,10 +1575,6 @@
             memcpy (p_ent->inq_info.results.remote_bd_addr, p_bda, BD_ADDR_LEN);
             p_ent->in_use = TRUE;
 
-#if (BTM_INQ_GET_REMOTE_NAME==TRUE)
-            p_ent->inq_info.remote_name_state = BTM_INQ_RMT_NAME_EMPTY;
-#endif
-
             return (p_ent);
         }
 
@@ -1799,19 +1587,10 @@
 
     /* If here, no free entry found. Return the oldest. */
 
-    /* Before deleting the oldest, if anyone is registered for change */
-    /* notifications, then tell him we are deleting an entry.         */
-    if (btm_cb.btm_inq_vars.p_inq_change_cb)
-        (*btm_cb.btm_inq_vars.p_inq_change_cb) (&p_old->inq_info, FALSE);
-
     memset (p_old, 0, sizeof (tINQ_DB_ENT));
     memcpy (p_old->inq_info.results.remote_bd_addr, p_bda, BD_ADDR_LEN);
     p_old->in_use = TRUE;
 
-#if (BTM_INQ_GET_REMOTE_NAME==TRUE)
-    p_old->inq_info.remote_name_state = BTM_INQ_RMT_NAME_EMPTY;
-#endif
-
     return (p_old);
 }
 
@@ -2013,9 +1792,7 @@
     BTM_TRACE_DEBUG ("btm_initiate_inquiry: inq_active:0x%x state:%d inqfilt_active:%d",
         btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state, btm_cb.btm_inq_vars.inqfilt_active);
 #endif
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     btm_acl_update_busy_level (BTM_BLI_INQ_EVT);
-#endif
 
     if (p_inq->inq_active & BTM_SSP_INQUIRY_ACTIVE)
     {
@@ -2038,7 +1815,6 @@
     }
     else
     {
-#if BTM_USE_INQ_RESULTS_FILTER == TRUE
         btm_clr_inq_result_flt();
 
         /* Allocate memory to hold bd_addrs responding */
@@ -2051,9 +1827,6 @@
         }
 
         if (!btsnd_hcic_inquiry(*lap, p_inqparms->duration, 0))
-#else
-        if (!btsnd_hcic_inquiry(*lap, p_inqparms->duration, p_inqparms->max_resps))
-#endif /* BTM_USE_INQ_RESULTS_FILTER */
             btm_process_inq_complete (BTM_NO_RESOURCES, (UINT8)(p_inqparms->mode & BTM_BR_INQUIRY_MASK));
     }
 }
@@ -2090,12 +1863,7 @@
     UINT8            rssi = 0;
     DEV_CLASS        dc;
     UINT16           clock_offset;
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
     UINT8            *p_eir_data = NULL;
-#if (BTM_INQ_GET_REMOTE_NAME==TRUE)
-    UINT8            remote_name_len;
-#endif
-#endif
 
 #if (BTM_INQ_DEBUG == TRUE)
     BTM_TRACE_DEBUG ("btm_process_inq_results inq_active:0x%x state:%d inqfilt_active:%d",
@@ -2129,7 +1897,6 @@
 
         p_i = btm_inq_db_find (bda);
 
-#if BTM_USE_INQ_RESULTS_FILTER == TRUE
         /* Only process the num_resp is smaller than max_resps.
            If results are queued to BTU task while canceling inquiry,
            or when more than one result is in this response, > max_resp
@@ -2150,7 +1917,6 @@
 /*            BTM_TRACE_WARNING("INQ RES: Extra Response Received...ignoring"); */
             return;
         }
-#endif
 
         /* Check if this address has already been processed for this inquiry */
         if (btm_inq_find_bdaddr(bda))
@@ -2186,15 +1952,6 @@
                 continue;
         }
 
-        /* Host can be registered to verify comming BDA or DC */
-        if (btm_cb.p_inq_filter_cb)
-        {
-            if (!(* btm_cb.p_inq_filter_cb) (bda, dc))
-            {
-                continue;
-            }
-        }
-
         /* If existing entry, use that, else get a new one (possibly reusing the oldest) */
         if (p_i == NULL)
         {
@@ -2208,7 +1965,7 @@
         */
         else if (p_i->inq_count == p_inq->inq_counter
 #if (BLE_INCLUDED == TRUE )
-            && (p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BREDR)
+            && (p_i->inq_info.results.device_type == BT_DEVICE_TYPE_BREDR)
 #endif
             )
             is_new = FALSE;
@@ -2231,7 +1988,7 @@
             p_cur->dev_class[2]       = dc[2];
             p_cur->clock_offset       = clock_offset  | BTM_CLOCK_OFFSET_VALID;
 
-            p_i->time_of_resp = GKI_get_tick_count ();
+            p_i->time_of_resp = GKI_get_os_tick_count();
 
             if (p_i->inq_count != p_inq->inq_counter)
                 p_inq->inq_cmpl_info.num_resp++;       /* A new response was found */
@@ -2248,7 +2005,6 @@
 #endif
                 p_i->inq_count = p_inq->inq_counter;   /* Mark entry for current inquiry */
 
-#if BTM_USE_INQ_RESULTS_FILTER == TRUE
             /* If the number of responses found and not unlimited, issue a cancel inquiry */
             if (!(p_inq->inq_active & BTM_PERIODIC_INQUIRY_ACTIVE) &&
                 p_inq->inqparms.max_resps &&
@@ -2268,52 +2024,14 @@
                 if ((p_inq->inqparms.mode & BTM_BLE_INQUIRY_MASK) != 0)
                     btm_ble_stop_inquiry();
 #endif
-
-
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
                 btm_acl_update_busy_level (BTM_BLI_INQ_DONE_EVT);
-#endif
             }
-#endif
             /* Initialize flag to FALSE. This flag is set/used by application */
             p_i->inq_info.appl_knows_rem_name = FALSE;
         }
 
         if (is_new || update)
         {
-#if (BTM_INQ_GET_REMOTE_NAME==TRUE)
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
-            if( inq_res_mode == BTM_INQ_RESULT_EXTENDED )
-            {
-                if((p_eir_data = BTM_CheckEirData( p, BTM_EIR_COMPLETE_LOCAL_NAME_TYPE,
-                                                   &remote_name_len )) == NULL)
-                {
-                    p_eir_data = BTM_CheckEirData( p, BTM_EIR_SHORTENED_LOCAL_NAME_TYPE,
-                                                   &remote_name_len );
-                }
-
-                if( p_eir_data )
-                {
-                    if( remote_name_len > BTM_MAX_REM_BD_NAME_LEN )
-                        remote_name_len = BTM_MAX_REM_BD_NAME_LEN;
-
-                    p_i->inq_info.remote_name_len = remote_name_len;
-                    memcpy( p_i->inq_info.remote_name, p_eir_data, p_i->inq_info.remote_name_len );
-                    p_i->inq_info.remote_name[p_i->inq_info.remote_name_len] = 0;
-                    p_i->inq_info.remote_name_state = BTM_INQ_RMT_NAME_DONE;
-                }
-                else
-                    p_i->inq_info.remote_name_state = BTM_INQ_RMT_NAME_EMPTY;
-            }
-            else
-#endif
-            {
-            /* Clear out the device name so that it can be re-read */
-            p_i->inq_info.remote_name_state = BTM_INQ_RMT_NAME_EMPTY;
-            }
-#endif /*(BTM_INQ_GET_REMOTE_NAME==TRUE)*/
-
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
             if( inq_res_mode == BTM_INQ_RESULT_EXTENDED )
             {
                 memset( p_cur->eir_uuid, 0,
@@ -2324,19 +2042,10 @@
             }
             else
                 p_eir_data = NULL;
-#endif
 
             /* If a callback is registered, call it with the results */
             if (p_inq_results_cb)
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
                 (p_inq_results_cb)((tBTM_INQ_RESULTS *) p_cur, p_eir_data);
-#else
-                (p_inq_results_cb)((tBTM_INQ_RESULTS *) p_cur, NULL);
-#endif
-
-            /* If anyone is registered for change notifications, then tell him we added an entry.  */
-            if (p_inq->p_inq_change_cb)
-                (*p_inq->p_inq_change_cb) (&p_i->inq_info, TRUE);
         }
     }
 }
@@ -2400,10 +2109,6 @@
     tBTM_CMPL_CB        *p_inq_cb = btm_cb.btm_inq_vars.p_inq_cmpl_cb;
     tBTM_INQUIRY_VAR_ST *p_inq = &btm_cb.btm_inq_vars;
 
-#if (BTM_INQ_GET_REMOTE_NAME==TRUE)
-    tBTM_INQ_INFO  *p_cur;
-    UINT8           tempstate;
-#endif
 #if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE)
     /* inquiry inactive case happens when inquiry is cancelled.
        Make mode 0 for no further inquiries from the current inquiry process
@@ -2435,35 +2140,12 @@
     BTM_TRACE_DEBUG ("btm_process_inq_complete inq_active:0x%x state:%d inqfilt_active:%d",
         btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state, btm_cb.btm_inq_vars.inqfilt_active);
 #endif
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     btm_acl_update_busy_level (BTM_BLI_INQ_DONE_EVT);
-#endif
     /* Ignore any stray or late complete messages if the inquiry is not active */
     if (p_inq->inq_active)
     {
         p_inq->inq_cmpl_info.status = (tBTM_STATUS)((status == HCI_SUCCESS) ? BTM_SUCCESS : BTM_ERR_PROCESSING);
 
-#if (BTM_INQ_GET_REMOTE_NAME==TRUE)
-        if (p_inq->inq_cmpl_info.status == BTM_SUCCESS)
-        {
-            for (p_cur = BTM_InqDbFirst(); p_cur; p_cur = BTM_InqDbNext (p_cur))
-            {
-                if (p_cur->remote_name_state == BTM_INQ_RMT_NAME_EMPTY)
-                {
-                    tempstate = p_cur->remote_name_state;
-                    p_cur->remote_name_state = BTM_INQ_RMT_NAME_PENDING;
-
-                    if (btm_initiate_rem_name (p_cur->results.remote_bd_addr,
-                                               p_cur, BTM_RMT_NAME_INQ,
-                                               BTM_INQ_RMT_NAME_TIMEOUT, NULL) != BTM_CMD_STARTED)
-                        p_cur->remote_name_state = tempstate;
-                    else
-                        return;
-                }
-            }
-        }
-#endif
-
         /* Notify caller that the inquiry has completed; (periodic inquiries do not send completion events */
         if (!(p_inq->inq_active & BTM_PERIODIC_INQUIRY_ACTIVE) && p_inq->inqparms.mode == 0)
         {
@@ -2475,7 +2157,7 @@
             btm_clr_inq_result_flt();
 
             if((p_inq->inq_cmpl_info.status == BTM_SUCCESS) &&
-                HCI_LMP_INQ_RSSI_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+                controller_get_interface()->supports_rssi_with_inquiry_results())
             {
                 btm_sort_inq_result();
             }
@@ -2534,9 +2216,7 @@
 *******************************************************************************/
 void btm_process_cancel_complete(UINT8 status, UINT8 mode)
 {
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
      btm_acl_update_busy_level (BTM_BLI_INQ_CANCEL_EVT);
-#endif
      btm_process_inq_complete(status, mode);
 }
 /*******************************************************************************
@@ -2619,40 +2299,10 @@
                 return BTM_NO_RESOURCES;
         }
     }
-    /* If the inquire feature is on */
-#if (BTM_INQ_GET_REMOTE_NAME==TRUE)
-
-    else if (origin == BTM_RMT_NAME_INQ)
-    {
-        /* If the database entry exists for the device, use its clock offset */
-        if (p_cur)
-        {
-            cmd_ok = btsnd_hcic_rmt_name_req (remote_bda,
-                                     p_cur->results.page_scan_rep_mode,
-                                     p_cur->results.page_scan_mode,
-                                     (UINT16)(p_cur->results.clock_offset |
-                                              BTM_CLOCK_OFFSET_VALID));
-        }
-        else
-        {
-            cmd_ok = FALSE
-        }
-
-        if (cmd_ok)
-            return BTM_CMD_STARTED;
-        else
-            return BTM_NO_RESOURCES;
-    }
-#endif
     else
     {
-
         return BTM_ILLEGAL_VALUE;
-
-
     }
-
-
 }
 
 /*******************************************************************************
@@ -2675,14 +2325,6 @@
 
     UINT16                 temp_evt_len;
 
-#if (BTM_INQ_GET_REMOTE_NAME==TRUE)
-    /*** These are only used if part of the Inquiry Process ***/
-    tBTM_CMPL_CB           *p_inq_cb;
-    tINQ_DB_ENT            *p_i = NULL;
-    UINT8                  *p_n;
-    tBTM_INQ_INFO          *p_cur;
-#endif
-
     if (bda != NULL)
     {
         BTM_TRACE_EVENT("BDA %02x:%02x:%02x:%02x:%02x:%02x",bda[0], bda[1],
@@ -2690,7 +2332,7 @@
                  bda[4], bda[5]);
     }
 
-	BTM_TRACE_EVENT("Inquire BDA %02x:%02x:%02x:%02x:%02x:%02x",p_inq->remname_bda[0], p_inq->remname_bda[1],
+    BTM_TRACE_EVENT("Inquire BDA %02x:%02x:%02x:%02x:%02x:%02x",p_inq->remname_bda[0], p_inq->remname_bda[1],
              p_inq->remname_bda[2], p_inq->remname_bda[3],
              p_inq->remname_bda[4], p_inq->remname_bda[5]);
 
@@ -2701,7 +2343,7 @@
         (((bda != NULL) &&
         (memcmp(bda, p_inq->remname_bda,BD_ADDR_LEN)==0)) || bda == NULL))
 
-	{
+    {
 #if BLE_INCLUDED == TRUE
         if (BTM_UseLeLink(p_inq->remname_bda))
         {
@@ -2749,98 +2391,6 @@
         if (p_cb)
             (p_cb)((tBTM_REMOTE_DEV_NAME *)&rem_name);
     }
-
-
-#if (BTM_INQ_GET_REMOTE_NAME==TRUE)
-    /* If existing entry, update the name */
-    if ((bda != NULL) && ((p_i = btm_inq_db_find (bda)) != NULL)
-     && (hci_status == HCI_SUCCESS))
-    {
-        p_i->inq_info.remote_name_state = BTM_INQ_RMT_NAME_DONE;
-        p_n = p_i->inq_info.remote_name;
-        memset(p_n, 0, BTM_MAX_REM_BD_NAME_LEN + 1);
-        p_i->inq_info.remote_name_len = (rem_name.length < BTM_MAX_REM_BD_NAME_LEN) ?
-                                         rem_name.length : BTM_MAX_REM_BD_NAME_LEN;
-        evt_len = p_i->inq_info.remote_name_len;
-        p_n1 = (UINT8 *)rem_name.remote_bd_name;
-        while (evt_len > 0)
-        {
-            *p_n++ = *p_n1++;
-            evt_len--;
-        }
-
-        if (btm_cb.btm_inq_vars.p_inq_change_cb)
-            (*btm_cb.btm_inq_vars.p_inq_change_cb) (&p_i->inq_info, TRUE);
-    }
-    else
-    {
-        if (p_i)
-            p_i->inq_info.remote_name_state = BTM_INQ_RMT_NAME_FAILED;
-        else
-        {
-            /* Find the entry which is currently doing name request */
-            for (p_cur = BTM_InqDbFirst(); p_cur; p_cur = BTM_InqDbNext (p_cur))
-            {
-                if (p_cur->remote_name_state == BTM_INQ_RMT_NAME_PENDING)
-                {
-                    /* Should be only one */
-                    p_cur->remote_name_state = BTM_INQ_RMT_NAME_FAILED;
-                    break;
-                }
-            }
-        }
-    }
-
-    /* If an inquiry is in progress then update other entries */
-    if (p_inq->inq_active)
-    {
-        /* Check if there are any more entries inquired but not named */
-        for (p_cur = BTM_InqDbFirst(); p_cur; p_cur = BTM_InqDbNext (p_cur))
-        {
-            if (p_cur->remote_name_state == BTM_INQ_RMT_NAME_EMPTY)
-            {
-                p_cur->remote_name_state = BTM_INQ_RMT_NAME_PENDING;
-#if (BLE_INCLUDED == TRUE)
-                if (BTM_UseLeLink(remote_bda))
-                {
-                    if (btm_ble_read_remote_name(remote_bda, p_cur, p_cb) != BTM_CMD_STARTED)
-                        p_cur->remote_name_state = BTM_INQ_RMT_NAME_FAILED;
-                    else
-                        return;
-                }
-                else
-#endif
-                {
-                    if (btm_initiate_rem_name (p_cur->results.remote_bd_addr,
-                                               p_cur, BTM_RMT_NAME_INQ,
-                                               BTM_INQ_RMT_NAME_TIMEOUT, NULL) != BTM_CMD_STARTED)
-                        p_cur->remote_name_state = BTM_INQ_RMT_NAME_FAILED;
-                    else
-                        return;
-                }
-            }
-        }
-
-        /* The inquiry has finished so call the callback for the inquiry */
-        p_inq_cb = p_inq->p_inq_cmpl_cb;
-        p_inq->state = BTM_INQ_INACTIVE_STATE;
-        p_inq->inq_active = BTM_INQUIRY_INACTIVE;
-        p_inq->p_inq_cmpl_cb = NULL;
-
-        /* If we have a callback registered for inquiry complete, call it */
-        if (p_inq_cb)
-            (p_inq_cb)((tBTM_INQUIRY_CMPL *) &p_inq->inq_cmpl_info);
-
-        /* In some cases we can not get name of the device once but will be */
-        /* able to do it next time.  Until we have better solution we will  */
-        /* try to get name every time */
-        for (p_cur = BTM_InqDbFirst(); p_cur; p_cur = BTM_InqDbNext (p_cur))
-        {
-            if (p_cur->remote_name_state == BTM_INQ_RMT_NAME_FAILED)
-                p_cur->remote_name_state = BTM_INQ_RMT_NAME_EMPTY;
-        }
-    }
-#endif  /* BTM_INQ_GET_REMOTE_NAME == TRUE */
 }
 
 /*******************************************************************************
@@ -2917,8 +2467,7 @@
 *******************************************************************************/
 tBTM_STATUS BTM_WriteEIR( BT_HDR *p_buff )
 {
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
-    if (HCI_EXT_INQ_RSP_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+    if (controller_get_interface()->supports_extended_inquiry_response())
     {
         BTM_TRACE_API("Write Extended Inquiry Response to controller");
         btsnd_hcic_write_ext_inquiry_response (p_buff, BTM_EIR_DEFAULT_FEC_REQUIRED);
@@ -2929,10 +2478,6 @@
         GKI_freebuf(p_buff);
         return BTM_MODE_UNSUPPORTED;
     }
-#else
-    GKI_freebuf(p_buff);
-    return BTM_SUCCESS;
-#endif
 }
 
 /*******************************************************************************
@@ -2950,7 +2495,6 @@
 *******************************************************************************/
 UINT8 *BTM_CheckEirData( UINT8 *p_eir, UINT8 type, UINT8 *p_length )
 {
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
     UINT8 *p = p_eir;
     UINT8 length;
     UINT8 eir_type;
@@ -2972,9 +2516,6 @@
 
     *p_length = 0;
     return NULL;
-#else
-    return NULL;
-#endif
 }
 
 /*******************************************************************************
@@ -2989,7 +2530,6 @@
 **                  BTM_EIR_MAX_SERVICES - if not found
 **
 *******************************************************************************/
-#if (( BTM_EIR_CLIENT_INCLUDED == TRUE )||( BTM_EIR_SERVER_INCLUDED == TRUE ))
 static UINT8 btm_convert_uuid_to_eir_service( UINT16 uuid16 )
 {
     UINT8 xx;
@@ -3003,7 +2543,6 @@
     }
     return BTM_EIR_MAX_SERVICES;
 }
-#endif
 
 /*******************************************************************************
 **
@@ -3020,7 +2559,6 @@
 *******************************************************************************/
 BOOLEAN BTM_HasEirService( UINT32 *p_eir_uuid, UINT16 uuid16 )
 {
-#if ((BTM_EIR_SERVER_INCLUDED == TRUE)||(BTM_EIR_CLIENT_INCLUDED == TRUE))
     UINT8 service_id;
 
     service_id = btm_convert_uuid_to_eir_service(uuid16);
@@ -3028,9 +2566,6 @@
         return( BTM_EIR_HAS_SERVICE( p_eir_uuid, service_id ));
     else
         return( FALSE );
-#else
-    return( FALSE );
-#endif
 }
 
 /*******************************************************************************
@@ -3049,7 +2584,6 @@
 *******************************************************************************/
 tBTM_EIR_SEARCH_RESULT BTM_HasInquiryEirService( tBTM_INQ_RESULTS *p_results, UINT16 uuid16 )
 {
-#if ((BTM_EIR_SERVER_INCLUDED == TRUE)||(BTM_EIR_CLIENT_INCLUDED == TRUE))
     if( BTM_HasEirService( p_results->eir_uuid, uuid16 ))
     {
         return BTM_EIR_FOUND;
@@ -3060,9 +2594,6 @@
     }
     else
         return BTM_EIR_UNKNOWN;
-#else
-    return BTM_EIR_UNKNOWN;
-#endif
 }
 
 /*******************************************************************************
@@ -3079,13 +2610,11 @@
 *******************************************************************************/
 void BTM_AddEirService( UINT32 *p_eir_uuid, UINT16 uuid16 )
 {
-#if ((BTM_EIR_SERVER_INCLUDED == TRUE)||(BTM_EIR_CLIENT_INCLUDED == TRUE))
     UINT8 service_id;
 
     service_id = btm_convert_uuid_to_eir_service(uuid16);
     if( service_id < BTM_EIR_MAX_SERVICES )
         BTM_EIR_SET_SERVICE( p_eir_uuid, service_id );
-#endif
 }
 
 /*******************************************************************************
@@ -3102,13 +2631,11 @@
 *******************************************************************************/
 void BTM_RemoveEirService( UINT32 *p_eir_uuid, UINT16 uuid16 )
 {
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
     UINT8 service_id;
 
     service_id = btm_convert_uuid_to_eir_service(uuid16);
     if( service_id < BTM_EIR_MAX_SERVICES )
         BTM_EIR_CLR_SERVICE( p_eir_uuid, service_id );
-#endif
 }
 
 /*******************************************************************************
@@ -3129,7 +2656,6 @@
 UINT8 BTM_GetEirSupportedServices( UINT32 *p_eir_uuid,    UINT8 **p,
                                    UINT8  max_num_uuid16, UINT8 *p_num_uuid16)
 {
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
     UINT8 service_index;
 
     *p_num_uuid16 = 0;
@@ -3151,9 +2677,6 @@
         }
     }
     return BTM_EIR_COMPLETE_16BITS_UUID_TYPE;
-#else
-    return BTM_EIR_COMPLETE_16BITS_UUID_TYPE;
-#endif
 }
 
 /*******************************************************************************
@@ -3180,7 +2703,6 @@
 UINT8 BTM_GetEirUuidList( UINT8 *p_eir, UINT8 uuid_size, UINT8 *p_num_uuid,
                             UINT8 *p_uuid_list, UINT8 max_num_uuid)
 {
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
     UINT8   *p_uuid_data;
     UINT8   type;
     UINT8   yy, xx;
@@ -3231,14 +2753,9 @@
     }
 
     return type;
-#else
-    *p_num_uuid = 0;
-    return 0x00;
-#endif
 }
 
 
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
 /*******************************************************************************
 **
 ** Function         btm_eir_get_uuid_list
@@ -3422,5 +2939,3 @@
         }
     }
 }
-#endif
-
diff --git a/stack/btm/btm_int.h b/stack/btm/btm_int.h
index fcb17bb..37931e7 100644
--- a/stack/btm/btm_int.h
+++ b/stack/btm/btm_int.h
@@ -29,9 +29,7 @@
 #include "gki.h"
 #include "hcidefs.h"
 
-#if RFCOMM_INCLUDED == TRUE
 #include "rfcdefs.h"
-#endif
 
 #include "btm_api.h"
 
@@ -69,10 +67,10 @@
                                           HCI_PKT_TYPES_MASK_NO_3_DH5)
 
 #define BTM_EPR_AVAILABLE(p) ((HCI_ATOMIC_ENCRYPT_SUPPORTED((p)->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]) && \
-                               HCI_ATOMIC_ENCRYPT_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0])) \
+                               HCI_ATOMIC_ENCRYPT_SUPPORTED(controller_get_interface()->get_features_classic(0)->as_array)) \
                                ? TRUE : FALSE)
 
-#define BTM_IS_BRCM_CONTROLLER() (btm_cb.devcb.local_version.manufacturer == LMP_COMPID_BROADCOM)
+#define BTM_IS_BRCM_CONTROLLER() (controller_get_interface()->get_bt_version()->manufacturer == LMP_COMPID_BROADCOM)
 
 /* Define the ACL Management control structure
 */
@@ -80,7 +78,6 @@
 {
     UINT16          hci_handle;
     UINT16          pkt_types_mask;
-    UINT16          restore_pkt_types;  /* when coming in/out of SCO connection restore the packet types */
     UINT16          clock_offset;
     BD_ADDR         remote_addr;
     DEV_CLASS       remote_dc;
@@ -104,7 +101,6 @@
 #define BTM_ACL_SWKEY_STATE_ENCRYPTION_ON       4
 #define BTM_ACL_SWKEY_STATE_IN_PROGRESS         5
     UINT8           switch_role_state;
-    UINT8           change_key_state;
 
 #define BTM_ACL_ENCRYPT_STATE_IDLE              0
 #define BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF       1   /* encryption turning off */
@@ -112,10 +108,6 @@
 #define BTM_ACL_ENCRYPT_STATE_ENCRYPT_ON        3   /* encryption turning on */
     UINT8           encrypt_state;                  /* overall BTM encryption state */
 
-#if BTM_PWR_MGR_INCLUDED == FALSE
-    UINT8           mode;
-#endif /* BTM_PWR_MGR_INCLUDED */
-
 #if BLE_INCLUDED == TRUE
     tBT_TRANSPORT   transport;
     BD_ADDR         conn_addr;              /* local device address used for this connection */
@@ -145,14 +137,10 @@
     tBTM_CMPL_CB        *p_stored_link_key_cmpl_cb;   /* Read/Write/Delete stored link key    */
 
     TIMER_LIST_ENT       reset_timer;
-    tBTM_CMPL_CB        *p_reset_cmpl_cb;   /* Callback function to be called       */
-                                            /* when startup of the device is done   */
+
     TIMER_LIST_ENT       rln_timer;
     tBTM_CMPL_CB        *p_rln_cmpl_cb;     /* Callback function to be called when  */
                                             /* read local name function complete    */
-    TIMER_LIST_ENT       rlinkp_timer;
-    tBTM_CMPL_CB        *p_rlinkp_cmpl_cb;  /* Callback function to be called when  */
-                                            /* read link policy function completes  */
     TIMER_LIST_ENT       rssi_timer;
     tBTM_CMPL_CB        *p_rssi_cmpl_cb;    /* Callback function to be called when  */
                                             /* read rssi function completes         */
@@ -171,36 +159,21 @@
     tBTM_CMPL_CB        *p_switch_role_cb;  /* Callback function to be called when  */
                                             /* requested switch role is completed   */
 
-    tBTM_CHANGE_KEY_CMPL chg_link_key_ref_data;
-    tBTM_CMPL_CB        *p_chg_link_key_cb; /* Callback function to be called when  */
-                                            /* change of link key is completed      */
-
     TIMER_LIST_ENT       tx_power_timer;
     tBTM_CMPL_CB        *p_tx_power_cmpl_cb;/* Callback function to be called       */
 
-    BD_ADDR              local_addr;        /* BD_ADDR of the local device          */
-    tBTM_VERSION_INFO    local_version;     /* Local Version Information            */
     DEV_CLASS            dev_class;         /* Local device class                   */
 
-    /* Local LMP Extended features mask table for the device */
-    BD_FEATURES          local_lmp_features[HCI_EXT_FEATURES_PAGE_MAX + 1];
-
 #if BLE_INCLUDED == TRUE
 
     tBTM_CMPL_CB        *p_le_test_cmd_cmpl_cb;   /* Callback function to be called when
                                                   LE test mode command has been sent successfully */
 
     BD_ADDR                 read_tx_pwr_addr;   /* read TX power target address     */
-    BD_FEATURES             local_le_features;  /* Local LE Supported features mask for the device */
 
     tBTM_BLE_LOCAL_ID_KEYS  id_keys;        /* local BLE ID keys                    */
     BT_OCTET16              er;             /* BLE encryption key                   */
 
-#define BTM_LE_SUPPORT_STATE_SIZE   8
-UINT8                   le_supported_states[BTM_LE_SUPPORT_STATE_SIZE];
-
-
-
 #if BTM_BLE_CONFORMANCE_TESTING == TRUE
     BOOLEAN                 no_disc_if_pair_fail;
     BOOLEAN                 enable_test_mac_val;
@@ -212,23 +185,8 @@
 
 #endif  /* BLE_INCLUDED */
 
-#define BTM_DEV_STATE_WAIT_RESET_CMPLT  0
-#define BTM_DEV_STATE_WAIT_AFTER_RESET  1
-#define BTM_DEV_STATE_READY             2
-
-    UINT8                state;
     tBTM_IO_CAP          loc_io_caps;       /* IO capability of the local device */
     tBTM_AUTH_REQ        loc_auth_req;      /* the auth_req flag  */
-    BD_FEATURES          brcm_features;     /* Broadcom specific features bit mask  */
-#define BTM_RELOAD_LE_HOST_FEATURE      0x10
-
-#define BTM_RE_READ_1ST_PAGE            0x01            /* Set it if you set at least one of "..._HOST_MAY_SUPP_..." bits */
-#define BTM_HOST_MAY_SUPP_SSP           0x02
-#define BTM_HOST_MAY_SUPP_LE            0x04
-#define BTM_HOST_MAY_SUPP_SIMULT_BR_LE  0x08
-    UINT8               lmp_features_host_may_support;  /* The flags of LMP features host may support via BR/EDR ctrlr + BTM_RE_READ_1ST_PAGE */
-    UINT8               supported_cmds[HCI_NUM_SUPP_COMMANDS_BYTES]; /* Supported Commands bit field */
-
 } tBTM_DEVCB;
 
 
@@ -246,7 +204,6 @@
 #define BTM_MIN_INQ_TX_POWER    -70
 #define BTM_MAX_INQ_TX_POWER    20
 
-#if BTM_USE_INQ_RESULTS_FILTER == TRUE
 typedef struct
 {
     UINT32          inq_count;          /* Used for determining if a response has already been      */
@@ -255,7 +212,6 @@
                                         /* the same device.                                         */
     BD_ADDR         bd_addr;
 } tINQ_BDADDR;
-#endif
 
 typedef struct
 {
@@ -313,16 +269,13 @@
     tBTM_CMPL_CB    *p_inq_ble_cmpl_cb;     /*completion callback exclusively for LE Observe*/
     tBTM_INQ_RESULTS_CB *p_inq_ble_results_cb;/*results callback exclusively for LE observe*/
     tBTM_CMPL_CB    *p_inqfilter_cmpl_cb;   /* Called (if not NULL) after inquiry filter completed */
-    tBTM_INQ_DB_CHANGE_CB *p_inq_change_cb; /* Inquiry database changed callback    */
     UINT32           inq_counter;           /* Counter incremented each time an inquiry completes */
                                             /* Used for determining whether or not duplicate devices */
                                             /* have responded to the same inquiry */
     TIMER_LIST_ENT   inq_timer_ent;
-#if BTM_USE_INQ_RESULTS_FILTER == TRUE
     tINQ_BDADDR     *p_bd_db;               /* Pointer to memory that holds bdaddrs */
     UINT16           num_bd_entries;        /* Number of entries in database */
     UINT16           max_bd_entries;        /* Maximum number of entries that can be stored */
-#endif
     tINQ_DB_ENT      inq_db[BTM_INQ_DB_SIZE];
     tBTM_INQ_PARMS   inqparms;              /* Contains the parameters for the current inquiry */
     tBTM_INQUIRY_CMPL inq_cmpl_info;        /* Status and number of responses from the last inquiry */
@@ -643,7 +596,6 @@
     UINT8            def_inq_scan_mode;          /* ??? limited/general/none */
 } tBTM_CFG;
 
-#if BTM_PWR_MGR_INCLUDED == TRUE
 enum
 {
     BTM_PM_ST_ACTIVE  = BTM_PM_STS_ACTIVE,
@@ -708,7 +660,6 @@
     tBTM_PM_STATUS_CBACK *cback;/* to notify the registered party of mode change event */
     UINT8                 mask; /* registered request mask. 0, if this entry is not used */
 } tBTM_PM_RCB;
-#endif  /* BTM_PWR_MGR_INCLUDED */
 
 enum
 {
@@ -784,18 +735,6 @@
 
 #define BTM_STATE_BUFFER_SIZE  5                  /* size of state buffer */
 
-#if (BTM_PCM2_INCLUDED == TRUE)
-/* Define pcm2_action           */
-enum
-{
-    BTM_PCM2_ACT_NONE,
-    BTM_PCM2_ACT_SENT_ARC,
-    BTM_PCM2_READ_PARAM,
-    BTM_PCM2_WRITE_PARAM,
-};
-typedef UINT8 tBTM_PCM2_ACTION;
-#endif
-
 typedef struct
 {
     tBTM_CFG    cfg;                        /* Device configuration */
@@ -804,30 +743,20 @@
     **      ACL Management
     ****************************************************/
     tACL_CONN   acl_db[MAX_L2CAP_LINKS];
-#if( RFCOMM_INCLUDED==TRUE)
     UINT8       btm_scn[BTM_MAX_SCN];        /* current SCNs: TRUE if SCN is in use */
-#endif
     UINT16      btm_def_link_policy;
     UINT16      btm_def_link_super_tout;
 
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     tBTM_BL_EVENT_MASK     bl_evt_mask;
     tBTM_BL_CHANGE_CB     *p_bl_changed_cb;    /* Callback for when Busy Level changed */
-#else
-    tBTM_ACL_DB_CHANGE_CB *p_acl_changed_cb;    /* Callback for when ACL DB changed */
-#endif
-
-    tBTM_LSTO_CBACK       *p_lsto_cback;  /* for link supervision timeout change event */
 
     /****************************************************
     **      Power Management
     ****************************************************/
-#if BTM_PWR_MGR_INCLUDED == TRUE
     tBTM_PM_MCB pm_mode_db[MAX_L2CAP_LINKS];   /* per ACL link */
     tBTM_PM_RCB pm_reg_db[BTM_MAX_PM_RECORDS+1]; /* per application/module */
     UINT8       pm_pend_link;  /* the index of acl_db, which has a pending PM cmd */
     UINT8       pm_pend_id;    /* the id pf the module, which has a pending PM cmd */
-#endif /* BTM_PWR_MGR_INCLUDED == TRUE */
 
     /*****************************************************
     **      Device control
@@ -856,8 +785,6 @@
     **      Inquiry
     *****************************************************/
     tBTM_INQUIRY_VAR_ST     btm_inq_vars;
-    tBTM_FILTER_CB          *p_inq_filter_cb;   /* Callback that can be set if host */
-                                                /* wants to verify inquiry filters */
 
     /*****************************************************
     **      SCO Management
@@ -874,9 +801,6 @@
 #define BTM_SEC_MAX_RMT_NAME_CALLBACKS  2
     tBTM_RMT_NAME_CALLBACK  *p_rmt_name_callback[BTM_SEC_MAX_RMT_NAME_CALLBACKS];
 
-    tBTM_FILTER_CB          *p_conn_filter_cb;  /* Callback that can be set if host */
-                                                /* wants to verify connectability filters*/
-
     tBTM_SEC_DEV_REC        *p_collided_dev_rec;
     TIMER_LIST_ENT           sec_collision_tle;
     UINT32                   collision_start_time;
@@ -910,17 +834,11 @@
     BD_ADDR                  connecting_bda;
     DEV_CLASS                connecting_dc;
 
-    UINT8                   first_disabled_channel;
-    UINT8                   last_disabled_channel;
-
     UINT8                   acl_disc_reason;
     UINT8                   trace_level;
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
-    UINT8                   num_acl;    /* num of active ACL links */
     UINT8                   busy_level; /* the current busy level */
     BOOLEAN                 is_paging;  /* TRUE, if paging is in progess */
     BOOLEAN                 is_inquiry; /* TRUE, if inquiry is in progess */
-#endif
     BUFFER_Q                page_queue;
     BOOLEAN                 paging;
     BOOLEAN                 discing;
@@ -930,12 +848,6 @@
     char state_temp_buffer[BTM_STATE_BUFFER_SIZE];
 #endif
 
-#if (defined(BTM_PCM2_INCLUDED) && BTM_PCM2_INCLUDED == TRUE)
-    UINT16                  sys_features;
-    UINT8                   pcm2_params[BRCM_PCM2_SETUP_WRITE_SIZE];
-    tBTM_PCM2_ACTION        pcm2_action;
-#endif
-
 } tBTM_CB;
 
 
@@ -945,9 +857,9 @@
 #endif
 
 #if BTM_DYNAMIC_MEMORY == FALSE
-BTM_API extern tBTM_CB  btm_cb;
+extern tBTM_CB  btm_cb;
 #else
-BTM_API extern tBTM_CB *btm_cb_ptr;
+extern tBTM_CB *btm_cb_ptr;
 #define btm_cb (*btm_cb_ptr)
 #endif
 
@@ -980,25 +892,21 @@
 extern tINQ_DB_ENT *btm_inq_db_find (BD_ADDR p_bda);
 extern BOOLEAN      btm_inq_find_bdaddr (BD_ADDR p_bda);
 
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
 extern BOOLEAN btm_lookup_eir(BD_ADDR_PTR p_rem_addr);
-#endif
 
 /* Internal functions provided by btm_acl.c
 ********************************************
 */
 extern void         btm_acl_init (void);
-extern void         btm_acl_timeout (TIMER_LIST_ENT  *p_tle);
 extern void         btm_acl_created (BD_ADDR bda, DEV_CLASS dc, BD_NAME bdn,
                                      UINT16 hci_handle, UINT8 link_role, tBT_TRANSPORT transport);
 extern void         btm_acl_removed (BD_ADDR bda, tBT_TRANSPORT transport);
 extern void         btm_acl_device_down (void);
 extern void         btm_acl_update_busy_level (tBTM_BLI_EVENT event);
-extern void         btm_acl_link_key_change (UINT16 handle, UINT8 status);
 
-extern void         btm_cont_rswitch_or_chglinkkey (tACL_CONN *p,
-                                                    tBTM_SEC_DEV_REC *p_dev_rec,
-                                                    UINT8 hci_status);
+extern void         btm_cont_rswitch (tACL_CONN *p,
+                                      tBTM_SEC_DEV_REC *p_dev_rec,
+                                      UINT8 hci_status);
 
 extern UINT8        btm_handle_to_acl_index (UINT16 hci_handle);
 extern void         btm_read_link_policy_complete (UINT8 *p);
@@ -1009,8 +917,8 @@
 extern void         btm_process_clk_off_comp_evt (UINT16 hci_handle, UINT16 clock_offset);
 extern void         btm_acl_role_changed (UINT8 hci_status, BD_ADDR bd_addr, UINT8 new_role);
 extern void         btm_acl_encrypt_change (UINT16 handle, UINT8 status, UINT8 encr_enable);
-BTM_API extern UINT16       btm_get_acl_disc_reason_code (void);
-BTM_API extern tBTM_STATUS  btm_remove_acl (BD_ADDR bd_addr, tBT_TRANSPORT transport);
+extern UINT16       btm_get_acl_disc_reason_code (void);
+extern tBTM_STATUS  btm_remove_acl (BD_ADDR bd_addr, tBT_TRANSPORT transport);
 extern void         btm_read_remote_features_complete (UINT8 *p);
 extern void         btm_read_remote_ext_features_complete (UINT8 *p);
 extern void         btm_read_remote_ext_features_failed (UINT8 status, UINT16 handle);
@@ -1025,14 +933,6 @@
 extern tACL_CONN *btm_bda_to_acl (BD_ADDR bda, tBT_TRANSPORT transport);
 extern BOOLEAN    btm_acl_notif_conn_collision (BD_ADDR bda);
 
-#if BTM_PWR_MGR_INCLUDED == FALSE
-extern void         btm_process_mode_change (UINT8 hci_status, UINT16 hci_handle, UINT8 mode,
-                                             UINT16 interval);
-
-/* Internal functions provided by btm_pm.c
-********************************************
-*/
-#else
 extern void btm_pm_reset(void);
 extern void btm_pm_sm_alloc(UINT8 ind);
 extern void btm_pm_proc_cmd_status(UINT8 status);
@@ -1044,7 +944,6 @@
 #else
 #define btm_sco_chk_pend_unpark(hci_status, hci_handle)
 #endif /* BTM_SCO_INCLUDED */
-#endif /* BTM_PWR_MGR_INCLUDED == FALSE */
 extern void btm_qos_setup_complete (UINT8 status, UINT16 handle, FLOW_SPEC *p_flow);
 
 
@@ -1073,24 +972,10 @@
 **********************************************
 */
 extern void btm_dev_init (void);
-extern void btm_dev_absent (void);
 extern void btm_dev_timeout (TIMER_LIST_ENT *p_tle);
-extern void btm_reset_complete (void);
-extern void btm_read_local_version_complete (UINT8 *p, UINT16 evt_len);
-extern void btm_read_hci_buf_size_complete (UINT8 *p, UINT16 evt_len);
-extern void btm_read_local_supported_cmds_complete (UINT8 *p);
-extern void btm_read_local_features_complete (UINT8 *p, UINT16 evt_len);
-extern void btm_read_local_ext_features_complete (UINT8 *p, UINT16 evt_len);
 extern void btm_read_local_name_complete (UINT8 *p, UINT16 evt_len);
-extern void btm_read_local_addr_complete (UINT8 *p, UINT16 evt_len);
-extern  void btm_reset_ctrlr_complete (void);
-extern void btm_write_simple_paring_mode_complete (UINT8 *p);
-extern void btm_write_le_host_supported_complete (UINT8 *p);
 
 #if (BLE_INCLUDED == TRUE)
-extern void btm_read_ble_buf_size_complete (UINT8 *p, UINT16 evt_len);
-extern void btm_read_ble_local_supported_features_complete (UINT8 *p, UINT16 evt_len);
-extern void btm_read_white_list_size_complete(UINT8 *p, UINT16 evt_len);
 extern void btm_ble_add_2_white_list_complete(UINT8 status);
 extern void btm_ble_remove_from_white_list_complete(UINT8 *p, UINT16 evt_len);
 extern void btm_ble_clear_white_list_complete(UINT8 *p, UINT16 evt_len);
@@ -1101,11 +986,7 @@
                               tBTM_CMPL_CB *p_vsc_cplt_cback);
 extern void btm_inq_db_reset (void);
 extern void btm_vendor_specific_evt (UINT8 *p, UINT8 evt_len);
-extern UINT8 btm_get_hci_version (void);
-extern void btm_read_stored_link_key_complete (UINT8 *p);
-extern void btm_write_stored_link_key_complete (UINT8 *p);
 extern void btm_delete_stored_link_key_complete (UINT8 *p);
-extern void btm_return_link_keys_evt (tBTM_RETURN_LINK_KEYS_EVT *result);
 extern void btm_report_device_status (tBTM_DEV_STATUS status);
 
 
@@ -1113,7 +994,6 @@
 **********************************************
 */
 extern BOOLEAN btm_dev_support_switch (BD_ADDR bd_addr);
-extern UINT8 btm_get_voice_coding_support (void);
 
 extern tBTM_SEC_DEV_REC  *btm_sec_alloc_dev (BD_ADDR bd_addr);
 extern void               btm_sec_free_dev (tBTM_SEC_DEV_REC *p_dev_rec);
@@ -1133,14 +1013,12 @@
                                         tBTM_SEC_CALLBACK *p_callback, void *p_ref_data);
 extern void  btm_sec_conn_req (UINT8 *bda, UINT8 *dc);
 extern void btm_create_conn_cancel_complete (UINT8 *p);
-extern void btm_proc_lsto_evt(UINT16 handle, UINT16 timeout);
 extern void btm_read_linq_tx_power_complete (UINT8 *p);
 
 extern void  btm_sec_init (UINT8 sec_mode);
 extern void  btm_sec_dev_reset (void);
 extern void  btm_sec_abort_access_req (BD_ADDR bd_addr);
 extern void  btm_sec_auth_complete (UINT16 handle, UINT8 status);
-extern void  btm_sec_mkey_comp_event (UINT16 handle, UINT8 status, UINT8 key_flg);
 extern void  btm_sec_encrypt_change (UINT16 handle, UINT8 status, UINT8 encr_enable);
 extern void  btm_sec_connected (UINT8 *bda, UINT16 handle, UINT8 status, UINT8 enc_mode);
 extern tBTM_STATUS btm_sec_disconnect (UINT16 handle, UINT8 reason);
@@ -1178,7 +1056,6 @@
 extern void  btm_acl_resubmit_page (void);
 extern void  btm_acl_reset_paging (void);
 extern void  btm_acl_paging (BT_HDR *p, BD_ADDR dest);
-extern void  btm_acl_set_discing (BOOLEAN discing);
 extern UINT8 btm_sec_clr_service_by_psm (UINT16 psm);
 extern void  btm_sec_clr_temp_auth_service (BD_ADDR bda);
 
@@ -1187,4 +1064,3 @@
 #endif
 
 #endif
-
diff --git a/stack/btm/btm_pm.c b/stack/btm/btm_pm.c
index 76bfc04..b22b5de 100644
--- a/stack/btm/btm_pm.c
+++ b/stack/btm/btm_pm.c
@@ -28,10 +28,13 @@
  *
  *****************************************************************************/
 
+#define LOG_TAG "bt_btm_pm"
+
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
 #include <stddef.h>
+
 #include "bt_types.h"
 #include "gki.h"
 #include "hcimsgs.h"
@@ -41,17 +44,7 @@
 #include "l2c_int.h"
 #include "hcidefs.h"
 #include "bt_utils.h"
-
-#if BTM_PWR_MGR_INCLUDED == TRUE
-
-/* This compile option is only useful when the FW has a bug
- * it automatically uses single slot when entering SNIFF mode, but does not restore the setting
- * This issue was found when A2DP link goes into sniff and existing sniff still has choppy audio.
- * If this issue is seen, look for FW solution first.
- * This work around code will be removed later. */
-#ifndef BTM_PM_SNIFF_SLOT_WORK_AROUND
-#define BTM_PM_SNIFF_SLOT_WORK_AROUND       FALSE
-#endif
+#include "osi/include/log.h"
 
 /*****************************************************************************/
 /*      to handle different modes                                            */
@@ -87,6 +80,7 @@
 /* function prototype */
 static int btm_pm_find_acl_ind(BD_ADDR remote_bda);
 static tBTM_STATUS btm_pm_snd_md_req( UINT8 pm_id, int link_ind, tBTM_PM_PWR_MD *p_mode );
+static const char *mode_to_string(tBTM_PM_MODE mode);
 
 /*
 #ifdef BTM_PM_DEBUG
@@ -121,7 +115,7 @@
     "pm_hci_sts_action",
     "pm_update_action"
 };
-#endif
+#endif  // BTM_PM_DEBUG
 
 /*****************************************************************************/
 /*                     P U B L I C  F U N C T I O N S                        */
@@ -241,7 +235,7 @@
     {
 #if BTM_PM_DEBUG == TRUE
     BTM_TRACE_DEBUG( "BTM_SetPowerMode: Saving cmd acl_ind %d temp_pm_id %d", acl_ind,temp_pm_id);
-#endif
+#endif  // BTM_PM_DEBUG
         /* Make sure mask is set to BTM_PM_REG_SET */
         btm_cb.pm_reg_db[temp_pm_id].mask |= BTM_PM_REG_SET;
         *(&p_cb->req_mode[temp_pm_id]) = *((tBTM_PM_PWR_MD *)p_mode);
@@ -250,7 +244,7 @@
 
 #if BTM_PM_DEBUG == TRUE
     BTM_TRACE_DEBUG( "btm_pm state:0x%x, pm_pend_link: %d", p_cb->state, btm_cb.pm_pend_link);
-#endif
+#endif  // BTM_PM_DEBUG
     /* if mode == hold or pending, return */
     if( (p_cb->state == BTM_PM_STS_HOLD) ||
         (p_cb->state ==  BTM_PM_STS_PENDING) ||
@@ -345,7 +339,7 @@
     return BTM_CMD_STORED;
 #else
     return BTM_ILLEGAL_ACTION;
-#endif
+#endif  // BTM_SSR_INCLUDED
 }
 
 /*******************************************************************************
@@ -400,7 +394,7 @@
     p_db->state = BTM_PM_ST_ACTIVE;
 #if BTM_PM_DEBUG == TRUE
     BTM_TRACE_DEBUG( "btm_pm_sm_alloc ind:%d st:%d", ind, p_db->state);
-#endif
+#endif  // BTM_PM_DEBUG
 }
 
 /*******************************************************************************
@@ -423,12 +417,12 @@
         if ((p->in_use) && (!memcmp (p->remote_addr, remote_bda, BD_ADDR_LEN))
 #if (BLE_INCLUDED == TRUE)
             && p->transport == BT_TRANSPORT_BR_EDR
-#endif
+#endif  // BLE_INCLUDED
             )
         {
 #if BTM_PM_DEBUG == TRUE
             BTM_TRACE_DEBUG( "btm_pm_find_acl_ind ind:%d, st:%d", xx, btm_cb.pm_mode_db[xx].state);
-#endif
+#endif  // BTM_PM_DEBUG
             break;
         }
     }
@@ -593,7 +587,7 @@
 #if BTM_PM_DEBUG == TRUE
     BTM_TRACE_DEBUG( "btm_pm_snd_md_req link_ind:%d, mode: %d",
         link_ind, mode);
-#endif
+#endif  // BTM_PM_DEBUG
 
     if( p_cb->state == mode)
     {
@@ -619,7 +613,7 @@
                                   p_cb->min_rmt_to, p_cb->min_loc_to);
         p_cb->max_lat = 0;
     }
-#endif
+#endif  // BTM_SSR_INCLUDED
     /* Default is failure */
     btm_cb.pm_pend_link = MAX_L2CAP_LINKS;
 
@@ -628,7 +622,9 @@
 
 #if BTM_PM_DEBUG == TRUE
     BTM_TRACE_DEBUG("btm_pm_snd_md_req state:0x%x, link_ind: %d", p_cb->state, link_ind);
-#endif
+#endif  // BTM_PM_DEBUG
+
+    LOG_DEBUG("%s switching from %s to %s.", __func__, mode_to_string(p_cb->state), mode_to_string(md_res.mode));
     switch(md_res.mode)
     {
     case BTM_PM_MD_ACTIVE:
@@ -686,7 +682,7 @@
         /* the command was not sent */
 #if BTM_PM_DEBUG == TRUE
         BTM_TRACE_DEBUG( "pm_pend_link: %d",btm_cb.pm_pend_link);
-#endif
+#endif  // BTM_PM_DEBUG
         return (BTM_NO_RESOURCES);
     }
 
@@ -748,7 +744,7 @@
         pm_status = BTM_PM_STS_PENDING;
 #if BTM_PM_DEBUG == TRUE
         BTM_TRACE_DEBUG( "btm_pm_proc_cmd_status new state:0x%x", p_cb->state);
-#endif
+#endif // BTM_PM_DEBUG
     }
     else /* the command was not successfull. Stay in the same state */
     {
@@ -766,7 +762,7 @@
 #if BTM_PM_DEBUG == TRUE
     BTM_TRACE_DEBUG( "btm_pm_proc_cmd_status state:0x%x, pm_pend_link: %d(new: %d)",
         p_cb->state, btm_cb.pm_pend_link, MAX_L2CAP_LINKS);
-#endif
+#endif  // BTM_PM_DEBUG
     btm_cb.pm_pend_link = MAX_L2CAP_LINKS;
 
     btm_pm_check_stored();
@@ -800,57 +796,13 @@
 
     p = &btm_cb.acl_db[xx];
 
-    /*** 2035 and 2045 work around:  If mode is active and coming out of a SCO disconnect, restore packet types ***/
-    if (mode == HCI_MODE_ACTIVE)
-    {
-        if(BTM_GetNumScoLinks() == 0)
-        {
-            if(p->restore_pkt_types)
-    {
-        BTM_TRACE_DEBUG("btm mode change AFTER unsniffing; hci hdl 0x%x, types 0x%02x/0x%02x",
-                            hci_handle, p->pkt_types_mask, p->restore_pkt_types);
-        p->pkt_types_mask = p->restore_pkt_types;
-        p->restore_pkt_types = 0;   /* Only exists while SCO is active */
-        btsnd_hcic_change_conn_type (p->hci_handle, p->pkt_types_mask);
-    }
-#if (BTM_PM_SNIFF_SLOT_WORK_AROUND == TRUE)
-            else
-            {
-                BTM_TRACE_DEBUG("btm mode change AFTER unsniffing; hci hdl 0x%x, types 0x%02x",
-                                    hci_handle, btm_cb.btm_acl_pkt_types_supported);
-                btm_set_packet_types (p, btm_cb.btm_acl_pkt_types_supported);
-            }
-#endif
-        }
-#if (BTM_PM_SNIFF_SLOT_WORK_AROUND == TRUE)
-        else
-        {
-            /* Mode changed from Sniff to Active while SCO is open. */
-            /* Packet types of active mode, not sniff mode, should be used for ACL when SCO is closed. */
-            p->restore_pkt_types = btm_cb.btm_acl_pkt_types_supported;
-
-            /* Exclude packet types not supported by the peer */
-            btm_acl_chk_peer_pkt_type_support (p, &p->restore_pkt_types);
-        }
-#endif
-    }
-#if (BTM_PM_SNIFF_SLOT_WORK_AROUND == TRUE)
-    else if (mode == HCI_MODE_SNIFF)
-    {
-        BTM_TRACE_DEBUG("btm mode change to sniff; hci hdl 0x%x use single slot",
-                            hci_handle);
-        btm_set_packet_types (p, (HCI_PKT_TYPES_MASK_DM1 | HCI_PKT_TYPES_MASK_DH1));
-    }
-#endif
-
     /* update control block */
     p_cb = &(btm_cb.pm_mode_db[xx]);
     old_state       = p_cb->state;
     p_cb->state     = mode;
     p_cb->interval  = interval;
-#if BTM_PM_DEBUG == TRUE
-    BTM_TRACE_DEBUG( "btm_pm_proc_mode_change new state:0x%x (old:0x%x)", p_cb->state, old_state);
-#endif
+
+    LOG_DEBUG("%s switched from %s to %s.", __func__, mode_to_string(old_state), mode_to_string(p_cb->state));
 
     if ((p_lcb = l2cu_find_lcb_by_bd_addr(p->remote_addr, BT_TRANSPORT_BR_EDR)) != NULL)
     {
@@ -876,7 +828,7 @@
     {
 #if BTM_PM_DEBUG == TRUE
         BTM_TRACE_DEBUG( "btm_pm_proc_mode_change: Sending stored req:%d", xx);
-#endif
+#endif  // BTM_PM_DEBUG
         btm_pm_snd_md_req(BTM_PM_SET_ONLY_ID, xx, NULL);
     }
     else
@@ -887,7 +839,7 @@
             {
 #if BTM_PM_DEBUG == TRUE
                 BTM_TRACE_DEBUG( "btm_pm_proc_mode_change: Sending PM req :%d", zz);
-#endif
+#endif   // BTM_PM_DEBUG
                 btm_pm_snd_md_req(BTM_PM_SET_ONLY_ID, zz, NULL);
                 break;
             }
@@ -905,7 +857,7 @@
     }
 
     /* If mode change was because of an active role switch or change link key */
-    btm_cont_rswitch_or_chglinkkey(p, btm_find_dev(p->remote_addr), hci_status);
+    btm_cont_rswitch(p, btm_find_dev(p->remote_addr), hci_status);
 }
 
 /*******************************************************************************
@@ -922,7 +874,7 @@
 {
     UINT8       status;
     UINT16      handle;
-    UINT16      max_tx_lat, max_rx_lat;
+    UINT16      max_rx_lat;
     int         xx, yy;
     tBTM_PM_MCB *p_cb;
     tACL_CONN   *p_acl=NULL;
@@ -936,7 +888,7 @@
     if ((xx = btm_handle_to_acl_index(handle)) >= MAX_L2CAP_LINKS)
         return;
 
-    STREAM_TO_UINT16 (max_tx_lat, p);
+    p += 2;
     STREAM_TO_UINT16 (max_rx_lat, p);
     p_cb = &(btm_cb.pm_mode_db[xx]);
 
@@ -959,52 +911,7 @@
         }
     }
 }
-
-#endif
-
-#else /* BTM_PWR_MGR_INCLUDED == TRUE */
-
-/*******************************************************************************
-**
-** Functions        BTM_PmRegister, BTM_SetPowerMode, and BTM_ReadPowerMode
-**
-** Description      Stubbed versions for BTM_PWR_MGR_INCLUDED = FALSE
-**
-** Returns          BTM_MODE_UNSUPPORTED.
-**
-*******************************************************************************/
-tBTM_STATUS BTM_PmRegister (UINT8 mask, UINT8 *p_pm_id, tBTM_PM_STATUS_CBACK *p_cb)
-{
-    return BTM_MODE_UNSUPPORTED;
-}
-
-tBTM_STATUS BTM_SetPowerMode (UINT8 pm_id, BD_ADDR remote_bda, tBTM_PM_PWR_MD *p_mode)
-{
-    return BTM_MODE_UNSUPPORTED;
-}
-
-tBTM_STATUS BTM_ReadPowerMode (BD_ADDR remote_bda, tBTM_PM_MODE *p_mode)
-{
-    return BTM_MODE_UNSUPPORTED;
-}
-
-#endif
-
-
-/*******************************************************************************
-**
-** Function         BTM_IsPowerManagerOn
-**
-** Description      This function is called to check if power manager is included.
-**                  in the BTE version.
-**
-** Returns          BTM_PWR_MGR_INCLUDED.
-**
-*******************************************************************************/
-BOOLEAN BTM_IsPowerManagerOn (void)
-{
-    return BTM_PWR_MGR_INCLUDED;
-}
+#endif  // BTM_SSR_INCLUDED
 
 /*******************************************************************************
 **
@@ -1020,9 +927,9 @@
     /* The active state is the highest state-includes connected device and sniff mode*/
 
     /* Covers active and sniff modes */
-    if (btm_cb.num_acl > 0)
+    if (BTM_GetNumAclLinks() > 0)
     {
-        BTM_TRACE_DEBUG("btm_pm_device_in_active_or_sniff_mode-acl:%d", btm_cb.num_acl);
+        BTM_TRACE_DEBUG("%s - ACL links: %d", __func__, BTM_GetNumAclLinks());
         return TRUE;
     }
 
@@ -1030,8 +937,7 @@
     /* Check BLE states */
     if (btm_ble_get_conn_st() != BLE_CONN_IDLE)
     {
-        BTM_TRACE_DEBUG("btm_pm_device_in_active_or_sniff_mode- BLE state: %x",
-                        btm_ble_get_conn_st());
+        BTM_TRACE_DEBUG("%s - BLE state: %x", __func__, btm_ble_get_conn_st());
         return TRUE;
     }
 #endif
@@ -1053,7 +959,7 @@
     /* Scan state-paging, inquiry, and trying to connect */
 
     /* Check for paging */
-    if (btm_cb.is_paging || btm_cb.page_queue.count > 0 ||
+    if (btm_cb.is_paging || GKI_queue_length(&btm_cb.page_queue) > 0 ||
        BTM_BL_PAGING_STARTED == btm_cb.busy_level)
     {
        BTM_TRACE_DEBUG("btm_pm_device_in_scan_state- paging");
@@ -1090,3 +996,12 @@
        return BTM_CONTRL_IDLE;
 }
 
+static const char *mode_to_string(tBTM_PM_MODE mode) {
+  switch (mode) {
+    case BTM_PM_MD_ACTIVE: return "ACTIVE";
+    case BTM_PM_MD_SNIFF:  return "SNIFF";
+    case BTM_PM_MD_PARK:   return "PARK";
+    case BTM_PM_MD_HOLD:   return "HOLD";
+    default:               return "UNKNOWN";
+  }
+}
diff --git a/stack/btm/btm_sco.c b/stack/btm/btm_sco.c
index d9d0fbc..801896d 100644
--- a/stack/btm/btm_sco.c
+++ b/stack/btm/btm_sco.c
@@ -176,61 +176,50 @@
     else    /* Connection is being accepted */
     {
         p_sco->state = SCO_ST_CONNECTING;
-        if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_1_2)
+        p_setup = &p_sco->esco.setup;
+        /* If parameters not specified use the default */
+        if (p_parms)
+            *p_setup = *p_parms;
+        else /* Use the last setup passed thru BTM_SetEscoMode (or defaults) */
         {
-            p_setup = &p_sco->esco.setup;
-            /* If parameters not specified use the default */
-            if (p_parms)
-                *p_setup = *p_parms;
-            else /* Use the last setup passed thru BTM_SetEscoMode (or defaults) */
-            {
-                *p_setup = btm_cb.sco_cb.def_esco_parms;
-            }
-
-            temp_pkt_types = (p_setup->packet_types &
-                              BTM_SCO_SUPPORTED_PKTS_MASK &
-                              btm_cb.btm_sco_pkt_types_supported);
-
-            /* Make sure at least one eSCO packet type is sent, else might confuse peer */
-            /* Taking this out to confirm with BQB tests
-            ** Real application would like to include this though, as many devices
-            ** do not retry with SCO only if an eSCO connection fails.
-            if (!(temp_pkt_types & BTM_ESCO_LINK_ONLY_MASK))
-            {
-                temp_pkt_types |= BTM_SCO_PKT_TYPES_MASK_EV3;
-            }
-            */
-            /* If SCO request, remove eSCO packet types (conformance) */
-            if (p_sco->esco.data.link_type == BTM_LINK_TYPE_SCO)
-            {
-                temp_pkt_types &= BTM_SCO_LINK_ONLY_MASK;
-
-                if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_2_0)
-                {
-                    temp_pkt_types |= BTM_SCO_EXCEPTION_PKTS_MASK;
-                }
-            }
-             /* OR in any exception packet types if at least 2.0 version of spec */
-            else if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_2_0)
-            {
-                temp_pkt_types |= ((p_setup->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) |
-                    (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK));
-            }
-
-            if (btsnd_hcic_accept_esco_conn (bda, p_setup->tx_bw, p_setup->rx_bw,
-                                         p_setup->max_latency, p_setup->voice_contfmt,
-                                             p_setup->retrans_effort, temp_pkt_types))
-            {
-                p_setup->packet_types = temp_pkt_types;
-            }
-            else
-            {
-                BTM_TRACE_ERROR("Could not accept SCO conn: No Buffer!!!");
-            }
+            *p_setup = btm_cb.sco_cb.def_esco_parms;
         }
-        else    /* Controller is version 1.1 or earlier */
+
+        temp_pkt_types = (p_setup->packet_types &
+                          BTM_SCO_SUPPORTED_PKTS_MASK &
+                          btm_cb.btm_sco_pkt_types_supported);
+
+        /* Make sure at least one eSCO packet type is sent, else might confuse peer */
+        /* Taking this out to confirm with BQB tests
+        ** Real application would like to include this though, as many devices
+        ** do not retry with SCO only if an eSCO connection fails.
+        if (!(temp_pkt_types & BTM_ESCO_LINK_ONLY_MASK))
         {
-            btsnd_hcic_accept_conn (bda, 0);
+            temp_pkt_types |= BTM_SCO_PKT_TYPES_MASK_EV3;
+        }
+        */
+        /* If SCO request, remove eSCO packet types (conformance) */
+        if (p_sco->esco.data.link_type == BTM_LINK_TYPE_SCO)
+        {
+            temp_pkt_types &= BTM_SCO_LINK_ONLY_MASK;
+            temp_pkt_types |= BTM_SCO_EXCEPTION_PKTS_MASK;
+        }
+        else
+        {
+            /* OR in any exception packet types */
+            temp_pkt_types |= ((p_setup->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) |
+                (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK));
+        }
+
+        if (btsnd_hcic_accept_esco_conn (bda, p_setup->tx_bw, p_setup->rx_bw,
+                                     p_setup->max_latency, p_setup->voice_contfmt,
+                                         p_setup->retrans_effort, temp_pkt_types))
+        {
+            p_setup->packet_types = temp_pkt_types;
+        }
+        else
+        {
+            BTM_TRACE_ERROR("Could not accept SCO conn: No Buffer!!!");
         }
     }
 #endif
@@ -421,12 +410,9 @@
         temp_pkt_types = (p_setup->packet_types & BTM_SCO_SUPPORTED_PKTS_MASK &
                              btm_cb.btm_sco_pkt_types_supported);
 
-        /* OR in any exception packet types if at least 2.0 version of spec */
-        if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_2_0)
-        {
-            temp_pkt_types |= ((p_setup->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) |
-                (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK));
-        }
+        /* OR in any exception packet types */
+        temp_pkt_types |= ((p_setup->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) |
+            (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK));
 
         /* Finally, remove EDR eSCO if the remote device doesn't support it */
         /* UPF25:  Only SCO was brought up in this case */
@@ -570,12 +556,12 @@
     UINT16            temp_pkt_types;
     tACL_CONN        *p_acl;
 
-#if (BTM_PWR_MGR_INCLUDED == TRUE) && (BTM_SCO_WAKE_PARKED_LINK == TRUE)
+#if (BTM_SCO_WAKE_PARKED_LINK == TRUE)
     tBTM_PM_MODE      md;
     tBTM_PM_PWR_MD    pm;
-#else
+#else  // BTM_SCO_WAKE_PARKED_LINK
     UINT8             mode;
-#endif
+#endif  // BTM_SCO_WAKE_PARKED_LINK
 
     *p_sco_inx = BTM_INVALID_SCO_INDEX;
 
@@ -619,7 +605,7 @@
                 if (is_orig)
                 {
                     /* can not create SCO link if in park mode */
-#if (BTM_PWR_MGR_INCLUDED == TRUE) && (BTM_SCO_WAKE_PARKED_LINK == TRUE)
+#if BTM_SCO_WAKE_PARKED_LINK == TRUE
                     if(BTM_ReadPowerMode(remote_bda, &md) == BTM_SUCCESS)
                     {
                         if (md == BTM_PM_MD_PARK || md == BTM_PM_MD_SNIFF)
@@ -630,13 +616,10 @@
                             p->state = SCO_ST_PEND_UNPARK;
                         }
                     }
-#elif BTM_PWR_MGR_INCLUDED == TRUE
+#else  // BTM_SCO_WAKE_PARKED_LINK
                     if( (BTM_ReadPowerMode(remote_bda, &mode) == BTM_SUCCESS) && (mode == BTM_PM_MD_PARK) )
                         return (BTM_WRONG_MODE);
-#else
-                    if( (BTM_ReadAclMode(remote_bda, &mode) == BTM_SUCCESS) && (mode == BTM_ACL_MODE_PARK) )
-                        return (BTM_WRONG_MODE);
-#endif
+#endif  // BTM_SCO_WAKE_PARKED_LINK
                 }
                 memcpy (p->esco.data.bd_addr, remote_bda, BD_ADDR_LEN);
                 p->rem_bd_known = TRUE;
@@ -656,18 +639,15 @@
             temp_pkt_types = (p_setup->packet_types & BTM_SCO_SUPPORTED_PKTS_MASK &
                              btm_cb.btm_sco_pkt_types_supported);
 
-            /* OR in any exception packet types if at least 2.0 version of spec */
-            if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_2_0)
+            /* OR in any exception packet types */
+            if (btm_cb.sco_cb.desired_sco_mode == HCI_LINK_TYPE_ESCO)
             {
-                if (btm_cb.sco_cb.desired_sco_mode == HCI_LINK_TYPE_ESCO)
-                {
-                    temp_pkt_types |= ((p_setup->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) |
-                        (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK));
-                }
-                else    /* Only using SCO packet types; turn off EDR also */
-                {
-                    temp_pkt_types |= BTM_SCO_EXCEPTION_PKTS_MASK;
-                }
+                temp_pkt_types |= ((p_setup->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) |
+                    (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK));
+            }
+            else    /* Only using SCO packet types; turn off EDR also */
+            {
+                temp_pkt_types |= BTM_SCO_EXCEPTION_PKTS_MASK;
             }
 
             p_setup->packet_types = temp_pkt_types;
@@ -719,7 +699,7 @@
     return (BTM_NO_RESOURCES);
 }
 
-#if (BTM_PWR_MGR_INCLUDED == TRUE) && (BTM_SCO_WAKE_PARKED_LINK == TRUE)
+#if (BTM_SCO_WAKE_PARKED_LINK == TRUE)
 /*******************************************************************************
 **
 ** Function         btm_sco_chk_pend_unpark
@@ -750,9 +730,9 @@
                 p->state = SCO_ST_CONNECTING;
         }
     }
-#endif
+#endif  // BTM_MAX_SCO_LINKS
 }
-#endif
+#endif  // BTM_SCO_WAKE_PARKED_LINK
 
 /*******************************************************************************
 **
@@ -810,8 +790,10 @@
          * If the sco state is in the SCO_ST_CONNECTING state, we still need
          * to return accept sco to avoid race conditon for sco creation
          */
-        if (((p->state == SCO_ST_LISTENING && p->rem_bd_known) || p->state == SCO_ST_CONNECTING)
-         && (!memcmp (p->esco.data.bd_addr, bda, BD_ADDR_LEN)))
+        int rem_bd_matches = p->rem_bd_known &&
+          !memcmp (p->esco.data.bd_addr, bda, BD_ADDR_LEN);
+        if (((p->state == SCO_ST_CONNECTING) && rem_bd_matches) ||
+            ((p->state == SCO_ST_LISTENING) && (rem_bd_matches || !p->rem_bd_known)))
         {
             /* If this guy was a wildcard, he is not one any more */
             p->rem_bd_known = TRUE;
@@ -1366,11 +1348,8 @@
                 p_def->voice_contfmt    = 0x0060;
                 p_def->retrans_effort   = 0;
 
-                /* OR in any exception packet types if at least 2.0 version of spec */
-                if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_2_0)
-                {
-                    p_def->packet_types |= BTM_SCO_EXCEPTION_PKTS_MASK;
-                }
+                /* OR in any exception packet types */
+                p_def->packet_types |= BTM_SCO_EXCEPTION_PKTS_MASK;
             }
         }
         p_esco->desired_sco_mode = sco_mode;
@@ -1534,12 +1513,9 @@
         temp_pkt_types = (p_parms->packet_types & BTM_SCO_SUPPORTED_PKTS_MASK &
                              btm_cb.btm_sco_pkt_types_supported);
 
-        /* OR in any exception packet types if at least 2.0 version of spec */
-        if (btm_cb.devcb.local_version.hci_version >= HCI_PROTO_VERSION_2_0)
-        {
-            temp_pkt_types |= ((p_parms->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) |
-                (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK));
-        }
+        /* OR in any exception packet types */
+        temp_pkt_types |= ((p_parms->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) |
+            (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK));
 
         BTM_TRACE_API("BTM_ChangeEScoLinkParms -> eSCO Link for handle 0x%04x", p_sco->hci_handle);
         BTM_TRACE_API("      txbw 0x%x, rxbw 0x%x, lat 0x%x, voice 0x%x, retrans 0x%02x, pkt 0x%04x",
diff --git a/stack/btm/btm_sec.c b/stack/btm/btm_sec.c
index f6810fe..68eecc5 100644
--- a/stack/btm/btm_sec.c
+++ b/stack/btm/btm_sec.c
@@ -22,13 +22,18 @@
  *
  ******************************************************************************/
 
+#define LOG_TAG "bt_btm_sec"
+
 #include <string.h>
+
 #include "bt_types.h"
+#include "device/include/controller.h"
 #include "hcimsgs.h"
 #include "btu.h"
 #include "btm_int.h"
 #include "l2c_int.h"
 #include "bt_utils.h"
+#include "osi/include/log.h"
 
 #if (BT_USE_TRACES == TRUE && BT_TRACE_VERBOSE == FALSE)
 /* needed for sprintf() */
@@ -39,7 +44,7 @@
     #include "gatt_int.h"
 #endif
 
-#define BTM_SEC_MAX_COLLISION_DELAY     (GKI_SECS_TO_TICKS(5))
+#define BTM_SEC_MAX_COLLISION_DELAY     (5000)
 
 #ifdef APPL_AUTH_WRITE_EXCEPTION
 BOOLEAN (APPL_AUTH_WRITE_EXCEPTION)(BD_ADDR bd_addr);
@@ -190,65 +195,42 @@
 ** Returns          TRUE if registered OK, else FALSE
 **
 *******************************************************************************/
-BOOLEAN  BTM_SecRegister (tBTM_APPL_INFO *p_cb_info)
+BOOLEAN BTM_SecRegister(tBTM_APPL_INFO *p_cb_info)
 {
 #if BLE_INCLUDED == TRUE
     BT_OCTET16      temp_value = {0};
 #endif
 
-    BTM_TRACE_EVENT ("BTM_Sec: application registered");
+    BTM_TRACE_EVENT("%s application registered", __func__);
 
 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
+    LOG_INFO("%s p_cb_info->p_le_callback == 0x%p", __func__, p_cb_info->p_le_callback);
     if (p_cb_info->p_le_callback)
     {
-        BTM_TRACE_ERROR ("BTM_SecRegister:p_cb_info->p_le_callback == 0x%x ", p_cb_info->p_le_callback);
-
-        if (p_cb_info->p_le_callback)
-        {
-    #if SMP_INCLUDED == TRUE
-            BTM_TRACE_EVENT ("BTM_Sec: SMP_Register( btm_proc_smp_cback )");
-            SMP_Register(btm_proc_smp_cback);
-    #endif
-            /* if no IR is loaded, need to regenerate all the keys */
-            if (memcmp(btm_cb.devcb.id_keys.ir, &temp_value, sizeof(BT_OCTET16)) == 0)
-            {
-                btm_ble_reset_id();
-            }
-        }
-        else
-        {
-            BTM_TRACE_ERROR ("BTM_SecRegister:p_cb_info->p_le_callback == NULL ");
-        }
+#if SMP_INCLUDED == TRUE
+      BTM_TRACE_EVENT("%s SMP_Register( btm_proc_smp_cback )", __func__);
+      SMP_Register(btm_proc_smp_cback);
+#endif
+      /* if no IR is loaded, need to regenerate all the keys */
+      if (memcmp(btm_cb.devcb.id_keys.ir, &temp_value, sizeof(BT_OCTET16)) == 0)
+      {
+        btm_ble_reset_id();
+      }
+    }
+    else
+    {
+      LOG_WARN("%s p_cb_info->p_le_callback == NULL", __func__);
     }
 #endif
 
     btm_cb.api = *p_cb_info;
 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
-     BTM_TRACE_ERROR ("BTM_SecRegister: btm_cb.api.p_le_callback = 0x%x ", btm_cb.api.p_le_callback);
+     LOG_INFO("%s btm_cb.api.p_le_callback = 0x%p ", __func__, btm_cb.api.p_le_callback);
 #endif
-    BTM_TRACE_EVENT ("BTM_Sec: application registered");
+    BTM_TRACE_EVENT("%s application registered", __func__);
     return(TRUE);
 }
 
-
-/*******************************************************************************
-**
-** Function         BTM_SecRegisterLinkKeyNotificationCallback
-**
-** Description      Application manager calls this function to register for
-**                  link key notification.  When there is nobody registered
-**                  we should avoid changing link key
-**
-** Returns          TRUE if registered OK, else FALSE
-**
-*******************************************************************************/
-BOOLEAN BTM_SecRegisterLinkKeyNotificationCallback (tBTM_LINK_KEY_CALLBACK *p_callback)
-{
-    btm_cb.api.p_link_key_callback = p_callback;
-    return(TRUE);
-}
-
-
 /*******************************************************************************
 **
 ** Function         BTM_SecAddRmtNameNotifyCallback
@@ -302,38 +284,6 @@
     return(FALSE);
 }
 
-
-/*******************************************************************************
-**
-** Function         BTM_SecSetConnectFilterCallback
-**
-** Description      Host can register to be asked whenever a HCI connection
-**                  request is received.  In the registered function host
-**                  suppose to check connectibility filters.  Yes/No result
-**                  should be returned syncronously
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTM_SecSetConnectFilterCallback (tBTM_FILTER_CB *p_callback)
-{
-    btm_cb.p_conn_filter_cb = p_callback;
-}
-
-/*******************************************************************************
-**
-** Function         BTM_GetSecurityMode
-**
-** Description      Get security mode for the device
-**
-** Returns          void
-**
-*******************************************************************************/
-UINT8 BTM_GetSecurityMode (void)
-{
-    return(btm_cb.security_mode);
-}
-
 /*******************************************************************************
 **
 ** Function         BTM_GetSecurityFlags
@@ -385,75 +335,6 @@
 
 /*******************************************************************************
 **
-** Function         BTM_SetSecurityMode
-**
-** Description      Set security mode for the device
-**
-** Returns          void
-**
-*******************************************************************************/
-void BTM_SetSecurityMode (UINT8 security_mode)
-{
-    UINT8   sp_mode = HCI_SP_MODE_ENABLED;
-    UINT8   sp_debug_mode = HCI_SPD_MODE_DISABLED;
-
-    switch (security_mode)
-    {
-#if (BTM_PRE_LISBON_INCLUDED == TRUE)
-        case BTM_SEC_MODE_NONE:
-        case BTM_SEC_MODE_SERVICE:
-        case BTM_SEC_MODE_LINK:
-            break;
-#endif
-
-        case BTM_SEC_MODE_SP_DEBUG:
-            sp_debug_mode = HCI_SPD_MODE_ENABLED;
-            break;
-        case BTM_SEC_MODE_SP:
-            /* the default is enabled */
-            break;
-        default:
-            BTM_TRACE_ERROR ("BTM_SetSecurityMode: unknown mode:%d", security_mode);
-            return;
-    }
-    btm_cb.security_mode = security_mode;
-
-    if (HCI_SIMPLE_PAIRING_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-    {
-        /* Lisbon devices and only use BTM_SEC_MODE_SP */
-        btm_cb.security_mode = BTM_SEC_MODE_SP;
-        BTM_TRACE_DEBUG("BTM_SetSecurityMode: SP:%d, debug:%d", sp_mode, sp_debug_mode);
-        btsnd_hcic_write_simple_pairing_mode(sp_mode);
-        btsnd_hcic_write_simp_pair_debug_mode(sp_debug_mode);
-        return;
-    }
-
-    /* must be a pre-Lisbon device */
-#if (BTM_PRE_LISBON_INCLUDED == TRUE)
-    /* If previously security mode was Link Level and now lesser notify */
-    /* controller not to perform authentication, encryption on startup  */
-    if ((old_mode == BTM_SEC_MODE_LINK)
-        && (       security_mode != BTM_SEC_MODE_LINK))
-    {
-        BTM_TRACE_DEBUG("BTM_SetSecurityMode: Authen Enable -> FALSE");
-        btsnd_hcic_write_auth_enable (FALSE);
-        btsnd_hcic_write_encr_mode (HCI_ENCRYPT_MODE_DISABLED);
-    }
-
-    /* If previously security is increased to Link Level notify */
-    /* controller to perform authentication, encryption on startup  */
-    if ((old_mode != BTM_SEC_MODE_LINK)
-        && (       security_mode == BTM_SEC_MODE_LINK))
-    {
-        BTM_TRACE_DEBUG("BTM_SetSecurityMode: Authen Enable -> TRUE");
-        btsnd_hcic_write_auth_enable (TRUE);
-        btsnd_hcic_write_encr_mode (HCI_ENCRYPT_MODE_POINT_TO_POINT);
-    }
-#endif  /* BTM_PRE_LISBON_INCLUDED == TRUE */
-}
-
-/*******************************************************************************
-**
 ** Function         BTM_SetPinType
 **
 ** Description      Set PIN type for the device.
@@ -468,7 +349,7 @@
 
     /* If device is not up security mode will be set as a part of startup */
     if ( (btm_cb.cfg.pin_type != pin_type)
-         && (btm_cb.devcb.state > BTM_DEV_STATE_WAIT_AFTER_RESET) )
+         && controller_get_interface()->get_is_ready() )
     {
         btsnd_hcic_write_pin_type (pin_type);
     }
@@ -505,51 +386,6 @@
 
 /*******************************************************************************
 **
-** Function         BTM_SetUCDSecurityLevel
-**
-** Description      Register UCD service security level with Security Manager
-**
-** Parameters:      is_originator - TRUE if originating the connection, FALSE if not
-**                  p_name      - Name of the service relevant only if
-**                                authorization will show this name to user. ignored
-**                                if BTM_SEC_SERVICE_NAME_LEN is 0.
-**                  service_id  - service ID for the service passed to authorization callback
-**                  sec_level   - bit mask of the security features
-**                  psm         - L2CAP PSM
-**                  mx_proto_id - protocol ID of multiplexing proto below
-**                  mx_chan_id  - channel ID of multiplexing proto below
-**
-** Returns          TRUE if registered OK, else FALSE
-**
-*******************************************************************************/
-BOOLEAN BTM_SetUCDSecurityLevel (BOOLEAN is_originator, char *p_name, UINT8 service_id,
-                                 UINT16 sec_level, UINT16 psm, UINT32 mx_proto_id,
-                                 UINT32 mx_chan_id)
-{
-#if (L2CAP_UCD_INCLUDED == TRUE)
-    CONNECTION_TYPE conn_type;
-
-    if (is_originator)
-        conn_type = CONNLESS_ORIG;
-    else
-        conn_type = CONNLESS_TERM;
-
-    return(btm_sec_set_security_level (conn_type, p_name, service_id,
-                                       sec_level, psm, mx_proto_id, mx_chan_id));
-#else
-    UNUSED(is_originator);
-    UNUSED(p_name);
-    UNUSED(service_id);
-    UNUSED(sec_level);
-    UNUSED(psm);
-    UNUSED(mx_proto_id);
-    UNUSED(mx_chan_id);
-    return FALSE;
-#endif
-}
-
-/*******************************************************************************
-**
 ** Function         BTM_SetSecurityLevel
 **
 ** Description      Register service security level with Security Manager
@@ -922,45 +758,6 @@
 
 /*******************************************************************************
 **
-**
-** Function         BTM_SecClrUCDService
-**
-** Description
-**
-** Parameters       Service ID - Id of the service to remove.
-**                               ('0' removes all service records )
-**
-** Returns          Number of records that were cleared.
-**
-*******************************************************************************/
-UINT8 BTM_SecClrUCDService (UINT8 service_id)
-{
-#if (L2CAP_UCD_INCLUDED == TRUE)
-    tBTM_SEC_SERV_REC   *p_srec = &btm_cb.sec_serv_rec[0];
-    UINT8   num_cleared = 0;
-    int     i;
-
-    for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_srec++)
-    {
-        /* Delete services with specified name (if in use and not SDP) */
-        if ((p_srec->security_flags & BTM_SEC_IN_USE) &&
-            (!service_id || (service_id == (UINT32)p_srec->service_id)))
-        {
-            BTM_TRACE_API("BTM_UCD_SEC_CLR[%d]: id %d", i, service_id);
-            p_srec->ucd_security_flags = 0;
-            num_cleared++;
-        }
-    }
-
-    return(num_cleared);
-#else
-    UNUSED(service_id);
-    return(0);
-#endif
-}
-
-/*******************************************************************************
-**
 ** Function         BTM_PINCodeReply
 **
 ** Description      This function is called after Security Manager submitted
@@ -1082,67 +879,6 @@
     btsnd_hcic_pin_code_req_reply (bd_addr, pin_len, p_pin);
 }
 
-
-/*******************************************************************************
-**
-** Function         BTM_DeviceAuthorized
-**
-** Description      This function is called after Security Manager submitted
-**                  authorization request to the UI.
-**
-** Parameters:      bd_addr     - Address of the device for which PIN was requested
-**                  res         - result of the operation BTM_SUCCESS if success
-**
-*******************************************************************************/
-void BTM_DeviceAuthorized (BD_ADDR bd_addr, UINT8 res, UINT32 trusted_mask[])
-{
-    tBTM_SEC_DEV_REC *p_dev_rec;
-
-    if ((p_dev_rec = btm_find_dev (bd_addr)) == NULL)
-    {
-        BTM_TRACE_WARNING ("Security Manager: Attempting Authorization of Unknown Device Address [%02x%02x%02x%02x%02x%02x]",
-                            bd_addr[0], bd_addr[1], bd_addr[2], bd_addr[3], bd_addr[4], bd_addr[5]);
-        return;
-    }
-
-    BTM_TRACE_EVENT ("Security Manager: authorized status:%d State:%d Trusted:%08x %08x",
-                      res, (p_dev_rec) ? p_dev_rec->sec_state : 0, trusted_mask[0], trusted_mask[1]);
-
-    if (res == BTM_SUCCESS)
-    {
-        p_dev_rec->sec_flags   |= BTM_SEC_AUTHORIZED;
-        if (trusted_mask)
-        {
-            BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask);
-        }
-
-        /* Save the currently authorized service in case we are asked again
-        by another multiplexer layer */
-        if (!p_dev_rec->is_originator)
-        {
-            BTM_TRACE_DEBUG("BTM_DeviceAuthorized: Setting last_author_service_id to %d",
-                             p_dev_rec->p_cur_service->service_id);
-            p_dev_rec->last_author_service_id = p_dev_rec->p_cur_service->service_id;
-        }
-    }
-
-    if (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHORIZING)
-        return;
-
-    p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
-
-    if (res != BTM_SUCCESS)
-    {
-        btm_sec_dev_rec_cback_event (p_dev_rec, res, FALSE);
-        return;
-    }
-
-    if ((res = (UINT8)btm_sec_execute_procedure (p_dev_rec)) != BTM_CMD_STARTED)
-    {
-        btm_sec_dev_rec_cback_event (p_dev_rec, res, FALSE);
-    }
-}
-
 /*******************************************************************************
 **
 ** Function         btm_sec_bond_by_transport
@@ -1241,7 +977,7 @@
 
 
     BTM_TRACE_DEBUG ("after update sec_flags=0x%x", p_dev_rec->sec_flags);
-    if (!HCI_SIMPLE_PAIRING_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
+    if (!controller_get_interface()->supports_simple_pairing())
     {
         /* The special case when we authenticate keyboard.  Set pin type to fixed */
         /* It would be probably better to do it from the application, but it is */
@@ -1284,7 +1020,7 @@
     }
 
     BTM_TRACE_DEBUG ("sec mode: %d sm4:x%x", btm_cb.security_mode, p_dev_rec->sm4);
-    if (!HCI_SIMPLE_PAIRING_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0])
+    if (!controller_get_interface()->supports_simple_pairing()
         || (p_dev_rec->sm4 == BTM_SM4_KNOWN))
     {
         if ( btm_sec_check_prefetch_pin (p_dev_rec) )
@@ -1470,37 +1206,6 @@
 
 /*******************************************************************************
 **
-** Function         BTM_SecUseMasterLinkKey
-**
-** Description      This function is called to tell master of the piconet to
-**                  switch to master link key
-**
-** Parameters:      use_master_key - If true Master Link Key shoul be used
-**
-*******************************************************************************/
-tBTM_STATUS BTM_SecUseMasterLinkKey (BOOLEAN use_master_key)
-{
-    return(btsnd_hcic_master_link_key (use_master_key) ?  BTM_SUCCESS :
-           BTM_NO_RESOURCES);
-}
-
-/*******************************************************************************
-**
-** Function         BTM_SetMasterKeyCompCback
-**
-** Description      This function is called to register for the master key complete
-**                  status event.
-**
-** Parameters:      mkey_cback - callback registered with the security manager
-**
-*******************************************************************************/
-void BTM_SetMasterKeyCompCback( tBTM_MKEY_CALLBACK *mkey_cback )
-{
-    btm_cb.mkey_cback = mkey_cback;
-}
-
-/*******************************************************************************
-**
 ** Function         BTM_SecGetDeviceLinkKey
 **
 ** Description      This function is called to obtain link key for the device
@@ -1935,7 +1640,7 @@
     {
         /* add mandatory part */
         UINT16_TO_STREAM(p, len);
-        BDADDR_TO_STREAM(p, btm_cb.devcb.local_addr);
+        BDADDR_TO_STREAM(p, controller_get_interface()->get_address()->address);
 
         len = BTM_OOB_MANDATORY_SIZE;
         max_len -= len;
@@ -2485,7 +2190,7 @@
             2046 may report HCI_Encryption_Change and L2C Connection Request out of sequence
             because of data path issues. Delay this disconnect a little bit
             */
-            BTM_TRACE_ERROR ("peer should have initiated security process by now (SM4 to SM4)");
+            LOG_INFO("%s peer should have initiated security process by now (SM4 to SM4)", __func__);
             p_dev_rec->p_callback        = p_callback;
             p_dev_rec->sec_state         = BTM_SEC_STATE_DELAY_FOR_ENC;
             (*p_callback) (bd_addr, transport, p_ref_data, rc);
@@ -2677,7 +2382,7 @@
     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev (bda);
 
     /* Some device may request a connection before we are done with the HCI_Reset sequence */
-    if (btm_cb.devcb.state != BTM_DEV_STATE_READY)
+    if (!controller_get_interface()->get_is_ready())
     {
         BTM_TRACE_EVENT ("Security Manager: connect request when device not ready");
         btsnd_hcic_reject_conn (bda, HCI_ERR_HOST_REJECT_DEVICE);
@@ -2710,19 +2415,6 @@
     }
 #endif
 
-    /* Host can be registered to verify comming BDA or DC */
-    if (btm_cb.p_conn_filter_cb)
-    {
-        if (!(* btm_cb.p_conn_filter_cb) (bda, dc))
-        {
-            BTM_TRACE_EVENT ("Security Manager: connect request did not pass filter");
-
-            /* incomming call did not pass connection filters.  Reject */
-            btsnd_hcic_reject_conn (bda, HCI_ERR_HOST_REJECT_DEVICE);
-            return;
-        }
-    }
-
     if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
         &&(btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
         &&(!memcmp (btm_cb.pairing_bda, bda, BD_ADDR_LEN)))
@@ -2926,38 +2618,13 @@
 *******************************************************************************/
 void btm_sec_dev_reset (void)
 {
-#if (BTM_PRE_LISBON_INCLUDED == TRUE)
-    if (btm_cb.security_mode == BTM_SEC_MODE_LINK)
+    if (controller_get_interface()->supports_simple_pairing())
     {
-        btsnd_hcic_write_auth_enable (TRUE);
-        btsnd_hcic_write_encr_mode (HCI_ENCRYPT_MODE_POINT_TO_POINT);
-    }
-#endif
-#if (BTM_PRE_LISBON_INCLUDED == TRUE)
-    else
-#endif
-        /* btm_sec_dev_reset() is only called from btm_decode_ext_features_page(...)
-         * right now. */
-        if (HCI_SIMPLE_PAIRING_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_0]))
-    {
-        btsnd_hcic_write_simple_pairing_mode(HCI_SP_MODE_ENABLED);
-#if BLE_INCLUDED == TRUE
-        btsnd_hcic_set_event_mask(LOCAL_BR_EDR_CONTROLLER_ID,
-                                  (UINT8 *)HCI_DUMO_EVENT_MASK_EXT);
-
-        btsnd_hcic_ble_set_evt_mask((UINT8 *)HCI_BLE_EVENT_MASK_DEF);
-
-#else
-        btsnd_hcic_set_event_mask(LOCAL_BR_EDR_CONTROLLER_ID,
-                                  (UINT8 *)HCI_LISBON_EVENT_MASK_EXT);
-#endif
         /* set the default IO capabilities */
         btm_cb.devcb.loc_io_caps = BTM_LOCAL_IO_CAPS;
         /* add mx service to use no security */
-#if (RFCOMM_INCLUDED == TRUE)
         BTM_SetSecurityLevel(FALSE, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX,
                              BTM_SEC_NONE, BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0);
-#endif
     }
     else
     {
@@ -2986,9 +2653,6 @@
     if (!p_dev_rec)
         return;
 
-    if (btm_cb.api.p_abort_callback)
-        (*btm_cb.api.p_abort_callback)(bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
-
     if ((p_dev_rec->sec_state != BTM_SEC_STATE_AUTHORIZING)
         && (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHENTICATING))
         return;
@@ -3034,9 +2698,7 @@
         return(BTM_NO_RESOURCES);
     }
 
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     btm_acl_update_busy_level (BTM_BLI_PAGE_EVT);
-#endif
 
     BTM_TRACE_DEBUG ("Security Manager: btm_sec_dd_create_conn [%02x%02x%02x%02x%02x%02x]",
                       p_dev_rec->bd_addr[0], p_dev_rec->bd_addr[1], p_dev_rec->bd_addr[2],
@@ -3896,9 +3558,9 @@
     tBTM_SEC_DEV_REC *p_dev_rec;
 
     if (!btm_cb.collision_start_time)
-        btm_cb.collision_start_time = GKI_get_tick_count ();
+        btm_cb.collision_start_time = GKI_get_os_tick_count();
 
-    if ((GKI_get_tick_count () - btm_cb.collision_start_time) < btm_cb.max_collision_delay)
+    if ((GKI_get_os_tick_count() - btm_cb.collision_start_time) < btm_cb.max_collision_delay)
     {
         if (handle == BTM_SEC_INVALID_HANDLE)
         {
@@ -4103,35 +3765,6 @@
 
 /*******************************************************************************
 **
-** Function         btm_sec_mkey_comp_event
-**
-** Description      This function is when encryption of the connection is
-**                  completed by the LM
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_sec_mkey_comp_event (UINT16 handle, UINT8 status, UINT8 key_flg)
-{
-    tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev_by_handle (handle);
-    UINT8 bd_addr[BD_ADDR_LEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} ;
-
-    BTM_TRACE_EVENT ("Security Manager: mkey comp status:%d State:%d",
-                      status, (p_dev_rec) ? p_dev_rec->sec_state : 0);
-
-    /* If encryption setup failed, notify the waiting layer */
-    /* There is no next procedure or start of procedure failed, notify the waiting layer */
-    if (btm_cb.mkey_cback)
-    {
-        if (!p_dev_rec)
-            (btm_cb.mkey_cback)(bd_addr, status, key_flg );
-        else
-            (btm_cb.mkey_cback)(p_dev_rec->bd_addr, status, key_flg );
-    }
-}
-
-/*******************************************************************************
-**
 ** Function         btm_sec_encrypt_change
 **
 ** Description      This function is when encryption of the connection is
@@ -4231,38 +3864,6 @@
 
 /*******************************************************************************
 **
-** Function         btm_sec_create_conn
-**
-** Description      This function records current role and forwards request to
-**                  HCI
-**
-** Returns          void
-**
-*******************************************************************************/
-BOOLEAN btm_sec_create_conn (BD_ADDR bda, UINT16 packet_types,
-                             UINT8 page_scan_rep_mode, UINT8 page_scan_mode,
-                             UINT16 clock_offset, UINT8 allow_switch)
-{
-    tBTM_SEC_DEV_REC *p_dev_rec = btm_find_or_alloc_dev (bda);
-
-    memcpy (btm_cb.connecting_bda, p_dev_rec->bd_addr,   BD_ADDR_LEN);
-    memcpy (btm_cb.connecting_dc,  p_dev_rec->dev_class, DEV_CLASS_LEN);
-
-    btm_cb.acl_disc_reason = 0xff ;
-
-    p_dev_rec->sec_state   = BTM_SEC_STATE_IDLE;
-    p_dev_rec->role_master = TRUE;
-
-    /* If any SCO link up, do not allow a switch */
-    if (BTM_GetNumScoLinks() != 0)
-        allow_switch = HCI_CR_CONN_NOT_ALLOW_SWITCH;
-
-    return(btsnd_hcic_create_conn (bda, packet_types, page_scan_rep_mode,
-                                   page_scan_mode, clock_offset, allow_switch));
-}
-
-/*******************************************************************************
-**
 ** Function         btm_sec_connect_after_reject_timeout
 **
 ** Description      Connection for bonding could not start because of the collision
@@ -4597,48 +4198,6 @@
 
 /*******************************************************************************
 **
-** Function         btm_sec_role_changed
-**
-** Description      This function is colled when controller reports role
-**                  changed, or failed command status for Role Change request
-**
-** Returns          void
-**
-*******************************************************************************/
-void btm_sec_role_changed (void *p_ref_data)
-{
-    tBTM_SEC_DEV_REC *p_dev_rec = (tBTM_SEC_DEV_REC *)p_ref_data;
-    UINT8 res;
-
-    BTM_TRACE_EVENT ("Security Manager: role changed");
-
-    /* If this role switch was started by peer do not need to do anything */
-    if (p_dev_rec->sec_state != BTM_SEC_STATE_SWITCHING_ROLE)
-        return;
-
-    /* If serurity required was to FORCE switch and it failed, notify the waiting layer */
-    if (((p_dev_rec->security_required & BTM_SEC_FORCE_MASTER) && !p_dev_rec->role_master)
-        || ((p_dev_rec->security_required & BTM_SEC_FORCE_SLAVE)  &&  p_dev_rec->role_master))
-    {
-        btm_sec_dev_rec_cback_event (p_dev_rec, BTM_ERR_PROCESSING, FALSE);
-        return;
-    }
-
-    p_dev_rec->sec_flags |= BTM_SEC_ROLE_SWITCHED;
-
-    p_dev_rec->security_required &= ~(BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER |
-                                      BTM_SEC_FORCE_SLAVE  | BTM_SEC_ATTEMPT_SLAVE);
-
-    p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
-
-    if ((res = (UINT8)btm_sec_execute_procedure (p_dev_rec)) != BTM_CMD_STARTED)
-    {
-        btm_sec_dev_rec_cback_event (p_dev_rec, res, FALSE);
-    }
-}
-
-/*******************************************************************************
-**
 ** Function         btm_sec_disconnect
 **
 ** Description      This function is called to disconnect HCI link
@@ -4701,18 +4260,19 @@
     p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING;     /* reset flag */
 
 #if BTM_DISC_DURING_RS == TRUE
-    BTM_TRACE_ERROR("btm_sec_disconnected - Clearing Pending flag");
+    LOG_INFO("%s clearing pending flag handle:%d reason:%d", __func__, handle, reason);
     p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING;     /* reset flag */
 #endif
 
     /* clear unused flags */
     p_dev_rec->sm4 &= BTM_SM4_TRUE;
 
-    BTM_TRACE_EVENT("btm_sec_disconnected() sec_req:x%x  State: %s   reason:%d bda:%04x%08x RName:%s",
-                     p_dev_rec->security_required, btm_pair_state_descr(btm_cb.pairing_state), reason,  (p_dev_rec->bd_addr[0]<<8)+p_dev_rec->bd_addr[1],
-                     (p_dev_rec->bd_addr[2]<<24)+(p_dev_rec->bd_addr[3]<<16)+(p_dev_rec->bd_addr[4]<<8)+p_dev_rec->bd_addr[5], p_dev_rec->sec_bd_name);
+    uint8_t *bd_addr = (uint8_t *)p_dev_rec->bd_addr;
+    BTM_TRACE_EVENT("%s sec_req:x%x state:%s reason:%d bd_addr:%02x:%02x:%02x:%02x:%02x:%02x"
+            "  remote_name:%s", __func__, p_dev_rec->security_required, btm_pair_state_descr(btm_cb.pairing_state),
+            reason, bd_addr[0], bd_addr[1], bd_addr[2], bd_addr[3], bd_addr[4], bd_addr[5], p_dev_rec->sec_bd_name);
 
-    BTM_TRACE_EVENT("before Update sec_flags=0x%x", p_dev_rec->sec_flags);
+    BTM_TRACE_EVENT("%s before update sec_flags=0x%x", __func__, p_dev_rec->sec_flags);
 
     /* If we are in the process of bonding we need to tell client that auth failed */
     if ( (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
@@ -4769,7 +4329,7 @@
         (*p_callback) (p_dev_rec->bd_addr, transport, p_dev_rec->p_ref_data, BTM_ERR_PROCESSING);
     }
 
-    BTM_TRACE_EVENT("after Update sec_flags=0x%x", p_dev_rec->sec_flags);
+    BTM_TRACE_EVENT("%s after update sec_flags=0x%x", __func__, p_dev_rec->sec_flags);
 }
 
 /*******************************************************************************
@@ -4794,9 +4354,6 @@
     /* If connection was made to do bonding restore link security if changed */
     btm_restore_mode();
 
-    /* Override the key type if version is pre-1.1 */
-    if (btm_cb.devcb.local_version.hci_version < HCI_VERSION_1_1)
-        p_dev_rec->link_key_type = BTM_LKEY_TYPE_IGNORE;
     if (key_type != BTM_LKEY_TYPE_CHANGED_COMB)
         p_dev_rec->link_key_type = key_type;
 
@@ -4895,20 +4452,6 @@
     /* Notify L2CAP to increase timeout */
     l2c_pin_code_request (p_bda);
 
-    /* Only ask the host for a key if this guy is not already bonding */
-    if ( (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE)
-         || (memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0) )
-    {
-        if (btm_cb.api.p_link_key_req_callback)
-        {
-            if ((*btm_cb.api.p_link_key_req_callback)(p_bda, p_dev_rec->link_key) == BTM_SUCCESS)
-            {
-                btsnd_hcic_link_key_req_reply (p_bda, p_dev_rec->link_key);
-                return;
-            }
-        }
-    }
-
     /* The link key is not in the database and it is not known to the manager */
     btsnd_hcic_link_key_neg_reply (p_bda);
 }
@@ -5755,41 +5298,6 @@
 
 /*******************************************************************************
 **
-** Function         BTM_snd_conn_encrypt
-**
-** Description      This function is called to start/stop encryption
-**                  Used by JSR-82
-**
-** Returns          TRUE if request started
-**
-*******************************************************************************/
-BOOLEAN BTM_snd_conn_encrypt (UINT16  handle, BOOLEAN enable)
-{
-    tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev_by_handle (handle);
-
-    BTM_TRACE_EVENT ("BTM_snd_conn_encrypt Security Manager: encrypt_change p_dev_rec : 0x%x, enable = %s", p_dev_rec, (enable == TRUE) ? "TRUE" : "FALSE");
-
-    if (!p_dev_rec)
-    {
-        BTM_TRACE_EVENT ("BTM_snd_conn_encrypt Error no  p_dev_rec : 0x%x\n", p_dev_rec);
-        return(FALSE);
-    }
-
-    if ( p_dev_rec->sec_state == BTM_SEC_STATE_IDLE)
-    {
-        if (!btsnd_hcic_set_conn_encrypt (handle, enable))
-            return(FALSE);
-
-        p_dev_rec->sec_state = BTM_SEC_STATE_ENCRYPTING;
-
-        return(TRUE);
-    }
-    else
-        return(FALSE);
-}
-
-/*******************************************************************************
-**
 ** Function         btm_sec_change_pairing_state
 **
 ** Description      This function is called to change pairing state
diff --git a/stack/btu/btu_hcif.c b/stack/btu/btu_hcif.c
index 9ec8dd3..c8a45d3 100644
--- a/stack/btu/btu_hcif.c
+++ b/stack/btu/btu_hcif.c
@@ -25,6 +25,9 @@
  *
  ******************************************************************************/
 
+#define LOG_TAG "bt_btu_hcif"
+
+#include <assert.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
@@ -36,39 +39,25 @@
 #include "l2c_int.h"
 #include "btm_api.h"
 #include "btm_int.h"
+#include "bt_utils.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "hci_layer.h"
+
+// TODO(zachoverflow): remove this horrible hack
+#include "btu.h"
+extern fixed_queue_t *btu_hci_msg_queue;
 
 extern void btm_process_cancel_complete(UINT8 status, UINT8 mode);
 extern void btm_ble_test_command_complete(UINT8 *p);
 
-// btla-specific ++
-#define LOG_TAG "BTLD"
-#if (defined(ANDROID_APP_INCLUDED) && (ANDROID_APP_INCLUDED == TRUE) && (!defined(LINUX_NATIVE)) )
-#include <cutils/log.h>
-#else
-#define LOGV(format, ...)  fprintf (stdout, LOG_TAG format"\n", ## __VA_ARGS__)
-#define LOGE(format, ...)  fprintf (stderr, LOG_TAG format"\n", ## __VA_ARGS__)
-#define LOGI(format, ...)  fprintf (stdout, LOG_TAG format"\n", ## __VA_ARGS__)
-#endif
-
-// btla-specific ++
-/* BTE application task */
-#if APPL_INCLUDED == TRUE
-#include "bte_appl.h"
-#endif
-// btla-specific --
-
-//Counter to track number of HCI command timeout
-static int num_hci_cmds_timed_out;
-
 /********************************************************************************/
 /*              L O C A L    F U N C T I O N     P R O T O T Y P E S            */
 /********************************************************************************/
 static void btu_hcif_inquiry_comp_evt (UINT8 *p);
 static void btu_hcif_inquiry_result_evt (UINT8 *p);
 static void btu_hcif_inquiry_rssi_result_evt (UINT8 *p);
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
 static void btu_hcif_extended_inquiry_result_evt (UINT8 *p);
-#endif
 
 static void btu_hcif_connection_comp_evt (UINT8 *p);
 static void btu_hcif_connection_request_evt (UINT8 *p);
@@ -76,20 +65,17 @@
 static void btu_hcif_authentication_comp_evt (UINT8 *p);
 static void btu_hcif_rmt_name_request_comp_evt (UINT8 *p, UINT16 evt_len);
 static void btu_hcif_encryption_change_evt (UINT8 *p);
-static void btu_hcif_change_conn_link_key_evt (UINT8 *p);
-static void btu_hcif_master_link_key_comp_evt (UINT8 *p);
 static void btu_hcif_read_rmt_features_comp_evt (UINT8 *p);
 static void btu_hcif_read_rmt_ext_features_comp_evt (UINT8 *p);
 static void btu_hcif_read_rmt_version_comp_evt (UINT8 *p);
 static void btu_hcif_qos_setup_comp_evt (UINT8 *p);
-static void btu_hcif_command_complete_evt (UINT8 controller_id, UINT8 *p, UINT16 evt_len);
-static void btu_hcif_command_status_evt (UINT8 controller_id, UINT8 *p);
+static void btu_hcif_command_complete_evt (BT_HDR *response, void *context);
+static void btu_hcif_command_status_evt (uint8_t status, BT_HDR *command, void *context);
 static void btu_hcif_hardware_error_evt (UINT8 *p);
 static void btu_hcif_flush_occured_evt (void);
 static void btu_hcif_role_change_evt (UINT8 *p);
 static void btu_hcif_num_compl_data_pkts_evt (UINT8 *p);
 static void btu_hcif_mode_change_evt (UINT8 *p);
-static void btu_hcif_return_link_keys_evt (UINT8 *p);
 static void btu_hcif_pin_code_request_evt (UINT8 *p);
 static void btu_hcif_link_key_request_evt (UINT8 *p);
 static void btu_hcif_link_key_notification_evt (UINT8 *p);
@@ -112,7 +98,6 @@
 static void btu_hcif_user_passkey_request_evt (UINT8 *p);
 static void btu_hcif_user_passkey_notif_evt (UINT8 *p);
 static void btu_hcif_keypress_notif_evt (UINT8 *p);
-static void btu_hcif_link_super_tout_evt (UINT8 *p);
 
     #if BTM_OOB_INCLUDED == TRUE
 static void btu_hcif_rem_oob_request_evt (UINT8 *p);
@@ -127,11 +112,6 @@
 static void btu_hcif_ssr_evt (UINT8 *p, UINT16 evt_len);
     #endif /* BTM_SSR_INCLUDED == TRUE */
 
-    #if (HID_DEV_INCLUDED == TRUE) && (HID_DEV_PM_INCLUDED == TRUE)
-extern void hidd_pm_proc_mode_change( UINT8 hci_status, UINT8 mode, UINT16 interval );
-    #endif
-
-
     #if BLE_INCLUDED == TRUE
 static void btu_ble_ll_conn_complete_evt (UINT8 *p, UINT16 evt_len);
 static void btu_ble_process_adv_pkt (UINT8 *p);
@@ -143,77 +123,6 @@
 static void btu_ble_rc_param_req_evt(UINT8 *p);
 #endif
     #endif
-/*******************************************************************************
-**
-** Function         btu_hcif_store_cmd
-**
-** Description      This function stores a copy of an outgoing command and
-**                  and sets a timer waiting for a event in response to the
-**                  command.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btu_hcif_store_cmd (UINT8 controller_id, BT_HDR *p_buf)
-{
-    tHCI_CMD_CB *p_hci_cmd_cb;
-    UINT16  opcode;
-    BT_HDR  *p_cmd;
-    UINT8   *p;
-
-    /* Validate controller ID */
-    if (controller_id >= BTU_MAX_LOCAL_CTRLS)
-        return;
-
-    p_hci_cmd_cb = &(btu_cb.hci_cmd_cb[controller_id]);
-    p = (UINT8 *)(p_buf + 1) + p_buf->offset;
-
-    /* get command opcode */
-    STREAM_TO_UINT16 (opcode, p);
-
-    /* don't do anything for certain commands */
-    if ((opcode == HCI_RESET) || (opcode == HCI_HOST_NUM_PACKETS_DONE))
-    {
-        return;
-    }
-
-    /* allocate buffer (HCI_GET_CMD_BUF will either get a buffer from HCI_CMD_POOL or from 'best-fit' pool) */
-    if ((p_cmd = HCI_GET_CMD_BUF(p_buf->len + p_buf->offset - HCIC_PREAMBLE_SIZE)) == NULL)
-    {
-        return;
-    }
-
-    /* copy buffer */
-    memcpy (p_cmd, p_buf, sizeof(BT_HDR));
-
-    /* If vendor specific save the callback function */
-    if ((opcode & HCI_GRP_VENDOR_SPECIFIC) == HCI_GRP_VENDOR_SPECIFIC
-#if BLE_INCLUDED == TRUE
-        || (opcode == HCI_BLE_RAND )
-        || (opcode == HCI_BLE_ENCRYPT)
-#endif
-       )
-    {
-        memcpy ((UINT8 *)(p_cmd + 1), (UINT8 *)(p_buf + 1), sizeof(void *));
-    }
-
-    memcpy ((UINT8 *)(p_cmd + 1) + p_cmd->offset,
-            (UINT8 *)(p_buf + 1) + p_buf->offset, p_buf->len);
-
-    /* queue copy of cmd */
-    GKI_enqueue(&(p_hci_cmd_cb->cmd_cmpl_q), p_cmd);
-
-    /* start timer */
-    if (BTU_CMD_CMPL_TIMEOUT > 0)
-    {
-#if (defined(BTU_CMD_CMPL_TOUT_DOUBLE_CHECK) && BTU_CMD_CMPL_TOUT_DOUBLE_CHECK == TRUE)
-        p_hci_cmd_cb->checked_hcisu = FALSE;
-#endif
-        btu_start_timer (&(p_hci_cmd_cb->cmd_cmpl_timer),
-                         (UINT16)(BTU_TTYPE_BTU_CMD_CMPL + controller_id),
-                         BTU_CMD_CMPL_TIMEOUT);
-    }
-}
 
 /*******************************************************************************
 **
@@ -225,7 +134,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-void btu_hcif_process_event (UINT8 controller_id, BT_HDR *p_msg)
+void btu_hcif_process_event (UNUSED_ATTR UINT8 controller_id, BT_HDR *p_msg)
 {
     UINT8   *p = (UINT8 *)(p_msg + 1) + p_msg->offset;
     UINT8   hci_evt_code, hci_evt_len;
@@ -246,11 +155,9 @@
         case HCI_INQUIRY_RSSI_RESULT_EVT:
             btu_hcif_inquiry_rssi_result_evt (p);
             break;
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
         case HCI_EXTENDED_INQUIRY_RESULT_EVT:
             btu_hcif_extended_inquiry_result_evt (p);
             break;
-#endif
         case HCI_CONNECTION_COMP_EVT:
             btu_hcif_connection_comp_evt (p);
             break;
@@ -274,12 +181,6 @@
             btu_hcif_encryption_key_refresh_cmpl_evt(p);
             break;
 #endif
-        case HCI_CHANGE_CONN_LINK_KEY_EVT:
-            btu_hcif_change_conn_link_key_evt (p);
-            break;
-        case HCI_MASTER_LINK_KEY_COMP_EVT:
-            btu_hcif_master_link_key_comp_evt (p);
-            break;
         case HCI_READ_RMT_FEATURES_COMP_EVT:
             btu_hcif_read_rmt_features_comp_evt (p);
             break;
@@ -293,10 +194,12 @@
             btu_hcif_qos_setup_comp_evt (p);
             break;
         case HCI_COMMAND_COMPLETE_EVT:
-            btu_hcif_command_complete_evt (controller_id, p, hci_evt_len);
+            LOG_ERROR("%s should not have received a command complete event. "
+                  "Someone didn't go through the hci transmit_command function.", __func__);
             break;
         case HCI_COMMAND_STATUS_EVT:
-            btu_hcif_command_status_evt (controller_id, p);
+            LOG_ERROR("%s should not have received a command status event. "
+                  "Someone didn't go through the hci transmit_command function.", __func__);
             break;
         case HCI_HARDWARE_ERROR_EVT:
             btu_hcif_hardware_error_evt (p);
@@ -313,9 +216,6 @@
         case HCI_MODE_CHANGE_EVT:
             btu_hcif_mode_change_evt (p);
             break;
-        case HCI_RETURN_LINK_KEYS_EVT:
-            btu_hcif_return_link_keys_evt (p);
-            break;
         case HCI_PIN_CODE_REQUEST_EVT:
             btu_hcif_pin_code_request_evt (p);
             break;
@@ -389,9 +289,6 @@
         case HCI_KEYPRESS_NOTIFY_EVT:
             btu_hcif_keypress_notif_evt (p);
             break;
-        case HCI_LINK_SUPER_TOUT_CHANGED_EVT:
-            btu_hcif_link_super_tout_evt (p);
-            break;
 #if L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE
         case HCI_ENHANCED_FLUSH_COMPLETE_EVT:
             btu_hcif_enhanced_flush_complete_evt ();
@@ -434,8 +331,6 @@
                 btm_vendor_specific_evt (p, hci_evt_len);
             break;
     }
-    // reset the  num_hci_cmds_timed_out upon receving any event from controller.
-    num_hci_cmds_timed_out = 0;
 }
 
 
@@ -443,88 +338,40 @@
 **
 ** Function         btu_hcif_send_cmd
 **
-** Description      This function is called to check if it can send commands
-**                  to the Host Controller. It may be passed the address of
-**                  a packet to send.
+** Description      This function is called to send commands to the Host Controller.
 **
 ** Returns          void
 **
 *******************************************************************************/
-void btu_hcif_send_cmd (UINT8 controller_id, BT_HDR *p_buf)
+void btu_hcif_send_cmd (UNUSED_ATTR UINT8 controller_id, BT_HDR *p_buf)
 {
-    tHCI_CMD_CB * p_hci_cmd_cb = &(btu_cb.hci_cmd_cb[controller_id]);
+    if (!p_buf)
+      return;
 
-#if ((L2CAP_HOST_FLOW_CTRL == TRUE)||defined(HCI_TESTER))
-    UINT8 *pp;
-    UINT16 code;
+    uint16_t opcode;
+    uint8_t *stream = p_buf->data + p_buf->offset;
+    void * vsc_callback = NULL;
+
+    STREAM_TO_UINT16(opcode, stream);
+
+    // Eww...horrible hackery here
+    /* If command was a VSC, then extract command_complete callback */
+    if ((opcode & HCI_GRP_VENDOR_SPECIFIC) == HCI_GRP_VENDOR_SPECIFIC
+#if BLE_INCLUDED == TRUE
+        || (opcode == HCI_BLE_RAND)
+        || (opcode == HCI_BLE_ENCRYPT)
 #endif
-
-    /* If there are already commands in the queue, then enqueue this command */
-    if ((p_buf) && (p_hci_cmd_cb->cmd_xmit_q.count))
-    {
-        GKI_enqueue (&(p_hci_cmd_cb->cmd_xmit_q), p_buf);
-        p_buf = NULL;
+       ) {
+        vsc_callback = *((void **)(p_buf + 1));
     }
 
-    /* Allow for startup case, where no acks may be received */
-    if ( ((controller_id == LOCAL_BR_EDR_CONTROLLER_ID)
-         && (p_hci_cmd_cb->cmd_window == 0)
-         && (btm_cb.devcb.state == BTM_DEV_STATE_WAIT_RESET_CMPLT)) )
-    {
-        p_hci_cmd_cb->cmd_window = p_hci_cmd_cb->cmd_xmit_q.count + 1;
-    }
+    hci_layer_get_interface()->transmit_command(
+      p_buf,
+      btu_hcif_command_complete_evt,
+      btu_hcif_command_status_evt,
+      vsc_callback);
 
-    /* See if we can send anything */
-    while (p_hci_cmd_cb->cmd_window != 0)
-    {
-        if (!p_buf)
-            p_buf = (BT_HDR *)GKI_dequeue (&(p_hci_cmd_cb->cmd_xmit_q));
-
-        if (p_buf)
-        {
-            btu_hcif_store_cmd(controller_id, p_buf);
-
-#if ((L2CAP_HOST_FLOW_CTRL == TRUE)||defined(HCI_TESTER))
-            pp = (UINT8 *)(p_buf + 1) + p_buf->offset;
-
-            STREAM_TO_UINT16 (code, pp);
-
-            /*
-             * We do not need to decrease window for host flow control,
-             * host flow control does not receive an event back from controller
-             */
-            if (code != HCI_HOST_NUM_PACKETS_DONE)
-#endif
-                p_hci_cmd_cb->cmd_window--;
-
-            if (controller_id == LOCAL_BR_EDR_CONTROLLER_ID)
-            {
-                HCI_CMD_TO_LOWER(p_buf);
-            }
-            else
-            {
-                /* Unknown controller */
-                HCI_TRACE_WARNING("BTU HCI(ctrl id=%d) controller ID not recognized", controller_id);
-                GKI_freebuf(p_buf);;
-            }
-
-            p_buf = NULL;
-        }
-        else
-            break;
-    }
-
-    if (p_buf)
-        GKI_enqueue (&(p_hci_cmd_cb->cmd_xmit_q), p_buf);
-
-#if (defined(HCILP_INCLUDED) && HCILP_INCLUDED == TRUE)
-    if (controller_id == LOCAL_BR_EDR_CONTROLLER_ID)
-    {
-        /* check if controller can go to sleep */
-        btu_check_bt_sleep ();
-    }
-#endif
-
+    btu_check_bt_sleep ();
 }
 
 
@@ -616,13 +463,11 @@
 ** Returns          void
 **
 *******************************************************************************/
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
 static void btu_hcif_extended_inquiry_result_evt (UINT8 *p)
 {
     /* Store results in the cache */
     btm_process_inq_results (p, BTM_INQ_RESULT_EXTENDED);
 }
-#endif
 
 /*******************************************************************************
 **
@@ -715,11 +560,10 @@
 *******************************************************************************/
 static void btu_hcif_disconnection_comp_evt (UINT8 *p)
 {
-    UINT8   status;
     UINT16  handle;
     UINT8   reason;
 
-    STREAM_TO_UINT8  (status, p);
+    ++p;
     STREAM_TO_UINT16 (handle, p);
     STREAM_TO_UINT8  (reason, p);
 
@@ -806,51 +650,6 @@
     btm_sec_encrypt_change (handle, status, encr_enable);
 }
 
-
-/*******************************************************************************
-**
-** Function         btu_hcif_change_conn_link_key_evt
-**
-** Description      Process event HCI_CHANGE_CONN_LINK_KEY_EVT
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btu_hcif_change_conn_link_key_evt (UINT8 *p)
-{
-    UINT8   status;
-    UINT16  handle;
-
-    STREAM_TO_UINT8  (status, p);
-    STREAM_TO_UINT16 (handle, p);
-
-    btm_acl_link_key_change (handle, status);
-}
-
-
-/*******************************************************************************
-**
-** Function         btu_hcif_master_link_key_comp_evt
-**
-** Description      Process event HCI_MASTER_LINK_KEY_COMP_EVT
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btu_hcif_master_link_key_comp_evt (UINT8 *p)
-{
-    UINT8   status;
-    UINT16  handle;
-    UINT8   key_flg;
-
-    STREAM_TO_UINT8  (status, p);
-    STREAM_TO_UINT16 (handle, p);
-    STREAM_TO_UINT8  (key_flg, p);
-
-    btm_sec_mkey_comp_event (handle, status, key_flg);
-}
-
-
 /*******************************************************************************
 **
 ** Function         btu_hcif_read_rmt_features_comp_evt
@@ -1014,10 +813,6 @@
 {
     switch (opcode)
     {
-        case HCI_RESET:
-            btm_reset_complete ();  /* BR/EDR */
-            break;
-
         case HCI_INQUIRY_CANCEL:
             /* Tell inquiry processing that we are done */
             btm_process_cancel_complete(HCI_SUCCESS, BTM_BR_INQUIRY_MASK);
@@ -1026,50 +821,14 @@
             btm_event_filter_complete (p);
             break;
 
-        case HCI_READ_STORED_LINK_KEY:
-            btm_read_stored_link_key_complete (p);
-            break;
-
-        case HCI_WRITE_STORED_LINK_KEY:
-            btm_write_stored_link_key_complete (p);
-            break;
-
         case HCI_DELETE_STORED_LINK_KEY:
             btm_delete_stored_link_key_complete (p);
             break;
 
-        case HCI_READ_LOCAL_VERSION_INFO:
-            btm_read_local_version_complete (p, evt_len);
-            break;
-
-        case HCI_READ_POLICY_SETTINGS:
-            btm_read_link_policy_complete (p);
-            break;
-
-        case HCI_READ_BUFFER_SIZE:
-            btm_read_hci_buf_size_complete (p, evt_len);
-            break;
-
-        case HCI_READ_LOCAL_SUPPORTED_CMDS:
-            btm_read_local_supported_cmds_complete (p);
-            break;
-
-        case HCI_READ_LOCAL_FEATURES:
-            btm_read_local_features_complete (p, evt_len);
-            break;
-
-        case HCI_READ_LOCAL_EXT_FEATURES:
-            btm_read_local_ext_features_complete (p, evt_len);
-            break;
-
         case HCI_READ_LOCAL_NAME:
             btm_read_local_name_complete (p, evt_len);
             break;
 
-        case HCI_READ_BD_ADDR:
-            btm_read_local_addr_complete (p, evt_len);
-            break;
-
         case HCI_GET_LINK_QUALITY:
             btm_read_link_quality_complete (p);
             break;
@@ -1097,20 +856,8 @@
             btm_read_linq_tx_power_complete (p);
             break;
 
-        case HCI_WRITE_SIMPLE_PAIRING_MODE:
-            btm_write_simple_paring_mode_complete (p);
-            break;
-
-        case HCI_WRITE_LE_HOST_SUPPORTED:
-            btm_write_le_host_supported_complete (p);
-            break;
-
 #if (BLE_INCLUDED == TRUE)
 /* BLE Commands sComplete*/
-        case HCI_BLE_READ_WHITE_LIST_SIZE :
-            btm_read_white_list_size_complete(p, evt_len);
-            break;
-
         case HCI_BLE_ADD_WHITE_LIST:
             btm_ble_add_2_white_list_complete(*p);
             break;
@@ -1128,14 +875,6 @@
             btm_ble_rand_enc_complete (p, opcode, (tBTM_RAND_ENC_CB *)p_cplt_cback);
             break;
 
-        case HCI_BLE_READ_BUFFER_SIZE:
-            btm_read_ble_buf_size_complete(p, evt_len);
-            break;
-
-        case HCI_BLE_READ_LOCAL_SPT_FEAT:
-            btm_read_ble_local_supported_features_complete(p, evt_len);
-            break;
-
         case HCI_BLE_READ_ADV_CHNL_TX_POWER:
             btm_read_tx_power_complete(p, TRUE);
             break;
@@ -1144,10 +883,6 @@
             btm_ble_write_adv_enable_complete(p);
             break;
 
-        case HCI_BLE_READ_SUPPORTED_STATES:
-            btm_read_ble_local_supported_states_complete(p, evt_len);
-            break;
-
         case HCI_BLE_CREATE_LL_CONN:
             btm_ble_create_ll_conn_complete(*p);
             break;
@@ -1175,91 +910,36 @@
 ** Returns          void
 **
 *******************************************************************************/
-static void btu_hcif_command_complete_evt (UINT8 controller_id, UINT8 *p, UINT16 evt_len)
+static void btu_hcif_command_complete_evt_on_task(BT_HDR *event)
 {
-    tHCI_CMD_CB *p_hci_cmd_cb = &(btu_cb.hci_cmd_cb[controller_id]);
-    UINT16      cc_opcode;
-    BT_HDR      *p_cmd;
-    void        *p_cplt_cback = NULL;
+    command_complete_hack_t *hack = (command_complete_hack_t *)&event->data[0];
 
-    STREAM_TO_UINT8  (p_hci_cmd_cb->cmd_window, p);
+    command_opcode_t opcode;
+    uint8_t *stream = hack->response->data + hack->response->offset + 3; // 2 to skip the event headers, 1 to skip the command credits
+    STREAM_TO_UINT16(opcode, stream);
 
-#if (defined(HCI_MAX_SIMUL_CMDS) && (HCI_MAX_SIMUL_CMDS > 0))
-    if (p_hci_cmd_cb->cmd_window > HCI_MAX_SIMUL_CMDS)
-        p_hci_cmd_cb->cmd_window = HCI_MAX_SIMUL_CMDS;
-#endif
+    btu_hcif_hdl_command_complete(
+      opcode,
+      stream,
+      hack->response->len - 5, // 3 for the command complete headers, 2 for the event headers
+      hack->context);
 
-    STREAM_TO_UINT16 (cc_opcode, p);
+   GKI_freebuf(hack->response);
+   osi_free(event);
+}
 
-    evt_len -= 3;
+static void btu_hcif_command_complete_evt(BT_HDR *response, void *context)
+{
+    BT_HDR *event = osi_calloc(sizeof(BT_HDR) + sizeof(command_complete_hack_t));
+    command_complete_hack_t *hack = (command_complete_hack_t *)&event->data[0];
 
-    /* only do this for certain commands */
-    if ((cc_opcode != HCI_RESET) && (cc_opcode != HCI_HOST_NUM_PACKETS_DONE) &&
-        (cc_opcode != HCI_COMMAND_NONE))
-    {
-        /* dequeue and free stored command */
+    hack->callback = btu_hcif_command_complete_evt_on_task;
+    hack->response = response;
+    hack->context = context;
 
-/* always use cmd code check, when one cmd timeout waiting for cmd_cmpl,
-   it'll cause the rest of the command goes in wrong order                  */
-        p_cmd = (BT_HDR *) GKI_getfirst (&p_hci_cmd_cb->cmd_cmpl_q);
+    event->event = BTU_POST_TO_TASK_NO_GOOD_HORRIBLE_HACK;
 
-        while (p_cmd)
-        {
-            UINT16 opcode_dequeued;
-            UINT8  *p_dequeued;
-
-            /* Make sure dequeued command is for the command_cplt received */
-            p_dequeued = (UINT8 *)(p_cmd + 1) + p_cmd->offset;
-            STREAM_TO_UINT16 (opcode_dequeued, p_dequeued);
-
-            if (opcode_dequeued != cc_opcode)
-            {
-                /* opcode does not match, check next command in the queue */
-                p_cmd = (BT_HDR *) GKI_getnext(p_cmd);
-                continue;
-            }
-            GKI_remove_from_queue(&p_hci_cmd_cb->cmd_cmpl_q, p_cmd);
-
-            /* If command was a VSC, then extract command_complete callback */
-            if ((cc_opcode & HCI_GRP_VENDOR_SPECIFIC) == HCI_GRP_VENDOR_SPECIFIC
-#if BLE_INCLUDED == TRUE
-                || (cc_opcode == HCI_BLE_RAND )
-                || (cc_opcode == HCI_BLE_ENCRYPT)
-#endif
-               )
-            {
-                p_cplt_cback = *((void **)(p_cmd + 1));
-            }
-
-            GKI_freebuf (p_cmd);
-
-            break;
-        }
-
-        /* if more commands in queue restart timer */
-        if (BTU_CMD_CMPL_TIMEOUT > 0)
-        {
-            if (!GKI_queue_is_empty (&(p_hci_cmd_cb->cmd_cmpl_q)))
-            {
-#if (defined(BTU_CMD_CMPL_TOUT_DOUBLE_CHECK) && BTU_CMD_CMPL_TOUT_DOUBLE_CHECK == TRUE)
-                p_hci_cmd_cb->checked_hcisu = FALSE;
-#endif
-                btu_start_timer (&(p_hci_cmd_cb->cmd_cmpl_timer),
-                                 (UINT16)(BTU_TTYPE_BTU_CMD_CMPL + controller_id),
-                                 BTU_CMD_CMPL_TIMEOUT);
-            }
-            else
-            {
-                btu_stop_timer (&(p_hci_cmd_cb->cmd_cmpl_timer));
-            }
-        }
-    }
-
-    /* handle event */
-    btu_hcif_hdl_command_complete (cc_opcode, p, evt_len, p_cplt_cback);
-
-    /* see if we can send more commands */
-    btu_hcif_send_cmd (controller_id, NULL);
+    fixed_queue_enqueue(btu_hci_msg_queue, event);
 }
 
 
@@ -1281,7 +961,6 @@
     tBTM_ESCO_DATA  esco_data;
 #endif
 
-#if BTM_PWR_MGR_INCLUDED == TRUE
     switch (opcode)
     {
         case HCI_EXIT_SNIFF_MODE:
@@ -1307,7 +986,6 @@
             break;
 
         default:
-#endif  /* BTM_PWR_MGR_INCLUDED */
             /* If command failed to start, we may need to tell BTM */
             if (status != HCI_SUCCESS)
             {
@@ -1325,18 +1003,6 @@
                         btm_sec_rmt_name_request_complete (NULL, NULL, status);
                         break;
 
-                    case HCI_CHANGE_CONN_LINK_KEY:
-                        /* Let host know we're done with error */
-                        /* read handle out of stored command */
-                        if (p_cmd != NULL)
-                        {
-                            p_cmd++;
-                            STREAM_TO_UINT16 (handle, p_cmd);
-
-                            btm_acl_link_key_change (handle, status);
-                        }
-                        break;
-
                     case HCI_QOS_SETUP_COMP_EVT:
                         /* Tell qos setup that we are done */
                         btm_qos_setup_complete(status,0,NULL);
@@ -1430,9 +1096,7 @@
                 if ((opcode & HCI_GRP_VENDOR_SPECIFIC) == HCI_GRP_VENDOR_SPECIFIC)
                     btm_vsc_complete (&status, opcode, 1, (tBTM_CMPL_CB *)p_vsc_status_cback);
             }
-#if BTM_PWR_MGR_INCLUDED == TRUE
     }
-#endif
 }
 
 /*******************************************************************************
@@ -1444,246 +1108,37 @@
 ** Returns          void
 **
 *******************************************************************************/
-static void btu_hcif_command_status_evt (UINT8 controller_id, UINT8 *p)
+static void btu_hcif_command_status_evt_on_task(BT_HDR *event)
 {
-    tHCI_CMD_CB * p_hci_cmd_cb = &(btu_cb.hci_cmd_cb[controller_id]);
-    UINT8       status;
-    UINT16      opcode;
-    UINT16      cmd_opcode;
-    BT_HDR      *p_cmd = NULL;
-    UINT8       *p_data = NULL;
-    void        *p_vsc_status_cback = NULL;
+    command_status_hack_t *hack = (command_status_hack_t *)&event->data[0];
 
-    STREAM_TO_UINT8  (status, p);
-    STREAM_TO_UINT8  (p_hci_cmd_cb->cmd_window, p);
+    command_opcode_t opcode;
+    uint8_t *stream = hack->command->data + hack->command->offset;
+    STREAM_TO_UINT16(opcode, stream);
 
-#if (defined(HCI_MAX_SIMUL_CMDS) && (HCI_MAX_SIMUL_CMDS > 0))
-    if (p_hci_cmd_cb->cmd_window > HCI_MAX_SIMUL_CMDS)
-        p_hci_cmd_cb->cmd_window = HCI_MAX_SIMUL_CMDS;
-#endif
+    btu_hcif_hdl_command_status(
+      opcode,
+      hack->status,
+      stream,
+      hack->context);
 
-    STREAM_TO_UINT16 (opcode, p);
-
-    /* only do this for certain commands */
-    if ((opcode != HCI_RESET) && (opcode != HCI_HOST_NUM_PACKETS_DONE) &&
-        (opcode != HCI_COMMAND_NONE))
-    {
-        /*look for corresponding command in cmd_queue*/
-        p_cmd = (BT_HDR *) GKI_getfirst(&(p_hci_cmd_cb->cmd_cmpl_q));
-        while (p_cmd)
-        {
-            p_data = (UINT8 *)(p_cmd + 1) + p_cmd->offset;
-            STREAM_TO_UINT16 (cmd_opcode, p_data);
-
-            /* Make sure this  command is for the command_status received */
-            if (cmd_opcode != opcode)
-            {
-                /* opcode does not match, check next command in the queue */
-                p_cmd = (BT_HDR *) GKI_getnext(p_cmd);
-                continue;
-            }
-            else
-            {
-                GKI_remove_from_queue(&p_hci_cmd_cb->cmd_cmpl_q, p_cmd);
-
-                /* If command was a VSC, then extract command_status callback */
-                 if ((cmd_opcode & HCI_GRP_VENDOR_SPECIFIC) == HCI_GRP_VENDOR_SPECIFIC)
-                {
-                    p_vsc_status_cback = *((void **)(p_cmd + 1));
-                }
-                break;
-            }
-        }
-
-        /* if more commands in queue restart timer */
-        if (BTU_CMD_CMPL_TIMEOUT > 0)
-        {
-            if (!GKI_queue_is_empty (&(p_hci_cmd_cb->cmd_cmpl_q)))
-            {
-#if (defined(BTU_CMD_CMPL_TOUT_DOUBLE_CHECK) && BTU_CMD_CMPL_TOUT_DOUBLE_CHECK == TRUE)
-                p_hci_cmd_cb->checked_hcisu = FALSE;
-#endif
-                btu_start_timer (&(p_hci_cmd_cb->cmd_cmpl_timer),
-                                 (UINT16)(BTU_TTYPE_BTU_CMD_CMPL + controller_id),
-                                 BTU_CMD_CMPL_TIMEOUT);
-            }
-            else
-            {
-                btu_stop_timer (&(p_hci_cmd_cb->cmd_cmpl_timer));
-            }
-        }
-    }
-
-    /* handle command */
-    btu_hcif_hdl_command_status (opcode, status, p_data, p_vsc_status_cback);
-
-    /* free stored command */
-    if (p_cmd != NULL)
-    {
-        GKI_freebuf (p_cmd);
-    }
-    else
-    {
-        HCI_TRACE_WARNING("No command in queue matching opcode %d", opcode);
-    }
-
-    /* See if we can forward any more commands */
-    btu_hcif_send_cmd (controller_id, NULL);
+    GKI_freebuf(hack->command);
+    osi_free(event);
 }
 
-/*******************************************************************************
-**
-** Function         btu_hcif_cmd_timeout
-**
-** Description      Handle a command timeout
-**
-** Returns          void
-**
-*******************************************************************************/
-void btu_hcif_cmd_timeout (UINT8 controller_id)
+static void btu_hcif_command_status_evt(uint8_t status, BT_HDR *command, void *context)
 {
-    tHCI_CMD_CB * p_hci_cmd_cb = &(btu_cb.hci_cmd_cb[controller_id]);
-    BT_HDR  *p_cmd;
-    UINT8   *p;
-    void    *p_cplt_cback = NULL;
-    UINT16  opcode;
-    UINT16  event;
+    BT_HDR *event = osi_calloc(sizeof(BT_HDR) + sizeof(command_status_hack_t));
+    command_status_hack_t *hack = (command_status_hack_t *)&event->data[0];
 
-#if (defined(BTU_CMD_CMPL_TOUT_DOUBLE_CHECK) && BTU_CMD_CMPL_TOUT_DOUBLE_CHECK == TRUE)
-    if (!(p_hci_cmd_cb->checked_hcisu))
-    {
-        HCI_TRACE_WARNING("BTU HCI(id=%d) command timeout - double check HCISU", controller_id);
+    hack->callback = btu_hcif_command_status_evt_on_task;
+    hack->status = status;
+    hack->command = command;
+    hack->context = context;
 
-        /* trigger HCISU to read any pending data in transport buffer */
-        GKI_send_event(HCISU_TASK, HCISU_EVT_MASK);
+    event->event = BTU_POST_TO_TASK_NO_GOOD_HORRIBLE_HACK;
 
-        btu_start_timer (&(p_hci_cmd_cb->cmd_cmpl_timer),
-                         (UINT16)(BTU_TTYPE_BTU_CMD_CMPL + controller_id),
-                         2); /* start short timer, if timer is set to 1 then it could expire before HCISU checks. */
-
-        p_hci_cmd_cb->checked_hcisu = TRUE;
-
-        return;
-    }
-#endif
-
-    /* set the controller cmd window to 1, as if we received a response, so
-    ** the flow of commands from the stack doesn't hang */
-    p_hci_cmd_cb->cmd_window = 1;
-
-    /* get queued command */
-    if ((p_cmd = (BT_HDR *) GKI_dequeue (&(p_hci_cmd_cb->cmd_cmpl_q))) == NULL)
-    {
-        HCI_TRACE_WARNING("Cmd timeout; no cmd in queue");
-        return;
-    }
-
-    /* if more commands in queue restart timer */
-    if (BTU_CMD_CMPL_TIMEOUT > 0)
-    {
-        if (!GKI_queue_is_empty (&(p_hci_cmd_cb->cmd_cmpl_q)))
-        {
-#if (defined(BTU_CMD_CMPL_TOUT_DOUBLE_CHECK) && BTU_CMD_CMPL_TOUT_DOUBLE_CHECK == TRUE)
-            p_hci_cmd_cb->checked_hcisu = FALSE;
-#endif
-            btu_start_timer (&(p_hci_cmd_cb->cmd_cmpl_timer),
-                             (UINT16)(BTU_TTYPE_BTU_CMD_CMPL + controller_id),
-                             BTU_CMD_CMPL_TIMEOUT);
-        }
-    }
-
-    p = (UINT8 *)(p_cmd + 1) + p_cmd->offset;
-#if (NFC_INCLUDED == TRUE)
-    if (controller_id == NFC_CONTROLLER_ID)
-    {
-        //TODO call nfc_ncif_cmd_timeout
-        HCI_TRACE_WARNING("BTU NCI command timeout - header 0x%02x%02x", p[0], p[1]);
-        return;
-    }
-#endif
-
-    /* get opcode from stored command */
-    STREAM_TO_UINT16 (opcode, p);
-
-// btla-specific ++
-#if (defined(ANDROID_APP_INCLUDED) && (ANDROID_APP_INCLUDED == TRUE))
-    ALOGE("######################################################################");
-    ALOGE("#");
-    ALOGE("# WARNING : BTU HCI(id=%d) command timeout. opcode=0x%x", controller_id, opcode);
-    ALOGE("#");
-    ALOGE("######################################################################");
-#else
-    HCI_TRACE_WARNING("BTU HCI(id=%d) command timeout. opcode=0x%x", controller_id, opcode);
-#endif
-// btla-specific ++
-
-    /* send stack a fake command complete or command status, but first determine
-    ** which to send
-    */
-    switch (opcode)
-    {
-        case HCI_HOLD_MODE:
-        case HCI_SNIFF_MODE:
-        case HCI_EXIT_SNIFF_MODE:
-        case HCI_PARK_MODE:
-        case HCI_EXIT_PARK_MODE:
-        case HCI_INQUIRY:
-        case HCI_RMT_NAME_REQUEST:
-        case HCI_QOS_SETUP_COMP_EVT:
-        case HCI_CREATE_CONNECTION:
-        case HCI_CHANGE_CONN_LINK_KEY:
-        case HCI_SWITCH_ROLE:
-        case HCI_READ_RMT_EXT_FEATURES:
-        case HCI_AUTHENTICATION_REQUESTED:
-        case HCI_SET_CONN_ENCRYPTION:
-#if BTM_SCO_INCLUDED == TRUE
-        case HCI_SETUP_ESCO_CONNECTION:
-#endif
-            /* fake a command status */
-            btu_hcif_hdl_command_status (opcode, HCI_ERR_UNSPECIFIED, p, NULL);
-            break;
-
-        default:
-            /* If vendor specific restore the callback function */
-            if ((opcode & HCI_GRP_VENDOR_SPECIFIC) == HCI_GRP_VENDOR_SPECIFIC
-#if BLE_INCLUDED == TRUE
-                || (opcode == HCI_BLE_RAND ) ||
-                (opcode == HCI_BLE_ENCRYPT)
-#endif
-               )
-            {
-                p_cplt_cback = *((void **)(p_cmd + 1));
-            }
-
-            /* fake a command complete; first create a fake event */
-            event = HCI_ERR_UNSPECIFIED;
-            btu_hcif_hdl_command_complete (opcode, (UINT8 *)&event, 1, p_cplt_cback);
-            break;
-    }
-
-    /* free stored command */
-    GKI_freebuf(p_cmd);
-
-    num_hci_cmds_timed_out++;
-    /* When we receive consecutive HCI cmd timeouts for >=BTM_MAX_HCI_CMD_TOUT_BEFORE_RESTART
-     times, Bluetooth process will be killed and restarted */
-    if (num_hci_cmds_timed_out >= BTM_MAX_HCI_CMD_TOUT_BEFORE_RESTART)
-    {
-        HCI_TRACE_ERROR("Num consecutive HCI Cmd tout =%d Restarting BT process",num_hci_cmds_timed_out);
-
-        usleep(10000); /* 10 milliseconds */
-        /* Killing the process to force a restart as part of fault tolerance */
-        kill(getpid(), SIGKILL);
-    }
-    else
-    {
-        HCI_TRACE_WARNING("HCI Cmd timeout counter %d", num_hci_cmds_timed_out);
-
-        /* If anyone wants device status notifications, give him one */
-        btm_report_device_status (BTM_DEV_STATUS_CMD_TOUT);
-    }
-    /* See if we can forward any more commands */
-    btu_hcif_send_cmd (controller_id, NULL);
+    fixed_queue_enqueue(btu_hci_msg_queue, event);
 }
 
 /*******************************************************************************
@@ -1785,14 +1240,10 @@
     STREAM_TO_UINT16 (handle, p);
     STREAM_TO_UINT8 (current_mode, p);
     STREAM_TO_UINT16 (interval, p);
-#if BTM_PWR_MGR_INCLUDED == TRUE
 #if BTM_SCO_WAKE_PARKED_LINK == TRUE
     btm_sco_chk_pend_unpark (status, handle);
 #endif
     btm_pm_proc_mode_change (status, handle, current_mode, interval);
-#else
-    btm_process_mode_change (status, handle, current_mode, interval);
-#endif /* BTM_PWR_MGR_INCLUDED == TRUE */
 
 #if (HID_DEV_INCLUDED == TRUE) && (HID_DEV_PM_INCLUDED == TRUE)
     hidd_pm_proc_mode_change( status, current_mode, interval ) ;
@@ -1811,44 +1262,10 @@
     #if (BTM_SSR_INCLUDED == TRUE)
 static void btu_hcif_ssr_evt (UINT8 *p, UINT16 evt_len)
 {
-#if (BTM_PWR_MGR_INCLUDED == TRUE)
     btm_pm_proc_ssr_evt(p, evt_len);
-#endif
 }
     #endif
 
-
-/*******************************************************************************
-**
-** Function         btu_hcif_return_link_keys_evt
-**
-** Description      Process event HCI_RETURN_LINK_KEYS_EVT
-**
-** Returns          void
-**
-*******************************************************************************/
-
-static void btu_hcif_return_link_keys_evt (UINT8 *p)
-{
-    UINT8                       num_keys;
-    tBTM_RETURN_LINK_KEYS_EVT   *result;
-
-    /* get the number of link keys */
-    num_keys = *p;
-
-    /* If there are no link keys don't call the call back */
-    if (!num_keys)
-        return;
-
-    /* Take one extra byte at the beginning to specify event */
-    result = (tBTM_RETURN_LINK_KEYS_EVT *)(--p);
-    result->event = BTM_CB_EVT_RETURN_LINK_KEYS;
-
-    /* Call the BTM function to pass the link keys to application */
-    btm_return_link_keys_evt (result);
-}
-
-
 /*******************************************************************************
 **
 ** Function         btu_hcif_pin_code_request_evt
@@ -2156,24 +1573,6 @@
 
 /*******************************************************************************
 **
-** Function         btu_hcif_link_super_tout_evt
-**
-** Description      Process event HCI_LINK_SUPER_TOUT_CHANGED_EVT
-**
-** Returns          void
-**
-*******************************************************************************/
-static void btu_hcif_link_super_tout_evt (UINT8 *p)
-{
-    UINT16 handle, timeout;
-    STREAM_TO_UINT16 (handle, p);
-    STREAM_TO_UINT16 (timeout, p);
-
-    btm_proc_lsto_evt(handle, timeout);
-}
-
-/*******************************************************************************
-**
 ** Function         btu_hcif_rem_oob_request_evt
 **
 ** Description      Process event HCI_REMOTE_OOB_DATA_REQUEST_EVT
@@ -2201,30 +1600,6 @@
 {
     btm_simple_pair_complete(p);
 }
-/*******************************************************************************
-**
-** Function         btu_hcif_flush_cmd_queue
-**
-** Description      Flush the HCI command complete queue and transmit queue when
-**                  needed.
-**
-** Returns          void
-**
-*******************************************************************************/
-void btu_hcif_flush_cmd_queue(void)
-{
-    BT_HDR *p_cmd;
-
-    btu_cb.hci_cmd_cb[0].cmd_window = 0;
-    while ((p_cmd = (BT_HDR *) GKI_dequeue (&btu_cb.hci_cmd_cb[0].cmd_cmpl_q)) != NULL)
-    {
-        GKI_freebuf (p_cmd);
-    }
-    while ((p_cmd = (BT_HDR *) GKI_dequeue (&btu_cb.hci_cmd_cb[0].cmd_xmit_q)) != NULL)
-    {
-        GKI_freebuf (p_cmd);
-    }
-}
 
 /*******************************************************************************
 **
diff --git a/stack/btu/btu_init.c b/stack/btu/btu_init.c
index c29d3e2..0888cb5 100644
--- a/stack/btu/btu_init.c
+++ b/stack/btu/btu_init.c
@@ -16,21 +16,26 @@
  *
  ******************************************************************************/
 
-/******************************************************************************
- *
- *  This module contains the routines that load and shutdown the core stack
- *  components.
- *
- ******************************************************************************/
+#define LOG_TAG "bt_task"
+
+#include <assert.h>
 
 #include "bt_target.h"
+#include <pthread.h>
 #include <string.h>
 #include "dyn_mem.h"
 
+#include "osi/include/alarm.h"
+#include "device/include/controller.h"
+#include "osi/include/fixed_queue.h"
+#include "osi/include/hash_map.h"
 #include "btu.h"
 #include "btm_int.h"
+#include "osi/include/hash_functions.h"
 #include "sdpint.h"
+#include "osi/include/thread.h"
 #include "l2c_int.h"
+#include "osi/include/log.h"
 
 #if (BLE_INCLUDED == TRUE)
 #include "gatt_api.h"
@@ -40,15 +45,45 @@
 #endif
 #endif
 
+extern fixed_queue_t *btif_msg_queue;
+
+// Communication queue from bta thread to bt_workqueue.
+fixed_queue_t *btu_bta_msg_queue;
+
+// Communication queue from hci thread to bt_workqueue.
+extern fixed_queue_t *btu_hci_msg_queue;
+
+// General timer queue.
+fixed_queue_t *btu_general_alarm_queue;
+hash_map_t *btu_general_alarm_hash_map;
+pthread_mutex_t btu_general_alarm_lock;
+static const size_t BTU_GENERAL_ALARM_HASH_MAP_SIZE = 17;
+
+// Oneshot timer queue.
+fixed_queue_t *btu_oneshot_alarm_queue;
+hash_map_t *btu_oneshot_alarm_hash_map;
+pthread_mutex_t btu_oneshot_alarm_lock;
+static const size_t BTU_ONESHOT_ALARM_HASH_MAP_SIZE = 17;
+
+// l2cap timer queue.
+fixed_queue_t *btu_l2cap_alarm_queue;
+hash_map_t *btu_l2cap_alarm_hash_map;
+pthread_mutex_t btu_l2cap_alarm_lock;
+static const size_t BTU_L2CAP_ALARM_HASH_MAP_SIZE = 17;
+
+thread_t *bt_workqueue_thread;
+static const char *BT_WORKQUEUE_NAME = "bt_workqueue";
+
 extern void PLATFORM_DisableHciTransport(UINT8 bDisable);
 /*****************************************************************************
 **                          V A R I A B L E S                                *
 ******************************************************************************/
+// TODO(cmanton) Move this out of this file
 const BD_ADDR   BT_BD_ANY = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
 
-/*****************************************************************************
-**                          F U N C T I O N S                                *
-******************************************************************************/
+void btu_task_start_up(void *context);
+void btu_task_shut_down(void *context);
+
 /*****************************************************************************
 **
 ** Function         btu_init_core
@@ -77,10 +112,29 @@
 #endif
 }
 
+/*****************************************************************************
+**
+** Function         btu_free_core
+**
+** Description      Releases control block memory for each core component.
+**
+**
+** Returns          void
+**
+******************************************************************************/
+void btu_free_core(void)
+{
+      /* Free the mandatory core stack components */
+      l2c_free();
+
+#if BLE_INCLUDED == TRUE
+      gatt_free();
+#endif
+}
 
 /*****************************************************************************
 **
-** Function         BTE_Init
+** Function         BTU_StartUp
 **
 ** Description      Initializes the BTU control block.
 **
@@ -90,35 +144,97 @@
 ** Returns          void
 **
 ******************************************************************************/
-void BTE_Init(void)
+void BTU_StartUp(void)
 {
-    int i = 0;
-
     memset (&btu_cb, 0, sizeof (tBTU_CB));
-    btu_cb.hcit_acl_pkt_size = BTU_DEFAULT_DATA_SIZE + HCI_DATA_PREAMBLE_SIZE;
-#if (BLE_INCLUDED == TRUE)
-    btu_cb.hcit_ble_acl_pkt_size = BTU_DEFAULT_BLE_DATA_SIZE + HCI_DATA_PREAMBLE_SIZE;
-#endif
     btu_cb.trace_level = HCI_INITIAL_TRACE_LEVEL;
 
-    for ( i = 0; i < BTU_MAX_LOCAL_CTRLS; i++ ) /* include BR/EDR */
-        btu_cb.hci_cmd_cb[i].cmd_window = 1;
+    btu_bta_msg_queue = fixed_queue_new(SIZE_MAX);
+    if (btu_bta_msg_queue == NULL)
+        goto error_exit;
+
+    btu_general_alarm_hash_map = hash_map_new(BTU_GENERAL_ALARM_HASH_MAP_SIZE,
+            hash_function_pointer, NULL, (data_free_fn)alarm_free, NULL);
+    if (btu_general_alarm_hash_map == NULL)
+        goto error_exit;
+
+    if (pthread_mutex_init(&btu_general_alarm_lock, NULL))
+        goto error_exit;
+
+    btu_general_alarm_queue = fixed_queue_new(SIZE_MAX);
+    if (btu_general_alarm_queue == NULL)
+        goto error_exit;
+
+    btu_oneshot_alarm_hash_map = hash_map_new(BTU_ONESHOT_ALARM_HASH_MAP_SIZE,
+            hash_function_pointer, NULL, (data_free_fn)alarm_free, NULL);
+    if (btu_oneshot_alarm_hash_map == NULL)
+        goto error_exit;
+
+    if (pthread_mutex_init(&btu_oneshot_alarm_lock, NULL))
+        goto error_exit;
+
+    btu_oneshot_alarm_queue = fixed_queue_new(SIZE_MAX);
+    if (btu_oneshot_alarm_queue == NULL)
+        goto error_exit;
+
+    btu_l2cap_alarm_hash_map = hash_map_new(BTU_L2CAP_ALARM_HASH_MAP_SIZE,
+            hash_function_pointer, NULL, (data_free_fn)alarm_free, NULL);
+    if (btu_l2cap_alarm_hash_map == NULL)
+        goto error_exit;
+
+    if (pthread_mutex_init(&btu_l2cap_alarm_lock, NULL))
+        goto error_exit;
+
+    btu_l2cap_alarm_queue = fixed_queue_new(SIZE_MAX);
+    if (btu_l2cap_alarm_queue == NULL)
+         goto error_exit;
+
+    bt_workqueue_thread = thread_new(BT_WORKQUEUE_NAME);
+    if (bt_workqueue_thread == NULL)
+        goto error_exit;
+
+    // Continue startup on bt workqueue thread.
+    thread_post(bt_workqueue_thread, btu_task_start_up, NULL);
+    return;
+
+  error_exit:;
+    LOG_ERROR("%s Unable to allocate resources for bt_workqueue", __func__);
+    BTU_ShutDown();
 }
 
+void BTU_ShutDown(void) {
+  btu_task_shut_down(NULL);
 
-/*****************************************************************************
-**
-** Function         BTU_AclPktSize
-**
-** Description      export the ACL packet size.
-**
-** Returns          UINT16
-**
-******************************************************************************/
-UINT16 BTU_AclPktSize(void)
-{
-    return btu_cb.hcit_acl_pkt_size;
+  fixed_queue_free(btu_bta_msg_queue, NULL);
+
+  hash_map_free(btu_general_alarm_hash_map);
+  pthread_mutex_destroy(&btu_general_alarm_lock);
+  fixed_queue_free(btu_general_alarm_queue, NULL);
+
+  hash_map_free(btu_oneshot_alarm_hash_map);
+  pthread_mutex_destroy(&btu_oneshot_alarm_lock);
+  fixed_queue_free(btu_oneshot_alarm_queue, NULL);
+
+  hash_map_free(btu_l2cap_alarm_hash_map);
+  pthread_mutex_destroy(&btu_l2cap_alarm_lock);
+  fixed_queue_free(btu_l2cap_alarm_queue, NULL);
+
+  thread_free(bt_workqueue_thread);
+
+  btu_bta_msg_queue = NULL;
+
+  btu_general_alarm_hash_map = NULL;
+  btu_general_alarm_queue = NULL;
+
+  btu_oneshot_alarm_hash_map = NULL;
+  btu_oneshot_alarm_queue = NULL;
+
+  btu_l2cap_alarm_hash_map = NULL;
+  btu_l2cap_alarm_queue = NULL;
+
+  bt_workqueue_thread = NULL;
 }
+
 /*****************************************************************************
 **
 ** Function         BTU_BleAclPktSize
@@ -131,7 +247,7 @@
 UINT16 BTU_BleAclPktSize(void)
 {
 #if BLE_INCLUDED == TRUE
-    return btu_cb.hcit_ble_acl_pkt_size;
+    return controller_get_interface()->get_acl_packet_size_ble();
 #else
     return 0;
 #endif
@@ -147,11 +263,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-void btu_uipc_rx_cback(BT_HDR *p_msg)
-{
-    BT_TRACE(TRACE_LAYER_BTM, TRACE_TYPE_DEBUG, "btu_uipc_rx_cback event 0x%x, len %d, offset %d",
-		p_msg->event, p_msg->len, p_msg->offset);
-    GKI_send_msg(BTU_TASK, BTU_HCI_RCV_MBOX, p_msg);
-
+void btu_uipc_rx_cback(BT_HDR *p_msg) {
+  assert(p_msg != NULL);
+  BT_TRACE(TRACE_LAYER_BTM, TRACE_TYPE_DEBUG, "btu_uipc_rx_cback event 0x%x,"
+      " len %d, offset %d", p_msg->event, p_msg->len, p_msg->offset);
+  fixed_queue_enqueue(btu_hci_msg_queue, p_msg);
 }
-
diff --git a/stack/btu/btu_task.c b/stack/btu/btu_task.c
index f93e637..e2b899e 100644
--- a/stack/btu/btu_task.c
+++ b/stack/btu/btu_task.c
@@ -16,72 +16,38 @@
  *
  ******************************************************************************/
 
-/******************************************************************************
- *
- *  This file contains the main Bluetooth Upper Layer processing loop.
- *  The Broadcom implementations of L2CAP RFCOMM, SDP and the BTIf run as one
- *  GKI task. This btu_task switches between them.
- *
- *  Note that there will always be an L2CAP, but there may or may not be an
- *  RFCOMM or SDP. Whether these layers are present or not is determined by
- *  compile switches.
- *
- ******************************************************************************/
+#define LOG_TAG "bt_btu_task"
 
+#include <assert.h>
 #include <stdlib.h>
-#include <string.h>
 #include <stdio.h>
+#include <string.h>
 
+#include "osi/include/alarm.h"
 #include "bt_target.h"
-#include "gki.h"
+#include "bt_trace.h"
 #include "bt_types.h"
-#include "hcimsgs.h"
-#include "l2c_int.h"
-#include "btu.h"
 #include "bt_utils.h"
-#include <sys/prctl.h>
-
-#include "sdpint.h"
-
-#if ( defined(RFCOMM_INCLUDED) && RFCOMM_INCLUDED == TRUE )
-#include "port_api.h"
-#include "port_ext.h"
-#endif
-
+#include "btif_common.h"
 #include "btm_api.h"
 #include "btm_int.h"
+#include "btu.h"
+#include "osi/include/fixed_queue.h"
+#include "osi/include/future.h"
+#include "gki.h"
+#include "osi/include/hash_map.h"
+#include "hcimsgs.h"
+#include "l2c_int.h"
+#include "btcore/include/module.h"
+#include "osi/include/osi.h"
+#include "osi/include/log.h"
+#include "sdpint.h"
+#include "osi/include/thread.h"
 
-#if (defined(EVAL) && EVAL == TRUE)
-#include "btu_eval.h"
-#endif
+#include "port_api.h"
+#include "port_ext.h"
 
-#if GAP_INCLUDED == TRUE
 #include "gap_int.h"
-#endif
-
-#if (defined(OBX_INCLUDED) && OBX_INCLUDED == TRUE)
-#include "obx_int.h"
-
-#if (defined(BIP_INCLUDED) && BIP_INCLUDED == TRUE)
-#include "bip_int.h"
-#endif /* BIP */
-
-#if (BPP_SND_INCLUDED == TRUE ||  BPP_INCLUDED == TRUE)
-#include "bpp_int.h"
-#endif /* BPP */
-
-#endif /* OBX */
-
-#include "bt_trace.h"
-
-/* BTE application task */
-#if APPL_INCLUDED == TRUE
-#include "bte_appl.h"
-#endif
-
-#if (defined(RPC_INCLUDED) && RPC_INCLUDED == TRUE)
-#include "rpct_main.h"
-#endif
 
 #if (defined(BNEP_INCLUDED) && BNEP_INCLUDED == TRUE)
 #include "bnep_int.h"
@@ -91,14 +57,6 @@
 #include "pan_int.h"
 #endif
 
-#if (defined(SAP_SERVER_INCLUDED) && SAP_SERVER_INCLUDED == TRUE)
-#include "sap_int.h"
-#endif
-
-#if (defined(HID_DEV_INCLUDED) && HID_DEV_INCLUDED == TRUE )
-#include "hidd_int.h"
-#endif
-
 #if (defined(HID_HOST_INCLUDED) && HID_HOST_INCLUDED == TRUE )
 #include "hidh_int.h"
 #endif
@@ -115,10 +73,7 @@
 #include "mca_int.h"
 #endif
 
-
-#if (defined(BTU_BTA_INCLUDED) && BTU_BTA_INCLUDED == TRUE)
 #include "bta_sys.h"
-#endif
 
 #if (BLE_INCLUDED == TRUE)
 #include "gatt_int.h"
@@ -128,16 +83,7 @@
 #include "btm_ble_int.h"
 #endif
 
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-BT_API extern void BTE_InitStack(void);
-
-#ifdef __cplusplus
-}
-#endif
+extern void BTE_InitStack(void);
 
 /* Define BTU storage area
 */
@@ -145,492 +91,239 @@
 tBTU_CB  btu_cb;
 #endif
 
+// Communication queue between btu_task and bta.
+extern fixed_queue_t *btu_bta_msg_queue;
+
+// Communication queue between btu_task and hci.
+extern fixed_queue_t *btu_hci_msg_queue;
+
+// General timer queue.
+extern fixed_queue_t *btu_general_alarm_queue;
+extern hash_map_t *btu_general_alarm_hash_map;
+extern pthread_mutex_t btu_general_alarm_lock;
+
+// Oneshot timer queue.
+extern fixed_queue_t *btu_oneshot_alarm_queue;
+extern hash_map_t *btu_oneshot_alarm_hash_map;
+extern pthread_mutex_t btu_oneshot_alarm_lock;
+
+// l2cap timer queue.
+extern fixed_queue_t *btu_l2cap_alarm_queue;
+extern hash_map_t *btu_l2cap_alarm_hash_map;
+extern pthread_mutex_t btu_l2cap_alarm_lock;
+
+extern fixed_queue_t *event_queue;
+extern fixed_queue_t *btif_msg_queue;
+
+extern thread_t *bt_workqueue_thread;
 
 /* Define a function prototype to allow a generic timeout handler */
 typedef void (tUSER_TIMEOUT_FUNC) (TIMER_LIST_ENT *p_tle);
 
-/*******************************************************************************
-**
-** Function         btu_task
-**
-** Description      This is the main task of the Bluetooth Upper Layers unit.
-**                  It sits in a loop waiting for messages, and dispatches them
-**                  to the appropiate handlers.
-**
-** Returns          should never return
-**
-*******************************************************************************/
-BTU_API UINT32 btu_task (UINT32 param)
-{
-    UINT16           event;
-    BT_HDR          *p_msg;
-    UINT8            i;
-    UINT16           mask;
-    BOOLEAN          handled;
-    UNUSED(param);
+static void btu_l2cap_alarm_process(TIMER_LIST_ENT *p_tle);
+static void btu_general_alarm_process(TIMER_LIST_ENT *p_tle);
+static void btu_bta_alarm_process(TIMER_LIST_ENT *p_tle);
+static void btu_hci_msg_process(BT_HDR *p_msg);
 
-#if (defined(HCISU_H4_INCLUDED) && HCISU_H4_INCLUDED == TRUE)
-    /* wait an event that HCISU is ready */
-    BT_TRACE(TRACE_LAYER_BTU, TRACE_TYPE_API,
-                "btu_task pending for preload complete event");
+void btu_hci_msg_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
+    BT_HDR *p_msg = (BT_HDR *)fixed_queue_dequeue(queue);
+    btu_hci_msg_process(p_msg);
+}
 
-    for (;;)
-    {
-        event = GKI_wait (0xFFFF, 0);
-        if (event & EVENT_MASK(GKI_SHUTDOWN_EVT))
-        {
-            /* indicates BT ENABLE abort */
-            BT_TRACE(TRACE_LAYER_BTU, TRACE_TYPE_WARNING,
-                        "btu_task start abort!");
-            return (0);
-        }
-        else if (event & BT_EVT_PRELOAD_CMPL)
-        {
+void btu_general_alarm_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
+    TIMER_LIST_ENT *p_tle = (TIMER_LIST_ENT *)fixed_queue_dequeue(queue);
+    btu_general_alarm_process(p_tle);
+}
+
+void btu_oneshot_alarm_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
+    TIMER_LIST_ENT *p_tle = (TIMER_LIST_ENT *)fixed_queue_dequeue(queue);
+    btu_general_alarm_process(p_tle);
+
+    switch (p_tle->event) {
+#if (defined(BLE_INCLUDED) && BLE_INCLUDED == TRUE)
+        case BTU_TTYPE_BLE_RANDOM_ADDR:
+            btm_ble_timeout(p_tle);
             break;
-        }
-        else
-        {
-            BT_TRACE(TRACE_LAYER_BTU, TRACE_TYPE_WARNING,
-                "btu_task ignore evt %04x while pending for preload complete",
-                event);
-        }
-    }
-
-    BT_TRACE(TRACE_LAYER_BTU, TRACE_TYPE_API,
-                "btu_task received preload complete event");
 #endif
 
-    /* Initialize the mandatory core stack control blocks
-       (BTU, BTM, L2CAP, and SDP)
-     */
-    btu_init_core();
-
-    /* Initialize any optional stack components */
-    BTE_InitStack();
-
-#if (defined(BTU_BTA_INCLUDED) && BTU_BTA_INCLUDED == TRUE)
-    bta_sys_init();
-#endif
-
-    /* Initialise platform trace levels at this point as BTE_InitStack() and bta_sys_init()
-     * reset the control blocks and preset the trace level with XXX_INITIAL_TRACE_LEVEL
-     */
-#if ( BT_USE_TRACES==TRUE )
-    BTE_InitTraceLevels();
-#endif
-
-    /* Send a startup evt message to BTIF_TASK to kickstart the init procedure */
-    GKI_send_event(BTIF_TASK, BT_EVT_TRIGGER_STACK_INIT);
-
-    prctl(PR_SET_NAME, (unsigned long)"BTU TASK", 0, 0, 0);
-
-    raise_priority_a2dp(TASK_HIGH_BTU);
-
-    /* Wait for, and process, events */
-    for (;;)
-    {
-        event = GKI_wait (0xFFFF, 0);
-
-        if (event & TASK_MBOX_0_EVT_MASK)
-        {
-            /* Process all messages in the queue */
-            while ((p_msg = (BT_HDR *) GKI_read_mbox (BTU_HCI_RCV_MBOX)) != NULL)
+        case BTU_TTYPE_USER_FUNC:
             {
-                /* Determine the input message type. */
-                switch (p_msg->event & BT_EVT_MASK)
-                {
-                    case BT_EVT_TO_BTU_HCI_ACL:
-                        /* All Acl Data goes to L2CAP */
-                        l2c_rcv_acl_data (p_msg);
-                        break;
+                tUSER_TIMEOUT_FUNC  *p_uf = (tUSER_TIMEOUT_FUNC *)p_tle->param;
+                (*p_uf)(p_tle);
+            }
+            break;
 
-                    case BT_EVT_TO_BTU_L2C_SEG_XMIT:
-                        /* L2CAP segment transmit complete */
-                        l2c_link_segments_xmitted (p_msg);
-                        break;
+        default:
+            // FAIL
+            BTM_TRACE_WARNING("Received unexpected oneshot timer event:0x%x\n",
+                p_tle->event);
+            break;
+    }
+}
 
-                    case BT_EVT_TO_BTU_HCI_SCO:
+void btu_l2cap_alarm_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
+    TIMER_LIST_ENT *p_tle = (TIMER_LIST_ENT *)fixed_queue_dequeue(queue);
+    btu_l2cap_alarm_process(p_tle);
+}
+
+void btu_bta_msg_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
+    BT_HDR *p_msg = (BT_HDR *)fixed_queue_dequeue(queue);
+    bta_sys_event(p_msg);
+}
+
+void btu_bta_alarm_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
+    TIMER_LIST_ENT *p_tle = (TIMER_LIST_ENT *)fixed_queue_dequeue(queue);
+    btu_bta_alarm_process(p_tle);
+}
+
+static void btu_hci_msg_process(BT_HDR *p_msg) {
+    /* Determine the input message type. */
+    switch (p_msg->event & BT_EVT_MASK)
+    {
+        case BTU_POST_TO_TASK_NO_GOOD_HORRIBLE_HACK: // TODO(zachoverflow): remove this
+            ((post_to_task_hack_t *)(&p_msg->data[0]))->callback(p_msg);
+            break;
+        case BT_EVT_TO_BTU_HCI_ACL:
+            /* All Acl Data goes to L2CAP */
+            l2c_rcv_acl_data (p_msg);
+            break;
+
+        case BT_EVT_TO_BTU_L2C_SEG_XMIT:
+            /* L2CAP segment transmit complete */
+            l2c_link_segments_xmitted (p_msg);
+            break;
+
+        case BT_EVT_TO_BTU_HCI_SCO:
 #if BTM_SCO_INCLUDED == TRUE
-                        btm_route_sco_data (p_msg);
-                        break;
+            btm_route_sco_data (p_msg);
+            break;
 #endif
 
-                    case BT_EVT_TO_BTU_HCI_EVT:
-                        btu_hcif_process_event ((UINT8)(p_msg->event & BT_SUB_EVT_MASK), p_msg);
-                        GKI_freebuf(p_msg);
+        case BT_EVT_TO_BTU_HCI_EVT:
+            btu_hcif_process_event ((UINT8)(p_msg->event & BT_SUB_EVT_MASK), p_msg);
+            GKI_freebuf(p_msg);
 
 #if (defined(HCILP_INCLUDED) && HCILP_INCLUDED == TRUE)
-                        /* If host receives events which it doesn't response to, */
-                        /* host should start idle timer to enter sleep mode.     */
-                        btu_check_bt_sleep ();
+            /* If host receives events which it doesn't response to, */
+            /* host should start idle timer to enter sleep mode.     */
+            btu_check_bt_sleep ();
 #endif
-                        break;
+            break;
 
-                    case BT_EVT_TO_BTU_HCI_CMD:
-                        btu_hcif_send_cmd ((UINT8)(p_msg->event & BT_SUB_EVT_MASK), p_msg);
-                        break;
+        case BT_EVT_TO_BTU_HCI_CMD:
+            btu_hcif_send_cmd ((UINT8)(p_msg->event & BT_SUB_EVT_MASK), p_msg);
+            break;
 
-#if (defined(OBX_INCLUDED) && OBX_INCLUDED == TRUE)
-#if (defined(OBX_SERVER_INCLUDED) && OBX_SERVER_INCLUDED == TRUE)
-                    case BT_EVT_TO_OBX_SR_MSG:
-                        obx_sr_proc_evt((tOBX_PORT_EVT *)(p_msg + 1));
-                        GKI_freebuf (p_msg);
-                        break;
+        default:;
+            int i = 0;
+            uint16_t mask = (UINT16) (p_msg->event & BT_EVT_MASK);
+            BOOLEAN handled = FALSE;
 
-                    case BT_EVT_TO_OBX_SR_L2C_MSG:
-                        obx_sr_proc_l2c_evt((tOBX_L2C_EVT_MSG *)(p_msg + 1));
-                        GKI_freebuf (p_msg);
-                        break;
-#endif
-
-#if (defined(OBX_CLIENT_INCLUDED) && OBX_CLIENT_INCLUDED == TRUE)
-                    case BT_EVT_TO_OBX_CL_MSG:
-                        obx_cl_proc_evt((tOBX_PORT_EVT *)(p_msg + 1));
-                        GKI_freebuf (p_msg);
-                        break;
-
-                    case BT_EVT_TO_OBX_CL_L2C_MSG:
-                        obx_cl_proc_l2c_evt((tOBX_L2C_EVT_MSG *)(p_msg + 1));
-                        GKI_freebuf (p_msg);
-                        break;
-#endif
-
-#if (defined(BIP_INCLUDED) && BIP_INCLUDED == TRUE)
-                    case BT_EVT_TO_BIP_CMDS :
-                        bip_proc_btu_event(p_msg);
-                        GKI_freebuf (p_msg);
-                        break;
-#endif /* BIP */
-#if (BPP_SND_INCLUDED == TRUE || BPP_INCLUDED == TRUE)
-                    case BT_EVT_TO_BPP_PR_CMDS:
-                        bpp_pr_proc_event(p_msg);
-                        GKI_freebuf (p_msg);
-                        break;
-                    case BT_EVT_TO_BPP_SND_CMDS:
-                        bpp_snd_proc_event(p_msg);
-                        GKI_freebuf (p_msg);
-                        break;
-
-#endif /* BPP */
-
-#endif /* OBX */
-
-#if (defined(SAP_SERVER_INCLUDED) && SAP_SERVER_INCLUDED == TRUE)
-                    case BT_EVT_TO_BTU_SAP :
-                        sap_proc_btu_event(p_msg);
-                        GKI_freebuf (p_msg);
-                        break;
-#endif /* SAP */
-#if (defined(GAP_CONN_INCLUDED) && GAP_CONN_INCLUDED == TRUE && GAP_CONN_POST_EVT_INCLUDED == TRUE)
-                    case BT_EVT_TO_GAP_MSG :
-                        gap_proc_btu_event(p_msg);
-                        GKI_freebuf (p_msg);
-                        break;
-#endif
-                    case BT_EVT_TO_START_TIMER :
-                        /* Start free running 1 second timer for list management */
-                        GKI_start_timer (TIMER_0, GKI_SECS_TO_TICKS (1), TRUE);
-                        GKI_freebuf (p_msg);
-                        break;
-
-                    case BT_EVT_TO_STOP_TIMER:
-                        if (GKI_timer_queue_is_empty(&btu_cb.timer_queue)) {
-                            GKI_stop_timer(TIMER_0);
-                        }
-                        GKI_freebuf (p_msg);
-                        break;
-
-                    case BT_EVT_TO_START_TIMER_ONESHOT:
-                        if (!GKI_timer_queue_is_empty(&btu_cb.timer_queue_oneshot)) {
-                            TIMER_LIST_ENT *tle = GKI_timer_getfirst(&btu_cb.timer_queue_oneshot);
-                            // Start non-repeating timer.
-                            GKI_start_timer(TIMER_3, tle->ticks, FALSE);
-                        } else {
-                            BTM_TRACE_WARNING("Oneshot timer queue empty when received start request");
-                        }
-                        GKI_freebuf(p_msg);
-                        break;
-
-                    case BT_EVT_TO_STOP_TIMER_ONESHOT:
-                        if (GKI_timer_queue_is_empty(&btu_cb.timer_queue_oneshot)) {
-                            GKI_stop_timer(TIMER_3);
-                        } else {
-                            BTM_TRACE_WARNING("Oneshot timer queue not empty when received stop request");
-                        }
-                        GKI_freebuf (p_msg);
-                        break;
-
-#if defined(QUICK_TIMER_TICKS_PER_SEC) && (QUICK_TIMER_TICKS_PER_SEC > 0)
-                    case BT_EVT_TO_START_QUICK_TIMER :
-                        GKI_start_timer (TIMER_2, QUICK_TIMER_TICKS, TRUE);
-                        GKI_freebuf (p_msg);
-                        break;
-#endif
-
-                    default:
-                        i = 0;
-                        mask = (UINT16) (p_msg->event & BT_EVT_MASK);
-                        handled = FALSE;
-
-                        for (; !handled && i < BTU_MAX_REG_EVENT; i++)
-                        {
-                            if (btu_cb.event_reg[i].event_cb == NULL)
-                                continue;
-
-                            if (mask == btu_cb.event_reg[i].event_range)
-                            {
-                                if (btu_cb.event_reg[i].event_cb)
-                                {
-                                    btu_cb.event_reg[i].event_cb(p_msg);
-                                    handled = TRUE;
-                                }
-                            }
-                        }
-
-                        if (handled == FALSE)
-                            GKI_freebuf (p_msg);
-
-                        break;
-                }
-            }
-        }
-
-
-        if (event & TIMER_0_EVT_MASK) {
-            GKI_update_timer_list (&btu_cb.timer_queue, 1);
-
-            while (!GKI_timer_queue_is_empty(&btu_cb.timer_queue)) {
-                TIMER_LIST_ENT *p_tle = GKI_timer_getfirst(&btu_cb.timer_queue);
-                if (p_tle->ticks != 0)
-                    break;
-
-                GKI_remove_from_timer_list(&btu_cb.timer_queue, p_tle);
-
-                switch (p_tle->event) {
-                    case BTU_TTYPE_BTM_DEV_CTL:
-                        btm_dev_timeout(p_tle);
-                        break;
-
-                    case BTU_TTYPE_BTM_ACL:
-                        btm_acl_timeout(p_tle);
-                        break;
-
-                    case BTU_TTYPE_L2CAP_LINK:
-                    case BTU_TTYPE_L2CAP_CHNL:
-                    case BTU_TTYPE_L2CAP_HOLD:
-                    case BTU_TTYPE_L2CAP_INFO:
-                    case BTU_TTYPE_L2CAP_FCR_ACK:
-                        l2c_process_timeout (p_tle);
-                        break;
-
-                    case BTU_TTYPE_SDP:
-                        sdp_conn_timeout ((tCONN_CB *)p_tle->param);
-                        break;
-
-                    case BTU_TTYPE_BTM_RMT_NAME:
-                        btm_inq_rmt_name_failed();
-                        break;
-
-#if (defined(RFCOMM_INCLUDED) && RFCOMM_INCLUDED == TRUE)
-                    case BTU_TTYPE_RFCOMM_MFC:
-                    case BTU_TTYPE_RFCOMM_PORT:
-                        rfcomm_process_timeout (p_tle);
-                        break;
-
-#endif /* If defined(RFCOMM_INCLUDED) && RFCOMM_INCLUDED == TRUE */
-
-#if ((defined(BNEP_INCLUDED) && BNEP_INCLUDED == TRUE))
-                    case BTU_TTYPE_BNEP:
-                        bnep_process_timeout(p_tle);
-                        break;
-#endif
-
-
-#if (defined(AVDT_INCLUDED) && AVDT_INCLUDED == TRUE)
-                    case BTU_TTYPE_AVDT_CCB_RET:
-                    case BTU_TTYPE_AVDT_CCB_RSP:
-                    case BTU_TTYPE_AVDT_CCB_IDLE:
-                    case BTU_TTYPE_AVDT_SCB_TC:
-                        avdt_process_timeout(p_tle);
-                        break;
-#endif
-
-#if (defined(OBX_INCLUDED) && OBX_INCLUDED == TRUE)
-#if (defined(OBX_CLIENT_INCLUDED) && OBX_CLIENT_INCLUDED == TRUE)
-                    case BTU_TTYPE_OBX_CLIENT_TO:
-                        obx_cl_timeout(p_tle);
-                        break;
-#endif
-#if (defined(OBX_SERVER_INCLUDED) && OBX_SERVER_INCLUDED == TRUE)
-                    case BTU_TTYPE_OBX_SERVER_TO:
-                        obx_sr_timeout(p_tle);
-                        break;
-
-                    case BTU_TTYPE_OBX_SVR_SESS_TO:
-                        obx_sr_sess_timeout(p_tle);
-                        break;
-#endif
-#endif
-
-#if (defined(SAP_SERVER_INCLUDED) && SAP_SERVER_INCLUDED == TRUE)
-                    case BTU_TTYPE_SAP_TO:
-                        sap_process_timeout(p_tle);
-                        break;
-#endif
-
-                    case BTU_TTYPE_BTU_CMD_CMPL:
-                        btu_hcif_cmd_timeout((UINT8)(p_tle->event - BTU_TTYPE_BTU_CMD_CMPL));
-                        break;
-
-#if (defined(HID_HOST_INCLUDED) && HID_HOST_INCLUDED == TRUE)
-                    case BTU_TTYPE_HID_HOST_REPAGE_TO :
-                        hidh_proc_repage_timeout(p_tle);
-                        break;
-#endif
-
-#if (defined(BLE_INCLUDED) && BLE_INCLUDED == TRUE)
-                    case BTU_TTYPE_BLE_INQUIRY:
-                    case BTU_TTYPE_BLE_GAP_LIM_DISC:
-                    case BTU_TTYPE_BLE_GAP_FAST_ADV:
-                    case BTU_TTYPE_BLE_OBSERVE:
-                        btm_ble_timeout(p_tle);
-                        break;
-
-                    case BTU_TTYPE_ATT_WAIT_FOR_RSP:
-                        gatt_rsp_timeout(p_tle);
-                        break;
-
-                    case BTU_TTYPE_ATT_WAIT_FOR_IND_ACK:
-                        gatt_ind_ack_timeout(p_tle);
-                        break;
-#if (defined(SMP_INCLUDED) && SMP_INCLUDED == TRUE)
-                    case BTU_TTYPE_SMP_PAIRING_CMD:
-                        smp_rsp_timeout(p_tle);
-                        break;
-#endif
-
-#endif
-
-#if (MCA_INCLUDED == TRUE)
-                    case BTU_TTYPE_MCA_CCB_RSP:
-                        mca_process_timeout(p_tle);
-                        break;
-#endif
-                    case BTU_TTYPE_USER_FUNC:
-                        {
-                            tUSER_TIMEOUT_FUNC  *p_uf = (tUSER_TIMEOUT_FUNC *)p_tle->param;
-                            (*p_uf)(p_tle);
-                        }
-                        break;
-
-                    default:
-                        i = 0;
-                        handled = FALSE;
-
-                        for (; !handled && i < BTU_MAX_REG_TIMER; i++)
-                        {
-                            if (btu_cb.timer_reg[i].timer_cb == NULL)
-                                continue;
-                            if (btu_cb.timer_reg[i].p_tle == p_tle)
-                            {
-                                btu_cb.timer_reg[i].timer_cb(p_tle);
-                                handled = TRUE;
-                            }
-                        }
-                        break;
-                }
-            }
-
-            /* if timer list is empty stop periodic GKI timer */
-            if (btu_cb.timer_queue.p_first == NULL)
+            for (; !handled && i < BTU_MAX_REG_EVENT; i++)
             {
-                GKI_stop_timer(TIMER_0);
-            }
-        }
+                if (btu_cb.event_reg[i].event_cb == NULL)
+                    continue;
 
-#if defined(QUICK_TIMER_TICKS_PER_SEC) && (QUICK_TIMER_TICKS_PER_SEC > 0)
-        if (event & TIMER_2_EVT_MASK)
-        {
-            btu_process_quick_timer_evt();
-        }
-#endif
-
-
-#if (RPC_INCLUDED == TRUE)
-        /* if RPC message queue event */
-        if (event & RPCGEN_MSG_EVT)
-        {
-            if ((p_msg = (BT_HDR *) GKI_read_mbox(RPCGEN_MSG_MBOX)) != NULL)
-                RPCT_RpcgenMsg(p_msg);  /* handle RPC message queue */
-        }
-#endif
-
-#if (defined(BTU_BTA_INCLUDED) && BTU_BTA_INCLUDED == TRUE)
-        if (event & TASK_MBOX_2_EVT_MASK)
-        {
-            while ((p_msg = (BT_HDR *) GKI_read_mbox(TASK_MBOX_2)) != NULL)
-            {
-                bta_sys_event(p_msg);
-            }
-        }
-
-        if (event & TIMER_1_EVT_MASK)
-        {
-            bta_sys_timer_update();
-        }
-#endif
-
-        if (event & TIMER_3_EVT_MASK) {
-            BTM_TRACE_API("Received oneshot timer event complete");
-            if (!GKI_timer_queue_is_empty(&btu_cb.timer_queue_oneshot)) {
-                INT32 ticks_since_last_update = GKI_timer_ticks_getinitial(GKI_timer_getfirst(&btu_cb.timer_queue_oneshot));
-                GKI_update_timer_list(&btu_cb.timer_queue_oneshot, ticks_since_last_update);
-            }
-
-            while (!GKI_timer_queue_is_empty(&btu_cb.timer_queue_oneshot)) {
-                TIMER_LIST_ENT *p_tle = GKI_timer_getfirst(&btu_cb.timer_queue_oneshot);
-                if (p_tle->ticks != 0)
-                    break;
-
-                GKI_remove_from_timer_list(&btu_cb.timer_queue_oneshot, p_tle);
-
-                switch (p_tle->event) {
-#if (defined(BLE_INCLUDED) && BLE_INCLUDED == TRUE)
-                    case BTU_TTYPE_BLE_RANDOM_ADDR:
-                        btm_ble_timeout(p_tle);
-                        break;
-#endif
-
-                    case BTU_TTYPE_USER_FUNC:
-                        {
-                            tUSER_TIMEOUT_FUNC  *p_uf = (tUSER_TIMEOUT_FUNC *)p_tle->param;
-                            (*p_uf)(p_tle);
-                        }
-                        break;
-
-                    default:
-                        // FAIL
-                        BTM_TRACE_WARNING("Received unexpected oneshot timer event:0x%x\n",
-                            p_tle->event);
-                        break;
+                if (mask == btu_cb.event_reg[i].event_range)
+                {
+                    if (btu_cb.event_reg[i].event_cb)
+                    {
+                        btu_cb.event_reg[i].event_cb(p_msg);
+                        handled = TRUE;
+                    }
                 }
             }
 
-            /* Update GKI timer with new tick value from first timer. */
-            if (!GKI_timer_queue_is_empty(&btu_cb.timer_queue_oneshot)) {
-                TIMER_LIST_ENT *p_tle = GKI_timer_getfirst(&btu_cb.timer_queue_oneshot);
-                if (p_tle->ticks > 0)
-                  GKI_start_timer(TIMER_3, p_tle->ticks, FALSE);
-            } else {
-                GKI_stop_timer(TIMER_3);
-            }
-        }
+            if (handled == FALSE)
+                GKI_freebuf (p_msg);
 
-        if (event & EVENT_MASK(APPL_EVT_7))
             break;
     }
 
-    return(0);
+}
+
+static void btu_bta_alarm_process(TIMER_LIST_ENT *p_tle) {
+    /* call timer callback */
+    if (p_tle->p_cback) {
+        (*p_tle->p_cback)(p_tle);
+    } else if (p_tle->event) {
+        BT_HDR *p_msg;
+        if ((p_msg = (BT_HDR *) GKI_getbuf(sizeof(BT_HDR))) != NULL) {
+            p_msg->event = p_tle->event;
+            p_msg->layer_specific = 0;
+            bta_sys_sendmsg(p_msg);
+        }
+    }
+}
+
+void btu_task_start_up(UNUSED_ATTR void *context) {
+  BT_TRACE(TRACE_LAYER_BTU, TRACE_TYPE_API,
+      "btu_task pending for preload complete event");
+
+  LOG_INFO("Bluetooth chip preload is complete");
+
+  BT_TRACE(TRACE_LAYER_BTU, TRACE_TYPE_API,
+      "btu_task received preload complete event");
+
+  /* Initialize the mandatory core stack control blocks
+     (BTU, BTM, L2CAP, and SDP)
+   */
+  btu_init_core();
+
+  /* Initialize any optional stack components */
+  BTE_InitStack();
+
+  bta_sys_init();
+
+  /* Initialise platform trace levels at this point as BTE_InitStack() and bta_sys_init()
+   * reset the control blocks and preset the trace level with XXX_INITIAL_TRACE_LEVEL
+   */
+#if ( BT_USE_TRACES==TRUE )
+  module_init(get_module(BTE_LOGMSG_MODULE));
+#endif
+
+  // Inform the bt jni thread initialization is ok.
+  btif_transfer_context(btif_init_ok, 0, NULL, 0, NULL);
+
+  fixed_queue_register_dequeue(btu_bta_msg_queue,
+      thread_get_reactor(bt_workqueue_thread),
+      btu_bta_msg_ready,
+      NULL);
+
+  fixed_queue_register_dequeue(btu_hci_msg_queue,
+      thread_get_reactor(bt_workqueue_thread),
+      btu_hci_msg_ready,
+      NULL);
+
+  fixed_queue_register_dequeue(btu_general_alarm_queue,
+      thread_get_reactor(bt_workqueue_thread),
+      btu_general_alarm_ready,
+      NULL);
+
+  fixed_queue_register_dequeue(btu_oneshot_alarm_queue,
+      thread_get_reactor(bt_workqueue_thread),
+      btu_oneshot_alarm_ready,
+      NULL);
+
+  fixed_queue_register_dequeue(btu_l2cap_alarm_queue,
+      thread_get_reactor(bt_workqueue_thread),
+      btu_l2cap_alarm_ready,
+      NULL);
+}
+
+void btu_task_shut_down(UNUSED_ATTR void *context) {
+  fixed_queue_unregister_dequeue(btu_bta_msg_queue);
+  fixed_queue_unregister_dequeue(btu_hci_msg_queue);
+  fixed_queue_unregister_dequeue(btu_general_alarm_queue);
+  fixed_queue_unregister_dequeue(btu_oneshot_alarm_queue);
+  fixed_queue_unregister_dequeue(btu_l2cap_alarm_queue);
+
+#if ( BT_USE_TRACES==TRUE )
+  module_clean_up(get_module(BTE_LOGMSG_MODULE));
+#endif
+
+  bta_sys_free();
+  btu_free_core();
 }
 
 /*******************************************************************************
@@ -644,52 +337,140 @@
 ** Returns          void
 **
 *******************************************************************************/
-void btu_start_timer (TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout)
-{
-    BT_HDR *p_msg;
-    GKI_disable();
-    /* if timer list is currently empty, start periodic GKI timer */
-    if (btu_cb.timer_queue.p_first == NULL)
-    {
-        /* if timer starts on other than BTU task */
-        if (GKI_get_taskid() != BTU_TASK)
-        {
-            /* post event to start timer in BTU task */
-            if ((p_msg = (BT_HDR *)GKI_getbuf(BT_HDR_SIZE)) != NULL)
+static void btu_general_alarm_process(TIMER_LIST_ENT *p_tle) {
+    assert(p_tle != NULL);
+
+    switch (p_tle->event) {
+        case BTU_TTYPE_BTM_DEV_CTL:
+            btm_dev_timeout(p_tle);
+            break;
+
+        case BTU_TTYPE_L2CAP_LINK:
+        case BTU_TTYPE_L2CAP_CHNL:
+        case BTU_TTYPE_L2CAP_HOLD:
+        case BTU_TTYPE_L2CAP_INFO:
+        case BTU_TTYPE_L2CAP_FCR_ACK:
+            l2c_process_timeout (p_tle);
+            break;
+
+        case BTU_TTYPE_SDP:
+            sdp_conn_timeout ((tCONN_CB *)p_tle->param);
+            break;
+
+        case BTU_TTYPE_BTM_RMT_NAME:
+            btm_inq_rmt_name_failed();
+            break;
+
+        case BTU_TTYPE_RFCOMM_MFC:
+        case BTU_TTYPE_RFCOMM_PORT:
+            rfcomm_process_timeout (p_tle);
+            break;
+
+#if ((defined(BNEP_INCLUDED) && BNEP_INCLUDED == TRUE))
+        case BTU_TTYPE_BNEP:
+            bnep_process_timeout(p_tle);
+            break;
+#endif
+
+
+#if (defined(AVDT_INCLUDED) && AVDT_INCLUDED == TRUE)
+        case BTU_TTYPE_AVDT_CCB_RET:
+        case BTU_TTYPE_AVDT_CCB_RSP:
+        case BTU_TTYPE_AVDT_CCB_IDLE:
+        case BTU_TTYPE_AVDT_SCB_TC:
+            avdt_process_timeout(p_tle);
+            break;
+#endif
+
+#if (defined(HID_HOST_INCLUDED) && HID_HOST_INCLUDED == TRUE)
+        case BTU_TTYPE_HID_HOST_REPAGE_TO :
+            hidh_proc_repage_timeout(p_tle);
+            break;
+#endif
+
+#if (defined(BLE_INCLUDED) && BLE_INCLUDED == TRUE)
+        case BTU_TTYPE_BLE_INQUIRY:
+        case BTU_TTYPE_BLE_GAP_LIM_DISC:
+        case BTU_TTYPE_BLE_RANDOM_ADDR:
+        case BTU_TTYPE_BLE_GAP_FAST_ADV:
+        case BTU_TTYPE_BLE_OBSERVE:
+            btm_ble_timeout(p_tle);
+            break;
+
+        case BTU_TTYPE_ATT_WAIT_FOR_RSP:
+            gatt_rsp_timeout(p_tle);
+            break;
+
+        case BTU_TTYPE_ATT_WAIT_FOR_IND_ACK:
+            gatt_ind_ack_timeout(p_tle);
+            break;
+#if (defined(SMP_INCLUDED) && SMP_INCLUDED == TRUE)
+        case BTU_TTYPE_SMP_PAIRING_CMD:
+            smp_rsp_timeout(p_tle);
+            break;
+#endif
+
+#endif
+
+#if (MCA_INCLUDED == TRUE)
+        case BTU_TTYPE_MCA_CCB_RSP:
+            mca_process_timeout(p_tle);
+            break;
+#endif
+        case BTU_TTYPE_USER_FUNC:
             {
-                p_msg->event = BT_EVT_TO_START_TIMER;
-                GKI_send_msg (BTU_TASK, TASK_MBOX_0, p_msg);
+                tUSER_TIMEOUT_FUNC  *p_uf = (tUSER_TIMEOUT_FUNC *)p_tle->param;
+                (*p_uf)(p_tle);
             }
-        }
-        else
-        {
-            /* Start free running 1 second timer for list management */
-            GKI_start_timer (TIMER_0, GKI_SECS_TO_TICKS (1), TRUE);
-        }
+            break;
+
+        default:;
+                int i = 0;
+                BOOLEAN handled = FALSE;
+
+                for (; !handled && i < BTU_MAX_REG_TIMER; i++)
+                {
+                    if (btu_cb.timer_reg[i].timer_cb == NULL)
+                        continue;
+                    if (btu_cb.timer_reg[i].p_tle == p_tle)
+                    {
+                        btu_cb.timer_reg[i].timer_cb(p_tle);
+                        handled = TRUE;
+                    }
+                }
+                break;
     }
-
-    GKI_remove_from_timer_list (&btu_cb.timer_queue, p_tle);
-
-    p_tle->event = type;
-    p_tle->ticks = timeout;
-    p_tle->ticks_initial = timeout;
-
-    GKI_add_to_timer_list (&btu_cb.timer_queue, p_tle);
-    GKI_enable();
 }
 
-/*******************************************************************************
-**
-** Function         btu_remaining_time
-**
-** Description      Return amount of time to expire
-**
-** Returns          time in second
-**
-*******************************************************************************/
-UINT32 btu_remaining_time (TIMER_LIST_ENT *p_tle)
-{
-    return(GKI_get_remaining_ticks (&btu_cb.timer_queue, p_tle));
+void btu_general_alarm_cb(void *data) {
+  assert(data != NULL);
+  TIMER_LIST_ENT *p_tle = (TIMER_LIST_ENT *)data;
+
+  fixed_queue_enqueue(btu_general_alarm_queue, p_tle);
+}
+
+void btu_start_timer(TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout_sec) {
+  assert(p_tle != NULL);
+
+  // Get the alarm for the timer list entry.
+  pthread_mutex_lock(&btu_general_alarm_lock);
+  if (!hash_map_has_key(btu_general_alarm_hash_map, p_tle)) {
+    hash_map_set(btu_general_alarm_hash_map, p_tle, alarm_new());
+  }
+  pthread_mutex_unlock(&btu_general_alarm_lock);
+
+  alarm_t *alarm = hash_map_get(btu_general_alarm_hash_map, p_tle);
+  if (alarm == NULL) {
+    LOG_ERROR("%s Unable to create alarm", __func__);
+    return;
+  }
+  alarm_cancel(alarm);
+
+  p_tle->event = type;
+  // NOTE: This value is in seconds but stored in a ticks field.
+  p_tle->ticks = timeout_sec;
+  p_tle->in_use = TRUE;
+  alarm_set(alarm, (period_ms_t)(timeout_sec * 1000), btu_general_alarm_cb, (void *)p_tle);
 }
 
 /*******************************************************************************
@@ -701,31 +482,20 @@
 ** Returns          void
 **
 *******************************************************************************/
-void btu_stop_timer (TIMER_LIST_ENT *p_tle)
-{
-    BT_HDR *p_msg;
-    GKI_disable();
-    GKI_remove_from_timer_list (&btu_cb.timer_queue, p_tle);
+void btu_stop_timer(TIMER_LIST_ENT *p_tle) {
+  assert(p_tle != NULL);
 
-    /* if timer is stopped on other than BTU task */
-    if (GKI_get_taskid() != BTU_TASK)
-    {
-        /* post event to stop timer in BTU task */
-        if ((p_msg = (BT_HDR *)GKI_getbuf(BT_HDR_SIZE)) != NULL)
-        {
-            p_msg->event = BT_EVT_TO_STOP_TIMER;
-            GKI_send_msg (BTU_TASK, TASK_MBOX_0, p_msg);
-        }
-    }
-    else
-    {
-        /* if timer list is empty stop periodic GKI timer */
-        if (btu_cb.timer_queue.p_first == NULL)
-        {
-            GKI_stop_timer(TIMER_0);
-        }
-    }
-    GKI_enable();
+  if (p_tle->in_use == FALSE)
+    return;
+  p_tle->in_use = FALSE;
+
+  // Get the alarm for the timer list entry.
+  alarm_t *alarm = hash_map_get(btu_general_alarm_hash_map, p_tle);
+  if (alarm == NULL) {
+    LOG_WARN("%s Unable to find expected alarm in hashmap", __func__);
+    return;
+  }
+  alarm_cancel(alarm);
 }
 
 #if defined(QUICK_TIMER_TICKS_PER_SEC) && (QUICK_TIMER_TICKS_PER_SEC > 0)
@@ -733,47 +503,55 @@
 **
 ** Function         btu_start_quick_timer
 **
-** Description      Start a timer for the specified amount of time.
-**                  NOTE: The timeout resolution depends on including modules.
-**                  QUICK_TIMER_TICKS_PER_SEC should be used to convert from
-**                  time to ticks.
-**
+** Description      Start a timer for the specified amount of time in ticks.
 **
 ** Returns          void
 **
 *******************************************************************************/
-void btu_start_quick_timer (TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout)
-{
-    BT_HDR *p_msg;
+static void btu_l2cap_alarm_process(TIMER_LIST_ENT *p_tle) {
+  assert(p_tle != NULL);
 
-    GKI_disable();
-    /* if timer list is currently empty, start periodic GKI timer */
-    if (btu_cb.quick_timer_queue.p_first == NULL)
-    {
-        /* script test calls stack API without posting event */
-        if (GKI_get_taskid() != BTU_TASK)
-        {
-            /* post event to start timer in BTU task */
-            if ((p_msg = (BT_HDR *)GKI_getbuf(BT_HDR_SIZE)) != NULL)
-            {
-                p_msg->event = BT_EVT_TO_START_QUICK_TIMER;
-                GKI_send_msg (BTU_TASK, TASK_MBOX_0, p_msg);
-            }
-        }
-        else
-            GKI_start_timer(TIMER_2, QUICK_TIMER_TICKS, TRUE);
-    }
+  switch (p_tle->event) {
+    case BTU_TTYPE_L2CAP_CHNL:      /* monitor or retransmission timer */
+    case BTU_TTYPE_L2CAP_FCR_ACK:   /* ack timer */
+      l2c_process_timeout (p_tle);
+      break;
 
-    GKI_remove_from_timer_list (&btu_cb.quick_timer_queue, p_tle);
-
-    p_tle->event = type;
-    p_tle->ticks = timeout;
-    p_tle->ticks_initial = timeout;
-
-    GKI_add_to_timer_list (&btu_cb.quick_timer_queue, p_tle);
-    GKI_enable();
+    default:
+      break;
+  }
 }
 
+static void btu_l2cap_alarm_cb(void *data) {
+  assert(data != NULL);
+  TIMER_LIST_ENT *p_tle = (TIMER_LIST_ENT *)data;
+
+  fixed_queue_enqueue(btu_l2cap_alarm_queue, p_tle);
+}
+
+void btu_start_quick_timer(TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout_ticks) {
+  assert(p_tle != NULL);
+
+  // Get the alarm for the timer list entry.
+  pthread_mutex_lock(&btu_l2cap_alarm_lock);
+  if (!hash_map_has_key(btu_l2cap_alarm_hash_map, p_tle)) {
+    hash_map_set(btu_l2cap_alarm_hash_map, p_tle, alarm_new());
+  }
+  pthread_mutex_unlock(&btu_l2cap_alarm_lock);
+
+  alarm_t *alarm = hash_map_get(btu_l2cap_alarm_hash_map, p_tle);
+  if (alarm == NULL) {
+    LOG_ERROR("%s Unable to create alarm", __func__);
+    return;
+  }
+  alarm_cancel(alarm);
+
+  p_tle->event = type;
+  p_tle->ticks = timeout_ticks;
+  p_tle->in_use = TRUE;
+  // The quick timer ticks are 100ms long.
+  alarm_set(alarm, (period_ms_t)(timeout_ticks * 100), btu_l2cap_alarm_cb, (void *)p_tle);
+}
 
 /*******************************************************************************
 **
@@ -784,126 +562,73 @@
 ** Returns          void
 **
 *******************************************************************************/
-void btu_stop_quick_timer (TIMER_LIST_ENT *p_tle)
-{
-    GKI_disable();
-    GKI_remove_from_timer_list (&btu_cb.quick_timer_queue, p_tle);
+void btu_stop_quick_timer(TIMER_LIST_ENT *p_tle) {
+  assert(p_tle != NULL);
 
-    /* if timer list is empty stop periodic GKI timer */
-    if (btu_cb.quick_timer_queue.p_first == NULL)
-    {
-        GKI_stop_timer(TIMER_2);
-    }
-    GKI_enable();
-}
+  if (p_tle->in_use == FALSE)
+    return;
+  p_tle->in_use = FALSE;
 
-/*******************************************************************************
-**
-** Function         btu_process_quick_timer_evt
-**
-** Description      Process quick timer event
-**
-** Returns          void
-**
-*******************************************************************************/
-void btu_process_quick_timer_evt(void)
-{
-    process_quick_timer_evt(&btu_cb.quick_timer_queue);
-
-    /* if timer list is empty stop periodic GKI timer */
-    if (btu_cb.quick_timer_queue.p_first == NULL)
-    {
-        GKI_stop_timer(TIMER_2);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         process_quick_timer_evt
-**
-** Description      Process quick timer event
-**
-** Returns          void
-**
-*******************************************************************************/
-void process_quick_timer_evt(TIMER_LIST_Q *p_tlq)
-{
-    TIMER_LIST_ENT  *p_tle;
-
-    GKI_update_timer_list (p_tlq, 1);
-
-    while ((p_tlq->p_first) && (!p_tlq->p_first->ticks))
-    {
-        p_tle = p_tlq->p_first;
-        GKI_remove_from_timer_list (p_tlq, p_tle);
-
-        switch (p_tle->event)
-        {
-            case BTU_TTYPE_L2CAP_CHNL:      /* monitor or retransmission timer */
-            case BTU_TTYPE_L2CAP_FCR_ACK:   /* ack timer */
-                l2c_process_timeout (p_tle);
-                break;
-
-            default:
-                break;
-        }
-    }
+  // Get the alarm for the timer list entry.
+  alarm_t *alarm = hash_map_get(btu_l2cap_alarm_hash_map, p_tle);
+  if (alarm == NULL) {
+    LOG_WARN("%s Unable to find expected alarm in hashmap", __func__);
+    return;
+  }
+  alarm_cancel(alarm);
 }
 #endif /* defined(QUICK_TIMER_TICKS_PER_SEC) && (QUICK_TIMER_TICKS_PER_SEC > 0) */
 
+void btu_oneshot_alarm_cb(void *data) {
+  assert(data != NULL);
+  TIMER_LIST_ENT *p_tle = (TIMER_LIST_ENT *)data;
+
+  btu_stop_timer_oneshot(p_tle);
+
+  fixed_queue_enqueue(btu_oneshot_alarm_queue, p_tle);
+}
+
 /*
  * Starts a oneshot timer with a timeout in seconds.
  */
-void btu_start_timer_oneshot(TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout_in_secs) {
-    INT32 timeout_in_ticks = GKI_SECS_TO_TICKS(timeout_in_secs);
-    BTM_TRACE_DEBUG("Starting oneshot timer type:%d timeout:%ds", type, timeout_in_secs);
-    GKI_disable();
-    if (GKI_timer_queue_is_empty(&btu_cb.timer_queue_oneshot)) {
-    }
+void btu_start_timer_oneshot(TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout_sec) {
+  assert(p_tle != NULL);
 
-    GKI_remove_from_timer_list(&btu_cb.timer_queue_oneshot, p_tle);
+  // Get the alarm for the timer list entry.
+  pthread_mutex_lock(&btu_oneshot_alarm_lock);
+  if (!hash_map_has_key(btu_oneshot_alarm_hash_map, p_tle)) {
+    hash_map_set(btu_oneshot_alarm_hash_map, p_tle, alarm_new());
+  }
+  pthread_mutex_unlock(&btu_oneshot_alarm_lock);
 
-    p_tle->event = type;
-    p_tle->ticks = timeout_in_ticks;
-    p_tle->ticks_initial = timeout_in_ticks;
+  alarm_t *alarm = hash_map_get(btu_oneshot_alarm_hash_map, p_tle);
+  if (alarm == NULL) {
+    LOG_ERROR("%s Unable to create alarm", __func__);
+    return;
+  }
+  alarm_cancel(alarm);
 
-    GKI_add_to_timer_list(&btu_cb.timer_queue_oneshot, p_tle);
-    /* RPC to BTU thread if timer start request from non-BTU task */
-    if (GKI_get_taskid() != BTU_TASK) {
-        /* post event to start timer in BTU task */
-        BTM_TRACE_WARNING("Posting oneshot timer event to btu_task");
-        BT_HDR *p_msg = (BT_HDR *)GKI_getbuf(BT_HDR_SIZE);
-        if (p_msg != NULL) {
-            p_msg->event = BT_EVT_TO_START_TIMER_ONESHOT;
-            GKI_send_msg (BTU_TASK, TASK_MBOX_0, p_msg);
-        }
-    } else {
-        TIMER_LIST_ENT *tle = GKI_timer_getfirst(&btu_cb.timer_queue_oneshot);
-        GKI_start_timer(TIMER_3, tle->ticks, FALSE);
-    }
-    GKI_enable();
+  p_tle->event = type;
+  p_tle->in_use = TRUE;
+  // NOTE: This value is in seconds but stored in a ticks field.
+  p_tle->ticks = timeout_sec;
+  alarm_set(alarm, (period_ms_t)(timeout_sec * 1000), btu_oneshot_alarm_cb, (void *)p_tle);
 }
 
 void btu_stop_timer_oneshot(TIMER_LIST_ENT *p_tle) {
-    GKI_disable();
-    GKI_remove_from_timer_list(&btu_cb.timer_queue_oneshot, p_tle);
+  assert(p_tle != NULL);
 
-    if (GKI_get_taskid() != BTU_TASK) {
-        /* post event to stop timer in BTU task */
-        BT_HDR *p_msg = (BT_HDR *)GKI_getbuf(BT_HDR_SIZE);
-        if (p_msg != NULL) {
-            p_msg->event = BT_EVT_TO_STOP_TIMER_ONESHOT;
-            GKI_send_msg (BTU_TASK, TASK_MBOX_0, p_msg);
-        }
-    } else {
-        if (GKI_timer_queue_is_empty(&btu_cb.timer_queue_oneshot)) {
-            BTM_TRACE_WARNING("Stopping oneshot timer");
-            GKI_stop_timer(TIMER_3);
-        } else {
-            BTM_TRACE_WARNING("Request to stop oneshot timer with non empty queue");
-        }
-    }
-    GKI_enable();
+  if (p_tle->in_use == FALSE)
+    return;
+  p_tle->in_use = FALSE;
+
+  // Get the alarm for the timer list entry.
+  alarm_t *alarm = hash_map_get(btu_oneshot_alarm_hash_map, p_tle);
+  if (alarm == NULL) {
+    LOG_WARN("%s Unable to find expected alarm in hashmap", __func__);
+    return;
+  }
+  alarm_cancel(alarm);
 }
 
 #if (defined(HCILP_INCLUDED) && HCILP_INCLUDED == TRUE)
@@ -918,14 +643,10 @@
 *******************************************************************************/
 void btu_check_bt_sleep (void)
 {
-    if ((btu_cb.hci_cmd_cb[LOCAL_BR_EDR_CONTROLLER_ID].cmd_cmpl_q.count == 0)
-        &&(btu_cb.hci_cmd_cb[LOCAL_BR_EDR_CONTROLLER_ID].cmd_xmit_q.count == 0))
+    // TODO(zachoverflow) take pending commands into account?
+    if (l2cb.controller_xmit_window == l2cb.num_lm_acl_bufs)
     {
-        if (l2cb.controller_xmit_window == l2cb.num_lm_acl_bufs)
-        {
-            /* enable dev to sleep  in the cmd cplt and cmd status only and num cplt packet */
-            HCI_LP_ALLOW_BT_DEVICE_SLEEP();
-        }
+        bte_main_lpm_allow_bt_device_sleep();
     }
 }
 #endif
diff --git a/stack/gap/gap_api.c b/stack/gap/gap_api.c
index 530d141..a81efdc 100644
--- a/stack/gap/gap_api.c
+++ b/stack/gap/gap_api.c
@@ -21,831 +21,8 @@
 #include "bt_target.h"
 #include "bt_utils.h"
 #include "gap_int.h"
-#include "btm_int.h"
-#include "gki.h"
-#include "btu.h"
 
-/*******************************************************************************
-**
-** Function         GAP_SetDiscoverableMode
-**
-** Description      This function is called to allow or disallow a service to
-**                  discovered (Inquiry Scans).
-**
-** Parameters:      mode        - GAP_NON_DISCOVERABLE, GAP_LIMITED_DISCOVERABLE,
-**                                  or GAP_GENERAL_DISCOVERABLE
-**
-**                  duration    - Amount of time for the duration of an inquiry scan.
-**                                The step size is in 0.625 msec intervals.
-**                                Range: 0x0012 - 0x1000 (11.25 - 2560 msecs)
-**
-**                                If a value of '0' is entered the default of
-**                                0x0012 (11.25 msecs) will be used.
-**                                Note: The duration must be less than or equal to
-**                                the interval.
-**
-**                  interval    - Amount of time between the start of two inquiry scans.
-**                                The step size is in 0.625 msec intervals.
-**                                Range: 0x0012 - 0x1000 (11.25 - 2560 msecs)
-**                                If a value of '0' is entered the default of
-**                                0x800 (1.28 secs) will be used.
-**
-**
-** Returns          BT_PASS (0) if successful,
-**                  GAP_ERR_ILL_PARM if a bad parameter is detected,
-**                  GAP_DEVICE_NOT_UP if the device is not active,
-**                  GAP_ERR_PROCESSING if not enough resources to carry out request
-**
-*******************************************************************************/
-UINT16 GAP_SetDiscoverableMode (UINT16 mode, UINT16 duration, UINT16 interval)
-{
-    tBTM_STATUS status;
-
-    status = BTM_SetDiscoverability(mode, duration, interval);
-
-    return (gap_convert_btm_status (status));
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_ReadDiscoverableMode
-**
-** Description      This function is called to retrieve the current discoverable mode
-**                  for the local device.
-**
-** Parameters:      duration    - pointer to the amount of time of an inquiry scan.
-**                                The step size is in 0.625 msec intervals.
-**                                Range: 0x0012 - 0x1000 (11.25 - 2560 msecs)
-**
-**                  interval    - pointer to the amount of time between the start of
-**                                two inquiry scans.
-**                                The step size is in 0.625 msec intervals.
-**                                Range: 0x0012 - 0x1000 (11.25 - 2560 msecs)
-**
-**
-** Returns          GAP_NON_DISCOVERABLE, GAP_LIMITED_DISCOVERABLE, or
-**                  GAP_GENERAL_DISCOVERABLE
-**
-*******************************************************************************/
-UINT16 GAP_ReadDiscoverableMode (UINT16 *duration, UINT16 *interval)
-{
-    return (BTM_ReadDiscoverability(duration, interval));
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_SetConnectableMode
-**
-** Description      This function is called to allow or disallow a
-**                  connections on the local device.
-**
-** Parameters:      mode        - GAP_NON_CONNECTABLE, GAP_CONNECTABLE,
-**
-**                  duration    - Amount of time for the duration of a page scan.
-**                                The step size is in 0.625 msec intervals.
-**                                Range: 0x0012 - 0x1000 (11.25 - 2560 msecs)
-**
-**                                If a value of '0' is entered the default of
-**                                0x0012 (11.25 msecs) will be used.
-**                                Note: The duration must be less than or equal to
-**                                the interval.
-**
-**                  interval    - Amount of time between the start of two page scans.
-**                                The step size is in 0.625 msec intervals.
-**                                Range: 0x0012 - 0x1000 (11.25 - 2560 msecs)
-**                                If a value of '0' is entered the default of
-**                                0x800 (1.28 secs) will be used.
-**
-**
-** Returns          BT_PASS (0) if successful,
-**                  GAP_ERR_ILL_PARM if a bad parameter is detected,
-**                  GAP_DEVICE_NOT_UP if the device is not active,
-**                  GAP_ERR_PROCESSING if not enough resources to carry out request
-**
-*******************************************************************************/
-UINT16 GAP_SetConnectableMode (UINT16 mode, UINT16 duration, UINT16 interval)
-{
-    tBTM_STATUS status;
-
-    status = BTM_SetConnectability(mode, duration, interval);
-
-    return (gap_convert_btm_status (status));
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_FindAddrByName
-**
-** Description      This function is called to retrieve a device address given
-**                  a device name.  It first looks in the current local inquiry
-**                  database for the device with the specified name.  If not found
-**                  it initiates a general inquiry.  Upon completion, it retrieves
-**                  the name for each device until a match is found or all devices
-**                  have been checked.  Note:  This process can take a while to
-**                  complete.
-**
-** Parameters:      devname -
-**
-**                  inqparms - pointer to the inquiry information
-**                      mode - GAP_GENERAL_INQUIRY or GAP_LIMITED_INQUIRY inquiry
-**                      duration - length in 1.28 sec intervals
-**                      max_resps - maximum amount of devices to search for before ending the inquiry
-**                      filter_cond_type - GAP_CLR_INQUIRY_FILTER, GAP_FILTER_COND_DEVICE_CLASS, or
-**                                         GAP_FILTER_COND_BD_ADDR
-**                      filter_cond - value for the filter (based on filter_cond_type)
-**
-**
-** Returns          BT_PASS if the name was immediately available.  (BD_ADDR is returned)
-**                  GAP_CMD_INITIATED if an inquiry has been initiated
-**
-*******************************************************************************/
-UINT16 GAP_FindAddrByName (BD_NAME devname, tGAP_INQ_PARMS *p_inq_parms, tGAP_CALLBACK *p_addr_cb,
-                           BD_ADDR bd_addr)
-{
-    UINT16           status;
-    tBTM_STATUS      btm_status;
-
-
-    /* If the remote name is retrieved automatically during an inquiry search the local db first */
-    if ((status = gap_find_local_addr_by_name (devname, bd_addr)) != BT_PASS)
-    {
-        /* If this code is used, the name wasn't in the current inquiry database */
-        /* A general inquiry must now be initiated */
-        if (gap_cb.findaddr_cb.in_use == FALSE)
-        {
-            gap_cb.findaddr_cb.p_cback = p_addr_cb;
-            gap_cb.findaddr_cb.p_cur_inq = (tBTM_INQ_INFO *) NULL;     /* Reset to the beginning of the database */
-            BCM_STRNCPY_S ((char *)gap_cb.findaddr_cb.results.devname, sizeof(gap_cb.findaddr_cb.results.devname), (char *)devname, BTM_MAX_REM_BD_NAME_LEN);
-
-            /* make sure we have an end of string char */
-            gap_cb.findaddr_cb.results.devname[BTM_MAX_REM_BD_NAME_LEN] = 0;
-
-            btm_status = BTM_StartInquiry (p_inq_parms, (tBTM_INQ_RESULTS_CB *) NULL,
-                    (tBTM_CMPL_CB *) gap_find_addr_inq_cb);
-                gap_cb.findaddr_cb.in_use = TRUE;
-
-            /* convert the error code into a GAP code and check the results for any errors */
-            if ((status = gap_convert_btm_status (btm_status)) == GAP_CMD_INITIATED)
-                gap_cb.findaddr_cb.in_use = TRUE;
-        }
-        else
-            status = GAP_ERR_BUSY;
-    }
-
-    return (status);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_ReadConnectableMode
-**
-** Description      This function is called to retrieve the current connectability
-**                  mode for the local device.
-**
-** Parameters:      duration    - pointer to the amount of time of an page scan.
-**                                The step size is in 0.625 msec intervals.
-**                                Range: 0x0012 - 0x1000 (11.25 - 2560 msecs)
-**
-**                  interval    - pointer to the amount of time between the start of
-**                                two page scans.
-**                                The step size is in 0.625 msec intervals.
-**                                Range: 0x0012 - 0x1000 (11.25 - 2560 msecs)
-**
-**
-** Returns          GAP_NON_CONNECTABLE, GAP_CONNECTABLE
-**
-*******************************************************************************/
-
-UINT16 GAP_ReadConnectableMode (UINT16 *duration, UINT16 *interval)
-{
-    return (BTM_ReadConnectability(duration, interval));
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_SetSecurityMode
-**
-** Description      Set security mode for the device
-**
-** Returns          void
-**
-*******************************************************************************/
-void GAP_SetSecurityMode (UINT8 sec_mode)
-{
-    BTM_SetSecurityMode (sec_mode);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_Bond
-**
-** Description      This function is called to perform bonding with peer device
-**
-** Parameters:      bd_addr      - Address of the device to bond
-**                  pin_len      - length in bytes of the PIN Code
-**                  p_pin        - pointer to array with the PIN Code
-**                  trusted_mask - bitwise OR of trusted services (array of UINT32)
-**
-*******************************************************************************/
-UINT8 GAP_Bond (BD_ADDR bd_addr, UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[])
-{
-    return ((UINT8) BTM_SecBond (bd_addr, pin_len, p_pin, trusted_mask));
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_SecRegister
-**
-** Description      Application manager calls this function to register for
-**                  security services.  There can be one and only one application
-**                  saving link keys.  BTM allows only first registration.
-**
-** Returns          TRUE if registered OK, else FALSE
-**
-*******************************************************************************/
-BOOLEAN  GAP_SecRegister (tBTM_APPL_INFO *p_cb_info)
-{
-    return (BTM_SecRegister (p_cb_info));
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_PinRsp
-**
-** Description      This function is called from UI after Security Manager submitted
-**                  PIN code request.
-**
-** Parameters:      bd_addr      - Address of the device for which PIN was requested
-**                  res          - result of the operation BTM_SUCCESS if success
-**                  pin_len      - length in bytes of the PIN Code
-**                  p_pin        - pointer to array with the PIN Code
-**                  trusted_mask - bitwise OR of trusted services (array of UINT32)
-**
-*******************************************************************************/
-void GAP_PinRsp (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[])
-{
-    BTM_PINCodeReply (bd_addr, res, pin_len, p_pin, trusted_mask);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_AuthorizeRsp
-**
-** Description      This function is called from UI after Security Manager submitted
-**                  authorization request
-**
-** Parameters:      bd_addr      - Address of the device for which PIN was requested
-**                  res          - result of the operation BTM_SUCCESS if success
-**                  trusted_mask - bitwise OR of trusted services (array of UINT32)
-**
-*******************************************************************************/
-void GAP_AuthorizeRsp (BD_ADDR bd_addr, UINT8 res, UINT32 trusted_mask[])
-{
-    BTM_DeviceAuthorized (bd_addr, res, trusted_mask);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_SetPairableMode
-**
-** Description      This function is called to allow or disallow pairing
-**                  on the local device.
-**
-** Parameters:      mode        - GAP_ALLOW_PAIRING, GAP_DISALLOW_PAIRING
-**                  connect_only_pairable - TRUE or FALSE connect only to paired devices
-**
-**                  callback    - The callback is called when a pin number is requested.
-**
-** Returns          BT_PASS (0) if successful, or a non-zero error code
-**
-*******************************************************************************/
-
-UINT16 GAP_SetPairableMode (UINT16 mode, BOOLEAN connect_only_paired)
-{
-    tBTM_STATUS btm_status;
-    UINT16      status = BT_PASS;
-
-    if (mode == GAP_ALLOW_PAIRING)
-    {
-        btm_status = BTM_SetConnectability(BTM_CONNECTABLE, 0, 0);
-
-        if ((status = gap_convert_btm_status (btm_status)) == BT_PASS)
-            BTM_SetPairableMode (TRUE, connect_only_paired);
-    }
-    else if (mode == GAP_DISALLOW_PAIRING)
-    {
-        BTM_SetPairableMode (FALSE, connect_only_paired);
-    }
-    else
-    {
-        GAP_TRACE_ERROR ("GAP_SetPairableMode: illegal mode %d", mode);
-        status = GAP_ERR_ILL_MODE;
-    }
-    return (status);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_StartInquiry
-**
-** Description      This function initiates a single inquiry.
-**
-** Parameters:      p_inqparms - pointer to the inquiry information
-**                      mode - GAP_GENERAL_INQUIRY or GAP_LIMITED_INQUIRY inquiry
-**                      duration - length in 1.28 sec intervals
-**                      max_resps - maximum amount of devices to search for before ending the inquiry
-**                      filter_cond_type - GAP_CLR_INQUIRY_FILTER, GAP_FILTER_COND_DEVICE_CLASS, or
-**                                         GAP_FILTER_COND_BD_ADDR
-**                      filter_cond - value for the filter (based on filter_cond_type)
-**
-**                  p_results_cb - Pointer to the callback routine which gets called
-**                                 upon receipt of an inquiry result. If this field is
-**                                 NULL, the application is not notified.
-**
-**                  p_cmpl_cb   - Pointer to the callback routine which gets called
-**                                upon completion.  If this field is NULL, the
-**                                application is not notified when completed.
-**
-**
-** Returns          BT_PASS (0) if successful,
-**                  GAP_ERR_ILL_MODE if a bad mode parameter was passed
-**                  GAP_ERR_ILL_INQ_TIME if a bad interval or duration was passed
-**                  GAP_ERR_NO_CTRL_BLK if out of control blocks
-**                  GAP_ERR_ILL_PARM if a bad parameter was detected in BTM
-**                  GAP_ERR_BUSY if the device already has an iquiry active
-**                  GAP_DEVICE_NOT_UP if the device is not initialized yet
-**                  GAP_ERR_PROCESSING if any other BTM error was returned
-**
-*******************************************************************************/
-UINT16 GAP_StartInquiry (tGAP_INQ_PARMS *p_inq_parms, tGAP_CALLBACK *p_results_cb, tGAP_CALLBACK *p_cmpl_cb)
-{
-    tGAP_INFO   *p_cb;
-    tBTM_STATUS  btm_status;
-    UINT16       retval;
-
-    /*** Make sure the parameters are valid before continuing ***/
-    if (p_inq_parms->mode != GAP_GENERAL_INQUIRY && p_inq_parms->mode != GAP_LIMITED_INQUIRY)
-        return (GAP_ERR_ILL_MODE);
-
-    if (p_inq_parms->duration < GAP_MIN_INQUIRY_LEN   ||
-        p_inq_parms->duration > GAP_MAX_INQUIRY_LENGTH)
-        return (GAP_ERR_ILL_INQ_TIME);
-
-    /*** get a control block for this operation ***/
-    if ((p_cb = gap_allocate_cb()) != NULL)
-    {
-        p_cb->gap_cback = p_cmpl_cb;
-        p_cb->gap_inq_rslt_cback = p_results_cb;
-        p_cb->event = GAP_EVT_INQUIRY_COMPLETE; /* Return event expected */
-
-        btm_status = BTM_StartInquiry(p_inq_parms, gap_inq_results_cb,
-                        (tBTM_CMPL_CB *) gap_cb.btm_cback[p_cb->index]);
-
-        /* convert the error code into a GAP code and check the results for any errors */
-        if ((retval = gap_convert_btm_status (btm_status)) != GAP_CMD_INITIATED)
-            gap_free_cb(p_cb);      /* Error starting the inquiry */
-    }
-    else
-        retval = GAP_ERR_NO_CTRL_BLK;
-
-    return (retval);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_StartPeriodicInquiry
-**
-** Description      This function initiates a periodic inquiry.
-**
-** Parameters:      p_inqparms - pointer to the inquiry information
-**                      mode - GAP_GENERAL_INQUIRY or GAP_LIMITED_INQUIRY inquiry
-**                      duration - length in 1.28 sec intervals
-**                      max_resps - maximum amount of devices to search for before ending the inquiry
-**                      filter_cond_type - GAP_CLR_INQUIRY_FILTER, GAP_FILTER_COND_DEVICE_CLASS, or
-**                                         GAP_FILTER_COND_BD_ADDR
-**                      filter_cond - value for the filter (based on filter_cond_type)
-**
-**                  min_time    - Minimum amount of time between consecutive inquiries.
-**                                The value is in 1.28 second intervals.
-**                                Range: 0x0002 - 0xFFFE (2.56 - 83883.52 seconds)
-**
-**                  max_time    - Maximum amount of time between consecutive inquiries.
-**                                The value is in 1.28 sec intervals.
-**                                Range: 0x0003 - 0xFFFF (3.84 - 83884.8 seconds)
-**
-**                  p_results_cb - Pointer to the callback routine which gets called
-**                                 upon receipt of an inquiry result. If this field is
-**                                 NULL, the application is not notified.
-**
-**
-** Returns          BT_PASS (0) if successful,
-**                  GAP_ERR_ILL_MODE if a bad mode parameter was passed
-**                  GAP_ERR_ILL_INQ_TIME if a bad interval or duration was passed
-**                  GAP_ERR_NO_CTRL_BLK if out of control blocks
-**                  GAP_ERR_ILL_PARM if a bad parameter was detected in BTM
-**                  GAP_ERR_BUSY if the device already has an iquiry active
-**                  GAP_DEVICE_NOT_UP if the device is not initialized yet
-**                  GAP_ERR_PROCESSING if any other BTM error was returned
-**
-*******************************************************************************/
-
-UINT16 GAP_StartPeriodicInquiry (tGAP_INQ_PARMS *p_inq_parms, UINT16 min_time,
-                                 UINT16 max_time, tGAP_CALLBACK *p_results_cb)
-{
-    tGAP_INFO   *p_cb;
-    tBTM_STATUS  btm_status;
-    UINT16       retval = BT_PASS;
-
-    /*** Make sure the parameters are valid before continuing ***/
-    if (p_inq_parms->mode != GAP_GENERAL_INQUIRY && p_inq_parms->mode != GAP_LIMITED_INQUIRY)
-        return (GAP_ERR_ILL_MODE);
-
-    if (p_inq_parms->duration < GAP_MIN_INQUIRY_LEN     ||
-        p_inq_parms->duration > GAP_MAX_INQUIRY_LENGTH  ||
-        min_time <= p_inq_parms->duration               ||
-        min_time < GAP_PER_INQ_MIN_MIN_PERIOD           ||
-        min_time > GAP_PER_INQ_MAX_MIN_PERIOD           ||
-        max_time <= min_time                            ||
-        max_time < GAP_PER_INQ_MIN_MAX_PERIOD)
-    {
-        return (GAP_ERR_ILL_INQ_TIME);
-    }
-
-    /*** get a control block for this operation ***/
-    if ((p_cb = gap_allocate_cb()) != NULL)
-    {
-        p_cb->gap_inq_rslt_cback = p_results_cb;
-        p_cb->event = GAP_EVT_INQUIRY_COMPLETE; /* mark the inquiry event active */
-
-        btm_status = BTM_SetPeriodicInquiryMode(p_inq_parms, max_time, min_time,
-                                                gap_inq_results_cb);
-
-        /* convert the error code into a GAP code and check the results for any errors */
-        if ((retval = gap_convert_btm_status (btm_status)) != GAP_CMD_INITIATED)
-            gap_free_cb(p_cb);      /* Error starting the inquiry */
-    }
-    else
-        retval = GAP_ERR_NO_CTRL_BLK;
-
-    return (retval);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_CancelInquiry
-**
-** Description      This function cancels a single inquiry (if in progress)
-**
-** Parameters:      None
-**
-** Returns          BOOLEAN (TRUE if successful, otherwise FALSE)
-**
-*******************************************************************************/
-UINT16 GAP_CancelInquiry(void)
-{
-    tGAP_INFO   *p_cb = &gap_cb.blk[0];
-    UINT8        x;
-    tBTM_STATUS  btm_status;
-    UINT16       status;
-
-    btm_status = BTM_CancelInquiry();
-    if ((status = gap_convert_btm_status (btm_status)) == BT_PASS)
-    {
-        /* Free the control block that is waiting for the inquiry complete event */
-        for (x = 0; x < GAP_MAX_BLOCKS; x++, p_cb++)
-        {
-            if (p_cb->in_use && p_cb->event == GAP_EVT_INQUIRY_COMPLETE)
-            {
-                gap_free_cb(p_cb);
-                return (BT_PASS);
-            }
-        }
-
-        /* If here the control block was not found */
-        status = GAP_ERR_NO_CTRL_BLK;
-    }
-
-    return (status);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_CancelPeriodicInquiry
-**
-** Description      This function cancels a periodic inquiry (if in progress)
-**
-** Parameters:      None
-**
-** Returns          BOOLEAN: (TRUE if successful, otherwise FALSE)
-**
-*******************************************************************************/
-UINT16 GAP_CancelPeriodicInquiry(void)
-{
-    tGAP_INFO   *p_cb = &gap_cb.blk[0];
-    UINT8        x;
-    tBTM_STATUS  btm_status;
-    UINT16       status;
-
-    btm_status = BTM_CancelPeriodicInquiry();
-    if ((status = gap_convert_btm_status (btm_status)) == BT_PASS)
-    {
-        /* Free the control block that is waiting for the inquiry complete event */
-        for (x = 0; x < GAP_MAX_BLOCKS; x++, p_cb++)
-        {
-            if (p_cb->in_use && p_cb->event == GAP_EVT_INQUIRY_COMPLETE)
-            {
-                gap_free_cb(p_cb);
-                return (BT_PASS);
-            }
-        }
-
-        /* If here the control block was not found */
-        status = GAP_ERR_NO_CTRL_BLK;
-    }
-
-    return (status);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_GetFirstInquiryResult
-**
-** Description      This function retrieves the first valid inquiry result.
-**
-** Parameters:      p_results - pointer to the inquiry results
-**
-** Returns          BT_PASS (0) if successful, or a non-zero error code
-**                  GAP_EOINQDB if no more entries in the database.
-**
-*******************************************************************************/
-UINT16 GAP_GetFirstInquiryResult(tGAP_INQ_RESULTS *p_results)
-{
-    UINT8 *ptr;
-
-    gap_cb.cur_inqptr = BTM_InqFirstResult();
-
-    if (gap_cb.cur_inqptr != NULL)
-    {
-        memcpy(p_results, &gap_cb.cur_inqptr->results, sizeof(tBTM_INQ_RESULTS));
-
-        ptr = (UINT8 *)gap_cb.cur_inqptr->results.remote_bd_addr;
-        GAP_TRACE_EVENT("GAP_GetFirstInqResult %02x%02x%02x%02x%02x%02x",
-                    ptr[0],ptr[1],ptr[2],ptr[3],ptr[4],ptr[5]);
-        return(BT_PASS);
-    }
-    else
-    {
-        GAP_TRACE_EVENT("GAP_FirstInqResults:  No BD_ADDRs Found");
-        memset(p_results, 0, sizeof(tBTM_INQ_RESULTS));
-        return(GAP_EOINQDB);
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_GetNextInquiryResult
-**
-** Description      This function retrieves the next valid inquiry result.
-**
-** Parameters:      p_results  - pointer to the inquiry results
-**
-** Returns          BT_PASS (0) if successful, or a non-zero status code
-**                  GAP_EOINQDB if no more entries in the database.
-**
-*******************************************************************************/
-UINT16 GAP_GetNextInquiryResult(tGAP_INQ_RESULTS *p_results)
-{
-    UINT8 *ptr;
-
-    /*** if the current inquiry db pointer is NULL then call the first entry ***/
-    if (gap_cb.cur_inqptr)
-    {
-        gap_cb.cur_inqptr = BTM_InqNextResult(gap_cb.cur_inqptr);
-        if (gap_cb.cur_inqptr != NULL)
-        {
-            memcpy(p_results, &gap_cb.cur_inqptr->results,
-                   sizeof(tGAP_INQ_RESULTS));
-
-            ptr = (UINT8 *)gap_cb.cur_inqptr->results.remote_bd_addr;
-            GAP_TRACE_EVENT("GAP_GetNextInqResult %02x%02x%02x%02x%02x%02x",
-                        ptr[0],ptr[1],ptr[2],ptr[3],ptr[4],ptr[5]);
-
-            return(BT_PASS);
-        }
-        else
-        {
-            GAP_TRACE_EVENT("GAP_NextInqResults:  No BD_ADDRs Found");
-            memset(p_results, 0, sizeof(tBTM_INQ_RESULTS));
-            return(GAP_EOINQDB);
-        }
-    }
-    else
-        return (GAP_GetFirstInquiryResult(p_results));
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_ReadLocalDeviceInfo
-**
-** Description      This function retrieves local device information to the caller.
-**
-** Parameters:      name        - (output) pointer to the UTF-8 encoded string representing
-**                                the device name.
-**
-**                  addr        - (output) pointer to the Bluetooth device address (BD_ADDR).
-**
-**                  verinfo     - (output) pointer to the LMP version information.
-**
-**                  features    - (output) pointer to the LMP features for the device.
-**
-**                  NOTE:  Return parameters that are set to NULL are not retrieved.
-**
-** Returns          BT_PASS (0) if successful, or a non-zero error code
-**
-*******************************************************************************/
-
-UINT16 GAP_ReadLocalDeviceInfo(UINT8 *name, BD_ADDR *addr, tGAP_LMP_VERSION *verinfo,
-                               tGAP_LMP_FEATURES *features)
-{
-    UNUSED(name);
-    UNUSED(addr);
-    UNUSED(verinfo);
-    UNUSED(features);
-    return (GAP_UNSUPPORTED);
-}
-
-
-
-/*******************************************************************************
-**
-** Function         GAP_GetRemoteDeviceName
-**
-** Description      The remote name is retrieved from the specified remote device.  If
-**                  GAP_CMD_INITIATED is returned by the function, the command was
-**                  successfully sent to the controller.  The GAP_EVT_NAME_RESP event
-**                  is passed in the callback when the remote device name has been retrieved.
-**
-** Parameters:      addr        - The Bluetooth device address (BD_ADDR) of the remote
-**                                device.
-**
-**                  callback    - pointer to the callback which is called after the
-**                                remote device has been retrieved.
-**                                p_data in the callback points to the structure containing the
-**                                status, device name length, and the UTF-8 encoded
-**                                device name. (type tBTM_REMOTE_DEV_NAME)
-**                                The event field in the callback is set to GAP_EVT_REM_NAME_COMPLETE.
-**  The callback is not called unless (GAP_CMD_INITIATED) is returned.
-**
-**
-** Returns
-**                  GAP_CMD_INITIATED if remote search successfully initiated
-**                  GAP_ERR_BUSY if a remote name request is already in progress,
-**                  GAP_ERR_NO_CTRL_BLK if out of control blocks (too many commands pending)
-**                  GAP_BAD_BD_ADDR if the device address is bad,
-**                  GAP_DEVICE_NOT_UP if the device has not been initialized yet
-**                  GAP_ERR_PROCESSING if any other BTM error has been returned
-**
-*******************************************************************************/
-UINT16 GAP_GetRemoteDeviceName (BD_ADDR addr, tGAP_CALLBACK *callback)
-{
-    tGAP_INFO   *p_cb;
-    UINT16       retval;
-    tBTM_STATUS  btm_status;
-
-    if ((p_cb = gap_allocate_cb()) != NULL)
-    {
-        p_cb->gap_cback = callback;
-        p_cb->event = GAP_EVT_REM_NAME_COMPLETE;     /* Return event expected */
-
-        btm_status = BTM_ReadRemoteDeviceName (addr, gap_cb.btm_cback[p_cb->index], BT_TRANSPORT_BR_EDR);
-
-        /* If the name was not returned immediately, or if an error occurred, release the control block */
-        if ((retval = gap_convert_btm_status (btm_status)) != GAP_CMD_INITIATED)
-            gap_free_cb (p_cb);
-    }
-    else
-        retval = GAP_ERR_NO_CTRL_BLK;
-
-    return (retval);
-}
-
-/*******************************************************************************
-**
-** Function         GAP_SetDeviceClass
-**
-** Description      This function updates the local Device Class.
-**
-** Parameters:
-**                  p_cod   - Pointer to the device class to set to
-**
-**                  cmd     - the fields of the device class to update.
-**                            GAP_SET_COD_MAJOR_MINOR, - overwrite major, minor class
-**                            GAP_SET_COD_SERVICE_CLASS - set the bits in the input
-**                            GAP_CLR_COD_SERVICE_CLASS - clear the bits in the input
-**                            GAP_SET_COD_ALL - overwrite major, minor, set the bits in service class
-**                            GAP_INIT_COD - overwrite major, minor, and service class
-**
-** Returns          BT_PASS (0) if successful,
-**                  GAP_ERR_BUSY if a discovery is already in progress
-**                  GAP_ERR_ILL_PARM if an illegal parameter was detected
-**                  GAP_ERR_PROCESSING if any other BTM error has been returned
-**
-*******************************************************************************/
-UINT16 GAP_SetDeviceClass(tGAP_COD *p_cod, UINT8 cmd)
-{
-    tBTM_STATUS btm_status;
-    UINT8 *dev;
-    UINT16 service;
-    UINT8  minor, major;
-    DEV_CLASS dev_class;
-
-    dev = BTM_ReadDeviceClass();
-    BTM_COD_SERVICE_CLASS( service, dev );
-    BTM_COD_MINOR_CLASS(minor, dev );
-    BTM_COD_MAJOR_CLASS(major, dev );
-
-    switch(cmd)
-    {
-    case GAP_SET_COD_MAJOR_MINOR:
-        minor = p_cod->minor & BTM_COD_MINOR_CLASS_MASK;
-        major = p_cod->major & BTM_COD_MAJOR_CLASS_MASK;
-        break;
-
-    case GAP_SET_COD_SERVICE_CLASS:
-        /* clear out the bits that is not SERVICE_CLASS bits */
-        p_cod->service &= BTM_COD_SERVICE_CLASS_MASK;
-        service = service | p_cod->service;
-        break;
-
-    case GAP_CLR_COD_SERVICE_CLASS:
-        p_cod->service &= BTM_COD_SERVICE_CLASS_MASK;
-        service = service & (~p_cod->service);
-        break;
-
-    case GAP_SET_COD_ALL:
-        minor = p_cod->minor & BTM_COD_MINOR_CLASS_MASK;
-        major = p_cod->major & BTM_COD_MAJOR_CLASS_MASK;
-        p_cod->service &= BTM_COD_SERVICE_CLASS_MASK;
-        service = service | p_cod->service;
-        break;
-
-    case GAP_INIT_COD:
-        minor = p_cod->minor & BTM_COD_MINOR_CLASS_MASK;
-        major = p_cod->major & BTM_COD_MAJOR_CLASS_MASK;
-        service = p_cod->service & BTM_COD_SERVICE_CLASS_MASK;
-        break;
-
-    default:
-        return GAP_ERR_ILL_PARM;
-    }
-
-    /* convert the fields into the device class type */
-    FIELDS_TO_COD(dev_class, minor, major, service);
-
-    btm_status = BTM_SetDeviceClass(dev_class);
-    return (gap_convert_btm_status (btm_status));
-}
-
-/*******************************************************************************
-**
-** Function         GAP_ReadDeviceClass
-**
-** Description      This function reads the local Device Class.
-**
-** Parameters:
-**
-** Returns          PASS
-**
-*******************************************************************************/
-UINT16   GAP_ReadDeviceClass(tGAP_COD *p_cod)
-{
-    UINT8 *dev;
-
-    dev = BTM_ReadDeviceClass();
-
-    BTM_COD_SERVICE_CLASS( p_cod->service, dev );
-    BTM_COD_MINOR_CLASS( p_cod->minor, dev );
-    BTM_COD_MAJOR_CLASS( p_cod->major, dev );
-
-    return (BT_PASS);
-}
+tGAP_CB  gap_cb;
 
 /*******************************************************************************
 **
@@ -881,26 +58,12 @@
 {
     memset (&gap_cb, 0, sizeof (tGAP_CB));
 
-    /*** Initialize the callbacks for BTM; Needs to be one per GAP_MAX_BLOCKS ***/
-    gap_cb.btm_cback[0] = gap_btm_cback0;
-#if GAP_MAX_BLOCKS > 1
-    gap_cb.btm_cback[1] = gap_btm_cback1;
-#endif
-#if GAP_MAX_BLOCKS > 2
-    gap_cb.btm_cback[2] = gap_btm_cback2;
-#endif
-
 #if defined(GAP_INITIAL_TRACE_LEVEL)
     gap_cb.trace_level = GAP_INITIAL_TRACE_LEVEL;
 #else
     gap_cb.trace_level = BT_TRACE_LEVEL_NONE;    /* No traces */
 #endif
 
-    /* Initialize the connection control block if included in build */
-#if GAP_CONN_INCLUDED == TRUE
-    gap_conn_init();
-#endif  /* GAP_CONN_INCLUDED */
-
 #if BLE_INCLUDED == TRUE
     gap_attr_db_init();
 #endif
diff --git a/stack/gap/gap_conn.c b/stack/gap/gap_conn.c
deleted file mode 100644
index 6bab72d..0000000
--- a/stack/gap/gap_conn.c
+++ /dev/null
@@ -1,1271 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2013 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-
-#include "bt_target.h"
-#include "bt_utils.h"
-#include "btu.h"
-#include "gap_int.h"
-#include "l2cdefs.h"
-#include "l2c_int.h"
-#include <string.h>
-#if GAP_CONN_INCLUDED == TRUE
-#include "btm_int.h"
-
-/********************************************************************************/
-/*              L O C A L    F U N C T I O N     P R O T O T Y P E S            */
-/********************************************************************************/
-static void gap_connect_ind (BD_ADDR  bd_addr, UINT16 l2cap_cid, UINT16 psm, UINT8 l2cap_id);
-static void gap_connect_cfm (UINT16 l2cap_cid, UINT16 result);
-static void gap_config_ind (UINT16 l2cap_cid, tL2CAP_CFG_INFO *p_cfg);
-static void gap_config_cfm (UINT16 l2cap_cid, tL2CAP_CFG_INFO *p_cfg);
-static void gap_disconnect_ind (UINT16 l2cap_cid, BOOLEAN ack_needed);
-static void gap_data_ind (UINT16 l2cap_cid, BT_HDR *p_msg);
-static void gap_congestion_ind (UINT16 lcid, BOOLEAN is_congested);
-
-static tGAP_CCB *gap_find_ccb_by_cid (UINT16 cid);
-static tGAP_CCB *gap_find_ccb_by_handle (UINT16 handle);
-static tGAP_CCB *gap_allocate_ccb (void);
-static void      gap_release_ccb (tGAP_CCB *p_ccb);
-
-/*******************************************************************************
-**
-** Function         gap_conn_init
-**
-** Description      This function is called to initialize GAP connection management
-**
-** Returns          void
-**
-*******************************************************************************/
-void gap_conn_init (void)
-{
-#if AMP_INCLUDED == TRUE
-    gap_cb.conn.reg_info.pAMP_ConnectInd_Cb         = gap_connect_ind;
-    gap_cb.conn.reg_info.pAMP_ConnectCfm_Cb         = gap_connect_cfm;
-    gap_cb.conn.reg_info.pAMP_ConnectPnd_Cb         = NULL;
-    gap_cb.conn.reg_info.pAMP_ConfigInd_Cb          = gap_config_ind;
-    gap_cb.conn.reg_info.pAMP_ConfigCfm_Cb          = gap_config_cfm;
-    gap_cb.conn.reg_info.pAMP_DisconnectInd_Cb      = gap_disconnect_ind;
-    gap_cb.conn.reg_info.pAMP_DisconnectCfm_Cb      = NULL;
-    gap_cb.conn.reg_info.pAMP_QoSViolationInd_Cb    = NULL;
-    gap_cb.conn.reg_info.pAMP_DataInd_Cb            = gap_data_ind;
-    gap_cb.conn.reg_info.pAMP_CongestionStatus_Cb   = gap_congestion_ind;
-    gap_cb.conn.reg_info.pAMP_TxComplete_Cb         = NULL;
-    gap_cb.conn.reg_info.pAMP_MoveInd_Cb            = NULL;
-    gap_cb.conn.reg_info.pAMP_MoveRsp_Cb            = NULL;
-    gap_cb.conn.reg_info.pAMP_MoveCfm_Cb            = NULL; //gap_move_cfm
-    gap_cb.conn.reg_info.pAMP_MoveCfmRsp_Cb         = NULL; //gap_move_cfm_rsp
-
-#else
-    gap_cb.conn.reg_info.pL2CA_ConnectInd_Cb       = gap_connect_ind;
-    gap_cb.conn.reg_info.pL2CA_ConnectCfm_Cb       = gap_connect_cfm;
-    gap_cb.conn.reg_info.pL2CA_ConnectPnd_Cb       = NULL;
-    gap_cb.conn.reg_info.pL2CA_ConfigInd_Cb        = gap_config_ind;
-    gap_cb.conn.reg_info.pL2CA_ConfigCfm_Cb        = gap_config_cfm;
-    gap_cb.conn.reg_info.pL2CA_DisconnectInd_Cb    = gap_disconnect_ind;
-    gap_cb.conn.reg_info.pL2CA_DisconnectCfm_Cb    = NULL;
-    gap_cb.conn.reg_info.pL2CA_QoSViolationInd_Cb  = NULL;
-    gap_cb.conn.reg_info.pL2CA_DataInd_Cb          = gap_data_ind;
-    gap_cb.conn.reg_info.pL2CA_CongestionStatus_Cb = gap_congestion_ind;
-    gap_cb.conn.reg_info.pL2CA_TxComplete_Cb       = NULL;
-#endif
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_ConnOpen
-**
-** Description      This function is called to open an L2CAP connection.
-**
-** Parameters:      is_server   - If TRUE, the connection is not created
-**                                but put into a "listen" mode waiting for
-**                                the remote side to connect.
-**
-**                  service_id  - Unique service ID from
-**                                BTM_SEC_SERVICE_FIRST_EMPTY (6)
-**                                to BTM_SEC_MAX_SERVICE_RECORDS (32)
-**
-**                  p_rem_bda   - Pointer to remote BD Address.
-**                                If a server, and we don't care about the
-**                                remote BD Address, then NULL should be passed.
-**
-**                  psm         - the PSM used for the connection
-**
-**                  p_config    - Optional pointer to configuration structure.
-**                                If NULL, the default GAP configuration will
-**                                be used.
-**
-**                  security    - security flags
-**                  chan_mode_mask - (GAP_FCR_CHAN_OPT_BASIC, GAP_FCR_CHAN_OPT_ERTM, GAP_FCR_CHAN_OPT_STREAM)
-**
-**                  p_cb        - Pointer to callback function for events.
-**
-** Returns          handle of the connection if successful, else GAP_INVALID_HANDLE
-**
-*******************************************************************************/
-UINT16 GAP_ConnOpen (char *p_serv_name, UINT8 service_id, BOOLEAN is_server,
-                     BD_ADDR p_rem_bda, UINT16 psm, tL2CAP_CFG_INFO *p_cfg,
-                     UINT16 security, UINT8 chan_mode_mask, tGAP_CONN_CALLBACK *p_cb)
-{
-    tGAP_CCB    *p_ccb;
-    UINT16       cid;
-
-    GAP_TRACE_EVENT ("GAP_CONN - Open Request");
-
-    /* Allocate a new CCB. Return if none available. */
-    if ((p_ccb = gap_allocate_ccb()) == NULL)
-        return (GAP_INVALID_HANDLE);
-
-    /* If caller specified a BD address, save it */
-    if (p_rem_bda)
-    {
-        /* the bd addr is not BT_BD_ANY, then a bd address was specified */
-        if (memcmp (p_rem_bda, BT_BD_ANY, BD_ADDR_LEN))
-            p_ccb->rem_addr_specified = TRUE;
-
-        memcpy (&p_ccb->rem_dev_address[0], p_rem_bda, BD_ADDR_LEN);
-    }
-    else if (!is_server)
-    {
-        /* remore addr is not specified and is not a server -> bad */
-        return (GAP_INVALID_HANDLE);
-    }
-
-    /* A client MUST have specified a bd addr to connect with */
-    if (!p_ccb->rem_addr_specified && !is_server)
-    {
-        gap_release_ccb (p_ccb);
-        GAP_TRACE_ERROR ("GAP ERROR: Client must specify a remote BD ADDR to connect to!");
-        return (GAP_INVALID_HANDLE);
-    }
-
-    /* Check if configuration was specified */
-    if (p_cfg)
-        p_ccb->cfg = *p_cfg;
-
-    p_ccb->p_callback     = p_cb;
-
-    /* If originator, use a dynamic PSM */
-#if AMP_INCLUDED == TRUE
-    if (!is_server)
-        gap_cb.conn.reg_info.pAMP_ConnectInd_Cb  = NULL;
-    else
-        gap_cb.conn.reg_info.pAMP_ConnectInd_Cb  = gap_connect_ind;
-#else
-    if (!is_server)
-        gap_cb.conn.reg_info.pL2CA_ConnectInd_Cb = NULL;
-    else
-        gap_cb.conn.reg_info.pL2CA_ConnectInd_Cb = gap_connect_ind;
-#endif
-
-    /* Register the PSM with L2CAP */
-    if ((p_ccb->psm = L2CA_REGISTER (psm, &gap_cb.conn.reg_info, AMP_AUTOSWITCH_ALLOWED|AMP_USE_AMP_IF_POSSIBLE)) == 0)
-    {
-        GAP_TRACE_ERROR ("GAP_ConnOpen: Failure registering PSM 0x%04x", psm);
-        gap_release_ccb (p_ccb);
-        return (GAP_INVALID_HANDLE);
-    }
-
-    /* Register with Security Manager for the specific security level */
-    p_ccb->service_id = service_id;
-    if (!BTM_SetSecurityLevel ((UINT8)!is_server, p_serv_name, p_ccb->service_id, security, p_ccb->psm, 0, 0))
-    {
-        GAP_TRACE_ERROR ("GAP_CONN - Security Error");
-        gap_release_ccb (p_ccb);
-        return (GAP_INVALID_HANDLE);
-    }
-
-    /* Fill in eL2CAP parameter data */
-    if( p_ccb->cfg.fcr_present )
-    {
-        p_ccb->ertm_info.preferred_mode = p_ccb->cfg.fcr.mode;
-        p_ccb->ertm_info.user_rx_pool_id = GAP_DATA_POOL_ID;
-        p_ccb->ertm_info.user_tx_pool_id = GAP_DATA_POOL_ID;
-        p_ccb->ertm_info.fcr_rx_pool_id = L2CAP_DEFAULT_ERM_POOL_ID;
-        p_ccb->ertm_info.fcr_tx_pool_id = L2CAP_DEFAULT_ERM_POOL_ID;
-    }
-
-    /* optional FCR channel modes */
-    p_ccb->ertm_info.allowed_modes = (chan_mode_mask) ? chan_mode_mask : (UINT8)L2CAP_FCR_CHAN_OPT_BASIC;
-
-    if (is_server)
-    {
-        p_ccb->con_flags |= GAP_CCB_FLAGS_SEC_DONE; /* assume btm/l2cap would handle it */
-        p_ccb->con_state = GAP_CCB_STATE_LISTENING;
-        return (p_ccb->gap_handle);
-    }
-    else
-    {
-        /* We are the originator of this connection */
-        p_ccb->con_flags = GAP_CCB_FLAGS_IS_ORIG;
-
-        /* Transition to the next appropriate state, waiting for connection confirm. */
-        p_ccb->con_state = GAP_CCB_STATE_CONN_SETUP;
-
-        /* mark security done flag, when security is not required */
-        if ((security & (BTM_SEC_OUT_AUTHORIZE | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT) ) == 0)
-            p_ccb->con_flags |= GAP_CCB_FLAGS_SEC_DONE;
-
-        /* Check if L2CAP started the connection process */
-        if (p_rem_bda && ((cid = L2CA_CONNECT_REQ (p_ccb->psm, p_rem_bda, &p_ccb->ertm_info, &bt_uuid)) != 0))
-        {
-            p_ccb->connection_id = cid;
-            return (p_ccb->gap_handle);
-        }
-        else
-        {
-            gap_release_ccb (p_ccb);
-            return (GAP_INVALID_HANDLE);
-        }
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_ConnClose
-**
-** Description      This function is called to close a connection.
-**
-** Parameters:      handle      - Handle of the connection returned by GAP_ConnOpen
-**
-** Returns          BT_PASS             - closed OK
-**                  GAP_ERR_BAD_HANDLE  - invalid handle
-**
-*******************************************************************************/
-UINT16 GAP_ConnClose (UINT16 gap_handle)
-{
-    tGAP_CCB    *p_ccb = gap_find_ccb_by_handle (gap_handle);
-
-    GAP_TRACE_EVENT ("GAP_CONN - close  handle: 0x%x", gap_handle);
-
-    if (p_ccb)
-    {
-        /* Check if we have a connection ID */
-        if (p_ccb->con_state != GAP_CCB_STATE_LISTENING)
-            L2CA_DISCONNECT_REQ (p_ccb->connection_id);
-
-        gap_release_ccb (p_ccb);
-
-        return (BT_PASS);
-    }
-
-    return (GAP_ERR_BAD_HANDLE);
-}
-
-
-
-/*******************************************************************************
-**
-** Function         GAP_ConnReadData
-**
-** Description      Normally not GKI aware application will call this function
-**                  after receiving GAP_EVT_RXDATA event.
-**
-** Parameters:      handle      - Handle of the connection returned in the Open
-**                  p_data      - Data area
-**                  max_len     - Byte count requested
-**                  p_len       - Byte count received
-**
-** Returns          BT_PASS             - data read
-**                  GAP_ERR_BAD_HANDLE  - invalid handle
-**                  GAP_NO_DATA_AVAIL   - no data available
-**
-*******************************************************************************/
-UINT16 GAP_ConnReadData (UINT16 gap_handle, UINT8 *p_data, UINT16 max_len, UINT16 *p_len)
-{
-    tGAP_CCB    *p_ccb = gap_find_ccb_by_handle (gap_handle);
-    BT_HDR     *p_buf;
-    UINT16      copy_len;
-
-    if (!p_ccb)
-        return (GAP_ERR_BAD_HANDLE);
-
-    *p_len = 0;
-
-    p_buf = (BT_HDR *)GKI_getfirst (&p_ccb->rx_queue);
-    if (!p_buf)
-        return (GAP_NO_DATA_AVAIL);
-
-    GKI_disable();
-
-    while (max_len && p_buf)
-    {
-        copy_len = (p_buf->len > max_len)?max_len:p_buf->len;
-        max_len -= copy_len;
-        *p_len  += copy_len;
-        if (p_data)
-        {
-            memcpy (p_data, (UINT8 *)(p_buf + 1) + p_buf->offset, copy_len);
-            p_data += copy_len;
-        }
-
-        if (p_buf->len > copy_len)
-        {
-            p_buf->offset += copy_len;
-            p_buf->len    -= copy_len;
-            break;
-        }
-        else
-        {
-            if (max_len)
-            {
-                p_buf = (BT_HDR *)GKI_getnext (p_buf);
-            }
-            GKI_freebuf (GKI_dequeue (&p_ccb->rx_queue));
-        }
-    }
-
-    p_ccb->rx_queue_size -= *p_len;
-
-    GKI_enable();
-
-    GAP_TRACE_EVENT ("GAP_ConnReadData - rx_queue_size left=%d, *p_len=%d",
-                                       p_ccb->rx_queue_size, *p_len);
-
-    return (BT_PASS);
-}
-
-/*******************************************************************************
-**
-** Function         GAP_GetRxQueueCnt
-**
-** Description      This function return number of bytes on the rx queue.
-**
-** Parameters:      handle     - Handle returned in the GAP_ConnOpen
-**                  p_rx_queue_count - Pointer to return queue count in.
-**
-**
-*******************************************************************************/
-int GAP_GetRxQueueCnt (UINT16 handle, UINT32 *p_rx_queue_count)
-{
-    tGAP_CCB    *p_ccb;
-    int         rc = BT_PASS;
-
-    /* Check that handle is valid */
-    if (handle < GAP_MAX_CONNECTIONS)
-    {
-        p_ccb = &gap_cb.conn.ccb_pool[handle];
-
-        if (p_ccb->con_state == GAP_CCB_STATE_CONNECTED)
-        {
-            *p_rx_queue_count = p_ccb->rx_queue_size;
-        }
-        else
-            rc = GAP_INVALID_HANDLE;
-    }
-    else
-        rc = GAP_INVALID_HANDLE;
-
-    GAP_TRACE_EVENT ("GAP_GetRxQueueCnt - rc = 0x%04x, rx_queue_count=%d",
-                                       rc , *p_rx_queue_count);
-
-    return (rc);
-}
-
-/*******************************************************************************
-**
-** Function         GAP_ConnBTRead
-**
-** Description      Bluetooth aware applications will call this function after receiving
-**                  GAP_EVT_RXDATA event.
-**
-** Parameters:      handle      - Handle of the connection returned in the Open
-**                  pp_buf      - pointer to address of buffer with data,
-**
-** Returns          BT_PASS             - data read
-**                  GAP_ERR_BAD_HANDLE  - invalid handle
-**                  GAP_NO_DATA_AVAIL   - no data available
-**
-*******************************************************************************/
-UINT16 GAP_ConnBTRead (UINT16 gap_handle, BT_HDR **pp_buf)
-{
-    tGAP_CCB    *p_ccb = gap_find_ccb_by_handle (gap_handle);
-    BT_HDR      *p_buf;
-
-    if (!p_ccb)
-        return (GAP_ERR_BAD_HANDLE);
-
-    p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->rx_queue);
-
-    if (p_buf)
-    {
-        *pp_buf = p_buf;
-
-        p_ccb->rx_queue_size -= p_buf->len;
-        return (BT_PASS);
-    }
-    else
-    {
-        *pp_buf = NULL;
-        return (GAP_NO_DATA_AVAIL);
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_ConnBTWrite
-**
-** Description      Bluetooth Aware applications can call this function to write data.
-**
-** Parameters:      handle      - Handle of the connection returned in the Open
-**                  p_buf      - pointer to address of buffer with data,
-**
-** Returns          BT_PASS                 - data read
-**                  GAP_ERR_BAD_HANDLE      - invalid handle
-**                  GAP_ERR_BAD_STATE       - connection not established
-**                  GAP_INVALID_BUF_OFFSET  - buffer offset is invalid
-*******************************************************************************/
-UINT16 GAP_ConnBTWrite (UINT16 gap_handle, BT_HDR *p_buf)
-{
-    tGAP_CCB    *p_ccb = gap_find_ccb_by_handle (gap_handle);
-
-    if (!p_ccb)
-    {
-        GKI_freebuf (p_buf);
-        return (GAP_ERR_BAD_HANDLE);
-    }
-
-    if (p_ccb->con_state != GAP_CCB_STATE_CONNECTED)
-    {
-        GKI_freebuf (p_buf);
-        return (GAP_ERR_BAD_STATE);
-    }
-
-    if (p_buf->offset < L2CAP_MIN_OFFSET)
-    {
-        GKI_freebuf (p_buf);
-        return (GAP_ERR_BUF_OFFSET);
-    }
-
-    GKI_enqueue (&p_ccb->tx_queue, p_buf);
-
-    if (p_ccb->is_congested)
-    {
-        return (BT_PASS);
-    }
-
-    /* Send the buffer through L2CAP */
-#if (GAP_CONN_POST_EVT_INCLUDED == TRUE)
-    gap_send_event (gap_handle);
-#else
-    while ((p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->tx_queue)) != NULL)
-    {
-        UINT8 status = L2CA_DATA_WRITE (p_ccb->connection_id, p_buf);
-
-        if (status == L2CAP_DW_CONGESTED)
-        {
-            p_ccb->is_congested = TRUE;
-            break;
-        }
-        else if (status != L2CAP_DW_SUCCESS)
-            return (GAP_ERR_BAD_STATE);
-    }
-#endif
-    return (BT_PASS);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_ConnWriteData
-**
-** Description      Normally not GKI aware application will call this function
-**                  to send data to the connection.
-**
-** Parameters:      handle      - Handle of the connection returned in the Open
-**                  p_data      - Data area
-**                  max_len     - Byte count requested
-**                  p_len       - Byte count received
-**
-** Returns          BT_PASS                 - data read
-**                  GAP_ERR_BAD_HANDLE      - invalid handle
-**                  GAP_ERR_BAD_STATE       - connection not established
-**                  GAP_CONGESTION          - system is congested
-**
-*******************************************************************************/
-UINT16 GAP_ConnWriteData (UINT16 gap_handle, UINT8 *p_data, UINT16 max_len, UINT16 *p_len)
-{
-    tGAP_CCB    *p_ccb = gap_find_ccb_by_handle (gap_handle);
-    BT_HDR     *p_buf;
-
-    *p_len = 0;
-
-    if (!p_ccb)
-        return (GAP_ERR_BAD_HANDLE);
-
-    if (p_ccb->con_state != GAP_CCB_STATE_CONNECTED)
-        return (GAP_ERR_BAD_STATE);
-
-    while (max_len)
-    {
-        if (p_ccb->cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
-        {
-            if ((p_buf = (BT_HDR *)GKI_getpoolbuf (p_ccb->ertm_info.user_tx_pool_id)) == NULL)
-                return (GAP_ERR_CONGESTED);
-        }
-        else
-        {
-            if ((p_buf = (BT_HDR *)GKI_getpoolbuf (GAP_DATA_POOL_ID)) == NULL)
-                return (GAP_ERR_CONGESTED);
-        }
-
-        p_buf->offset = L2CAP_MIN_OFFSET;
-        p_buf->len = (p_ccb->rem_mtu_size < max_len) ? p_ccb->rem_mtu_size : max_len;
-        p_buf->event = BT_EVT_TO_BTU_SP_DATA;
-
-        memcpy ((UINT8 *)(p_buf + 1) + p_buf->offset, p_data, p_buf->len);
-
-        *p_len  += p_buf->len;
-        max_len -= p_buf->len;
-        p_data  += p_buf->len;
-
-        GAP_TRACE_EVENT ("GAP_WriteData %d bytes", p_buf->len);
-
-        GKI_enqueue (&p_ccb->tx_queue, p_buf);
-    }
-
-    if (p_ccb->is_congested)
-    {
-        return (BT_PASS);
-    }
-
-    /* Send the buffer through L2CAP */
-#if (GAP_CONN_POST_EVT_INCLUDED == TRUE)
-    gap_send_event (gap_handle);
-#else
-    while ((p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->tx_queue)) != NULL)
-    {
-        UINT8 status = L2CA_DATA_WRITE (p_ccb->connection_id, p_buf);
-
-        if (status == L2CAP_DW_CONGESTED)
-        {
-            p_ccb->is_congested = TRUE;
-            break;
-        }
-        else if (status != L2CAP_DW_SUCCESS)
-            return (GAP_ERR_BAD_STATE);
-    }
-#endif
-    return (BT_PASS);
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_ConnReconfig
-**
-** Description      Applications can call this function to reconfigure the connection.
-**
-** Parameters:      handle      - Handle of the connection
-**                  p_cfg       - Pointer to new configuration
-**
-** Returns          BT_PASS                 - config process started
-**                  GAP_ERR_BAD_HANDLE      - invalid handle
-**
-*******************************************************************************/
-UINT16 GAP_ConnReconfig (UINT16 gap_handle, tL2CAP_CFG_INFO *p_cfg)
-{
-    tGAP_CCB    *p_ccb = gap_find_ccb_by_handle (gap_handle);
-
-    if (!p_ccb)
-        return (GAP_ERR_BAD_HANDLE);
-
-    p_ccb->cfg = *p_cfg;
-
-    if (p_ccb->con_state == GAP_CCB_STATE_CONNECTED)
-        L2CA_CONFIG_REQ (p_ccb->connection_id, p_cfg);
-
-    return (BT_PASS);
-}
-
-
-
-/*******************************************************************************
-**
-** Function         GAP_ConnSetIdleTimeout
-**
-** Description      Higher layers call this function to set the idle timeout for
-**                  a connection, or for all future connections. The "idle timeout"
-**                  is the amount of time that a connection can remain up with
-**                  no L2CAP channels on it. A timeout of zero means that the
-**                  connection will be torn down immediately when the last channel
-**                  is removed. A timeout of 0xFFFF means no timeout. Values are
-**                  in seconds.
-**
-** Parameters:      handle      - Handle of the connection
-**                  timeout     - in secs
-**                                0 = immediate disconnect when last channel is removed
-**                                0xFFFF = no idle timeout
-**
-** Returns          BT_PASS                 - config process started
-**                  GAP_ERR_BAD_HANDLE      - invalid handle
-**
-*******************************************************************************/
-UINT16 GAP_ConnSetIdleTimeout (UINT16 gap_handle, UINT16 timeout)
-{
-    tGAP_CCB    *p_ccb;
-
-    if ((p_ccb = gap_find_ccb_by_handle (gap_handle)) == NULL)
-        return (GAP_ERR_BAD_HANDLE);
-
-    if (L2CA_SetIdleTimeout (p_ccb->connection_id, timeout, FALSE))
-        return (BT_PASS);
-    else
-        return (GAP_ERR_BAD_HANDLE);
-}
-
-
-
-/*******************************************************************************
-**
-** Function         GAP_ConnGetRemoteAddr
-**
-** Description      This function is called to get the remote BD address
-**                  of a connection.
-**
-** Parameters:      handle      - Handle of the connection returned by GAP_ConnOpen
-**
-** Returns          BT_PASS             - closed OK
-**                  GAP_ERR_BAD_HANDLE  - invalid handle
-**
-*******************************************************************************/
-UINT8 *GAP_ConnGetRemoteAddr (UINT16 gap_handle)
-{
-    tGAP_CCB    *p_ccb = gap_find_ccb_by_handle (gap_handle);
-
-    GAP_TRACE_EVENT ("GAP_ConnGetRemoteAddr gap_handle = %d", gap_handle);
-
-    if ((p_ccb) && (p_ccb->con_state > GAP_CCB_STATE_LISTENING))
-    {
-        GAP_TRACE_EVENT("GAP_ConnGetRemoteAddr bda :0x%02x:0x%02x:0x%02x:0x%02x:0x%02x:0x%02x\n", \
-                         p_ccb->rem_dev_address[0],p_ccb->rem_dev_address[1],p_ccb->rem_dev_address[2],
-                         p_ccb->rem_dev_address[3],p_ccb->rem_dev_address[4],p_ccb->rem_dev_address[5]);
-        return (p_ccb->rem_dev_address);
-    }
-    else
-    {
-        GAP_TRACE_EVENT ("GAP_ConnGetRemoteAddr return Error ");
-        return (NULL);
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         GAP_ConnGetRemMtuSize
-**
-** Description      Returns the remote device's MTU size
-**
-** Parameters:      handle      - Handle of the connection
-**
-** Returns          UINT16      - maximum size buffer that can be transmitted to the peer
-**
-*******************************************************************************/
-UINT16 GAP_ConnGetRemMtuSize (UINT16 gap_handle)
-{
-    tGAP_CCB    *p_ccb;
-
-    if ((p_ccb = gap_find_ccb_by_handle (gap_handle)) == NULL)
-        return (0);
-
-    return (p_ccb->rem_mtu_size);
-}
-
-/*******************************************************************************
-**
-** Function         GAP_ConnGetL2CAPCid
-**
-** Description      Returns the L2CAP channel id
-**
-** Parameters:      handle      - Handle of the connection
-**
-** Returns          UINT16      - The L2CAP channel id
-**                  0, if error
-**
-*******************************************************************************/
-UINT16 GAP_ConnGetL2CAPCid (UINT16 gap_handle)
-{
-    tGAP_CCB    *p_ccb;
-
-    if ((p_ccb = gap_find_ccb_by_handle (gap_handle)) == NULL)
-        return (0);
-
-    return (p_ccb->connection_id);
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_connect_ind
-**
-** Description      This function handles an inbound connection indication
-**                  from L2CAP. This is the case where we are acting as a
-**                  server.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void gap_connect_ind (BD_ADDR  bd_addr, UINT16 l2cap_cid, UINT16 psm, UINT8 l2cap_id)
-{
-    UINT16       xx;
-    tGAP_CCB     *p_ccb;
-
-    /* See if we have a CCB listening for the connection */
-    for (xx = 0, p_ccb = gap_cb.conn.ccb_pool; xx < GAP_MAX_CONNECTIONS; xx++, p_ccb++)
-    {
-        if ((p_ccb->con_state == GAP_CCB_STATE_LISTENING)
-         && (p_ccb->psm == psm)
-         && ((p_ccb->rem_addr_specified == FALSE)
-           || (!memcmp (bd_addr, p_ccb->rem_dev_address, BD_ADDR_LEN))))
-            break;
-    }
-
-    if (xx == GAP_MAX_CONNECTIONS)
-    {
-        GAP_TRACE_WARNING("*******");
-        GAP_TRACE_WARNING("WARNING: GAP Conn Indication for Unexpected Bd Addr...Disconnecting");
-        GAP_TRACE_WARNING("*******");
-
-        /* Disconnect because it is an unexpected connection */
-        L2CA_DISCONNECT_REQ (l2cap_cid);
-        return;
-    }
-
-    /* Transition to the next appropriate state, waiting for config setup. */
-    p_ccb->con_state = GAP_CCB_STATE_CFG_SETUP;
-
-    /* Save the BD Address and Channel ID. */
-    memcpy (&p_ccb->rem_dev_address[0], bd_addr, BD_ADDR_LEN);
-    p_ccb->connection_id = l2cap_cid;
-
-    /* Send response to the L2CAP layer. */
-    L2CA_CONNECT_RSP (bd_addr, l2cap_id, l2cap_cid, L2CAP_CONN_OK, L2CAP_CONN_OK, &p_ccb->ertm_info, &bt_uuid);
-
-    GAP_TRACE_EVENT("GAP_CONN - Rcvd L2CAP conn ind, CID: 0x%x", p_ccb->connection_id);
-
-    /* Send a Configuration Request. */
-    L2CA_CONFIG_REQ (l2cap_cid, &p_ccb->cfg);
-}
-
-/*******************************************************************************
-**
-** Function         gap_checks_con_flags
-**
-** Description      This function processes the L2CAP configuration indication
-**                  event.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void gap_checks_con_flags (tGAP_CCB    *p_ccb)
-{
-    GAP_TRACE_EVENT ("gap_checks_con_flags conn_flags:0x%x, ", p_ccb->con_flags);
-    /* if all the required con_flags are set, report the OPEN event now */
-    if ((p_ccb->con_flags & GAP_CCB_FLAGS_CONN_DONE) == GAP_CCB_FLAGS_CONN_DONE)
-    {
-        p_ccb->con_state = GAP_CCB_STATE_CONNECTED;
-
-        p_ccb->p_callback (p_ccb->gap_handle, GAP_EVT_CONN_OPENED);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         gap_sec_check_complete
-**
-** Description      The function called when Security Manager finishes
-**                  verification of the service side connection
-**
-** Returns          void
-**
-*******************************************************************************/
-static void gap_sec_check_complete (BD_ADDR bd_addr, tBT_TRANSPORT transport, void *p_ref_data, UINT8 res)
-{
-    tGAP_CCB *p_ccb = (tGAP_CCB *)p_ref_data;
-    UNUSED(bd_addr);
-    UNUSED (transport);
-
-    GAP_TRACE_EVENT ("gap_sec_check_complete conn_state:%d, conn_flags:0x%x, status:%d",
-        p_ccb->con_state, p_ccb->con_flags, res);
-    if (p_ccb->con_state == GAP_CCB_STATE_IDLE)
-        return;
-
-    if (res == BTM_SUCCESS)
-    {
-        p_ccb->con_flags |= GAP_CCB_FLAGS_SEC_DONE;
-        gap_checks_con_flags (p_ccb);
-    }
-    else
-    {
-        /* security failed - disconnect the channel */
-        L2CA_DISCONNECT_REQ (p_ccb->connection_id);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         gap_connect_cfm
-**
-** Description      This function handles the connect confirm events
-**                  from L2CAP. This is the case when we are acting as a
-**                  client and have sent a connect request.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void gap_connect_cfm (UINT16 l2cap_cid, UINT16 result)
-{
-    tGAP_CCB    *p_ccb;
-
-    /* Find CCB based on CID */
-    if ((p_ccb = gap_find_ccb_by_cid (l2cap_cid)) == NULL)
-        return;
-
-    /* initiate security process, if needed */
-    if ( (p_ccb->con_flags & GAP_CCB_FLAGS_SEC_DONE) == 0)
-    {
-        btm_sec_mx_access_request (p_ccb->rem_dev_address, p_ccb->psm, TRUE,
-                                   0, 0, &gap_sec_check_complete, p_ccb);
-    }
-
-    /* If the connection response contains success status, then */
-    /* Transition to the next state and startup the timer.      */
-    if ((result == L2CAP_CONN_OK) && (p_ccb->con_state == GAP_CCB_STATE_CONN_SETUP))
-    {
-        p_ccb->con_state = GAP_CCB_STATE_CFG_SETUP;
-
-        /* Send a Configuration Request. */
-        L2CA_CONFIG_REQ (l2cap_cid, &p_ccb->cfg);
-    }
-    else
-    {
-        /* Tell the user if he has a callback */
-        if (p_ccb->p_callback)
-            (*p_ccb->p_callback) (p_ccb->gap_handle, GAP_EVT_CONN_CLOSED);
-
-        gap_release_ccb (p_ccb);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         gap_config_ind
-**
-** Description      This function processes the L2CAP configuration indication
-**                  event.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void gap_config_ind (UINT16 l2cap_cid, tL2CAP_CFG_INFO *p_cfg)
-{
-    tGAP_CCB    *p_ccb;
-    UINT16      local_mtu_size;
-
-    /* Find CCB based on CID */
-    if ((p_ccb = gap_find_ccb_by_cid (l2cap_cid)) == NULL)
-        return;
-
-    /* Remember the remote MTU size */
-
-    if (p_ccb->cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
-    {
-        local_mtu_size = GKI_get_pool_bufsize (p_ccb->ertm_info.user_tx_pool_id)
-                       - sizeof(BT_HDR) - L2CAP_MIN_OFFSET;
-    }
-    else
-        local_mtu_size = L2CAP_MTU_SIZE;
-
-    if ((!p_cfg->mtu_present)||(p_cfg->mtu > local_mtu_size))
-    {
-        p_ccb->rem_mtu_size = local_mtu_size;
-    }
-    else
-        p_ccb->rem_mtu_size = p_cfg->mtu;
-
-    /* For now, always accept configuration from the other side */
-    p_cfg->flush_to_present = FALSE;
-    p_cfg->mtu_present      = FALSE;
-    p_cfg->result           = L2CAP_CFG_OK;
-    p_cfg->fcs_present      = FALSE;
-
-    L2CA_CONFIG_RSP (l2cap_cid, p_cfg);
-
-    p_ccb->con_flags |= GAP_CCB_FLAGS_HIS_CFG_DONE;
-
-    gap_checks_con_flags (p_ccb);
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_config_cfm
-**
-** Description      This function processes the L2CAP configuration confirmation
-**                  event.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void gap_config_cfm (UINT16 l2cap_cid, tL2CAP_CFG_INFO *p_cfg)
-{
-    tGAP_CCB    *p_ccb;
-
-    /* Find CCB based on CID */
-    if ((p_ccb = gap_find_ccb_by_cid (l2cap_cid)) == NULL)
-        return;
-
-    if (p_cfg->result == L2CAP_CFG_OK)
-    {
-        p_ccb->con_flags |= GAP_CCB_FLAGS_MY_CFG_DONE;
-
-
-        if (p_ccb->cfg.fcr_present)
-            p_ccb->cfg.fcr.mode = p_cfg->fcr.mode;
-        else
-            p_ccb->cfg.fcr.mode = L2CAP_FCR_BASIC_MODE;
-
-        gap_checks_con_flags (p_ccb);
-    }
-    else
-    {
-        p_ccb->p_callback (p_ccb->gap_handle, GAP_EVT_CONN_CLOSED);
-        gap_release_ccb (p_ccb);
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_disconnect_ind
-**
-** Description      This function handles a disconnect event from L2CAP. If
-**                  requested to, we ack the disconnect before dropping the CCB
-**
-** Returns          void
-**
-*******************************************************************************/
-static void gap_disconnect_ind (UINT16 l2cap_cid, BOOLEAN ack_needed)
-{
-    tGAP_CCB    *p_ccb;
-
-    GAP_TRACE_EVENT ("GAP_CONN - Rcvd L2CAP disc, CID: 0x%x", l2cap_cid);
-
-    /* Find CCB based on CID */
-    if ((p_ccb = gap_find_ccb_by_cid (l2cap_cid)) == NULL)
-        return;
-
-    if (ack_needed)
-        L2CA_DISCONNECT_RSP (l2cap_cid);
-
-    p_ccb->p_callback (p_ccb->gap_handle, GAP_EVT_CONN_CLOSED);
-    gap_release_ccb (p_ccb);
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_data_ind
-**
-** Description      This function is called when data is received from L2CAP.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void gap_data_ind (UINT16 l2cap_cid, BT_HDR *p_msg)
-{
-    tGAP_CCB    *p_ccb;
-
-    /* Find CCB based on CID */
-    if ((p_ccb = gap_find_ccb_by_cid (l2cap_cid)) == NULL)
-    {
-        GKI_freebuf (p_msg);
-        return;
-    }
-
-    if (p_ccb->con_state == GAP_CCB_STATE_CONNECTED)
-    {
-        GKI_enqueue (&p_ccb->rx_queue, p_msg);
-
-        p_ccb->rx_queue_size += p_msg->len;
-        /*
-        GAP_TRACE_EVENT ("gap_data_ind - rx_queue_size=%d, msg len=%d",
-                                       p_ccb->rx_queue_size, p_msg->len);
-         */
-
-        p_ccb->p_callback (p_ccb->gap_handle, GAP_EVT_CONN_DATA_AVAIL);
-    }
-    else
-    {
-        GKI_freebuf (p_msg);
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_congestion_ind
-**
-** Description      This is a callback function called by L2CAP when
-**                  data L2CAP congestion status changes
-**
-*******************************************************************************/
-static void gap_congestion_ind (UINT16 lcid, BOOLEAN is_congested)
-{
-    tGAP_CCB    *p_ccb;
-    UINT16       event;
-    BT_HDR      *p_buf;
-    UINT8        status;
-
-    GAP_TRACE_EVENT ("GAP_CONN - Rcvd L2CAP Is Congested (%d), CID: 0x%x",
-                      is_congested, lcid);
-
-    /* Find CCB based on CID */
-    if ((p_ccb = gap_find_ccb_by_cid (lcid)) == NULL)
-        return;
-
-    p_ccb->is_congested = is_congested;
-
-    event = (is_congested) ? GAP_EVT_CONN_CONGESTED : GAP_EVT_CONN_UNCONGESTED;
-    p_ccb->p_callback (p_ccb->gap_handle, event);
-
-    if (!is_congested)
-    {
-        while ((p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->tx_queue)) != NULL)
-        {
-            status = L2CA_DATA_WRITE (p_ccb->connection_id, p_buf);
-
-            if (status == L2CAP_DW_CONGESTED)
-            {
-                p_ccb->is_congested = TRUE;
-                break;
-            }
-            else if (status != L2CAP_DW_SUCCESS)
-                break;
-        }
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_find_ccb_by_cid
-**
-** Description      This function searches the CCB table for an entry with the
-**                  passed CID.
-**
-** Returns          the CCB address, or NULL if not found.
-**
-*******************************************************************************/
-static tGAP_CCB *gap_find_ccb_by_cid (UINT16 cid)
-{
-    UINT16       xx;
-    tGAP_CCB     *p_ccb;
-
-    /* Look through each connection control block */
-    for (xx = 0, p_ccb = gap_cb.conn.ccb_pool; xx < GAP_MAX_CONNECTIONS; xx++, p_ccb++)
-    {
-        if ((p_ccb->con_state != GAP_CCB_STATE_IDLE) && (p_ccb->connection_id == cid))
-            return (p_ccb);
-    }
-
-    /* If here, not found */
-    return (NULL);
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_find_ccb_by_handle
-**
-** Description      This function searches the CCB table for an entry with the
-**                  passed handle.
-**
-** Returns          the CCB address, or NULL if not found.
-**
-*******************************************************************************/
-static tGAP_CCB *gap_find_ccb_by_handle (UINT16 handle)
-{
-    tGAP_CCB     *p_ccb;
-
-    /* Check that handle is valid */
-    if (handle < GAP_MAX_CONNECTIONS)
-    {
-        p_ccb = &gap_cb.conn.ccb_pool[handle];
-
-        if (p_ccb->con_state != GAP_CCB_STATE_IDLE)
-            return (p_ccb);
-    }
-
-    /* If here, handle points to invalid connection */
-    return (NULL);
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_allocate_ccb
-**
-** Description      This function allocates a new CCB.
-**
-** Returns          CCB address, or NULL if none available.
-**
-*******************************************************************************/
-static tGAP_CCB *gap_allocate_ccb (void)
-{
-    UINT16       xx;
-    tGAP_CCB     *p_ccb;
-
-    /* Look through each connection control block for a free one */
-    for (xx = 0, p_ccb = gap_cb.conn.ccb_pool; xx < GAP_MAX_CONNECTIONS; xx++, p_ccb++)
-    {
-        if (p_ccb->con_state == GAP_CCB_STATE_IDLE)
-        {
-            memset (p_ccb, 0, sizeof (tGAP_CCB));
-
-            p_ccb->gap_handle   = xx;
-            p_ccb->rem_mtu_size = L2CAP_MTU_SIZE;
-
-            return (p_ccb);
-        }
-    }
-
-    /* If here, no free CCB found */
-    return (NULL);
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_release_ccb
-**
-** Description      This function releases a CCB.
-**
-** Returns          void
-**
-*******************************************************************************/
-static void gap_release_ccb (tGAP_CCB *p_ccb)
-{
-    UINT16       xx;
-    UINT16      psm = p_ccb->psm;
-    UINT8       service_id = p_ccb->service_id;
-
-    /* Drop any buffers we may be holding */
-    p_ccb->rx_queue_size = 0;
-
-    while (p_ccb->rx_queue.p_first)
-        GKI_freebuf (GKI_dequeue (&p_ccb->rx_queue));
-
-    while (p_ccb->tx_queue.p_first)
-        GKI_freebuf (GKI_dequeue (&p_ccb->tx_queue));
-
-    p_ccb->con_state = GAP_CCB_STATE_IDLE;
-
-    /* If no-one else is using the PSM, deregister from L2CAP */
-    for (xx = 0, p_ccb = gap_cb.conn.ccb_pool; xx < GAP_MAX_CONNECTIONS; xx++, p_ccb++)
-    {
-        if ((p_ccb->con_state != GAP_CCB_STATE_IDLE) && (p_ccb->psm == psm))
-            return;
-    }
-
-    /* Free the security record for this PSM */
-    BTM_SecClrService(service_id);
-    L2CA_DEREGISTER (psm);
-}
-
-#if (GAP_CONN_POST_EVT_INCLUDED == TRUE)
-
-/*******************************************************************************
-**
-** Function     gap_send_event
-**
-** Description  Send BT_EVT_TO_GAP_MSG event to BTU task
-**
-** Returns      None
-**
-*******************************************************************************/
-void gap_send_event (UINT16 gap_handle)
-{
-    BT_HDR  *p_msg;
-
-    if ((p_msg = (BT_HDR*)GKI_getbuf(BT_HDR_SIZE)) != NULL)
-    {
-        p_msg->event  = BT_EVT_TO_GAP_MSG;
-        p_msg->len    = 0;
-        p_msg->offset = 0;
-        p_msg->layer_specific = gap_handle;
-
-        GKI_send_msg(BTU_TASK, BTU_HCI_RCV_MBOX, p_msg);
-    }
-    else
-    {
-        GAP_TRACE_ERROR("Unable to allocate message buffer for event.");
-    }
-}
-
-/*******************************************************************************
-**
-** Function     gap_proc_btu_event
-**
-** Description  Event handler for BT_EVT_TO_GAP_MSG event from BTU task
-**
-** Returns      None
-**
-*******************************************************************************/
-void gap_proc_btu_event(BT_HDR *p_msg)
-{
-    tGAP_CCB   *p_ccb = gap_find_ccb_by_handle (p_msg->layer_specific);
-    UINT8       status;
-    BT_HDR     *p_buf;
-
-    if (!p_ccb)
-    {
-        return;
-    }
-
-    if (p_ccb->con_state != GAP_CCB_STATE_CONNECTED)
-    {
-        return;
-    }
-
-    if (p_ccb->is_congested)
-    {
-        return;
-    }
-
-    /* Send the buffer through L2CAP */
-
-    while ((p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->tx_queue)) != NULL)
-    {
-        status = L2CA_DATA_WRITE (p_ccb->connection_id, p_buf);
-
-        if (status == L2CAP_DW_CONGESTED)
-        {
-            p_ccb->is_congested = TRUE;
-            break;
-        }
-        else if (status != L2CAP_DW_SUCCESS)
-            break;
-    }
-
-}
-#endif /* (GAP_CONN_POST_EVT_INCLUDED == TRUE) */
-#endif  /* GAP_CONN_INCLUDED */
diff --git a/stack/gap/gap_int.h b/stack/gap/gap_int.h
index 295ad83..40fe96a 100644
--- a/stack/gap/gap_int.h
+++ b/stack/gap/gap_int.h
@@ -22,104 +22,11 @@
 
 #include "bt_target.h"
 #include "gap_api.h"
-#include "btm_api.h"
 #include "gki.h"
 #include "gatt_api.h"
-#if AMP_INCLUDED == TRUE
-    #include "amp_api.h"
-#endif
-
-#if defined BLE_INCLUDED && BLE_INCLUDED == TRUE
-    #include "gatt_api.h"
-#endif
-
-#define GAP_MAX_BLOCKS 2        /* Concurrent GAP commands pending at a time*/
-/* There must be a different btm callback for*/
-/* each control block.*/
-
-
-/* Definitions of limits for inquiries */
-#define GAP_PER_INQ_MIN_MAX_PERIOD      BTM_PER_INQ_MIN_MAX_PERIOD
-#define GAP_PER_INQ_MAX_MAX_PERIOD      BTM_PER_INQ_MAX_MAX_PERIOD
-#define GAP_PER_INQ_MIN_MIN_PERIOD      BTM_PER_INQ_MIN_MIN_PERIOD
-#define GAP_PER_INQ_MAX_MIN_PERIOD      BTM_PER_INQ_MAX_MIN_PERIOD
-#define GAP_MAX_INQUIRY_LENGTH          BTM_MAX_INQUIRY_LENGTH
-#define GAP_MIN_INQUIRY_LEN             BTM_MIN_INQUIRY_LEN
-
-/* Define the Generic Access Profile control structure */
-typedef struct
-{
-    void          *p_data;      /* Pointer to any data returned in callback */
-    tGAP_CALLBACK *gap_cback;   /* Pointer to users callback function */
-    tGAP_CALLBACK *gap_inq_rslt_cback; /* Used for inquiry results */
-    UINT16         event;       /* Passed back in the callback */
-    UINT8          index;       /* Index of this control block and callback */
-    BOOLEAN        in_use;      /* True when structure is allocated */
-} tGAP_INFO;
-
-/* Define the control block for the FindAddrByName operation (Only 1 active at a time) */
-typedef struct
-{
-    tGAP_CALLBACK           *p_cback;
-    tBTM_INQ_INFO           *p_cur_inq; /* Pointer to the current inquiry database entry */
-    tGAP_FINDADDR_RESULTS    results;
-    BOOLEAN                  in_use;
-} tGAP_FINDADDR_CB;
-
-
-/* Define the GAP Connection Control Block.
-*/
-typedef struct
-{
-#define GAP_CCB_STATE_IDLE              0
-#define GAP_CCB_STATE_LISTENING         1
-#define GAP_CCB_STATE_CONN_SETUP        2
-#define GAP_CCB_STATE_CFG_SETUP         3
-#define GAP_CCB_STATE_WAIT_SEC          4
-#define GAP_CCB_STATE_CONNECTED         5
-    UINT8             con_state;
-
-#define GAP_CCB_FLAGS_IS_ORIG           0x01
-#define GAP_CCB_FLAGS_HIS_CFG_DONE      0x02
-#define GAP_CCB_FLAGS_MY_CFG_DONE       0x04
-#define GAP_CCB_FLAGS_SEC_DONE          0x08
-#define GAP_CCB_FLAGS_CONN_DONE         0x0E
-    UINT8             con_flags;
-
-    UINT8             service_id;           /* Used by BTM                          */
-    UINT16            gap_handle;           /* GAP handle                           */
-    UINT16            connection_id;        /* L2CAP CID                            */
-    BOOLEAN           rem_addr_specified;
-    UINT8             chan_mode_mask;       /* Supported channel modes (FCR)        */
-    BD_ADDR           rem_dev_address;
-    UINT16            psm;
-    UINT16            rem_mtu_size;
-
-    BOOLEAN           is_congested;
-    BUFFER_Q          tx_queue;             /* Queue of buffers waiting to be sent  */
-    BUFFER_Q          rx_queue;             /* Queue of buffers waiting to be read  */
-
-    UINT32            rx_queue_size;        /* Total data count in rx_queue         */
-
-    tGAP_CONN_CALLBACK *p_callback;         /* Users callback function              */
-
-    tL2CAP_CFG_INFO   cfg;                  /* Configuration                        */
-    tL2CAP_ERTM_INFO  ertm_info;            /* Pools and modes for ertm */
-} tGAP_CCB;
-
-typedef struct
-{
-#if AMP_INCLUDED == TRUE
-    tAMP_APPL_INFO    reg_info;
-#else
-    tL2CAP_APPL_INFO  reg_info;                     /* L2CAP Registration info */
-#endif
-    tGAP_CCB    ccb_pool[GAP_MAX_CONNECTIONS];
-} tGAP_CONN;
-
 
 #if BLE_INCLUDED == TRUE
-    #define GAP_MAX_CHAR_NUM          5
+#define GAP_MAX_CHAR_NUM          5
 
 typedef struct
 {
@@ -161,15 +68,7 @@
 
 typedef struct
 {
-    tGAP_INFO        blk[GAP_MAX_BLOCKS];
-    tBTM_CMPL_CB    *btm_cback[GAP_MAX_BLOCKS];
     UINT8            trace_level;
-    tGAP_FINDADDR_CB findaddr_cb;   /* Contains the control block for finding a device addr */
-    tBTM_INQ_INFO   *cur_inqptr;
-
-#if GAP_CONN_INCLUDED == TRUE
-    tGAP_CONN        conn;
-#endif
 
     /* LE GAP attribute database */
 #if BLE_INCLUDED == TRUE
@@ -182,50 +81,10 @@
 } tGAP_CB;
 
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if GAP_DYNAMIC_MEMORY == FALSE
-    GAP_API extern tGAP_CB  gap_cb;
-#else
-    GAP_API extern tGAP_CB *gap_cb_ptr;
-#define gap_cb (*gap_cb_ptr)
-#endif
-
-    extern tGAP_INFO        *gap_allocate_cb(void);
-    extern void              gap_free_cb(tGAP_INFO *p_cb);
-
-    /* GAP inquiry functions */
-    extern void              gap_inq_results_cb(tGAP_INQ_RESULTS *p_results, UINT8 *p_eir);
-    extern UINT16            gap_find_local_addr_by_name (const BD_NAME devname, BD_ADDR bd_addr);
-    extern void              gap_find_addr_inq_cb (tBTM_INQUIRY_CMPL *p);
-
-    extern BOOLEAN           gap_is_service_busy (UINT16 request);
-    extern UINT16            gap_convert_btm_status (tBTM_STATUS btm_status);
-
-    extern void gap_btm_cback0(void *p1);
-#if GAP_MAX_BLOCKS > 1
-    extern void gap_btm_cback1(void *p1);
-#endif
-#if GAP_MAX_BLOCKS > 2
-    extern void gap_btm_cback2(void *p1);
-#endif
-
-#if (GAP_CONN_INCLUDED == TRUE)
-    extern void gap_conn_init(void);
-#if (GAP_CONN_POST_EVT_INCLUDED == TRUE)
-    void gap_send_event (UINT16 gap_handle);
-    void gap_proc_btu_event(BT_HDR *p_msg);
-#endif
-#endif
+extern tGAP_CB  gap_cb;
 
 #if (BLE_INCLUDED == TRUE)
     extern void gap_attr_db_init(void);
 #endif
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif
diff --git a/stack/gap/gap_utils.c b/stack/gap/gap_utils.c
deleted file mode 100644
index 3ef893d..0000000
--- a/stack/gap/gap_utils.c
+++ /dev/null
@@ -1,436 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2009-2013 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-#include <string.h>
-#include "bt_target.h"
-#include "bt_utils.h"
-#include "gap_int.h"
-
-/*****************************************************************************/
-/*                 G L O B A L      GAP       D A T A                        */
-/*****************************************************************************/
-#if GAP_DYNAMIC_MEMORY == FALSE
-tGAP_CB  gap_cb;
-#endif
-
-/*****************************************************************************
-** Callbacks passed to BTM -
-**      There are different callbacks based on the control block index so that
-**      more than one command can be pending at a time.
-**  NOTE:  There must be 1 callback for each control block defined
-**          GAP_MAX_BLOCKS
-**
-**          Also, the inquiry results event has its own callback; Not handled here!
-******************************************************************************/
-static void btm_cback(UINT16 index, void *p_data)
-{
-    tGAP_INFO       *p_cb;
-    tGAP_INQ_CMPL    inq_cmpl;
-
-    /* Make sure that the index is valid AND it is in use */
-    if (index < GAP_MAX_BLOCKS && gap_cb.blk[index].in_use)
-    {
-        p_cb = &gap_cb.blk[index];
-
-        /* If the callback is non-NULL, call it with the specified event */
-        switch (p_cb->event)
-        {
-        case GAP_EVT_INQUIRY_COMPLETE:
-            /* pass the number of results to caller */
-            inq_cmpl.num_results = ((tBTM_INQUIRY_CMPL *)p_data)->num_resp;
-
-            inq_cmpl.status = (((tBTM_INQUIRY_CMPL *)p_data)->status == BTM_SUCCESS) ? BT_PASS : GAP_ERR_PROCESSING;
-
-            p_data = &inq_cmpl;
-
-            GAP_TRACE_EVENT("   GAP Inquiry Complete Event (Status 0x%04x, Result(s) %d)",
-                            inq_cmpl.status, inq_cmpl.num_results);
-            break;
-
-        case GAP_EVT_DISCOVERY_COMPLETE:
-            if (*((UINT16 *) p_data))
-            {
-                GAP_TRACE_EVENT("   GAP Discovery Complete Event(SDP Result: 0x%04x)", *((UINT16 *) p_data));
-            }
-            else
-            {
-                GAP_TRACE_EVENT("   GAP Discovery Successfully Completed");
-            }
-
-            break;
-
-        case GAP_EVT_REM_NAME_COMPLETE:
-            /* override the BTM error code with a GAP error code */
-            ((tGAP_REMOTE_DEV_NAME *)p_data)->status =
-                    gap_convert_btm_status ((tBTM_STATUS)((tBTM_REMOTE_DEV_NAME *)p_data)->status);
-
-            GAP_TRACE_EVENT("   GAP Remote Name Complete Event (status 0x%04x)", ((tGAP_REMOTE_DEV_NAME *)p_data)->status);
-
-            break;
-        };
-
-        if (p_cb->gap_cback)
-            p_cb->gap_cback(p_cb->event, p_data);
-
-        /* Deallocate the control block */
-        gap_free_cb(p_cb);
-    }
-}
-
-
-/*** Callback functions for BTM_CMPL_CB ***/
-void gap_btm_cback0(void *p1)
-{
-    btm_cback(0, p1);
-}
-
-#if GAP_MAX_BLOCKS > 1
-void gap_btm_cback1(void *p1)
-{
-    btm_cback(1, p1);
-}
-#endif
-#if GAP_MAX_BLOCKS > 2
-void gap_btm_cback2(void *p1)
-{
-    btm_cback(2, p1);
-}
-#endif
-
-/* There is only one instance of this because only 1 inquiry can be active at a time */
-void gap_inq_results_cb(tBTM_INQ_RESULTS *p_results, UINT8 *p_eir)
-{
-    tGAP_INFO   *p_cb;
-    UINT8        index;
-    UNUSED(p_eir);
-
-    GAP_TRACE_EVENT ("GAP Inquiry Results Callback (bdaddr [%02x%02x%02x%02x%02x%02x])",
-                p_results->remote_bd_addr[0], p_results->remote_bd_addr[1],
-                p_results->remote_bd_addr[2], p_results->remote_bd_addr[3],
-                p_results->remote_bd_addr[4], p_results->remote_bd_addr[5]);
-    GAP_TRACE_EVENT ("                             (COD [%02x%02x%02x], clkoff 0x%04x)",
-                p_results->dev_class[0], p_results->dev_class[1], p_results->dev_class[2],
-                p_results->clock_offset);
-
-    /* Find the control block which has an Inquiry Active and call its results callback */
-    for (index = 0, p_cb = &gap_cb.blk[0]; index < GAP_MAX_BLOCKS; index++, p_cb++)
-    {
-        /* Look for the control block that is using inquiry */
-        if (p_cb->in_use && (p_cb->event == GAP_EVT_INQUIRY_COMPLETE))
-        {
-            /* Notify the higher layer if they care */
-            if (p_cb->gap_inq_rslt_cback)
-                p_cb->gap_inq_rslt_cback (GAP_EVT_INQUIRY_RESULTS, (tGAP_INQ_RESULTS *)p_results);
-        }
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_find_addr_name_cb
-**
-** Description      Processes the remote name request event when the Find Addr by Name
-**                  request is active.  The following procedure takes place:
-**                  1. Check the resulting name (If return status is ok)
-**                  2. If name matches requested name, we're done, call the appl's callback
-**                          with the BD ADDR.
-**                  3. Otherwise get the next BD ADDR out of the inquiry database and intiate
-**                          another remote name request.
-**                  4. If there are no more BD ADDRs, then call the appl's callback with a FAIL
-**                          status.
-**
-** Returns          void
-**
-*******************************************************************************/
-void gap_find_addr_name_cb (tBTM_REMOTE_DEV_NAME *p)
-{
-    tGAP_FINDADDR_CB        *p_cb = &gap_cb.findaddr_cb;
-    tGAP_FINDADDR_RESULTS   *p_result = &p_cb->results;
-
-    if (p_cb->in_use)
-    {
-        if (p->status == BTM_SUCCESS)
-        {
-            GAP_TRACE_EVENT("   GAP: FindAddrByName Rem Name Cmpl Evt (Status 0x%04x, Name [%s])",
-                                p->status, p->remote_bd_name);
-
-            /* See if the returned name matches the desired name; if not initiate another search */
-            if (!strncmp ((char *)p_result->devname, (char *) p->remote_bd_name, strlen ((char *) p_result->devname)))
-            {
-                /* We found the device!  Copy it into the return structure */
-                memcpy (p_result->bd_addr, p_cb->p_cur_inq->results.remote_bd_addr, BD_ADDR_LEN);
-                p_result->status = BT_PASS;
-            }
-            else    /* The name doesn't match so initiate another search */
-            {
-                /* Get the device address of the next database entry */
-                if ((p_cb->p_cur_inq = BTM_InqDbNext(p_cb->p_cur_inq)) != NULL)
-                {
-                    if ((BTM_ReadRemoteDeviceName (p_cb->p_cur_inq->results.remote_bd_addr,
-                        (tBTM_CMPL_CB *) gap_find_addr_name_cb, BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED)
-                        return;     /* This routine will get called again with the next results */
-                    else
-                        p_result->status = gap_convert_btm_status ((tBTM_STATUS) p->status);
-                }
-                else
-                    p_result->status = GAP_EOINQDB;     /* No inquiry results; we're done! */
-            }
-        }
-        else
-        {
-            GAP_TRACE_EVENT("   GAP: FindAddrByName Rem Name Cmpl Evt (Status 0x%04x)", p->status);
-            p_result->status = gap_convert_btm_status ((tBTM_STATUS) p->status);
-        }
-
-        /* If this code is reached, the process has completed so call the appl's callback with results */
-        if (p_cb->p_cback)
-            p_cb->p_cback (GAP_EVT_FIND_ADDR_COMPLETE, (tGAP_FINDADDR_RESULTS *) p_result);
-
-        /* Clear out the control block */
-        p_cb->in_use = FALSE;
-        p_cb->p_cback = (tGAP_CALLBACK *) NULL;
-    }
-}
-
-/*******************************************************************************
-**
-** Function         gap_find_addr_inq_cb
-**
-** Description      Processes the inquiry complete event when the Find Addr by Name
-**                  request is active.  This callback performs one of the two following
-**                  steps:
-**                      1. If the remote name is retrieved automatically, the DB is searched
-**                          immediately, and the results are returned in the appls callback.
-**
-**                      2. If remote name is not automatic, retrieve the first BTM INQ
-**                         database entry and initiate a remote name request.
-**
-** Returns          void
-**
-*******************************************************************************/
-void gap_find_addr_inq_cb (tBTM_INQUIRY_CMPL *p)
-{
-    tGAP_FINDADDR_CB        *p_cb = &gap_cb.findaddr_cb;
-    tGAP_FINDADDR_RESULTS   *p_result = &p_cb->results;
-
-    if (p_cb->in_use)
-    {
-
-        GAP_TRACE_EVENT("   GAP: FindAddrByName Inq Cmpl Evt (Status 0x%04x, Result(s) %d)",
-            p->status, p->num_resp);
-
-        if (p->status == BTM_SUCCESS)
-        {
-            /* Step 1: If automatically retrieving remote names then search the local database */
-            if ((p_result->status = gap_find_local_addr_by_name (p_result->devname, p_result->bd_addr)) == GAP_NO_DATA_AVAIL)
-            {
-                /* Step 2:  The name is not stored automatically, so a search of all devices needs to
-                 *          be initiated.
-                 */
-                if ((p_cb->p_cur_inq = BTM_InqDbFirst()) != NULL)
-                {
-                    if ((BTM_ReadRemoteDeviceName (p_cb->p_cur_inq->results.remote_bd_addr,
-                        (tBTM_CMPL_CB *) gap_find_addr_name_cb, BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED)
-                        return;     /* Wait for the response in gap_find_addr_name_cb() */
-                    else
-                        p_result->status = gap_convert_btm_status (p->status);
-                }
-                else
-                    p_result->status = GAP_EOINQDB;     /* No inquiry results; we're done! */
-            }
-        }
-        else
-            p_result->status = gap_convert_btm_status (p->status);
-
-        /* If this code is reached, the process has completed so call the appl's callback with results */
-        if (p_cb->p_cback)
-            p_cb->p_cback (GAP_EVT_FIND_ADDR_COMPLETE, (tGAP_FINDADDR_RESULTS *) p_result);
-
-        /* Clear out the control block */
-        p_cb->in_use = FALSE;
-        p_cb->p_cback = (tGAP_CALLBACK *) NULL;
-    }
-}
-
-/*******************************************************************************
-**
-** Function         gap_find_local_addr_by_name
-**
-** Description      Searches through the internal inquiry database for a device
-**                  that has the same name as the one passed in.  If found, the
-**                  device address is filled in.
-**
-**                  NOTE:  It only searches up to the first BTM_MAX_REM_BD_NAME_LEN
-**                          bytes because the inquiry database uses tBTM_BD_NAME.
-**
-** Returns          BT_PASS if the name was found and the device address is filled in
-**                  GAP_EOINQDB if the name was not found in the database
-**                  GAP_NO_DATA_AVAIL if the name is not saved with the inquiry
-**
-*******************************************************************************/
-UINT16 gap_find_local_addr_by_name (const tBTM_BD_NAME devname, BD_ADDR bd_addr)
-{
-
-/* If the remote name is retrieved automatically during an inquiry search the local db */
-#if (BTM_INQ_GET_REMOTE_NAME == TRUE)
-    tBTM_INQ_INFO   *p_result;
-
-    p_result = BTM_InqDbFirst();
-
-    while (p_result)
-    {
-        /* Check the entry for a device name match */
-        if (!strncmp ((char *)devname, (char *)p_result->remote_name, BTM_MAX_REM_BD_NAME_LEN))
-        {
-            memcpy (bd_addr, p_result->results.remote_bd_addr, BD_ADDR_LEN);
-            return (BT_PASS);
-        }
-        else
-            p_result = BTM_InqDbNext(p_result);
-    };
-
-    return (GAP_EOINQDB);
-#else
-    UNUSED(devname);
-    UNUSED(bd_addr);
-    /* No data available because we are not automatically saving the data */
-    return (GAP_NO_DATA_AVAIL);
-#endif
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_allocate_cb
-**
-** Description      Look through the GAP Control Blocks for a free one.
-**
-** Returns          Pointer to the control block or NULL if not found
-**
-*******************************************************************************/
-tGAP_INFO *gap_allocate_cb (void)
-{
-    tGAP_INFO     *p_cb = &gap_cb.blk[0];
-    UINT8        x;
-
-    for (x = 0; x < GAP_MAX_BLOCKS; x++, p_cb++)
-    {
-        if (!p_cb->in_use)
-        {
-            memset (p_cb, 0, sizeof (tGAP_INFO));
-
-            p_cb->in_use = TRUE;
-            p_cb->index = x;
-            p_cb->p_data = (void *)NULL;
-            return (p_cb);
-        }
-    }
-
-    /* If here, no free control blocks found */
-    return (NULL);
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_free_cb
-**
-** Description      Release GAP control block.
-**
-** Returns          Pointer to the control block or NULL if not found
-**
-*******************************************************************************/
-void gap_free_cb (tGAP_INFO *p_cb)
-{
-    if (p_cb)
-    {
-        p_cb->gap_cback = NULL;
-        p_cb->in_use = FALSE;
-    }
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_is_service_busy
-**
-** Description      Look through the GAP Control Blocks that are in use
-**                  and check to see if the event waiting for is the command
-**                  requested.
-**
-** Returns          TRUE if already in use
-**                  FALSE if not busy
-**
-*******************************************************************************/
-BOOLEAN gap_is_service_busy (UINT16 request)
-{
-    tGAP_INFO   *p_cb = &gap_cb.blk[0];
-    UINT8        x;
-
-    for (x = 0; x < GAP_MAX_BLOCKS; x++, p_cb++)
-    {
-        if (p_cb->in_use && p_cb->event == request)
-            return (TRUE);
-    }
-
-    /* If here, service is not busy */
-    return (FALSE);
-}
-
-
-/*******************************************************************************
-**
-** Function         gap_convert_btm_status
-**
-** Description      Converts a BTM error status into a GAP error status
-**
-**
-** Returns          GAP_UNKNOWN_BTM_STATUS is returned if not recognized
-**
-*******************************************************************************/
-UINT16 gap_convert_btm_status (tBTM_STATUS btm_status)
-{
-    switch (btm_status)
-    {
-    case BTM_SUCCESS:
-        return (BT_PASS);
-
-    case BTM_CMD_STARTED:
-        return (GAP_CMD_INITIATED);
-
-    case BTM_BUSY:
-        return (GAP_ERR_BUSY);
-
-    case BTM_MODE_UNSUPPORTED:
-    case BTM_ILLEGAL_VALUE:
-        return (GAP_ERR_ILL_PARM);
-
-    case BTM_WRONG_MODE:
-        return (GAP_DEVICE_NOT_UP);
-
-    case BTM_UNKNOWN_ADDR:
-        return (GAP_BAD_BD_ADDR);
-
-    case BTM_DEVICE_TIMEOUT:
-        return (GAP_ERR_TIMEOUT);
-
-    default:
-        return (GAP_ERR_PROCESSING);
-    }
-}
diff --git a/stack/gatt/gatt_api.c b/stack/gatt/gatt_api.c
index 6683cb6..d7b06e4 100644
--- a/stack/gatt/gatt_api.c
+++ b/stack/gatt/gatt_api.c
@@ -1323,7 +1323,7 @@
 **
 ** Parameter        gatt_if: applicaiton interface.
 **
-** Returns          0 for error, otherwise the index of the client registered with GATT
+** Returns          None.
 **
 *******************************************************************************/
 void GATT_StartIf (tGATT_IF gatt_if)
@@ -1338,7 +1338,6 @@
     GATT_TRACE_API ("GATT_StartIf gatt_if=%d", gatt_if);
     if ((p_reg = gatt_get_regcb(gatt_if)) != NULL)
     {
-        p_reg = &gatt_cb.cl_rcb[gatt_if - 1];
         start_idx = 0;
         while (gatt_find_the_connected_bda(start_idx, bda, &found_idx, &transport))
         {
@@ -1602,7 +1601,6 @@
 BOOLEAN GATT_Listen (tGATT_IF gatt_if, BOOLEAN start, BD_ADDR_PTR bd_addr)
 {
     tGATT_REG    *p_reg;
-    BOOLEAN status = TRUE;
 
     GATT_TRACE_API ("GATT_Listen gatt_if=%d", gatt_if);
 
@@ -1615,7 +1613,7 @@
 
     if (bd_addr != NULL)
     {
-        status = gatt_update_auto_connect_dev(gatt_if,start, bd_addr, FALSE);
+        gatt_update_auto_connect_dev(gatt_if,start, bd_addr, FALSE);
     }
     else
     {
diff --git a/stack/gatt/gatt_attr.c b/stack/gatt/gatt_attr.c
index 8773036..fe3fcc4 100644
--- a/stack/gatt/gatt_attr.c
+++ b/stack/gatt/gatt_attr.c
@@ -98,7 +98,7 @@
             return p_clcb;
     }
 
-    return p_clcb;
+    return NULL;
 }
 
 /*******************************************************************************
@@ -122,7 +122,7 @@
             return p_clcb;
     }
 
-    return p_clcb;
+    return NULL;
 }
 
 /*******************************************************************************
@@ -151,7 +151,10 @@
             break;
         }
     }
-    return p_clcb;
+    if(i_clcb < GATT_MAX_APPS)
+        return p_clcb;
+
+    return NULL;
 }
 
 /*******************************************************************************
diff --git a/stack/gatt/gatt_auth.c b/stack/gatt/gatt_auth.c
index 10cf76e..ae52145 100644
--- a/stack/gatt/gatt_auth.c
+++ b/stack/gatt/gatt_auth.c
@@ -192,7 +192,7 @@
             gatt_sec_check_complete(status , p_buf->p_clcb, p_tcb->sec_act);
             GKI_freebuf(p_buf);
             /* start all other pending operation in queue */
-            count = p_tcb->pending_enc_clcb.count;
+            count = GKI_queue_length(&p_tcb->pending_enc_clcb);
             for (; count > 0; count --)
             {
                 if ((p_buf = (tGATT_PENDING_ENC_CLCB *)GKI_dequeue (&p_tcb->pending_enc_clcb)) != NULL)
@@ -246,7 +246,7 @@
         {
             gatt_set_sec_act(p_tcb, GATT_SEC_NONE);
 
-            count = p_tcb->pending_enc_clcb.count;
+            count = GKI_queue_length(&p_tcb->pending_enc_clcb);
 
             for (; count > 0; count --)
             {
diff --git a/stack/gatt/gatt_db.c b/stack/gatt/gatt_db.c
index b7887c9..ef4f468 100644
--- a/stack/gatt/gatt_db.c
+++ b/stack/gatt/gatt_db.c
@@ -62,6 +62,8 @@
 BOOLEAN gatts_init_service_db (tGATT_SVC_DB *p_db, tBT_UUID *p_service,  BOOLEAN is_pri,
                                UINT16 s_hdl, UINT16 num_handle)
 {
+    GKI_init_q(&p_db->svc_buffer);
+
     if (!allocate_svc_db_buf(p_db))
     {
         GATT_TRACE_ERROR("gatts_init_service_db failed, no resources");
@@ -214,7 +216,6 @@
     UINT16          len = 0, uuid16 = 0;
     UINT8           *p = *p_data;
     tGATT_STATUS    status;
-    UINT16          read_long_uuid=0;
     tGATT_ATTR16    *p_attr16  = (tGATT_ATTR16  *)p_attr;
 
     GATT_TRACE_DEBUG("read_attr_value uuid=0x%04x perm=0x%0x sec_flag=0x%x offset=%d read_long=%d",
@@ -234,12 +235,6 @@
 
     status = GATT_NO_RESOURCES;
 
-    if (read_long &&
-        (uuid16 == GATT_UUID_CHAR_DESCRIPTION || uuid16 == GATT_UUID_CHAR_AGG_FORMAT))
-    {
-        read_long_uuid = p_attr16->uuid;
-    }
-
     if (uuid16 == GATT_UUID_PRI_SERVICE || uuid16 == GATT_UUID_SEC_SERVICE)
     {
         len = p_attr16->p_value->uuid.len;
diff --git a/stack/gatt/gatt_int.h b/stack/gatt/gatt_int.h
index d49c6e1..ccdb148 100644
--- a/stack/gatt/gatt_int.h
+++ b/stack/gatt/gatt_int.h
@@ -533,14 +533,14 @@
 
 /* Global GATT data */
 #if GATT_DYNAMIC_MEMORY == FALSE
-GATT_API extern tGATT_CB  gatt_cb;
+extern tGATT_CB  gatt_cb;
 #else
-GATT_API extern tGATT_CB *gatt_cb_ptr;
+extern tGATT_CB *gatt_cb_ptr;
 #define gatt_cb (*gatt_cb_ptr)
 #endif
 
 #if GATT_CONFORMANCE_TESTING == TRUE
-GATT_API extern void gatt_set_err_rsp(BOOLEAN enable, UINT8 req_op_code, UINT8 err_status);
+extern void gatt_set_err_rsp(BOOLEAN enable, UINT8 req_op_code, UINT8 err_status);
 #endif
 
 #ifdef __cplusplus
@@ -549,6 +549,7 @@
 
 /* internal functions */
 extern void gatt_init (void);
+extern void gatt_free(void);
 
 /* from gatt_main.c */
 extern BOOLEAN gatt_disconnect (tGATT_TCB *p_tcb);
@@ -709,5 +710,3 @@
 
 extern void gatt_reset_bgdev_list(void);
 #endif
-
-
diff --git a/stack/gatt/gatt_main.c b/stack/gatt/gatt_main.c
index 54951b2..f0a0229 100644
--- a/stack/gatt/gatt_main.c
+++ b/stack/gatt/gatt_main.c
@@ -102,6 +102,8 @@
 #endif
     gatt_cb.def_mtu_size = GATT_DEF_BLE_MTU_SIZE;
     GKI_init_q (&gatt_cb.sign_op_queue);
+    GKI_init_q (&gatt_cb.srv_chg_clt_q);
+    GKI_init_q (&gatt_cb.pending_new_srv_start_q);
     /* First, register fixed L2CAP channel for ATT over BLE */
     fixed_reg.fixed_chnl_opts.mode         = L2CAP_FCR_BASIC_MODE;
     fixed_reg.fixed_chnl_opts.max_transmit = 0xFF;
@@ -134,6 +136,24 @@
 }
 
 
+/*******************************************************************************
+**
+** Function         gatt_free
+**
+** Description      This function frees resources used by the GATT profile.
+**
+** Returns          void
+**
+*******************************************************************************/
+void gatt_free(void)
+{
+    int i;
+    GATT_TRACE_DEBUG("gatt_free()");
+    for (i = 0; i < GATT_MAX_SR_PROFILES; i++)
+    {
+        gatt_free_hdl_buffer(&gatt_cb.hdl_list[i]);
+    }
+}
 
 /*******************************************************************************
 **
diff --git a/stack/gatt/gatt_sr.c b/stack/gatt/gatt_sr.c
index dafaf30..ecf2427 100755
--- a/stack/gatt/gatt_sr.c
+++ b/stack/gatt/gatt_sr.c
@@ -106,7 +106,7 @@
         GKI_freebuf (p_tcb->sr_cmd.p_rsp_msg);
     }
 
-    while (p_tcb->sr_cmd.multi_rsp_q.p_first)
+    while (GKI_getfirst(&p_tcb->sr_cmd.multi_rsp_q))
         GKI_freebuf (GKI_dequeue (&p_tcb->sr_cmd.multi_rsp_q));
     memset( &p_tcb->sr_cmd, 0, sizeof(tGATT_SR_CMD));
 }
@@ -145,9 +145,9 @@
     if (status == GATT_SUCCESS)
     {
         GATT_TRACE_DEBUG ("Multi read count=%d num_hdls=%d",
-                           p_cmd->multi_rsp_q.count, p_cmd->multi_req.num_handles);
+                           GKI_queue_length(&p_cmd->multi_rsp_q), p_cmd->multi_req.num_handles);
         /* Wait till we get all the responses */
-        if (p_cmd->multi_rsp_q.count == p_cmd->multi_req.num_handles)
+        if (GKI_queue_length(&p_cmd->multi_rsp_q) == p_cmd->multi_req.num_handles)
         {
             len = sizeof(BT_HDR) + L2CAP_MIN_OFFSET + mtu;
             if ((p_buf = (BT_HDR *)GKI_getbuf(len)) == NULL)
diff --git a/stack/gatt/gatt_utils.c b/stack/gatt/gatt_utils.c
index 0e841a9..11d8dff 100644
--- a/stack/gatt/gatt_utils.c
+++ b/stack/gatt/gatt_utils.c
@@ -93,7 +93,7 @@
 {
     GATT_TRACE_DEBUG("gatt_free_pending_ind");
     /* release all queued indications */
-    while (p_tcb->pending_ind_q.p_first)
+    while (!GKI_queue_is_empty(&p_tcb->pending_ind_q))
         GKI_freebuf (GKI_dequeue (&p_tcb->pending_ind_q));
 }
 
@@ -110,7 +110,7 @@
 {
     GATT_TRACE_DEBUG("gatt_free_pending_enc_queue");
     /* release all queued indications */
-    while (p_tcb->pending_enc_clcb.p_first)
+    while (!GKI_queue_is_empty(&p_tcb->pending_enc_clcb))
         GKI_freebuf (GKI_dequeue (&p_tcb->pending_enc_clcb));
 }
 
@@ -373,7 +373,7 @@
 
     if (p)
     {
-        while (p->svc_db.svc_buffer.p_first)
+        while (!GKI_queue_is_empty(&p->svc_db.svc_buffer))
             GKI_freebuf (GKI_dequeue (&p->svc_db.svc_buffer));
         memset(p, 0, sizeof(tGATT_HDL_LIST_ELEM));
     }
@@ -397,7 +397,7 @@
     {
         if (memcmp(p_app_id, &p_elem->asgn_range.app_uuid128, sizeof(tBT_UUID)) == 0)
         {
-            while (p_elem->svc_db.svc_buffer.p_first)
+            while (!GKI_queue_is_empty(&p_elem->svc_db.svc_buffer))
                 GKI_freebuf (GKI_dequeue (&p_elem->svc_db.svc_buffer));
 
             p_elem->svc_db.mem_free = 0;
@@ -1363,7 +1363,7 @@
             p_sreg->e_hdl               = p_list->asgn_range.e_handle;
             p_sreg->p_db                = &p_list->svc_db;
 
-            GATT_TRACE_DEBUG ("total GKI buffer in db [%d]",p_sreg->p_db->svc_buffer.count);
+            GATT_TRACE_DEBUG ("total GKI buffer in db [%d]",GKI_queue_length(&p_sreg->p_db->svc_buffer));
             break;
         }
     }
@@ -1562,15 +1562,20 @@
     UINT8           ii = (UINT8)gatt_if;
     tGATT_REG       *p_reg = NULL;
 
-    if (ii)
-    {
-        ii--; /* convert from one based to zero based */
-        p_reg = &gatt_cb.cl_rcb[ii];
-        if ( (ii < GATT_MAX_APPS)  && (p_reg->in_use) )
-            return(p_reg);
+    if (ii < 1 || ii > GATT_MAX_APPS) {
+        GATT_TRACE_WARNING("gatt_if out of range [ = %d]", ii);
+        return NULL;
     }
 
-    return NULL;
+    // Index for cl_rcb is always 1 less than gatt_if.
+    p_reg = &gatt_cb.cl_rcb[ii - 1];
+
+    if (!p_reg->in_use) {
+        GATT_TRACE_WARNING("gatt_if found but not in use.");
+        return NULL;
+    }
+
+    return p_reg;
 }
 
 
diff --git a/stack/hcic/hciblecmds.c b/stack/hcic/hciblecmds.c
index 860fb7a..fa46dec 100644
--- a/stack/hcic/hciblecmds.c
+++ b/stack/hcic/hciblecmds.c
@@ -35,68 +35,6 @@
 
 #if (defined BLE_INCLUDED) && (BLE_INCLUDED == TRUE)
 
-BOOLEAN btsnd_hcic_ble_set_evt_mask (BT_EVENT_MASK event_mask)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_SET_EVENT_MASK)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_SET_EVENT_MASK;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_BLE_SET_EVENT_MASK);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_SET_EVENT_MASK);
-    ARRAY8_TO_STREAM (pp, event_mask);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-
-BOOLEAN btsnd_hcic_ble_read_buffer_size (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_BLE_READ_BUFFER_SIZE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_ble_read_local_spt_feat (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_BLE_READ_LOCAL_SPT_FEAT);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_ble_set_local_used_feat (UINT8 feat_set[8])
 {
     BT_HDR *p;
@@ -391,26 +329,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_ble_read_white_list_size (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_BLE_READ_WHITE_LIST_SIZE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_ble_clear_white_list (void)
 {
     BT_HDR *p;
@@ -707,26 +625,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_ble_read_supported_states (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_BLE_READ_SUPPORTED_STATES);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_ble_receiver_test(UINT8 rx_freq)
 {
     BT_HDR *p;
@@ -806,35 +704,13 @@
     p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
     p->offset = 0;
 
-    UINT16_TO_STREAM (pp, HCI_READ_LE_HOST_SUPPORTED);
+    UINT16_TO_STREAM (pp, HCI_READ_LE_HOST_SUPPORT);
     UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_READ_CMD);
 
     btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_ble_write_host_supported (UINT8 le_host_spt, UINT8 simul_le_host_spt)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_LE_HOST_SUPPORTED)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_LE_HOST_SUPPORTED;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_LE_HOST_SUPPORTED);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_LE_HOST_SUPPORTED);
-	UINT8_TO_STREAM  (pp, le_host_spt);
-	UINT8_TO_STREAM  (pp, simul_le_host_spt);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 #if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE)
 
 BOOLEAN btsnd_hcic_ble_rc_param_req_reply(  UINT16 handle,
diff --git a/stack/hcic/hcicmds.c b/stack/hcic/hcicmds.c
index a530d2a..13d7558 100644
--- a/stack/hcic/hcicmds.c
+++ b/stack/hcic/hcicmds.c
@@ -24,6 +24,7 @@
  ******************************************************************************/
 
 #include "bt_target.h"
+#include "btcore/include/counter.h"
 #include "gki.h"
 #include "hcidefs.h"
 #include "hcimsgs.h"
@@ -33,12 +34,7 @@
 #include <stddef.h>
 #include <string.h>
 
-#if defined (LMP_TEST)
-#include <script.h>
-#define btu_hcif_send_cmd(p1, p2) HCI_CMD_TO_LOWER((p2))
-#else
 #include "btm_int.h"    /* Included for UIPC_* macro definitions */
-#endif
 
 BOOLEAN btsnd_hcic_inquiry(const LAP inq_lap, UINT8 duration, UINT8 response_cnt)
 {
@@ -163,12 +159,7 @@
 #if !defined (BT_10A)
     UINT8_TO_STREAM  (pp, allow_switch);
 #endif
-/* If calling from LMP_TEST or ScriptEngine, then send HCI command immediately */
-#if (!defined (LMP_TEST) && !defined(BTISE))
     btm_acl_paging (p, dest);
-#else
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID, p);
-#endif
     return (TRUE);
 }
 
@@ -191,12 +182,6 @@
     UINT8_TO_STREAM  (pp, reason);
 
     btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID, p);
-/* If calling from LMP_TEST or ScriptEngine, then send HCI command immediately */
-#if (!defined (LMP_TEST) && !defined(BTISE))
-// btla-specific ++
-    // btm_acl_set_discing(TRUE);
-// btla-specific --
-#endif
     return (TRUE);
 }
 
@@ -265,6 +250,8 @@
     BDADDR_TO_STREAM (pp, dest);
     UINT8_TO_STREAM  (pp, role);
 
+    counter_add("hci.conn.accept", 1);
+
     btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID, p);
     return (TRUE);
 }
@@ -288,6 +275,8 @@
     BDADDR_TO_STREAM (pp, dest);
     UINT8_TO_STREAM (pp, reason);
 
+    counter_add("hci.conn.reject", 1);
+
     btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID, p);
     return (TRUE);
 }
@@ -459,50 +448,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_change_link_key (UINT16 handle)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_CMD_HANDLE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_CMD_HANDLE;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_CHANGE_CONN_LINK_KEY);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_CMD_HANDLE);
-
-    UINT16_TO_STREAM (pp, handle);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID, p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_master_link_key (BOOLEAN key_flag)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_MASTER_LINK_KEY)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_MASTER_LINK_KEY;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_MASTER_LINK_KEY);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_MASTER_LINK_KEY);
-
-    UINT8_TO_STREAM  (pp, key_flag);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID, p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_rmt_name_req (BD_ADDR bd_addr, UINT8 page_scan_rep_mode,
                                  UINT8 page_scan_mode, UINT16 clock_offset)
 {
@@ -525,12 +470,7 @@
     UINT8_TO_STREAM  (pp, page_scan_mode);
     UINT16_TO_STREAM (pp, clock_offset);
 
-/* If calling from LMP_TEST or ScriptEngine, then send HCI command immediately */
-#if (!defined (LMP_TEST) && !defined(BTISE))
     btm_acl_paging (p, bd_addr);
-#else
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID, p);
-#endif
     return (TRUE);
 }
 
@@ -903,28 +843,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_role_discovery (UINT16 handle)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_CMD_HANDLE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_CMD_HANDLE;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_ROLE_DISCOVERY);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_CMD_HANDLE);
-
-    UINT16_TO_STREAM (pp, handle);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_switch_role (BD_ADDR bd_addr, UINT8 role)
 {
     BT_HDR *p;
@@ -948,28 +866,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_policy_set (UINT16 handle)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_CMD_HANDLE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_CMD_HANDLE;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_POLICY_SETTINGS);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_CMD_HANDLE);
-
-    UINT16_TO_STREAM (pp, handle);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_policy_set (UINT16 handle, UINT16 settings)
 {
     BT_HDR *p;
@@ -992,26 +888,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_def_policy_set (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_DEF_POLICY_SET)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_DEF_POLICY_SET;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_DEF_POLICY_SETTINGS);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_READ_DEF_POLICY_SET);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_def_policy_set (UINT16 settings)
 {
     BT_HDR *p;
@@ -1033,108 +909,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_flow_specification(UINT16 handle, UINT8 flags, UINT8 flow_direct,
-                                      UINT8  service_type, UINT32 token_rate,
-                                      UINT32 token_bucket_size, UINT32 peak,
-                                      UINT32 latency)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_FLOW_SPEC)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_FLOW_SPEC;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_FLOW_SPECIFICATION);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_FLOW_SPEC);
-
-    UINT16_TO_STREAM (pp, handle);
-    UINT8_TO_STREAM  (pp, flags);
-    UINT8_TO_STREAM  (pp, flow_direct);
-    UINT8_TO_STREAM  (pp, service_type);
-    UINT32_TO_STREAM (pp, token_rate);
-    UINT32_TO_STREAM (pp, token_bucket_size);
-    UINT32_TO_STREAM (pp, peak);
-    UINT32_TO_STREAM (pp, latency);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_set_event_mask(UINT8 local_controller_id, BT_EVENT_MASK event_mask)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_SET_EVENT_MASK)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_SET_EVENT_MASK;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_SET_EVENT_MASK);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_SET_EVENT_MASK);
-    ARRAY8_TO_STREAM (pp, event_mask);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_set_event_mask_page_2 (UINT8 local_controller_id, BT_EVENT_MASK event_mask)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_SET_EVENT_MASK_PAGE_2)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_SET_EVENT_MASK_PAGE_2;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_SET_EVENT_MASK_PAGE_2);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_SET_EVENT_MASK_PAGE_2);
-    ARRAY8_TO_STREAM (pp, event_mask);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_reset (UINT8 local_controller_id)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_RESET)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_RESET;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_RESET);
-    UINT8_TO_STREAM (pp, HCIC_PARAM_SIZE_RESET);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-/* If calling from LMP_TEST or ScriptEngine, then send HCI command immediately */
-#if (!defined (LMP_TEST) && !defined(BTISE))
-    if (local_controller_id == LOCAL_BR_EDR_CONTROLLER_ID)
-    {
-        btm_acl_reset_paging ();
-        btm_acl_set_discing (FALSE);
-    }
-#endif
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_set_event_filter (UINT8 filt_type, UINT8 filt_cond_type,
                                      UINT8 *filt_cond, UINT8 filt_cond_len)
 {
@@ -1191,47 +965,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_flush (UINT8 local_controller_id, UINT16 handle)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_CMD_HANDLE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_CMD_HANDLE;
-    p->offset = 0;
-    UINT16_TO_STREAM (pp, HCI_FLUSH);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_CMD_HANDLE);
-
-    UINT16_TO_STREAM (pp, handle);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_pin_type (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_PIN_TYPE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_pin_type (UINT8 type)
 {
     BT_HDR *p;
@@ -1254,83 +987,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_new_unit_key (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_NEW_UNIT_KEY)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_NEW_UNIT_KEY;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_CREATE_NEW_UNIT_KEY);
-    UINT8_TO_STREAM (pp, HCIC_PARAM_SIZE_NEW_UNIT_KEY);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_stored_key (BD_ADDR bd_addr, BOOLEAN read_all_flag)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_STORED_KEY)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_STORED_KEY;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_STORED_LINK_KEY);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_READ_STORED_KEY);
-
-    BDADDR_TO_STREAM (pp, bd_addr);
-    UINT8_TO_STREAM  (pp, read_all_flag);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_write_stored_key (UINT8 num_keys, BD_ADDR *bd_addr,
-                                     LINK_KEY *link_key)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-    int j;
-
-    if ((p = HCI_GET_CMD_BUF(1 + (num_keys * (BD_ADDR_LEN + LINK_KEY_LEN)))) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-
-    p->len    = HCIC_PREAMBLE_SIZE + 1 + (num_keys * (BD_ADDR_LEN + LINK_KEY_LEN));
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_STORED_LINK_KEY);
-    UINT8_TO_STREAM  (pp, p->len - HCIC_PREAMBLE_SIZE);
-
-    if(num_keys > HCI_MAX_NUM_OF_LINK_KEYS_PER_CMMD)
-        num_keys = HCI_MAX_NUM_OF_LINK_KEYS_PER_CMMD;
-
-    UINT8_TO_STREAM (pp, num_keys);
-
-    for (j = 0; j < num_keys; j++)
-    {
-        BDADDR_TO_STREAM  (pp, bd_addr[j]);
-        ARRAY16_TO_STREAM (pp, link_key[j]);
-    }
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_delete_stored_key (BD_ADDR bd_addr, BOOLEAN delete_all_flag)
 {
     BT_HDR *p;
@@ -1401,68 +1057,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_conn_acc_tout (UINT8 local_controller_id)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_CONN_ACCEPT_TOUT);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_write_conn_acc_tout (UINT8 local_controller_id, UINT16 timeout)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_PARAM2)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_PARAM2;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_CONN_ACCEPT_TOUT);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_PARAM2);
-
-    UINT16_TO_STREAM (pp, timeout);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_page_tout (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_PAGE_TOUT);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_page_tout (UINT16 timeout)
 {
     BT_HDR *p;
@@ -1485,26 +1079,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_scan_enable (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_SCAN_ENABLE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_scan_enable (UINT8 flag)
 {
     BT_HDR *p;
@@ -1527,26 +1101,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_pagescan_cfg(void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_PAGESCAN_CFG);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_pagescan_cfg(UINT16 interval, UINT16 window)
 {
     BT_HDR *p;
@@ -1570,26 +1124,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_inqscan_cfg(void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_INQUIRYSCAN_CFG);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_inqscan_cfg(UINT16 interval, UINT16 window)
 {
     BT_HDR *p;
@@ -1613,26 +1147,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_auth_enable (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_AUTHENTICATION_ENABLE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_auth_enable (UINT8 flag)
 {
     BT_HDR *p;
@@ -1655,68 +1169,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_encr_mode (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_ENCRYPTION_MODE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_write_encr_mode (UINT8 mode)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_PARAM1)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_PARAM1;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_ENCRYPTION_MODE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_PARAM1);
-
-    UINT8_TO_STREAM (pp, mode);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_dev_class(void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_CLASS_OF_DEVICE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_dev_class(DEV_CLASS dev_class)
 {
     BT_HDR *p;
@@ -1739,26 +1191,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_voice_settings(void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_VOICE_SETTINGS);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_voice_settings(UINT16 flags)
 {
     BT_HDR *p;
@@ -1781,28 +1213,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_auto_flush_tout (UINT16 handle)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_CMD_HANDLE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_CMD_HANDLE;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_AUTO_FLUSH_TOUT);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_CMD_HANDLE);
-
-    UINT16_TO_STREAM (pp, handle);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_auto_flush_tout (UINT16 handle, UINT16 tout)
 {
     BT_HDR *p;
@@ -1826,90 +1236,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_num_bcast_xmit (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_NUM_BCAST_REXMITS);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_write_num_bcast_xmit (UINT8 num)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_PARAM1)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_PARAM1;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_NUM_BCAST_REXMITS);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_PARAM1);
-
-    UINT8_TO_STREAM (pp, num);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_hold_mode_act (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_HOLD_MODE_ACTIVITY);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_write_hold_mode_act (UINT8 flags)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_PARAM1)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_PARAM1;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_HOLD_MODE_ACTIVITY);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_PARAM1);
-
-    UINT8_TO_STREAM (pp, flags);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_read_tx_power (UINT16 handle, UINT8 type)
 {
     BT_HDR *p;
@@ -1933,96 +1259,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_sco_flow_enable (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_SCO_FLOW_CTRL_ENABLE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_write_sco_flow_enable (UINT8 flag)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_PARAM1)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_PARAM1;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_SCO_FLOW_CTRL_ENABLE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_PARAM1);
-
-    UINT8_TO_STREAM (pp, flag);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_set_host_flow_ctrl (UINT8 value)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_PARAM1)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_PARAM1;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_SET_HC_TO_HOST_FLOW_CTRL);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_PARAM1);
-
-    UINT8_TO_STREAM (pp, value);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_set_host_buf_size (UINT16 acl_len, UINT8 sco_len,
-                                      UINT16 acl_num, UINT16 sco_num)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_SET_HOST_BUF_SIZE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_SET_HOST_BUF_SIZE;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_HOST_BUFFER_SIZE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_SET_HOST_BUF_SIZE);
-
-    UINT16_TO_STREAM (pp, acl_len);
-    UINT8_TO_STREAM  (pp, sco_len);
-    UINT16_TO_STREAM (pp, acl_num);
-    UINT16_TO_STREAM (pp, sco_num);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_host_num_xmitted_pkts (UINT8 num_handles, UINT16 *handle,
                                           UINT16 *num_pkts)
 {
@@ -2053,28 +1289,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_link_super_tout (UINT8 local_controller_id, UINT16 handle)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_CMD_HANDLE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_CMD_HANDLE;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_LINK_SUPER_TOUT);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_CMD_HANDLE);
-
-    UINT16_TO_STREAM (pp, handle);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_link_super_tout (UINT8 local_controller_id, UINT16 handle, UINT16 timeout)
 {
     BT_HDR *p;
@@ -2098,46 +1312,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_max_iac (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_NUM_SUPPORTED_IAC);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_cur_iac_lap (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_CURRENT_IAC_LAP);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_cur_iac_lap (UINT8 num_cur_iac, LAP * const iac_lap)
 {
     BT_HDR *p;
@@ -2164,90 +1338,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_page_scan_per (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_PAGESCAN_PERIOD_MODE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_write_page_scan_per (UINT8 mode)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_PARAM1)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_PARAM1;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_PAGESCAN_PERIOD_MODE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_PARAM1);
-
-    UINT8_TO_STREAM  (pp, mode);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_page_scan_mode (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_PAGESCAN_MODE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_write_page_scan_mode (UINT8 mode)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_PARAM1)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_PARAM1;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_PAGESCAN_MODE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_PARAM1);
-
-    UINT8_TO_STREAM (pp, mode);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 /******************************************
 **    Lisbon Features
 *******************************************/
@@ -2280,28 +1370,7 @@
 }
 #endif /* BTM_SSR_INCLUDED */
 
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
 /**** Extended Inquiry Response Commands ****/
-BOOLEAN btsnd_hcic_read_ext_inquiry_response (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_EXT_INQ_RESPONSE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 void btsnd_hcic_write_ext_inquiry_response (void *buffer, UINT8 fec_req)
 {
     BT_HDR *p = (BT_HDR *)buffer;
@@ -2317,72 +1386,6 @@
 
     btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
 }
-#endif  /* BTM_EIR_SERVER_INCLUDED == TRUE */
-
-/**** Simple Pairing Commands ****/
-BOOLEAN btsnd_hcic_write_simple_pairing_mode (UINT8 mode)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_W_SIMP_PAIR)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_W_SIMP_PAIR;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_SIMPLE_PAIRING_MODE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_W_SIMP_PAIR);
-
-    UINT8_TO_STREAM (pp, mode);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_simple_pairing_mode (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_R_SIMP_PAIR)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_R_SIMP_PAIR;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_SIMPLE_PAIRING_MODE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_R_SIMP_PAIR);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_write_simp_pair_debug_mode(UINT8 debug_mode)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_SIMP_PAIR_DBUG)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_SIMP_PAIR_DBUG;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_SIMP_PAIR_DEBUG_MODE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_SIMP_PAIR_DBUG);
-
-    UINT8_TO_STREAM (pp, debug_mode);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
 
 BOOLEAN btsnd_hcic_io_cap_req_reply (BD_ADDR bd_addr, UINT8 capability,
                                 UINT8 oob_present, UINT8 auth_req)
@@ -2597,72 +1600,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_write_inq_tx_power (INT8 level)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_W_TX_POWER)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_W_TX_POWER;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_INQ_TX_POWER_LEVEL);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_W_TX_POWER);
-
-    INT8_TO_STREAM (pp, level);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-#if 0 /* currently not been used */
-BOOLEAN btsnd_hcic_read_default_erroneous_data_rpt (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_R_ERR_DATA_RPT)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_R_ERR_DATA_RPT;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_ERRONEOUS_DATA_RPT);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_R_ERR_DATA_RPT);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-#endif
-
-BOOLEAN btsnd_hcic_write_default_erroneous_data_rpt (UINT8 flag)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_W_ERR_DATA_RPT)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_W_ERR_DATA_RPT;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_ERRONEOUS_DATA_RPT);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_W_ERR_DATA_RPT);
-
-    UINT8_TO_STREAM (pp, flag);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_send_keypress_notif (BD_ADDR bd_addr, UINT8 notif)
 {
     BT_HDR *p;
@@ -2712,217 +1649,10 @@
 }
 #endif
 
-
-BOOLEAN btsnd_hcic_refresh_encryption_key (UINT16 handle)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_CMD_HANDLE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_CMD_HANDLE;
-    p->offset = 0;
-    UINT16_TO_STREAM (pp, HCI_REFRESH_ENCRYPTION_KEY);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_CMD_HANDLE);
-
-    UINT16_TO_STREAM (pp, handle);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
 /*************************
 ** End of Lisbon Commands
 **************************/
 
-BOOLEAN btsnd_hcic_read_local_ver (UINT8 local_controller_id)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_LOCAL_VERSION_INFO);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_local_supported_cmds (UINT8 local_controller_id)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_LOCAL_SUPPORTED_CMDS);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_local_features (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_LOCAL_FEATURES);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_local_ext_features (UINT8 page_num)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_LOCAL_EXT_FEATURES)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_LOCAL_EXT_FEATURES;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_LOCAL_EXT_FEATURES);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_LOCAL_EXT_FEATURES);
-
-    UINT8_TO_STREAM (pp, page_num);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_buffer_size (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_BUFFER_SIZE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_country_code (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_COUNTRY_CODE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_bd_addr (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_BD_ADDR);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_fail_contact_count (UINT8 local_controller_id, UINT16 handle)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_CMD_HANDLE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_CMD_HANDLE;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_FAILED_CONTACT_COUNT);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_CMD_HANDLE);
-
-    UINT16_TO_STREAM (pp, handle);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_reset_fail_contact_count (UINT8 local_controller_id, UINT16 handle)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_CMD_HANDLE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_CMD_HANDLE;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_RESET_FAILED_CONTACT_COUNT);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_CMD_HANDLE);
-
-    UINT16_TO_STREAM (pp, handle);
-
-    btu_hcif_send_cmd (local_controller_id,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_get_link_quality (UINT16 handle)
 {
     BT_HDR *p;
@@ -2967,48 +1697,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_loopback_mode (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_LOOPBACK_MODE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_write_loopback_mode (UINT8 mode)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_PARAM1)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_PARAM1;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_LOOPBACK_MODE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_PARAM1);
-
-    UINT8_TO_STREAM (pp, mode);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_enable_test_mode (void)
 {
     BT_HDR *p;
@@ -3029,173 +1717,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_write_afh_channel_assessment_mode (UINT8 mode)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_WRITE_PARAM1)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_PARAM1;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_WRITE_AFH_ASSESSMENT_MODE);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_WRITE_PARAM1);
-
-    UINT8_TO_STREAM  (pp, mode);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_afh_channel_assessment_mode(void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_AFH_ASSESSMENT_MODE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_set_afh_channels (UINT8 first, UINT8 last)
-{
-    BT_HDR *p;
-    UINT8  *pp;
-    UINT8  channels[10] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F};
-    int    i;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_SET_AFH_CHANNELS)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_SET_AFH_CHANNELS;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_SET_AFH_CHANNELS);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_SET_AFH_CHANNELS);
-
-    /* Just make sure that caller did not exceed 79 Bluetooth channels */
-    if ((first <= last) && (last <= 78))
-    {
-        for (i = first; i <= last; i++)
-        {
-            int byte_offset = i / 8;
-            int bit_offset  = i % 8;
-            channels[byte_offset] &= ~(1 << bit_offset);
-        }
-    }
-    for (i = 0; i < 10; i++)
-        *pp++ = channels[i];
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_set_afh_host_channel_class (UINT8 *p_afhchannelmap)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-    int    i;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_SET_AFH_CHANNELS)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_SET_AFH_CHANNELS;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_SET_AFH_CHANNELS);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_SET_AFH_CHANNELS);
-
-    /* Copy and convert */
-    for (i = 0; i < 10; i++)
-        *pp++ = p_afhchannelmap[9-i];
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_afh_channel_map (UINT16 handle)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_CMD_HANDLE)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_CMD_HANDLE;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_AFH_CH_MAP);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_CMD_HANDLE);
-
-    UINT16_TO_STREAM (pp, handle);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_clock (UINT16 handle, UINT8 which_clock)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CLOCK)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CLOCK;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_CLOCK);
-    UINT8_TO_STREAM  (pp, HCIC_PARAM_SIZE_READ_CLOCK);
-
-    UINT16_TO_STREAM (pp, handle);
-    UINT8_TO_STREAM  (pp, which_clock);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
-BOOLEAN btsnd_hcic_read_inqscan_type(void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_INQSCAN_TYPE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_inqscan_type (UINT8 type)
 {
     BT_HDR *p;
@@ -3218,26 +1739,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_inquiry_mode (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_INQUIRY_MODE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_inquiry_mode (UINT8 mode)
 {
     BT_HDR *p;
@@ -3260,26 +1761,6 @@
     return (TRUE);
 }
 
-BOOLEAN btsnd_hcic_read_pagescan_type (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_READ_PAGESCAN_TYPE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
 BOOLEAN btsnd_hcic_write_pagescan_type (UINT8 type)
 {
     BT_HDR *p;
@@ -3303,7 +1784,7 @@
 }
 
 /* Must have room to store BT_HDR + max VSC length + callback pointer */
-#if !defined (LMP_TEST) && (HCI_CMD_POOL_BUF_SIZE < 268)
+#if (HCI_CMD_POOL_BUF_SIZE < 268)
 #error "HCI_CMD_POOL_BUF_SIZE must be larger than 268"
 #endif
 
@@ -3325,41 +1806,3 @@
 
     btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
 }
-
-void btsnd_hcic_data (BT_HDR *p_buf, UINT16 len, UINT16 handle, UINT8 boundary, UINT8 broadcast)
-{
-    UINT8   *p;
-
-    /* Higher layer should have left 4 bytes for us to fill the header */
-    p_buf->offset -= 4;
-    p_buf->len    += 4;
-
-    /* Find the pointer to the beginning of the data */
-    p = (UINT8 *)(p_buf + 1) + p_buf->offset;
-
-    UINT16_TO_STREAM (p, handle | ((boundary & 3) << 12) | ((broadcast & 3) << 14));
-    UINT16_TO_STREAM (p, len);
-
-    HCI_ACL_DATA_TO_LOWER (p_buf);
-}
-
-BOOLEAN btsnd_hcic_nop (void)
-{
-    BT_HDR *p;
-    UINT8 *pp;
-
-    if ((p = HCI_GET_CMD_BUF(HCIC_PARAM_SIZE_READ_CMD)) == NULL)
-        return (FALSE);
-
-    pp = (UINT8 *)(p + 1);
-
-    p->len    = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_READ_CMD;
-    p->offset = 0;
-
-    UINT16_TO_STREAM (pp, HCI_COMMAND_NONE);
-    UINT8_TO_STREAM  (pp,  HCIC_PARAM_SIZE_READ_CMD);
-
-    btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
-    return (TRUE);
-}
-
diff --git a/stack/hid/hidh_conn.c b/stack/hid/hidh_conn.c
index 3a354cc..d8b619d 100644
--- a/stack/hid/hidh_conn.c
+++ b/stack/hid/hidh_conn.c
@@ -321,9 +321,7 @@
 {
     tHID_HOST_DEV_CTB *p_dev = (tHID_HOST_DEV_CTB *) p_ref_data;
     UINT8 dhandle;
-#if (HID_HOST_MAX_CONN_RETRY > 0)
-    UINT32 cb_res = HID_ERR_AUTH_FAILED;
-#endif
+    UINT32 reason;
     UNUSED(bd_addr);
     UNUSED (transport);
 
@@ -350,8 +348,6 @@
                 hidh_conn_retry (dhandle);
                 return;
             }
-            else
-                cb_res = HID_L2CAP_CONN_FAIL | HCI_ERR_PAGE_TIMEOUT ;
         }
 #endif
         p_dev->conn.disc_reason = HID_ERR_AUTH_FAILED;      /* Save reason for disconnecting */
@@ -456,13 +452,11 @@
 {
     UINT8 dhandle;
     tHID_CONN    *p_hcon = NULL;
-    tHID_HOST_DEV_CTB *p_dev;
     UINT32  reason;
 
     /* Find CCB based on CID */
     if( (dhandle = find_conn_by_cid(l2cap_cid)) < HID_HOST_MAX_DEVICES )
     {
-        p_dev = &hh_cb.devices[dhandle];
         p_hcon = &hh_cb.devices[dhandle].conn;
     }
 
diff --git a/stack/hid/hidh_int.h b/stack/hid/hidh_int.h
index ad07412..3fedea2 100644
--- a/stack/hid/hidh_int.h
+++ b/stack/hid/hidh_int.h
@@ -80,9 +80,9 @@
 ** Main Control Block
 *******************************************************************************/
 #if HID_DYNAMIC_MEMORY == FALSE
-HID_API extern tHID_HOST_CTB  hh_cb;
+extern tHID_HOST_CTB  hh_cb;
 #else
-HID_API extern tHID_HOST_CTB *hidh_cb_ptr;
+extern tHID_HOST_CTB *hidh_cb_ptr;
 #define hh_cb (*hidh_cb_ptr)
 #endif
 
@@ -91,4 +91,3 @@
 #endif
 
 #endif
-
diff --git a/stack/include/a2d_api.h b/stack/include/a2d_api.h
index f21ba6c..f786670 100644
--- a/stack/include/a2d_api.h
+++ b/stack/include/a2d_api.h
@@ -163,7 +163,7 @@
 **                  A2D_FAIL if function execution failed.
 **
 ******************************************************************************/
-A2D_API extern tA2D_STATUS A2D_AddRecord(UINT16 service_uuid, char *p_service_name, char *p_provider_name,
+extern tA2D_STATUS A2D_AddRecord(UINT16 service_uuid, char *p_service_name, char *p_provider_name,
         UINT16 features, UINT32 sdp_handle);
 
 /******************************************************************************
@@ -201,8 +201,8 @@
 **                  A2D_FAIL if function execution failed.
 **
 ******************************************************************************/
-A2D_API extern tA2D_STATUS A2D_FindService(UINT16 service_uuid, BD_ADDR bd_addr,
-                        tA2D_SDP_DB_PARAMS *p_db, tA2D_FIND_CBACK *p_cback);
+extern tA2D_STATUS A2D_FindService(UINT16 service_uuid, BD_ADDR bd_addr,
+                                   tA2D_SDP_DB_PARAMS *p_db, tA2D_FIND_CBACK *p_cback);
 
 /******************************************************************************
 **
@@ -225,7 +225,7 @@
 **                  the input parameter is 0xff.
 **
 ******************************************************************************/
-A2D_API extern UINT8 A2D_SetTraceLevel (UINT8 new_level);
+extern UINT8 A2D_SetTraceLevel (UINT8 new_level);
 
 /******************************************************************************
 ** Function         A2D_BitsSet
@@ -235,7 +235,7 @@
 **                  A2D_SET_ZERO_BIT, if all bits clear
 **                  A2D_SET_MULTL_BIT, if multiple bits are set
 ******************************************************************************/
-A2D_API extern UINT8 A2D_BitsSet(UINT8 num);
+extern UINT8 A2D_BitsSet(UINT8 num);
 
 #ifdef __cplusplus
 }
@@ -252,6 +252,6 @@
 ** Returns          void
 **
 *******************************************************************************/
-A2D_API extern void A2D_Init(void);
+extern void A2D_Init(void);
 
 #endif /* A2D_API_H */
diff --git a/stack/include/a2d_sbc.h b/stack/include/a2d_sbc.h
index dad0b8b..a7beb73 100644
--- a/stack/include/a2d_sbc.h
+++ b/stack/include/a2d_sbc.h
@@ -101,7 +101,7 @@
 **
 ** Returns          nothing.
 ******************************************************************************/
-A2D_API extern void A2D_SbcChkFrInit(UINT8 *p_pkt);
+extern void A2D_SbcChkFrInit(UINT8 *p_pkt);
 
 /******************************************************************************
 **
@@ -111,7 +111,7 @@
 **
 ** Returns          nothing.
 ******************************************************************************/
-A2D_API extern void A2D_SbcDescramble(UINT8 *p_pkt, UINT16 len);
+extern void A2D_SbcDescramble(UINT8 *p_pkt, UINT16 len);
 
 /******************************************************************************
 **
@@ -131,8 +131,8 @@
 ** Returns          A2D_SUCCESS if function execution succeeded.
 **                  Error status code, otherwise.
 ******************************************************************************/
-A2D_API extern tA2D_STATUS A2D_BldSbcInfo(UINT8 media_type, tA2D_SBC_CIE *p_ie,
-                                          UINT8 *p_result);
+extern tA2D_STATUS A2D_BldSbcInfo(UINT8 media_type, tA2D_SBC_CIE *p_ie,
+                                  UINT8 *p_result);
 
 /******************************************************************************
 **
@@ -152,8 +152,8 @@
 ** Returns          A2D_SUCCESS if function execution succeeded.
 **                  Error status code, otherwise.
 ******************************************************************************/
-A2D_API extern tA2D_STATUS A2D_ParsSbcInfo(tA2D_SBC_CIE *p_ie, UINT8 *p_info,
-                                           BOOLEAN for_caps);
+extern tA2D_STATUS A2D_ParsSbcInfo(tA2D_SBC_CIE *p_ie, UINT8 *p_info,
+                                   BOOLEAN for_caps);
 
 /******************************************************************************
 **
@@ -177,8 +177,8 @@
 **
 ** Returns          void.
 ******************************************************************************/
-A2D_API extern void A2D_BldSbcMplHdr(UINT8 *p_dst, BOOLEAN frag, BOOLEAN start,
-                                     BOOLEAN last, UINT8 num);
+extern void A2D_BldSbcMplHdr(UINT8 *p_dst, BOOLEAN frag, BOOLEAN start,
+                             BOOLEAN last, UINT8 num);
 
 /******************************************************************************
 **
@@ -202,9 +202,9 @@
 **
 ** Returns          void.
 ******************************************************************************/
-A2D_API extern void A2D_ParsSbcMplHdr(UINT8 *p_src, BOOLEAN *p_frag,
-                                      BOOLEAN *p_start, BOOLEAN *p_last,
-                                      UINT8 *p_num);
+extern void A2D_ParsSbcMplHdr(UINT8 *p_src, BOOLEAN *p_frag,
+                              BOOLEAN *p_start, BOOLEAN *p_last,
+                              UINT8 *p_num);
 #ifdef __cplusplus
 }
 #endif
diff --git a/stack/include/avct_api.h b/stack/include/avct_api.h
index 2880011..001ca1b 100644
--- a/stack/include/avct_api.h
+++ b/stack/include/avct_api.h
@@ -138,7 +138,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVCT_API extern void AVCT_Register(UINT16 mtu, UINT16 mtu_br, UINT8 sec_mask);
+extern void AVCT_Register(UINT16 mtu, UINT16 mtu_br, UINT8 sec_mask);
 
 /*******************************************************************************
 **
@@ -154,7 +154,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVCT_API extern void AVCT_Deregister(void);
+extern void AVCT_Deregister(void);
 
 /*******************************************************************************
 **
@@ -172,8 +172,8 @@
 ** Returns          AVCT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVCT_API extern UINT16 AVCT_CreateConn(UINT8 *p_handle, tAVCT_CC *p_cc,
-                                       BD_ADDR peer_addr);
+extern UINT16 AVCT_CreateConn(UINT8 *p_handle, tAVCT_CC *p_cc,
+                              BD_ADDR peer_addr);
 
 /*******************************************************************************
 **
@@ -188,7 +188,7 @@
 ** Returns          AVCT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVCT_API extern UINT16 AVCT_RemoveConn(UINT8 handle);
+extern UINT16 AVCT_RemoveConn(UINT8 handle);
 
 /*******************************************************************************
 **
@@ -206,7 +206,7 @@
 ** Returns          AVCT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVCT_API extern UINT16 AVCT_CreateBrowse(UINT8 handle, UINT8 role);
+extern UINT16 AVCT_CreateBrowse(UINT8 handle, UINT8 role);
 
 /*******************************************************************************
 **
@@ -221,7 +221,7 @@
 ** Returns          AVCT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVCT_API extern UINT16 AVCT_RemoveBrowse(UINT8 handle);
+extern UINT16 AVCT_RemoveBrowse(UINT8 handle);
 
 /*******************************************************************************
 **
@@ -233,7 +233,7 @@
 ** Returns          the peer browsing channel MTU.
 **
 *******************************************************************************/
-AVCT_API extern UINT16 AVCT_GetBrowseMtu (UINT8 handle);
+extern UINT16 AVCT_GetBrowseMtu (UINT8 handle);
 
 /*******************************************************************************
 **
@@ -245,7 +245,7 @@
 ** Returns          the peer MTU size.
 **
 *******************************************************************************/
-AVCT_API extern UINT16 AVCT_GetPeerMtu (UINT8 handle);
+extern UINT16 AVCT_GetPeerMtu (UINT8 handle);
 
 /*******************************************************************************
 **
@@ -268,7 +268,7 @@
 ** Returns          AVCT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVCT_API extern UINT16 AVCT_MsgReq(UINT8 handle, UINT8 label, UINT8 cr, BT_HDR *p_msg);
+extern UINT16 AVCT_MsgReq(UINT8 handle, UINT8 label, UINT8 cr, BT_HDR *p_msg);
 
 #ifdef __cplusplus
 }
@@ -276,4 +276,3 @@
 
 
 #endif /* AVCT_API_H */
-
diff --git a/stack/include/avdt_api.h b/stack/include/avdt_api.h
index 93ed6ae..a9613c0 100644
--- a/stack/include/avdt_api.h
+++ b/stack/include/avdt_api.h
@@ -437,7 +437,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDT_Register(tAVDT_REG *p_reg, tAVDT_CTRL_CBACK *p_cback);
+extern void AVDT_Register(tAVDT_REG *p_reg, tAVDT_CTRL_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -452,7 +452,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDT_Deregister(void);
+extern void AVDT_Deregister(void);
 
 
 /*******************************************************************************
@@ -467,7 +467,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDT_SINK_Activate(void);
+extern void AVDT_SINK_Activate(void);
 
 /*******************************************************************************
 **
@@ -481,7 +481,7 @@
 ** Returns          void.
 **
 *******************************************************************************/
-AVDT_API extern void AVDT_SINK_Deactivate(void);
+extern void AVDT_SINK_Deactivate(void);
 
 /*******************************************************************************
 **
@@ -497,7 +497,7 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_CreateStream(UINT8 *p_handle, tAVDT_CS *p_cs);
+extern UINT16 AVDT_CreateStream(UINT8 *p_handle, tAVDT_CS *p_cs);
 
 /*******************************************************************************
 **
@@ -513,7 +513,7 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_RemoveStream(UINT8 handle);
+extern UINT16 AVDT_RemoveStream(UINT8 handle);
 
 /*******************************************************************************
 **
@@ -541,8 +541,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_DiscoverReq(BD_ADDR bd_addr, tAVDT_SEP_INFO *p_sep_info,
-                                        UINT8 max_seps, tAVDT_CTRL_CBACK *p_cback);
+extern UINT16 AVDT_DiscoverReq(BD_ADDR bd_addr, tAVDT_SEP_INFO *p_sep_info,
+                               UINT8 max_seps, tAVDT_CTRL_CBACK *p_cback);
 
 
 /*******************************************************************************
@@ -569,8 +569,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_GetCapReq(BD_ADDR bd_addr, UINT8 seid, tAVDT_CFG *p_cfg,
-                                      tAVDT_CTRL_CBACK *p_cback);
+extern UINT16 AVDT_GetCapReq(BD_ADDR bd_addr, UINT8 seid, tAVDT_CFG *p_cfg,
+                             tAVDT_CTRL_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -596,8 +596,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_GetAllCapReq(BD_ADDR bd_addr, UINT8 seid, tAVDT_CFG *p_cfg,
-                                      tAVDT_CTRL_CBACK *p_cback);
+extern UINT16 AVDT_GetAllCapReq(BD_ADDR bd_addr, UINT8 seid, tAVDT_CFG *p_cfg,
+                                tAVDT_CTRL_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -610,7 +610,7 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_DelayReport(UINT8 handle, UINT8 seid, UINT16 delay);
+extern UINT16 AVDT_DelayReport(UINT8 handle, UINT8 seid, UINT16 delay);
 
 /*******************************************************************************
 **
@@ -625,8 +625,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_OpenReq(UINT8 handle, BD_ADDR bd_addr, UINT8 seid,
-                                    tAVDT_CFG *p_cfg);
+extern UINT16 AVDT_OpenReq(UINT8 handle, BD_ADDR bd_addr, UINT8 seid,
+                           tAVDT_CFG *p_cfg);
 
 
 /*******************************************************************************
@@ -641,8 +641,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_ConfigRsp(UINT8 handle, UINT8 label, UINT8 error_code,
-                                      UINT8 category);
+extern UINT16 AVDT_ConfigRsp(UINT8 handle, UINT8 label, UINT8 error_code,
+                             UINT8 category);
 
 /*******************************************************************************
 **
@@ -658,7 +658,7 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_StartReq(UINT8 *p_handles, UINT8 num_handles);
+extern UINT16 AVDT_StartReq(UINT8 *p_handles, UINT8 num_handles);
 
 /*******************************************************************************
 **
@@ -675,7 +675,7 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_SuspendReq(UINT8 *p_handles, UINT8 num_handles);
+extern UINT16 AVDT_SuspendReq(UINT8 *p_handles, UINT8 num_handles);
 
 /*******************************************************************************
 **
@@ -691,7 +691,7 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_CloseReq(UINT8 handle);
+extern UINT16 AVDT_CloseReq(UINT8 handle);
 
 /*******************************************************************************
 **
@@ -709,7 +709,7 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_ReconfigReq(UINT8 handle, tAVDT_CFG *p_cfg);
+extern UINT16 AVDT_ReconfigReq(UINT8 handle, tAVDT_CFG *p_cfg);
 
 /*******************************************************************************
 **
@@ -723,8 +723,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_ReconfigRsp(UINT8 handle, UINT8 label, UINT8 error_code,
-                                        UINT8 category);
+extern UINT16 AVDT_ReconfigRsp(UINT8 handle, UINT8 label, UINT8 error_code,
+                               UINT8 category);
 
 /*******************************************************************************
 **
@@ -740,7 +740,7 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_SecurityReq(UINT8 handle, UINT8 *p_data, UINT16 len);
+extern UINT16 AVDT_SecurityReq(UINT8 handle, UINT8 *p_data, UINT16 len);
 
 /*******************************************************************************
 **
@@ -756,8 +756,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_SecurityRsp(UINT8 handle, UINT8 label, UINT8 error_code,
-                                        UINT8 *p_data, UINT16 len);
+extern UINT16 AVDT_SecurityRsp(UINT8 handle, UINT8 label, UINT8 error_code,
+                               UINT8 *p_data, UINT16 len);
 
 /*******************************************************************************
 **
@@ -792,8 +792,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_WriteReq(UINT8 handle, BT_HDR *p_pkt, UINT32 time_stamp,
-                                     UINT8 m_pt);
+extern UINT16 AVDT_WriteReq(UINT8 handle, BT_HDR *p_pkt, UINT32 time_stamp,
+                            UINT8 m_pt);
 /*******************************************************************************
 **
 ** Function         AVDT_WriteReqOpt
@@ -830,8 +830,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_WriteReqOpt(UINT8 handle, BT_HDR *p_pkt, UINT32 time_stamp,
-                                     UINT8 m_pt, tAVDT_DATA_OPT_MASK opt);
+extern UINT16 AVDT_WriteReqOpt(UINT8 handle, BT_HDR *p_pkt, UINT32 time_stamp,
+                               UINT8 m_pt, tAVDT_DATA_OPT_MASK opt);
 
 /*******************************************************************************
 **
@@ -848,8 +848,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_ConnectReq(BD_ADDR bd_addr, UINT8 sec_mask,
-                                       tAVDT_CTRL_CBACK *p_cback);
+extern UINT16 AVDT_ConnectReq(BD_ADDR bd_addr, UINT8 sec_mask,
+                              tAVDT_CTRL_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -863,7 +863,7 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_DisconnectReq(BD_ADDR bd_addr, tAVDT_CTRL_CBACK *p_cback);
+extern UINT16 AVDT_DisconnectReq(BD_ADDR bd_addr, tAVDT_CTRL_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -874,7 +874,7 @@
 ** Returns          CID if successful, otherwise 0.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_GetL2CapChannel(UINT8 handle);
+extern UINT16 AVDT_GetL2CapChannel(UINT8 handle);
 
 /*******************************************************************************
 **
@@ -885,7 +885,7 @@
 ** Returns          CID if successful, otherwise 0.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_GetSignalChannel(UINT8 handle, BD_ADDR bd_addr);
+extern UINT16 AVDT_GetSignalChannel(UINT8 handle, BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -908,8 +908,8 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_WriteDataReq(UINT8 handle, UINT8 *p_data, UINT32 data_len,
-                                     UINT32 time_stamp, UINT8 m_pt, UINT8 marker);
+extern UINT16 AVDT_WriteDataReq(UINT8 handle, UINT8 *p_data, UINT32 data_len,
+                                UINT32 time_stamp, UINT8 m_pt, UINT8 marker);
 
 /*******************************************************************************
 **
@@ -929,7 +929,7 @@
 ** Returns          AVDT_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_SetMediaBuf(UINT8 handle, UINT8 *p_buf, UINT32 buf_len);
+extern UINT16 AVDT_SetMediaBuf(UINT8 handle, UINT8 *p_buf, UINT32 buf_len);
 
 /*******************************************************************************
 **
@@ -942,8 +942,8 @@
 ** Returns
 **
 *******************************************************************************/
-AVDT_API extern UINT16 AVDT_SendReport(UINT8 handle, AVDT_REPORT_TYPE type,
-                       tAVDT_REPORT_DATA *p_data);
+extern UINT16 AVDT_SendReport(UINT8 handle, AVDT_REPORT_TYPE type,
+                              tAVDT_REPORT_DATA *p_data);
 
 /******************************************************************************
 **
@@ -966,7 +966,7 @@
 **                  the input parameter is 0xff.
 **
 ******************************************************************************/
-AVDT_API extern UINT8 AVDT_SetTraceLevel (UINT8 new_level);
+extern UINT8 AVDT_SetTraceLevel (UINT8 new_level);
 
 #ifdef __cplusplus
 }
diff --git a/stack/include/avdtc_api.h b/stack/include/avdtc_api.h
index 14a1a21..96b20e7 100644
--- a/stack/include/avdtc_api.h
+++ b/stack/include/avdtc_api.h
@@ -76,7 +76,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_Init(tAVDTC_CTRL_CBACK *p_cback);
+extern void AVDTC_Init(tAVDTC_CTRL_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -87,8 +87,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_DiscoverRsp(BD_ADDR bd_addr, UINT8 label,
-                                     tAVDT_SEP_INFO sep_info[], UINT8 num_seps);
+extern void AVDTC_DiscoverRsp(BD_ADDR bd_addr, UINT8 label,
+                              tAVDT_SEP_INFO sep_info[], UINT8 num_seps);
 
 /*******************************************************************************
 **
@@ -99,7 +99,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_GetCapRsp(BD_ADDR bd_addr, UINT8 label, tAVDT_CFG *p_cap);
+extern void AVDTC_GetCapRsp(BD_ADDR bd_addr, UINT8 label, tAVDT_CFG *p_cap);
 
 /*******************************************************************************
 **
@@ -110,7 +110,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_GetAllCapRsp(BD_ADDR bd_addr, UINT8 label, tAVDT_CFG *p_cap);
+extern void AVDTC_GetAllCapRsp(BD_ADDR bd_addr, UINT8 label, tAVDT_CFG *p_cap);
 
 /*******************************************************************************
 **
@@ -121,7 +121,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_GetConfigReq(UINT8 handle);
+extern void AVDTC_GetConfigReq(UINT8 handle);
 
 /*******************************************************************************
 **
@@ -132,7 +132,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_GetConfigRsp(UINT8 handle, UINT8 label, tAVDT_CFG *p_cfg);
+extern void AVDTC_GetConfigRsp(UINT8 handle, UINT8 label, tAVDT_CFG *p_cfg);
 
 /*******************************************************************************
 **
@@ -143,7 +143,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_OpenReq(UINT8 handle);
+extern void AVDTC_OpenReq(UINT8 handle);
 
 /*******************************************************************************
 **
@@ -154,7 +154,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_OpenRsp(UINT8 handle, UINT8 label);
+extern void AVDTC_OpenRsp(UINT8 handle, UINT8 label);
 
 /*******************************************************************************
 **
@@ -165,7 +165,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_StartRsp(UINT8 *p_handles, UINT8 num_handles, UINT8 label);
+extern void AVDTC_StartRsp(UINT8 *p_handles, UINT8 num_handles, UINT8 label);
 
 /*******************************************************************************
 **
@@ -176,7 +176,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_CloseRsp(UINT8 handle, UINT8 label);
+extern void AVDTC_CloseRsp(UINT8 handle, UINT8 label);
 
 /*******************************************************************************
 **
@@ -187,7 +187,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_SuspendRsp(UINT8 *p_handles, UINT8 num_handles, UINT8 label);
+extern void AVDTC_SuspendRsp(UINT8 *p_handles, UINT8 num_handles, UINT8 label);
 
 /*******************************************************************************
 **
@@ -198,7 +198,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_AbortReq(UINT8 handle);
+extern void AVDTC_AbortReq(UINT8 handle);
 
 /*******************************************************************************
 **
@@ -209,7 +209,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_AbortRsp(UINT8 handle, UINT8 label);
+extern void AVDTC_AbortRsp(UINT8 handle, UINT8 label);
 
 /*******************************************************************************
 **
@@ -220,12 +220,11 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVDT_API extern void AVDTC_Rej(UINT8 handle, BD_ADDR bd_addr, UINT8 cmd, UINT8 label,
-                             UINT8 err_code, UINT8 err_param);
+extern void AVDTC_Rej(UINT8 handle, BD_ADDR bd_addr, UINT8 cmd, UINT8 label,
+                      UINT8 err_code, UINT8 err_param);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif /* AVDT_CAPI_H */
-
diff --git a/stack/include/avrc_api.h b/stack/include/avrc_api.h
index cc6db7f..2198074 100644
--- a/stack/include/avrc_api.h
+++ b/stack/include/avrc_api.h
@@ -89,6 +89,9 @@
  * send messages. */
 #define AVRC_BROWSE_UNCONG_IND_EVT     7
 
+/* AVRC_CMD_TIMEOUT_EVT event indicates timeout waiting for AVRC command response from the peer */
+#define AVRC_CMD_TIMEOUT_EVT           8
+
 /* Supported categories */
 #define AVRC_SUPF_CT_CAT1               0x0001      /* Category 1 */
 #define AVRC_SUPF_CT_CAT2               0x0002      /* Category 2 */
@@ -200,7 +203,7 @@
 **                  AVRC_NO_RESOURCES if not enough resources to build the SDP record.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_AddRecord(UINT16 service_uuid, char *p_service_name,
+extern UINT16 AVRC_AddRecord(UINT16 service_uuid, char *p_service_name,
                 char *p_provider_name, UINT16 categories, UINT32 sdp_handle);
 
 /******************************************************************************
@@ -240,8 +243,8 @@
 **                                    perform the service search.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_FindService(UINT16 service_uuid, BD_ADDR bd_addr,
-                tAVRC_SDP_DB_PARAMS *p_db, tAVRC_FIND_CBACK *p_cback);
+extern UINT16 AVRC_FindService(UINT16 service_uuid, BD_ADDR bd_addr,
+                               tAVRC_SDP_DB_PARAMS *p_db, tAVRC_FIND_CBACK *p_cback);
 
 /******************************************************************************
 **
@@ -288,8 +291,8 @@
 **                  the connection.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_Open(UINT8 *p_handle, tAVRC_CONN_CB *p_ccb,
-                                 BD_ADDR_PTR peer_addr);
+extern UINT16 AVRC_Open(UINT8 *p_handle, tAVRC_CONN_CB *p_ccb,
+                        BD_ADDR_PTR peer_addr);
 
 /******************************************************************************
 **
@@ -309,7 +312,7 @@
 **                  AVRC_BAD_HANDLE if handle is invalid.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_Close(UINT8 handle);
+extern UINT16 AVRC_Close(UINT8 handle);
 
 /******************************************************************************
 **
@@ -325,7 +328,7 @@
 **                  the connection.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_OpenBrowse(UINT8 handle, UINT8 conn_role);
+extern UINT16 AVRC_OpenBrowse(UINT8 handle, UINT8 conn_role);
 
 /******************************************************************************
 **
@@ -339,7 +342,7 @@
 **                  AVRC_BAD_HANDLE if handle is invalid.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_CloseBrowse(UINT8 handle);
+extern UINT16 AVRC_CloseBrowse(UINT8 handle);
 
 /******************************************************************************
 **
@@ -357,7 +360,7 @@
 **                  AVRC_BAD_HANDLE if handle is invalid.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_MsgReq (UINT8 handle, UINT8 label, UINT8 ctype, BT_HDR *p_pkt);
+extern UINT16 AVRC_MsgReq (UINT8 handle, UINT8 label, UINT8 ctype, BT_HDR *p_pkt);
 
 /******************************************************************************
 **
@@ -380,7 +383,7 @@
 **                  AVRC_BAD_HANDLE if handle is invalid.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_UnitCmd(UINT8 handle, UINT8 label);
+extern UINT16 AVRC_UnitCmd(UINT8 handle, UINT8 label);
 
 /******************************************************************************
 **
@@ -407,7 +410,7 @@
 **                  AVRC_BAD_HANDLE if handle is invalid.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_SubCmd(UINT8 handle, UINT8 label, UINT8 page);
+extern UINT16 AVRC_SubCmd(UINT8 handle, UINT8 label, UINT8 page);
 
 
 /******************************************************************************
@@ -433,7 +436,7 @@
 **                  AVRC_BAD_HANDLE if handle is invalid.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_PassCmd(UINT8 handle, UINT8 label, tAVRC_MSG_PASS *p_msg);
+extern UINT16 AVRC_PassCmd(UINT8 handle, UINT8 label, tAVRC_MSG_PASS *p_msg);
 
 /******************************************************************************
 **
@@ -460,7 +463,7 @@
 **                  AVRC_BAD_HANDLE if handle is invalid.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_PassRsp(UINT8 handle, UINT8 label, tAVRC_MSG_PASS *p_msg);
+extern UINT16 AVRC_PassRsp(UINT8 handle, UINT8 label, tAVRC_MSG_PASS *p_msg);
 
 
 /******************************************************************************
@@ -486,7 +489,7 @@
 **                  AVRC_BAD_HANDLE if handle is invalid.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_VendorCmd(UINT8  handle, UINT8  label, tAVRC_MSG_VENDOR *p_msg);
+extern UINT16 AVRC_VendorCmd(UINT8  handle, UINT8  label, tAVRC_MSG_VENDOR *p_msg);
 
 
 /******************************************************************************
@@ -514,7 +517,7 @@
 **                  AVRC_BAD_HANDLE if handle is invalid.
 **
 ******************************************************************************/
-AVRC_API extern UINT16 AVRC_VendorRsp(UINT8  handle, UINT8  label, tAVRC_MSG_VENDOR *p_msg);
+extern UINT16 AVRC_VendorRsp(UINT8  handle, UINT8  label, tAVRC_MSG_VENDOR *p_msg);
 
 
 /******************************************************************************
@@ -538,7 +541,7 @@
 **                  the input parameter is 0xff.
 **
 ******************************************************************************/
-AVRC_API extern UINT8 AVRC_SetTraceLevel (UINT8 new_level);
+extern UINT8 AVRC_SetTraceLevel (UINT8 new_level);
 
 /*******************************************************************************
 **
@@ -551,7 +554,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-AVRC_API extern void AVRC_Init(void);
+extern void AVRC_Init(void);
 
 /*******************************************************************************
 **
@@ -563,8 +566,8 @@
 **                  Otherwise, the error code defined by AVRCP 1.4
 **
 *******************************************************************************/
-AVRC_API extern tAVRC_STS AVRC_ParsCommand (tAVRC_MSG *p_msg, tAVRC_COMMAND *p_result,
-    UINT8 *p_buf, UINT16 buf_len);
+extern tAVRC_STS AVRC_ParsCommand (tAVRC_MSG *p_msg, tAVRC_COMMAND *p_result,
+                                   UINT8 *p_buf, UINT16 buf_len);
 
 /*******************************************************************************
 **
@@ -576,8 +579,8 @@
 **                  Otherwise, the error code defined by AVRCP 1.4
 **
 *******************************************************************************/
-AVRC_API extern tAVRC_STS AVRC_ParsResponse (tAVRC_MSG *p_msg, tAVRC_RESPONSE *p_result,
-    UINT8 *p_buf, UINT16 buf_len);
+extern tAVRC_STS AVRC_ParsResponse (tAVRC_MSG *p_msg, tAVRC_RESPONSE *p_result,
+                                    UINT8 *p_buf, UINT16 buf_len);
 
 /*******************************************************************************
 **
@@ -590,7 +593,7 @@
 **                  Otherwise, the error code.
 **
 *******************************************************************************/
-AVRC_API extern tAVRC_STS AVRC_BldCommand( tAVRC_COMMAND *p_cmd, BT_HDR **pp_pkt);
+extern tAVRC_STS AVRC_BldCommand( tAVRC_COMMAND *p_cmd, BT_HDR **pp_pkt);
 
 /*******************************************************************************
 **
@@ -603,7 +606,7 @@
 **                  Otherwise, the error code.
 **
 *******************************************************************************/
-AVRC_API extern tAVRC_STS AVRC_BldResponse( UINT8 handle, tAVRC_RESPONSE *p_rsp, BT_HDR **pp_pkt);
+extern tAVRC_STS AVRC_BldResponse( UINT8 handle, tAVRC_RESPONSE *p_rsp, BT_HDR **pp_pkt);
 
 /**************************************************************************
 **
@@ -615,7 +618,7 @@
 **
 **
 *******************************************************************************/
-AVRC_API extern BOOLEAN AVRC_IsValidAvcType(UINT8 pdu_id, UINT8 avc_type);
+extern BOOLEAN AVRC_IsValidAvcType(UINT8 pdu_id, UINT8 avc_type);
 
 /*******************************************************************************
 **
@@ -627,7 +630,7 @@
 ** Returns          returns TRUE if it is valid
 **
 *******************************************************************************/
-AVRC_API extern BOOLEAN AVRC_IsValidPlayerAttr(UINT8 attr);
+extern BOOLEAN AVRC_IsValidPlayerAttr(UINT8 attr);
 
 #ifdef __cplusplus
 }
diff --git a/stack/include/bnep_api.h b/stack/include/bnep_api.h
index b2bc0fd..3ca31d5 100644
--- a/stack/include/bnep_api.h
+++ b/stack/include/bnep_api.h
@@ -242,7 +242,7 @@
 **                  BNEP_FAILURE        if connection state callback is missing
 **
 *******************************************************************************/
-BNEP_API extern tBNEP_RESULT BNEP_Register (tBNEP_REGISTER *p_reg_info);
+extern tBNEP_RESULT BNEP_Register (tBNEP_REGISTER *p_reg_info);
 
 /*******************************************************************************
 **
@@ -257,7 +257,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BNEP_API extern void BNEP_Deregister (void);
+extern void BNEP_Deregister (void);
 
 
 /*******************************************************************************
@@ -276,10 +276,10 @@
 **                  BNEP_NO_RESOURCES           if no resources
 **
 *******************************************************************************/
-BNEP_API extern tBNEP_RESULT BNEP_Connect (BD_ADDR p_rem_bda,
-                                         tBT_UUID *src_uuid,
-                                         tBT_UUID *dst_uuid,
-                                         UINT16 *p_handle);
+extern tBNEP_RESULT BNEP_Connect (BD_ADDR p_rem_bda,
+                                  tBT_UUID *src_uuid,
+                                  tBT_UUID *dst_uuid,
+                                  UINT16 *p_handle);
 
 /*******************************************************************************
 **
@@ -296,7 +296,7 @@
 **                  BNEP_WRONG_STATE            if the responce is not expected
 **
 *******************************************************************************/
-BNEP_API extern tBNEP_RESULT BNEP_ConnectResp (UINT16 handle, tBNEP_RESULT resp);
+extern tBNEP_RESULT BNEP_ConnectResp (UINT16 handle, tBNEP_RESULT resp);
 
 /*******************************************************************************
 **
@@ -310,7 +310,7 @@
 **                  BNEP_WRONG_HANDLE           if no connection is not found
 **
 *******************************************************************************/
-BNEP_API extern tBNEP_RESULT BNEP_Disconnect (UINT16 handle);
+extern tBNEP_RESULT BNEP_Disconnect (UINT16 handle);
 
 /*******************************************************************************
 **
@@ -333,12 +333,12 @@
 **                  BNEP_SUCCESS            - If written successfully
 **
 *******************************************************************************/
-BNEP_API extern tBNEP_RESULT BNEP_WriteBuf (UINT16 handle,
-                                          UINT8 *p_dest_addr,
-                                          BT_HDR *p_buf,
-                                          UINT16 protocol,
-                                          UINT8 *p_src_addr,
-                                          BOOLEAN fw_ext_present);
+extern tBNEP_RESULT BNEP_WriteBuf (UINT16 handle,
+                                   UINT8 *p_dest_addr,
+                                   BT_HDR *p_buf,
+                                   UINT16 protocol,
+                                   UINT8 *p_src_addr,
+                                   BOOLEAN fw_ext_present);
 
 /*******************************************************************************
 **
@@ -362,13 +362,13 @@
 **                  BNEP_SUCCESS            - If written successfully
 **
 *******************************************************************************/
-BNEP_API extern tBNEP_RESULT  BNEP_Write (UINT16 handle,
-                                        UINT8 *p_dest_addr,
-                                        UINT8 *p_data,
-                                        UINT16 len,
-                                        UINT16 protocol,
-                                        UINT8 *p_src_addr,
-                                        BOOLEAN fw_ext_present);
+extern tBNEP_RESULT  BNEP_Write (UINT16 handle,
+                                 UINT8 *p_dest_addr,
+                                 UINT8 *p_data,
+                                 UINT16 len,
+                                 UINT16 protocol,
+                                 UINT8 *p_src_addr,
+                                 BOOLEAN fw_ext_present);
 
 /*******************************************************************************
 **
@@ -387,10 +387,10 @@
 **                  BNEP_SUCCESS                - if request sent successfully
 **
 *******************************************************************************/
-BNEP_API extern tBNEP_RESULT BNEP_SetProtocolFilters (UINT16 handle,
-                                                    UINT16 num_filters,
-                                                    UINT16 *p_start_array,
-                                                    UINT16 *p_end_array);
+extern tBNEP_RESULT BNEP_SetProtocolFilters (UINT16 handle,
+                                             UINT16 num_filters,
+                                             UINT16 *p_start_array,
+                                             UINT16 *p_end_array);
 
 /*******************************************************************************
 **
@@ -411,22 +411,10 @@
 **                  BNEP_SUCCESS                - if request sent successfully
 **
 *******************************************************************************/
-BNEP_API extern tBNEP_RESULT BNEP_SetMulticastFilters (UINT16 handle,
-                                                     UINT16 num_filters,
-                                                     UINT8 *p_start_array,
-                                                     UINT8 *p_end_array);
-
-/*******************************************************************************
-**
-** Function         BNEP_GetMyBdAddr
-**
-** Description      This function returns a pointer to the local device BD address.
-**                  If the BD address has not been read yet, it returns NULL.
-**
-** Returns          the BD address
-**
-*******************************************************************************/
-BNEP_API extern UINT8 *BNEP_GetMyBdAddr (void);
+extern tBNEP_RESULT BNEP_SetMulticastFilters (UINT16 handle,
+                                              UINT16 num_filters,
+                                              UINT8 *p_start_array,
+                                              UINT8 *p_end_array);
 
 /*******************************************************************************
 **
@@ -438,7 +426,7 @@
 ** Returns          the new (current) trace level
 **
 *******************************************************************************/
-BNEP_API extern UINT8 BNEP_SetTraceLevel (UINT8 new_level);
+extern UINT8 BNEP_SetTraceLevel (UINT8 new_level);
 
 /*******************************************************************************
 **
@@ -450,7 +438,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BNEP_API extern void BNEP_Init (void);
+extern void BNEP_Init (void);
 
 /*******************************************************************************
 **
@@ -464,7 +452,7 @@
 **                  BNEP_WRONG_STATE        - if not in connected state
 **
 *******************************************************************************/
-BNEP_API extern tBNEP_RESULT BNEP_GetStatus (UINT16 handle, tBNEP_STATUS *p_status);
+extern tBNEP_RESULT BNEP_GetStatus (UINT16 handle, tBNEP_STATUS *p_status);
 
 
 
diff --git a/stack/include/bt_types.h b/stack/include/bt_types.h
index 617eaf3..441cd17 100644
--- a/stack/include/bt_types.h
+++ b/stack/include/bt_types.h
@@ -19,14 +19,38 @@
 #ifndef BT_TYPES_H
 #define BT_TYPES_H
 
-#include "data_types.h"
+#include <stdint.h>
+#include <stdbool.h>
 
-#ifdef _WIN32
-#ifdef BLUESTACK_TESTER
-    #include "bte_stack_entry.h"
+#ifndef FALSE
+#  define FALSE  false
 #endif
+
+#ifndef TRUE
+#  define TRUE   true
 #endif
 
+typedef uint8_t UINT8;
+typedef uint16_t UINT16;
+typedef uint32_t UINT32;
+typedef uint64_t UINT64;
+
+typedef int8_t INT8;
+typedef int16_t INT16;
+typedef int32_t INT32;
+typedef bool BOOLEAN;
+
+#ifdef __arm
+#  define PACKED  __packed
+#  define INLINE  __inline
+#else
+#  define PACKED
+#  define INLINE
+#endif
+
+#define BCM_STRCPY_S(x1,x2,x3)      strcpy((x1),(x3))
+#define BCM_STRNCPY_S(x1,x2,x3,x4)  strncpy((x1),(x3),(x4))
+
 /* READ WELL !!
 **
 ** This section defines global events. These are events that cross layers.
@@ -87,15 +111,8 @@
 
 #define BT_EVT_TO_TCS_CMDS          0x3000
 
-#define BT_EVT_TO_OBX_CL_MSG        0x3100
-#define BT_EVT_TO_OBX_SR_MSG        0x3200
-
 #define BT_EVT_TO_CTP_CMDS          0x3300
 
-/* Obex Over L2CAP */
-#define BT_EVT_TO_OBX_CL_L2C_MSG    0x3400
-#define BT_EVT_TO_OBX_SR_L2C_MSG    0x3500
-
 /* ftp events */
 #define BT_EVT_TO_FTP_SRVR_CMDS     0x3600
 #define BT_EVT_TO_FTP_CLNT_CMDS     0x3700
@@ -109,16 +126,6 @@
 /* gap events */
 #define BT_EVT_TO_GAP_MSG           0x3b00
 
-/* start timer */
-#define BT_EVT_TO_START_TIMER       0x3c00
-
-/* stop timer */
-#define BT_EVT_TO_STOP_TIMER        0x3d00
-
-/* start quick timer */
-#define BT_EVT_TO_START_QUICK_TIMER 0x3e00
-
-
 /* for NFC                          */
                                                 /************************************/
 #define BT_EVT_TO_NFC_NCI           0x4000      /* NCI Command, Notification or Data*/
@@ -128,12 +135,6 @@
 
 #define BT_EVT_TO_NFCCSIM_NCI       0x4a00      /* events to NFCC simulation (NCI packets) */
 
-/* start timer */
-#define BT_EVT_TO_START_TIMER_ONESHOT 0x4c00
-
-/* stop timer */
-#define BT_EVT_TO_STOP_TIMER_ONESHOT  0x4d00
-
 /* HCISU Events */
 
 #define BT_EVT_HCISU                0x5000
@@ -196,11 +197,6 @@
 #define BT_EVT_BTIF                 0xA000
 #define BT_EVT_CONTEXT_SWITCH_EVT  (0x0001 | BT_EVT_BTIF)
 
-#define BT_EVT_TRIGGER_STACK_INIT   EVENT_MASK(APPL_EVT_0)
-#define BT_EVT_HARDWARE_INIT_FAIL   EVENT_MASK(APPL_EVT_1)
-
-#define BT_EVT_PRELOAD_CMPL         EVENT_MASK(APPL_EVT_6)
-
 /* Define the header of each buffer used in the Bluetooth stack.
 */
 typedef struct
@@ -269,6 +265,9 @@
 #define STREAM_TO_ARRAY(a, p, len) {register int ijk; for (ijk = 0; ijk < len; ijk++) ((UINT8 *) a)[ijk] = *p++;}
 #define REVERSE_STREAM_TO_ARRAY(a, p, len) {register int ijk; register UINT8 *_pa = (UINT8 *)a + len - 1; for (ijk = 0; ijk < len; ijk++) *_pa-- = *p++;}
 
+#define STREAM_SKIP_UINT8(p)  do { (p) += 1; } while (0)
+#define STREAM_SKIP_UINT16(p) do { (p) += 2; } while (0)
+
 /********************************************************************************
 ** Macros to get and put bytes to and from a field (Little Endian format).
 ** These are the same as to stream, except the pointer is not incremented.
@@ -568,8 +567,6 @@
 #define TRACE_LAYER_OBEX            0x000c0000
 #define TRACE_LAYER_BTM             0x000d0000
 #define TRACE_LAYER_GAP             0x000e0000
-#define TRACE_LAYER_DUN             0x000f0000
-#define TRACE_LAYER_GOEP            0x00100000
 #define TRACE_LAYER_ICP             0x00110000
 #define TRACE_LAYER_HSP2            0x00120000
 #define TRACE_LAYER_SPP             0x00130000
@@ -702,5 +699,99 @@
 /* Define a function for logging */
 typedef void (BT_LOG_FUNC) (int trace_type, const char *fmt_str, ...);
 
+/* bd addr length and type */
+#ifndef BD_ADDR_LEN
+#define BD_ADDR_LEN     6
+typedef uint8_t BD_ADDR[BD_ADDR_LEN];
 #endif
 
+// From bd.c
+
+/*****************************************************************************
+**  Constants
+*****************************************************************************/
+
+/* global constant for "any" bd addr */
+static const BD_ADDR bd_addr_any = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
+static const BD_ADDR bd_addr_null= {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+/*****************************************************************************
+**  Functions
+*****************************************************************************/
+
+/*******************************************************************************
+**
+** Function         bdcpy
+**
+** Description      Copy bd addr b to a.
+**
+**
+** Returns          void
+**
+*******************************************************************************/
+inline void bdcpy(BD_ADDR a, const BD_ADDR b)
+{
+    int i;
+
+    for (i = BD_ADDR_LEN; i != 0; i--)
+    {
+        *a++ = *b++;
+    }
+}
+
+/*******************************************************************************
+**
+** Function         bdcmp
+**
+** Description      Compare bd addr b to a.
+**
+**
+** Returns          Zero if b==a, nonzero otherwise (like memcmp).
+**
+*******************************************************************************/
+inline int bdcmp(const BD_ADDR a, const BD_ADDR b)
+{
+    int i;
+
+    for (i = BD_ADDR_LEN; i != 0; i--)
+    {
+        if (*a++ != *b++)
+        {
+            return -1;
+        }
+    }
+    return 0;
+}
+
+/*******************************************************************************
+**
+** Function         bdcmpany
+**
+** Description      Compare bd addr to "any" bd addr.
+**
+**
+** Returns          Zero if a equals bd_addr_any.
+**
+*******************************************************************************/
+static inline int bdcmpany(const BD_ADDR a)
+{
+    return bdcmp(a, bd_addr_any);
+}
+
+/*******************************************************************************
+**
+** Function         bdsetany
+**
+** Description      Set bd addr to "any" bd addr.
+**
+**
+** Returns          void
+**
+*******************************************************************************/
+static inline void bdsetany(BD_ADDR a)
+{
+    bdcpy(a, bd_addr_any);
+}
+#endif
+
+
diff --git a/stack/include/btm_api.h b/stack/include/btm_api.h
index dbd0fb2..731ac34 100644
--- a/stack/include/btm_api.h
+++ b/stack/include/btm_api.h
@@ -411,7 +411,6 @@
 /* BTM service definitions
 ** Used for storing EIR data to bit mask
 */
-#ifndef BTM_EIR_UUID_LKUP_TBL
 enum
 {
     BTM_EIR_UUID_SERVCLASS_SERVICE_DISCOVERY_SERVER,
@@ -488,7 +487,6 @@
     BTM_EIR_UUID_SERVCLASS_HDP_SINK,
     BTM_EIR_MAX_SERVICES
 };
-#endif /* BTM_EIR_UUID_LKUP_TBL */
 
 /* search result in EIR of inquiry database */
 #define BTM_EIR_FOUND           0
@@ -611,10 +609,8 @@
     UINT8       page_scan_per_mode;
     UINT8       page_scan_mode;
     INT8        rssi;       /* Set to BTM_INQ_RES_IGNORE_RSSI if  not valid */
-#if (BTM_EIR_CLIENT_INCLUDED == TRUE)
     UINT32      eir_uuid[BTM_EIR_SERVICE_ARRAY_SIZE];
     BOOLEAN     eir_complete_list;
-#endif
 #if (BLE_INCLUDED == TRUE)
     tBT_DEVICE_TYPE         device_type;
     UINT8       inq_result_type;
@@ -635,15 +631,6 @@
     BOOLEAN             appl_knows_rem_name;    /* set by application if it knows the remote name of the peer device.
                                                    This is later used by application to determine if remote name request is
                                                    required to be done. Having the flag here avoid duplicate store of inquiry results */
-
-
-#if (BTM_INQ_GET_REMOTE_NAME == TRUE || BLE_INCLUDED == TRUE)
-    UINT16          remote_name_len;
-    tBTM_BD_NAME    remote_name;
-    UINT8           remote_name_state;
-    UINT8           remote_name_type;
-#endif
-
 } tBTM_INQ_INFO;
 
 
@@ -724,17 +711,6 @@
 **  ACL Types
 ****************/
 
-/* Structure returned with link policy information (in tBTM_CMPL_CB callback function)
-** in response to BTM_ReadLinkPolicy call.
-*/
-typedef struct
-{
-    tBTM_STATUS status;
-    UINT8       hci_status;
-    BD_ADDR     rem_bda;
-    UINT16      settings;
-} tBTM_LNK_POLICY_RESULTS;
-
 /* Structure returned with Role Switch information (in tBTM_CMPL_CB callback function)
 ** in response to BTM_SwitchRole call.
 */
@@ -745,17 +721,6 @@
     BD_ADDR remote_bd_addr; /* Remote BD addr involved with the switch */
 } tBTM_ROLE_SWITCH_CMPL;
 
-
-/* Structure returned with Change Link Key information (in tBTM_CMPL_CB callback function)
-** in response to BTM_ChangeLinkKey call.
-*/
-typedef struct
-{
-    UINT8   hci_status;     /* HCI status returned with the event */
-    BD_ADDR remote_bd_addr; /* Remote BD addr involved with the change link key */
-} tBTM_CHANGE_KEY_CMPL;
-
-
 /* Structure returned with QoS information (in tBTM_CMPL_CB callback function)
 ** in response to BTM_SetQoS call.
 */
@@ -976,6 +941,8 @@
 /*******************
 ** SCO Codec Types
 ********************/
+// TODO(google) This should use common definitions
+// in hci/include/hci_audio.h
 #define BTM_SCO_CODEC_NONE          0x0000
 #define BTM_SCO_CODEC_CVSD          0x0001
 #define BTM_SCO_CODEC_MSBC          0x0002
@@ -1350,13 +1317,6 @@
 typedef UINT8 (tBTM_PIN_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class,
                                    tBTM_BD_NAME bd_name);
 
-
-/* Get Link Key for the connection.  Parameters are
-**              BD Address of remote
-**              Link Key
-*/
-typedef UINT8 (tBTM_LINK_KEY_REQ_CALLBACK) (BD_ADDR bd_addr, LINK_KEY key);
-
 /* New Link Key for the connection.  Parameters are
 **              BD Address of remote
 **              Link Key
@@ -1384,14 +1344,6 @@
 typedef UINT8 (tBTM_AUTH_COMPLETE_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class,
                                              tBTM_BD_NAME bd_name, int result);
 
-/* Operation abort.  Called by the stack when link goes down during.  Pin code
-** request or authorization.  Parameters are
-**              BD Address of remote
-**
-*/
-typedef UINT8 (tBTM_ABORT_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class,
-                                     tBTM_BD_NAME bd_name);
-
 enum
 {
     BTM_SP_IO_REQ_EVT,      /* received IO_CAPABILITY_REQUEST event */
@@ -1752,9 +1704,7 @@
     tBTM_AUTHORIZE_CALLBACK     *p_authorize_callback;
     tBTM_PIN_CALLBACK           *p_pin_callback;
     tBTM_LINK_KEY_CALLBACK      *p_link_key_callback;
-    tBTM_LINK_KEY_REQ_CALLBACK  *p_link_key_req_callback;
     tBTM_AUTH_COMPLETE_CALLBACK *p_auth_complete_callback;
-    tBTM_ABORT_CALLBACK         *p_abort_callback;
     tBTM_BOND_CANCEL_CMPL_CALLBACK *p_bond_cancel_cmpl_callback;
     tBTM_SP_CALLBACK            *p_sp_callback;
 #if BLE_INCLUDED == TRUE
@@ -1829,90 +1779,16 @@
 /************************
 **  Stored Linkkey Types
 *************************/
-#define BTM_CB_EVT_RETURN_LINK_KEYS         1
-#define BTM_CB_EVT_READ_STORED_LINK_KEYS    2
-#define BTM_CB_EVT_WRITE_STORED_LINK_KEYS   3
 #define BTM_CB_EVT_DELETE_STORED_LINK_KEYS  4
 
 typedef struct
 {
     UINT8          event;
-
-} tBTM_STORED_LINK_KEYS_EVT;
-
-
-typedef struct
-{
-    UINT8          event;
-    UINT8          num_keys;
-
-} tBTM_RETURN_LINK_KEYS_EVT;
-
-
-typedef struct
-{
-    BD_ADDR         bd_addr;
-    LINK_KEY        link_key;
-
-} tBTM_BD_ADDR_LINK_KEY_PAIR;
-
-
-typedef struct
-{
-    UINT8          event;
-    UINT8          status;
-    UINT16         max_keys;
-    UINT16         read_keys;
-
-} tBTM_READ_STORED_LINK_KEY_COMPLETE;
-
-
-typedef struct
-{
-    UINT8          event;
-    UINT8          status;
-    UINT8          num_keys;
-
-} tBTM_WRITE_STORED_LINK_KEY_COMPLETE;
-
-
-typedef struct
-{
-    UINT8          event;
     UINT8          status;
     UINT16         num_keys;
 
 } tBTM_DELETE_STORED_LINK_KEY_COMPLETE;
 
-
-/* These macros are defined to check the Broadcom features supported in controller
- * (the return value for BTM_ReadBrcmFeatures() */
-/* multi-av */
-#define BTM_FEATURE_MULTI_AV_MASK 0x01
-#define BTM_FEATURE_MULTI_AV_OFF  0
-#define BTM_VSC_MULTI_AV_SUPPORTED(x) ((x)[BTM_FEATURE_MULTI_AV_OFF] & BTM_FEATURE_MULTI_AV_MASK)
-
-/* WBS SBC codec */
-#define BTM_FEATURE_WBS_SBC_MASK 0x02
-#define BTM_FEATURE_WBS_SBC_OFF  0
-#define BTM_VSC_WBS_SBC_SUPPORTED(x) ((x)[BTM_FEATURE_WBS_SBC_OFF] & BTM_FEATURE_WBS_SBC_MASK)
-
-/* Advanced Audio LC-PLC */
-#define BTM_FEATURE_AUDIO_LC_PLC_MASK 0x04
-#define BTM_FEATURE_AUDIO_LC_PLC_OFF  0
-#define BTM_VSC_AUDIO_LC_PLC_SUPPORTED(x) ((x)[BTM_FEATURE_AUDIO_LC_PLC_OFF] & BTM_FEATURE_AUDIO_LC_PLC_MASK)
-
-/* Light stack for audio routing in Controller */
-#define BTM_FEATURE_LIGHT_STACK_MASK 0x08
-#define BTM_FEATURE_LIGHT_STACK_OFF  0
-#define BTM_VSC_LIGHT_STACK_SUPPORTED(x) ((x)[BTM_FEATURE_LIGHT_STACK_OFF] & BTM_FEATURE_LIGHT_STACK_MASK)
-
-/* NFC support */
-#define BTM_FEATURE_NFC_MASK        (HCI_BRCM_FEATURE_NFC_MASK) /* 0x10 */
-#define BTM_FEATURE_NFC_OFF         (HCI_BRCM_FEATURE_NFC_OFF)  /* 0    */
-#define BTM_VSC_NFC_SUPPORTED(x) ((x)[BTM_FEATURE_NFC_OFF] & BTM_FEATURE_NFC_MASK)
-
-
 /* MIP evnets, callbacks    */
 enum
 {
@@ -1995,28 +1871,6 @@
 
 /*******************************************************************************
 **
-** Function         BTM_SetAfhChannels
-**
-** Description      This function is called to disable channels
-**
-** Returns          status
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetAfhChannels (UINT8 first, UINT8 last);
-
-/*******************************************************************************
-**
-** Function         BTM_SetAfhChannelAssessment
-**
-** Description      This function is called to set the channel assessment mode on or off
-**
-** Returns          status
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetAfhChannelAssessment (BOOLEAN enable_or_disable);
-
-/*******************************************************************************
-**
 ** Function         BTM_DeviceReset
 **
 ** Description      This function is called to reset the controller.The Callback function
@@ -2026,7 +1880,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTM_API extern void BTM_DeviceReset (tBTM_CMPL_CB *p_cb);
+extern void BTM_DeviceReset (tBTM_CMPL_CB *p_cb);
 
 
 /*******************************************************************************
@@ -2038,7 +1892,7 @@
 ** Returns          TRUE if device is up, else FALSE
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_IsDeviceUp (void);
+extern BOOLEAN BTM_IsDeviceUp (void);
 
 
 /*******************************************************************************
@@ -2050,7 +1904,7 @@
 ** Returns          BTM_CMD_STARTED if successful, otherwise an error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetLocalDeviceName (char *p_name);
+extern tBTM_STATUS BTM_SetLocalDeviceName (char *p_name);
 
 /*******************************************************************************
 **
@@ -2061,7 +1915,7 @@
 ** Returns          BTM_SUCCESS if successful, otherwise an error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS  BTM_SetDeviceClass (DEV_CLASS dev_class);
+extern tBTM_STATUS  BTM_SetDeviceClass (DEV_CLASS dev_class);
 
 
 /*******************************************************************************
@@ -2077,7 +1931,7 @@
 **                              is returned and p_name is set to NULL
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadLocalDeviceName (char **p_name);
+extern tBTM_STATUS BTM_ReadLocalDeviceName (char **p_name);
 
 /*******************************************************************************
 **
@@ -2089,45 +1943,7 @@
 ** Returns          BTM_CMD_STARTED if successful, otherwise an error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadLocalDeviceNameFromController (tBTM_CMPL_CB *p_rln_cmpl_cback);
-
-/*******************************************************************************
-**
-** Function         BTM_ReadLocalVersion
-**
-** Description      This function is called to read the local device version
-**
-** Returns          BTM_SUCCESS if successful, otherwise an error
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadLocalVersion (tBTM_VERSION_INFO *p_vers);
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadLocalDeviceAddr
-**
-** Description      This function is called to read the local device address
-**
-** Returns          BTM_SUCCESS
-**                  Callback returns the local device address
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadLocalDeviceAddr (tBTM_CMPL_CB *p_cb);
-
-
-/*******************************************************************************
-**
-** Function         BTM_GetLocalDeviceAddr
-**
-** Description      This function is called to read the local device address
-**
-** Returns          void
-**                  the local device address is copied into bd_addr
-**
-*******************************************************************************/
-    BTM_API extern void BTM_GetLocalDeviceAddr (BD_ADDR bd_addr);
-
+extern tBTM_STATUS BTM_ReadLocalDeviceNameFromController (tBTM_CMPL_CB *p_rln_cmpl_cback);
 
 /*******************************************************************************
 **
@@ -2138,7 +1954,7 @@
 ** Returns          pointer to the device class
 **
 *******************************************************************************/
-    BTM_API extern UINT8 *BTM_ReadDeviceClass (void);
+extern UINT8 *BTM_ReadDeviceClass (void);
 
 
 /*******************************************************************************
@@ -2150,30 +1966,7 @@
 ** Returns          pointer to the local features string
 **
 *******************************************************************************/
-    BTM_API extern UINT8 *BTM_ReadLocalFeatures (void);
-
-/*******************************************************************************
-**
-** Function         BTM_ReadLocalExtendedFeatures
-**
-** Description      This function is called to read the local extended features
-**
-** Returns          pointer to the local extended features mask or NULL if bad
-**                  page
-**
-*******************************************************************************/
-    BTM_API extern UINT8 *BTM_ReadLocalExtendedFeatures (UINT8 page_number);
-
-/*******************************************************************************
-**
-** Function         BTM_ReadBrcmFeatures
-**
-** Description      This function is called to read the Broadcom specific features
-**
-** Returns          pointer to the Broadcom features string
-**
-*******************************************************************************/
-    BTM_API extern UINT8 *BTM_ReadBrcmFeatures (void);
+extern UINT8 *BTM_ReadLocalFeatures (void);
 
 /*******************************************************************************
 **
@@ -2186,7 +1979,7 @@
 **                  registration.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_DEV_STATUS_CB *BTM_RegisterForDeviceStatusNotif (tBTM_DEV_STATUS_CB *p_cb);
+extern tBTM_DEV_STATUS_CB *BTM_RegisterForDeviceStatusNotif (tBTM_DEV_STATUS_CB *p_cb);
 
 
 /*******************************************************************************
@@ -2204,25 +1997,7 @@
 **                           registered.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_RegisterForVSEvents (tBTM_VS_EVT_CB *p_cb, BOOLEAN is_register);
-
-
-/*******************************************************************************
-**
-** Function         BTM_ContinueReset
-**
-** Description      Instructs stack to continue its stack initialization after
-**                  an application has completed any vender specific commands
-**                  sent to the controller.
-**
-**                  Note: This function is only called if an application
-**                      initialization function has been inserted in the reset
-**                      sequence.  (BTM_APP_DEV_INIT is defined with a function).
-**
-** Returns          void
-**
-*******************************************************************************/
-    BTM_API extern void BTM_ContinueReset (void);
+extern tBTM_STATUS BTM_RegisterForVSEvents (tBTM_VS_EVT_CB *p_cb, BOOLEAN is_register);
 
 
 /*******************************************************************************
@@ -2239,10 +2014,10 @@
 **                              prior command.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_VendorSpecificCommand(UINT16 opcode,
-                                                         UINT8 param_len,
-                                                         UINT8 *p_param_buf,
-                                                         tBTM_VSC_CMPL_CB *p_cb);
+extern tBTM_STATUS BTM_VendorSpecificCommand(UINT16 opcode,
+                                             UINT8 param_len,
+                                             UINT8 *p_param_buf,
+                                             tBTM_VSC_CMPL_CB *p_cb);
 
 
 /*******************************************************************************
@@ -2255,7 +2030,7 @@
 ** Returns          Allocated SCN number or 0 if none.
 **
 *******************************************************************************/
-    BTM_API extern UINT8 BTM_AllocateSCN(void);
+extern UINT8 BTM_AllocateSCN(void);
 
 // btla-specific ++
 /*******************************************************************************
@@ -2267,7 +2042,7 @@
 ** Returns          Returns TRUE if server channel was available
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_TryAllocateSCN(UINT8 scn);
+extern BOOLEAN BTM_TryAllocateSCN(UINT8 scn);
 // btla-specific --
 
 
@@ -2280,7 +2055,7 @@
 ** Returns          TRUE if successful, FALSE if SCN is not in use or invalid
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_FreeSCN(UINT8 scn);
+extern BOOLEAN BTM_FreeSCN(UINT8 scn);
 
 
 /*******************************************************************************
@@ -2293,7 +2068,7 @@
 ** Returns          The new or current trace level
 **
 *******************************************************************************/
-    BTM_API extern UINT8 BTM_SetTraceLevel (UINT8 new_level);
+extern UINT8 BTM_SetTraceLevel (UINT8 new_level);
 
 
 /*******************************************************************************
@@ -2307,7 +2082,7 @@
 **      BTM_NO_RESOURCES    If out of resources to send the command.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_WritePageTimeout(UINT16 timeout);
+extern tBTM_STATUS BTM_WritePageTimeout(UINT16 timeout);
 
 /*******************************************************************************
 **
@@ -2322,7 +2097,7 @@
 **
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_WriteVoiceSettings(UINT16 settings);
+extern tBTM_STATUS BTM_WriteVoiceSettings(UINT16 settings);
 
 /*******************************************************************************
 **
@@ -2339,7 +2114,7 @@
 **
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_EnableTestMode(void);
+extern tBTM_STATUS BTM_EnableTestMode(void);
 
 
 /*****************************************************************************
@@ -2362,8 +2137,8 @@
 **                  BTM_WRONG_MODE if the device is not up.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS  BTM_SetDiscoverability (UINT16 inq_mode, UINT16 window,
-                                                        UINT16 interval);
+extern tBTM_STATUS  BTM_SetDiscoverability (UINT16 inq_mode, UINT16 window,
+                                            UINT16 interval);
 
 
 /*******************************************************************************
@@ -2380,8 +2155,8 @@
 **                  BTM_GENERAL_DISCOVERABLE
 **
 *******************************************************************************/
-    BTM_API extern UINT16       BTM_ReadDiscoverability (UINT16 *p_window,
-                                                         UINT16 *p_interval);
+extern UINT16       BTM_ReadDiscoverability (UINT16 *p_window,
+                                             UINT16 *p_interval);
 
 
 /*******************************************************************************
@@ -2411,9 +2186,9 @@
 **                  BTM_WRONG_MODE if the device is not up.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS  BTM_SetPeriodicInquiryMode (tBTM_INQ_PARMS *p_inqparms,
-                                                            UINT16 max_delay, UINT16 min_delay,
-                                                            tBTM_INQ_RESULTS_CB *p_results_cb);
+extern tBTM_STATUS  BTM_SetPeriodicInquiryMode (tBTM_INQ_PARMS *p_inqparms,
+                                                UINT16 max_delay, UINT16 min_delay,
+                                                tBTM_INQ_RESULTS_CB *p_results_cb);
 
 
 /*******************************************************************************
@@ -2445,9 +2220,9 @@
 **                  BTM_WRONG_MODE if the device is not up.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS  BTM_StartInquiry (tBTM_INQ_PARMS *p_inqparms,
-                                                  tBTM_INQ_RESULTS_CB *p_results_cb,
-                                                  tBTM_CMPL_CB *p_cmpl_cb);
+extern tBTM_STATUS  BTM_StartInquiry (tBTM_INQ_PARMS *p_inqparms,
+                                      tBTM_INQ_RESULTS_CB *p_results_cb,
+                                      tBTM_CMPL_CB *p_cmpl_cb);
 
 
 /*******************************************************************************
@@ -2462,7 +2237,7 @@
 **                  BTM_PERIODIC_INQUIRY_ACTIVE if a periodic inquiry is active
 **
 *******************************************************************************/
-    BTM_API extern UINT16 BTM_IsInquiryActive (void);
+extern UINT16 BTM_IsInquiryActive (void);
 
 
 /*******************************************************************************
@@ -2476,7 +2251,7 @@
 **                  BTM_WRONG_MODE if the device is not up.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_CancelInquiry(void);
+extern tBTM_STATUS BTM_CancelInquiry(void);
 
 
 /*******************************************************************************
@@ -2491,21 +2266,7 @@
 **                  BTM_WRONG_MODE if the device is not up.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_CancelPeriodicInquiry(void);
-
-
-/*******************************************************************************
-**
-** Function         BTM_SetInquiryFilterCallback
-**
-** Description      Host can register to be asked whenever an inquiry result
-**                  is received.  If host does not like the device no name
-**                  request is issued for the device
-**
-** Returns          void
-**
-*******************************************************************************/
-    BTM_API extern void BTM_SetInquiryFilterCallback(tBTM_FILTER_CB *p_callback);
+extern tBTM_STATUS BTM_CancelPeriodicInquiry(void);
 
 
 /*******************************************************************************
@@ -2521,8 +2282,8 @@
 **                  BTM_WRONG_MODE if the device is not up.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetConnectability (UINT16 page_mode, UINT16 window,
-                                                      UINT16 interval);
+extern tBTM_STATUS BTM_SetConnectability (UINT16 page_mode, UINT16 window,
+                                          UINT16 interval);
 
 
 /*******************************************************************************
@@ -2537,7 +2298,7 @@
 ** Returns          BTM_NON_CONNECTABLE or BTM_CONNECTABLE
 **
 *******************************************************************************/
-    BTM_API extern UINT16 BTM_ReadConnectability (UINT16 *p_window, UINT16 *p_interval);
+extern UINT16 BTM_ReadConnectability (UINT16 *p_window, UINT16 *p_interval);
 
 
 /*******************************************************************************
@@ -2556,7 +2317,7 @@
 **                  BTM_WRONG_MODE if the device is not up.
 **
 *******************************************************************************/
-    BT_API extern tBTM_STATUS  BTM_SetInquiryMode (UINT8 mode);
+extern tBTM_STATUS  BTM_SetInquiryMode (UINT8 mode);
 
 /*******************************************************************************
 **
@@ -2572,7 +2333,7 @@
 **                  BTM_WRONG_MODE if the device is not up.
 **
 *******************************************************************************/
-    BT_API extern tBTM_STATUS BTM_SetInquiryScanType (UINT16 scan_type);
+extern tBTM_STATUS BTM_SetInquiryScanType (UINT16 scan_type);
 
 /*******************************************************************************
 **
@@ -2589,7 +2350,7 @@
 **
 *******************************************************************************/
 
-    BT_API extern tBTM_STATUS BTM_SetPageScanType (UINT16 scan_type);
+extern tBTM_STATUS BTM_SetPageScanType (UINT16 scan_type);
 
 /*******************************************************************************
 **
@@ -2613,9 +2374,9 @@
 **                  BTM_WRONG_MODE if the device is not up.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS  BTM_ReadRemoteDeviceName (BD_ADDR remote_bda,
-                                                          tBTM_CMPL_CB *p_cb,
-                                                          tBT_TRANSPORT transport);
+extern tBTM_STATUS  BTM_ReadRemoteDeviceName (BD_ADDR remote_bda,
+                                              tBTM_CMPL_CB *p_cb,
+                                              tBT_TRANSPORT transport);
 
 
 /*******************************************************************************
@@ -2634,7 +2395,7 @@
 **                  BTM_WRONG_MODE if there is not an active remote name request.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS  BTM_CancelRemoteDeviceName (void);
+extern tBTM_STATUS  BTM_CancelRemoteDeviceName (void);
 
 /*******************************************************************************
 **
@@ -2645,10 +2406,10 @@
 ** Returns          BTM_SUCCESS if successful, otherwise an error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadRemoteVersion (BD_ADDR addr,
-                                                      UINT8 *lmp_version,
-                                                      UINT16 *manufacturer,
-                                                      UINT16 *lmp_sub_version);
+extern tBTM_STATUS BTM_ReadRemoteVersion (BD_ADDR addr,
+                                          UINT8 *lmp_version,
+                                          UINT16 *manufacturer,
+                                          UINT16 *lmp_sub_version);
 
 /*******************************************************************************
 **
@@ -2663,7 +2424,7 @@
 ** Returns          pointer to the remote supported features mask
 **
 *******************************************************************************/
-    BTM_API extern UINT8 *BTM_ReadRemoteFeatures (BD_ADDR addr);
+extern UINT8 *BTM_ReadRemoteFeatures (BD_ADDR addr);
 
 /*******************************************************************************
 **
@@ -2682,7 +2443,7 @@
 **                  or NULL if page_number is not valid
 **
 *******************************************************************************/
-    BTM_API extern UINT8 *BTM_ReadRemoteExtendedFeatures (BD_ADDR addr, UINT8 page_number);
+extern UINT8 *BTM_ReadRemoteExtendedFeatures (BD_ADDR addr, UINT8 page_number);
 
 /*******************************************************************************
 **
@@ -2694,7 +2455,7 @@
 ** Returns          number of features pages read from the remote device
 **
 *******************************************************************************/
-    BTM_API extern UINT8 BTM_ReadNumberRemoteFeaturesPages (BD_ADDR addr);
+extern UINT8 BTM_ReadNumberRemoteFeaturesPages (BD_ADDR addr);
 
 /*******************************************************************************
 **
@@ -2709,36 +2470,7 @@
 **                  BTM_FEATURE_BYTES_PER_PAGE * (BTM_EXT_FEATURES_PAGE_MAX + 1).
 **
 *******************************************************************************/
-    BTM_API extern UINT8 *BTM_ReadAllRemoteFeatures (BD_ADDR addr);
-
-/*******************************************************************************
-**
-** Function         BTM_InqFirstResult
-**
-** Description      This function looks through the inquiry database for the first
-**                  used entrysince the LAST inquiry. This is used in conjunction
-**                  with BTM_InqNext by applications as a way to walk through the
-**                  inquiry results database.
-**
-** Returns          pointer to first in-use entry, or NULL if DB is empty
-**
-*******************************************************************************/
-    BTM_API extern tBTM_INQ_INFO *BTM_InqFirstResult (void);
-
-
-/*******************************************************************************
-**
-** Function         BTM_InqNextResult
-**
-** Description      This function looks through the inquiry database for the next
-**                  used entrysince the LAST inquiry. If the input parameter is NULL,
-**                  the first entry is returned.
-**
-** Returns          pointer to next in-use entry, or NULL if no more found.
-**
-*******************************************************************************/
-    BTM_API extern tBTM_INQ_INFO *BTM_InqNextResult (tBTM_INQ_INFO *p_cur);
-
+extern UINT8 *BTM_ReadAllRemoteFeatures (BD_ADDR addr);
 
 /*******************************************************************************
 **
@@ -2751,7 +2483,7 @@
 ** Returns          pointer to entry, or NULL if not found
 **
 *******************************************************************************/
-    BTM_API extern tBTM_INQ_INFO *BTM_InqDbRead (BD_ADDR p_bda);
+extern tBTM_INQ_INFO *BTM_InqDbRead (BD_ADDR p_bda);
 
 
 /*******************************************************************************
@@ -2766,7 +2498,7 @@
 ** Returns          pointer to first in-use entry, or NULL if DB is empty
 **
 *******************************************************************************/
-    BTM_API extern tBTM_INQ_INFO *BTM_InqDbFirst (void);
+extern tBTM_INQ_INFO *BTM_InqDbFirst (void);
 
 
 /*******************************************************************************
@@ -2780,7 +2512,7 @@
 ** Returns          pointer to next in-use entry, or NULL if no more found.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_INQ_INFO *BTM_InqDbNext (tBTM_INQ_INFO *p_cur);
+extern tBTM_INQ_INFO *BTM_InqDbNext (tBTM_INQ_INFO *p_cur);
 
 
 /*******************************************************************************
@@ -2797,30 +2529,7 @@
 **                          is active, otherwise BTM_SUCCESS
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS  BTM_ClearInqDb (BD_ADDR p_bda);
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadNumInqDbEntries
-**
-** Returns          This function returns the number of entries in the inquiry database.
-**
-*******************************************************************************/
-    BTM_API extern UINT8 BTM_ReadNumInqDbEntries (void);
-
-
-/*******************************************************************************
-**
-** Function         BTM_InquiryRegisterForChanges
-**
-** Description      This function is called to register a callback for when the
-**                  inquiry database changes, i.e. new entry or entry deleted.
-**
-** Returns          BTM_SUCCESS if successful, otherwise error code
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_InquiryRegisterForChanges (tBTM_INQ_DB_CHANGE_CB *p_cb);
+extern tBTM_STATUS  BTM_ClearInqDb (BD_ADDR p_bda);
 
 /*******************************************************************************
 **
@@ -2833,21 +2542,7 @@
 ** Returns          BTM_SUCCESS if successful
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadInquiryRspTxPower (tBTM_CMPL_CB *p_cb);
-
-/*******************************************************************************
-**
-** Function         BTM_WriteInquiryTxPower
-**
-** Description      This command is used to write the inquiry transmit power level
-**                  used to transmit the inquiry (ID) data packets. The Controller
-**                  should use the supported TX power level closest to the Tx_Power
-**                  parameter.
-**
-** Returns          BTM_SUCCESS if successful
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS  BTM_WriteInquiryTxPower (INT8 tx_power);
+extern tBTM_STATUS BTM_ReadInquiryRspTxPower (tBTM_CMPL_CB *p_cb);
 
 /*******************************************************************************
 **
@@ -2864,8 +2559,8 @@
 **                      BTM_ERR_PROCESSING if err initiating the command
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_StartDiscovery (tBTM_CMPL_CB *p_cmpl_cb,
-                                                   BD_ADDR_PTR p_rem_addr);
+extern tBTM_STATUS BTM_StartDiscovery (tBTM_CMPL_CB *p_cmpl_cb,
+                                       BD_ADDR_PTR p_rem_addr);
 
 
 /*******************************************************************************
@@ -2879,8 +2574,8 @@
 ** Returns          Pointer to matching record, or NULL
 **
 *******************************************************************************/
-    BTM_API extern tSDP_DISC_REC *BTM_FindAttribute (UINT16 attr_id,
-                                                     tSDP_DISC_REC *p_start_rec);
+extern tSDP_DISC_REC *BTM_FindAttribute (UINT16 attr_id,
+                                         tSDP_DISC_REC *p_start_rec);
 
 
 /*******************************************************************************
@@ -2894,8 +2589,8 @@
 ** Returns          Pointer to matching record, or NULL
 **
 *******************************************************************************/
-    BTM_API extern tSDP_DISC_REC *BTM_FindService (UINT16 service_uuid,
-                                                   tSDP_DISC_REC *p_start_rec);
+extern tSDP_DISC_REC *BTM_FindService (UINT16 service_uuid,
+                                       tSDP_DISC_REC *p_start_rec);
 
 
 /*******************************************************************************
@@ -2909,8 +2604,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTM_API extern void BTM_SetDiscoveryParams (UINT16 num_uuid, tSDP_UUID *p_uuid_list,
-                                                UINT16 num_attr, UINT16 *p_attr_list);
+extern void BTM_SetDiscoveryParams (UINT16 num_uuid, tSDP_UUID *p_uuid_list,
+                                    UINT16 num_attr, UINT16 *p_attr_list);
 
 
 /*****************************************************************************
@@ -2925,24 +2620,8 @@
 ** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetLinkPolicy (BD_ADDR remote_bda,
-                                                  UINT16 *settings);
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadLinkPolicy
-**
-** Description      This function is called to read the link policy settings.
-**                  The address of link policy results are returned in the callback.
-**                  (tBTM_LNK_POLICY_RESULTS)
-**
-** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadLinkPolicy (BD_ADDR remote_bda,
-                                                   tBTM_CMPL_CB *p_cb);
-
+extern tBTM_STATUS BTM_SetLinkPolicy (BD_ADDR remote_bda,
+                                      UINT16 *settings);
 
 /*******************************************************************************
 **
@@ -2954,7 +2633,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTM_API extern void BTM_SetDefaultLinkPolicy (UINT16 settings);
+extern void BTM_SetDefaultLinkPolicy (UINT16 settings);
 
 
 /*******************************************************************************
@@ -2967,7 +2646,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTM_API extern void BTM_SetDefaultLinkSuperTout (UINT16 timeout);
+extern void BTM_SetDefaultLinkSuperTout (UINT16 timeout);
 
 
 /*******************************************************************************
@@ -2979,8 +2658,8 @@
 ** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetLinkSuperTout (BD_ADDR remote_bda,
-                                                     UINT16 timeout);
+extern tBTM_STATUS BTM_SetLinkSuperTout (BD_ADDR remote_bda,
+                                         UINT16 timeout);
 /*******************************************************************************
 **
 ** Function         BTM_GetLinkSuperTout
@@ -2990,148 +2669,8 @@
 ** Returns          status of the operation
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_GetLinkSuperTout (BD_ADDR remote_bda,
-                                                     UINT16 *p_timeout);
-
-/*******************************************************************************
-**
-** Function         BTM_RegForLstoEvt
-**
-** Description      register for the HCI "Link Supervision Timeout Change" event
-**
-** Returns          void
-**
-*******************************************************************************/
-    BTM_API extern void BTM_RegForLstoEvt (tBTM_LSTO_CBACK *p_cback);
-
-
-/* These next APIs are available if the power manager is not compiled in */
-#if BTM_PWR_MGR_INCLUDED == FALSE
-/*******************************************************************************
-**
-** Function         BTM_SetHoldMode
-**
-** Description      This function is called to set a connection into hold mode.
-**                  A check is made if the connection is in sniff or park mode,
-**                  and if yes, the hold mode is ignored.
-**
-** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetHoldMode (BD_ADDR remote_bda, UINT16 min_interval,
-                                                UINT16 max_interval);
-
-
-/*******************************************************************************
-**
-** Function         BTM_SetSniffMode
-**
-** Description      This function is called to set a connection into sniff mode.
-**                  A check is made if the connection is already in sniff or park
-**                  mode, and if yes, the sniff mode is ignored.
-**
-** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetSniffMode (BD_ADDR remote_bda, UINT16 min_period,
-                                                 UINT16 max_period, UINT16 attempt,
-                                                 UINT16 timeout);
-
-
-/*******************************************************************************
-**
-** Function         BTM_CancelSniffMode
-**
-** Description      This function is called to put a connection out of sniff mode.
-**                  A check is made if the connection is already in sniff mode,
-**                  and if not, the cancel sniff mode is ignored.
-**
-** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_CancelSniffMode (BD_ADDR remote_bda);
-
-
-/*******************************************************************************
-**
-** Function         BTM_SetParkMode
-**
-** Description      This function is called to set a connection into park mode.
-**                  A check is made if the connection is already in sniff or park
-**                  mode, and if yes, the park mode is ignored.
-**
-** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetParkMode (BD_ADDR remote_bda,
-                                                UINT16 beacon_min_period,
-                                                UINT16 beacon_max_period);
-
-
-/*******************************************************************************
-**
-** Function         BTM_CancelParkMode
-**
-** Description      This function is called to put a connection out of park mode.
-**                  A check is made if the connection is already in park mode,
-**                  and if not, the cancel sniff mode is ignored.
-**
-** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_CancelParkMode (BD_ADDR remote_bda);
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadAclMode
-**
-** Description      This returns the current mode for a specific
-**                  ACL connection.
-**
-** Input Param      remote_bda - device address of desired ACL connection
-**
-** Output Param     p_mode - address where the current mode is copied into.
-**                          BTM_ACL_MODE_NORMAL
-**                          BTM_ACL_MODE_HOLD
-**                          BTM_ACL_MODE_SNIFF
-**                          BTM_ACL_MODE_PARK
-**                          (valid only if return code is BTM_SUCCESS)
-**
-** Returns          BTM_SUCCESS if successful,
-**                  BTM_UNKNOWN_ADDR if bd addr is not active or bad
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadAclMode (BD_ADDR remote_bda, UINT8 *p_mode);
-
-#endif /* if BTM_PWR_MGR_INCLUDED == FALSE */
-
-
-/*******************************************************************************
-**
-** Function         BTM_SetPacketTypes
-**
-** Description      This function is set the packet types used for a specific
-**                  ACL connection,
-**
-** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetPacketTypes (BD_ADDR remote_bda, UINT16 pkt_types);
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadPacketTypes
-**
-** Description      This function is set the packet types used for the specified
-**                  ACL connection,
-**
-** Returns          packet types supported for the connection, or 0 if no BD address
-**
-*******************************************************************************/
-    BTM_API extern UINT16 BTM_ReadPacketTypes (BD_ADDR remote_bda);
-
+extern tBTM_STATUS BTM_GetLinkSuperTout (BD_ADDR remote_bda,
+                                         UINT16 *p_timeout);
 
 /*******************************************************************************
 **
@@ -3143,7 +2682,7 @@
 ** Returns          TRUE if connection is up, else FALSE.
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_IsAclConnectionUp (BD_ADDR remote_bda, tBT_TRANSPORT transport);
+extern BOOLEAN BTM_IsAclConnectionUp (BD_ADDR remote_bda, tBT_TRANSPORT transport);
 
 
 /*******************************************************************************
@@ -3157,7 +2696,7 @@
 **                  BTM_UNKNOWN_ADDR if no active link with bd addr specified
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_GetRole (BD_ADDR remote_bd_addr, UINT8 *p_role);
+extern tBTM_STATUS BTM_GetRole (BD_ADDR remote_bd_addr, UINT8 *p_role);
 
 
 
@@ -3177,25 +2716,9 @@
 **                  BTM_MODE_UNSUPPORTED if local device does not support role switching
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SwitchRole (BD_ADDR remote_bd_addr,
-                                               UINT8 new_role,
-                                               tBTM_CMPL_CB *p_cb);
-
-/*******************************************************************************
-**
-** Function         BTM_ChangeLinkKey
-**
-** Description      This function is called to change the link key of the
-**                  connection.
-**
-** Returns          BTM_CMD_STARTED if command issued to controller.
-**                  BTM_NO_RESOURCES if couldn't allocate memory to issue command
-**                  BTM_UNKNOWN_ADDR if no active link with bd addr specified
-**                  BTM_BUSY if the previous command is not completed
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ChangeLinkKey (BD_ADDR remote_bd_addr,
-                                                  tBTM_CMPL_CB *p_cb);
+extern tBTM_STATUS BTM_SwitchRole (BD_ADDR remote_bd_addr,
+                                   UINT8 new_role,
+                                   tBTM_CMPL_CB *p_cb);
 
 /*******************************************************************************
 **
@@ -3211,7 +2734,7 @@
 **                  BTM_BUSY if command is already in progress
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadRSSI (BD_ADDR remote_bda, tBTM_CMPL_CB *p_cb);
+extern tBTM_STATUS BTM_ReadRSSI (BD_ADDR remote_bda, tBTM_CMPL_CB *p_cb);
 
 
 /*******************************************************************************
@@ -3229,8 +2752,8 @@
 **                  BTM_BUSY if command is already in progress
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadTxPower (BD_ADDR remote_bda,
-                                                      tBT_TRANSPORT transport, tBTM_CMPL_CB *p_cb);
+extern tBTM_STATUS BTM_ReadTxPower (BD_ADDR remote_bda,
+                                    tBT_TRANSPORT transport, tBTM_CMPL_CB *p_cb);
 
 /*******************************************************************************
 **
@@ -3246,7 +2769,7 @@
 **                  BTM_BUSY if command is already in progress
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadLinkQuality (BD_ADDR remote_bda, tBTM_CMPL_CB *p_cb);
+extern tBTM_STATUS BTM_ReadLinkQuality (BD_ADDR remote_bda, tBTM_CMPL_CB *p_cb);
 
 /*******************************************************************************
 **
@@ -3258,8 +2781,8 @@
 ** Returns          BTM_SUCCESS if successfully registered, otherwise error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_RegBusyLevelNotif (tBTM_BL_CHANGE_CB *p_cb, UINT8 *p_level,
-                                                      tBTM_BL_EVENT_MASK evt_mask);
+extern tBTM_STATUS BTM_RegBusyLevelNotif (tBTM_BL_CHANGE_CB *p_cb, UINT8 *p_level,
+                                          tBTM_BL_EVENT_MASK evt_mask);
 
 /*******************************************************************************
 **
@@ -3271,7 +2794,7 @@
 ** Returns          BTM_SUCCESS if successfully initiated, otherwise error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_AclRegisterForChanges (tBTM_ACL_DB_CHANGE_CB *p_cb);
+extern tBTM_STATUS BTM_AclRegisterForChanges (tBTM_ACL_DB_CHANGE_CB *p_cb);
 
 /*******************************************************************************
 **
@@ -3283,21 +2806,7 @@
 ** Returns          UINT16  Number of active ACL links
 **
 *******************************************************************************/
-    BTM_API extern UINT16 BTM_GetNumAclLinks (void);
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadClockOffset
-**
-** Description      This returns the clock offset for a specific
-**                  ACL connection.
-**
-** Returns          clock-offset or 0 if unknown
-**
-*******************************************************************************/
-    BTM_API extern UINT16 BTM_ReadClockOffset (BD_ADDR remote_bda);
-
+extern UINT16 BTM_GetNumAclLinks (void);
 
 /*******************************************************************************
 **
@@ -3308,8 +2817,8 @@
 ** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetQoS(BD_ADDR bd, FLOW_SPEC *p_flow,
-                                          tBTM_CMPL_CB *p_cb);
+extern tBTM_STATUS BTM_SetQoS(BD_ADDR bd, FLOW_SPEC *p_flow,
+                              tBTM_CMPL_CB *p_cb);
 
 
 /*****************************************************************************
@@ -3332,10 +2841,10 @@
 **                                   with the sco index used for the connection.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_CreateSco (BD_ADDR remote_bda, BOOLEAN is_orig,
-                                              UINT16 pkt_types, UINT16 *p_sco_inx,
-                                              tBTM_SCO_CB *p_conn_cb,
-                                              tBTM_SCO_CB *p_disc_cb);
+extern tBTM_STATUS BTM_CreateSco (BD_ADDR remote_bda, BOOLEAN is_orig,
+                                  UINT16 pkt_types, UINT16 *p_sco_inx,
+                                  tBTM_SCO_CB *p_conn_cb,
+                                  tBTM_SCO_CB *p_disc_cb);
 
 
 /*******************************************************************************
@@ -3347,7 +2856,7 @@
 ** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_RemoveSco (UINT16 sco_inx);
+extern tBTM_STATUS BTM_RemoveSco (UINT16 sco_inx);
 
 
 /*******************************************************************************
@@ -3370,7 +2879,7 @@
 ** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetScoPacketTypes (UINT16 sco_inx, UINT16 pkt_types);
+extern tBTM_STATUS BTM_SetScoPacketTypes (UINT16 sco_inx, UINT16 pkt_types);
 
 
 /*******************************************************************************
@@ -3391,7 +2900,7 @@
 ** Returns          packet types supported for the connection
 **
 *******************************************************************************/
-    BTM_API extern UINT16 BTM_ReadScoPacketTypes (UINT16 sco_inx);
+extern UINT16 BTM_ReadScoPacketTypes (UINT16 sco_inx);
 
 
 /*******************************************************************************
@@ -3404,7 +2913,7 @@
 ** Returns          packet types supported by the device.
 **
 *******************************************************************************/
-    BTM_API extern UINT16 BTM_ReadDeviceScoPacketTypes (void);
+extern UINT16 BTM_ReadDeviceScoPacketTypes (void);
 
 
 /*******************************************************************************
@@ -3417,7 +2926,7 @@
 ** Returns          handle for the connection, or 0xFFFF if invalid SCO index.
 **
 *******************************************************************************/
-    BTM_API extern UINT16 BTM_ReadScoHandle (UINT16 sco_inx);
+extern UINT16 BTM_ReadScoHandle (UINT16 sco_inx);
 
 
 /*******************************************************************************
@@ -3430,7 +2939,7 @@
 ** Returns          pointer to BD address or NULL if not known
 **
 *******************************************************************************/
-    BTM_API extern UINT8 *BTM_ReadScoBdAddr (UINT16 sco_inx);
+extern UINT8 *BTM_ReadScoBdAddr (UINT16 sco_inx);
 
 
 /*******************************************************************************
@@ -3444,7 +2953,7 @@
 ** Returns          HCI reason or BTM_INVALID_SCO_DISC_REASON if not set.
 **
 *******************************************************************************/
-    BTM_API extern UINT16 BTM_ReadScoDiscReason (void);
+extern UINT16 BTM_ReadScoDiscReason (void);
 
 
 /*******************************************************************************
@@ -3460,8 +2969,8 @@
 **                  BTM_BUSY if there are one or more active (e)SCO links.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetEScoMode (tBTM_SCO_TYPE sco_mode,
-                                                tBTM_ESCO_PARAMS *p_parms);
+extern tBTM_STATUS BTM_SetEScoMode (tBTM_SCO_TYPE sco_mode,
+                                    tBTM_ESCO_PARAMS *p_parms);
 
 /*******************************************************************************
 **
@@ -3474,7 +2983,7 @@
 **
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_SetWBSCodec (tBTM_SCO_CODEC_TYPE codec_type);
+extern tBTM_STATUS BTM_SetWBSCodec (tBTM_SCO_CODEC_TYPE codec_type);
 
 /*******************************************************************************
 **
@@ -3489,8 +2998,8 @@
 **                  BTM_ILLEGAL_VALUE if there is an illegal sco_inx
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_RegForEScoEvts (UINT16 sco_inx,
-                                                   tBTM_ESCO_CBACK *p_esco_cback);
+extern tBTM_STATUS BTM_RegForEScoEvts (UINT16 sco_inx,
+                                       tBTM_ESCO_CBACK *p_esco_cback);
 
 /*******************************************************************************
 **
@@ -3513,8 +3022,8 @@
 **                      1.2 specification.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadEScoLinkParms (UINT16 sco_inx,
-                                                      tBTM_ESCO_DATA *p_parms);
+extern tBTM_STATUS BTM_ReadEScoLinkParms (UINT16 sco_inx,
+                                          tBTM_ESCO_DATA *p_parms);
 
 /*******************************************************************************
 **
@@ -3535,8 +3044,8 @@
 **                      1.2 specification.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ChangeEScoLinkParms (UINT16 sco_inx,
-                                                        tBTM_CHG_ESCO_PARAMS *p_parms);
+extern tBTM_STATUS BTM_ChangeEScoLinkParms (UINT16 sco_inx,
+                                            tBTM_CHG_ESCO_PARAMS *p_parms);
 
 /*******************************************************************************
 **
@@ -3556,8 +3065,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTM_API extern void BTM_EScoConnRsp (UINT16 sco_inx, UINT8 hci_status,
-                                         tBTM_ESCO_PARAMS *p_parms);
+extern void BTM_EScoConnRsp (UINT16 sco_inx, UINT8 hci_status,
+                             tBTM_ESCO_PARAMS *p_parms);
 
 /*******************************************************************************
 **
@@ -3568,7 +3077,7 @@
 ** Returns          UINT8
 **
 *******************************************************************************/
-    BTM_API extern UINT8 BTM_GetNumScoLinks (void);
+extern UINT8 BTM_GetNumScoLinks (void);
 
 /*****************************************************************************
 **  SECURITY MANAGEMENT FUNCTIONS
@@ -3584,21 +3093,7 @@
 ** Returns          TRUE if registered OK, else FALSE
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_SecRegister (tBTM_APPL_INFO *p_cb_info);
-
-
-/*******************************************************************************
-**
-** Function         BTM_SecRegisterLinkKeyNotificationCallback
-**
-** Description      Profiles can register to be notified when a new Link Key
-**                  is generated per connection.
-**
-** Returns          TRUE if registered OK, else FALSE
-**
-*******************************************************************************/
-    BTM_API extern BOOLEAN BTM_SecRegisterLinkKeyNotificationCallback (
-                                                        tBTM_LINK_KEY_CALLBACK *p_callback);
+extern BOOLEAN BTM_SecRegister (tBTM_APPL_INFO *p_cb_info);
 
 
 /*******************************************************************************
@@ -3611,8 +3106,7 @@
 ** Returns          TRUE if registered OK, else FALSE
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_SecAddRmtNameNotifyCallback (
-                                                               tBTM_RMT_NAME_CALLBACK *p_callback);
+extern BOOLEAN BTM_SecAddRmtNameNotifyCallback (tBTM_RMT_NAME_CALLBACK *p_callback);
 
 
 /*******************************************************************************
@@ -3625,36 +3119,7 @@
 ** Returns          TRUE if OK, else FALSE
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_SecDeleteRmtNameNotifyCallback (
-                                                            tBTM_RMT_NAME_CALLBACK *p_callback);
-
-
-/*******************************************************************************
-**
-** Function         BTM_SecSetConnectFilterCallback
-**
-** Description      Host can register to be asked whenever an HCI connection
-**                  request is received.  In the registered function host
-**                  suppose to check connectibility filters.  Yes/No result
-**                  should be returned synchronously.
-**
-** Returns          void
-**
-*******************************************************************************/
-    BTM_API extern void BTM_SecSetConnectFilterCallback (tBTM_FILTER_CB *p_callback);
-
-
-/*******************************************************************************
-**
-** Function         BTM_GetSecurityMode
-**
-** Description      Get security mode for the device
-**
-** Returns          void
-**
-*******************************************************************************/
-    BTM_API extern UINT8 BTM_GetSecurityMode (void);
-
+extern BOOLEAN BTM_SecDeleteRmtNameNotifyCallback (tBTM_RMT_NAME_CALLBACK *p_callback);
 
 /*******************************************************************************
 **
@@ -3665,7 +3130,7 @@
 ** Returns          BOOLEAN TRUE or FALSE is device found
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_GetSecurityFlags (BD_ADDR bd_addr, UINT8 * p_sec_flags);
+extern BOOLEAN BTM_GetSecurityFlags (BD_ADDR bd_addr, UINT8 * p_sec_flags);
 
 /*******************************************************************************
 **
@@ -3680,8 +3145,8 @@
 ** Returns          BOOLEAN TRUE or FALSE is device found
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_GetSecurityFlagsByTransport (BD_ADDR bd_addr,
-                                UINT8 * p_sec_flags, tBT_TRANSPORT transport);
+extern BOOLEAN BTM_GetSecurityFlagsByTransport (BD_ADDR bd_addr,
+                                                UINT8 * p_sec_flags, tBT_TRANSPORT transport);
 
 /*******************************************************************************
 **
@@ -3693,20 +3158,7 @@
 **                  otherwise, the trusted mask
 **
 *******************************************************************************/
-    BTM_API extern UINT32 * BTM_ReadTrustedMask (BD_ADDR bd_addr);
-
-
-/*******************************************************************************
-**
-** Function         BTM_SetSecurityMode
-**
-** Description      Set security mode for the device
-**
-** Returns          void
-**
-*******************************************************************************/
-    BTM_API extern void BTM_SetSecurityMode (UINT8 sec_mode);
-
+extern UINT32 * BTM_ReadTrustedMask (BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -3717,7 +3169,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTM_API extern void BTM_SetPinType (UINT8 pin_type, PIN_CODE pin_code, UINT8 pin_code_len);
+extern void BTM_SetPinType (UINT8 pin_type, PIN_CODE pin_code, UINT8 pin_code_len);
 
 
 /*******************************************************************************
@@ -3734,7 +3186,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTM_API extern void BTM_SetPairableMode (BOOLEAN allow_pairing, BOOLEAN connect_only_paired);
+extern void BTM_SetPairableMode (BOOLEAN allow_pairing, BOOLEAN connect_only_paired);
 
 /*******************************************************************************
 **
@@ -3748,27 +3200,10 @@
 ** Returns          TRUE if registered OK, else FALSE
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_SetSecurityLevel (BOOLEAN is_originator, char *p_name,
-                                                 UINT8 service_id, UINT16 sec_level,
-                                                 UINT16 psm, UINT32 mx_proto_id,
-                                                 UINT32 mx_chan_id);
-
-/*******************************************************************************
-**
-** Function         BTM_SetUCDSecurityLevel
-**
-** Description      Register UCD service security level with Security Manager.  Each
-**                  service must register its requirements regardless of the
-**                  security level that is used.  This API is called once for originators
-**                  and again for acceptors of connections.
-**
-** Returns          TRUE if registered OK, else FALSE
-**
-*******************************************************************************/
-    BTM_API extern BOOLEAN BTM_SetUCDSecurityLevel (BOOLEAN is_originator, char *p_name,
-                                                          UINT8 service_id, UINT16 sec_level,
-                                                          UINT16 psm, UINT32 mx_proto_id,
-                                                          UINT32 mx_chan_id);
+extern BOOLEAN BTM_SetSecurityLevel (BOOLEAN is_originator, char *p_name,
+                                     UINT8 service_id, UINT16 sec_level,
+                                     UINT16 psm, UINT32 mx_proto_id,
+                                     UINT32 mx_chan_id);
 
 /*******************************************************************************
 **
@@ -3780,7 +3215,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTM_API extern void BTM_SetOutService(BD_ADDR bd_addr, UINT8 service_id, UINT32 mx_chan_id);
+extern void BTM_SetOutService(BD_ADDR bd_addr, UINT8 service_id, UINT32 mx_chan_id);
 
 /*******************************************************************************
 **
@@ -3795,21 +3230,7 @@
 ** Returns          Number of records that were freed.
 **
 *******************************************************************************/
-    BTM_API extern UINT8 BTM_SecClrService (UINT8 service_id);
-
-/*******************************************************************************
-**
-** Function         BTM_SecClrUCDService
-**
-** Description
-**
-** Parameters       Service ID - Id of the service to remove. ('0' removes all service
-**                          records.
-**
-** Returns          Number of records that were freed.
-**
-*******************************************************************************/
-    BTM_API extern UINT8 BTM_SecClrUCDService (UINT8 service_id);
+extern UINT8 BTM_SecClrService (UINT8 service_id);
 
 /*******************************************************************************
 **
@@ -3823,10 +3244,10 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_SecAddDevice (BD_ADDR bd_addr, DEV_CLASS dev_class,
-                                             BD_NAME bd_name, UINT8 *features,
-                                             UINT32 trusted_mask[], LINK_KEY link_key,
-                                             UINT8 key_type, tBTM_IO_CAP io_cap);
+extern BOOLEAN BTM_SecAddDevice (BD_ADDR bd_addr, DEV_CLASS dev_class,
+                                 BD_NAME bd_name, UINT8 *features,
+                                 UINT32 trusted_mask[], LINK_KEY link_key,
+                                 UINT8 key_type, tBTM_IO_CAP io_cap);
 
 
 /*******************************************************************************
@@ -3838,35 +3259,7 @@
 ** Returns          TRUE if rmoved OK, FALSE if not found
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_SecDeleteDevice (BD_ADDR bd_addr);
-
-
-/*******************************************************************************
-**
-** Function         BTM_SecUseMasterLinkKey
-**
-** Description      This function is called to tell master of the piconet to
-**                  switch to master link key
-**
-** Returns          BTM_SUCCESS if command is successully initiated
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SecUseMasterLinkKey (BOOLEAN use_master_key);
-
-
-/*******************************************************************************
-**
-** Function         BTM_SetMasterKeyCompCback
-**
-** Description      This function is called to register for the master key complete
-**                  status event.
-**
-** Parameters:      mkey_cback - callback registered with the security manager
-**
-** Returns          void
-**
-*******************************************************************************/
-    BTM_API extern void BTM_SetMasterKeyCompCback(tBTM_MKEY_CALLBACK *mkey_cback );
+extern BOOLEAN BTM_SecDeleteDevice (BD_ADDR bd_addr);
 
 
 /*******************************************************************************
@@ -3881,8 +3274,8 @@
 ** Returns          BTM_SUCCESS if successful, otherwise error code
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SecGetDeviceLinkKey (BD_ADDR bd_addr,
-                                                        LINK_KEY link_key);
+extern tBTM_STATUS BTM_SecGetDeviceLinkKey (BD_ADDR bd_addr,
+                                            LINK_KEY link_key);
 
 
 /*******************************************************************************
@@ -3901,25 +3294,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    BTM_API extern void BTM_PINCodeReply (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len,
-                                          UINT8 *p_pin, UINT32 trusted_mask[]);
-
-
-/*******************************************************************************
-**
-** Function         BTM_DeviceAuthorized
-**
-** Description      This function is called after Security Manager submitted
-**                  authorization request to the UI.
-**
-** Parameters:      bd_addr     - Address of the device for which PIN was requested
-**                  res         - result of the operation BTM_SUCCESS if success
-**
-** Returns          void
-**
-*******************************************************************************/
-    BTM_API extern void BTM_DeviceAuthorized (BD_ADDR bd_addr, UINT8 res,
-                                              UINT32 trusted_mask[]);
+extern void BTM_PINCodeReply (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len,
+                              UINT8 *p_pin, UINT32 trusted_mask[]);
 
 
 /*******************************************************************************
@@ -3936,9 +3312,9 @@
 ** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SecBond (BD_ADDR bd_addr,
-                                            UINT8 pin_len, UINT8 *p_pin,
-                                            UINT32 trusted_mask[]);
+extern tBTM_STATUS BTM_SecBond (BD_ADDR bd_addr,
+                                UINT8 pin_len, UINT8 *p_pin,
+                                UINT32 trusted_mask[]);
 
 /*******************************************************************************
 **
@@ -3955,10 +3331,10 @@
 ** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SecBondByTransport (BD_ADDR bd_addr,
-                                            tBT_TRANSPORT transport,
-                                            UINT8 pin_len, UINT8 *p_pin,
-                                            UINT32 trusted_mask[]);
+extern tBTM_STATUS BTM_SecBondByTransport (BD_ADDR bd_addr,
+                                           tBT_TRANSPORT transport,
+                                           UINT8 pin_len, UINT8 *p_pin,
+                                           UINT32 trusted_mask[]);
 
 /*******************************************************************************
 **
@@ -3970,7 +3346,7 @@
 ** Returns          BTM_CMD_STARTED if successfully initiated, otherwise error
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SecBondCancel (BD_ADDR bd_addr);
+extern tBTM_STATUS BTM_SecBondCancel (BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -3997,8 +3373,8 @@
 **                  BTM_MODE_UNSUPPORTED - if security manager not linked in.
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetEncryption (BD_ADDR bd_addr, tBT_TRANSPORT transport,
-                                                  tBTM_SEC_CBACK *p_callback, void *p_ref_data);
+extern tBTM_STATUS BTM_SetEncryption (BD_ADDR bd_addr, tBT_TRANSPORT transport,
+                                      tBTM_SEC_CBACK *p_callback, void *p_ref_data);
 
 /*******************************************************************************
 **
@@ -4011,7 +3387,7 @@
 **                  bd_addr       - Address of the peer device
 **
 *******************************************************************************/
-    BTM_API extern void BTM_ConfirmReqReply(tBTM_STATUS res, BD_ADDR bd_addr);
+extern void BTM_ConfirmReqReply(tBTM_STATUS res, BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -4025,7 +3401,7 @@
 **                  passkey       - numeric value in the range of 0 - 999999(0xF423F).
 **
 *******************************************************************************/
-    BTM_API extern void BTM_PasskeyReqReply(tBTM_STATUS res, BD_ADDR bd_addr, UINT32 passkey);
+extern void BTM_PasskeyReqReply(tBTM_STATUS res, BD_ADDR bd_addr, UINT32 passkey);
 
 /*******************************************************************************
 **
@@ -4041,7 +3417,7 @@
 **                  type - notification type
 **
 *******************************************************************************/
-    BTM_API extern void BTM_SendKeypressNotif(BD_ADDR bd_addr, tBTM_SP_KEY_TYPE type);
+extern void BTM_SendKeypressNotif(BD_ADDR bd_addr, tBTM_SP_KEY_TYPE type);
 
 /*******************************************************************************
 **
@@ -4058,8 +3434,8 @@
 **                  auth_req- MITM protection required or not.
 **
 *******************************************************************************/
-    BTM_API extern void BTM_IoCapRsp(BD_ADDR bd_addr, tBTM_IO_CAP io_cap,
-                                     tBTM_OOB_DATA oob, tBTM_AUTH_REQ auth_req);
+extern void BTM_IoCapRsp(BD_ADDR bd_addr, tBTM_IO_CAP io_cap,
+                         tBTM_OOB_DATA oob, tBTM_AUTH_REQ auth_req);
 
 /*******************************************************************************
 **
@@ -4069,7 +3445,7 @@
 **                  LM
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadLocalOobData(void);
+extern tBTM_STATUS BTM_ReadLocalOobData(void);
 
 /*******************************************************************************
 **
@@ -4083,8 +3459,8 @@
 **                  r           - simple pairing Randomizer  C.
 **
 *******************************************************************************/
-    BTM_API extern void BTM_RemoteOobDataReply(tBTM_STATUS res, BD_ADDR bd_addr,
-                                                        BT_OCTET16 c, BT_OCTET16 r);
+extern void BTM_RemoteOobDataReply(tBTM_STATUS res, BD_ADDR bd_addr,
+                                   BT_OCTET16 c, BT_OCTET16 r);
 
 /*******************************************************************************
 **
@@ -4104,8 +3480,8 @@
 ** Returns          Number of bytes in p_data.
 **
 *******************************************************************************/
-    BTM_API extern UINT16 BTM_BuildOobData(UINT8 *p_data, UINT16 max_len, BT_OCTET16 c,
-                                           BT_OCTET16 r, UINT8 name_len);
+extern UINT16 BTM_BuildOobData(UINT8 *p_data, UINT16 max_len, BT_OCTET16 c,
+                               BT_OCTET16 r, UINT8 name_len);
 
 /*******************************************************************************
 **
@@ -4122,7 +3498,7 @@
 **                  NULL, if the tag is not found.
 **
 *******************************************************************************/
-    BTM_API extern UINT8 * BTM_ReadOobData(UINT8 *p_data, UINT8 eir_tag, UINT8 *p_len);
+extern UINT8 * BTM_ReadOobData(UINT8 *p_data, UINT8 eir_tag, UINT8 *p_len);
 
 /*******************************************************************************
 **
@@ -4134,7 +3510,7 @@
 ** Returns          Pointer to the name or NULL
 **
 *******************************************************************************/
-    BTM_API extern char *BTM_SecReadDevName (BD_ADDR bd_addr);
+extern char *BTM_SecReadDevName (BD_ADDR bd_addr);
 
 
 /*****************************************************************************
@@ -4151,8 +3527,8 @@
 **                  BTM_ILLEGAL_VALUE
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_PmRegister (UINT8 mask, UINT8 *p_pm_id,
-                                               tBTM_PM_STATUS_CBACK *p_cb);
+extern tBTM_STATUS BTM_PmRegister (UINT8 mask, UINT8 *p_pm_id,
+                                   tBTM_PM_STATUS_CBACK *p_cb);
 
 
 /*******************************************************************************
@@ -4166,8 +3542,8 @@
 **                  BTM_UNKNOWN_ADDR if bd addr is not active or bad
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetPowerMode (UINT8 pm_id, BD_ADDR remote_bda,
-                                                 tBTM_PM_PWR_MD *p_mode);
+extern tBTM_STATUS BTM_SetPowerMode (UINT8 pm_id, BD_ADDR remote_bda,
+                                     tBTM_PM_PWR_MD *p_mode);
 
 
 /*******************************************************************************
@@ -4190,8 +3566,8 @@
 **                  BTM_UNKNOWN_ADDR if bd addr is not active or bad
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadPowerMode (BD_ADDR remote_bda,
-                                                  tBTM_PM_MODE *p_mode);
+extern tBTM_STATUS BTM_ReadPowerMode (BD_ADDR remote_bda,
+                                      tBTM_PM_MODE *p_mode);
 
 /*******************************************************************************
 **
@@ -4211,21 +3587,8 @@
 **                  BTM_CMD_STORED if the command is stored
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_SetSsrParams (BD_ADDR remote_bda, UINT16 max_lat,
-                                                 UINT16 min_rmt_to, UINT16 min_loc_to);
-
-/*******************************************************************************
-**
-** Function         BTM_IsPowerManagerOn
-**
-** Description      This function is called to check if power manager is included.
-**                  in the BTE version.
-**
-** Returns          TRUE if power manager is compiled in, otherwise FALSE.
-**
-*******************************************************************************/
-    BTM_API extern BOOLEAN BTM_IsPowerManagerOn (void);
-
+extern tBTM_STATUS BTM_SetSsrParams (BD_ADDR remote_bda, UINT16 max_lat,
+                                     UINT16 min_rmt_to, UINT16 min_loc_to);
 
 /*******************************************************************************
 **
@@ -4237,45 +3600,7 @@
 ** Returns          the handle of the connection, or 0xFFFF if none.
 **
 *******************************************************************************/
-    BTM_API extern UINT16 BTM_GetHCIConnHandle (BD_ADDR remote_bda, tBT_TRANSPORT transport);
-
-
-/*******************************************************************************
-**
-** Function         BTM_ReadStoredLinkKey
-**
-** Description      This function is called to obtain link key for the specified
-**                  device from the NVRAM storage attached to the Bluetooth
-**                  controller.
-**
-** Parameters:      bd_addr      - Address of the device
-**                  p_cb         - Call back function to be called to return
-**                                 the results
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ReadStoredLinkKey (BD_ADDR bd_addr,  tBTM_CMPL_CB *p_cb);
-
-
-/*******************************************************************************
-**
-** Function         BTM_WriteStoredLinkKey
-**
-** Description      This function is called to write link keys for the specified
-**                  device addresses to the NVRAM storage attached to the Bluetooth
-**                  controller.
-**
-** Parameters:      num_keys     - Number of link keys
-**                  bd_addr      - Addresses of the devices
-**                  link_key     - Link Keys to be stored
-**                  p_cb         - Call back function to be called to return
-**                                 the results
-**
-*******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_WriteStoredLinkKey (UINT8 num_keys,
-                                                       BD_ADDR *bd_addr,
-                                                       LINK_KEY *link_key,
-                                                       tBTM_CMPL_CB *p_cb);
-
+extern UINT16 BTM_GetHCIConnHandle (BD_ADDR remote_bda, tBT_TRANSPORT transport);
 
 /*******************************************************************************
 **
@@ -4290,7 +3615,7 @@
 **                                 the results
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_DeleteStoredLinkKey(BD_ADDR bd_addr, tBTM_CMPL_CB *p_cb);
+extern tBTM_STATUS BTM_DeleteStoredLinkKey(BD_ADDR bd_addr, tBTM_CMPL_CB *p_cb);
 
 /*******************************************************************************
 **
@@ -4305,7 +3630,7 @@
 **                  BTM_MODE_UNSUPPORTED - if local device cannot support it
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_WriteEIR( BT_HDR * p_buff );
+extern tBTM_STATUS BTM_WriteEIR( BT_HDR * p_buff );
 
 /*******************************************************************************
 **
@@ -4320,7 +3645,7 @@
 ** Returns          pointer of EIR data
 **
 *******************************************************************************/
-    BTM_API extern UINT8 *BTM_CheckEirData( UINT8 *p_eir, UINT8 type, UINT8 *p_length );
+extern UINT8 *BTM_CheckEirData( UINT8 *p_eir, UINT8 type, UINT8 *p_length );
 
 /*******************************************************************************
 **
@@ -4335,7 +3660,7 @@
 **                  FALSE - if not found
 **
 *******************************************************************************/
-    BTM_API extern BOOLEAN BTM_HasEirService( UINT32 *p_eir_uuid, UINT16 uuid16 );
+extern BOOLEAN BTM_HasEirService( UINT32 *p_eir_uuid, UINT16 uuid16 );
 
 /*******************************************************************************
 **
@@ -4351,8 +3676,8 @@
 **                  BTM_EIR_UNKNOWN - if not found and it is not complete list
 **
 *******************************************************************************/
-    BTM_API extern tBTM_EIR_SEARCH_RESULT BTM_HasInquiryEirService( tBTM_INQ_RESULTS *p_results,
-                                                                    UINT16 uuid16 );
+extern tBTM_EIR_SEARCH_RESULT BTM_HasInquiryEirService( tBTM_INQ_RESULTS *p_results,
+                                                        UINT16 uuid16 );
 
 /*******************************************************************************
 **
@@ -4366,7 +3691,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-    BTM_API extern void BTM_AddEirService( UINT32 *p_eir_uuid, UINT16 uuid16 );
+extern void BTM_AddEirService( UINT32 *p_eir_uuid, UINT16 uuid16 );
 
 /*******************************************************************************
 **
@@ -4380,7 +3705,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-    BTM_API extern void BTM_RemoveEirService( UINT32 *p_eir_uuid, UINT16 uuid16 );
+extern void BTM_RemoveEirService( UINT32 *p_eir_uuid, UINT16 uuid16 );
 
 /*******************************************************************************
 **
@@ -4397,8 +3722,8 @@
 **                  BTM_EIR_COMPLETE_16BITS_UUID_TYPE, otherwise
 **
 *******************************************************************************/
-    BTM_API extern UINT8 BTM_GetEirSupportedServices( UINT32 *p_eir_uuid,    UINT8 **p,
-                                                      UINT8  max_num_uuid16, UINT8 *p_num_uuid16);
+extern UINT8 BTM_GetEirSupportedServices( UINT32 *p_eir_uuid,    UINT8 **p,
+                                          UINT8  max_num_uuid16, UINT8 *p_num_uuid16);
 
 /*******************************************************************************
 **
@@ -4421,8 +3746,8 @@
 **                  BTM_EIR_MORE_128BITS_UUID_TYPE
 **
 *******************************************************************************/
-    BTM_API extern UINT8 BTM_GetEirUuidList( UINT8 *p_eir, UINT8 uuid_size, UINT8 *p_num_uuid,
-                                             UINT8 *p_uuid_list, UINT8 max_num_uuid);
+extern UINT8 BTM_GetEirUuidList( UINT8 *p_eir, UINT8 uuid_size, UINT8 *p_num_uuid,
+                                 UINT8 *p_uuid_list, UINT8 max_num_uuid);
 
 /*****************************************************************************
 **  SCO OVER HCI
@@ -4451,10 +3776,10 @@
 **
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_ConfigScoPath (tBTM_SCO_ROUTE_TYPE path,
-                                                  tBTM_SCO_DATA_CB *p_sco_data_cb,
-                                                  tBTM_SCO_PCM_PARAM *p_pcm_param,
-                                                  BOOLEAN err_data_rpt);
+extern tBTM_STATUS BTM_ConfigScoPath (tBTM_SCO_ROUTE_TYPE path,
+                                      tBTM_SCO_DATA_CB *p_sco_data_cb,
+                                      tBTM_SCO_PCM_PARAM *p_pcm_param,
+                                      BOOLEAN err_data_rpt);
 
 /*******************************************************************************
 **
@@ -4477,7 +3802,7 @@
 **
 **
 *******************************************************************************/
-    BTM_API extern tBTM_STATUS BTM_WriteScoData (UINT16 sco_inx, BT_HDR *p_buf);
+extern tBTM_STATUS BTM_WriteScoData (UINT16 sco_inx, BT_HDR *p_buf);
 
 /*******************************************************************************
 **
@@ -4488,7 +3813,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_SetARCMode (UINT8 iface, UINT8 arc_mode, tBTM_VSC_CMPL_CB *p_arc_cb);
+extern void BTM_SetARCMode (UINT8 iface, UINT8 arc_mode, tBTM_VSC_CMPL_CB *p_arc_cb);
 
 
 /*******************************************************************************
@@ -4500,7 +3825,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_PCM2Setup_Write (BOOLEAN clk_master, tBTM_VSC_CMPL_CB *p_arc_cb);
+extern void BTM_PCM2Setup_Write (BOOLEAN clk_master, tBTM_VSC_CMPL_CB *p_arc_cb);
 
 
 /*******************************************************************************
@@ -4512,7 +3837,7 @@
 ** Returns          Controller state (BTM_CONTRL_ACTIVE, BTM_CONTRL_SCAN, and BTM_CONTRL_IDLE)
 **
 *******************************************************************************/
-BTM_API extern tBTM_CONTRL_STATE BTM_PM_ReadControllerState(void);
+extern tBTM_CONTRL_STATE BTM_PM_ReadControllerState(void);
 
 #ifdef __cplusplus
 }
diff --git a/stack/include/btm_ble_api.h b/stack/include/btm_ble_api.h
index 0e76468..5f93c53 100644
--- a/stack/include/btm_ble_api.h
+++ b/stack/include/btm_ble_api.h
@@ -451,6 +451,7 @@
 typedef struct
 {
     UINT8                       inst_id;
+    BOOLEAN                     in_use;
     UINT8                       adv_evt;
     BD_ADDR                     rpa;
     TIMER_LIST_ENT              raddr_timer_ent;
@@ -843,7 +844,7 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_SecAddBleDevice (BD_ADDR bd_addr, BD_NAME bd_name,
+extern BOOLEAN BTM_SecAddBleDevice (BD_ADDR bd_addr, BD_NAME bd_name,
                                            tBT_DEVICE_TYPE dev_type, tBLE_ADDR_TYPE addr_type);
 
 /*******************************************************************************
@@ -861,8 +862,8 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_SecAddBleKey (BD_ADDR bd_addr, tBTM_LE_KEY_VALUE *p_le_key,
-                                         tBTM_LE_KEY_TYPE key_type);
+extern BOOLEAN BTM_SecAddBleKey (BD_ADDR bd_addr, tBTM_LE_KEY_VALUE *p_le_key,
+                                 tBTM_LE_KEY_TYPE key_type);
 
 /*******************************************************************************
 **
@@ -875,8 +876,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleSetAdvParams(UINT16 adv_int_min, UINT16 adv_int_max,
-                                tBLE_BD_ADDR *p_dir_bda, tBTM_BLE_ADV_CHNL_MAP chnl_map);
+extern tBTM_STATUS BTM_BleSetAdvParams(UINT16 adv_int_min, UINT16 adv_int_max,
+                                       tBLE_BD_ADDR *p_dir_bda, tBTM_BLE_ADV_CHNL_MAP chnl_map);
 
 /*******************************************************************************
 **
@@ -889,8 +890,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleWriteAdvData(tBTM_BLE_AD_MASK  data_mask,
-                                               tBTM_BLE_ADV_DATA *p_data);
+extern tBTM_STATUS BTM_BleWriteAdvData(tBTM_BLE_AD_MASK  data_mask,
+                                       tBTM_BLE_ADV_DATA *p_data);
 
 /*******************************************************************************
 **
@@ -906,8 +907,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleReadAdvParams (UINT16 *adv_int_min, UINT16 *adv_int_max,
-                            tBLE_BD_ADDR *p_dir_bda, tBTM_BLE_ADV_CHNL_MAP *p_chnl_map);
+extern void BTM_BleReadAdvParams (UINT16 *adv_int_min, UINT16 *adv_int_max,
+                                  tBLE_BD_ADDR *p_dir_bda, tBTM_BLE_ADV_CHNL_MAP *p_chnl_map);
 
 /*******************************************************************************
 **
@@ -935,8 +936,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleSetScanParams(UINT16 scan_interval, UINT16 scan_window,
-                                         tBTM_BLE_SCAN_MODE scan_type);
+extern void BTM_BleSetScanParams(UINT16 scan_interval, UINT16 scan_window,
+                                 tBTM_BLE_SCAN_MODE scan_type);
 /*******************************************************************************
 **
 ** Function         BTM_BleGetVendorCapabilities
@@ -948,7 +949,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB *p_cmn_vsc_cb);
+extern void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB *p_cmn_vsc_cb);
 /*******************************************************************************
 **
 ** Function         BTM_BleSetStorageConfig
@@ -965,7 +966,7 @@
 ** Returns          tBTM_STATUS
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleSetStorageConfig(UINT8 batch_scan_full_max,
+extern tBTM_STATUS BTM_BleSetStorageConfig(UINT8 batch_scan_full_max,
                                         UINT8 batch_scan_trunc_max,
                                         UINT8 batch_scan_notify_threshold,
                                         tBTM_BLE_SCAN_SETUP_CBACK *p_setup_cback,
@@ -988,7 +989,7 @@
 ** Returns          tBTM_STATUS
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleEnableBatchScan(tBTM_BLE_BATCH_SCAN_MODE scan_mode,
+extern tBTM_STATUS BTM_BleEnableBatchScan(tBTM_BLE_BATCH_SCAN_MODE scan_mode,
                                         UINT32 scan_interval, UINT32 scan_window,
                                         tBTM_BLE_DISCARD_RULE discard_rule,
                                         tBLE_ADDR_TYPE addr_type,
@@ -1005,7 +1006,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleDisableBatchScan(tBTM_BLE_REF_VALUE ref_value);
+extern tBTM_STATUS BTM_BleDisableBatchScan(tBTM_BLE_REF_VALUE ref_value);
 
 /*******************************************************************************
 **
@@ -1019,7 +1020,7 @@
 ** Returns          tBTM_STATUS
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleReadScanReports(tBTM_BLE_SCAN_MODE scan_mode,
+extern tBTM_STATUS BTM_BleReadScanReports(tBTM_BLE_SCAN_MODE scan_mode,
                                                   tBTM_BLE_REF_VALUE ref_value);
 
 /*******************************************************************************
@@ -1034,7 +1035,7 @@
 ** Returns          tBTM_STATUS
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleTrackAdvertiser(tBTM_BLE_TRACK_ADV_CBACK *p_track_cback,
+extern tBTM_STATUS BTM_BleTrackAdvertiser(tBTM_BLE_TRACK_ADV_CBACK *p_track_cback,
                                                   tBTM_BLE_REF_VALUE ref_value);
 
 /*******************************************************************************
@@ -1048,8 +1049,8 @@
 ** Returns          status
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleWriteScanRsp(tBTM_BLE_AD_MASK data_mask,
-                                               tBTM_BLE_ADV_DATA *p_data);
+extern tBTM_STATUS BTM_BleWriteScanRsp(tBTM_BLE_AD_MASK data_mask,
+                                       tBTM_BLE_ADV_DATA *p_data);
 
 /*******************************************************************************
 **
@@ -1063,8 +1064,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleObserve(BOOLEAN start, UINT8 duration,
-                           tBTM_INQ_RESULTS_CB *p_results_cb, tBTM_CMPL_CB *p_cmpl_cb);
+extern tBTM_STATUS BTM_BleObserve(BOOLEAN start, UINT8 duration,
+                                  tBTM_INQ_RESULTS_CB *p_results_cb, tBTM_CMPL_CB *p_cmpl_cb);
 
 
 /*******************************************************************************
@@ -1078,7 +1079,7 @@
 **                  the local device ER is copied into er
 **
 *******************************************************************************/
-BTM_API extern void BTM_GetDeviceIDRoot (BT_OCTET16 ir);
+extern void BTM_GetDeviceIDRoot (BT_OCTET16 ir);
 
 /*******************************************************************************
 **
@@ -1091,7 +1092,7 @@
 **                  the local device ER is copied into er
 **
 *******************************************************************************/
-BTM_API extern void BTM_GetDeviceEncRoot (BT_OCTET16 er);
+extern void BTM_GetDeviceEncRoot (BT_OCTET16 er);
 
 /*******************************************************************************
 **
@@ -1103,7 +1104,7 @@
 **                  the local device DHK is copied into dhk
 **
 *******************************************************************************/
-BTM_API extern void BTM_GetDeviceDHK (BT_OCTET16 dhk);
+extern void BTM_GetDeviceDHK (BT_OCTET16 dhk);
 
 /*******************************************************************************
 **
@@ -1118,7 +1119,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-BTM_API extern void BTM_SecurityGrant(BD_ADDR bd_addr, UINT8 res);
+extern void BTM_SecurityGrant(BD_ADDR bd_addr, UINT8 res);
 
 /*******************************************************************************
 **
@@ -1133,7 +1134,7 @@
 **                  BTM_MIN_PASSKEY_VAL(0) - BTM_MAX_PASSKEY_VAL(999999(0xF423F)).
 **
 *******************************************************************************/
-BTM_API extern void BTM_BlePasskeyReply (BD_ADDR bd_addr, UINT8 res, UINT32 passkey);
+extern void BTM_BlePasskeyReply (BD_ADDR bd_addr, UINT8 res, UINT32 passkey);
 
 /*******************************************************************************
 **
@@ -1147,7 +1148,7 @@
 **                  p_data      - simple pairing Randomizer  C.
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleOobDataReply(BD_ADDR bd_addr, UINT8 res, UINT8 len, UINT8 *p_data);
+extern void BTM_BleOobDataReply(BD_ADDR bd_addr, UINT8 res, UINT8 len, UINT8 *p_data);
 
 
 /*******************************************************************************
@@ -1166,8 +1167,8 @@
 ** Returns          TRUE if signing sucessul, otherwise FALSE.
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_BleDataSignature (BD_ADDR bd_addr, UINT8 *p_text, UINT16 len,
-                                             BLE_SIGNATURE signature);
+extern BOOLEAN BTM_BleDataSignature (BD_ADDR bd_addr, UINT8 *p_text, UINT16 len,
+                                     BLE_SIGNATURE signature);
 
 /*******************************************************************************
 **
@@ -1184,9 +1185,9 @@
 ** Returns          TRUE if signature verified correctly; otherwise FALSE.
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_BleVerifySignature (BD_ADDR bd_addr, UINT8 *p_orig,
-                                            UINT16 len, UINT32 counter,
-                                            UINT8 *p_comp);
+extern BOOLEAN BTM_BleVerifySignature (BD_ADDR bd_addr, UINT8 *p_orig,
+                                       UINT16 len, UINT32 counter,
+                                       UINT8 *p_comp);
 
 /*******************************************************************************
 **
@@ -1198,7 +1199,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_ReadConnectionAddr (BD_ADDR remote_bda, BD_ADDR local_conn_addr,
+extern void BTM_ReadConnectionAddr (BD_ADDR remote_bda, BD_ADDR local_conn_addr,
                                             tBLE_ADDR_TYPE *p_addr_type);
 
 
@@ -1213,7 +1214,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_ReadRemoteConnectionAddr(BD_ADDR pseudo_addr,
+extern BOOLEAN BTM_ReadRemoteConnectionAddr(BD_ADDR pseudo_addr,
                                                     BD_ADDR conn_addr,
                                                     tBLE_ADDR_TYPE *p_addr_type);
 
@@ -1230,7 +1231,7 @@
 ** Returns          non2.
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleLoadLocalKeys(UINT8 key_type, tBTM_BLE_LOCAL_KEYS *p_key);
+extern void BTM_BleLoadLocalKeys(UINT8 key_type, tBTM_BLE_LOCAL_KEYS *p_key);
 
 
 /*******************************************************************************
@@ -1247,7 +1248,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_BleSetBgConnType(tBTM_BLE_CONN_TYPE   conn_type,
+extern BOOLEAN BTM_BleSetBgConnType(tBTM_BLE_CONN_TYPE   conn_type,
                                     tBTM_BLE_SEL_CBACK   *p_select_cback);
 
 /*******************************************************************************
@@ -1265,7 +1266,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_BleUpdateBgConnDev(BOOLEAN add_remove, BD_ADDR   remote_bda);
+extern BOOLEAN BTM_BleUpdateBgConnDev(BOOLEAN add_remove, BD_ADDR   remote_bda);
 
 /*******************************************************************************
 **
@@ -1280,7 +1281,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleClearBgConnDev(void);
+extern void BTM_BleClearBgConnDev(void);
 
 /********************************************************
 **
@@ -1300,7 +1301,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern  void BTM_BleSetPrefConnParams (BD_ADDR bd_addr,
+extern  void BTM_BleSetPrefConnParams (BD_ADDR bd_addr,
                                                UINT16 min_conn_int,  UINT16 max_conn_int,
                                                UINT16 slave_latency, UINT16 supervision_tout);
 
@@ -1316,7 +1317,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern  void BTM_BleSetConnScanParams (UINT16 scan_interval, UINT16 scan_window);
+extern  void BTM_BleSetConnScanParams (UINT16 scan_interval, UINT16 scan_window);
 
 /******************************************************************************
 **
@@ -1329,7 +1330,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK  *p_vsc_cback);
+extern void BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK  *p_vsc_cback);
 
 /*******************************************************************************
 **
@@ -1344,7 +1345,7 @@
 ** Returns          pointer of ADV data
 **
 *******************************************************************************/
-BTM_API extern  UINT8 *BTM_CheckAdvData( UINT8 *p_adv, UINT8 type, UINT8 *p_length);
+extern  UINT8 *BTM_CheckAdvData( UINT8 *p_adv, UINT8 type, UINT8 *p_length);
 
 /*******************************************************************************
 **
@@ -1358,7 +1359,7 @@
 **                  p_addr_type: output parameter to read the address type.
 **
 *******************************************************************************/
-BTM_API extern void BTM_ReadDevInfo (BD_ADDR remote_bda, tBT_DEVICE_TYPE *p_dev_type,
+extern void BTM_ReadDevInfo (BD_ADDR remote_bda, tBT_DEVICE_TYPE *p_dev_type,
                                      tBLE_ADDR_TYPE *p_addr_type);
 
 /*******************************************************************************
@@ -1372,7 +1373,7 @@
 ** Returns          status.
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleBroadcast(BOOLEAN start);
+extern tBTM_STATUS BTM_BleBroadcast(BOOLEAN start);
 
 /*******************************************************************************
 **
@@ -1387,7 +1388,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_RegisterScanReqEvt(tBTM_BLE_SCAN_REQ_CBACK *p_scan_req_cback);
+extern void BTM_RegisterScanReqEvt(tBTM_BLE_SCAN_REQ_CBACK *p_scan_req_cback);
 
 /*******************************************************************************
 **
@@ -1401,7 +1402,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleConfigPrivacy(BOOLEAN enable);
+extern void BTM_BleConfigPrivacy(BOOLEAN enable);
 
 /*******************************************************************************
 **
@@ -1412,7 +1413,7 @@
 ** Returns          Return TRUE if local privacy is enabled else FALSE
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_BleLocalPrivacyEnabled();
+extern BOOLEAN BTM_BleLocalPrivacyEnabled();
 
 /*******************************************************************************
 **
@@ -1423,7 +1424,7 @@
 ** Returns          Max multi adv instance count
 **
 *******************************************************************************/
-BTM_API extern UINT8  BTM_BleMaxMultiAdvInstanceCount();
+extern UINT8  BTM_BleMaxMultiAdvInstanceCount();
 
 /*******************************************************************************
 **
@@ -1438,7 +1439,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleSetConnMode(BOOLEAN directed);
+extern tBTM_STATUS BTM_BleSetConnMode(BOOLEAN directed);
 
 /*******************************************************************************
 **
@@ -1453,7 +1454,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern void BTM_BleTurnOnPrivacyOnRemote(BD_ADDR bd_addr,
+extern void BTM_BleTurnOnPrivacyOnRemote(BD_ADDR bd_addr,
                                                  BOOLEAN privacy_on);
 
 
@@ -1466,7 +1467,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_BleUpdateAdvWhitelist(BOOLEAN add_remove, BD_ADDR emote_bda);
+extern BOOLEAN BTM_BleUpdateAdvWhitelist(BOOLEAN add_remove, BD_ADDR emote_bda);
 
 /*******************************************************************************
 **
@@ -1478,7 +1479,7 @@
 **
 ** Return           void
 *******************************************************************************/
-BTM_API extern void BTM_BleUpdateAdvFilterPolicy(tBTM_BLE_AFP adv_policy);
+extern void BTM_BleUpdateAdvFilterPolicy(tBTM_BLE_AFP adv_policy);
 
 /*******************************************************************************
 **
@@ -1528,7 +1529,7 @@
 ** Returns          TRUE to use LE, FALSE use BR/EDR.
 **
 *******************************************************************************/
-BTM_API extern BOOLEAN BTM_UseLeLink (BD_ADDR bd_addr);
+extern BOOLEAN BTM_UseLeLink (BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -1542,7 +1543,7 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleStackEnable (BOOLEAN enable);
+extern tBTM_STATUS BTM_BleStackEnable (BOOLEAN enable);
 
 /*******************************************************************************/
 /*                          Multi ADV API                                      */
@@ -1561,7 +1562,7 @@
 ** Returns          status
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleEnableAdvInstance (tBTM_BLE_ADV_PARAMS *p_params,
+extern tBTM_STATUS BTM_BleEnableAdvInstance (tBTM_BLE_ADV_PARAMS *p_params,
                                       tBTM_BLE_MULTI_ADV_CBACK *p_cback,
                                       void *p_ref);
 
@@ -1578,7 +1579,7 @@
 ** Returns          status
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleUpdateAdvInstParam (UINT8 inst_id, tBTM_BLE_ADV_PARAMS *p_params);
+extern tBTM_STATUS BTM_BleUpdateAdvInstParam (UINT8 inst_id, tBTM_BLE_ADV_PARAMS *p_params);
 
 /*******************************************************************************
 **
@@ -1595,7 +1596,7 @@
 ** Returns          status
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleCfgAdvInstData (UINT8 inst_id, BOOLEAN is_scan_rsp,
+extern tBTM_STATUS BTM_BleCfgAdvInstData (UINT8 inst_id, BOOLEAN is_scan_rsp,
                                     tBTM_BLE_AD_MASK data_mask,
                                     tBTM_BLE_ADV_DATA *p_data);
 
@@ -1610,7 +1611,7 @@
 ** Returns          status
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleDisableAdvInstance (UINT8 inst_id);
+extern tBTM_STATUS BTM_BleDisableAdvInstance (UINT8 inst_id);
 
 /*******************************************************************************
 **
@@ -1626,7 +1627,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleAdvFilterParamSetup(int action,
+extern tBTM_STATUS BTM_BleAdvFilterParamSetup(int action,
                                 tBTM_BLE_PF_FILT_INDEX filt_index,
                                 tBTM_BLE_PF_FILT_PARAMS *p_filt_params,
                                 tBLE_BD_ADDR *p_target, tBTM_BLE_PF_PARAM_CBACK *p_cmpl_cback,
@@ -1646,7 +1647,7 @@
 ** Returns          tBTM_STATUS
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleCfgFilterCondition(tBTM_BLE_SCAN_COND_OP action,
+extern tBTM_STATUS BTM_BleCfgFilterCondition(tBTM_BLE_SCAN_COND_OP action,
                                       tBTM_BLE_PF_COND_TYPE cond_type,
                                       tBTM_BLE_PF_FILT_INDEX filt_index,
                                       tBTM_BLE_PF_COND_PARAM *p_cond,
@@ -1665,7 +1666,7 @@
 ** Returns          tBTM_STATUS
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleEnableDisableFilterFeature(UINT8 enable,
+extern tBTM_STATUS BTM_BleEnableDisableFilterFeature(UINT8 enable,
                                                tBTM_BLE_PF_STATUS_CBACK *p_stat_cback,
                                                tBTM_BLE_REF_VALUE ref_value);
 
@@ -1680,7 +1681,7 @@
 ** Returns          status
 **
 *******************************************************************************/
-BTM_API extern tBTM_STATUS BTM_BleGetEnergyInfo(tBTM_BLE_ENERGY_INFO_CBACK *p_ener_cback);
+extern tBTM_STATUS BTM_BleGetEnergyInfo(tBTM_BLE_ENERGY_INFO_CBACK *p_ener_cback);
 
 #ifdef __cplusplus
 }
diff --git a/stack/include/btu.h b/stack/include/btu.h
index 5526536..ca56301 100644
--- a/stack/include/btu.h
+++ b/stack/include/btu.h
@@ -30,10 +30,24 @@
 #include "bt_target.h"
 #include "gki.h"
 
-/* Define the BTU mailbox usage
-*/
-#define BTU_HCI_RCV_MBOX        TASK_MBOX_0     /* Messages from HCI  */
-#define BTU_BTIF_MBOX           TASK_MBOX_1     /* Messages to BTIF   */
+// HACK(zachoverflow): temporary dark magic
+#define BTU_POST_TO_TASK_NO_GOOD_HORRIBLE_HACK 0x1700 // didn't look used in bt_types...here goes nothing
+typedef struct {
+  void (*callback)(BT_HDR *);
+} post_to_task_hack_t;
+
+typedef struct {
+  void (*callback)(BT_HDR *);
+  BT_HDR *response;
+  void *context;
+} command_complete_hack_t;
+
+typedef struct {
+  void (*callback)(BT_HDR *);
+  uint8_t status;
+  BT_HDR *command;
+  void *context;
+} command_status_hack_t;
 
 /* callbacks
 */
@@ -99,12 +113,6 @@
 /* BNEP Timers */
 #define BTU_TTYPE_BNEP              50
 
-/* OBX */
-#define BTU_TTYPE_OBX_CLIENT_TO     51
-#define BTU_TTYPE_OBX_SERVER_TO     52
-#define BTU_TTYPE_OBX_SVR_SESS_TO   53
-
-
 #define BTU_TTYPE_HSP2_SDP_FAIL_TO  55
 #define BTU_TTYPE_HSP2_SDP_RTRY_TO  56
 
@@ -136,12 +144,6 @@
 #define BTU_TTYPE_L2CAP_FCR_ACK     78
 #define BTU_TTYPE_L2CAP_INFO        79
 
-/* BTU internal for BR/EDR and AMP HCI command timeout (reserve up to 3 AMP controller) */
-#define BTU_TTYPE_BTU_CMD_CMPL                      80
-#define BTU_TTYPE_BTU_AMP1_CMD_CMPL                 81
-#define BTU_TTYPE_BTU_AMP2_CMD_CMPL                 82
-#define BTU_TTYPE_BTU_AMP3_CMD_CMPL                 83
-
 #define BTU_TTYPE_MCA_CCB_RSP                       98
 
 /* BTU internal timer for BLE activity */
@@ -159,14 +161,6 @@
 
 #define BTU_TTYPE_UCD_TO                            108
 
-
-
-/* Define the BTU_TASK APPL events
-*/
-#if (defined(NFC_SHARED_TRANSPORT_ENABLED) && (NFC_SHARED_TRANSPORT_ENABLED==TRUE))
-#define BTU_NFC_AVAILABLE_EVT   EVENT_MASK(APPL_EVT_0)  /* Notifies BTU task that NFC is available (used for shared NFC+BT transport) */
-#endif
-
 /* This is the inquiry response information held by BTU, and available
 ** to applications.
 */
@@ -210,18 +204,6 @@
 #define NFC_CONTROLLER_ID       (1)
 #define BTU_MAX_LOCAL_CTRLS     (1 + NFC_MAX_LOCAL_CTRLS) /* only BR/EDR */
 
-/* AMP HCI control block */
-typedef struct
-{
-    BUFFER_Q         cmd_xmit_q;
-    BUFFER_Q         cmd_cmpl_q;
-    UINT16           cmd_window;
-    TIMER_LIST_ENT   cmd_cmpl_timer;        /* Command complete timer */
-#if (defined(BTU_CMD_CMPL_TOUT_DOUBLE_CHECK) && BTU_CMD_CMPL_TOUT_DOUBLE_CHECK == TRUE)
-    BOOLEAN          checked_hcisu;
-#endif
-} tHCI_CMD_CB;
-
 /* Define structure holding BTU variables
 */
 typedef struct
@@ -229,26 +211,8 @@
     tBTU_TIMER_REG   timer_reg[BTU_MAX_REG_TIMER];
     tBTU_EVENT_REG   event_reg[BTU_MAX_REG_EVENT];
 
-    TIMER_LIST_Q  quick_timer_queue;        /* Timer queue for transport level (100/10 msec)*/
-    TIMER_LIST_Q  timer_queue;              /* Timer queue for normal BTU task (1 second)   */
-    TIMER_LIST_Q  timer_queue_oneshot;      /* Timer queue for oneshot BTU tasks */
-
-    TIMER_LIST_ENT   cmd_cmpl_timer;        /* Command complete timer */
-
-    UINT16    hcit_acl_data_size;           /* Max ACL data size across HCI transport    */
-    UINT16    hcit_acl_pkt_size;            /* Max ACL packet size across HCI transport  */
-                                            /* (this is data size plus 4 bytes overhead) */
-
-#if BLE_INCLUDED == TRUE
-    UINT16    hcit_ble_acl_data_size;           /* Max BLE ACL data size across HCI transport    */
-    UINT16    hcit_ble_acl_pkt_size;            /* Max BLE ACL packet size across HCI transport  */
-                                            /* (this is data size plus 4 bytes overhead) */
-#endif
-
     BOOLEAN     reset_complete;             /* TRUE after first ack from device received */
     UINT8       trace_level;                /* Trace level for HCI layer */
-
-    tHCI_CMD_CB hci_cmd_cb[BTU_MAX_LOCAL_CTRLS]; /* including BR/EDR */
 } tBTU_CB;
 
 #ifdef __cplusplus
@@ -257,57 +221,55 @@
 
 /* Global BTU data */
 #if BTU_DYNAMIC_MEMORY == FALSE
-BTU_API extern tBTU_CB  btu_cb;
+extern tBTU_CB  btu_cb;
 #else
-BTU_API extern tBTU_CB *btu_cb_ptr;
+extern tBTU_CB *btu_cb_ptr;
 #define btu_cb (*btu_cb_ptr)
 #endif
 
-BTU_API extern const BD_ADDR        BT_BD_ANY;
+extern const BD_ADDR        BT_BD_ANY;
 
 /* Functions provided by btu_task.c
 ************************************
 */
-BTU_API extern void btu_start_timer (TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout);
-BTU_API extern void btu_stop_timer (TIMER_LIST_ENT *p_tle);
-BTU_API extern void btu_start_timer_oneshot(TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout);
-BTU_API extern void btu_stop_timer_oneshot(TIMER_LIST_ENT *p_tle);
+extern void btu_start_timer (TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout);
+extern void btu_stop_timer (TIMER_LIST_ENT *p_tle);
+extern void btu_start_timer_oneshot(TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout);
+extern void btu_stop_timer_oneshot(TIMER_LIST_ENT *p_tle);
 
-BTU_API extern UINT32 btu_remaining_time (TIMER_LIST_ENT *p_tle);
+extern void btu_uipc_rx_cback(BT_HDR *p_msg);
 
-BTU_API extern void btu_uipc_rx_cback(BT_HDR *p_msg);
-
-BTU_API extern void btu_hcif_flush_cmd_queue(void);
 /*
 ** Quick Timer
 */
 #if defined(QUICK_TIMER_TICKS_PER_SEC) && (QUICK_TIMER_TICKS_PER_SEC > 0)
-#define QUICK_TIMER_TICKS (GKI_SECS_TO_TICKS (1)/QUICK_TIMER_TICKS_PER_SEC)
-BTU_API extern void btu_start_quick_timer (TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout);
-BTU_API extern void btu_stop_quick_timer (TIMER_LIST_ENT *p_tle);
-BTU_API extern void btu_process_quick_timer_evt (void);
-BTU_API extern void process_quick_timer_evt (TIMER_LIST_Q *p_tlq);
+extern void btu_start_quick_timer (TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout);
+extern void btu_stop_quick_timer (TIMER_LIST_ENT *p_tle);
+extern void btu_process_quick_timer_evt (void);
 #endif
 
 #if (defined(HCILP_INCLUDED) && HCILP_INCLUDED == TRUE)
-BTU_API extern void btu_check_bt_sleep (void);
+extern void btu_check_bt_sleep (void);
 #endif
 
 /* Functions provided by btu_hcif.c
 ************************************
 */
-BTU_API extern void  btu_hcif_process_event (UINT8 controller_id, BT_HDR *p_buf);
-BTU_API extern void  btu_hcif_send_cmd (UINT8 controller_id, BT_HDR *p_msg);
-BTU_API extern void  btu_hcif_send_host_rdy_for_data(void);
-BTU_API extern void  btu_hcif_cmd_timeout (UINT8 controller_id);
+extern void  btu_hcif_process_event (UINT8 controller_id, BT_HDR *p_buf);
+extern void  btu_hcif_send_cmd (UINT8 controller_id, BT_HDR *p_msg);
+extern void  btu_hcif_send_host_rdy_for_data(void);
+extern void  btu_hcif_cmd_timeout (UINT8 controller_id);
 
 /* Functions provided by btu_core.c
 ************************************
 */
-BTU_API extern void  btu_init_core(void);
-BTU_API extern void  BTE_Init(void);
-BTU_API extern UINT16 BTU_AclPktSize(void);
-BTU_API extern UINT16 BTU_BleAclPktSize(void);
+extern void  btu_init_core(void);
+extern void  btu_free_core(void);
+
+void BTU_StartUp(void);
+void BTU_ShutDown(void);
+
+extern UINT16 BTU_BleAclPktSize(void);
 
 #ifdef __cplusplus
 }
diff --git a/stack/include/dyn_mem.h b/stack/include/dyn_mem.h
index 3ad8361..2693ae6 100644
--- a/stack/include/dyn_mem.h
+++ b/stack/include/dyn_mem.h
@@ -19,15 +19,6 @@
 #define DYN_MEM_H
 
 /****************************************************************************
-** Define memory usage for GKI (if not defined in bdroid_buildcfg.h)
-**  The default for GKI is to use static memory allocation for its control
-**  block.
-*/
-#ifndef GKI_DYNAMIC_MEMORY
-#define GKI_DYNAMIC_MEMORY  FALSE
-#endif
-
-/****************************************************************************
 ** Define memory usage for each CORE component (if not defined in bdroid_buildcfg.h)
 **  The default for each component is to use static memory allocations.
 */
@@ -55,10 +46,6 @@
 #define TCS_DYNAMIC_MEMORY  FALSE
 #endif
 
-#ifndef OBX_DYNAMIC_MEMORY
-#define OBX_DYNAMIC_MEMORY  FALSE
-#endif
-
 #ifndef BNEP_DYNAMIC_MEMORY
 #define BNEP_DYNAMIC_MEMORY FALSE
 #endif
@@ -111,22 +98,10 @@
 #define CTP_DYNAMIC_MEMORY  FALSE
 #endif
 
-#ifndef DUN_DYNAMIC_MEMORY
-#define DUN_DYNAMIC_MEMORY  FALSE
-#endif
-
 #ifndef FTP_DYNAMIC_MEMORY
 #define FTP_DYNAMIC_MEMORY  FALSE
 #endif
 
-#ifndef GAP_DYNAMIC_MEMORY
-#define GAP_DYNAMIC_MEMORY  FALSE
-#endif
-
-#ifndef GOEP_DYNAMIC_MEMORY
-#define GOEP_DYNAMIC_MEMORY FALSE
-#endif
-
 #ifndef HCRP_DYNAMIC_MEMORY
 #define HCRP_DYNAMIC_MEMORY FALSE
 #endif
@@ -175,13 +150,5 @@
 #define BTA_DYNAMIC_MEMORY FALSE
 #endif
 
-/****************************************************************************
-** Define memory usage for BT Trace (if not defined in bdroid_buildcfg.h)
-**  The default is to use static memory allocations.
-*/
-#ifndef BTTRC_DYNAMIC_MEMORY
-#define BTTRC_DYNAMIC_MEMORY FALSE
-#endif
-
 #endif  /* #ifdef DYN_MEM_H */
 
diff --git a/stack/include/gap_api.h b/stack/include/gap_api.h
index a210f69..0d86d07 100644
--- a/stack/include/gap_api.h
+++ b/stack/include/gap_api.h
@@ -19,117 +19,10 @@
 #ifndef GAP_API_H
 #define GAP_API_H
 
-#include "profiles_api.h"
-#include "btm_api.h"
-#include "l2c_api.h"
-
 /*****************************************************************************
 **  Constants
 *****************************************************************************/
 
-/*** GAP Error and Status Codes ***/
-#define GAP_UNSUPPORTED     (GAP_ERR_GRP + 0x01)    /* Unsupported call */
-#define GAP_EOINQDB         (GAP_ERR_GRP + 0x02)    /* End of inquiry database marker */
-#define GAP_ERR_BUSY        (GAP_ERR_GRP + 0x03)    /* The requested function was busy */
-#define GAP_ERR_NO_CTRL_BLK (GAP_ERR_GRP + 0x04)    /* No control blocks available */
-#define GAP_ERR_STARTING_CMD (GAP_ERR_GRP + 0x05)   /* Error occurred while initiating the command */
-#define GAP_NO_BDADDR_REC   (GAP_ERR_GRP + 0x06)    /* No Inquiry DB record for BD_ADDR */
-#define GAP_ERR_ILL_MODE    (GAP_ERR_GRP + 0x07)    /* An illegal mode parameter was detected */
-#define GAP_ERR_ILL_INQ_TIME (GAP_ERR_GRP + 0x08)   /* An illegal time parameter was detected */
-#define GAP_ERR_ILL_PARM     (GAP_ERR_GRP + 0x09)   /* An illegal parameter was detected */
-#define GAP_ERR_REM_NAME    (GAP_ERR_GRP + 0x0a)    /* Error starting the remote device name request */
-#define GAP_CMD_INITIATED   (GAP_ERR_GRP + 0x0b)    /* The GAP command was started (result pending) */
-#define GAP_DEVICE_NOT_UP   (GAP_ERR_GRP + 0x0c)    /* The device was not up; the request was not executed */
-#define GAP_BAD_BD_ADDR     (GAP_ERR_GRP + 0x0d)    /* The bd addr passed in was not found or invalid */
-
-#define GAP_ERR_BAD_HANDLE  (GAP_ERR_GRP + 0x0e)    /* Bad GAP handle                       */
-#define GAP_ERR_BUF_OFFSET  (GAP_ERR_GRP + 0x0f)    /* Buffer offset invalid                */
-#define GAP_ERR_BAD_STATE   (GAP_ERR_GRP + 0x10)    /* Connection is in invalid state       */
-#define GAP_NO_DATA_AVAIL   (GAP_ERR_GRP + 0x11)    /* No data available                    */
-#define GAP_ERR_CONGESTED   (GAP_ERR_GRP + 0x12)    /* BT stack is congested                */
-#define GAP_ERR_SECURITY    (GAP_ERR_GRP + 0x13)    /* Security failed                      */
-
-#define GAP_ERR_PROCESSING  (GAP_ERR_GRP + 0x14)    /* General error processing BTM request */
-#define GAP_ERR_TIMEOUT     (GAP_ERR_GRP + 0x15)    /* Timeout occurred while processing cmd */
-
-/** GAP Events - definitions of GAP return events ***/
-#define GAP_EVT_INQUIRY_RESULTS     0x0001
-#define GAP_EVT_INQUIRY_COMPLETE    0x0002
-#define GAP_EVT_DISCOVERY_COMPLETE  0x0003
-#define GAP_EVT_REM_NAME_COMPLETE   0x0004
-#define GAP_EVT_FIND_ADDR_COMPLETE  0x0005
-
-#define GAP_EVT_CONN_OPENED         0x0100
-#define GAP_EVT_CONN_CLOSED         0x0101
-#define GAP_EVT_CONN_DATA_AVAIL     0x0102
-#define GAP_EVT_CONN_CONGESTED      0x0103
-#define GAP_EVT_CONN_UNCONGESTED    0x0104
-
-/* Values for 'chan_mode_mask' field */
-/* GAP_ConnOpen() - optional channels to negotiate */
-#define GAP_FCR_CHAN_OPT_BASIC      L2CAP_FCR_CHAN_OPT_BASIC
-#define GAP_FCR_CHAN_OPT_ERTM       L2CAP_FCR_CHAN_OPT_ERTM
-#define GAP_FCR_CHAN_OPT_STREAM     L2CAP_FCR_CHAN_OPT_STREAM
-
-/*** discovery of devices ***/
-#define GAP_INQUIRY_NONE            BTM_INQUIRY_NONE
-#define GAP_GENERAL_INQUIRY         BTM_GENERAL_INQUIRY
-#define GAP_LIMITED_INQUIRY         BTM_LIMITED_INQUIRY
-
-#if BLE_INCLUDED == TRUE
-#define GAP_BLE_INQUIRY_NONE        BTM_BLE_INQUIRY_NONE
-#define GAP_BLE_GENERAL_INQUIRY     BTM_BLE_GENERAL_INQUIRY
-#define GAP_BLE_LIMITED_INQUIRY     BTM_BLE_LIMITED_INQUIRY
-#endif
-
-/*** discoverable modes ***/
-#define GAP_NON_DISCOVERABLE        BTM_NON_DISCOVERABLE
-#define GAP_LIMITED_DISCOVERABLE    BTM_LIMITED_DISCOVERABLE
-#define GAP_GENERAL_DISCOVERABLE    BTM_GENERAL_DISCOVERABLE
-
-/*** Inquiry Filter Condition types  (The values are defined in btm_api.h) ***/
-#define GAP_CLR_INQUIRY_FILTER      BTM_CLR_INQUIRY_FILTER          /* Inquiry Filtering is turned off */
-#define GAP_FILTER_COND_DEVICE_CLASS BTM_FILTER_COND_DEVICE_CLASS    /* Filter on device class */
-#define GAP_FILTER_COND_BD_ADDR     BTM_FILTER_COND_BD_ADDR         /* Filter on device addr */
-
-/*** connectability ***/
-#define GAP_NON_CONNECTABLE         BTM_NON_CONNECTABLE
-#define GAP_CONNECTABLE             BTM_CONNECTABLE
-
-/*** security features ***/
-#define GAP_DISALLOW_PAIRING        0
-#define GAP_ALLOW_PAIRING           1
-
-/*** class of device settings ***/
-#define GAP_SET_COD_MAJOR_MINOR     0x01
-#define GAP_SET_COD_SERVICE_CLASS   0x02 /* only set the bits in the input */
-#define GAP_CLR_COD_SERVICE_CLASS   0x04
-#define GAP_SET_COD_ALL             0x08 /* take service class as the input (may clear some set bits!!) */
-#define GAP_INIT_COD                0x0a
-
-/*** used in connection variables and functions ***/
-#define GAP_INVALID_HANDLE      0xFFFF
-
-/* This is used to change the criteria for AMP  */
-#define GAP_PROTOCOL_ID         (UUID_PROTOCOL_UDP)
-
-/* slave preferred parameter, minimum connection interval */
-#ifndef GAP_SL_CONN_INT_MIN
-#define GAP_SL_CONN_INT_MIN     6
-#endif
-/* slave preferred parameter, maximum connection interval */
-#ifndef GAP_SL_CONN_INT_MAX
-#define GAP_SL_CONN_INT_MAX     20
-#endif
-/* slave preferred parameter */
-#ifndef GAP_SL_LATENCY
-#define GAP_SL_LATENCY     2
-#endif
-
-#ifndef GAP_BLE_PRIVACY_RECONN_ADDR_PERM
-#define GAP_BLE_PRIVACY_RECONN_ADDR_PERM        (GATT_PERM_READ|GATT_PERM_WRITE)
-#endif
-
 #ifndef  GAP_PREFER_CONN_INT_MAX
 #define  GAP_PREFER_CONN_INT_MAX         BTM_BLE_CONN_INT_MIN
 #endif
@@ -149,60 +42,6 @@
 /*****************************************************************************
 **  Type Definitions
 *****************************************************************************/
-/*
-** Callback function for connection services
-*/
-typedef void (tGAP_CONN_CALLBACK) (UINT16 gap_handle, UINT16 event);
-
-/*
-** Define the callback function prototypes.  Parameters are specific
-** to each event and are described below
-*/
-typedef void (tGAP_CALLBACK) (UINT16 event, void *p_data);
-
-typedef tBTM_REMOTE_DEV_NAME    tGAP_REMOTE_DEV_NAME;   /* see btm_api.h */
-typedef tBTM_INQ_PARMS          tGAP_INQ_PARMS;         /* see btm_api.h */
-typedef tBTM_INQ_RESULTS        tGAP_INQ_RESULTS;       /* see btm_api.h */
-
-/* Inquiry results structure */
-typedef struct
-{
-    UINT16  status;
-    UINT8   num_results;
-} tGAP_INQ_CMPL;
-
-/* Definition of the GAP_FindAddrByName results structure */
-typedef struct
-{
-    UINT16       status;
-    BD_ADDR      bd_addr;
-    tBTM_BD_NAME devname;
-} tGAP_FINDADDR_RESULTS;
-
-/** for GAP_SetDeviceClass() **/
-/* Define Class of Device related values
- *
- * >>> changes to this type need to also be made to tHSP_COD in hsp2_int.h
- */
-typedef struct
-{
-    UINT8       minor;
-    UINT8       major;
-    UINT16      service;
-} tGAP_COD;
-
-/*** Constants and functions for device features ***/
-typedef struct
-{
-    UINT8   lmp_version;
-    UINT16  mfc_name;
-    UINT16  lmp_subversion;
-} tGAP_LMP_VERSION;
-
-typedef struct
-{
-    UINT8   lmp_features[8];
-} tGAP_LMP_FEATURES;
 
 typedef struct
 {
@@ -229,482 +68,6 @@
 /*****************************************************************************
 **  External Function Declarations
 *****************************************************************************/
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/*******************************************************************************
-**
-** Function         GAP_SetDiscoverableMode
-**
-** Description      This function is called to allow or disallow a service to
-**                  discovered (Inquiry Scans).
-**
-** Returns          BT_PASS (0) if successful,
-**                  GAP_ERR_ILL_PARM if a bad parameter is detected,
-**                  GAP_DEVICE_NOT_UP if the device is not active,
-**                  GAP_ERR_PROCESSING if not enough resources to carry out request
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_SetDiscoverableMode (UINT16 mode, UINT16 duration,
-                                               UINT16 interval);
-
-/*******************************************************************************
-**
-** Function         GAP_ReadDiscoverableMode
-**
-** Description      This function is called to retrieve the current discoverable
-**                  mode for the local device.
-**
-** Returns          GAP_NON_DISCOVERABLE, GAP_LIMITED_DISCOVERABLE, or
-**                  GAP_GENERAL_DISCOVERABLE
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ReadDiscoverableMode (UINT16 *duration, UINT16 *interval);
-
-/*******************************************************************************
-**
-** Function         GAP_StartInquiry
-**
-** Description      This function initiates a single inquiry.
-**
-** Returns          BT_PASS (0) if successful,
-**                  GAP_ERR_ILL_MODE if a bad mode parameter was passed
-**                  GAP_ERR_ILL_INQ_TIME if a bad interval or duration was passed
-**                  GAP_ERR_NO_CTRL_BLK if out of control blocks
-**                  GAP_ERR_ILL_PARM if a bad parameter was detected in BTM
-**                  GAP_ERR_BUSY if the device already has an iquiry active
-**                  GAP_DEVICE_NOT_UP if the device is not initialized yet
-**                  GAP_ERR_PROCESSING if any other BTM error was returned
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_StartInquiry (tGAP_INQ_PARMS *p_inq_parms,
-                                        tGAP_CALLBACK *p_results_cb,
-                                        tGAP_CALLBACK *p_cmpl_cb);
-
-/*******************************************************************************
-**
-** Function         GAP_StartPeriodicInquiry
-**
-** Description      This function initiates a periodic inquiry.
-**
-** Returns          BT_PASS (0) if successful,
-**                  GAP_ERR_ILL_MODE if a bad mode parameter was passed
-**                  GAP_ERR_ILL_INQ_TIME if a bad interval or duration was passed
-**                  GAP_ERR_NO_CTRL_BLK if out of control blocks
-**                  GAP_ERR_ILL_PARM if a bad parameter was detected in BTM
-**                  GAP_ERR_BUSY if the device already has an iquiry active
-**                  GAP_DEVICE_NOT_UP if the device is not initialized yet
-**                  GAP_ERR_PROCESSING if any other BTM error was returned
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_StartPeriodicInquiry (tGAP_INQ_PARMS *p_inq_parms,
-                                                UINT16 min_time,
-                                                UINT16 max_time,
-                                                tGAP_CALLBACK *p_results_cb);
-
-/*******************************************************************************
-**
-** Function         GAP_CancelInquiry
-**
-** Description      This function cancels a single inquiry (if in progress)
-**
-** Returns          BOOLEAN (TRUE if successful, otherwise FALSE)
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_CancelInquiry(void);
-
-/*******************************************************************************
-**
-** Function         GAP_CancelPeriodicInquiry
-**
-** Description      This function cancels a periodic inquiry (if in progress)
-**
-** Returns          BOOLEAN: (TRUE if successful, otherwise FALSE)
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_CancelPeriodicInquiry(void);
-
-/*******************************************************************************
-**
-** Function         GAP_GetFirstInquiryResult
-**
-** Description      This function retrieves the first valid inquiry result.
-**
-** Returns          BT_PASS (0) if successful, or a non-zero error code
-**                  GAP_EOINQDB if no more entries in the database.
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_GetFirstInquiryResult(tGAP_INQ_RESULTS *p_results);
-
-/*******************************************************************************
-**
-** Function         GAP_GetNextInquiryResult
-**
-** Description      This function retrieves the next valid inquiry result.
-**
-** Returns          BT_PASS (0) if successful, or a non-zero status code
-**                  GAP_EOINQDB if no more entries in the database.
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_GetNextInquiryResult(tGAP_INQ_RESULTS *p_results);
-
-/*******************************************************************************
-**
-** Function         GAP_FindAddrByName
-**
-** Description      This function is called to retrieve a device address given
-**                  a device name.  It first looks in the current local inquiry
-**                  database for the device with the specified name.  If not found
-**                  it initiates a general inquiry.  Upon completion, it retrieves
-**                  the name for each device until a match is found or all devices
-**                  have been checked.  Note:  This process can take a while to
-**                  complete.
-**
-** Returns          BT_PASS if the name was immediately available. (BD_ADDR is returned)
-**                  GAP_CMD_INITIATED if an inquiry has been initiated
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_FindAddrByName (BD_NAME devname,
-                                          tGAP_INQ_PARMS *p_inq_parms,
-                                          tGAP_CALLBACK *p_addr_cb,
-                                          BD_ADDR bd_addr);
-
-/*******************************************************************************
-**
-** Function         GAP_SetConnectableMode
-**
-** Description      This function is called to allow or disallow a
-**                  connections on the local device.
-**
-** Returns          BT_PASS (0) if successful,
-**                  GAP_ERR_ILL_PARM if a bad parameter is detected,
-**                  GAP_DEVICE_NOT_UP if the device is not active,
-**                  GAP_ERR_PROCESSING if not enough resources to carry out request
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_SetConnectableMode (UINT16 mode, UINT16 duration,
-                                              UINT16 interval);
-
-/*******************************************************************************
-**
-** Function         GAP_ReadConnectableMode
-**
-** Description      This function is called to retrieve the current connectability
-**                  mode for the local device.
-**
-** Returns          GAP_NON_CONNECTABLE, GAP_CONNECTABLE
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ReadConnectableMode (UINT16 *duration, UINT16 *interval);
-
-/*******************************************************************************
-**
-** Function         GAP_SetSecurityMode
-**
-** Description      Set security mode for the device (Service or Link level)
-**
-** Returns          void
-**
-*******************************************************************************/
-GAP_API extern void GAP_SetSecurityMode (UINT8 sec_mode);
-
-/*******************************************************************************
-**
-** Function         GAP_SecRegister
-**
-** Description      Application calls this function to register for
-**                  security services.
-**
-** Returns          TRUE if registered OK, else FALSE
-**
-*******************************************************************************/
-GAP_API extern BOOLEAN GAP_SecRegister (tBTM_APPL_INFO *p_cb_info);
-
-/*******************************************************************************
-**
-** Function         GAP_SetPairableMode
-**
-** Description      This function is called to allow or disallow pairing
-**                  on the local device.
-**
-** Returns          BT_PASS (0) if successful, or a non-zero error code
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_SetPairableMode (UINT16 mode, BOOLEAN connect_only_paired);
-
-/*******************************************************************************
-**
-** Function         GAP_Bond
-**
-** Description      This function is called to initiate bonding with peer device
-**
-** Parameters:      bd_addr      - Address of the device to bond
-**                  pin_len      - length in bytes of the PIN Code
-**                  p_pin        - pointer to array with the PIN Code
-**                  trusted_mask - bitwise OR of trusted services (array of UINT32)
-**
-** Returns          tBTM_STATUS - BTM_CMD_STARTED of successfully initiated
-**
-*******************************************************************************/
-GAP_API extern UINT8 GAP_Bond (BD_ADDR bd_addr, UINT8 pin_len,
-                               UINT8 *p_pin, UINT32 trusted_mask[]);
-
-/*******************************************************************************
-**
-** Function         GAP_PinRsp
-**
-** Description      This function is called from UI after Security Manager submitted
-**                  PIN code request.
-**
-** Returns          void
-**
-*******************************************************************************/
-GAP_API extern void GAP_PinRsp (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len,
-                                UINT8 *p_pin, UINT32 trusted_mask[]);
-
-/*******************************************************************************
-**
-** Function         GAP_AuthorizeRsp
-**
-** Description      This function is called from UI after Security Manager submitted
-**                  an authorization request.
-**
-** Returns          void
-**
-*******************************************************************************/
-GAP_API extern void GAP_AuthorizeRsp (BD_ADDR bd_addr, UINT8 res,
-                                      UINT32 trusted_mask[]);
-
-/*******************************************************************************
-**
-** Function         GAP_SetDeviceClass
-**
-** Description      This function updates the local Device Class.
-**
-** Returns          BT_PASS (0) if successful,
-**                  GAP_ERR_BUSY if a discovery is already in progress
-**                  GAP_ERR_ILL_PARM if an illegal parameter was detected
-**                  GAP_ERR_PROCESSING if any other BTM error has been returned
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_SetDeviceClass(tGAP_COD *p_cod, UINT8 cmd);
-
-/*******************************************************************************
-**
-** Function         GAP_ReadDeviceClass
-**
-** Description      This function reads the current local Device Class setting.
-**
-** Returns          BT_PASS
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ReadDeviceClass(tGAP_COD *p_cod);
-
-/*******************************************************************************
-**
-** Function         GAP_ReadLocalDeviceInfo
-**
-** Description      This function retrieves local device information to the caller.
-**                  NOTE:  Return parameters that are set to NULL are not retrieved.
-**
-** Returns          BT_PASS (0) if successful, or a non-zero error code
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ReadLocalDeviceInfo(  UINT8 *name, BD_ADDR *addr,
-                                                tGAP_LMP_VERSION *verinfo,
-                                                tGAP_LMP_FEATURES *features);
-
-
-/*******************************************************************************
-**
-** Function         GAP_GetRemoteDeviceName
-**
-** Description      The remote name is retrieved from the specified remote device.  If
-**                  GAP_CMD_INITIATED is returned by the function, the command was
-**                  successfully sent to the controller.  The GAP_EVT_NAME_RESP event
-**                  is passed in the callback when the remote device name has been retrieved.
-**
-** Returns
-**                  GAP_CMD_INITIATED if remote search successfully initiated
-**                  GAP_ERR_BUSY if a remote name request is already in progress,
-**                  GAP_ERR_NO_CTRL_BLK if out of control blocks (too many commands pending)
-**                  GAP_BAD_BD_ADDR if the device address is bad,
-**                  GAP_DEVICE_NOT_UP if the device has not been initialized yet
-**                  GAP_ERR_PROCESSING if any other BTM error has been returned
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_GetRemoteDeviceName (BD_ADDR addr, tGAP_CALLBACK *callback);
-
-/*** Functions for L2CAP connection interface ***/
-/*******************************************************************************
-**
-** Function         GAP_ConnOpen
-**
-** Description      This function is called to open a generic L2CAP connection.
-**
-** Returns          handle of the connection if successful, else GAP_INVALID_HANDLE
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ConnOpen (char *p_serv_name, UINT8 service_id, BOOLEAN is_server,
-                                    BD_ADDR p_rem_bda, UINT16 psm, tL2CAP_CFG_INFO *p_cfg,
-                                    UINT16 security, UINT8 chan_mode_mask, tGAP_CONN_CALLBACK *p_cb);
-
-/*******************************************************************************
-**
-** Function         GAP_ConnClose
-**
-** Description      This function is called to close a connection.
-**
-** Returns          BT_PASS             - closed OK
-**                  GAP_ERR_BAD_HANDLE  - invalid handle
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ConnClose (UINT16 gap_handle);
-
-/*******************************************************************************
-**
-** Function         GAP_ConnReadData
-**
-** Description      GKI buffer unaware application will call this function
-**                  after receiving GAP_EVT_RXDATA event. A data copy is made
-**                  into the receive buffer parameter.
-**
-** Returns          BT_PASS             - data read
-**                  GAP_ERR_BAD_HANDLE  - invalid handle
-**                  GAP_NO_DATA_AVAIL   - no data available
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ConnReadData (UINT16 gap_handle, UINT8 *p_data,
-                                        UINT16 max_len, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function         GAP_GetRxQueueCnt
-**
-** Description      This function return number of bytes on the rx queue.
-**
-** Parameters:      handle     - Handle returned in the GAP_ConnOpen
-**                  p_rx_queue_count - Pointer to return queue count in.
-**
-**
-*******************************************************************************/
-GAP_API extern int GAP_GetRxQueueCnt (UINT16 handle, UINT32 *p_rx_queue_count);
-
-/*******************************************************************************
-**
-** Function         GAP_ConnBTRead
-**
-** Description      GKI buffer aware applications will call this function after
-**                  receiving an GAP_EVT_RXDATA event to process the incoming
-**                  data buffer.
-**
-** Returns          BT_PASS             - data read
-**                  GAP_ERR_BAD_HANDLE  - invalid handle
-**                  GAP_NO_DATA_AVAIL   - no data available
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ConnBTRead (UINT16 gap_handle, BT_HDR **pp_buf);
-
-/*******************************************************************************
-**
-** Function         GAP_ConnBTWrite
-**
-** Description      GKI buffer aware applications can call this function to write data
-**                  by passing a pointer to the GKI buffer of data.
-**
-** Returns          BT_PASS                 - data read
-**                  GAP_ERR_BAD_HANDLE      - invalid handle
-**                  GAP_ERR_BAD_STATE       - connection not established
-**                  GAP_INVALID_BUF_OFFSET  - buffer offset is invalid
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ConnBTWrite (UINT16 gap_handle, BT_HDR *p_buf);
-
-/*******************************************************************************
-**
-** Function         GAP_ConnWriteData
-**
-** Description      GKI buffer unaware application will call this function
-**                  to send data to the connection. A data copy is made into a GKI
-**                  buffer.
-**
-** Returns          BT_PASS                 - data read
-**                  GAP_ERR_BAD_HANDLE      - invalid handle
-**                  GAP_ERR_BAD_STATE       - connection not established
-**                  GAP_CONGESTION          - system is congested
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ConnWriteData (UINT16 gap_handle, UINT8 *p_data,
-                                         UINT16 max_len, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function         GAP_ConnReconfig
-**
-** Description      Applications can call this function to reconfigure the connection.
-**
-** Returns          BT_PASS                 - config process started
-**                  GAP_ERR_BAD_HANDLE      - invalid handle
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ConnReconfig (UINT16 gap_handle, tL2CAP_CFG_INFO *p_cfg);
-
-/*******************************************************************************
-**
-** Function         GAP_ConnSetIdleTimeout
-**
-** Description      Higher layers call this function to set the idle timeout for
-**                  a connection, or for all future connections. The "idle timeout"
-**                  is the amount of time that a connection can remain up with
-**                  no L2CAP channels on it. A timeout of zero means that the
-**                  connection will be torn down immediately when the last channel
-**                  is removed. A timeout of 0xFFFF means no timeout. Values are
-**                  in seconds.
-**
-** Returns          BT_PASS                 - config process started
-**                  GAP_ERR_BAD_HANDLE      - invalid handle
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ConnSetIdleTimeout (UINT16 gap_handle, UINT16 timeout);
-
-/*******************************************************************************
-**
-** Function         GAP_ConnGetRemoteAddr
-**
-** Description      This function is called to get the remote BD address
-**                  of a connection.
-**
-** Returns          BT_PASS             - closed OK
-**                  GAP_ERR_BAD_HANDLE  - invalid handle
-**
-*******************************************************************************/
-GAP_API extern UINT8 *GAP_ConnGetRemoteAddr (UINT16 gap_handle);
-
-/*******************************************************************************
-**
-** Function         GAP_ConnGetRemMtuSize
-**
-** Description      Returns the remote device's MTU size.
-**
-** Returns          UINT16 - maximum size buffer that can be transmitted to the peer
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ConnGetRemMtuSize (UINT16 gap_handle);
-
-/*******************************************************************************
-**
-** Function         GAP_ConnGetL2CAPCid
-**
-** Description      Returns the L2CAP channel id
-**
-** Parameters:      handle      - Handle of the connection
-**
-** Returns          UINT16      - The L2CAP channel id
-**                  0, if error
-**
-*******************************************************************************/
-GAP_API extern UINT16 GAP_ConnGetL2CAPCid (UINT16 gap_handle);
 
 /*******************************************************************************
 **
@@ -716,7 +79,7 @@
 ** Returns          The new or current trace level
 **
 *******************************************************************************/
-GAP_API extern UINT8 GAP_SetTraceLevel (UINT8 new_level);
+extern UINT8 GAP_SetTraceLevel (UINT8 new_level);
 
 /*******************************************************************************
 **
@@ -729,7 +92,7 @@
 ** Returns          Nothing
 **
 *******************************************************************************/
-GAP_API extern void GAP_Init(void);
+extern void GAP_Init(void);
 
 #if (BLE_INCLUDED == TRUE)
 /*******************************************************************************
@@ -741,7 +104,7 @@
 ** Returns          Nothing
 **
 *******************************************************************************/
-GAP_API extern void GAP_BleAttrDBUpdate(UINT16 attr_uuid, tGAP_BLE_ATTR_VALUE *p_value);
+extern void GAP_BleAttrDBUpdate(UINT16 attr_uuid, tGAP_BLE_ATTR_VALUE *p_value);
 
 
 /*******************************************************************************
@@ -754,7 +117,7 @@
 ** Returns          TRUE if read started, else FALSE if GAP is busy
 **
 *******************************************************************************/
-GAP_API extern BOOLEAN GAP_BleReadPeerPrefConnParams (BD_ADDR peer_bda);
+extern BOOLEAN GAP_BleReadPeerPrefConnParams (BD_ADDR peer_bda);
 
 /*******************************************************************************
 **
@@ -765,7 +128,7 @@
 ** Returns          TRUE if request accepted
 **
 *******************************************************************************/
-GAP_API extern BOOLEAN GAP_BleReadPeerDevName (BD_ADDR peer_bda, tGAP_BLE_DEV_NAME_CBACK *p_cback);
+extern BOOLEAN GAP_BleReadPeerDevName (BD_ADDR peer_bda, tGAP_BLE_DEV_NAME_CBACK *p_cback);
 
 
 /*******************************************************************************
@@ -777,7 +140,7 @@
 ** Returns          TRUE if request accepted
 **
 *******************************************************************************/
-GAP_API extern BOOLEAN GAP_BleCancelReadPeerDevName (BD_ADDR peer_bda);
+extern BOOLEAN GAP_BleCancelReadPeerDevName (BD_ADDR peer_bda);
 
 /*******************************************************************************
 **
@@ -789,15 +152,10 @@
 ** Returns          TRUE if read started, else FALSE if GAP is busy
 **
 *******************************************************************************/
-GAP_API extern BOOLEAN GAP_BleUpdateReconnectAddr (BD_ADDR peer_bda,
-                                                   BD_ADDR reconn_addr,
-                                                   tGAP_BLE_RECONN_ADDR_CBACK *p_cback);
+extern BOOLEAN GAP_BleUpdateReconnectAddr (BD_ADDR peer_bda,
+                                           BD_ADDR reconn_addr,
+                                           tGAP_BLE_RECONN_ADDR_CBACK *p_cback);
 
 #endif
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif  /* GAP_API_H */
-
diff --git a/stack/include/gatt_api.h b/stack/include/gatt_api.h
index 2c99c02..3c8b504 100644
--- a/stack/include/gatt_api.h
+++ b/stack/include/gatt_api.h
@@ -678,7 +678,7 @@
 ** Returns          The new or current trace level
 **
 *******************************************************************************/
-    GATT_API extern UINT8 GATT_SetTraceLevel (UINT8 new_level);
+extern UINT8 GATT_SetTraceLevel (UINT8 new_level);
 
 
 /*******************************************************************************/
@@ -699,7 +699,7 @@
 **
 *******************************************************************************/
 
-    GATT_API extern BOOLEAN GATTS_AddHandleRange(tGATTS_HNDL_RANGE *p_hndl_range);
+extern BOOLEAN GATTS_AddHandleRange(tGATTS_HNDL_RANGE *p_hndl_range);
 
 /*******************************************************************************
 **
@@ -714,7 +714,7 @@
 ** Returns          TRUE if registered OK, else FALSE
 **
 *******************************************************************************/
-    GATT_API extern BOOLEAN  GATTS_NVRegister (tGATT_APPL_INFO *p_cb_info);
+extern BOOLEAN  GATTS_NVRegister (tGATT_APPL_INFO *p_cb_info);
 
 
 /*******************************************************************************
@@ -734,8 +734,8 @@
 ** Returns          service handle if sucessful, otherwise 0.
 **
 *******************************************************************************/
-    GATT_API extern UINT16 GATTS_CreateService (tGATT_IF gatt_if, tBT_UUID *p_svc_uuid,
-                                                UINT16 svc_inst, UINT16 num_handles, BOOLEAN is_pri);
+extern UINT16 GATTS_CreateService (tGATT_IF gatt_if, tBT_UUID *p_svc_uuid,
+                                   UINT16 svc_inst, UINT16 num_handles, BOOLEAN is_pri);
 
 
 /*******************************************************************************
@@ -751,8 +751,8 @@
 **                  fail.
 **
 *******************************************************************************/
-    GATT_API extern UINT16 GATTS_AddIncludeService (UINT16 service_handle,
-                                                    UINT16 include_svc_handle);
+extern UINT16 GATTS_AddIncludeService (UINT16 service_handle,
+                                       UINT16 include_svc_handle);
 
 
 /*******************************************************************************
@@ -773,8 +773,8 @@
 **                  characteristic failed.
 **
 *******************************************************************************/
-    GATT_API extern UINT16 GATTS_AddCharacteristic (UINT16 service_handle, tBT_UUID *char_uuid,
-                                                    tGATT_PERM perm,tGATT_CHAR_PROP property);
+extern UINT16 GATTS_AddCharacteristic (UINT16 service_handle, tBT_UUID *char_uuid,
+                                       tGATT_PERM perm,tGATT_CHAR_PROP property);
 
 /*******************************************************************************
 **
@@ -795,8 +795,8 @@
 **                 characteristic descriptor failed.
 **
 *******************************************************************************/
-    GATT_API extern UINT16 GATTS_AddCharDescriptor (UINT16 service_handle, tGATT_PERM perm,
-                                                     tBT_UUID * p_descr_uuid);
+extern UINT16 GATTS_AddCharDescriptor (UINT16 service_handle, tGATT_PERM perm,
+                                       tBT_UUID * p_descr_uuid);
 
 /*******************************************************************************
 **
@@ -811,8 +811,8 @@
 ** Returns          TRUE if operation succeed, FALSE if handle block was not found.
 **
 *******************************************************************************/
-    GATT_API extern BOOLEAN GATTS_DeleteService (tGATT_IF gatt_if, tBT_UUID *p_svc_uuid,
-                                                      UINT16 svc_inst);
+extern BOOLEAN GATTS_DeleteService (tGATT_IF gatt_if, tBT_UUID *p_svc_uuid,
+                                    UINT16 svc_inst);
 
 /*******************************************************************************
 **
@@ -827,8 +827,8 @@
 ** return           GATT_SUCCESS if sucessfully started; otherwise error code.
 **
 *******************************************************************************/
-    GATT_API extern tGATT_STATUS GATTS_StartService (tGATT_IF gatt_if, UINT16 service_handle,
-                                                     tGATT_TRANSPORT sup_transport);
+extern tGATT_STATUS GATTS_StartService (tGATT_IF gatt_if, UINT16 service_handle,
+                                        tGATT_TRANSPORT sup_transport);
 
 
 /*******************************************************************************
@@ -842,7 +842,7 @@
 ** Returns          None.
 **
 *******************************************************************************/
-    GATT_API extern void GATTS_StopService (UINT16 service_handle);
+extern void GATTS_StopService (UINT16 service_handle);
 
 
 /*******************************************************************************
@@ -859,9 +859,9 @@
 ** Returns          GATT_SUCCESS if sucessfully sent or queued; otherwise error code.
 **
 *******************************************************************************/
-    GATT_API extern  tGATT_STATUS GATTS_HandleValueIndication (UINT16 conn_id,
-                                                               UINT16 attr_handle,
-                                                               UINT16 val_len, UINT8 *p_val);
+extern  tGATT_STATUS GATTS_HandleValueIndication (UINT16 conn_id,
+                                                  UINT16 attr_handle,
+                                                  UINT16 val_len, UINT8 *p_val);
 
 /*******************************************************************************
 **
@@ -877,8 +877,8 @@
 ** Returns          GATT_SUCCESS if sucessfully sent; otherwise error code.
 **
 *******************************************************************************/
-    GATT_API extern  tGATT_STATUS GATTS_HandleValueNotification (UINT16 conn_id, UINT16 attr_handle,
-                                                                 UINT16 val_len, UINT8 *p_val);
+extern  tGATT_STATUS GATTS_HandleValueNotification (UINT16 conn_id, UINT16 attr_handle,
+                                                    UINT16 val_len, UINT8 *p_val);
 
 
 /*******************************************************************************
@@ -895,8 +895,8 @@
 ** Returns          GATT_SUCCESS if sucessfully sent; otherwise error code.
 **
 *******************************************************************************/
-    GATT_API extern  tGATT_STATUS GATTS_SendRsp (UINT16 conn_id,  UINT32 trans_id,
-                                                 tGATT_STATUS status, tGATTS_RSP *p_msg);
+extern  tGATT_STATUS GATTS_SendRsp (UINT16 conn_id,  UINT32 trans_id,
+                                    tGATT_STATUS status, tGATTS_RSP *p_msg);
 
 
 /*******************************************************************************/
@@ -916,7 +916,7 @@
 ** Returns          GATT_SUCCESS if command started successfully.
 **
 *******************************************************************************/
-    GATT_API extern tGATT_STATUS GATTC_ConfigureMTU (UINT16 conn_id, UINT16  mtu);
+extern tGATT_STATUS GATTC_ConfigureMTU (UINT16 conn_id, UINT16  mtu);
 
 /*******************************************************************************
 **
@@ -931,9 +931,9 @@
 ** Returns          GATT_SUCCESS if command received/sent successfully.
 **
 *******************************************************************************/
-    GATT_API extern tGATT_STATUS GATTC_Discover (UINT16 conn_id,
-                                                 tGATT_DISC_TYPE disc_type,
-                                                 tGATT_DISC_PARAM *p_param );
+extern tGATT_STATUS GATTC_Discover (UINT16 conn_id,
+                                    tGATT_DISC_TYPE disc_type,
+                                    tGATT_DISC_PARAM *p_param );
 /*******************************************************************************
 **
 ** Function         GATTC_Read
@@ -948,8 +948,8 @@
 ** Returns          GATT_SUCCESS if command started successfully.
 **
 *******************************************************************************/
-    GATT_API extern tGATT_STATUS GATTC_Read (UINT16 conn_id, tGATT_READ_TYPE type,
-                                             tGATT_READ_PARAM *p_read);
+extern tGATT_STATUS GATTC_Read (UINT16 conn_id, tGATT_READ_TYPE type,
+                                tGATT_READ_PARAM *p_read);
 
 /*******************************************************************************
 **
@@ -965,8 +965,8 @@
 ** Returns          GATT_SUCCESS if command started successfully.
 **
 *******************************************************************************/
-    GATT_API extern tGATT_STATUS GATTC_Write (UINT16 conn_id, tGATT_WRITE_TYPE type,
-                                              tGATT_VALUE *p_write);
+extern tGATT_STATUS GATTC_Write (UINT16 conn_id, tGATT_WRITE_TYPE type,
+                                 tGATT_VALUE *p_write);
 
 
 /*******************************************************************************
@@ -982,7 +982,7 @@
 ** Returns          GATT_SUCCESS if command started successfully.
 **
 *******************************************************************************/
-    GATT_API extern tGATT_STATUS GATTC_ExecuteWrite (UINT16 conn_id, BOOLEAN is_execute);
+extern tGATT_STATUS GATTC_ExecuteWrite (UINT16 conn_id, BOOLEAN is_execute);
 
 /*******************************************************************************
 **
@@ -997,7 +997,7 @@
 ** Returns          GATT_SUCCESS if command started successfully.
 **
 *******************************************************************************/
-    GATT_API extern tGATT_STATUS GATTC_SendHandleValueConfirm (UINT16 conn_id, UINT16 handle);
+extern tGATT_STATUS GATTC_SendHandleValueConfirm (UINT16 conn_id, UINT16 handle);
 
 
 /*******************************************************************************
@@ -1014,8 +1014,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    GATT_API extern void GATT_SetIdleTimeout (BD_ADDR bd_addr, UINT16 idle_tout,
-                                            tGATT_TRANSPORT transport);
+extern void GATT_SetIdleTimeout (BD_ADDR bd_addr, UINT16 idle_tout,
+                                 tGATT_TRANSPORT transport);
 
 
 /*******************************************************************************
@@ -1031,7 +1031,7 @@
 ** Returns          0 for error, otherwise the index of the client registered with GATT
 **
 *******************************************************************************/
-    GATT_API extern  tGATT_IF GATT_Register (tBT_UUID *p_app_uuid128, tGATT_CBACK *p_cb_info);
+extern  tGATT_IF GATT_Register (tBT_UUID *p_app_uuid128, tGATT_CBACK *p_cb_info);
 
 /*******************************************************************************
 **
@@ -1044,7 +1044,7 @@
 ** Returns          None.
 **
 *******************************************************************************/
-    GATT_API extern void GATT_Deregister (tGATT_IF gatt_if);
+extern void GATT_Deregister (tGATT_IF gatt_if);
 
 /*******************************************************************************
 **
@@ -1059,7 +1059,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-    GATT_API extern  void GATT_StartIf (tGATT_IF gatt_if);
+extern  void GATT_StartIf (tGATT_IF gatt_if);
 
 /*******************************************************************************
 **
@@ -1076,8 +1076,8 @@
 ** Returns          TRUE if connection started; FALSE if connection start failure.
 **
 *******************************************************************************/
-    GATT_API extern BOOLEAN GATT_Connect (tGATT_IF gatt_if, BD_ADDR bd_addr,
-                                          BOOLEAN is_direct, tBT_TRANSPORT transport);
+extern BOOLEAN GATT_Connect (tGATT_IF gatt_if, BD_ADDR bd_addr,
+                             BOOLEAN is_direct, tBT_TRANSPORT transport);
 
 
 /*******************************************************************************
@@ -1095,8 +1095,8 @@
 ** Returns          TRUE if connection started; FALSE if connection start failure.
 **
 *******************************************************************************/
-    GATT_API extern BOOLEAN GATT_CancelConnect (tGATT_IF gatt_if, BD_ADDR bd_addr,
-                                                BOOLEAN is_direct);
+extern BOOLEAN GATT_CancelConnect (tGATT_IF gatt_if, BD_ADDR bd_addr,
+                                   BOOLEAN is_direct);
 
 /*******************************************************************************
 **
@@ -1110,7 +1110,7 @@
 ** Returns          GATT_SUCCESS if disconnected.
 **
 *******************************************************************************/
-    GATT_API extern tGATT_STATUS GATT_Disconnect (UINT16 conn_id);
+extern tGATT_STATUS GATT_Disconnect (UINT16 conn_id);
 
 
 
@@ -1129,8 +1129,8 @@
 ** Returns          TRUE the ligical link information is found for conn_id
 **
 *******************************************************************************/
-    GATT_API extern BOOLEAN GATT_GetConnectionInfor(UINT16 conn_id, tGATT_IF *p_gatt_if,
-                                        BD_ADDR bd_addr, tBT_TRANSPORT *p_transport);
+extern BOOLEAN GATT_GetConnectionInfor(UINT16 conn_id, tGATT_IF *p_gatt_if,
+                                       BD_ADDR bd_addr, tBT_TRANSPORT *p_transport);
 
 
 /*******************************************************************************
@@ -1148,8 +1148,8 @@
 ** Returns          TRUE the ligical link is connected
 **
 *******************************************************************************/
-    GATT_API extern BOOLEAN GATT_GetConnIdIfConnected(tGATT_IF gatt_if, BD_ADDR bd_addr,
-                                                      UINT16 *p_conn_id, tBT_TRANSPORT transport);
+extern BOOLEAN GATT_GetConnIdIfConnected(tGATT_IF gatt_if, BD_ADDR bd_addr,
+                                         UINT16 *p_conn_id, tBT_TRANSPORT transport);
 
 
 /*******************************************************************************
@@ -1167,7 +1167,7 @@
 ** Returns          TRUE if advertisement is started; FALSE if adv start failure.
 **
 *******************************************************************************/
-    GATT_API extern BOOLEAN GATT_Listen (tGATT_IF gatt_if, BOOLEAN start, BD_ADDR_PTR bd_addr);
+extern BOOLEAN GATT_Listen (tGATT_IF gatt_if, BOOLEAN start, BD_ADDR_PTR bd_addr);
 
 /*******************************************************************************
 **
@@ -1178,7 +1178,7 @@
 ** Returns          None.
 **
 *******************************************************************************/
-    GATT_API extern void GATT_ConfigServiceChangeCCC (BD_ADDR remote_bda, BOOLEAN enable,
+extern void GATT_ConfigServiceChangeCCC (BD_ADDR remote_bda, BOOLEAN enable,
                                                     tBT_TRANSPORT transport);
  
 #ifdef __cplusplus
diff --git a/stack/include/goep_fs.h b/stack/include/goep_fs.h
deleted file mode 100644
index c5d054e..0000000
--- a/stack/include/goep_fs.h
+++ /dev/null
@@ -1,393 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2000-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef GOEP_FS_H
-#define GOEP_FS_H
-
-#include "bt_target.h"
-
-/*****************************************************************************
-**     Constants
-*****************************************************************************/
-
-/* Flags passed to the open function (tGOEP_OPEN_CBACK)
-**      Values are OR'd together. (First 3 are
-**      mutually exclusive.
-*/
-#define GOEP_O_RDONLY            0x0000
-#define GOEP_O_WRONLY            0x0001
-#define GOEP_O_RDWR              0x0002
-
-#define GOEP_O_CREAT             0x0100
-#define GOEP_O_EXCL              0x0200
-#define GOEP_O_TRUNC             0x1000
-
-
-#define GOEP_LEN_UNKNOWN          0xFFFFFFFF
-#define GOEP_INVALID_FD          (-1)
-
-/* Values passed to the access function (tGOEP_ACCESS_CBACK)
-*/
-#define GOEP_ACC_EXIST           0x0
-#define GOEP_ACC_READ            0x4
-#define GOEP_ACC_RDWR            0x6
-
-/* Constants used in directory listing structure */
-#define GOEP_A_RDONLY            0x1
-#define GOEP_A_DIR               0x2      /* Entry is a sub directory */
-
-#define GOEP_CTIME_LEN           17       /* Creation time "yyyymmddTHHMMSSZ" */
-
-/*****************************************************************************
-**     Seek Constants
-*****************************************************************************/
-/* Origin for the seek function (tGOEP_SEEK_CBACK) */
-#define GOEP_SEEK_SET    0
-#define GOEP_SEEK_CUR    1
-#define GOEP_SEEK_END    2
-
-
-
-/*****************************************************************************
-**    Typedefs
-*****************************************************************************/
-typedef INT32   tGOEP_FD;
-
-enum
-{
-    GOEP_OK,
-    GOEP_FAIL,
-    GOEP_EACCES,
-    GOEP_ENOTEMPTY,
-    GOEP_EOF,
-    GOEP_EODIR,
-    GOEP_ENOSPACE,
-    GOEP_EIS_DIR,
-    GOEP_RESUME,
-    GOEP_NONE
-};
-typedef UINT16 tGOEP_STATUS;
-
-/* Structure passed in Directory Entry Callback to be filled in */
-typedef struct
-{
-    UINT32  refdata;                /* holder for OS specific data used to get next entry */
-    UINT32  filesize;
-    char    crtime[GOEP_CTIME_LEN]; /* "yyyymmddTHHMMSSZ", or "" if none */
-    char   *p_name;                 /* Contains the addr of memory to copy name into */
-    UINT8   mode;                   /* GOEP_A_RDONLY and/or GOEP_A_DIR */
-} tGOEP_DIRENTRY;
-
-
-/*****************************************************************************
-**    Typedefs for messages from response functions
-*****************************************************************************/
-typedef struct
-{
-    BT_HDR          hdr;
-    tGOEP_FD        fd;
-    tGOEP_STATUS    status;
-    UINT32          file_size;
-} tGOEP_OPEN_RSP;
-
-typedef struct
-{
-    BT_HDR          hdr;
-    tGOEP_FD        fd;
-    tGOEP_STATUS    status;
-    UINT16          bytes_read;
-} tGOEP_READ_RSP;
-
-typedef struct
-{
-    BT_HDR          hdr;
-    tGOEP_FD        fd;
-    tGOEP_STATUS    status;
-} tGOEP_WRITE_RSP;
-
-typedef struct
-{
-    BT_HDR       hdr;
-    tGOEP_STATUS status;
-} tGOEP_DIRENTRY_RSP;
-
-/*****************************************************************************
-**    Object Store Interface
-*****************************************************************************/
-/*******************************************************************************
-**
-** Callback Function: tGOEP_OPEN_CBACK
-**
-** Description  This function is executed by OBX profiles to open
-**              a file for reading or writing.
-**
-** Parameters   p_path      - Fully qualified path and file name.
-**              flags       - permissions and mode (see constants above)
-**              size        - size of file to put (0 if unavailable or not applicable)
-**              event_id    - code that must be passed to the call-in function.
-**
-** Returns      void
-**
-** Note:        Upon completion of the request, a file descriptor (tGOEP_FD),
-**              file size (UINT32), and an status code (tGOEP_STATUS)
-**              are returned in GOEP_OpenRsp().
-**
-*******************************************************************************/
-typedef void (tGOEP_OPEN_CBACK) (const UINT8 *p_name, UINT16 flags, UINT32 size,
-                                 UINT16 event_id, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Callback Function: tGOEP_CLOSE_CBACK
-**
-** Description  This function is executed by OBX profiles when the file descriptor
-**              is no longer in use.
-**
-** Returns      void
-**
-*******************************************************************************/
-typedef void (tGOEP_CLOSE_CBACK) (tGOEP_FD fd, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Callback Function: tGOEP_READ_CBACK
-**
-** Description  This function is executed by OBX profiles to read in data from the
-**              previously opened file.
-**
-** Returns      void
-**
-** Note:        Upon completion of the request, GOEP_ReadRsp() is
-**              called with the buffer of data, along with the number
-**              of bytes read into the buffer, and a status.  The
-**              call-in function should only be called when ALL requested
-**              bytes have been read, the end of file has been detected,
-**              or an error has occurred.
-**
-*******************************************************************************/
-typedef void (tGOEP_READ_CBACK) (tGOEP_FD fd, void *p_data, INT16 size,
-                                 UINT16 event_id, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Callback Function: tGOEP_WRITE_CBACK
-**
-** Description  This function is executed by OBX profiles to write the data to the
-**              previously opened file.
-**
-** Returns      void
-**
-** Note:        Upon completion of the request, GOEP_WriteRsp() is
-**              called with the file descriptor and the status.  The
-**              call-in function should only be called when ALL requested
-**              bytes have been written, or an error has been detected,
-**
-*******************************************************************************/
-typedef void (tGOEP_WRITE_CBACK) (tGOEP_FD fd, const void *p_data, INT16 size,
-                                  UINT16 event_id, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Callback Function: tGOEP_SEEK_CBACK
-**
-** Description  This function is executed by OBX profiles to Move a file pointer
-**              of a previously opened file to the specified location for the
-**              next read or write operation.
-**
-** Returns      void
-**
-*******************************************************************************/
-typedef void (tGOEP_SEEK_CBACK) (tGOEP_FD fd, INT32 offset, INT16 origin, UINT8 app_id);
-
-
-/*******************************************************************************
-**
-** Callback Function: tGOEP_DIRENTRY_CBACK
-**
-** Description  This function is called to retrieve a directory entry for the
-**              specified path.  The first/next directory should be filled
-**              into the location specified by p_entry.
-**
-** Parameters   p_path     - directory to search (Fully qualified path)
-**              first_item - TRUE if first search, FALSE if next search
-**                                      (p_cur contains previous)
-**              p_entry (input/output) - Points to last entry data (valid when
-**                                           first_item is FALSE)
-**              event_id - event that must be passed into the call-in function.
-**
-** Returns      void
-**
-** Note:        Upon completion of the request, GOEP_DirentryRsp() is
-**              filled in entry and the status.
-**              GOEP_OK is returned when p_entry is valid,
-**              GOEP_EODIR is returned when no more entries [finished]
-**              GOEP_FAIL is returned if an error occurred
-**
-*******************************************************************************/
-typedef void (tGOEP_DIRENTRY_CBACK) (const char *p_path, BOOLEAN first_item,
-                                     tGOEP_DIRENTRY *p_entry, UINT16 event_id,
-                                     UINT8 app_id);
-
-/*******************************************************************************
-**
-** Callback Function: tGOEP_ACCESS_CBACK
-**
-** Description  This function is called to check the existence of a file or
-**              directory.
-**
-** Returns      (tGOEP_STATUS) status of the call.
-**               [GOEP_OK if it exists]
-**               [GOEP_EACCES if permissions are wrong]
-**               [GOEP_FAIL if it does not exist]
-**
-*******************************************************************************/
-typedef tGOEP_STATUS (tGOEP_ACCESS_CBACK) (const char *p_path, UINT16 mode,
-                                           BOOLEAN *p_is_dir, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Callback Function: tGOEP_MKDIR_CBACK
-**
-** Description  This function is called to create a directory with
-**              the pathname given by path. The pathname is a null terminated
-**              string. All components of the path must already exist.
-**
-** Parameters   p_path   - (input) name of directory to create (fully qualified path).
-**
-** Returns      (tGOEP_STATUS) status of the call.
-**               [GOEP_OK if successful]
-**               [GOEP_FAIL if unsuccessful]
-**
-*******************************************************************************/
-typedef tGOEP_STATUS (tGOEP_MKDIR_CBACK) (const char *p_path, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Callback Function: tGOEP_RMDIR_CBACK
-**
-** Description  This function is called to remove a directory whose
-**                  name is given by path. The directory must be empty.
-**
-** Parameters   p_path   - (input) name of directory to remove (fully qualified path).
-**
-** Returns      (tGOEP_STATUS) status of the call.
-**               [GOEP_OK if successful]
-**               [GOEP_EACCES if read-only]
-**               [GOEP_ENOTEMPTY if directory is not empty]
-**               [GOEP_FAIL otherwise]
-**
-*******************************************************************************/
-typedef tGOEP_STATUS (tGOEP_RMDIR_CBACK) (const char *p_path, UINT8 app_id);
-
-/*******************************************************************************
-**
-** Callback Function: tGOEP_UNLINK_CBACK
-**
-** Description  This function is called to remove a directory whose
-**                  name is given by path. The directory must be empty.
-**
-** Parameters   p_path   - (input) name of file to remove (fully qualified path).
-**
-** Returns      (tGOEP_STATUS) status of the call.
-**               [GOEP_OK if successful]
-**               [GOEP_EACCES if read-only]
-**               [GOEP_FAIL otherwise]
-**
-*******************************************************************************/
-typedef tGOEP_STATUS (tGOEP_UNLINK_CBACK) (const char *p_path, UINT8 app_id);
-
-
-/*****************************************************************************
-**     Prototypes
-*****************************************************************************/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*****************************************************************************
-**
-**  Function:    GOEP_OpenRsp
-**
-**  Purpose:     Report the status of tGOEP_OPEN_CBACK callback function.
-**
-**  Parameters:  fd         - File handle.
-**               status     - Status of the operation.
-**               file_size  - total number of bytes in this file.
-**               event_id   - event id as given in the tGOEP_OPEN_CBACK function.
-**
-**  Returns:     void
-**
-*****************************************************************************/
-GOEP_API extern void GOEP_OpenRsp (tGOEP_FD fd, tGOEP_STATUS status,
-                                   UINT32 file_size, UINT16 event_id);
-
-/*****************************************************************************
-**
-**  Function:    GOEP_ReadRsp
-**
-**  Purpose:     Report the status of tGOEP_READ_CBACK callback function.
-**
-**  Parameters:  fd         - File handle.
-**               status     - Status of the operation.
-**               bytes_read - total number of bytes read from the file.
-**               event_id   - event id as given in the tGOEP_READ_CBACK function.
-**
-**  Returns:     void
-**
-*****************************************************************************/
-GOEP_API extern void GOEP_ReadRsp (tGOEP_FD fd, tGOEP_STATUS status,
-                                   UINT16 bytes_read, UINT16 event_id);
-
-/*****************************************************************************
-**
-**  Function:    GOEP_WriteRsp
-**
-**  Purpose:     Report the status of tGOEP_WRITE_CBACK callback function.
-**
-**  Parameters:  fd         - File handle.
-**               status     - Status of the operation.
-**               event_id   - event id as given in the tGOEP_WRITE_CBACK function.
-**
-**  Returns:     void
-**
-*****************************************************************************/
-GOEP_API extern void GOEP_WriteRsp (tGOEP_FD fd, tGOEP_STATUS status, UINT16 event_id);
-
-/*******************************************************************************
-**
-** Function     GOEP_DirentryRsp
-**
-** Description  This function is called in response to the
-**              tGOEP_DIRENTRY_CBACK function with a filled in directory listing
-**              entry.
-**
-** Parameters   status - GOEP_OK if p_entry points to a valid entry.
-**                       GOEP_EODIR if no more entries (p_entry is ignored).
-**                       GOEP_FAIL if any errors have occurred.
-**              event_id - event id as given in the tGOEP_DIRENTRY_CBACK function.
-**
-** Returns      void
-**
-*******************************************************************************/
-GOEP_API extern void GOEP_DirentryRsp(tGOEP_STATUS status, UINT16 event_id);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* GOEP_FS_H */
diff --git a/stack/include/hcidefs.h b/stack/include/hcidefs.h
index 0349d6a..63a0bc5 100644
--- a/stack/include/hcidefs.h
+++ b/stack/include/hcidefs.h
@@ -218,8 +218,8 @@
 #define HCI_READ_BE_FLUSH_TOUT                (0x0069 | HCI_GRP_HOST_CONT_BASEBAND_CMDS)
 #define HCI_WRITE_BE_FLUSH_TOUT               (0x006A | HCI_GRP_HOST_CONT_BASEBAND_CMDS)
 #define HCI_SHORT_RANGE_MODE                  (0x006B | HCI_GRP_HOST_CONT_BASEBAND_CMDS) /* 802.11 only */
-#define HCI_READ_LE_HOST_SUPPORTED              (0x006C | HCI_GRP_HOST_CONT_BASEBAND_CMDS)
-#define HCI_WRITE_LE_HOST_SUPPORTED             (0x006D | HCI_GRP_HOST_CONT_BASEBAND_CMDS)
+#define HCI_READ_LE_HOST_SUPPORT              (0x006C | HCI_GRP_HOST_CONT_BASEBAND_CMDS)
+#define HCI_WRITE_LE_HOST_SUPPORT             (0x006D | HCI_GRP_HOST_CONT_BASEBAND_CMDS)
 
 
 /* MWS coexistence */
@@ -588,14 +588,6 @@
 #define HCI_SUPP_LE_STATES_INIT_MASTER_SLAVE_OFF           5
 #define HCI_LE_STATES_INIT_MASTER_SLAVE_SUPPORTED(x)      ((x)[HCI_SUPP_LE_STATES_INIT_MASTER_SLAVE_OFF] & HCI_SUPP_LE_STATES_INIT_MASTER_SLAVE_MASK)
 
-#define HCI_BRCM_ENABLE_WBS_MODIFIED        (0x0102 | HCI_GRP_VENDOR_SPECIFIC)
-
-/* ConnectionLess Broadcast Stream VSC */
-#define HCI_BRCM_SET_CLB_STREAM             (0x0111 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_BRCM_RECEIVE_CLB_STREAM         (0x0112 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_BRCM_WRITE_CLB_STREAM_DATA      (0x0113 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_BRCM_CLB_STREAM_FLUSH           (0x0114 | HCI_GRP_VENDOR_SPECIFIC)
-
 /*
 **  Definitions for HCI Events
 */
@@ -1351,164 +1343,9 @@
 #define LMP_TESTCTL_POWCTL_FIXEDTX_OP   0
 #define LMP_TESTCTL_POWCTL_ADAPTIVE     1
 
-
-/*
-** Define company IDs (from Bluetooth Assigned Numbers v1.1, section 2.2)
-*/
-#define LMP_COMPID_ERICSSON             0
-#define LMP_COMPID_NOKIA                1
-#define LMP_COMPID_INTEL                2
-#define LMP_COMPID_IBM                  3
-#define LMP_COMPID_TOSHIBA              4
-#define LMP_COMPID_3COM                 5
-#define LMP_COMPID_MICROSOFT            6
-#define LMP_COMPID_LUCENT               7
-#define LMP_COMPID_MOTOROLA             8
-#define LMP_COMPID_INFINEON             9
-#define LMP_COMPID_CSR                  10
-#define LMP_COMPID_SILICON_WAVE         11
-#define LMP_COMPID_DIGIANSWER           12
-#define LMP_COMPID_TEXAS_INSTRUMENTS    13
-#define LMP_COMPID_PARTHUS              14
+// TODO(zachoverflow): remove this once broadcom specific hacks are removed
 #define LMP_COMPID_BROADCOM             15
-#define LMP_COMPID_MITEL_SEMI           16
-#define LMP_COMPID_WIDCOMM              17
-#define LMP_COMPID_ZEEVO                18
-#define LMP_COMPID_ATMEL                19
-#define LMP_COMPID_MITSUBISHI           20
-#define LMP_COMPID_RTX_TELECOM          21
-#define LMP_COMPID_KC_TECH              22
-#define LMP_COMPID_NEWLOGIC             23
-#define LMP_COMPID_TRANSILICA           24
-#define LMP_COMPID_ROHDE_SCHWARZ        25
-#define LMP_COMPID_TTPCOM               26
-#define LMP_COMPID_SIGNIA               27
-#define LMP_COMPID_CONEXANT             28
-#define LMP_COMPID_QUALCOMM             29
-#define LMP_COMPID_INVENTEL             30
-#define LMP_COMPID_AVM                  31
-#define LMP_COMPID_BANDSPEED            32
-#define LMP_COMPID_MANSELLA             33
-#define LMP_COMPID_NEC_CORP             34
-#define LMP_COMPID_WAVEPLUS             35
-#define LMP_COMPID_ALCATEL              36
-#define LMP_COMPID_PHILIPS              37
-#define LMP_COMPID_C_TECHNOLOGIES       38
-#define LMP_COMPID_OPEN_INTERFACE       39
-#define LMP_COMPID_RF_MICRO             40
-#define LMP_COMPID_HITACHI              41
-#define LMP_COMPID_SYMBOL_TECH          42
-#define LMP_COMPID_TENOVIS              43
-#define LMP_COMPID_MACRONIX             44
-#define LMP_COMPID_GCT_SEMI             45
-#define LMP_COMPID_NORWOOD_SYSTEMS      46
-#define LMP_COMPID_MEWTEL_TECH          47
-#define LMP_COMPID_STM                  48
-#define LMP_COMPID_SYNOPSYS             49
-#define LMP_COMPID_RED_M_LTD            50
-#define LMP_COMPID_COMMIL_LTD           51
-#define LMP_COMPID_CATC                 52
-#define LMP_COMPID_ECLIPSE              53
-#define LMP_COMPID_RENESAS_TECH         54
-#define LMP_COMPID_MOBILIAN_CORP        55
-#define LMP_COMPID_TERAX                56
-#define LMP_COMPID_ISSC                 57
-#define LMP_COMPID_MATSUSHITA           58
-#define LMP_COMPID_GENNUM_CORP          59
-#define LMP_COMPID_RESEARCH_IN_MOTION   60
-#define LMP_COMPID_IPEXTREME            61
-#define LMP_COMPID_SYSTEMS_AND_CHIPS    62
-#define LMP_COMPID_BLUETOOTH_SIG        63
-#define LMP_COMPID_SEIKO_EPSON_CORP     64
-#define LMP_COMPID_ISS_TAIWAN           65
-#define LMP_COMPID_CONWISE_TECHNOLOGIES 66
-#define LMP_COMPID_PARROT_SA            67
-#define LMP_COMPID_SOCKET_COMM          68
-#define LMP_COMPID_ALTHEROS             69
-#define LMP_COMPID_MEDIATEK             70
-#define LMP_COMPID_BLUEGIGA             71
-#define LMP_COMPID_MARVELL              72
-#define LMP_COMPID_3DSP_CORP            73
-#define LMP_COMPID_ACCEL_SEMICONDUCTOR  74
-#define LMP_COMPID_CONTINENTAL_AUTO     75
-#define LMP_COMPID_APPLE                76
-#define LMP_COMPID_STACCATO             77
-#define LMP_COMPID_AVAGO_TECHNOLOGIES   78
-#define LMP_COMPID_APT_LTD              79
-#define LMP_COMPID_SIRF_TECHNOLOGY      80
-#define LMP_COMPID_TZERO_TECHNOLOGY     81
-#define LMP_COMPID_J_AND_M_CORP         82
-#define LMP_COMPID_FREE_2_MOVE          83
-#define LMP_COMPID_3DIJOY_CORP          84
-#define LMP_COMPID_PLANTRONICS          85
-#define LMP_COMPID_SONY_ERICSSON_MOBILE 86
-#define LMP_COMPID_HARMON_INTL_IND      87
-#define LMP_COMPID_VIZIO                88
-#define LMP_COMPID_NORDIC SEMI          89
-#define LMP_COMPID_EM MICRO             90
-#define LMP_COMPID_RALINK TECH          91
-#define LMP_COMPID_BELKIN INC           92
-#define LMP_COMPID_REALTEK SEMI         93
-#define LMP_COMPID_STONESTREET ONE      94
-#define LMP_COMPID_WICENTRIC            95
-#define LMP_COMPID_RIVIERAWAVES         96
-#define LMP_COMPID_RDA MICRO            97
-#define LMP_COMPID_GIBSON GUITARS       98
-#define LMP_COMPID_MICOMMAND INC        99
-#define LMP_COMPID_BAND XI              100
-#define LMP_COMPID_HP COMPANY           101
-#define LMP_COMPID_9SOLUTIONS OY        102
-#define LMP_COMPID_GN NETCOM            103
-#define LMP_COMPID_GENERAL MOTORS       104
-#define LMP_COMPID_AD ENGINEERING       105
-#define LMP_COMPID_MINDTREE LTD         106
-#define LMP_COMPID_POLAR ELECTRO        107
-#define LMP_COMPID_BEAUTIFUL ENTERPRISE 108
-#define LMP_COMPID_BRIARTEK             109
-#define LMP_COMPID_SUMMIT DATA COMM     110
-#define LMP_COMPID_SOUND ID             111
-#define LMP_COMPID_MONSTER LLC          112
-#define LMP_COMPID_CONNECTBLU           113
 
-#define LMP_COMPID_SHANGHAI_SSE         114
-#define LMP_COMPID_GROUP_SENSE          115
-#define LMP_COMPID_ZOMM                 116
-#define LMP_COMPID_SAMSUNG              117
-#define LMP_COMPID_CREATIVE_TECH        118
-#define LMP_COMPID_LAIRD_TECH           119
-#define LMP_COMPID_NIKE                 120
-#define LMP_COMPID_LESSWIRE             121
-#define LMP_COMPID_MSTAR_SEMI           122
-#define LMP_COMPID_HANLYNN_TECH         123
-#define LMP_COMPID_AR_CAMBRIDGE         124
-#define LMP_COMPID_SEERS_TECH           125
-#define LMP_COMPID_SPORTS_TRACKING      126
-#define LMP_COMPID_AUTONET_MOBILE       127
-#define LMP_COMPID_DELORME_PUBLISH      128
-#define LMP_COMPID_WUXI_VIMICRO         129
-#define LMP_COMPID_SENNHEISER           130
-#define LMP_COMPID_TIME_KEEPING_SYS     131
-#define LMP_COMPID_LUDUS_HELSINKI       132
-#define LMP_COMPID_BLUE_RADIOS          133
-#define LMP_COMPID_EQUINUX              134
-#define LMP_COMPID_GARMIN_INTL          135
-#define LMP_COMPID_ECOTEST              136
-#define LMP_COMPID_GN_RESOUND           137
-#define LMP_COMPID_JAWBONE              138
-#define LMP_COMPID_TOPCON_POSITIONING   139
-#define LMP_COMPID_QUALCOMM_LABS        140
-#define LMP_COMPID_ZSCAN_SOFTWARE       141
-#define LMP_COMPID_QUINTIC              142
-#define LMP_COMPID_STOLLMAN_EV          143
-#define LMP_COMPID_FUNAI_ELECTRONIC     144
-#define LMP_COMPID_ADV_PANMOBILE        145
-#define LMP_COMPID_THINK_OPTICS         146
-#define LMP_COMPID_UNIVERSAL_ELEC       147
-#define LMP_COMPID_AIROHA_TECH          148
-#define LMP_COMPID_MAX_ID               149 /* this is a place holder */
-#define LMP_COMPID_INTERNAL             65535
-
-#define MAX_LMP_COMPID                  (LMP_COMPID_MAX_ID)
 /*
 ** Define the packet types in the packet header, and a couple extra
 */
@@ -1798,14 +1635,8 @@
 #define HCI_FEATURE_NON_FLUSHABLE_PB_MASK      0x40
 #define HCI_FEATURE_NON_FLUSHABLE_PB_OFF       6
 
-// btla-specific ++
-#ifdef ANDROID_APP_INCLUDED
 /* This feature is causing frequent link drops when doing call switch with certain av/hfp headsets */
 #define HCI_NON_FLUSHABLE_PB_SUPPORTED(x)      (0)//((x)[HCI_FEATURE_NON_FLUSHABLE_PB_OFF] & HCI_FEATURE_NON_FLUSHABLE_PB_MASK)
-#else
-#define HCI_NON_FLUSHABLE_PB_SUPPORTED(x)      ((x)[HCI_FEATURE_NON_FLUSHABLE_PB_OFF] & HCI_FEATURE_NON_FLUSHABLE_PB_MASK)
-#endif
-// btla-specific --
 
 #define HCI_FEATURE_LINK_SUP_TO_EVT_MASK 0x01
 #define HCI_FEATURE_LINK_SUP_TO_EVT_OFF  7
@@ -2714,98 +2545,5 @@
 #define HCI_SUPP_COMMANDS_LE_RC_CONN_PARAM_UPD_NEG_RPY_OFF           33
 #define HCI_LE_RC_CONN_PARAM_UPD_NEG_RPY_SUPPORTED(x)      ((x)[HCI_SUPP_COMMANDS_LE_RC_CONN_PARAM_UPD_NEG_RPY_OFF] & HCI_SUPP_COMMANDS_RLE_RC_CONN_PARAM_UPD_NEG_RPY_MASK)
 
-/*
-Commands of HCI_GRP_VENDOR_SPECIFIC group for WIDCOMM SW LM Simulator
-*/
-#ifdef _WIDCOMM
-
-#define HCI_SET_HCI_TRACE               (0x0001 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_SET_LM_TRACE                (0x0002 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_WRITE_COUNTRY_CODE          (0x0004 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_READ_LM_HISTORY             (0x0005 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_WRITE_BD_ADDR               (0x0006 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_DISABLE_ENCRYPTION          (0x0007 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_DISABLE_AUTHENTICATION      (0x0008 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_GENERIC_LC_CMD              (0x000A | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_INCR_POWER                  (0x000B | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_DECR_POWER                  (0x000C | HCI_GRP_VENDOR_SPECIFIC)
-
-/* Definitions for the local transactions */
-#define LM_DISCONNECT                  (0x00D0 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_AUTHENTICATION_REQUESTED    (0x00D1 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_SET_CONN_ENCRYPTION         (0x00D2 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_START_ENCRYPT_KEY_SIZE      (0x00D3 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_START_ENCRYPTION            (0x00D4 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_STOP_ENCRYPTION             (0x00D5 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_CHANGE_CONN_PACKET_TYPE     (0x00D6 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_RMT_NAME_REQUEST            (0x00D7 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_READ_RMT_FEATURES           (0x00D8 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_READ_RMT_VERSION_INFO       (0x00D9 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_READ_RMT_TIMING_INFO        (0x00DA | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_READ_RMT_CLOCK_OFFSET       (0x00DB | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HOLD_MODE                   (0x00DC | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_EXIT_PARK_MODE              (0x00DD | HCI_GRP_VENDOR_SPECIFIC)
-
-#define LM_SCO_LINK_REQUEST            (0x00E0 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_SCO_CHANGE                  (0x00E4 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_SCO_REMOVE                  (0x00E8 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_MAX_SLOTS                   (0x00F1 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_MAX_SLOTS_REQUEST           (0x00F2 | HCI_GRP_VENDOR_SPECIFIC)
-
-#ifdef INCLUDE_OPTIONAL_PAGING_SCHEME
-#define LM_OPTIONAL_PAGE_REQUEST       (0x00F3 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_OPTIONAL_PAGESCAN_REQUEST   (0x00F4 | HCI_GRP_VENDOR_SPECIFIC)
-#endif
-
-#define LM_SETUP_COMPLETE              (0x00FF | HCI_GRP_VENDOR_SPECIFIC)
-
-#define LM_HIST_SEND_LMP_FRAME         (0x0100 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_RECV_LMP_FRAME         (0x0101 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_HCIT_ERROR             (0x0102 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_PER_INQ_TOUT           (0x0103 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_INQ_SCAN_TOUT          (0x0104 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_PAGE_SCAN_TOUT         (0x0105 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_RESET_TOUT             (0x0106 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_MANDAT_PSCAN_TOUT      (0x0107 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_ACL_START_TRANS        (0x0108 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_ACL_HOST_REPLY         (0x0109 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_ACL_TIMEOUT            (0x010A | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_ACL_TX_COMP            (0x010B | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_ACL_HCID_SUSPENDED     (0x010C | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_ACL_FAILED             (0x010D | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_HCI_COMMAND            (0x010E | HCI_GRP_VENDOR_SPECIFIC)
-
-#define LM_HIST_HCI_EVENT              (0x010F | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_HCI_UPDATA             (0x0110 | HCI_GRP_VENDOR_SPECIFIC)
-#define LM_HIST_HCI_DNDATA             (0x0111 | HCI_GRP_VENDOR_SPECIFIC)
-
-#define HCI_ENTER_TEST_MODE            (0x0300 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_LMP_TEST_CNTRL             (0x0301 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_DEBUG_LC_CMD_MIN           (0x0300 | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_DEBUG_LC_CMD_MAX           (0x03FF | HCI_GRP_VENDOR_SPECIFIC)
-#define HCI_DEBUG_LC_COMMAND           HCI_DEBUG_LC_CMD_MAX
-
-#endif
-
-
-/* AMP VSE events
-*/
-#define AMP_VSE_CHANSPEC_CHAN_MASK      0x00ff
-
-#define AMP_VSE_CHANSPEC_CTL_SB_MASK    0x0300
-#define AMP_VSE_CHANSPEC_CTL_SB_LOWER   0x0100
-#define AMP_VSE_CHANSPEC_CTL_SB_UPPER   0x0200
-#define AMP_VSE_CHANSPEC_CTL_SB_NONE    0x0300
-
-#define AMP_VSE_CHANSPEC_BW_MASK        0x0C00
-#define AMP_VSE_CHANSPEC_BW_10          0x0400
-#define AMP_VSE_CHANSPEC_BW_20          0x0800
-#define AMP_VSE_CHANSPEC_BW_40          0x0C00
-
-#define AMP_VSE_CHANSPEC_BAND_MASK      0xf000
-#define AMP_VSE_CHANSPEC_BAND_5G        0x1000
-#define AMP_VSE_CHANSPEC_BAND_2G        0x2000
-
-
 #endif
 
diff --git a/stack/include/hcimsgs.h b/stack/include/hcimsgs.h
index 3201f75..1447cce 100644
--- a/stack/include/hcimsgs.h
+++ b/stack/include/hcimsgs.h
@@ -23,58 +23,13 @@
 #include "hcidefs.h"
 #include "bt_types.h"
 
-
-#ifdef __cplusplus
-extern "C" {
-#endif
+void bte_main_hci_send(BT_HDR *p_msg, UINT16 event);
+void bte_main_lpm_allow_bt_device_sleep(void);
 
 /* Message by message.... */
 
-#define HCIC_GET_UINT8(p, off)    (UINT8)(*((UINT8 *)((p) + 1) + p->offset + 3 + (off)))
-
-#define HCIC_GET_UINT16(p, off)  (UINT16)((*((UINT8 *)((p) + 1) + p->offset + 3 + (off)) + \
-                                          (*((UINT8 *)((p) + 1) + p->offset + 3 + (off) + 1) << 8)))
-
-#define HCIC_GET_UINT32(p, off)  (UINT32)((*((UINT8 *)((p) + 1) + p->offset + 3 + (off)) + \
-                                          (*((UINT8 *)((p) + 1) + p->offset + 3 + (off) + 1) << 8) + \
-                                          (*((UINT8 *)((p) + 1) + p->offset + 3 + (off) + 2) << 16) + \
-                                          (*((UINT8 *)((p) + 1) + p->offset + 3 + (off) + 3) << 24)))
-
-#define HCIC_GET_ARRAY(p, off, x, len) \
-{ \
-    UINT8 *qq = ((UINT8 *)((p) + 1) + p->offset + 3 + (off)); UINT8 *rr = (UINT8 *)x; \
-    int ii; for (ii = 0; ii < len; ii++) *rr++ = *qq++; \
-}
-
-#define HCIC_GET_ARRAY16(p, off, x) \
-{ \
-    UINT8 *qq = ((UINT8 *)((p) + 1) + p->offset + 3 + (off)); UINT8 *rr = (UINT8 *)x + 15; \
-    int ii; for (ii = 0; ii < 16; ii++) *rr-- = *qq++; \
-}
-
-#define HCIC_GET_BDADDR(p, off, x) \
-{ \
-    UINT8 *qq = ((UINT8 *)((p) + 1) + p->offset + 3 + (off)); UINT8 *rr = (UINT8 *)x + BD_ADDR_LEN - 1; \
-    int ii; for (ii = 0; ii < BD_ADDR_LEN; ii++) *rr-- = *qq++; \
-}
-
-#define HCIC_GET_DEVCLASS(p, off, x) \
-{ \
-    UINT8 *qq = ((UINT8 *)((p) + 1) + p->offset + 3 + (off)); UINT8 *rr = (UINT8 *)x + DEV_CLASS_LEN - 1; \
-    int ii; for (ii = 0; ii < DEV_CLASS_LEN; ii++) *rr-- = *qq++; \
-}
-
-#define HCIC_GET_LAP(p, off, x) \
-{ \
-    UINT8 *qq = ((UINT8 *)((p) + 1) + p->offset + 3 + (off)); UINT8 *rr = (UINT8 *)x + LAP_LEN - 1; \
-    int ii; for (ii = 0; ii < LAP_LEN; ii++) *rr-- = *qq++; \
-}
-
-#define HCIC_GET_POINTER(p, off) ((UINT8 *)((p) + 1) + p->offset + 3 + (off))
-
-
-HCI_API extern BOOLEAN btsnd_hcic_inquiry(const LAP inq_lap, UINT8 duration,
-                                          UINT8 response_cnt);
+extern BOOLEAN btsnd_hcic_inquiry(const LAP inq_lap, UINT8 duration,
+                                  UINT8 response_cnt);
 
 #define HCIC_PARAM_SIZE_INQUIRY 5
 
@@ -85,14 +40,14 @@
                                                                     /* Inquiry */
 
                                                                     /* Inquiry Cancel */
-HCI_API extern BOOLEAN btsnd_hcic_inq_cancel(void);
+extern BOOLEAN btsnd_hcic_inq_cancel(void);
 
 #define HCIC_PARAM_SIZE_INQ_CANCEL   0
 
                                                                     /* Periodic Inquiry Mode */
-HCI_API extern BOOLEAN btsnd_hcic_per_inq_mode(UINT16 max_period, UINT16 min_period,
-                                               const LAP inq_lap, UINT8 duration,
-                                               UINT8 response_cnt);
+extern BOOLEAN btsnd_hcic_per_inq_mode(UINT16 max_period, UINT16 min_period,
+                                       const LAP inq_lap, UINT8 duration,
+                                       UINT8 response_cnt);
 
 #define HCIC_PARAM_SIZE_PER_INQ_MODE    9
 
@@ -104,15 +59,15 @@
                                                                     /* Periodic Inquiry Mode */
 
                                                                     /* Exit Periodic Inquiry Mode */
-HCI_API extern BOOLEAN btsnd_hcic_exit_per_inq(void);
+extern BOOLEAN btsnd_hcic_exit_per_inq(void);
 
 #define HCIC_PARAM_SIZE_EXIT_PER_INQ   0
                                                                     /* Create Connection */
-HCI_API extern BOOLEAN btsnd_hcic_create_conn(BD_ADDR dest, UINT16 packet_types,
-                                              UINT8 page_scan_rep_mode,
-                                              UINT8 page_scan_mode,
-                                              UINT16 clock_offset,
-                                              UINT8 allow_switch);
+extern BOOLEAN btsnd_hcic_create_conn(BD_ADDR dest, UINT16 packet_types,
+                                      UINT8 page_scan_rep_mode,
+                                      UINT8 page_scan_mode,
+                                      UINT16 clock_offset,
+                                      UINT8 allow_switch);
 
 #define HCIC_PARAM_SIZE_CREATE_CONN  13
 
@@ -125,7 +80,7 @@
                                                                     /* Create Connection */
 
                                                                     /* Disconnect */
-HCI_API extern BOOLEAN btsnd_hcic_disconnect(UINT16 handle, UINT8 reason);
+extern BOOLEAN btsnd_hcic_disconnect(UINT16 handle, UINT8 reason);
 
 #define HCIC_PARAM_SIZE_DISCONNECT 3
 
@@ -135,7 +90,7 @@
 
 #if BTM_SCO_INCLUDED == TRUE
                                                                     /* Add SCO Connection */
-HCI_API extern BOOLEAN btsnd_hcic_add_SCO_conn (UINT16 handle, UINT16 packet_types);
+extern BOOLEAN btsnd_hcic_add_SCO_conn (UINT16 handle, UINT16 packet_types);
 #endif /* BTM_SCO_INCLUDED */
 
 #define HCIC_PARAM_SIZE_ADD_SCO_CONN    4
@@ -145,7 +100,7 @@
                                                                     /* Add SCO Connection */
 
                                                                     /* Create Connection Cancel */
-HCI_API extern BOOLEAN btsnd_hcic_create_conn_cancel(BD_ADDR dest);
+extern BOOLEAN btsnd_hcic_create_conn_cancel(BD_ADDR dest);
 
 #define HCIC_PARAM_SIZE_CREATE_CONN_CANCEL  6
 
@@ -153,7 +108,7 @@
                                                                     /* Create Connection Cancel */
 
                                                                     /* Accept Connection Request */
-HCI_API extern BOOLEAN btsnd_hcic_accept_conn (BD_ADDR bd_addr, UINT8 role);
+extern BOOLEAN btsnd_hcic_accept_conn (BD_ADDR bd_addr, UINT8 role);
 
 #define HCIC_PARAM_SIZE_ACCEPT_CONN     7
 
@@ -162,7 +117,7 @@
                                                                     /* Accept Connection Request */
 
                                                                     /* Reject Connection Request */
-HCI_API extern BOOLEAN btsnd_hcic_reject_conn (BD_ADDR bd_addr, UINT8 reason);
+extern BOOLEAN btsnd_hcic_reject_conn (BD_ADDR bd_addr, UINT8 reason);
 
 #define HCIC_PARAM_SIZE_REJECT_CONN      7
 
@@ -171,8 +126,8 @@
                                                                     /* Reject Connection Request */
 
                                                                     /* Link Key Request Reply */
-HCI_API extern BOOLEAN btsnd_hcic_link_key_req_reply (BD_ADDR bd_addr,
-                                                      LINK_KEY link_key);
+extern BOOLEAN btsnd_hcic_link_key_req_reply (BD_ADDR bd_addr,
+                                              LINK_KEY link_key);
 
 #define HCIC_PARAM_SIZE_LINK_KEY_REQ_REPLY   22
 
@@ -181,7 +136,7 @@
                                                                     /* Link Key Request Reply  */
 
                                                                     /* Link Key Request Neg Reply */
-HCI_API extern BOOLEAN btsnd_hcic_link_key_neg_reply (BD_ADDR bd_addr);
+extern BOOLEAN btsnd_hcic_link_key_neg_reply (BD_ADDR bd_addr);
 
 #define HCIC_PARAM_SIZE_LINK_KEY_NEG_REPLY   6
 
@@ -189,9 +144,9 @@
                                                                     /* Link Key Request Neg Reply  */
 
                                                                     /* PIN Code Request Reply */
-HCI_API extern BOOLEAN btsnd_hcic_pin_code_req_reply (BD_ADDR bd_addr,
-                                                      UINT8 pin_code_len,
-                                                      PIN_CODE pin_code);
+extern BOOLEAN btsnd_hcic_pin_code_req_reply (BD_ADDR bd_addr,
+                                              UINT8 pin_code_len,
+                                              PIN_CODE pin_code);
 
 #define HCIC_PARAM_SIZE_PIN_CODE_REQ_REPLY   23
 
@@ -201,7 +156,7 @@
                                                                     /* PIN Code Request Reply  */
 
                                                                     /* Link Key Request Neg Reply */
-HCI_API extern BOOLEAN btsnd_hcic_pin_code_neg_reply (BD_ADDR bd_addr);
+extern BOOLEAN btsnd_hcic_pin_code_neg_reply (BD_ADDR bd_addr);
 
 #define HCIC_PARAM_SIZE_PIN_CODE_NEG_REPLY   6
 
@@ -209,7 +164,7 @@
                                                                     /* Link Key Request Neg Reply  */
 
                                                                     /* Change Connection Type */
-HCI_API extern BOOLEAN btsnd_hcic_change_conn_type (UINT16 handle, UINT16 packet_types);
+extern BOOLEAN btsnd_hcic_change_conn_type (UINT16 handle, UINT16 packet_types);
 
 #define HCIC_PARAM_SIZE_CHANGE_CONN_TYPE     4
 
@@ -221,10 +176,10 @@
 
 #define HCI_CMD_HANDLE_HANDLE_OFF       0
 
-HCI_API extern BOOLEAN btsnd_hcic_auth_request (UINT16 handle);     /* Authentication Request */
+extern BOOLEAN btsnd_hcic_auth_request (UINT16 handle);     /* Authentication Request */
 
                                                                     /* Set Connection Encryption */
-HCI_API extern BOOLEAN btsnd_hcic_set_conn_encrypt (UINT16 handle, BOOLEAN enable);
+extern BOOLEAN btsnd_hcic_set_conn_encrypt (UINT16 handle, BOOLEAN enable);
 #define HCIC_PARAM_SIZE_SET_CONN_ENCRYPT     3
 
 
@@ -232,21 +187,11 @@
 #define HCI_SET_ENCRYPT_ENABLE_OFF      2
                                                                     /* Set Connection Encryption */
 
-HCI_API extern BOOLEAN btsnd_hcic_change_link_key (UINT16 handle);  /* Change Connection Link Key */
-
-                                                                    /* Master Link Key */
-HCI_API extern BOOLEAN btsnd_hcic_master_link_key (BOOLEAN key_flag);
-
-#define HCIC_PARAM_SIZE_MASTER_LINK_KEY 1
-
-#define HCI_MASTER_KEY_FLAG_OFF         0
-                                                                    /* Master Link Key */
-
                                                                     /* Remote Name Request */
-HCI_API extern BOOLEAN btsnd_hcic_rmt_name_req (BD_ADDR bd_addr,
-                                                UINT8 page_scan_rep_mode,
-                                                UINT8 page_scan_mode,
-                                                UINT16 clock_offset);
+extern BOOLEAN btsnd_hcic_rmt_name_req (BD_ADDR bd_addr,
+                                        UINT8 page_scan_rep_mode,
+                                        UINT8 page_scan_mode,
+                                        UINT16 clock_offset);
 
 #define HCIC_PARAM_SIZE_RMT_NAME_REQ   10
 
@@ -257,17 +202,17 @@
                                                                     /* Remote Name Request */
 
                                                                     /* Remote Name Request Cancel */
-HCI_API extern BOOLEAN btsnd_hcic_rmt_name_req_cancel(BD_ADDR bd_addr);
+extern BOOLEAN btsnd_hcic_rmt_name_req_cancel(BD_ADDR bd_addr);
 
 #define HCIC_PARAM_SIZE_RMT_NAME_REQ_CANCEL   6
 
 #define HCI_RMT_NAME_CANCEL_BD_ADDR_OFF       0
                                                                     /* Remote Name Request Cancel */
 
-HCI_API extern BOOLEAN btsnd_hcic_rmt_features_req(UINT16 handle);      /* Remote Features Request */
+extern BOOLEAN btsnd_hcic_rmt_features_req(UINT16 handle);      /* Remote Features Request */
 
                                                                     /* Remote Extended Features */
-HCI_API extern BOOLEAN btsnd_hcic_rmt_ext_features(UINT16 handle, UINT8 page_num);
+extern BOOLEAN btsnd_hcic_rmt_ext_features(UINT16 handle, UINT8 page_num);
 
 #define HCIC_PARAM_SIZE_RMT_EXT_FEATURES   3
 
@@ -276,24 +221,15 @@
                                                                     /* Remote Extended Features */
 
 
-                                                                    /* Local Extended Features */
-HCI_API extern BOOLEAN btsnd_hcic_read_local_ext_features (UINT8 page_num);
+extern BOOLEAN btsnd_hcic_rmt_ver_req(UINT16 handle);           /* Remote Version Info Request */
+extern BOOLEAN btsnd_hcic_read_rmt_clk_offset(UINT16 handle);   /* Remote Clock Offset */
+extern BOOLEAN btsnd_hcic_read_lmp_handle(UINT16 handle);       /* Remote LMP Handle */
 
-#define HCIC_PARAM_SIZE_LOCAL_EXT_FEATURES     1
-
-#define HCI_LOCAL_EXT_FEATURES_PAGE_NUM_OFF    0
-                                                                    /* Local Extended Features */
-
-
-HCI_API extern BOOLEAN btsnd_hcic_rmt_ver_req(UINT16 handle);           /* Remote Version Info Request */
-HCI_API extern BOOLEAN btsnd_hcic_read_rmt_clk_offset(UINT16 handle);   /* Remote Clock Offset */
-HCI_API extern BOOLEAN btsnd_hcic_read_lmp_handle(UINT16 handle);       /* Remote LMP Handle */
-
-HCI_API extern BOOLEAN btsnd_hcic_setup_esco_conn (UINT16 handle,
-                                                   UINT32 tx_bw, UINT32 rx_bw,
-                                                   UINT16 max_latency, UINT16 voice,
-                                                   UINT8 retrans_effort,
-                                                   UINT16 packet_types);
+extern BOOLEAN btsnd_hcic_setup_esco_conn (UINT16 handle,
+                                           UINT32 tx_bw, UINT32 rx_bw,
+                                           UINT16 max_latency, UINT16 voice,
+                                           UINT8 retrans_effort,
+                                           UINT16 packet_types);
 #define HCIC_PARAM_SIZE_SETUP_ESCO      17
 
 #define HCI_SETUP_ESCO_HANDLE_OFF       0
@@ -305,12 +241,12 @@
 #define HCI_SETUP_ESCO_PKT_TYPES_OFF    15
 
 
-HCI_API extern BOOLEAN btsnd_hcic_accept_esco_conn (BD_ADDR bd_addr,
-                                                    UINT32 tx_bw, UINT32 rx_bw,
-                                                    UINT16 max_latency,
-                                                    UINT16 content_fmt,
-                                                    UINT8 retrans_effort,
-                                                    UINT16 packet_types);
+extern BOOLEAN btsnd_hcic_accept_esco_conn (BD_ADDR bd_addr,
+                                            UINT32 tx_bw, UINT32 rx_bw,
+                                            UINT16 max_latency,
+                                            UINT16 content_fmt,
+                                            UINT8 retrans_effort,
+                                            UINT16 packet_types);
 #define HCIC_PARAM_SIZE_ACCEPT_ESCO     21
 
 #define HCI_ACCEPT_ESCO_BDADDR_OFF      0
@@ -322,15 +258,15 @@
 #define HCI_ACCEPT_ESCO_PKT_TYPES_OFF   19
 
 
-HCI_API extern BOOLEAN btsnd_hcic_reject_esco_conn (BD_ADDR bd_addr, UINT8 reason);
+extern BOOLEAN btsnd_hcic_reject_esco_conn (BD_ADDR bd_addr, UINT8 reason);
 #define HCIC_PARAM_SIZE_REJECT_ESCO     7
 
 #define HCI_REJECT_ESCO_BDADDR_OFF      0
 #define HCI_REJECT_ESCO_REASON_OFF      6
 
 /* Hold Mode */
-HCI_API extern BOOLEAN btsnd_hcic_hold_mode(UINT16 handle, UINT16 max_hold_period,
-                                            UINT16 min_hold_period);
+extern BOOLEAN btsnd_hcic_hold_mode(UINT16 handle, UINT16 max_hold_period,
+                                    UINT16 min_hold_period);
 
 #define HCIC_PARAM_SIZE_HOLD_MODE       6
 
@@ -340,11 +276,11 @@
                                                                     /* Hold Mode */
 
                                                                     /* Sniff Mode */
-HCI_API extern BOOLEAN btsnd_hcic_sniff_mode(UINT16 handle,
-                                             UINT16 max_sniff_period,
-                                             UINT16 min_sniff_period,
-                                             UINT16 sniff_attempt,
-                                             UINT16 sniff_timeout);
+extern BOOLEAN btsnd_hcic_sniff_mode(UINT16 handle,
+                                     UINT16 max_sniff_period,
+                                     UINT16 min_sniff_period,
+                                     UINT16 sniff_attempt,
+                                     UINT16 sniff_timeout);
 
 #define HCIC_PARAM_SIZE_SNIFF_MODE      10
 
@@ -356,12 +292,12 @@
 #define HCI_SNIFF_MODE_TIMEOUT_OFF      8
                                                                     /* Sniff Mode */
 
-HCI_API extern BOOLEAN btsnd_hcic_exit_sniff_mode(UINT16 handle);       /* Exit Sniff Mode */
+extern BOOLEAN btsnd_hcic_exit_sniff_mode(UINT16 handle);       /* Exit Sniff Mode */
 
                                                                     /* Park Mode */
-HCI_API extern BOOLEAN btsnd_hcic_park_mode (UINT16 handle,
-                                             UINT16 beacon_max_interval,
-                                             UINT16 beacon_min_interval);
+extern BOOLEAN btsnd_hcic_park_mode (UINT16 handle,
+                                     UINT16 beacon_max_interval,
+                                     UINT16 beacon_min_interval);
 
 #define HCIC_PARAM_SIZE_PARK_MODE       6
 
@@ -370,13 +306,13 @@
 #define HCI_PARK_MODE_MIN_PER_OFF       4
                                                                     /* Park Mode */
 
-HCI_API extern BOOLEAN btsnd_hcic_exit_park_mode(UINT16 handle);  /* Exit Park Mode */
+extern BOOLEAN btsnd_hcic_exit_park_mode(UINT16 handle);  /* Exit Park Mode */
 
                                                                     /* QoS Setup */
-HCI_API extern BOOLEAN btsnd_hcic_qos_setup (UINT16 handle, UINT8 flags,
-                                             UINT8 service_type,
-                                             UINT32 token_rate, UINT32 peak,
-                                             UINT32 latency, UINT32 delay_var);
+extern BOOLEAN btsnd_hcic_qos_setup (UINT16 handle, UINT8 flags,
+                                     UINT8 service_type,
+                                     UINT32 token_rate, UINT32 peak,
+                                     UINT32 latency, UINT32 delay_var);
 
 #define HCIC_PARAM_SIZE_QOS_SETUP       20
 
@@ -389,10 +325,8 @@
 #define HCI_QOS_DELAY_VAR_OFF           16
                                                                     /* QoS Setup */
 
-HCI_API extern BOOLEAN btsnd_hcic_role_discovery (UINT16 handle);       /* Role Discovery */
-
                                                                     /* Switch Role Request */
-HCI_API extern BOOLEAN btsnd_hcic_switch_role (BD_ADDR bd_addr, UINT8 role);
+extern BOOLEAN btsnd_hcic_switch_role (BD_ADDR bd_addr, UINT8 role);
 
 #define HCIC_PARAM_SIZE_SWITCH_ROLE  7
 
@@ -400,10 +334,8 @@
 #define HCI_SWITCH_ROLE_OFF             6
                                                                     /* Switch Role Request */
 
-HCI_API extern BOOLEAN btsnd_hcic_read_policy_set(UINT16 handle);       /* Read Policy Settings */
-
                                                                     /* Write Policy Settings */
-HCI_API extern BOOLEAN btsnd_hcic_write_policy_set(UINT16 handle, UINT16 settings);
+extern BOOLEAN btsnd_hcic_write_policy_set(UINT16 handle, UINT16 settings);
 
 #define HCIC_PARAM_SIZE_WRITE_POLICY_SET     4
 
@@ -411,48 +343,22 @@
 #define HCI_WRITE_POLICY_SETTINGS_OFF        2
                                                                     /* Write Policy Settings */
 
-                                                                    /* Read Default Policy Settings */
-HCI_API extern BOOLEAN btsnd_hcic_read_def_policy_set(void);
-
-#define HCIC_PARAM_SIZE_READ_DEF_POLICY_SET           0
-                                                                    /* Read Default Policy Settings */
-
                                                                     /* Write Default Policy Settings */
-HCI_API extern BOOLEAN btsnd_hcic_write_def_policy_set(UINT16 settings);
+extern BOOLEAN btsnd_hcic_write_def_policy_set(UINT16 settings);
 
 #define HCIC_PARAM_SIZE_WRITE_DEF_POLICY_SET     2
 
 #define HCI_WRITE_DEF_POLICY_SETTINGS_OFF        0
                                                                     /* Write Default Policy Settings */
 
-                                                                    /* Flow Specification */
-HCI_API extern BOOLEAN btsnd_hcic_flow_specification(UINT16 handle, UINT8 flags,
-                                                     UINT8 flow_direct,
-                                                     UINT8 service_type,
-                                                     UINT32 token_rate,
-                                                     UINT32 token_bucket_size,
-                                                     UINT32 peak, UINT32 latency);
-
-#define HCIC_PARAM_SIZE_FLOW_SPEC             21
-
-#define HCI_FLOW_SPEC_HANDLE_OFF              0
-#define HCI_FLOW_SPEC_FLAGS_OFF               2
-#define HCI_FLOW_SPEC_FLOW_DIRECT_OFF         3
-#define HCI_FLOW_SPEC_SERVICE_TYPE_OFF        4
-#define HCI_FLOW_SPEC_TOKEN_RATE_OFF          5
-#define HCI_FLOW_SPEC_TOKEN_BUCKET_SIZE_OFF   9
-#define HCI_FLOW_SPEC_PEAK_BANDWIDTH_OFF      13
-#define HCI_FLOW_SPEC_LATENCY_OFF             17
-                                                                    /* Flow Specification */
-
 /******************************************
 **    Lisbon Features
 *******************************************/
 #if BTM_SSR_INCLUDED == TRUE
                                                                     /* Sniff Subrating */
-HCI_API extern BOOLEAN btsnd_hcic_sniff_sub_rate(UINT16 handle, UINT16 max_lat,
-						                         UINT16 min_remote_lat,
-                                                 UINT16 min_local_lat);
+extern BOOLEAN btsnd_hcic_sniff_sub_rate(UINT16 handle, UINT16 max_lat,
+                                         UINT16 min_remote_lat,
+                                         UINT16 min_local_lat);
 
 #define HCIC_PARAM_SIZE_SNIFF_SUB_RATE             8
 
@@ -469,42 +375,15 @@
 #endif  /* BTM_SSR_INCLUDED */
 
                                                                     /* Extended Inquiry Response */
-#if (BTM_EIR_SERVER_INCLUDED == TRUE)
-HCI_API extern void btsnd_hcic_write_ext_inquiry_response(void *buffer, UINT8 fec_req);
+extern void btsnd_hcic_write_ext_inquiry_response(void *buffer, UINT8 fec_req);
 
 #define HCIC_PARAM_SIZE_EXT_INQ_RESP        241
 
 #define HCIC_EXT_INQ_RESP_FEC_OFF     0
 #define HCIC_EXT_INQ_RESP_RESPONSE    1
-
-HCI_API extern BOOLEAN btsnd_hcic_read_ext_inquiry_response(void);   /* Read Extended Inquiry Response */
-#else
-#define btsnd_hcic_write_ext_inquiry_response(buffer, fec_req)
-#define btsnd_hcic_read_ext_inquiry_response() FALSE
-#endif
-                                                                    /* Write Simple Pairing Mode */
-/**** Simple Pairing Commands ****/
-HCI_API extern BOOLEAN btsnd_hcic_write_simple_pairing_mode(UINT8 mode);
-
-#define HCIC_PARAM_SIZE_W_SIMP_PAIR     1
-
-#define HCIC_WRITE_SP_MODE_OFF          0
-
-
-HCI_API extern BOOLEAN btsnd_hcic_read_simple_pairing_mode (void);
-
-#define HCIC_PARAM_SIZE_R_SIMP_PAIR     0
-
-                                                                    /* Write Simple Pairing Debug Mode */
-HCI_API extern BOOLEAN btsnd_hcic_write_simp_pair_debug_mode(UINT8 debug_mode);
-
-#define HCIC_PARAM_SIZE_SIMP_PAIR_DBUG  1
-
-#define HCIC_WRITE_SP_DBUG_MODE_OFF     0
-
-                                                                    /* IO Capabilities Response */
-HCI_API extern BOOLEAN btsnd_hcic_io_cap_req_reply (BD_ADDR bd_addr, UINT8 capability,
-                                               UINT8 oob_present, UINT8 auth_req);
+                                                                   /* IO Capabilities Response */
+extern BOOLEAN btsnd_hcic_io_cap_req_reply (BD_ADDR bd_addr, UINT8 capability,
+                                            UINT8 oob_present, UINT8 auth_req);
 
 #define HCIC_PARAM_SIZE_IO_CAP_RESP     9
 
@@ -514,7 +393,7 @@
 #define HCI_IO_CAP_AUTH_REQ_OFF         8
 
                                                                     /* IO Capabilities Req Neg Reply */
-HCI_API extern BOOLEAN btsnd_hcic_io_cap_req_neg_reply (BD_ADDR bd_addr, UINT8 err_code);
+extern BOOLEAN btsnd_hcic_io_cap_req_neg_reply (BD_ADDR bd_addr, UINT8 err_code);
 
 #define HCIC_PARAM_SIZE_IO_CAP_NEG_REPLY 7
 
@@ -522,19 +401,19 @@
 #define HCI_IO_CAP_NR_ERR_CODE           6
 
                                                          /* Read Local OOB Data */
-HCI_API extern BOOLEAN btsnd_hcic_read_local_oob_data (void);
+extern BOOLEAN btsnd_hcic_read_local_oob_data (void);
 
 #define HCIC_PARAM_SIZE_R_LOCAL_OOB     0
 
 
-HCI_API extern BOOLEAN btsnd_hcic_user_conf_reply (BD_ADDR bd_addr, BOOLEAN is_yes);
+extern BOOLEAN btsnd_hcic_user_conf_reply (BD_ADDR bd_addr, BOOLEAN is_yes);
 
 #define HCIC_PARAM_SIZE_UCONF_REPLY     6
 
 #define HCI_USER_CONF_BD_ADDR_OFF       0
 
 
-HCI_API extern BOOLEAN btsnd_hcic_user_passkey_reply (BD_ADDR bd_addr, UINT32 value);
+extern BOOLEAN btsnd_hcic_user_passkey_reply (BD_ADDR bd_addr, UINT32 value);
 
 #define HCIC_PARAM_SIZE_U_PKEY_REPLY    10
 
@@ -542,15 +421,15 @@
 #define HCI_USER_PASSKEY_VALUE_OFF      6
 
 
-HCI_API extern BOOLEAN btsnd_hcic_user_passkey_neg_reply (BD_ADDR bd_addr);
+extern BOOLEAN btsnd_hcic_user_passkey_neg_reply (BD_ADDR bd_addr);
 
 #define HCIC_PARAM_SIZE_U_PKEY_NEG_REPLY 6
 
 #define HCI_USER_PASSKEY_NEG_BD_ADDR_OFF 0
 
                                                             /* Remote OOB Data Request Reply */
-HCI_API extern BOOLEAN btsnd_hcic_rem_oob_reply (BD_ADDR bd_addr, UINT8 *p_c,
-                                                 UINT8 *p_r);
+extern BOOLEAN btsnd_hcic_rem_oob_reply (BD_ADDR bd_addr, UINT8 *p_c,
+                                         UINT8 *p_r);
 
 #define HCIC_PARAM_SIZE_REM_OOB_REPLY   38
 
@@ -559,83 +438,45 @@
 #define HCI_REM_OOB_DATA_R_OFF          22
 
                                                             /* Remote OOB Data Request Negative Reply */
-HCI_API extern BOOLEAN btsnd_hcic_rem_oob_neg_reply (BD_ADDR bd_addr);
+extern BOOLEAN btsnd_hcic_rem_oob_neg_reply (BD_ADDR bd_addr);
 
 #define HCIC_PARAM_SIZE_REM_OOB_NEG_REPLY   6
 
 #define HCI_REM_OOB_DATA_NEG_BD_ADDR_OFF    0
 
                                                             /* Read Tx Power Level */
-HCI_API extern BOOLEAN btsnd_hcic_read_inq_tx_power (void);
+extern BOOLEAN btsnd_hcic_read_inq_tx_power (void);
 
 #define HCIC_PARAM_SIZE_R_TX_POWER      0
 
-                                                            /* Write Tx Power Level */
-HCI_API extern BOOLEAN btsnd_hcic_write_inq_tx_power (INT8 level);
-
-#define HCIC_PARAM_SIZE_W_TX_POWER      1
-
-#define HCIC_WRITE_TX_POWER_LEVEL_OFF   0
                                                             /* Read Default Erroneous Data Reporting */
-HCI_API extern BOOLEAN btsnd_hcic_read_default_erroneous_data_rpt (void);
+extern BOOLEAN btsnd_hcic_read_default_erroneous_data_rpt (void);
 
 #define HCIC_PARAM_SIZE_R_ERR_DATA_RPT      0
 
-                                                            /* Write Default Erroneous Data Reporting */
-HCI_API extern BOOLEAN btsnd_hcic_write_default_erroneous_data_rpt (UINT8 level);
-
-#define HCIC_PARAM_SIZE_W_ERR_DATA_RPT      1
-
-#define HCIC_WRITE_ERR_DATA_RPT_OFF   0
-
-
 #if L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE
-HCI_API extern BOOLEAN btsnd_hcic_enhanced_flush (UINT16 handle, UINT8 packet_type);
+extern BOOLEAN btsnd_hcic_enhanced_flush (UINT16 handle, UINT8 packet_type);
 
 #define HCIC_PARAM_SIZE_ENHANCED_FLUSH  3
 #endif
 
 
-HCI_API extern BOOLEAN btsnd_hcic_send_keypress_notif (BD_ADDR bd_addr, UINT8 notif);
+extern BOOLEAN btsnd_hcic_send_keypress_notif (BD_ADDR bd_addr, UINT8 notif);
 
 #define HCIC_PARAM_SIZE_SEND_KEYPRESS_NOTIF    7
 
 #define HCI_SEND_KEYPRESS_NOTIF_BD_ADDR_OFF    0
 #define HCI_SEND_KEYPRESS_NOTIF_NOTIF_OFF      6
 
-
-HCI_API extern BOOLEAN btsnd_hcic_refresh_encryption_key(UINT16 handle);       /* Refresh Encryption Key */
-
 /**** end of Simple Pairing Commands ****/
 
-
-HCI_API extern BOOLEAN btsnd_hcic_set_event_mask(UINT8 local_controller_id, BT_EVENT_MASK evt_mask);
-
-#define HCIC_PARAM_SIZE_SET_EVENT_MASK  8
-#define HCI_EVENT_MASK_MASK_OFF         0
-                                                                    /* Set Event Mask */
-
-                                                                    /* Reset */
-HCI_API extern BOOLEAN btsnd_hcic_set_event_mask_page_2 (UINT8 local_controller_id,
-                                                         BT_EVENT_MASK event_mask);
-
-#define HCIC_PARAM_SIZE_SET_EVENT_MASK_PAGE_2   8
-#define HCI_EVENT_MASK_MASK_OFF                 0
-                                                                    /* Set Event Mask Page 2 */
-
-                                                                    /* Reset */
-HCI_API extern BOOLEAN btsnd_hcic_reset(UINT8 local_controller_id);
-
-#define HCIC_PARAM_SIZE_RESET           0
-                                                                    /* Reset */
-
                                                                     /* Store Current Settings */
 #define MAX_FILT_COND   (sizeof (BD_ADDR) + 1)
 
-HCI_API extern BOOLEAN btsnd_hcic_set_event_filter(UINT8 filt_type,
-                                                   UINT8 filt_cond_type,
-                                                   UINT8 *filt_cond,
-                                                   UINT8 filt_cond_len);
+extern BOOLEAN btsnd_hcic_set_event_filter(UINT8 filt_type,
+                                           UINT8 filt_cond_type,
+                                           UINT8 *filt_cond,
+                                           UINT8 filt_cond_len);
 
 #define HCIC_PARAM_SIZE_SET_EVT_FILTER  9
 
@@ -644,40 +485,8 @@
 #define HCI_FILT_COND_FILT_OFF          2
                                                                     /* Set Event Filter */
 
-HCI_API extern BOOLEAN btsnd_hcic_flush(UINT8 local_controller_id, UINT16 handle);                 /* Flush */
-
-                                                                    /* Create New Unit Type */
-HCI_API extern BOOLEAN btsnd_hcic_new_unit_key(void);
-
-#define HCIC_PARAM_SIZE_NEW_UNIT_KEY     0
-                                                                    /* Create New Unit Type */
-
-                                                                /* Read Stored Key */
-HCI_API extern BOOLEAN btsnd_hcic_read_stored_key (BD_ADDR bd_addr,
-                                                   BOOLEAN read_all_flag);
-
-#define HCIC_PARAM_SIZE_READ_STORED_KEY 7
-
-#define HCI_READ_KEY_BD_ADDR_OFF        0
-#define HCI_READ_KEY_ALL_FLAG_OFF       6
-                                                                /* Read Stored Key */
-
-#define MAX_WRITE_KEYS 10
-                                                                /* Write Stored Key */
-HCI_API extern BOOLEAN btsnd_hcic_write_stored_key (UINT8 num_keys, BD_ADDR *bd_addr,
-                                                    LINK_KEY *link_key);
-
-#define HCIC_PARAM_SIZE_WRITE_STORED_KEY  sizeof(btmsg_hcic_write_stored_key_t)
-
-#define HCI_WRITE_KEY_NUM_KEYS_OFF          0
-#define HCI_WRITE_KEY_BD_ADDR_OFF           1
-#define HCI_WRITE_KEY_KEY_OFF               7
-/* only 0x0b keys cab be sent in one HCI command */
-#define HCI_MAX_NUM_OF_LINK_KEYS_PER_CMMD   0x0b
-                                                                /* Write Stored Key */
-
                                                                 /* Delete Stored Key */
-HCI_API extern BOOLEAN btsnd_hcic_delete_stored_key (BD_ADDR bd_addr, BOOLEAN delete_all_flag);
+extern BOOLEAN btsnd_hcic_delete_stored_key (BD_ADDR bd_addr, BOOLEAN delete_all_flag);
 
 #define HCIC_PARAM_SIZE_DELETE_STORED_KEY        7
 
@@ -686,7 +495,7 @@
                                                                 /* Delete Stored Key */
 
                                                                 /* Change Local Name */
-HCI_API extern BOOLEAN btsnd_hcic_change_name(BD_NAME name);
+extern BOOLEAN btsnd_hcic_change_name(BD_NAME name);
 
 #define HCIC_PARAM_SIZE_CHANGE_NAME     BD_NAME_LEN
 
@@ -710,21 +519,13 @@
 
 #define HCIC_PARAM_SIZE_SET_AFH_CHANNELS    10
 
-HCI_API extern BOOLEAN btsnd_hcic_read_pin_type(void);                          /* Read PIN Type */
-HCI_API extern BOOLEAN btsnd_hcic_write_pin_type(UINT8 type);                   /* Write PIN Type */
-HCI_API extern BOOLEAN btsnd_hcic_read_auto_accept(void);                       /* Read Auto Accept */
-HCI_API extern BOOLEAN btsnd_hcic_write_auto_accept(UINT8 flag);                /* Write Auto Accept */
-HCI_API extern BOOLEAN btsnd_hcic_read_name (void);                             /* Read Local Name */
-HCI_API extern BOOLEAN btsnd_hcic_read_conn_acc_tout(UINT8 local_controller_id);       /* Read Connection Accept Timout */
-HCI_API extern BOOLEAN btsnd_hcic_write_conn_acc_tout(UINT8 local_controller_id, UINT16 tout); /* Write Connection Accept Timout */
-HCI_API extern BOOLEAN btsnd_hcic_read_page_tout(void);                         /* Read Page Timout */
-HCI_API extern BOOLEAN btsnd_hcic_write_page_tout(UINT16 timeout);              /* Write Page Timout */
-HCI_API extern BOOLEAN btsnd_hcic_read_scan_enable(void);                       /* Read Scan Enable */
-HCI_API extern BOOLEAN btsnd_hcic_write_scan_enable(UINT8 flag);                /* Write Scan Enable */
-HCI_API extern BOOLEAN btsnd_hcic_read_pagescan_cfg(void);                      /* Read Page Scan Activity */
-
-HCI_API extern BOOLEAN btsnd_hcic_write_pagescan_cfg(UINT16 interval,
-                                                     UINT16 window);            /* Write Page Scan Activity */
+extern BOOLEAN btsnd_hcic_write_pin_type(UINT8 type);                   /* Write PIN Type */
+extern BOOLEAN btsnd_hcic_write_auto_accept(UINT8 flag);                /* Write Auto Accept */
+extern BOOLEAN btsnd_hcic_read_name (void);                             /* Read Local Name */
+extern BOOLEAN btsnd_hcic_write_page_tout(UINT16 timeout);              /* Write Page Timout */
+extern BOOLEAN btsnd_hcic_write_scan_enable(UINT8 flag);                /* Write Scan Enable */
+extern BOOLEAN btsnd_hcic_write_pagescan_cfg(UINT16 interval,
+                                             UINT16 window);            /* Write Page Scan Activity */
 
 #define HCIC_PARAM_SIZE_WRITE_PAGESCAN_CFG  4
 
@@ -732,10 +533,8 @@
 #define HCI_SCAN_CFG_WINDOW_OFF         2
                                                                 /* Write Page Scan Activity */
 
-HCI_API extern BOOLEAN btsnd_hcic_read_inqscan_cfg(void);       /* Read Inquiry Scan Activity */
-
                                                                 /* Write Inquiry Scan Activity */
-HCI_API extern BOOLEAN btsnd_hcic_write_inqscan_cfg(UINT16 interval, UINT16 window);
+extern BOOLEAN btsnd_hcic_write_inqscan_cfg(UINT16 interval, UINT16 window);
 
 #define HCIC_PARAM_SIZE_WRITE_INQSCAN_CFG    4
 
@@ -743,14 +542,9 @@
 #define HCI_SCAN_CFG_WINDOW_OFF         2
                                                                 /* Write Inquiry Scan Activity */
 
-HCI_API extern BOOLEAN btsnd_hcic_read_auth_enable(void);                        /* Read Authentication Enable */
-HCI_API extern BOOLEAN btsnd_hcic_write_auth_enable(UINT8 flag);                 /* Write Authentication Enable */
-HCI_API extern BOOLEAN btsnd_hcic_read_encr_mode (void);                         /* Read encryption mode */
-HCI_API extern BOOLEAN btsnd_hcic_write_encr_mode (UINT8 mode);                  /* Write encryption mode */
-HCI_API extern BOOLEAN btsnd_hcic_read_dev_class(void);                          /* Read Class of Device */
-HCI_API extern BOOLEAN btsnd_hcic_write_dev_class(DEV_CLASS dev);                /* Write Class of Device */
-HCI_API extern BOOLEAN btsnd_hcic_read_voice_settings(void);                     /* Read Voice Settings */
-HCI_API extern BOOLEAN btsnd_hcic_write_voice_settings(UINT16 flags);            /* Write Voice Settings */
+extern BOOLEAN btsnd_hcic_write_auth_enable(UINT8 flag);                 /* Write Authentication Enable */
+extern BOOLEAN btsnd_hcic_write_dev_class(DEV_CLASS dev);                /* Write Class of Device */
+extern BOOLEAN btsnd_hcic_write_voice_settings(UINT16 flags);            /* Write Voice Settings */
 
 /* Host Controller to Host flow control */
 #define HCI_HOST_FLOW_CTRL_OFF          0
@@ -758,25 +552,15 @@
 #define HCI_HOST_FLOW_CTRL_SCO_ON       2
 #define HCI_HOST_FLOW_CTRL_BOTH_ON      3
 
-HCI_API extern BOOLEAN btsnd_hcic_set_host_flow_ctrl (UINT8 value);         /* Enable/disable flow control toward host */
-
-
-HCI_API extern BOOLEAN btsnd_hcic_read_auto_flush_tout(UINT16 handle);      /* Read Retransmit Timout */
-
-HCI_API extern BOOLEAN btsnd_hcic_write_auto_flush_tout(UINT16 handle,
-                                                        UINT16 timeout);    /* Write Retransmit Timout */
+extern BOOLEAN btsnd_hcic_write_auto_flush_tout(UINT16 handle,
+                                                UINT16 timeout);    /* Write Retransmit Timout */
 
 #define HCIC_PARAM_SIZE_WRITE_AUTO_FLUSH_TOUT    4
 
 #define HCI_FLUSH_TOUT_HANDLE_OFF       0
 #define HCI_FLUSH_TOUT_TOUT_OFF         2
 
-HCI_API extern BOOLEAN btsnd_hcic_read_num_bcast_xmit(void);                    /* Read Num Broadcast Retransmits */
-HCI_API extern BOOLEAN btsnd_hcic_write_num_bcast_xmit(UINT8 num);              /* Write Num Broadcast Retransmits */
-HCI_API extern BOOLEAN btsnd_hcic_read_hold_mode_act(void);                     /* Read Hold Mode Activity */
-HCI_API extern BOOLEAN btsnd_hcic_write_hold_mode_act(UINT8 flags);             /* Write Hold Mode Activity */
-
-HCI_API extern BOOLEAN btsnd_hcic_read_tx_power(UINT16 handle, UINT8 type);     /* Read Tx Power */
+extern BOOLEAN btsnd_hcic_read_tx_power(UINT16 handle, UINT8 type);     /* Read Tx Power */
 
 #define HCIC_PARAM_SIZE_READ_TX_POWER    3
 
@@ -787,26 +571,9 @@
 #define HCI_READ_CURRENT                0x00
 #define HCI_READ_MAXIMUM                0x01
 
-HCI_API extern BOOLEAN btsnd_hcic_read_sco_flow_enable(void);                       /* Read Authentication Enable */
-HCI_API extern BOOLEAN btsnd_hcic_write_sco_flow_enable(UINT8 flag);                /* Write Authentication Enable */
-
-                                                                /* Set Host Buffer Size */
-HCI_API extern BOOLEAN btsnd_hcic_set_host_buf_size (UINT16 acl_len,
-                                                     UINT8 sco_len,
-                                                     UINT16 acl_num,
-                                                     UINT16 sco_num);
-
-#define HCIC_PARAM_SIZE_SET_HOST_BUF_SIZE    7
-
-#define HCI_HOST_BUF_SIZE_ACL_LEN_OFF   0
-#define HCI_HOST_BUF_SIZE_SCO_LEN_OFF   2
-#define HCI_HOST_BUF_SIZE_ACL_NUM_OFF   3
-#define HCI_HOST_BUF_SIZE_SCO_NUM_OFF   5
-
-
-HCI_API extern BOOLEAN btsnd_hcic_host_num_xmitted_pkts (UINT8 num_handles,
-                                                         UINT16 *handle,
-                                                         UINT16 *num_pkts);         /* Set Host Buffer Size */
+extern BOOLEAN btsnd_hcic_host_num_xmitted_pkts (UINT8 num_handles,
+                                                 UINT16 *handle,
+                                                 UINT16 *num_pkts);         /* Set Host Buffer Size */
 
 #define HCIC_PARAM_SIZE_NUM_PKTS_DONE_SIZE    sizeof(btmsg_hcic_num_pkts_done_t)
 
@@ -816,10 +583,8 @@
 #define HCI_PKTS_DONE_HANDLE_OFF        1
 #define HCI_PKTS_DONE_NUM_PKTS_OFF      3
 
-HCI_API extern BOOLEAN btsnd_hcic_read_link_super_tout(UINT8 local_controller_id, UINT16 handle);  /* Read Link Supervision Timeout */
-
                                                                 /* Write Link Supervision Timeout */
-HCI_API extern BOOLEAN btsnd_hcic_write_link_super_tout(UINT8 local_controller_id, UINT16 handle, UINT16 timeout);
+extern BOOLEAN btsnd_hcic_write_link_super_tout(UINT8 local_controller_id, UINT16 handle, UINT16 timeout);
 
 #define HCIC_PARAM_SIZE_WRITE_LINK_SUPER_TOUT        4
 
@@ -827,11 +592,8 @@
 #define HCI_LINK_SUPER_TOUT_TOUT_OFF    2
                                                                 /* Write Link Supervision Timeout */
 
-HCI_API extern BOOLEAN btsnd_hcic_read_max_iac (void);                      /* Read Num Supported IAC */
-HCI_API extern BOOLEAN btsnd_hcic_read_cur_iac_lap (void);                  /* Read Current IAC LAP */
-
-HCI_API extern BOOLEAN btsnd_hcic_write_cur_iac_lap (UINT8 num_cur_iac,
-                                                     LAP * const iac_lap);  /* Write Current IAC LAP */
+extern BOOLEAN btsnd_hcic_write_cur_iac_lap (UINT8 num_cur_iac,
+                                             LAP * const iac_lap);  /* Write Current IAC LAP */
 
 #define MAX_IAC_LAPS    0x40
 
@@ -839,66 +601,12 @@
 #define HCI_WRITE_IAC_LAP_LAP_OFF       1
                                                                 /* Write Current IAC LAP */
 
-                                                                /* Read Clock */
-HCI_API extern BOOLEAN btsnd_hcic_read_clock (UINT16 handle, UINT8 which_clock);
-
-#define HCIC_PARAM_SIZE_READ_CLOCK      3
-
-#define HCI_READ_CLOCK_HANDLE_OFF       0
-#define HCI_READ_CLOCK_WHICH_CLOCK      2
-                                                                /* Read Clock */
-
-#ifdef TESTER_ENABLE
-
-#define HCIC_PARAM_SIZE_ENTER_TEST_MODE  2
-
-#define HCI_ENTER_TEST_HANDLE_OFF        0
-
-#define HCIC_PARAM_SIZE_TEST_CNTRL          10
-#define HCI_TEST_CNTRL_HANDLE_OFF           0
-#define HCI_TEST_CNTRL_SCENARIO_OFF         2
-#define HCI_TEST_CNTRL_HOPPINGMODE_OFF      3
-#define HCI_TEST_CNTRL_TX_FREQ_OFF          4
-#define HCI_TEST_CNTRL_RX_FREQ_OFF          5
-#define HCI_TEST_CNTRL_PWR_CNTRL_MODE_OFF   6
-#define HCI_TEST_CNTRL_POLL_PERIOD_OFF      7
-#define HCI_TEST_CNTRL_PKT_TYPE_OFF         8
-#define HCI_TEST_CNTRL_LENGTH_OFF           9
-
-#endif
-
-HCI_API extern BOOLEAN btsnd_hcic_read_page_scan_per (void);                   /* Read Page Scan Period Mode */
-HCI_API extern BOOLEAN btsnd_hcic_write_page_scan_per (UINT8 mode);            /* Write Page Scan Period Mode */
-HCI_API extern BOOLEAN btsnd_hcic_read_page_scan_mode (void);                  /* Read Page Scan Mode */
-HCI_API extern BOOLEAN btsnd_hcic_write_page_scan_mode (UINT8 mode);           /* Write Page Scan Mode */
-HCI_API extern BOOLEAN btsnd_hcic_read_local_ver (UINT8 local_controller_id);         /* Read Local Version Info */
-HCI_API extern BOOLEAN btsnd_hcic_read_local_supported_cmds (UINT8 local_controller_id); /* Read Local Supported Commands */
-HCI_API extern BOOLEAN btsnd_hcic_read_local_features (void);                  /* Read Local Supported Features */
-HCI_API extern BOOLEAN btsnd_hcic_read_buffer_size (void);                     /* Read Local buffer sizes */
-HCI_API extern BOOLEAN btsnd_hcic_read_country_code (void);                    /* Read Country Code */
-HCI_API extern BOOLEAN btsnd_hcic_read_bd_addr (void);                         /* Read Local BD_ADDR */
-HCI_API extern BOOLEAN btsnd_hcic_read_fail_contact_count (UINT8 local_controller_id, UINT16 handle); /* Read Failed Contact Counter */
-HCI_API extern BOOLEAN btsnd_hcic_reset_fail_contact_count (UINT8 local_controller_id, UINT16 handle);/* Reset Failed Contact Counter */
-HCI_API extern BOOLEAN btsnd_hcic_get_link_quality (UINT16 handle);            /* Get Link Quality */
-HCI_API extern BOOLEAN btsnd_hcic_read_rssi (UINT16 handle);                   /* Read RSSI */
-HCI_API extern BOOLEAN btsnd_hcic_read_loopback_mode (void);                   /* Read Loopback Mode */
-HCI_API extern BOOLEAN btsnd_hcic_write_loopback_mode (UINT8 mode);            /* Write Loopback Mode */
-HCI_API extern BOOLEAN btsnd_hcic_enable_test_mode (void);                     /* Enable Device Under Test Mode */
-HCI_API extern BOOLEAN btsnd_hcic_write_pagescan_type(UINT8 type);             /* Write Page Scan Type */
-HCI_API extern BOOLEAN btsnd_hcic_read_pagescan_type(void);                    /* Read Page Scan Type */
-HCI_API extern BOOLEAN btsnd_hcic_write_inqscan_type(UINT8 type);              /* Write Inquiry Scan Type */
-HCI_API extern BOOLEAN btsnd_hcic_read_inqscan_type(void);                     /* Read Inquiry Scan Type */
-HCI_API extern BOOLEAN btsnd_hcic_write_inquiry_mode(UINT8 type);              /* Write Inquiry Mode */
-HCI_API extern BOOLEAN btsnd_hcic_read_inquiry_mode(void);                     /* Read Inquiry Mode */
-HCI_API extern BOOLEAN btsnd_hcic_set_afh_channels (UINT8 first, UINT8 last);
-HCI_API extern BOOLEAN btsnd_hcic_write_afh_channel_assessment_mode (UINT8 mode);
-HCI_API extern BOOLEAN btsnd_hcic_set_afh_host_channel_class (UINT8 *p_afhchannelmap);
-HCI_API extern BOOLEAN btsnd_hcic_read_afh_channel_assessment_mode(void);
-HCI_API extern BOOLEAN btsnd_hcic_read_afh_channel_map (UINT16 handle);
-HCI_API extern BOOLEAN btsnd_hcic_nop(void);                               /* NOP */
-
-                                                              /* Send HCI Data */
-HCI_API extern void btsnd_hcic_data (BT_HDR *p_buf, UINT16 len, UINT16 handle, UINT8 boundary, UINT8 broadcast);
+extern BOOLEAN btsnd_hcic_get_link_quality (UINT16 handle);            /* Get Link Quality */
+extern BOOLEAN btsnd_hcic_read_rssi (UINT16 handle);                   /* Read RSSI */
+extern BOOLEAN btsnd_hcic_enable_test_mode (void);                     /* Enable Device Under Test Mode */
+extern BOOLEAN btsnd_hcic_write_pagescan_type(UINT8 type);             /* Write Page Scan Type */
+extern BOOLEAN btsnd_hcic_write_inqscan_type(UINT8 type);              /* Write Inquiry Scan Type */
+extern BOOLEAN btsnd_hcic_write_inquiry_mode(UINT8 type);              /* Write Inquiry Mode */
 
 #define HCI_DATA_HANDLE_MASK 0x0FFF
 
@@ -919,304 +627,12 @@
                                          (*((UINT8 *)((p) + 1) + p->offset + 3) << 8)))
 
 #define HCID_HEADER_SIZE      4
-                                                                /*  Send HCI Data */
 
 #define HCID_GET_SCO_LEN(p)  (*((UINT8 *)((p) + 1) + p->offset + 2))
 
-HCI_API extern void btsnd_hcic_vendor_spec_cmd (
-                                                void *buffer, UINT16 opcode,
-                                                UINT8 len, UINT8 *p_data,
-                                                void *p_cmd_cplt_cback);
-
-
-/*********************************************************************************
-**                                                                              **
-**                          H C I    E V E N T S                                **
-**                                                                              **
-*********************************************************************************/
-
-/* Inquiry Complete Event */
-HCI_API extern void btsnd_hcie_inq_comp(void *buffer, UINT8 status);
-
-#define HCIE_PARAM_SIZE_INQ_COMP  1
-
-/* Inquiry Response Event */
-HCI_API extern void btsnd_hcie_inq_res(void *buffer, UINT8 num_resp, UINT8 **bd_addr,
-                                      UINT8 *page_scan_rep_mode, UINT8 *page_scan_per_mode,
-                                      UINT8 *page_scan_mode, UINT8 **dev_class,
-                                      UINT16 *clock_offset);
-
-/* Connection Complete Event */
-HCI_API extern void btsnd_hcie_connection_comp(void *buffer, UINT8 status, UINT16 handle,
-                                    BD_ADDR bd_addr, UINT8 link_type, UINT8 encr_mode);
-
-#define HCIE_PARAM_SIZE_CONNECTION_COMP    11
-
-
-#define HCI_LINK_TYPE_SCO               0x00
-#define HCI_LINK_TYPE_ACL               0x01
-
-#define HCI_ENCRYPT_MODE_DISABLED       0x00
-#define HCI_ENCRYPT_MODE_POINT_TO_POINT 0x01
-#define HCI_ENCRYPT_MODE_ALL            0x02
-
-
-/* Connection Request Event */
-HCI_API extern void btsnd_hcie_connection_req(void *buffer, BD_ADDR bd_addr, DEV_CLASS dev_class, UINT8 link_type);
-
-#define HCIE_PARAM_SIZE_CONNECTION_REQ  10
-
-#define HCI_LINK_TYPE_SCO               0x00
-#define HCI_LINK_TYPE_ACL               0x01
-
-
-/* Disonnection Complete Event */
-HCI_API extern void btsnd_hcie_disc_comp(void *buffer, UINT8 status, UINT16 handle, UINT8 reason);
-
-#define HCIE_PARAM_SIZE_DISC_COMP  4
-
-
-/* Authentication Complete Event */
-HCI_API extern void btsnd_hcie_auth_comp (void *buffer, UINT8 status, UINT16 handle);
-
-#define HCIE_PARAM_SIZE_AUTH_COMP  3
-
-
-/* Remote Name Request Complete Event */
-HCI_API extern void btsnd_hcie_rmt_name_req_comp(void *buffer, UINT8 status, BD_ADDR bd_addr, BD_NAME name);
-
-#define HCIE_PARAM_SIZE_RMT_NAME_REQ_COMP  (1 + BD_ADDR_LEN + BD_NAME_LEN)
-
-
-/* Encryption Change Event */
-HCI_API extern void btsnd_hcie_encryption_change (void *buffer, UINT8 status, UINT16 handle, BOOLEAN enable);
-
-#define HCIE_PARAM_SIZE_ENCR_CHANGE  4
-
-
-/* Connection Link Key Change Event */
-HCI_API extern void btsnd_hcie_conn_link_key_change (void *buffer, UINT8 status, UINT16 handle);
-
-#define HCIE_PARAM_SIZE_LINK_KEY_CHANGE  3
-
-
-/* Encryption Key Refresh Complete Event */
-HCI_API extern void btsnd_hcie_encrypt_key_refresh (void *buffer, UINT8 status, UINT16 handle);
-
-#define HCIE_PARAM_SIZE_ENCRYPT_KEY_REFRESH  3
-
-
-/* Master Link Key Complete Event */
-HCI_API extern void btsnd_hcie_master_link_key (void *buffer, UINT8 status, UINT16 handle, UINT8 flag);
-
-#define HCIE_PARAM_SIZE_MASTER_LINK_KEY  4
-
-
-/* Read Remote Supported Features Complete Event */
-HCI_API extern void btsnd_hcie_read_rmt_features (void *buffer, UINT8 status, UINT16 handle, UINT8 *features);
-
-#define LMP_FEATURES_SIZE   8
-#define HCIE_PARAM_SIZE_READ_RMT_FEATURES  11
-
-
-/* Read Remote Extended Features Complete Event */
-HCI_API extern void btsnd_hcie_read_rmt_ext_features (void *buffer, UINT8 status, UINT16 handle, UINT8 page_num,
-													  UINT8 max_page_num, UINT8 *features);
-
-#define EXT_LMP_FEATURES_SIZE   8
-#define HCIE_PARAM_SIZE_READ_RMT_EXT_FEATURES  13
-
-
-/* Read Remote Version Complete Event */
-HCI_API extern void btsnd_hcie_read_rmt_version (void *buffer, UINT8 status, UINT16 handle, UINT8 version,
-                                  UINT16 comp_name, UINT16 sub_version);
-
-#define HCIE_PARAM_SIZE_READ_RMT_VERSION  8
-
-
-/* QOS setup complete */
-HCI_API extern void btsnd_hcie_qos_setup_compl (void *buffer, UINT8 status, UINT16 handle, UINT8 flags,
-                                 UINT8 service_type, UINT32 token_rate, UINT32 peak,
-                                 UINT32 latency, UINT32 delay_var);
-
-#define HCIE_PARAM_SIZE_QOS_SETUP_COMP 21
-
-
-/* Flow Specification complete */
-HCI_API extern void btsnd_hcie_flow_spec_compl (void *buffer, UINT8 status, UINT16 handle, UINT8 flags,
-                                 UINT8 flow_direction, UINT8 service_type, UINT32 token_rate, UINT32 token_bucket_size,
-                                 UINT32 peak, UINT32 latency);
-
-#define HCIE_PARAM_SIZE_FLOW_SPEC_COMP 22
-
-
-/*  Command Complete Event */
-HCI_API extern void btsnd_hcie_cmd_comp(void *buffer, UINT8 max_host_cmds, UINT16 opcode, UINT8 status);
-
-#define HCIE_PARAM_SIZE_CMD_COMP  4
-
-
-/*  Command Complete with pre-filled in parameters */
-HCI_API extern void btsnd_hcie_cmd_comp_params (void *buffer, UINT8 max_host_cmds, UINT16 cmd_opcode, UINT8 status);
-
-#define HCI_CMD_COMPL_PARAM_OFFSET 4
-
-
-/*  Command Complete Event with 1-byte param */
-HCI_API extern void btsnd_hcie_cmd_comp_param1(void *buffer, UINT8 max_host_cmds, UINT16 opcode,
-                                UINT8 status, UINT8 param1);
-
-#define HCIE_PARAM_SIZE_CMD_COMP_PARAM1  5
-
-/*  Command Complete Event with 2-byte param */
-HCI_API extern void btsnd_hcie_cmd_comp_param2(void *buffer, UINT8 max_host_cmds, UINT16 opcode,
-                                UINT8 status, UINT16 param2);
-
-#define HCIE_PARAM_SIZE_CMD_COMP_PARAM2  6
-
-
-/*  Command Complete Event with BD-addr as param */
-HCI_API extern void btsnd_hcie_cmd_comp_bd_addr(void *buffer, UINT8 max_host_cmds, UINT16 opcode,
-                                 UINT8 status, BD_ADDR bd_addr);
-
-#define HCIE_PARAM_SIZE_CMD_COMP_BD_ADDR  10
-
-
-/*  Command Pending Event */
-HCI_API extern void btsnd_hcie_cmd_status (void *buffer, UINT8 status, UINT8 max_host_cmds, UINT16 opcode);
-
-#define HCIE_PARAM_SIZE_CMD_STATUS  4
-
-
-/*  HW failure Event */
-HCI_API extern void btsnd_hcie_hw_failure (void *buffer, UINT8 code);
-
-#define HCIE_PARAM_SIZE_HW_FAILURE 1
-
-
-/*  Flush Occured Event */
-HCI_API extern void btsnd_hcie_flush_occured (void *buffer, UINT16 handle);
-
-#define HCIE_PARAM_SIZE_FLUSH_OCCURED  2
-
-
-/*  Role Changed Event */
-HCI_API extern void btsnd_hcie_role_change (void *buffer, UINT8 status, BD_ADDR bd_addr, UINT8 role);
-
-#define HCIE_PARAM_SIZE_ROLE_CHANGE  8
-
-
-/* Ready for Data Packets Event */
-HCI_API extern void btsnd_hcie_num_compl_pkts (void *buffer, UINT8 num_handles, UINT16 *p_handle, UINT16 *num_pkts);
-
-#define MAX_DATA_HANDLES        10
-
-
-/* Mode Change Event */
-HCI_API extern void btsnd_hcie_mode_change (void *buffer, UINT8 status, UINT16 handle,
-                             UINT8 mode, UINT16 interval);
-
-#define HCIE_PARAM_SIZE_MODE_CHANGE  6
-#define MAX_DATA_HANDLES        10
-
-
-
-/* Return Link Keys Event */
-HCI_API extern void btsnd_hcie_return_link_keys (void *buffer, UINT8 num_keys, BD_ADDR *bd_addr, LINK_KEY *link_key);
-
-/* This should not be more than 0x0b */
-#define MAX_LINK_KEYS 10
-
-
-
-/* PIN Code Request Event */
-HCI_API extern void btsnd_hcie_pin_code_req (void *buffer, BD_ADDR bd_addr);
-
-#define HCIE_PARAM_SIZE_PIN_CODE_REQ  6
-
-
-
-/* Link Key Request Event */
-HCI_API extern void btsnd_hcie_link_key_req (void *buffer, BD_ADDR bd_addr);
-
-#define HCIE_PARAM_SIZE_LINK_KEY_REQ  6
-
-
-
-/* Link Key Notification Event */
-HCI_API extern void btsnd_hcie_link_key_notify (void *buffer, BD_ADDR bd_addr, LINK_KEY link_key, UINT8 key_type);
-
-#define HCIE_PARAM_SIZE_LINK_KEY_NOTIFY  23
-
-
-
-/* Loopback Command Event */
-HCI_API extern void btsnd_hcie_loopback_command (void *buffer, UINT8 data_len, UINT8 *data);
-
-#define HCIE_PARAM_SIZE_LOOPBACK_COMMAND  sizeof(btmsg_hcie_loopback_cmd_t)
-
-
-
-/* Data Buffer Overflow Event */
-HCI_API extern void btsnd_hcie_data_buf_overflow (void *buffer, UINT8 link_type);
-
-#define HCIE_PARAM_SIZE_DATA_BUF_OVERFLOW  1
-
-
-
-/* Max Slots Change Event */
-HCI_API extern void btsnd_hcie_max_slots_change(void *buffer, UINT16 handle, UINT8 max_slots);
-
-#define HCIE_PARAM_SIZE_MAX_SLOTS_CHANGE  3
-
-
-/* Read Clock Offset Complet Event */
-HCI_API extern void btsnd_hcie_read_clock_off_comp(void *buffer, UINT8 status, UINT16 handle,
-                                    UINT16 clock_offset);
-
-#define HCIE_PARAM_SIZE_READ_CLOCK_OFF_COMP  5
-
-
-
-/* Connection Packet Type Change Event */
-HCI_API extern void btsnd_hcie_pkt_type_change (void *buffer, UINT8 status, UINT16 handle, UINT16 pkt_type);
-
-#define HCIE_PARAM_SIZE_PKT_TYPE_CHANGE  5
-
-
-
-/* QOS violation Event */
-HCI_API extern void btsnd_hcie_qos_violation (void *buffer, UINT16 handle);
-
-#define HCIE_PARAM_SIZE_QOS_VIOLATION  2
-
-
-
-/* Page Scan Mode Change Event */
-HCI_API extern void btsnd_hcie_pagescan_mode_chng (void *buffer, BD_ADDR bd_addr, UINT8 mode);
-
-#define HCIE_PARAM_SIZE_PAGE_SCAN_MODE_CHNG  7
-
-
-/* Page Scan Repetition Mode Change Event */
-HCI_API extern void btsnd_hcie_pagescan_rep_mode_chng (void *buffer, BD_ADDR bd_addr, UINT8 mode);
-
-#define HCIE_PARAM_SIZE_PAGE_SCAN_REP_MODE_CHNG  7
-
-
-/* Sniff Sub Rate Event */
-HCI_API extern void btsnd_hcie_sniff_sub_rate(void *buffer, UINT8 status, UINT16 handle, UINT16 max_tx_lat, UINT16 max_rx_lat,
-                                        UINT16 min_remote_timeout, UINT16 min_local_timeout);
-
-#define HCIE_PARAM_SIZE_SNIFF_SUB_RATE  11
-
-
-
-/* Extended Inquiry Result Event */
-HCI_API extern void btsnd_hcie_ext_inquiry_result(void *buffer, UINT8 num_resp, UINT8 **bd_addr,
-                                      UINT8 *page_scan_rep_mode, UINT8 *reserved,
-                                      UINT8 **dev_class, UINT16 *clock_offset, UINT8 *rssi, UINT8 *p_data);
-
+extern void btsnd_hcic_vendor_spec_cmd (void *buffer, UINT16 opcode,
+                                        UINT8 len, UINT8 *p_data,
+                                        void *p_cmd_cplt_cback);
 
 #if (BLE_INCLUDED == TRUE)
 /********************************************************************************
@@ -1252,102 +668,97 @@
 #define HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA      31
 
 /* ULP HCI command */
-HCI_API extern BOOLEAN btsnd_hcic_ble_set_evt_mask (BT_EVENT_MASK event_mask);
+extern BOOLEAN btsnd_hcic_ble_set_evt_mask (BT_EVENT_MASK event_mask);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_read_buffer_size (void);
+extern BOOLEAN btsnd_hcic_ble_read_buffer_size (void);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_read_local_spt_feat (void);
+extern BOOLEAN btsnd_hcic_ble_read_local_spt_feat (void);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_set_local_used_feat (UINT8 feat_set[8]);
+extern BOOLEAN btsnd_hcic_ble_set_local_used_feat (UINT8 feat_set[8]);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_set_random_addr (BD_ADDR random_addr);
+extern BOOLEAN btsnd_hcic_ble_set_random_addr (BD_ADDR random_addr);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_write_adv_params (UINT16 adv_int_min, UINT16 adv_int_max,
-                                       UINT8 adv_type, UINT8 addr_type_own,
-                                       UINT8 addr_type_dir, BD_ADDR direct_bda,
-                                       UINT8 channel_map, UINT8 scan_filter_policy);
+extern BOOLEAN btsnd_hcic_ble_write_adv_params (UINT16 adv_int_min, UINT16 adv_int_max,
+                                                UINT8 adv_type, UINT8 addr_type_own,
+                                                UINT8 addr_type_dir, BD_ADDR direct_bda,
+                                                UINT8 channel_map, UINT8 scan_filter_policy);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_read_adv_chnl_tx_power (void);
+extern BOOLEAN btsnd_hcic_ble_read_adv_chnl_tx_power (void);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_set_adv_data (UINT8 data_len, UINT8 *p_data);
+extern BOOLEAN btsnd_hcic_ble_set_adv_data (UINT8 data_len, UINT8 *p_data);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_set_scan_rsp_data (UINT8 data_len, UINT8 *p_scan_rsp);
+extern BOOLEAN btsnd_hcic_ble_set_scan_rsp_data (UINT8 data_len, UINT8 *p_scan_rsp);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_set_adv_enable (UINT8 adv_enable);
+extern BOOLEAN btsnd_hcic_ble_set_adv_enable (UINT8 adv_enable);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_set_scan_params (UINT8 scan_type,
-                                          UINT16 scan_int, UINT16 scan_win,
-                                          UINT8 addr_type, UINT8 scan_filter_policy);
+extern BOOLEAN btsnd_hcic_ble_set_scan_params (UINT8 scan_type,
+                                               UINT16 scan_int, UINT16 scan_win,
+                                               UINT8 addr_type, UINT8 scan_filter_policy);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_set_scan_enable (UINT8 scan_enable, UINT8 duplicate);
+extern BOOLEAN btsnd_hcic_ble_set_scan_enable (UINT8 scan_enable, UINT8 duplicate);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_create_ll_conn (UINT16 scan_int, UINT16 scan_win,
-                                       UINT8 init_filter_policy, UINT8 addr_type_peer, BD_ADDR bda_peer, UINT8 addr_type_own,
-                                       UINT16 conn_int_min, UINT16 conn_int_max, UINT16 conn_latency, UINT16 conn_timeout,
-                                       UINT16 min_ce_len, UINT16 max_ce_len);
+extern BOOLEAN btsnd_hcic_ble_create_ll_conn (UINT16 scan_int, UINT16 scan_win,
+                                              UINT8 init_filter_policy, UINT8 addr_type_peer, BD_ADDR bda_peer, UINT8 addr_type_own,
+                                              UINT16 conn_int_min, UINT16 conn_int_max, UINT16 conn_latency, UINT16 conn_timeout,
+                                              UINT16 min_ce_len, UINT16 max_ce_len);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_create_conn_cancel (void);
+extern BOOLEAN btsnd_hcic_ble_create_conn_cancel (void);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_read_white_list_size (void);
+extern BOOLEAN btsnd_hcic_ble_read_white_list_size (void);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_clear_white_list (void);
+extern BOOLEAN btsnd_hcic_ble_clear_white_list (void);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_add_white_list (UINT8 addr_type, BD_ADDR bda);
+extern BOOLEAN btsnd_hcic_ble_add_white_list (UINT8 addr_type, BD_ADDR bda);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_remove_from_white_list (UINT8 addr_type, BD_ADDR bda);
+extern BOOLEAN btsnd_hcic_ble_remove_from_white_list (UINT8 addr_type, BD_ADDR bda);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_upd_ll_conn_params (UINT16 handle, UINT16 conn_int_min, UINT16 conn_int_max,
-                                           UINT16 conn_latency, UINT16 conn_timeout, UINT16 min_len, UINT16 max_len);
+extern BOOLEAN btsnd_hcic_ble_upd_ll_conn_params (UINT16 handle, UINT16 conn_int_min, UINT16 conn_int_max,
+                                                  UINT16 conn_latency, UINT16 conn_timeout, UINT16 min_len, UINT16 max_len);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_set_host_chnl_class (UINT8 chnl_map[HCIC_BLE_CHNL_MAP_SIZE]);
+extern BOOLEAN btsnd_hcic_ble_set_host_chnl_class (UINT8 chnl_map[HCIC_BLE_CHNL_MAP_SIZE]);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_read_chnl_map (UINT16 handle);
+extern BOOLEAN btsnd_hcic_ble_read_chnl_map (UINT16 handle);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_read_remote_feat ( UINT16 handle);
+extern BOOLEAN btsnd_hcic_ble_read_remote_feat ( UINT16 handle);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_encrypt (UINT8* key, UINT8 key_len, UINT8* plain_text, UINT8 pt_len, void *p_cmd_cplt_cback);
+extern BOOLEAN btsnd_hcic_ble_encrypt (UINT8* key, UINT8 key_len, UINT8* plain_text, UINT8 pt_len, void *p_cmd_cplt_cback);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_rand (void *p_cmd_cplt_cback);
+extern BOOLEAN btsnd_hcic_ble_rand (void *p_cmd_cplt_cback);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_start_enc ( UINT16 handle,
-                                                 UINT8 rand[HCIC_BLE_RAND_DI_SIZE],
-                                                UINT16 ediv, UINT8 ltk[HCIC_BLE_ENCRYT_KEY_SIZE]);
+extern BOOLEAN btsnd_hcic_ble_start_enc ( UINT16 handle,
+                                          UINT8 rand[HCIC_BLE_RAND_DI_SIZE],
+                                          UINT16 ediv, UINT8 ltk[HCIC_BLE_ENCRYT_KEY_SIZE]);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_ltk_req_reply (UINT16 handle, UINT8 ltk[HCIC_BLE_ENCRYT_KEY_SIZE]);
+extern BOOLEAN btsnd_hcic_ble_ltk_req_reply (UINT16 handle, UINT8 ltk[HCIC_BLE_ENCRYT_KEY_SIZE]);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_ltk_req_neg_reply (UINT16 handle);
+extern BOOLEAN btsnd_hcic_ble_ltk_req_neg_reply (UINT16 handle);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_read_supported_states (void);
+extern BOOLEAN btsnd_hcic_ble_read_supported_states (void);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_write_host_supported (UINT8 le_host_spt, UINT8 simul_le_host_spt);
+extern BOOLEAN btsnd_hcic_ble_write_host_supported (UINT8 le_host_spt, UINT8 simul_le_host_spt);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_read_host_supported (void);
+extern BOOLEAN btsnd_hcic_ble_read_host_supported (void);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_receiver_test(UINT8 rx_freq);
+extern BOOLEAN btsnd_hcic_ble_receiver_test(UINT8 rx_freq);
 
-HCI_API extern BOOLEAN btsnd_hcic_ble_transmitter_test(UINT8 tx_freq, UINT8 test_data_len,
-                                                           UINT8 payload);
-HCI_API extern BOOLEAN btsnd_hcic_ble_test_end(void);
+extern BOOLEAN btsnd_hcic_ble_transmitter_test(UINT8 tx_freq, UINT8 test_data_len,
+                                               UINT8 payload);
+extern BOOLEAN btsnd_hcic_ble_test_end(void);
 
 #if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE)
 
 #define HCIC_PARAM_SIZE_BLE_RC_PARAM_REQ_REPLY           14
-HCI_API extern BOOLEAN btsnd_hcic_ble_rc_param_req_reply(UINT16 handle,
-                                                        UINT16 conn_int_min, UINT16 conn_int_max,
-                                                        UINT16 conn_latency, UINT16 conn_timeout,
-                                                        UINT16 min_ce_len, UINT16 max_ce_len);
+extern BOOLEAN btsnd_hcic_ble_rc_param_req_reply(UINT16 handle,
+                                                 UINT16 conn_int_min, UINT16 conn_int_max,
+                                                 UINT16 conn_latency, UINT16 conn_timeout,
+                                                 UINT16 min_ce_len, UINT16 max_ce_len);
 
 #define HCIC_PARAM_SIZE_BLE_RC_PARAM_REQ_NEG_REPLY       3
-HCI_API extern BOOLEAN btsnd_hcic_ble_rc_param_req_neg_reply(UINT16 handle, UINT8 reason);
+extern BOOLEAN btsnd_hcic_ble_rc_param_req_neg_reply(UINT16 handle, UINT8 reason);
 
 #endif /* BLE_LLT_INCLUDED */
 
 
 #endif /* BLE_INCLUDED */
 
-#ifdef __cplusplus
-}
 #endif
-
-#endif
-
diff --git a/stack/include/hidh_api.h b/stack/include/hidh_api.h
index 27e8ac5..00b8fde 100644
--- a/stack/include/hidh_api.h
+++ b/stack/include/hidh_api.h
@@ -100,10 +100,10 @@
 ** Returns          tHID_STATUS
 **
 *******************************************************************************/
-HID_API extern tHID_STATUS HID_HostGetSDPRecord (BD_ADDR addr,
-                                                 tSDP_DISCOVERY_DB *p_db,
-                                                 UINT32 db_len,
-                                                 tHID_HOST_SDP_CALLBACK *sdp_cback );
+extern tHID_STATUS HID_HostGetSDPRecord (BD_ADDR addr,
+                                         tSDP_DISCOVERY_DB *p_db,
+                                         UINT32 db_len,
+                                         tHID_HOST_SDP_CALLBACK *sdp_cback );
 
 /*******************************************************************************
 **
@@ -114,7 +114,7 @@
 ** Returns          tHID_STATUS
 **
 *******************************************************************************/
-HID_API extern tHID_STATUS HID_HostRegister (tHID_HOST_DEV_CALLBACK *dev_cback);
+extern tHID_STATUS HID_HostRegister (tHID_HOST_DEV_CALLBACK *dev_cback);
 
 /*******************************************************************************
 **
@@ -125,7 +125,7 @@
 ** Returns          tHID_STATUS
 **
 *******************************************************************************/
-HID_API extern tHID_STATUS HID_HostDeregister(void);
+extern tHID_STATUS HID_HostDeregister(void);
 
 /*******************************************************************************
 **
@@ -136,8 +136,8 @@
 ** Returns          tHID_STATUS
 **
 *******************************************************************************/
-HID_API extern tHID_STATUS HID_HostAddDev (BD_ADDR addr, UINT16 attr_mask,
-                                           UINT8 *handle );
+extern tHID_STATUS HID_HostAddDev (BD_ADDR addr, UINT16 attr_mask,
+                                   UINT8 *handle );
 
 /*******************************************************************************
 **
@@ -148,7 +148,7 @@
 ** Returns          tHID_STATUS
 **
 *******************************************************************************/
-HID_API extern tHID_STATUS HID_HostRemoveDev (UINT8 dev_handle );
+extern tHID_STATUS HID_HostRemoveDev (UINT8 dev_handle );
 
 /*******************************************************************************
 **
@@ -160,7 +160,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-HID_API extern tHID_STATUS HID_HostOpenDev (UINT8 dev_handle );
+extern tHID_STATUS HID_HostOpenDev (UINT8 dev_handle );
 
 /*******************************************************************************
 **
@@ -171,9 +171,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-HID_API extern tHID_STATUS HID_HostWriteDev(UINT8 dev_handle, UINT8 t_type,
-                                            UINT8 param, UINT16 data,
-                                            UINT8 report_id, BT_HDR *pbuf);
+extern tHID_STATUS HID_HostWriteDev(UINT8 dev_handle, UINT8 t_type,
+                                    UINT8 param, UINT16 data,
+                                    UINT8 report_id, BT_HDR *pbuf);
 
 /*******************************************************************************
 **
@@ -184,7 +184,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-HID_API extern tHID_STATUS HID_HostCloseDev(UINT8 dev_handle );
+extern tHID_STATUS HID_HostCloseDev(UINT8 dev_handle );
 
 /*******************************************************************************
 ** Function         HID_HostInit
@@ -193,7 +193,7 @@
 **
 ** Returns          void
 *******************************************************************************/
-HID_API extern void HID_HostInit(void);
+extern void HID_HostInit(void);
 
 /*******************************************************************************
 ** Function        HID_HostSetSecurityLevel
@@ -203,7 +203,7 @@
 **
 ** Returns         tHID_STATUS
 *******************************************************************************/
-HID_API extern tHID_STATUS HID_HostSetSecurityLevel( char serv_name[], UINT8 sec_lvl );
+extern tHID_STATUS HID_HostSetSecurityLevel( char serv_name[], UINT8 sec_lvl );
 
 /*******************************************************************************
 **
@@ -227,7 +227,7 @@
 ** Returns          the new (current) trace level
 **
 *******************************************************************************/
-HID_API extern UINT8 HID_HostSetTraceLevel (UINT8 new_level);
+extern UINT8 HID_HostSetTraceLevel (UINT8 new_level);
 
 #ifdef __cplusplus
 }
diff --git a/stack/include/l2c_api.h b/stack/include/l2c_api.h
index c85d76b..0101614 100644
--- a/stack/include/l2c_api.h
+++ b/stack/include/l2c_api.h
@@ -24,6 +24,8 @@
 #ifndef L2C_API_H
 #define L2C_API_H
 
+#include <stdbool.h>
+
 #include "bt_target.h"
 #include "l2cdefs.h"
 #include "hcidefs.h"
@@ -347,7 +349,7 @@
 **                  BTM_SetSecurityLevel().
 **
 *******************************************************************************/
-L2C_API extern UINT16 L2CA_Register (UINT16 psm, tL2CAP_APPL_INFO *p_cb_info);
+extern UINT16 L2CA_Register (UINT16 psm, tL2CAP_APPL_INFO *p_cb_info);
 
 /*******************************************************************************
 **
@@ -359,7 +361,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-L2C_API extern void L2CA_Deregister (UINT16 psm);
+extern void L2CA_Deregister (UINT16 psm);
 
 /*******************************************************************************
 **
@@ -371,7 +373,7 @@
 ** Returns          PSM to use.
 **
 *******************************************************************************/
-L2C_API extern UINT16 L2CA_AllocatePSM(void);
+extern UINT16 L2CA_AllocatePSM(void);
 
 /*******************************************************************************
 **
@@ -385,7 +387,7 @@
 ** Returns          the CID of the connection, or 0 if it failed to start
 **
 *******************************************************************************/
-L2C_API extern UINT16 L2CA_ConnectReq (UINT16 psm, BD_ADDR p_bd_addr);
+extern UINT16 L2CA_ConnectReq (UINT16 psm, BD_ADDR p_bd_addr);
 
 /*******************************************************************************
 **
@@ -398,7 +400,7 @@
 ** Returns          TRUE for success, FALSE for failure
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_ConnectRsp (BD_ADDR p_bd_addr, UINT8 id, UINT16 lcid,
+extern BOOLEAN L2CA_ConnectRsp (BD_ADDR p_bd_addr, UINT8 id, UINT16 lcid,
                                         UINT16 result, UINT16 status);
 
 /*******************************************************************************
@@ -414,9 +416,16 @@
 ** Returns          the CID of the connection, or 0 if it failed to start
 **
 *******************************************************************************/
-L2C_API extern UINT16 L2CA_ErtmConnectReq (UINT16 psm, BD_ADDR p_bd_addr,
+extern UINT16 L2CA_ErtmConnectReq (UINT16 psm, BD_ADDR p_bd_addr,
                                            tL2CAP_ERTM_INFO *p_ertm_info);
 
+// This function sets the callback routines for the L2CAP connection referred to by
+// |local_cid|. The callback routines can only be modified for outgoing connections
+// established by |L2CA_ConnectReq| or accepted incoming connections. |callbacks|
+// must not be NULL. This function returns true if the callbacks could be updated,
+// false if not (e.g. |local_cid| was not found).
+bool L2CA_SetConnectionCallbacks(uint16_t local_cid, const tL2CAP_APPL_INFO *callbacks);
+
 /*******************************************************************************
 **
 ** Function         L2CA_ErtmConnectRsp
@@ -429,7 +438,7 @@
 ** Returns          TRUE for success, FALSE for failure
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN  L2CA_ErtmConnectRsp (BD_ADDR p_bd_addr, UINT8 id, UINT16 lcid,
+extern BOOLEAN  L2CA_ErtmConnectRsp (BD_ADDR p_bd_addr, UINT8 id, UINT16 lcid,
                                              UINT16 result, UINT16 status,
                                              tL2CAP_ERTM_INFO *p_ertm_info);
 
@@ -442,7 +451,7 @@
 ** Returns          TRUE if configuration sent, else FALSE
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_ConfigReq (UINT16 cid, tL2CAP_CFG_INFO *p_cfg);
+extern BOOLEAN L2CA_ConfigReq (UINT16 cid, tL2CAP_CFG_INFO *p_cfg);
 
 /*******************************************************************************
 **
@@ -454,7 +463,7 @@
 ** Returns          TRUE if configuration response sent, else FALSE
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_ConfigRsp (UINT16 cid, tL2CAP_CFG_INFO *p_cfg);
+extern BOOLEAN L2CA_ConfigRsp (UINT16 cid, tL2CAP_CFG_INFO *p_cfg);
 
 /*******************************************************************************
 **
@@ -465,7 +474,7 @@
 ** Returns          TRUE if disconnect sent, else FALSE
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_DisconnectReq (UINT16 cid);
+extern BOOLEAN L2CA_DisconnectReq (UINT16 cid);
 
 /*******************************************************************************
 **
@@ -477,7 +486,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_DisconnectRsp (UINT16 cid);
+extern BOOLEAN L2CA_DisconnectRsp (UINT16 cid);
 
 /*******************************************************************************
 **
@@ -490,7 +499,7 @@
 **                  L2CAP_DW_FAILED, if error
 **
 *******************************************************************************/
-L2C_API extern UINT8 L2CA_DataWrite (UINT16 cid, BT_HDR *p_data);
+extern UINT8 L2CA_DataWrite (UINT16 cid, BT_HDR *p_data);
 
 /*******************************************************************************
 **
@@ -501,7 +510,7 @@
 ** Returns          TRUE if echo request sent, else FALSE.
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_Ping (BD_ADDR p_bd_addr, tL2CA_ECHO_RSP_CB *p_cb);
+extern BOOLEAN L2CA_Ping (BD_ADDR p_bd_addr, tL2CA_ECHO_RSP_CB *p_cb);
 
 /*******************************************************************************
 **
@@ -513,7 +522,13 @@
 ** Returns          TRUE if echo request sent, else FALSE.
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN  L2CA_Echo (BD_ADDR p_bd_addr, BT_HDR *p_data, tL2CA_ECHO_DATA_CB *p_callback);
+extern BOOLEAN  L2CA_Echo (BD_ADDR p_bd_addr, BT_HDR *p_data, tL2CA_ECHO_DATA_CB *p_callback);
+
+// Given a local channel identifier, |lcid|, this function returns the bound remote
+// channel identifier, |rcid|, and the ACL link handle, |handle|. If |lcid| is not
+// known or is invalid, this function returns false and does not modify the values
+// pointed at by |rcid| and |handle|. |rcid| and |handle| may be NULL.
+bool L2CA_GetIdentifiers(uint16_t lcid, uint16_t *rcid, uint16_t *handle);
 
 /*******************************************************************************
 **
@@ -530,7 +545,7 @@
 ** Returns          TRUE if command succeeded, FALSE if failed
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_SetIdleTimeout (UINT16 cid, UINT16 timeout,
+extern BOOLEAN L2CA_SetIdleTimeout (UINT16 cid, UINT16 timeout,
                                             BOOLEAN is_global);
 
 /*******************************************************************************
@@ -552,7 +567,7 @@
 ** NOTE             This timeout applies to all logical channels active on the
 **                  ACL link.
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_SetIdleTimeoutByBdAddr(BD_ADDR bd_addr, UINT16 timeout);
+extern BOOLEAN L2CA_SetIdleTimeoutByBdAddr(BD_ADDR bd_addr, UINT16 timeout);
 
 /*******************************************************************************
 **
@@ -564,7 +579,7 @@
 ** Returns          the new (current) trace level
 **
 *******************************************************************************/
-L2C_API extern UINT8 L2CA_SetTraceLevel (UINT8 trace_level);
+extern UINT8 L2CA_SetTraceLevel (UINT8 trace_level);
 
 /*******************************************************************************
 **
@@ -582,7 +597,7 @@
 ** Returns      the new (current) role
 **
 *******************************************************************************/
-L2C_API extern UINT8 L2CA_SetDesireRole (UINT8 new_role);
+extern UINT8 L2CA_SetDesireRole (UINT8 new_role);
 
 /*******************************************************************************
 **
@@ -593,7 +608,7 @@
 ** Returns      CID of 0 if none.
 **
 *******************************************************************************/
-L2C_API extern UINT16 L2CA_LocalLoopbackReq (UINT16 psm, UINT16 handle, BD_ADDR p_bd_addr);
+extern UINT16 L2CA_LocalLoopbackReq (UINT16 psm, UINT16 handle, BD_ADDR p_bd_addr);
 
 /*******************************************************************************
 **
@@ -609,7 +624,7 @@
 ** Returns      Number of buffers left queued for that CID
 **
 *******************************************************************************/
-L2C_API extern UINT16   L2CA_FlushChannel (UINT16 lcid, UINT16 num_to_flush);
+extern UINT16   L2CA_FlushChannel (UINT16 lcid, UINT16 num_to_flush);
 
 
 /*******************************************************************************
@@ -623,7 +638,7 @@
 ** Returns          TRUE if a valid channel, else FALSE
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_SetAclPriority (BD_ADDR bd_addr, UINT8 priority);
+extern BOOLEAN L2CA_SetAclPriority (BD_ADDR bd_addr, UINT8 priority);
 
 /*******************************************************************************
 **
@@ -636,7 +651,7 @@
 ** Returns          TRUE if valid channel, else FALSE
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_FlowControl (UINT16 cid, BOOLEAN data_enabled);
+extern BOOLEAN L2CA_FlowControl (UINT16 cid, BOOLEAN data_enabled);
 
 /*******************************************************************************
 **
@@ -647,7 +662,7 @@
 ** Returns          TRUE if valid Channel, else FALSE
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_SendTestSFrame (UINT16 cid, UINT8 sup_type,
+extern BOOLEAN L2CA_SendTestSFrame (UINT16 cid, UINT8 sup_type,
                                             UINT8 back_track);
 
 /*******************************************************************************
@@ -659,7 +674,7 @@
 ** Returns          TRUE if a valid channel, else FALSE
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_SetTxPriority (UINT16 cid, tL2CAP_CHNL_PRIORITY priority);
+extern BOOLEAN L2CA_SetTxPriority (UINT16 cid, tL2CAP_CHNL_PRIORITY priority);
 
 /*******************************************************************************
 **
@@ -673,7 +688,7 @@
 ** Returns
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_RegForNoCPEvt(tL2CA_NOCP_CB *p_cb, BD_ADDR p_bda);
+extern BOOLEAN L2CA_RegForNoCPEvt(tL2CA_NOCP_CB *p_cb, BD_ADDR p_bda);
 
 /*******************************************************************************
 **
@@ -684,7 +699,7 @@
 ** Returns          TRUE if a valid channel, else FALSE
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_SetChnlDataRate (UINT16 cid, tL2CAP_CHNL_DATA_RATE tx, tL2CAP_CHNL_DATA_RATE rx);
+extern BOOLEAN L2CA_SetChnlDataRate (UINT16 cid, tL2CAP_CHNL_DATA_RATE tx, tL2CAP_CHNL_DATA_RATE rx);
 
 typedef void (tL2CA_RESERVE_CMPL_CBACK) (void);
 
@@ -709,7 +724,7 @@
 ** NOTE             This flush timeout applies to all logical channels active on the
 **                  ACL link.
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_SetFlushTimeout (BD_ADDR bd_addr, UINT16 flush_tout);
+extern BOOLEAN L2CA_SetFlushTimeout (BD_ADDR bd_addr, UINT16 flush_tout);
 
 /*******************************************************************************
 **
@@ -726,7 +741,7 @@
 **                  L2CAP_DW_FAILED, if error
 **
 *******************************************************************************/
-L2C_API extern UINT8 L2CA_DataWriteEx (UINT16 cid, BT_HDR *p_data, UINT16 flags);
+extern UINT8 L2CA_DataWriteEx (UINT16 cid, BT_HDR *p_data, UINT16 flags);
 
 /*******************************************************************************
 **
@@ -738,7 +753,7 @@
 ** Returns          TRUE if CID found, else FALSE
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_SetChnlFlushability (UINT16 cid, BOOLEAN is_flushable);
+extern BOOLEAN L2CA_SetChnlFlushability (UINT16 cid, BOOLEAN is_flushable);
 
 /*******************************************************************************
 **
@@ -752,7 +767,7 @@
 **  Return value:    TRUE if peer is connected
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_GetPeerFeatures (BD_ADDR bd_addr, UINT32 *p_ext_feat, UINT8 *p_chnl_mask);
+extern BOOLEAN L2CA_GetPeerFeatures (BD_ADDR bd_addr, UINT32 *p_ext_feat, UINT8 *p_chnl_mask);
 
 /*******************************************************************************
 **
@@ -766,7 +781,7 @@
 **  Return value:    TRUE if found lcb for the given handle, FALSE otherwise
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_GetBDAddrbyHandle (UINT16 handle, BD_ADDR bd_addr);
+extern BOOLEAN L2CA_GetBDAddrbyHandle (UINT16 handle, BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -779,7 +794,7 @@
 **  Return value:    Channel mode
 **
 *******************************************************************************/
-L2C_API extern UINT8 L2CA_GetChnlFcrMode (UINT16 lcid);
+extern UINT8 L2CA_GetChnlFcrMode (UINT16 lcid);
 
 
 /*******************************************************************************
@@ -832,7 +847,7 @@
 **  Return value:   TRUE if successs
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_UcdRegister ( UINT16 psm, tL2CAP_UCD_CB_INFO *p_cb_info );
+extern BOOLEAN L2CA_UcdRegister ( UINT16 psm, tL2CAP_UCD_CB_INFO *p_cb_info );
 
 /*******************************************************************************
 **
@@ -845,7 +860,7 @@
 **  Return value:   TRUE if successs
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_UcdDeregister ( UINT16 psm );
+extern BOOLEAN L2CA_UcdDeregister ( UINT16 psm );
 
 /*******************************************************************************
 **
@@ -862,7 +877,7 @@
 **  Return value:   TRUE if successs
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_UcdDiscover ( UINT16 psm, BD_ADDR rem_bda, UINT8 info_type );
+extern BOOLEAN L2CA_UcdDiscover ( UINT16 psm, BD_ADDR rem_bda, UINT8 info_type );
 
 /*******************************************************************************
 **
@@ -881,7 +896,7 @@
 **                  L2CAP_DW_FAILED,  if error
 **
 *******************************************************************************/
-L2C_API extern UINT16 L2CA_UcdDataWrite (UINT16 psm, BD_ADDR rem_bda, BT_HDR *p_buf, UINT16 flags);
+extern UINT16 L2CA_UcdDataWrite (UINT16 psm, BD_ADDR rem_bda, BT_HDR *p_buf, UINT16 flags);
 
 /*******************************************************************************
 **
@@ -895,7 +910,7 @@
 **  Return value:   TRUE if successs
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_UcdSetIdleTimeout ( BD_ADDR rem_bda, UINT16 timeout );
+extern BOOLEAN L2CA_UcdSetIdleTimeout ( BD_ADDR rem_bda, UINT16 timeout );
 
 /*******************************************************************************
 **
@@ -906,7 +921,7 @@
 ** Returns          TRUE if a valid channel, else FALSE
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_UCDSetTxPriority ( BD_ADDR rem_bda, tL2CAP_CHNL_PRIORITY priority );
+extern BOOLEAN L2CA_UCDSetTxPriority ( BD_ADDR rem_bda, tL2CAP_CHNL_PRIORITY priority );
 
 
 /*******************************************************************************
@@ -963,7 +978,7 @@
 **  Return value:   TRUE if registered OK
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN  L2CA_RegisterFixedChannel (UINT16 fixed_cid, tL2CAP_FIXED_CHNL_REG *p_freg);
+extern BOOLEAN  L2CA_RegisterFixedChannel (UINT16 fixed_cid, tL2CAP_FIXED_CHNL_REG *p_freg);
 
 /*******************************************************************************
 **
@@ -977,7 +992,7 @@
 **  Return value:   TRUE if connection started
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_ConnectFixedChnl (UINT16 fixed_cid, BD_ADDR bd_addr);
+extern BOOLEAN L2CA_ConnectFixedChnl (UINT16 fixed_cid, BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -993,7 +1008,7 @@
 **                  L2CAP_DW_FAILED,  if error
 **
 *******************************************************************************/
-L2C_API extern UINT16 L2CA_SendFixedChnlData (UINT16 fixed_cid, BD_ADDR rem_bda, BT_HDR *p_buf);
+extern UINT16 L2CA_SendFixedChnlData (UINT16 fixed_cid, BD_ADDR rem_bda, BT_HDR *p_buf);
 
 /*******************************************************************************
 **
@@ -1008,7 +1023,7 @@
 **  Return value:   TRUE if channel removed
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_RemoveFixedChnl (UINT16 fixed_cid, BD_ADDR rem_bda);
+extern BOOLEAN L2CA_RemoveFixedChnl (UINT16 fixed_cid, BD_ADDR rem_bda);
 
 /*******************************************************************************
 **
@@ -1027,7 +1042,7 @@
 ** Returns          TRUE if command succeeded, FALSE if failed
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_SetFixedChannelTout (BD_ADDR rem_bda, UINT16 fixed_cid, UINT16 idle_tout);
+extern BOOLEAN L2CA_SetFixedChannelTout (BD_ADDR rem_bda, UINT16 fixed_cid, UINT16 idle_tout);
 
 #endif /* (L2CAP_NUM_FIXED_CHNLS > 0) */
 
@@ -1044,74 +1059,9 @@
 ** Returns      TRUE if successful
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_GetCurrentConfig (UINT16 lcid,
-                                              tL2CAP_CFG_INFO **pp_our_cfg,  tL2CAP_CH_CFG_BITS *p_our_cfg_bits,
-                                              tL2CAP_CFG_INFO **pp_peer_cfg, tL2CAP_CH_CFG_BITS *p_peer_cfg_bits);
-
-#if (L2CAP_CORRUPT_ERTM_PKTS == TRUE)
-/*******************************************************************************
-**
-** Function         L2CA_SetupErtmTest
-**
-** Description      This function is used for testing purposes only.
-**                  It corrupts or drops one or more packets used with ERTM channels.
-**
-** Parameters
-**                  cid - channel ID  (0 uses RFCOMM PSM's CID)
-**
-**                  type - type of test to run (L2CAP_FCR_TTYPE_CORR_IFRAMES
-**                                              L2CAP_FCR_TTYPE_CORR_SFRAME
-**                                              L2CAP_FCR_TTYPE_STOP_TEST
-**                                              L2CAP_FCR_TTYPE_GET_CID - returns rfcomm cid only)
-**
-**                  is_rx  - TRUE to corrupt Rx packet, FALSE for Tx packet)
-**
-**                  freq - L2CAP_FCR_FREQ_RANDOM    (turns on random corruptions/drops)
-**                         L2CAP_FCR_FREQ_NORMAL    (turns on test with "count" corruptions/drops)
-**
-**                  count - number of packets in a row to drop or corrupt
-**
-** Returns          CID of channel running test
-**
-*******************************************************************************/
-L2C_API extern UINT16 L2CA_SetupErtmTest (UINT16 cid, UINT8 type, BOOLEAN is_rx, UINT8 freq, UINT16 count);
-
-/*******************************************************************************
-**
-** Function         L2CA_SendPolledSFrame
-**
-** Description      This function is used for testing purposes only.
-**                  It Sends a Polled RR or RNR to the peer
-**
-** Parameters
-**                  cid - channel ID
-**
-**                  sup_type - (L2CAP_FCR_SUP_RR or L2CAP_FCR_SUP_RNR)
-**
-** Returns          void
-**
-*******************************************************************************/
-L2C_API extern void L2CA_SendPolledSFrame (UINT16 cid, UINT16 sup_type);
-
-/*******************************************************************************
-**
-** Function         L2CA_BypassSFrame
-**
-** Description      This function is used for testing purposes only.
-**                  It skips sending 'count' S-Frames.
-**
-** Parameters
-**                  cid - channel ID
-**
-**                  count - Number of S-Frames to skip sending
-**
-** Returns          void
-**
-*******************************************************************************/
-L2C_API extern void L2CA_BypassSFrame (UINT16 cid, UINT8 count);
-
-#endif /* (L2CAP_CORRUPT_ERTM_PKTS == TRUE) */
-
+extern BOOLEAN L2CA_GetCurrentConfig (UINT16 lcid,
+                                      tL2CAP_CFG_INFO **pp_our_cfg,  tL2CAP_CH_CFG_BITS *p_our_cfg_bits,
+                                      tL2CAP_CFG_INFO **pp_peer_cfg, tL2CAP_CH_CFG_BITS *p_peer_cfg_bits);
 
 #if (BLE_INCLUDED == TRUE)
 /*******************************************************************************
@@ -1125,7 +1075,7 @@
 **  Return value:   TRUE if connection was cancelled
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_CancelBleConnectReq (BD_ADDR rem_bda);
+extern BOOLEAN L2CA_CancelBleConnectReq (BD_ADDR rem_bda);
 
 /*******************************************************************************
 **
@@ -1138,8 +1088,8 @@
 **  Return value:   TRUE if update started
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_UpdateBleConnParams (BD_ADDR rem_bdRa, UINT16 min_int,
-                                                          UINT16 max_int, UINT16 latency, UINT16 timeout);
+extern BOOLEAN L2CA_UpdateBleConnParams (BD_ADDR rem_bdRa, UINT16 min_int,
+                                         UINT16 max_int, UINT16 latency, UINT16 timeout);
 
 /*******************************************************************************
 **
@@ -1153,7 +1103,7 @@
 **  Return value:   TRUE if update started
 **
 *******************************************************************************/
-L2C_API extern BOOLEAN L2CA_EnableUpdateBleConnParams (BD_ADDR rem_bda, BOOLEAN enable);
+extern BOOLEAN L2CA_EnableUpdateBleConnParams (BD_ADDR rem_bda, BOOLEAN enable);
 
 /*******************************************************************************
 **
@@ -1164,7 +1114,7 @@
 ** Returns          link role.
 **
 *******************************************************************************/
-L2C_API extern UINT8 L2CA_GetBleConnRole (BD_ADDR bd_addr);
+extern UINT8 L2CA_GetBleConnRole (BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -1178,7 +1128,7 @@
 ** Returns          disconnect reason
 **
 *******************************************************************************/
-L2C_API extern UINT16 L2CA_GetDisconnectReason (BD_ADDR remote_bda, tBT_TRANSPORT transport);
+extern UINT16 L2CA_GetDisconnectReason (BD_ADDR remote_bda, tBT_TRANSPORT transport);
 
 #endif /* (BLE_INCLUDED == TRUE) */
 
diff --git a/stack/include/l2cap_client.h b/stack/include/l2cap_client.h
new file mode 100644
index 0000000..b995d5e
--- /dev/null
+++ b/stack/include/l2cap_client.h
@@ -0,0 +1,74 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#pragma once
+
+#include <hardware/bluetooth.h>
+#include <stdbool.h>
+#include <stdint.h>
+
+typedef struct buffer_t buffer_t;
+typedef struct l2cap_client_t l2cap_client_t;
+
+typedef struct {
+  void (*connected)(l2cap_client_t *client, void *context);
+  void (*disconnected)(l2cap_client_t *client, void *context);
+  void (*read_ready)(l2cap_client_t *client, buffer_t *packet, void *context);
+  void (*write_ready)(l2cap_client_t *client, void *context);
+} l2cap_client_callbacks_t;
+
+// Returns a new buffer with enough space for |size| bytes of L2CAP payload.
+// |size| must be greater than zero. This function returns NULL if the buffer
+// could not be allocated. The returned buffer must be freed with |buffer_free|
+// when it is no longer needed.
+buffer_t *l2cap_buffer_new(size_t size);
+
+// Creates and returns a new L2CAP client object. |callbacks| must not be NULL and
+// must specify a set of functions that should be called back when events occur
+// on the L2CAP connection. |context| may be NULL and will be passed as the argument
+// to all callbacks in |l2cap_client_callbacks_t|. The returned object must be freed
+// with |l2cap_client_free|.
+l2cap_client_t *l2cap_client_new(const l2cap_client_callbacks_t *callbacks, void *context);
+
+// Frees the L2CAP client object allocated with |l2cap_client_new|. |client| may be NULL.
+void l2cap_client_free(l2cap_client_t *client);
+
+// Attempts to connect the |client| to a peer device specified by |remote_bdaddr|
+// using the |psm| protocol specifier. This function returns true if the connect
+// operation could be started and will indicate completion with either a 'connected'
+// callback (success) or a 'disconnected' callback (failure).
+//
+// This function must not be called while a connect operation is in progress or
+// while |l2cap_client_is_connected|. |client| and |remote_bdaddr| must not be NULL.
+// |psm| must be greater than zero.
+bool l2cap_client_connect(l2cap_client_t *client, const bt_bdaddr_t *remote_bdaddr, uint16_t psm);
+
+// Disconnects a connected |client|. This function is asynchronous and idempotent. It
+// will indicate completion with a 'disconnected' callback. |client| must not be NULL.
+void l2cap_client_disconnect(l2cap_client_t *client);
+
+// Returns true if |client| is connected and is ready to accept data written to it.
+// |client| must not be NULL.
+bool l2cap_client_is_connected(const l2cap_client_t *client);
+
+// Writes data contained in |packet| to a connected |client|. This function returns
+// true if the packet was successfully queued for delivery, false if the client cannot
+// accept more data at this time. If this function returns false, the caller must wait
+// for the 'write_ready' callback to write additional data to the client. Neither
+// |client| nor |packet| may be NULL.
+bool l2cap_client_write(l2cap_client_t *client, buffer_t *packet);
diff --git a/stack/include/l2cdefs.h b/stack/include/l2cdefs.h
index fe41476..1063749 100644
--- a/stack/include/l2cdefs.h
+++ b/stack/include/l2cdefs.h
@@ -293,17 +293,4 @@
 #define L2CAP_FCR_INIT_CRC            0   /* Initial state of the CRC register */
 #define L2CAP_FCR_SEQ_MODULO          0x3F     /* Mask for sequence numbers (range 0 - 63) */
 
-/*************************************************************************************************
-** The following definitions are only used for internal testing of ERTM at the application level
-*************************************************************************************************/
-/* L2CA_SetupErtmTest() corruption test types */
-#define L2CAP_FCR_TTYPE_CORR_IFRAME     0       /* Corrupt one or more I-frames, based on count   */
-#define L2CAP_FCR_TTYPE_CORR_SFRAME     1       /* Corrupt an S-frame, (acknowledgement) */
-#define L2CAP_FCR_TTYPE_STOP_TEST       2       /* Used when turning off a test */
-#define L2CAP_FCR_TTYPE_GET_CID         3       /* Returns RFCOMM cid when '0' is passed in cid argument */
-
-/* L2CA_SetupErtmTest() Freq */
-#define L2CAP_FCR_FREQ_NORMAL           0       /* A single test is run */
-#define L2CAP_FCR_FREQ_RANDOM           1       /* Randomly loses or corrupts a packet */
-
 #endif
diff --git a/stack/include/mca_api.h b/stack/include/mca_api.h
index d455e5b..57e8f8b 100644
--- a/stack/include/mca_api.h
+++ b/stack/include/mca_api.h
@@ -224,7 +224,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-MCA_API extern void MCA_Init(void);
+extern void MCA_Init(void);
 
 /*******************************************************************************
 **
@@ -247,7 +247,7 @@
 **                  the input parameter is 0xff.
 **
 *******************************************************************************/
-MCA_API extern UINT8 MCA_SetTraceLevel (UINT8 level);
+extern UINT8 MCA_SetTraceLevel (UINT8 level);
 
 /*******************************************************************************
 **
@@ -261,7 +261,7 @@
 ** Returns          0, if failed. Otherwise, the MCA handle.
 **
 *******************************************************************************/
-MCA_API extern tMCA_HANDLE MCA_Register(tMCA_REG *p_reg, tMCA_CTRL_CBACK *p_cback);
+extern tMCA_HANDLE MCA_Register(tMCA_REG *p_reg, tMCA_CTRL_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -274,7 +274,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-MCA_API extern void MCA_Deregister(tMCA_HANDLE handle);
+extern void MCA_Deregister(tMCA_HANDLE handle);
 
 /*******************************************************************************
 **
@@ -288,7 +288,7 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_CreateDep(tMCA_HANDLE handle, tMCA_DEP *p_dep, tMCA_CS *p_cs);
+extern tMCA_RESULT MCA_CreateDep(tMCA_HANDLE handle, tMCA_DEP *p_dep, tMCA_CS *p_cs);
 
 /*******************************************************************************
 **
@@ -303,7 +303,7 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_DeleteDep(tMCA_HANDLE handle, tMCA_DEP dep);
+extern tMCA_RESULT MCA_DeleteDep(tMCA_HANDLE handle, tMCA_DEP dep);
 
 /*******************************************************************************
 **
@@ -321,9 +321,9 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_ConnectReq(tMCA_HANDLE handle, BD_ADDR bd_addr,
-                                          UINT16 ctrl_psm,
-                                          UINT16 sec_mask);
+extern tMCA_RESULT MCA_ConnectReq(tMCA_HANDLE handle, BD_ADDR bd_addr,
+                                  UINT16 ctrl_psm,
+                                  UINT16 sec_mask);
 
 /*******************************************************************************
 **
@@ -338,7 +338,7 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_DisconnectReq(tMCA_CL mcl);
+extern tMCA_RESULT MCA_DisconnectReq(tMCA_CL mcl);
 
 /*******************************************************************************
 **
@@ -355,9 +355,9 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_CreateMdl(tMCA_CL mcl, tMCA_DEP dep, UINT16 data_psm,
-                                         UINT16 mdl_id, UINT8 peer_dep_id,
-                                         UINT8 cfg, const tMCA_CHNL_CFG *p_chnl_cfg);
+extern tMCA_RESULT MCA_CreateMdl(tMCA_CL mcl, tMCA_DEP dep, UINT16 data_psm,
+                                 UINT16 mdl_id, UINT8 peer_dep_id,
+                                 UINT8 cfg, const tMCA_CHNL_CFG *p_chnl_cfg);
 
 /*******************************************************************************
 **
@@ -373,9 +373,9 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_CreateMdlRsp(tMCA_CL mcl, tMCA_DEP dep,
-                                            UINT16 mdl_id, UINT8 cfg, UINT8 rsp_code,
-                                            const tMCA_CHNL_CFG *p_chnl_cfg);
+extern tMCA_RESULT MCA_CreateMdlRsp(tMCA_CL mcl, tMCA_DEP dep,
+                                    UINT16 mdl_id, UINT8 cfg, UINT8 rsp_code,
+                                    const tMCA_CHNL_CFG *p_chnl_cfg);
 
 /*******************************************************************************
 **
@@ -388,7 +388,7 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_CloseReq(tMCA_DL mdl);
+extern tMCA_RESULT MCA_CloseReq(tMCA_DL mdl);
 
 /*******************************************************************************
 **
@@ -403,8 +403,8 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_ReconnectMdl(tMCA_CL mcl, tMCA_DEP dep, UINT16 data_psm,
-                                            UINT16 mdl_id, const tMCA_CHNL_CFG *p_chnl_cfg);
+extern tMCA_RESULT MCA_ReconnectMdl(tMCA_CL mcl, tMCA_DEP dep, UINT16 data_psm,
+                                    UINT16 mdl_id, const tMCA_CHNL_CFG *p_chnl_cfg);
 
 /*******************************************************************************
 **
@@ -419,9 +419,9 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_ReconnectMdlRsp(tMCA_CL mcl, tMCA_DEP dep,
-                                               UINT16 mdl_id, UINT8 rsp_code,
-                                               const tMCA_CHNL_CFG *p_chnl_cfg);
+extern tMCA_RESULT MCA_ReconnectMdlRsp(tMCA_CL mcl, tMCA_DEP dep,
+                                       UINT16 mdl_id, UINT8 rsp_code,
+                                       const tMCA_CHNL_CFG *p_chnl_cfg);
 
 /*******************************************************************************
 **
@@ -435,7 +435,7 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_DataChnlCfg(tMCA_CL mcl, const tMCA_CHNL_CFG *p_chnl_cfg);
+extern tMCA_RESULT MCA_DataChnlCfg(tMCA_CL mcl, const tMCA_CHNL_CFG *p_chnl_cfg);
 
 /*******************************************************************************
 **
@@ -447,7 +447,7 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_Abort(tMCA_CL mcl);
+extern tMCA_RESULT MCA_Abort(tMCA_CL mcl);
 
 /*******************************************************************************
 **
@@ -459,7 +459,7 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_Delete(tMCA_CL mcl, UINT16 mdl_id);
+extern tMCA_RESULT MCA_Delete(tMCA_CL mcl, UINT16 mdl_id);
 
 /*******************************************************************************
 **
@@ -479,7 +479,7 @@
 ** Returns          MCA_SUCCESS if successful, otherwise error.
 **
 *******************************************************************************/
-MCA_API extern tMCA_RESULT MCA_WriteReq(tMCA_DL mdl, BT_HDR *p_pkt);
+extern tMCA_RESULT MCA_WriteReq(tMCA_DL mdl, BT_HDR *p_pkt);
 
 /*******************************************************************************
 **
@@ -490,6 +490,6 @@
 ** Returns          L2CAP channel ID if successful, otherwise 0.
 **
 *******************************************************************************/
-MCA_API extern UINT16 MCA_GetL2CapChannel (tMCA_DL mdl);
+extern UINT16 MCA_GetL2CapChannel (tMCA_DL mdl);
 
 #endif /* MCA_API_H */
diff --git a/stack/include/obx_api.h b/stack/include/obx_api.h
deleted file mode 100644
index 472eeb0..0000000
--- a/stack/include/obx_api.h
+++ /dev/null
@@ -1,1704 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef OBX_API_H
-#define OBX_API_H
-#include "bt_target.h"
-#include "bt_types.h"
-#include "l2c_api.h"
-
-/* 18 is 7/OBX_CONN_HDRS_OFFSET + 5/conn id, 2/ssn, 2/srm 2/srm_param */
-#define OBX_HDR_OFFSET              (18 + L2CAP_MIN_OFFSET)
-#define OBX_MAX_TRIPLET             3
-
-#define OBX_MIN_MTU                 255 /* per IrOBEX spec */
-#define OBX_MAX_MTU                 (OBX_LRG_DATA_POOL_SIZE - BT_HDR_SIZE - OBX_HDR_OFFSET)
-
-#define OBX_CONN_ID_SIZE            4
-#define OBX_PKT_LEN_SIZE            2
-
-#define OBX_CONN_HDRS_OFFSET        7
-#define OBX_SESS_HDRS_OFFSET        3
-#define OBX_DISCON_HDRS_OFFSET      3
-#define OBX_PUT_HDRS_OFFSET         3
-#define OBX_GET_HDRS_OFFSET         3
-#define OBX_SETPATH_REQ_HDRS_OFFSET 5
-#define OBX_ABORT_HDRS_OFFSET       3
-#define OBX_ACTION_HDRS_OFFSET      3
-#define OBX_RESPONSE_HDRS_OFFSET    3
-
-/* this is not needed if OBX_HDR_OFFSET is 18+ */
-#define OBX_MAX_CONN_HDR_EXTRA      8 /* 5/conn id, 2/ssn, 2/srm 2/srm_param - (5/setpath + 5/conn_id - 7/conn) */
-
-/* offset for header functions to access fields */
-#define OBX_CONNECT_MTU_OFFSET      5
-#define OBX_SETPATH_FLAG_OFFSET     3
-
-#define OBX_MAX_NUM_AUTH_TRIPLET    3
-#define OBX_UNICODE_SIZE            2 /* sizeof(UINT16) */
-
-#define OBX_INVALID_HDR_LEN         0xFFFF
-
-#define OBX_MIN_NONCE_SIZE          4   /* fixed size per IrOBEX spec */
-#define OBX_NONCE_SIZE              16  /* fixed size per IrOBEX spec */
-#define OBX_DIGEST_SIZE             16  /* fixed size per IrOBEX spec */
-#define OBX_MAX_AUTH_KEY_SIZE       16
-#define OBX_MAX_AUTH_USER_SIZE      20
-#define OBX_SESSION_ID_SIZE         16  /* fixed size per IrOBEX spec */
-#define OBX_SESSION_INFO_SIZE       32  /* OBX_SESSION_ID_SIZE + 4(local nonce) + 4 (connection id) + 4 (timeout) + 2(mtu) + 1(state) + 1(srm)  */
-#define OBX_SESSION_INFO_NONCE_IDX  16  /* The index to the (local nonce) in session info */
-#define OBX_SESSION_INFO_ID_IDX     20  /* The index to the (connection id) in session info */
-#define OBX_SESSION_INFO_TO_IDX     24  /* The index to the (timeout) in session info */
-#define OBX_SESSION_INFO_MTU_IDX    28  /* The index to peer MTU in session info */
-#define OBX_SESSION_INFO_ST_IDX     30  /* The index to sr/cl state in session info */
-#define OBX_SESSION_INFO_SRM_IDX    31  /* The index to srm in session info */
-#define OBX_TIMEOUT_SIZE            4
-
-/* handle related definitions */
-#define OBX_SESS_SHIFT              8
-#define OBX_ENC_SESS_HANDLE(oh, os) (((os)<<OBX_SESS_SHIFT)|(oh))
-#define OBX_HANDLE_MASK             0xFF
-#define OBX_SESS_MASK               0x7F00
-#define OBX_DEC_HANDLE(os)          ((os) & OBX_HANDLE_MASK)
-#define OBX_DEC_SESS_IND(os)        ((os & OBX_SESS_MASK)>>OBX_SESS_SHIFT)
-
-/* Return values for API functions */
-enum
-{
-    OBX_SUCCESS,        /* Status is successful. */
-    OBX_BAD_PARAMS,     /* Bad parameter(s). */
-    OBX_NO_RESOURCES,   /* No resources (GKI buffers, control block) */
-    OBX_BAD_HANDLE      /* The OBEX handle is not valid. */
-};
-typedef UINT8 tOBX_STATUS;
-
-
-typedef UINT16 tOBX_HANDLE;
-
-#define OBX_HANDLE_NULL             0
-
-enum
-{
-    OBX_PT_PUT,     /* Regular Put request */
-    OBX_PT_DELETE,  /* Delete request - a Put request with NO Body or End-of-Body header. */
-    OBX_PT_CREATE   /* Create-Empty request - a Put request with an empty End-of-Body header. */
-};
-typedef UINT8   tOBX_PUT_TYPE;
-
-/* SetPath Request Flags - the following definitions can be ORed if both flags are wanted */
-#define OBX_SPF_BACKUP      0x01    /* Backup a level before applying name(equivalent to ../) */
-#define OBX_SPF_NO_CREATE   0x02    /* Don't create directory if it does not exist, return an error instead. */
-typedef UINT8   tOBX_SETPATH_FLAG;
-
-/* Authentication Challenge Options */
-#define OBX_AO_NONE         0x00    /* If this is used in OBX_StartServer and the authenticate
-                                     * flag is TRUE, the optional Challenge Information (tag 0x01)
-                                     * will not be sent. */
-#define OBX_AO_USR_ID       0x01    /* Set this bit to make the client respond with the user ID. */
-typedef UINT8 tOBX_AUTH_OPT;
-
-/* CHARSET definition for Authentication Challenge Realm */
-#define OBX_RCS_ASCII       0x00    /* ASCII */
-#define OBX_RCS_8859_1      0x01    /* ISO-8859-1 */
-#define OBX_RCS_8859_2      0x02    /* ISO-8859-2 */
-#define OBX_RCS_8859_3      0x03    /* ISO-8859-3 */
-#define OBX_RCS_8859_4      0x04    /* ISO-8859-4 */
-#define OBX_RCS_8859_5      0x05    /* ISO-8859-5 */
-#define OBX_RCS_8859_6      0x06    /* ISO-8859-6 */
-#define OBX_RCS_8859_7      0x07    /* ISO-8859-7 */
-#define OBX_RCS_8859_8      0x08    /* ISO-8859-8 */
-#define OBX_RCS_8859_9      0x09    /* ISO-8859-9 */
-#define OBX_RCS_UNICODE     0xFF    /* Unicode */
-typedef UINT8 tOBX_CHARSET;
-
-typedef struct
-{
-    UINT8               ssn;        /* session sequence number */
-    BOOLEAN             final;      /* TRUE, if this is the final packet of this PUT transaction. */
-    tOBX_PUT_TYPE       type;       /* The type of PUT request. */
-} tOBX_PUT_EVT;
-
-typedef struct
-{
-    UINT8               ssn;        /* session sequence number */
-    BOOLEAN             final;      /* TRUE, if this is the final packet of this GET transaction. */
-} tOBX_GET_EVT;
-
-typedef struct
-{
-    UINT8               ssn;        /* session sequence number */
-    BD_ADDR             peer_addr;  /* The peer Bluetooth Address. */
-    UINT16              mtu;        /* The peer MTU. This element is associated with OBX_CONNECT_REQ_EVT and OBX_CONNECT_RSP_EVT. */
-    tOBX_HANDLE         handle;     /* the OBX handle returned by OBX_StartServer(), OBX_CreateSession() and OBX_ConnectReq() */
-    BOOLEAN             no_rsp;     /* TRUE, when the event is generated as a part of RESUME SESSION */
-} tOBX_CONN_EVT;
-
-/* Session Opcode Definitions: */
-#define OBX_SESS_OP_CREATE              0x00 /* Create Session */
-#define OBX_SESS_OP_CLOSE               0x01 /* Close Session */
-#define OBX_SESS_OP_SUSPEND             0x02 /* Suspend Session */
-#define OBX_SESS_OP_RESUME              0x03 /* Resume Session */
-#define OBX_SESS_OP_SET_TIME            0x04 /* Set Timeout */
-#define OBX_SESS_OP_TRANSPORT           0xFF /* transport dropped */
-typedef UINT8   tOBX_SESS_OP;
-
-/* Session States Definitions for external use: */
-enum
-{
-    OBX_SESS_NONE,       /* 0x00    session is not engaged/closed */
-    OBX_SESS_ACTIVE,     /* 0x01    session is active. */
-    OBX_SESS_SUSPENDED,  /* 0x02    session is suspended. */
-    OBX_SESS_EXT_MAX
-};
-typedef UINT8 tOBX_SESS_ST;
-
-
-typedef struct
-{
-    UINT8               ssn;            /* session sequence number */
-    tOBX_SESS_OP        sess_op;        /* the session op code */
-    tOBX_SESS_ST        sess_st;        /* the session state */
-    BD_ADDR             peer_addr;      /* The peer Bluetooth Address. */
-    UINT8               *p_sess_info;   /* The session ID and the local nonce for a reliable session, a reference to the location in OBEX control block or NULL */
-    UINT32              timeout;        /* The number of seconds remaining in suspend. 0xffff if infinite. */
-    UINT32              obj_offset;     /* The object offset for resume session. */
-    UINT8               nssn;           /* tne next session sequence number the server expects */
-} tOBX_SESS_EVT;
-
-#define OBX_ACT_COPY        0x00    /* Copy object */
-#define OBX_ACT_MOVE        0x01    /* Move/rename object */
-#define OBX_ACT_PERMISSION  0x02    /* Set object permission */
-typedef UINT8 tOBX_ACTION;
-
-typedef struct
-{
-    UINT8               ssn;        /* session sequence number */
-    tOBX_ACTION         action;     /* The action opcode. */
-} tOBX_ACT_EVT;
-
-typedef struct
-{
-    UINT8               ssn;        /* session sequence number */
-    tOBX_SETPATH_FLAG   flag;       /* The set path flags. */
-} tOBX_SETPATH_EVT;
-
-/* permission flags */
-#define OBX_PERMISSION_READ         0x01
-#define OBX_PERMISSION_WRITE        0x02
-#define OBX_PERMISSION_DELETE       0x04
-#define OBX_PERMISSION_MODIFY       0x80
-
-typedef union
-{
-    UINT8               ssn;        /* session sequence number */
-    tOBX_CONN_EVT       conn;       /* This element is associated with OBX_CONNECT_REQ_EVT and OBX_CONNECT_RSP_EVT. */
-    tOBX_SESS_EVT       sess;       /* This element is associated with OBX_SESSION_RSP_EVT and OBX_SESSION_REQ_EVT. */
-    tOBX_PUT_EVT        put;        /* This element is associated with OBX_PUT_REQ_EVT. */
-    tOBX_SETPATH_EVT    sp;         /* This element is associated with OBX_SETPATH_REQ_EVT. */
-    tOBX_ACT_EVT        action;     /* This element is associated with OBX_ACTION_REQ_EVT */
-    tOBX_GET_EVT        get;        /* This element is associated with OBX_GET_REQ_EVT. TRUE, if this is the final packet that contains the OBEX headers for this GET request. */
-} tOBX_EVT_PARAM;
-
-
-enum
-{
-    OBX_NULL_EVT,
-    /* server events */
-    OBX_CONNECT_REQ_EVT,    /* param = packet MTU */
-    OBX_SESSION_REQ_EVT,    /* A Crease Session or Resume Session request is received by the server. Call OBX_SessionRsp(). */
-    OBX_DISCONNECT_REQ_EVT,
-    OBX_PUT_REQ_EVT,        /* could have param indicate delete or create? */
-    OBX_GET_REQ_EVT,
-    OBX_SETPATH_REQ_EVT,    /* param = flags */
-    OBX_ABORT_REQ_EVT,
-    OBX_ACTION_REQ_EVT,     /* An Action request is received by the server. Call OBX_ActionRsp(). */
-
-    /* client events */
-    OBX_CONNECT_RSP_EVT,    /* param = packet MTU */
-    OBX_SESSION_RSP_EVT,    /* A response for Create Session or Resume Session is received by the client. The client needs to remember the session id. The session id is to be used in calling OBX_ResumeSession, if the current session is terminated prematurely. */
-    OBX_DISCONNECT_RSP_EVT,
-    OBX_PUT_RSP_EVT,
-    OBX_GET_RSP_EVT,
-    OBX_SETPATH_RSP_EVT,
-    OBX_ABORT_RSP_EVT,
-    OBX_ACTION_RSP_EVT,     /* An Action response is received by the client. */
-
-    /* common events */
-    OBX_SESSION_INFO_EVT,   /* the session information event to resume the session. */
-    OBX_CLOSE_IND_EVT,      /* when transport goes down; p_pkt = NULL; no response needed */
-    OBX_TIMEOUT_EVT,        /* param = tOBX_EVENT */
-    OBX_PASSWORD_EVT
-};
-typedef UINT8 tOBX_EVENT;
-
-/* this is used by the protocol display function only*/
-enum
-{
-    OBX_NULL_DISP,
-    /* server events */
-    OBX_CONNECT_REQ_DISP,
-    OBX_SESSION_REQ_DISP,
-    OBX_DISCONNECT_REQ_DISP,
-    OBX_PUT_REQ_DISP,
-    OBX_GET_REQ_DISP,
-    OBX_SETPATH_REQ_DISP,
-    OBX_ABORT_REQ_DISP,
-    OBX_ACTION_REQ_DISP,
-    /* client events */
-    OBX_CONNECT_RSP_DISP,
-    OBX_SESSION_RSP_DISP,
-    OBX_DISCONNECT_RSP_DISP,
-    OBX_PUT_RSP_DISP,
-    OBX_GET_RSP_DISP,
-    OBX_SETPATH_RSP_DISP,
-    OBX_ABORT_RSP_DISP,
-    OBX_ACTION_RSP_DISP,
-    /* common events */
-    OBX_CLOSE_IND_DISP,
-    OBX_TIMEOUT_DISP,
-    OBX_PASSWORD_DISP
-};
-#define OBX_DISP_IS_RECV    0x80
-#define OBX_DISP_TYPE_MASK  0x7F
-
-#define OBX_MAX_EVT         OBX_PASSWORD_EVT
-#define OBX_MAX_OFFSET_IND  OBX_ABORT_RSP_EVT /* This is used to access obx_hdr_start_offset */
-
-/*
-** Define Miscellaneous Constants
-*/
-#define OBX_VERSION                     0x10    /* Version 1.0 */
-#define OBX_CONN_FLAGS                  0       /* Connect flags per IrOBEX spec */
-#define OBX_SETPATH_CONST               0       /* SetPath Request constants per IrOBEX spec */
-#define OBX_INVALID_CONN_ID             0xFFFFFFFF  /* invalid connection ID per IrOBEX spec */
-#define OBX_INFINITE_TIMEOUT            0xFFFFFFFF
-
-/* Header Identifier Data Type Constants */
-#define OBX_HI_TYPE_MASK                0xC0    /* This mask get the encoding (data type) of the header ID. */
-#define OBX_HI_ID_MASK                  0x3F    /* This mask gets the meaning of the header ID. */
-#define OBX_HI_TYPE_UNIC                0x00    /* Null terminated Unicode text */
-#define OBX_HI_TYPE_ARRAY               0x40    /* Unstructured octet array (byte sequence) */
-#define OBX_HI_TYPE_BYTE                0x80    /* 8-bit integer */
-#define OBX_HI_TYPE_INT                 0xC0    /* 32-bit integer */
-
-/*
-** Define OBEX Header Identifiers
-*/
-#define OBX_HI_NULL                     0
-#define OBX_HI_COUNT                    0xC0
-#define OBX_HI_NAME                     0x01
-#define OBX_HI_TYPE                     0x42
-#define OBX_HI_LENGTH                   0xC3
-#define OBX_HI_TIME                     0x44
-#define OBX_HI_DESCRIPTION              0x05
-#define OBX_HI_TARGET                   0x46
-#define OBX_HI_HTTP                     0x47
-#define OBX_HI_BODY                     0x48
-#define OBX_HI_BODY_END                 0x49
-#define OBX_HI_WHO                      0x4A
-#define OBX_HI_CONN_ID                  0xCB
-#define OBX_HI_APP_PARMS                0x4C
-#define OBX_HI_CHALLENGE                0x4D
-#define OBX_HI_AUTH_RSP                 0x4E
-#define OBX_HI_CREATOR_ID               0xCF
-#define OBX_HI_WAN_UUID                 0x50
-#define OBX_HI_OBJ_CLASS                0x51
-#define OBX_HI_SESSION_PARAM            0x52
-#define OBX_HI_SESSION_SN               0x93
-#define OBX_HI_ACTION_ID                0x94
-#define OBX_HI_DEST_NAME                0x15
-#define OBX_HI_PERMISSION               0xD6
-#define OBX_HI_SRM                      0x97
-#define OBX_HI_SRM_PARAM                0x98
-#define OBX_HI_LO_USER                  0x30
-#define OBX_HI_HI_USER                  0x3F
-
-/* Obex Header Values for the SRM header */
-#define OBX_HV_SRM_DISABLE  0x00    /* SRM header value - disable */
-#define OBX_HV_SRM_ENABLE   0x01    /* SRM header value - enable */
-#define OBX_HV_SRM_IND      0x02    /* SRM header value - indicate support */
-
-/* Obex Header Values for the SRM Parameter header */
-#define OBX_HV_SRM_PARAM_MORE   0x00    /* SRM Param header value - request additional packet */
-#define OBX_HV_SRM_PARAM_WAIT   0x01    /* SRM Param header value - wait for next req/rsp */
-#define OBX_HV_SRM_PARAM_COMBO  0x02    /* SRM Param header value - next and wait */
-
-#define OBX_TAG_SESS_PARAM_ADDR         0x00
-#define OBX_TAG_SESS_PARAM_NONCE        0x01
-#define OBX_TAG_SESS_PARAM_SESS_ID      0x02
-#define OBX_TAG_SESS_PARAM_NSEQNUM      0x03
-#define OBX_TAG_SESS_PARAM_TOUT         0x04
-#define OBX_TAG_SESS_PARAM_SESS_OP      0x05
-#define OBX_TAG_SESS_PARAM_OBJ_OFF      0x06
-#define OBX_MAX_SESS_PARAM_TRIP         7   /* max number of TLV for session operations */
-
-#define OBX_LEN_SESS_PARAM_SESS_OP      1
-#define OBX_LEN_SESS_PARAM_OBJ_OFF      4   /* this value varies, so it needs to be verified on the receiving side */
-
-/*
-** Define OBEX Request Codes
-*/
-#define OBX_REQ_CONNECT                         0x00    /* need to set final bit */
-#define OBX_REQ_DISCONNECT                      0x01    /* need to set final bit */
-#define OBX_REQ_PUT                             0x02
-#define OBX_REQ_GET                             0x03
-#define OBX_REQ_SETPATH                         0x05    /* need to set final bit */
-#define OBX_REQ_ACTION                          0x06
-#define OBX_REQ_SESSION                         0x07    /* need to set final bit */
-#define OBX_REQ_ABORT                           0x7F    /* need to set final bit */
-#define OBX_FINAL                               0x80
-
-/* OBEX response code as defined in IrOBEX spec. version 1.2 */
-#define OBX_RSP_DEFAULT                         0x00
-#define OBX_RSP_FAILED                          0x08    /* OBEX failed - not from spec */
-#define OBX_RSP_CONTINUE                        0x10    /* Continue */
-#define OBX_RSP_OK                              0x20    /* OK, Success */
-#define OBX_RSP_CREATED                         0x21    /* Created */
-#define OBX_RSP_ACCEPTED                        0x22    /* Accepted */
-#define OBX_RSP_NON_AUTH_INFO                   0x23    /* Non-Authoritative Information */
-#define OBX_RSP_NO_CONTENT                      0x24    /* No Content */
-#define OBX_RSP_RESET_CONTENT                   0x25    /* Reset Content */
-#define OBX_RSP_PART_CONTENT                    0x26    /* Partial Content */
-#define OBX_RSP_MULTI_CHOICES                   0x30    /* Multiple Choices */
-#define OBX_RSP_MVD_PERM                        0x31    /* Moved Permanently */
-#define OBX_RSP_MVD_TEMP                        0x32    /* Moved temporarily */
-#define OBX_RSP_SEE_OTHER                       0x33    /* See Other */
-#define OBX_RSP_NOT_MODIFIED                    0x34    /* Not modified */
-#define OBX_RSP_USE_PROXY                       0x35    /* Use Proxy */
-#define OBX_RSP_BAD_REQUEST                     0x40    /* Bad Request - server couldn't understand request */
-#define OBX_RSP_UNAUTHORIZED                    0x41    /* Unauthorized */
-#define OBX_RSP_PAYMENT_REQD                    0x42    /* Payment required */
-#define OBX_RSP_FORBIDDEN                       0x43    /* Forbidden - operation is understood but refused */
-#define OBX_RSP_NOT_FOUND                       0x44    /* Not Found */
-#define OBX_RSP_NOT_ALLOWED                     0x45    /* Method not allowed */
-#define OBX_RSP_NOT_ACCEPTABLE                  0x46    /* Not Acceptable */
-#define OBX_RSP_PROXY_AUTH_REQD                 0x47    /* Proxy Authentication required */
-#define OBX_RSP_REQUEST_TIMEOUT                 0x48    /* Request Time Out */
-#define OBX_RSP_CONFLICT                        0x49    /* Conflict */
-#define OBX_RSP_GONE                            0x4A    /* Gone */
-#define OBX_RSP_LENGTH_REQD                     0x4B    /* Length Required */
-#define OBX_RSP_PRECONDTN_FAILED                0x4C    /* Precondition failed */
-#define OBX_RSP_REQ_ENT_2_LARGE                 0x4D    /* Requested entity too large */
-#define OBX_RSP_REQ_URL_2_LARGE                 0x4E    /* Request URL too large */
-#define OBX_RSP_UNSUPTD_TYPE                    0x4F    /* Unsupported media type */
-#define OBX_RSP_INTRNL_SRVR_ERR                 0x50    /* Internal Server Error */
-#define OBX_RSP_NOT_IMPLEMENTED                 0x51    /* Not Implemented */
-#define OBX_RSP_BAD_GATEWAY                     0x52    /* Bad Gateway */
-#define OBX_RSP_SERVICE_UNAVL                   0x53    /* Service Unavailable */
-#define OBX_RSP_GATEWAY_TIMEOUT                 0x54    /* Gateway Timeout */
-#define OBX_RSP_HTTP_VER_NOT_SUPTD              0x55    /* HTTP version not supported */
-#define OBX_RSP_DATABASE_FULL                   0x60    /* Database Full */
-#define OBX_RSP_DATABASE_LOCKED                 0x61    /* Database Locked */
-
-#define OBX_MAX_OK_RSP      OBX_RSP_PART_CONTENT
-
-typedef UINT8   tOBX_RSP_CODE;
-
-/* tags for authentication triplet */
-#define OBX_NONCE_CHLNG_TAG         0
-#define OBX_OPTIONS_CHLNG_TAG       1
-#define OBX_REALM_CHLNG_TAG         2
-
-#define OBX_DIGEST_RSP_TAG          0
-#define OBX_USERID_RSP_TAG          1
-#define OBX_NONCE_RSP_TAG           2
-
-typedef struct
-{
-    UINT8   tag;
-    UINT8   len;
-    UINT8   *p_array;
-} tOBX_TRIPLET;
-
-/* Server Callback type: */
-typedef void (tOBX_SR_CBACK) (tOBX_HANDLE shandle, tOBX_EVENT event, tOBX_EVT_PARAM param, BT_HDR *p_pkt);
-/* Client Callback type: */
-typedef void (tOBX_CL_CBACK) (tOBX_HANDLE handle, tOBX_EVENT event, UINT8 rsp_code, tOBX_EVT_PARAM param, BT_HDR *p_pkt);
-
-
-typedef struct
-{
-    UINT16  len;                        /* Length of target header. */
-    UINT8   target[OBX_MAX_TARGET_LEN]; /* The byte sequence that describes the target header. */
-} tOBX_TARGET;
-
-
-typedef struct
-{
-    tOBX_TARGET     *p_target;
-    tOBX_SR_CBACK   *p_cback;
-    UINT16          mtu;
-    UINT8           scn;            /* The RFCOMM SCN number that this server listens for incoming requests. 0, if do not wish to listen to connection from RFCOMM. */
-    BOOLEAN         authenticate;
-    UINT8           auth_option;
-    UINT8           realm_charset;
-    UINT8           *p_realm;
-    UINT8           realm_len;
-    UINT8           max_sessions;
-    BOOLEAN         get_nonf;       /* report GET non-final request event. If FALSE, GET response is sent automatically */
-    UINT16          psm;            /* The L2CAP PSM number that this server listens for incoming requests. 0, if do not wish to listen to connection from L2CAP. */
-    UINT32          nonce;          /* This is converted to UINT8[16] internally before adding to the OBEX header. This value is copied to the server control block and is increased after each use. 0, if only legacy OBEX (unreliable) session is desired. */
-    BOOLEAN         srm;            /* TRUE, to support single response mode. */
-    UINT8           max_suspend;    /* Max number of suspended session. must be less than OBX_MAX_SUSPEND_SESSIONS. ignored, if nonce is 0 */
-} tOBX_StartParams;
-
-
-
-
-
-/*****************************************************************************
-**  External Function Declarations
-*****************************************************************************/
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/*******************************************************************************
-**
-** Function     OBX_Init
-**
-** Description  This function is called to initialize the control block for this
-**              layer. It must be called before accessing any other of its API
-**              functions.  It is typically called once during the start up of
-**              the stack.
-**
-** Returns      void.
-**
-*******************************************************************************/
-OBX_API extern void OBX_Init(void);
-
-/*******************************************************************************
-**
-** Function         OBX_SetTraceLevel
-**
-** Description      This function sets the debug trace level for OBX.
-**                  If 0xff is passed, the current trace level is returned.
-**
-**                  Input Parameters:
-**                      level:  The level to set the OBX tracing to:
-**                      0xff-returns the current setting.
-**                      0-turns off tracing.
-**                      >= 1-Errors.
-**                      >= 2-Warnings.
-**                      >= 3-APIs.
-**                      >= 4-Events.
-**                      >= 5-Debug.
-**
-** Returns          The new trace level or current trace level if
-**                  the input parameter is 0xff.
-**
-*******************************************************************************/
-OBX_API extern UINT8 OBX_SetTraceLevel (UINT8 level);
-
-/*******************************************************************************
-** Function     OBX_HandleToMtu
-**
-** Description  Given an OBEX handle, return the associated peer MTU.
-**
-** Returns      MTU.
-**
-*******************************************************************************/
-OBX_API extern UINT16 OBX_HandleToMtu(tOBX_HANDLE handle);
-
-/* Server API's: */
-/*******************************************************************************
-**
-** Function     OBX_StartServer
-**
-** Description  This function is to register a server entity to OBEX.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_NO_RESOURCES, if OBX does not have resources.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_StartServer(tOBX_StartParams *p_params, tOBX_HANDLE *p_handle);
-
-/*******************************************************************************
-**
-** Function     OBX_StopServer
-**
-** Description  This function is to stop this OBEX server from receiving any
-**              more incoming requests.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_StopServer(tOBX_HANDLE handle);
-
-/*******************************************************************************
-**
-** Function     OBX_AddSuspendedSession
-**
-** Description  This function is to add the session information for a previously
-**				suspended reliable session to the server control block
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_AddSuspendedSession(tOBX_HANDLE shandle, BD_ADDR peer_addr, UINT8 *p_sess_info,
-                                                   UINT32 timeout, UINT8 ssn, UINT32 offset);
-
-/*******************************************************************************
-**
-** Function     OBX_ConnectRsp
-**
-** Description  This function is called to send the response to a Connect
-**              Request from an OBEX client.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_ConnectRsp(tOBX_HANDLE shandle, UINT8 rsp_code, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_SessionRsp
-**
-** Description  This function is called to respond to a request to create a reliable session.
-**
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_SessionRsp(tOBX_HANDLE shandle, UINT8 rsp_code,
-                                          UINT8 ssn, UINT32 offset, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_SetPathRsp
-**
-** Description  This function is called to send the response to a Set Path
-**              Request from an OBEX client.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_SetPathRsp(tOBX_HANDLE shandle, UINT8 rsp_code, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_PutRsp
-**
-** Description  This function is called to send the response to a Put
-**              Request from an OBEX client.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_PutRsp(tOBX_HANDLE shandle, UINT8 rsp_code, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_GetRsp
-**
-** Description  This function is called to send the response to a Get
-**              Request from an OBEX client.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_GetRsp(tOBX_HANDLE shandle, UINT8 rsp_code, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_AbortRsp
-**
-** Description  This function is called to send the response to an Abort
-**              Request from an OBEX client.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_AbortRsp(tOBX_HANDLE shandle, UINT8 rsp_code, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_ActionRsp
-**
-** Description  This function is called to respond to an Action command Request
-**              from an OBEX client.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_ActionRsp(tOBX_HANDLE shandle, UINT8 rsp_code, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_DisconnectRsp
-**
-** Description  This function is called to send the response to a Disconnect
-**              Request from an OBEX client.
-**              This function can also be used to force close the transport
-**              to a connected client.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_DisconnectRsp(tOBX_HANDLE shandle, UINT8 rsp_code, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_Password
-**
-** Description  This function is called to respond to an OBX_PASSWORD_EVT event.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_NO_RESOURCES, if OBX does not resources
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_Password(tOBX_HANDLE shandle, UINT8 *p_password, UINT8 password_len,
-                                        UINT8 *p_userid, UINT8 userid_len);
-
-/*******************************************************************************
-**
-** Function     OBX_GetPeerAddr
-**
-** Description  This function is called to learn the Bluetooth address of the
-**              connected device.
-**
-** Returns      L2CAP channel ID.
-**
-*******************************************************************************/
-OBX_API extern UINT16 OBX_GetPeerAddr(tOBX_HANDLE shandle, BD_ADDR bd_addr);
-
-/*******************************************************************************
-**
-** Function     OBX_GetPortHandle
-**
-** Description  This function is called to get the RFCOMM port handle for the obex connection.
-**
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_NO_RESOURCES, if no existing connection.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_GetPortHandle(tOBX_HANDLE handle, UINT16 *port_handle);
-
-/* Client API's: */
-/*******************************************************************************
-**
-** Function     OBX_ConnectReq
-**
-** Description  This function registers a client entity to OBEX and sends a
-**              CONNECT request to the server specified by the API parameters.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_NO_RESOURCES, if OBX does not resources
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_ConnectReq(BD_ADDR bd_addr, UINT8 scn, UINT16 mtu,
-                                          tOBX_CL_CBACK *p_cback, tOBX_HANDLE *p_handle, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_AllocSession
-**
-** Description  This function registers a client entity to OBEX.
-**              If p_session_id is not NULL, it tries to find an suspended session
-**                  with matching session_id.
-**              If scn is not 0, it allocates a control block for this new session.
-**              Otherwise, it allocates a control block for the given PSM.
-**              The associated virtual PSM assigned by L2CAP is returned in p_psm
-**              The allocated OBEX handle is returned in p_handle.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_NO_RESOURCES, if OBX does not resources
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_AllocSession (UINT8 *p_session_info, UINT8 scn, UINT16 *p_psm,
-                              tOBX_CL_CBACK *p_cback, tOBX_HANDLE *p_handle);
-
-/*******************************************************************************
-**
-** Function     OBX_CreateSession
-**
-** Description  This function registers a client entity to OBEX.
-**              It may send a CreateSession request and wait for CreateSession response.
-**              It sends a CONNECT request to the server specified by the API parameters.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_NO_RESOURCES, if OBX does not resources
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_CreateSession (BD_ADDR bd_addr, UINT16 mtu, BOOLEAN srm, UINT32 nonce,
-                                              tOBX_HANDLE handle, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_ResumeSession
-**
-** Description  This function registers a client entity to OBEX and resumes
-**              a previously interrupted reliable session.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_NO_RESOURCES, if OBX does not resources
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_ResumeSession (BD_ADDR bd_addr, UINT8 ssn, UINT32 offset, tOBX_HANDLE handle);
-
-/*******************************************************************************
-**
-** Function     OBX_SessionReq
-**
-** Description  This function is used to Suspend, Resume, or Close a session.
-**              For Resume: this function registers a client entity to OBEX and resumes
-**              a previously interrupted reliable session.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_NO_RESOURCES, if OBX does not resources
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_SessionReq (tOBX_HANDLE handle, tOBX_SESS_OP opcode, UINT32 timeout);
-
-/*******************************************************************************
-**
-** Function     OBX_SetPathReq
-**
-** Description  This function sends a Set Path request to the connected server.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_SetPathReq(tOBX_HANDLE handle, UINT8 flags, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_PutReq
-**
-** Description  This function sends a Put request to the connected server.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_PutReq(tOBX_HANDLE handle, BOOLEAN final, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_GetReq
-**
-** Description  This function sends a Get request to the connected server.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_GetReq(tOBX_HANDLE handle, BOOLEAN final, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_AbortReq
-**
-** Description  This function sends an Abort request to the connected server.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_AbortReq(tOBX_HANDLE handle, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_DisconnectReq
-**
-** Description  This function sends a Disconnect request to the connected server.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_DisconnectReq(tOBX_HANDLE handle, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_ActionReq
-**
-** Description  This function sends a Action request to the connected server.
-**              The Name Header and DestName Header must be in p_pkt for
-**                  the Copy and Move Object action.
-**              The Name header and Permission Header must be in p_pkt for
-**                  the Set Object Permission action.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_BAD_HANDLE, if the handle is not valid.
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_ActionReq(tOBX_HANDLE handle, tOBX_ACTION action_id, BT_HDR *p_pkt);
-
-/*******************************************************************************
-**
-** Function     OBX_AuthResponse
-**
-** Description  This function is called to respond to an OBX_PASSWORD_EVT event.
-**
-** Returns      OBX_SUCCESS, if successful.
-**              OBX_NO_RESOURCES, if OBX does not resources
-**
-*******************************************************************************/
-OBX_API extern tOBX_STATUS OBX_AuthResponse(tOBX_HANDLE handle,
-                                            UINT8 *p_password, UINT8 password_len,
-                                            UINT8 *p_userid, UINT8 userid_len,
-                                            BOOLEAN authenticate);
-
-
-/*******************************************************************************
-**
-** Function     OBX_HdrInit
-**
-** Description  This function is called to initialize an OBEX packet. This
-**              function takes a GKI buffer and sets the offset in BT_HDR as
-**              OBEX_HDR_OFFSET, the len as 0. The layer_specific is set to the
-**              length still available. This function compares the given
-**              (pkt_size - sizeof(BT_HDR)) with the peer MTU to get the lesser
-**              of the two and set the layer_specific to
-**              (lesser_size - OBEX_HDR_OFFSET).
-**              If composing a header for the CONNECT request (there is no
-**              client handle yet), use OBX_HANDLE_NULL as the handle.
-**
-** Returns      BT_HDR *.
-**
-*******************************************************************************/
-OBX_API extern BT_HDR * OBX_HdrInit(tOBX_HANDLE handle, UINT16 pkt_size);
-
-/*******************************************************************************
-**
-** Function     OBX_AddNameHdr
-**
-** Description  This function is called to add an OBEX Name header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddNameHdr(BT_HDR *p_pkt, UINT16 *p_name, UINT16 len);
-
-/*******************************************************************************
-**
-** Function     OBX_CharToWchar
-**
-** Description  This function is called to convert ASCII to Unicode (UINT16).
-**
-** Returns      the length.
-**
-*******************************************************************************/
-OBX_API extern UINT16 OBX_CharToWchar (UINT16 *w_str, char* a_str, UINT16 w_size);
-
-/*******************************************************************************
-**
-** Function     OBX_AddAsciiNameHdr
-**
-** Description  This function is called to add an OBEX Name header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddAsciiNameHdr(BT_HDR *p_pkt, char *p_name);
-
-/*******************************************************************************
-**
-** Function     OBX_AddTypeHdr
-**
-** Description  This function is called to add an OBEX Type header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddTypeHdr(BT_HDR *p_pkt, char *p_type);
-
-/*******************************************************************************
-**
-** Function     OBX_AddLengthHdr
-**
-** Description  This function is called to add an OBEX Length header to an OBEX
-**              packet. The Length header describes the total length in bytes of
-**              the object.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddLengthHdr(BT_HDR *p_pkt, UINT32 len);
-
-/*******************************************************************************
-**
-** Function     OBX_AddTimeHdr
-**
-** Description  This function is called to add an OBEX Time header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddTimeHdr(BT_HDR *p_pkt, char *p_time);
-
-/*******************************************************************************
-**
-** Function     OBX_AddDescrHdr
-**
-** Description  This function is called to add an OBEX Description header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddDescrHdr(BT_HDR *p_pkt, UINT16 *p_descr, UINT16 len);
-
-/*******************************************************************************
-**
-** Function     OBX_AddAsciiDescrHdr
-**
-** Description  This function is called to add an OBEX Description header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddAsciiDescrHdr(BT_HDR *p_pkt, char *p_descr);
-
-/*******************************************************************************
-**
-** Function     OBX_AddTargetHdr
-**
-** Description  This function is called to add an OBEX Target header to an OBEX
-**              packet. This header is most commonly used in Connect packets.
-**
-**              NOTE: The target header must be the first header in an OBEX message.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddTargetHdr(BT_HDR *p_pkt, UINT8 *p_target, UINT16 len);
-
-/*******************************************************************************
-**
-** Function     OBX_AddHttpHdr
-**
-** Description  This function is called to add an OBEX HTTP header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddHttpHdr(BT_HDR *p_pkt, UINT8 *p_http, UINT16 len);
-
-/*******************************************************************************
-**
-** Function     OBX_AddBodyHdr
-**
-** Description  This function is called to add an OBEX body header
-**              to an OBEX packet.
-**
-**              NOTE: The body header must be the last header in an OBEX message.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddBodyHdr(BT_HDR *p_pkt, UINT8 *p_body, UINT16 len, BOOLEAN end);
-
-/* Alternate Body header functions: for non-blocking scenario */
-/*******************************************************************************
-**
-** Function     OBX_AddBodyStart
-**
-** Description  This function is called to get the address to the beginning of
-**              the byte sequence for an OBEX body header in an OBEX packet.
-**
-** Returns      The address to add body content.
-**
-*******************************************************************************/
-OBX_API extern UINT8 *OBX_AddBodyStart(BT_HDR *p_pkt, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function     OBX_AddBodyEnd
-**
-** Description  This function is called to add the HI and the length of HV of an
-**              OBEX body header to an OBEX packet. If end is TRUE, HI is
-**              OBX_HI_BODY_END. If FALSE, HI is OBX_HI_BODY. It is assumed that
-**              the actual value of the body has been copied into the OBEX packet.
-**
-** Returns      void
-**
-*******************************************************************************/
-OBX_API extern void OBX_AddBodyEnd(BT_HDR *p_pkt, UINT8 *p, UINT16 len, BOOLEAN end);
-
-/*******************************************************************************
-**
-** Function     OBX_AddWhoHdr
-**
-** Description  This function is called to add an OBEX Who header to an OBEX
-**              packet.
-**
-** Note:        Who header is typically used in an OBEX CONNECT response packet
-**              to indicate the UUID of the service that has accepted the
-**              directed connection. If the server calls OBX_StartServer() with
-**              specified target header, this OBEX implementation automatically
-**              adds this WHO header to the CONNECT response packet. If
-**              OBX_StartServer() is called with target header length as 0, the
-**              OBEX API user is responsible to add the WHO header.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddWhoHdr(BT_HDR *p_pkt, UINT8 *p_who, UINT16 len);
-
-/*******************************************************************************
-**
-** Function     OBX_AddAppParamHdr
-**
-** Description  This function is called to add an OBEX Application Parameter
-**              header to an OBEX packet. This header is used by the application
-**              layer above OBEX to convey application specific information.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddAppParamHdr(BT_HDR *p_pkt, tOBX_TRIPLET *p_triplet, UINT8 num);
-
-/*******************************************************************************
-**
-** Function     OBX_AddDestNameHdr
-**
-** Description  This function is called to add an OBEX DestName header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddDestNameHdr(BT_HDR *p_pkt, UINT16 *p_dest, UINT16 len);
-
-/*******************************************************************************
-**
-** Function     OBX_AddAsciiDestNameHdr
-**
-** Description  This function is called to add an OBEX DestName header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddAsciiDestNameHdr(BT_HDR *p_pkt, char *p_descr);
-
-/*******************************************************************************
-**
-** Function     OBX_AddPermissionHdr
-**
-** Description  This function is called to add an OBEX Permission header to an OBEX
-**              packet.
-**              bit 0 is set for read permission
-**              bit 1 is set for write permission
-**              bit 2 is set for delete permission
-**              bit 7 is set for modify permission
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddPermissionHdr(BT_HDR *p_pkt, UINT8 user, UINT8 group, UINT8 other);
-
-/*******************************************************************************
-**
-** Function     OBX_Add1ByteHdr
-**
-** Description  This function is called to add a header with type as UINT8
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_Add1ByteHdr(BT_HDR *p_pkt, UINT8 id, UINT8 data);
-
-/*******************************************************************************
-**
-** Function     OBX_Add4ByteHdr
-**
-** Description  This function is called to add a header with type as UINT32
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_Add4ByteHdr(BT_HDR *p_pkt, UINT8 id, UINT32 data);
-
-/*******************************************************************************
-**
-** Function     OBX_AddByteStrStart
-**
-** Description  This function is called to get the address to the beginning of
-**              the byte sequence for an OBEX header in an OBEX packet.
-**
-** Returns      The address to add the byte sequence.
-**
-*******************************************************************************/
-OBX_API extern UINT8 *OBX_AddByteStrStart(BT_HDR *p_pkt, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function     OBX_AddByteStrHdr
-**
-** Description  This function is called to add a header with type as byte sequence
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddByteStrHdr(BT_HDR *p_pkt, UINT8 id, UINT8 *p_data, UINT16 len);
-
-/*******************************************************************************
-**
-** Function     OBX_AddUnicodeHdr
-**
-** Description  This function is called to add a header with type as Unicode string
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddUnicodeHdr(BT_HDR *p_pkt, UINT8 id, UINT16 *p_data, UINT16 len);
-
-/*******************************************************************************
-**
-** Function     OBX_AddTriplet
-**
-** Description  This function is called to add a header with type as byte sequence
-**              to an OBEX packet.
-**
-** Note:        The byte sequence uses a Tag-Length-Value encoding scheme
-**              These headers include: Application Parameters header
-**                                     Authenticate Challenge header
-**                                     Authenticate Response header
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddTriplet(BT_HDR *p_pkt, UINT8 id, tOBX_TRIPLET *p_triplet, UINT8 num);
-
-/*******************************************************************************
-**
-** Function     OBX_CheckHdr
-**
-** Description  This function is called to check if the given OBEX packet
-**              contains the specified header.
-**
-** Returns      NULL, if the header is not in the OBEX packet.
-**              The pointer to the specified header beginning from HI.
-**
-*******************************************************************************/
-OBX_API extern UINT8 * OBX_CheckHdr(BT_HDR *p_pkt, UINT8 id);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadNumHdrs
-**
-** Description  This function is called to check the number of headers in the
-**              given OBEX packet
-**
-** Returns      number of headers.
-**
-*******************************************************************************/
-OBX_API extern UINT8 OBX_ReadNumHdrs(BT_HDR *p_pkt, UINT8 *p_num_body);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadHdrLen
-**
-** Description  This function is called to check the length of the specified
-**              header in the given OBEX packet.
-**
-** Returns      OBX_INVALID_HDR_LEN, if the header is not in the OBEX packet.
-**              Otherwise the actual length of the header.
-**
-*******************************************************************************/
-OBX_API extern UINT16 OBX_ReadHdrLen(BT_HDR *p_pkt, UINT8 id);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadNameHdr
-**
-** Description  This function is called to get the Name Header in the given
-**              OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadNameHdr(BT_HDR *p_pkt, UINT16 *p_name, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function     OBX_WcharToChar
-**
-** Description  This function is called to convert Unicode (UINT16) to ASCII.
-**
-** Returns      void.
-**
-*******************************************************************************/
-OBX_API extern void OBX_WcharToChar (char *a_str, UINT16* w_str, UINT16 a_size) ;
-
-/*******************************************************************************
-**
-** Function     OBX_ReadAsciiNameHdr
-**
-** Description  This function is called to get the Name Header in the given
-**              OBEX packet. If Name header exists in the given OBEX packet,
-**              it is converted to ASCII format and copied into p_name.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadAsciiNameHdr(BT_HDR *p_pkt, char *p_name, UINT16 max_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadTypeHdr
-**
-** Description  This function is called to get the Type Header in the given
-**              OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadTypeHdr(BT_HDR *p_pkt, UINT8 **p_type, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadLengthHdr
-**
-** Description  This function is called to get the Length Header in the given
-**              OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadLengthHdr(BT_HDR *p_pkt, UINT32 *p_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadTimeHdr
-**
-** Description  This function is called to get the Time Header in the given
-**              OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadTimeHdr(BT_HDR *p_pkt, UINT8 **p_time, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadDescrHdr
-**
-** Description  This function is called to get the Description Header in the
-**              given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadDescrHdr(BT_HDR *p_pkt, UINT16 *p_descr, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadDestNameHdr
-**
-** Description  This function is called to get the DestName Header in the
-**              given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadDestNameHdr(BT_HDR *p_pkt, UINT16 *p_dest, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadAsciiDescrHdr
-**
-** Description  This function is called to get the Description Header in the
-**              given OBEX packet. If Description header exists in the given
-**              OBEX packet, it is converted to ASCII format and copied into
-**              p_descr.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadAsciiDescrHdr(BT_HDR *p_pkt, char *p_descr, UINT16 max_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadAsciiDestNameHdr
-**
-** Description  This function is called to get the DestName Header in the
-**              given OBEX packet. If DestName header exists in the given
-**              OBEX packet, it is converted to ASCII format and copied into
-**              p_descr.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadAsciiDestNameHdr(BT_HDR *p_pkt, char *p_dest, UINT16 max_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadTargetHdr
-**
-** Description  This function is called to get the Target Header in the
-**              given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadTargetHdr(BT_HDR *p_pkt, UINT8 **p_target, UINT16 *p_len, UINT8 next);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadHttpHdr
-**
-** Description  This function is called to get the HTTP Header in the
-**              given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadHttpHdr(BT_HDR *p_pkt, UINT8 **p_http, UINT16 *p_len, UINT8 next);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadBodyHdr
-**
-** Description  This function is called to get the Body Header in the
-**              given OBEX packet.
-**
-** Returns      1, if a single header is in the OBEX packet.
-**              2, if a end of body header is in the OBEX packet.
-**              0, (FALSE) otherwise.
-**
-*******************************************************************************/
-OBX_API extern UINT8 OBX_ReadBodyHdr(BT_HDR *p_pkt, UINT8 **p_body, UINT16 *p_len, BOOLEAN *p_end);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadWhoHdr
-**
-** Description  This function is called to get the Who Header in the
-**              given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadWhoHdr(BT_HDR *p_pkt, UINT8 **p_who, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadAppParamHdr
-**
-** Description  This function is called to get the Application Parameter Header
-**              in the given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadAppParamHdr(BT_HDR *p_pkt, UINT8 *p_tag, UINT8 **p_app_param, UINT8 *p_len, UINT8 next);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadPermissionHdr
-**
-** Description  This function is called to get the Application Parameter Header
-**              in the given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadPermissionHdr(BT_HDR *p_pkt, UINT8 *p_user, UINT8 *p_group, UINT8 *p_other);
-
-/*******************************************************************************
-**
-** Function     OBX_Read1ByteHdr
-**
-** Description  This function is called to get the UINT8 HV of the given HI
-**              in the given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_Read1ByteHdr(BT_HDR *p_pkt, UINT8 id, UINT8 *p_data);
-
-/*******************************************************************************
-**
-** Function     OBX_Read4ByteHdr
-**
-** Description  This function is called to get the UINT32 HV of the given HI
-**              in the given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_Read4ByteHdr(BT_HDR *p_pkt, UINT8 id, UINT32 *p_data);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadByteStrHdr
-**
-** Description  This function is called to get the byte sequence HV of the given
-**              HI in the given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadByteStrHdr(BT_HDR *p_pkt, UINT8 id, UINT8 **p_data, UINT16 *p_len, UINT8 next);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadUnicodeHdr
-**
-** Description  This function is called to get the Unicode HV of the given
-**              HI in the given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadUnicodeHdr(BT_HDR *p_pkt, UINT8 id, UINT16 *p_data, UINT16 *p_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadTriplet
-**
-** Description  This function is called to get the Triplet HV of the given
-**              HI in the given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadTriplet(BT_HDR *p_pkt, UINT8 id, tOBX_TRIPLET *p_triplet, UINT8 *p_num);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadActionIdHdr
-**
-** Description  This function is called to get the HV of the Action ID header
-**              in the given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadActionIdHdr(BT_HDR *p_pkt, UINT8 *p_data);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadChallenge
-**
-** Description  This function is called to read the Realm and options of the
-**              Authentication Challenge Header in the given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadChallenge(BT_HDR *p_pkt, tOBX_CHARSET *p_charset,
-                                         UINT8 **p_realm, UINT8 *p_len,
-                                         tOBX_AUTH_OPT *p_option);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadAuthParams
-**
-** Description  This function is called to read the User ID of the
-**              Authentication Response Header in the given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadAuthParams(BT_HDR *p_pkt, UINT8 **p_userid, UINT8 *p_len,
-                                          BOOLEAN *is_challenged, tOBX_AUTH_OPT *p_option);
-
-
-/*******************************************************************************
-**
-** Function         utfc_16_to_8
-**
-** Description      Convert a UTF-16 array to a null-terminated UTF-8 string.
-**                  Illegal characters are skipped.
-**
-** Returns          Length of UTF-8 string in bytes.
-**
-*******************************************************************************/
-OBX_API extern UINT16 utfc_16_to_8(UINT8 *p_utf8, UINT16 utf8_len, UINT16 *p_utf16, UINT16 utf16_len);
-
-/*******************************************************************************
-**
-** Function         utfc_8_to_16
-**
-** Description      Convert a null-terminated UTF-8 string to a UTF-16 array.
-**                  Illegal characters are skipped.
-**
-** Returns          Length of UTF-16 array.
-**
-*******************************************************************************/
-OBX_API extern UINT16 utfc_8_to_16(UINT16 *p_utf16, UINT16 utf16_len, UINT8 *p_utf8);
-
-/*******************************************************************************
-**
-** Function     OBX_AddUtf8NameHdr
-**
-** Description  This function is called to add an OBEX Name header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddUtf8NameHdr(BT_HDR *p_pkt, UINT8 *p_name);
-
-/*******************************************************************************
-**
-** Function     OBX_AddUtf8DescrHdr
-**
-** Description  This function is called to add an OBEX Description header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddUtf8DescrHdr(BT_HDR *p_pkt, UINT8 *p_descr);
-
-/*******************************************************************************
-**
-** Function     OBX_AddUtf8DestNameHdr
-**
-** Description  This function is called to add an OBEX DestName header
-**              to an OBEX packet.
-**
-** Returns      TRUE, if the header is added successfully.
-**              FALSE, if the operation failed. p_pkt is not altered.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_AddUtf8DestNameHdr(BT_HDR *p_pkt, UINT8 *p_dest);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadUtf8NameHdr
-**
-** Description  This function is called to get the Name Header in the given
-**              OBEX packet. If Name header exists in the given OBEX packet,
-**              it is converted to UTF8 format and copied into p_name.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadUtf8NameHdr(BT_HDR *p_pkt, UINT8 *p_name, UINT16 max_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadUtf8DescrHdr
-**
-** Description  This function is called to get the Description Header in the
-**              given OBEX packet. If Description header exists in the given
-**              OBEX packet, it is converted to UTF8 format and copied into
-**              p_descr.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadUtf8DescrHdr(BT_HDR *p_pkt, UINT8 *p_descr, UINT16 max_len);
-
-/*******************************************************************************
-**
-** Function     OBX_ReadUtf8DestNameHdr
-**
-** Description  This function is called to get the DestName Header in the
-**              given OBEX packet.
-**
-** Returns      TRUE, if the header is in the OBEX packet.
-**              FALSE, otherwise.
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_ReadUtf8DestNameHdr(BT_HDR *p_pkt, UINT8 *p_dest, UINT16 max_len);
-
-/*******************************************************************************
-**
-** Function     OBX_VerifyResponse
-**
-** Description  This function is called by the client to verify the challenge
-**              response.
-**
-** Returns      TRUE, if successful.
-**              FALSE, if authentication failed
-**
-*******************************************************************************/
-OBX_API extern BOOLEAN OBX_VerifyResponse(UINT32 nonce_u32, UINT8 *p_password, UINT8 password_len, UINT8 *p_response);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* OBX_API_H */
diff --git a/stack/include/pan_api.h b/stack/include/pan_api.h
index a604463..17826b5 100644
--- a/stack/include/pan_api.h
+++ b/stack/include/pan_api.h
@@ -236,7 +236,7 @@
 ** Returns          none
 **
 *******************************************************************************/
-PAN_API extern void PAN_Register (tPAN_REGISTER *p_register);
+extern void PAN_Register (tPAN_REGISTER *p_register);
 
 
 /*******************************************************************************
@@ -251,7 +251,7 @@
 ** Returns          none
 **
 *******************************************************************************/
-PAN_API extern void PAN_Deregister (void);
+extern void PAN_Deregister (void);
 
 /*******************************************************************************
 **
@@ -277,11 +277,11 @@
 **                  PAN_FAILURE     - if the role is not valid
 **
 *******************************************************************************/
-PAN_API extern tPAN_RESULT PAN_SetRole (UINT8 role,
-                                       UINT8 *sec_mask,
-                                       char *p_user_name,
-                                       char *p_gn_name,
-                                       char *p_nap_name);
+extern tPAN_RESULT PAN_SetRole (UINT8 role,
+                                UINT8 *sec_mask,
+                                char *p_user_name,
+                                char *p_gn_name,
+                                char *p_nap_name);
 
 /*******************************************************************************
 **
@@ -306,7 +306,7 @@
 **                                           allowed at that point of time
 **
 *******************************************************************************/
-PAN_API extern tPAN_RESULT PAN_Connect (BD_ADDR rem_bda, UINT8 src_role, UINT8 dst_role, UINT16 *handle);
+extern tPAN_RESULT PAN_Connect (BD_ADDR rem_bda, UINT8 src_role, UINT8 dst_role, UINT16 *handle);
 
 /*******************************************************************************
 **
@@ -321,7 +321,7 @@
 **                                           there is an error in disconnecting
 **
 *******************************************************************************/
-PAN_API extern tPAN_RESULT PAN_Disconnect (UINT16 handle);
+extern tPAN_RESULT PAN_Disconnect (UINT16 handle);
 
 /*******************************************************************************
 **
@@ -346,13 +346,13 @@
 **                                           there is an error in sending data
 **
 *******************************************************************************/
-PAN_API extern tPAN_RESULT PAN_Write (UINT16 handle,
-                                     BD_ADDR dst,
-                                     BD_ADDR src,
-                                     UINT16 protocol,
-                                     UINT8 *p_data,
-                                     UINT16 len,
-                                     BOOLEAN ext);
+extern tPAN_RESULT PAN_Write (UINT16 handle,
+                              BD_ADDR dst,
+                              BD_ADDR src,
+                              UINT16 protocol,
+                              UINT8 *p_data,
+                              UINT16 len,
+                              BOOLEAN ext);
 
 /*******************************************************************************
 **
@@ -376,12 +376,12 @@
 **                                           there is an error in sending data
 **
 *******************************************************************************/
-PAN_API extern tPAN_RESULT PAN_WriteBuf (UINT16 handle,
-                                        BD_ADDR dst,
-                                        BD_ADDR src,
-                                        UINT16 protocol,
-                                        BT_HDR *p_buf,
-                                        BOOLEAN ext);
+extern tPAN_RESULT PAN_WriteBuf (UINT16 handle,
+                                 BD_ADDR dst,
+                                 BD_ADDR src,
+                                 UINT16 protocol,
+                                 BT_HDR *p_buf,
+                                 BOOLEAN ext);
 
 /*******************************************************************************
 **
@@ -399,10 +399,10 @@
 **                  PAN_FAILURE        if connection not found or error in setting
 **
 *******************************************************************************/
-PAN_API extern tPAN_RESULT PAN_SetProtocolFilters (UINT16 handle,
-                                                  UINT16 num_filters,
-                                                  UINT16 *p_start_array,
-                                                  UINT16 *p_end_array);
+extern tPAN_RESULT PAN_SetProtocolFilters (UINT16 handle,
+                                           UINT16 num_filters,
+                                           UINT16 *p_start_array,
+                                           UINT16 *p_end_array);
 
 /*******************************************************************************
 **
@@ -422,10 +422,10 @@
 **                  PAN_FAILURE        if connection not found or error in setting
 **
 *******************************************************************************/
-PAN_API extern tBNEP_RESULT PAN_SetMulticastFilters (UINT16 handle,
-                                                    UINT16 num_mcast_filters,
-                                                    UINT8 *p_start_array,
-                                                    UINT8 *p_end_array);
+extern tBNEP_RESULT PAN_SetMulticastFilters (UINT16 handle,
+                                             UINT16 num_mcast_filters,
+                                             UINT8 *p_start_array,
+                                             UINT8 *p_end_array);
 
 /*******************************************************************************
 **
@@ -437,7 +437,7 @@
 ** Returns          the new (current) trace level
 **
 *******************************************************************************/
-PAN_API extern UINT8 PAN_SetTraceLevel (UINT8 new_level);
+extern UINT8 PAN_SetTraceLevel (UINT8 new_level);
 
 /*******************************************************************************
 **
@@ -450,7 +450,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-PAN_API extern void PAN_Init (void);
+extern void PAN_Init (void);
 
 #ifdef __cplusplus
 }
diff --git a/stack/include/port_api.h b/stack/include/port_api.h
index 050ee52..f24887b 100644
--- a/stack/include/port_api.h
+++ b/stack/include/port_api.h
@@ -175,6 +175,7 @@
 #define PORT_PAGE_TIMEOUT           (PORT_ERR_BASE + 24)
 #define PORT_INVALID_SCN            (PORT_ERR_BASE + 25)
 
+#define PORT_ERR_MAX                (PORT_ERR_BASE + 26)
 
 /*****************************************************************************
 **  External Function Declarations
@@ -215,7 +216,7 @@
 ** (scn * 2 + 1) dlci.
 **
 *******************************************************************************/
-RFC_API extern int RFCOMM_CreateConnection (UINT16 uuid, UINT8 scn,
+extern int RFCOMM_CreateConnection (UINT16 uuid, UINT8 scn,
                                             BOOLEAN is_server, UINT16 mtu,
                                             BD_ADDR bd_addr, UINT16 *p_handle,
                                             tPORT_CALLBACK *p_mgmt_cb);
@@ -230,7 +231,7 @@
 ** Parameters:      handle     - Handle of the port returned in the Open
 **
 *******************************************************************************/
-RFC_API extern int RFCOMM_RemoveConnection (UINT16 handle);
+extern int RFCOMM_RemoveConnection (UINT16 handle);
 
 
 /*******************************************************************************
@@ -242,7 +243,7 @@
 ** Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
 **
 *******************************************************************************/
-RFC_API extern int RFCOMM_RemoveServer (UINT16 handle);
+extern int RFCOMM_RemoveServer (UINT16 handle);
 
 
 /*******************************************************************************
@@ -257,8 +258,8 @@
 **                                 specified in the mask occurs.
 **
 *******************************************************************************/
-RFC_API extern int PORT_SetEventCallback (UINT16 port_handle,
-                                          tPORT_CALLBACK *p_port_cb);
+extern int PORT_SetEventCallback (UINT16 port_handle,
+                                  tPORT_CALLBACK *p_port_cb);
 
 /*******************************************************************************
 **
@@ -283,10 +284,10 @@
 **                                 packet is received.
 **
 *******************************************************************************/
-RFC_API extern int PORT_SetDataCallback (UINT16 port_handle,
-                                         tPORT_DATA_CALLBACK *p_cb);
+extern int PORT_SetDataCallback (UINT16 port_handle,
+                                 tPORT_DATA_CALLBACK *p_cb);
 
-RFC_API extern int PORT_SetDataCOCallback (UINT16 port_handle, tPORT_DATA_CO_CALLBACK *p_port_cb);
+extern int PORT_SetDataCOCallback (UINT16 port_handle, tPORT_DATA_CO_CALLBACK *p_port_cb);
 /*******************************************************************************
 **
 ** Function         PORT_SetEventMask
@@ -298,7 +299,7 @@
 **                           of zero disables all events.
 **
 *******************************************************************************/
-RFC_API extern int PORT_SetEventMask (UINT16 port_handle, UINT32 mask);
+extern int PORT_SetEventMask (UINT16 port_handle, UINT32 mask);
 
 
 /*******************************************************************************
@@ -313,8 +314,8 @@
 **                  p_lcid     - OUT L2CAP's LCID
 **
 *******************************************************************************/
-RFC_API extern int PORT_CheckConnection (UINT16 handle, BD_ADDR bd_addr,
-                                         UINT16 *p_lcid);
+extern int PORT_CheckConnection (UINT16 handle, BD_ADDR bd_addr,
+                                 UINT16 *p_lcid);
 
 /*******************************************************************************
 **
@@ -327,7 +328,7 @@
 **                  bd_addr    - bd_addr of the peer
 **
 *******************************************************************************/
-RFC_API extern BOOLEAN PORT_IsOpening (BD_ADDR bd_addr);
+extern BOOLEAN PORT_IsOpening (BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -341,7 +342,7 @@
 **                               configuration information for the connection.
 **
 *******************************************************************************/
-RFC_API extern int PORT_SetState (UINT16 handle, tPORT_STATE *p_settings);
+extern int PORT_SetState (UINT16 handle, tPORT_STATE *p_settings);
 
 /*******************************************************************************
 **
@@ -353,7 +354,7 @@
 **                  p_rx_queue_count - Pointer to return queue count in.
 **
 *******************************************************************************/
-RFC_API extern int PORT_GetRxQueueCnt (UINT16 handle, UINT16 *p_rx_queue_count);
+extern int PORT_GetRxQueueCnt (UINT16 handle, UINT16 *p_rx_queue_count);
 
 /*******************************************************************************
 **
@@ -367,7 +368,7 @@
 **                               configuration information is returned.
 **
 *******************************************************************************/
-RFC_API extern int PORT_GetState (UINT16 handle, tPORT_STATE *p_settings);
+extern int PORT_GetState (UINT16 handle, tPORT_STATE *p_settings);
 
 
 /*******************************************************************************
@@ -391,7 +392,7 @@
 #define PORT_CLR_DCD            0x08        /* DCE only */
 #define PORT_BREAK              0x09        /* Break event */
 
-RFC_API extern int PORT_Control (UINT16 handle, UINT8 signal);
+extern int PORT_Control (UINT16 handle, UINT8 signal);
 
 
 /*******************************************************************************
@@ -406,7 +407,7 @@
 **                  enable     - enables data flow
 **
 *******************************************************************************/
-RFC_API extern int PORT_FlowControl (UINT16 handle, BOOLEAN enable);
+extern int PORT_FlowControl (UINT16 handle, BOOLEAN enable);
 
 
 /*******************************************************************************
@@ -436,7 +437,7 @@
 #define PORT_PPP_DEFAULT_SIGNAL_STATE   (PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON)
 #define PORT_DUN_DEFAULT_SIGNAL_STATE   (PORT_DTRDSR_ON | PORT_CTSRTS_ON)
 
-RFC_API extern int PORT_GetModemStatus (UINT16 handle, UINT8 *p_control_signal);
+extern int PORT_GetModemStatus (UINT16 handle, UINT8 *p_control_signal);
 
 
 /*******************************************************************************
@@ -475,8 +476,8 @@
 } tPORT_STATUS;
 
 
-RFC_API extern int PORT_ClearError (UINT16 handle, UINT16 *p_errors,
-                                    tPORT_STATUS *p_status);
+extern int PORT_ClearError (UINT16 handle, UINT16 *p_errors,
+                            tPORT_STATUS *p_status);
 
 
 /*******************************************************************************
@@ -489,7 +490,7 @@
 **                  errors     - receive error codes
 **
 *******************************************************************************/
-RFC_API extern int PORT_SendError (UINT16 handle, UINT8 errors);
+extern int PORT_SendError (UINT16 handle, UINT8 errors);
 
 
 /*******************************************************************************
@@ -503,7 +504,7 @@
 **                               connection status
 **
 *******************************************************************************/
-RFC_API extern int PORT_GetQueueStatus (UINT16 handle, tPORT_STATUS *p_status);
+extern int PORT_GetQueueStatus (UINT16 handle, tPORT_STATUS *p_status);
 
 
 /*******************************************************************************
@@ -520,7 +521,7 @@
 #define PORT_PURGE_TXCLEAR  0x01
 #define PORT_PURGE_RXCLEAR  0x02
 
-RFC_API extern int PORT_Purge (UINT16 handle, UINT8 purge_flags);
+extern int PORT_Purge (UINT16 handle, UINT8 purge_flags);
 
 
 /*******************************************************************************
@@ -538,7 +539,7 @@
 **                  pp_buf      - pointer to address of buffer with data,
 **
 *******************************************************************************/
-RFC_API extern int PORT_Read (UINT16 handle, BT_HDR **pp_buf);
+extern int PORT_Read (UINT16 handle, BT_HDR **pp_buf);
 
 
 /*******************************************************************************
@@ -555,8 +556,8 @@
 **                  p_len       - Byte count received
 **
 *******************************************************************************/
-RFC_API extern int PORT_ReadData (UINT16 handle, char *p_data, UINT16 max_len,
-                                  UINT16 *p_len);
+extern int PORT_ReadData (UINT16 handle, char *p_data, UINT16 max_len,
+                          UINT16 *p_len);
 
 
 /*******************************************************************************
@@ -570,7 +571,7 @@
 **                  p_buf       - pointer to the buffer with data,
 **
 *******************************************************************************/
-RFC_API extern int PORT_Write (UINT16 handle, BT_HDR *p_buf);
+extern int PORT_Write (UINT16 handle, BT_HDR *p_buf);
 
 
 /*******************************************************************************
@@ -586,8 +587,8 @@
 **                  p_len       - Bytes written
 **
 *******************************************************************************/
-RFC_API extern int PORT_WriteData (UINT16 handle, char *p_data, UINT16 max_len,
-                                   UINT16 *p_len);
+extern int PORT_WriteData (UINT16 handle, char *p_data, UINT16 max_len,
+                           UINT16 *p_len);
 
 /*******************************************************************************
 **
@@ -599,7 +600,7 @@
 ** Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
 **
 *******************************************************************************/
-RFC_API extern int PORT_WriteDataCO (UINT16 handle, int* p_len);
+extern int PORT_WriteDataCO (UINT16 handle, int* p_len);
 
 /*******************************************************************************
 **
@@ -612,7 +613,7 @@
 **                  max_len     - Byte count requested
 **
 *******************************************************************************/
-RFC_API extern int PORT_Test (UINT16 handle, UINT8 *p_data, UINT16 len);
+extern int PORT_Test (UINT16 handle, UINT8 *p_data, UINT16 len);
 
 
 /*******************************************************************************
@@ -622,7 +623,7 @@
 ** Description      This function is called to initialize RFCOMM layer
 **
 *******************************************************************************/
-RFC_API extern void RFCOMM_Init (void);
+extern void RFCOMM_Init (void);
 
 
 /*******************************************************************************
@@ -635,9 +636,22 @@
 ** Returns          the new (current) trace level
 **
 *******************************************************************************/
-RFC_API extern UINT8 PORT_SetTraceLevel (UINT8 new_level);
+extern UINT8 PORT_SetTraceLevel (UINT8 new_level);
 
 
+/*******************************************************************************
+**
+** Function         PORT_GetResultString
+**
+** Description      This function returns the human-readable string for a given
+**                  result code.
+**
+** Returns          a pointer to the human-readable string for the given
+**                  result. Note that the string returned must not be freed.
+**
+*******************************************************************************/
+extern const char *PORT_GetResultString (const uint8_t result_code);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/stack/include/sdp_api.h b/stack/include/sdp_api.h
index dcc813e..ff44bf5 100644
--- a/stack/include/sdp_api.h
+++ b/stack/include/sdp_api.h
@@ -49,11 +49,6 @@
 #define  SDP_CONN_REJECTED                  0xFFF7
 #define  SDP_CANCEL                         0xFFF8
 
-/* these result codes are used only when SDP_FOR_JV_INCLUDED==TRUE */
-#define  SDP_EVT_OPEN                       0x00F0 /* connected */
-#define  SDP_EVT_DATA_IND                   0x00F1 /* data ind */
-#define  SDP_EVT_CLOSE                      0x00F2 /* disconnected */
-
 /* Define the PSM that SDP uses */
 #define SDP_PSM     0x0001
 
@@ -201,11 +196,11 @@
 ** Returns          TRUE if successful, FALSE if one or more parameters are bad
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_InitDiscoveryDb (tSDP_DISCOVERY_DB *p_db, UINT32 len,
-                                            UINT16 num_uuid,
-                                            tSDP_UUID *p_uuid_list,
-                                            UINT16 num_attr,
-                                            UINT16 *p_attr_list);
+extern BOOLEAN SDP_InitDiscoveryDb (tSDP_DISCOVERY_DB *p_db, UINT32 len,
+                                    UINT16 num_uuid,
+                                    tSDP_UUID *p_uuid_list,
+                                    UINT16 num_attr,
+                                    UINT16 *p_attr_list);
 
 /*******************************************************************************
 **
@@ -216,7 +211,7 @@
 ** Returns          TRUE if discovery cancelled, FALSE if a matching activity is not found.
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_CancelServiceSearch (tSDP_DISCOVERY_DB *p_db);
+extern BOOLEAN SDP_CancelServiceSearch (tSDP_DISCOVERY_DB *p_db);
 
 /*******************************************************************************
 **
@@ -227,9 +222,9 @@
 ** Returns          TRUE if discovery started, FALSE if failed.
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_ServiceSearchRequest (UINT8 *p_bd_addr,
-                                                 tSDP_DISCOVERY_DB *p_db,
-                                                 tSDP_DISC_CMPL_CB *p_cb);
+extern BOOLEAN SDP_ServiceSearchRequest (UINT8 *p_bd_addr,
+                                         tSDP_DISCOVERY_DB *p_db,
+                                         tSDP_DISC_CMPL_CB *p_cb);
 
 
 /*******************************************************************************
@@ -245,9 +240,9 @@
 ** Returns          TRUE if discovery started, FALSE if failed.
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_ServiceSearchAttributeRequest (UINT8 *p_bd_addr,
-                                                          tSDP_DISCOVERY_DB *p_db,
-                                                          tSDP_DISC_CMPL_CB *p_cb);
+extern BOOLEAN SDP_ServiceSearchAttributeRequest (UINT8 *p_bd_addr,
+                                                  tSDP_DISCOVERY_DB *p_db,
+                                                  tSDP_DISC_CMPL_CB *p_cb);
 
 /*******************************************************************************
 **
@@ -263,9 +258,9 @@
 ** Returns          TRUE if discovery started, FALSE if failed.
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_ServiceSearchAttributeRequest2 (UINT8 *p_bd_addr,
-                                                          tSDP_DISCOVERY_DB *p_db,
-                                                          tSDP_DISC_CMPL_CB2 *p_cb, void * user_data);
+extern BOOLEAN SDP_ServiceSearchAttributeRequest2 (UINT8 *p_bd_addr,
+                                                   tSDP_DISCOVERY_DB *p_db,
+                                                   tSDP_DISC_CMPL_CB2 *p_cb, void * user_data);
 
 /* API of utilities to find data in the local discovery database */
 
@@ -281,9 +276,9 @@
 ** Returns          Pointer to matching record, or NULL
 **
 *******************************************************************************/
-SDP_API extern tSDP_DISC_REC *SDP_FindAttributeInDb (tSDP_DISCOVERY_DB *p_db,
-                                                     UINT16 attr_id,
-                                                     tSDP_DISC_REC *p_start_rec);
+extern tSDP_DISC_REC *SDP_FindAttributeInDb (tSDP_DISCOVERY_DB *p_db,
+                                             UINT16 attr_id,
+                                             tSDP_DISC_REC *p_start_rec);
 
 
 /*******************************************************************************
@@ -296,8 +291,8 @@
 ** Returns          Pointer to matching attribute entry, or NULL
 **
 *******************************************************************************/
-SDP_API extern tSDP_DISC_ATTR *SDP_FindAttributeInRec (tSDP_DISC_REC *p_rec,
-                                                       UINT16 attr_id);
+extern tSDP_DISC_ATTR *SDP_FindAttributeInRec (tSDP_DISC_REC *p_rec,
+                                               UINT16 attr_id);
 
 
 /*******************************************************************************
@@ -312,9 +307,9 @@
 ** Returns          Pointer to record containing service class, or NULL
 **
 *******************************************************************************/
-SDP_API extern tSDP_DISC_REC *SDP_FindServiceInDb (tSDP_DISCOVERY_DB *p_db,
-                                                   UINT16 service_uuid,
-                                                   tSDP_DISC_REC *p_start_rec);
+extern tSDP_DISC_REC *SDP_FindServiceInDb (tSDP_DISCOVERY_DB *p_db,
+                                           UINT16 service_uuid,
+                                           tSDP_DISC_REC *p_start_rec);
 
 
 /*******************************************************************************
@@ -333,9 +328,9 @@
 ** Returns          Pointer to record containing service class, or NULL
 **
 *******************************************************************************/
-SDP_API extern tSDP_DISC_REC *SDP_FindServiceUUIDInDb (tSDP_DISCOVERY_DB *p_db,
-                                                       tBT_UUID *p_uuid,
-                                                       tSDP_DISC_REC *p_start_rec);
+extern tSDP_DISC_REC *SDP_FindServiceUUIDInDb (tSDP_DISCOVERY_DB *p_db,
+                                               tBT_UUID *p_uuid,
+                                               tSDP_DISC_REC *p_start_rec);
 
 /*******************************************************************************
 **
@@ -350,7 +345,7 @@
 ** Returns          TRUE if found, otherwise FALSE.
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_FindServiceUUIDInRec_128bit(tSDP_DISC_REC *p_rec, tBT_UUID * p_uuid);
+extern BOOLEAN SDP_FindServiceUUIDInRec_128bit(tSDP_DISC_REC *p_rec, tBT_UUID * p_uuid);
 
 /*******************************************************************************
 **
@@ -364,8 +359,8 @@
 ** Returns          Pointer to record containing service class, or NULL
 **
 *******************************************************************************/
-SDP_API extern tSDP_DISC_REC *SDP_FindServiceInDb_128bit(tSDP_DISCOVERY_DB *p_db,
-                                                       tSDP_DISC_REC *p_start_rec);
+extern tSDP_DISC_REC *SDP_FindServiceInDb_128bit(tSDP_DISCOVERY_DB *p_db,
+                                                 tSDP_DISC_REC *p_start_rec);
 
 /*******************************************************************************
 **
@@ -378,9 +373,9 @@
 **                  If found, the passed protocol list element is filled in.
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_FindProtocolListElemInRec (tSDP_DISC_REC *p_rec,
-                                                      UINT16 layer_uuid,
-                                                      tSDP_PROTOCOL_ELEM *p_elem);
+extern BOOLEAN SDP_FindProtocolListElemInRec (tSDP_DISC_REC *p_rec,
+                                              UINT16 layer_uuid,
+                                              tSDP_PROTOCOL_ELEM *p_elem);
 
 
 /*******************************************************************************
@@ -394,9 +389,9 @@
 **                  If found, the passed protocol list element is filled in.
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_FindAddProtoListsElemInRec (tSDP_DISC_REC *p_rec,
-                                                       UINT16 layer_uuid,
-                                                       tSDP_PROTOCOL_ELEM *p_elem);
+extern BOOLEAN SDP_FindAddProtoListsElemInRec (tSDP_DISC_REC *p_rec,
+                                               UINT16 layer_uuid,
+                                               tSDP_PROTOCOL_ELEM *p_elem);
 
 
 /*******************************************************************************
@@ -413,9 +408,9 @@
 **                  in are filled in.
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_FindProfileVersionInRec (tSDP_DISC_REC *p_rec,
-                                                    UINT16 profile_uuid,
-                                                    UINT16 *p_version);
+extern BOOLEAN SDP_FindProfileVersionInRec (tSDP_DISC_REC *p_rec,
+                                            UINT16 profile_uuid,
+                                            UINT16 *p_version);
 
 
 /* API into SDP for local service database updates */
@@ -432,7 +427,7 @@
 ** Returns          Record handle if OK, else 0.
 **
 *******************************************************************************/
-SDP_API extern UINT32 SDP_CreateRecord (void);
+extern UINT32 SDP_CreateRecord (void);
 
 
 /*******************************************************************************
@@ -448,7 +443,7 @@
 ** Returns          TRUE if succeeded, else FALSE
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_DeleteRecord (UINT32 handle);
+extern BOOLEAN SDP_DeleteRecord (UINT32 handle);
 
 
 /*******************************************************************************
@@ -464,7 +459,7 @@
 **                  The size of data copied into p_data is in *p_data_len.
 **
 *******************************************************************************/
-SDP_API extern INT32 SDP_ReadRecord(UINT32 handle, UINT8 *p_data, INT32 *p_data_len);
+extern INT32 SDP_ReadRecord(UINT32 handle, UINT8 *p_data, INT32 *p_data_len);
 
 /*******************************************************************************
 **
@@ -480,9 +475,9 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_AddAttribute (UINT32 handle, UINT16 attr_id,
-                                         UINT8 attr_type, UINT32 attr_len,
-                                         UINT8 *p_val);
+extern BOOLEAN SDP_AddAttribute (UINT32 handle, UINT16 attr_id,
+                                 UINT8 attr_type, UINT32 attr_len,
+                                 UINT8 *p_val);
 
 
 /*******************************************************************************
@@ -499,9 +494,9 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_AddSequence (UINT32 handle,  UINT16 attr_id,
-                                        UINT16 num_elem, UINT8 type[],
-                                        UINT8 len[], UINT8 *p_val[]);
+extern BOOLEAN SDP_AddSequence (UINT32 handle,  UINT16 attr_id,
+                                UINT16 num_elem, UINT8 type[],
+                                UINT8 len[], UINT8 *p_val[]);
 
 
 /*******************************************************************************
@@ -516,8 +511,8 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_AddUuidSequence (UINT32 handle,  UINT16 attr_id,
-                                            UINT16 num_uuids, UINT16 *p_uuids);
+extern BOOLEAN SDP_AddUuidSequence (UINT32 handle,  UINT16 attr_id,
+                                    UINT16 num_uuids, UINT16 *p_uuids);
 
 
 /*******************************************************************************
@@ -532,8 +527,8 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_AddProtocolList (UINT32 handle, UINT16 num_elem,
-                                            tSDP_PROTOCOL_ELEM *p_elem_list);
+extern BOOLEAN SDP_AddProtocolList (UINT32 handle, UINT16 num_elem,
+                                    tSDP_PROTOCOL_ELEM *p_elem_list);
 
 
 /*******************************************************************************
@@ -548,8 +543,8 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_AddAdditionProtoLists (UINT32 handle, UINT16 num_elem,
-                                                  tSDP_PROTO_LIST_ELEM *p_proto_list);
+extern BOOLEAN SDP_AddAdditionProtoLists (UINT32 handle, UINT16 num_elem,
+                                          tSDP_PROTO_LIST_ELEM *p_proto_list);
 
 
 /*******************************************************************************
@@ -564,9 +559,9 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_AddProfileDescriptorList (UINT32 handle,
-                                                     UINT16 profile_uuid,
-                                                     UINT16 version);
+extern BOOLEAN SDP_AddProfileDescriptorList (UINT32 handle,
+                                             UINT16 profile_uuid,
+                                             UINT16 version);
 
 
 /*******************************************************************************
@@ -581,9 +576,9 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_AddLanguageBaseAttrIDList (UINT32 handle,
-                                                      UINT16 lang, UINT16 char_enc,
-                                                      UINT16 base_id);
+extern BOOLEAN SDP_AddLanguageBaseAttrIDList (UINT32 handle,
+                                              UINT16 lang, UINT16 char_enc,
+                                              UINT16 base_id);
 
 
 /*******************************************************************************
@@ -598,9 +593,9 @@
 ** Returns          TRUE if added OK, else FALSE
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_AddServiceClassIdList (UINT32 handle,
-                                                  UINT16 num_services,
-                                                  UINT16 *p_service_uuids);
+extern BOOLEAN SDP_AddServiceClassIdList (UINT32 handle,
+                                          UINT16 num_services,
+                                          UINT16 *p_service_uuids);
 
 
 /*******************************************************************************
@@ -613,7 +608,7 @@
 ** Returns          TRUE if deleted OK, else FALSE if not found
 **
 *******************************************************************************/
-SDP_API extern BOOLEAN SDP_DeleteAttribute (UINT32 handle, UINT16 attr_id);
+extern BOOLEAN SDP_DeleteAttribute (UINT32 handle, UINT16 attr_id);
 
 
 /* Device Identification APIs */
@@ -627,23 +622,8 @@
 ** Returns          Returns SDP_SUCCESS if record added successfully, else error
 **
 *******************************************************************************/
-SDP_API extern UINT16 SDP_SetLocalDiRecord (tSDP_DI_RECORD *device_info,
-                                            UINT32 *p_handle);
-
-/*******************************************************************************
-**
-** Function         SDP_GetLocalDiRecord
-**
-** Description      This function adds a DI record to the local SDP database.
-**
-**                  Fills in the device information of the record
-**                  p_handle - if p_handle == NULL, the primary record is returned
-**
-** Returns          Returns SDP_SUCCESS if record exists, else error
-**
-*******************************************************************************/
-SDP_API extern UINT16 SDP_GetLocalDiRecord(tSDP_DI_GET_RECORD *p_device_info,
-                                           UINT32 *p_handle );
+extern UINT16 SDP_SetLocalDiRecord (tSDP_DI_RECORD *device_info,
+                                    UINT32 *p_handle);
 
 /*******************************************************************************
 **
@@ -654,9 +634,9 @@
 ** Returns          SDP_SUCCESS if query started successfully, else error
 **
 *******************************************************************************/
-SDP_API extern UINT16 SDP_DiDiscover (BD_ADDR remote_device,
-                                      tSDP_DISCOVERY_DB *p_db, UINT32 len,
-                                      tSDP_DISC_CMPL_CB *p_cb);
+extern UINT16 SDP_DiDiscover (BD_ADDR remote_device,
+                              tSDP_DISCOVERY_DB *p_db, UINT32 len,
+                              tSDP_DISC_CMPL_CB *p_cb);
 
 
 /*******************************************************************************
@@ -668,7 +648,7 @@
 ** Returns          number of DI records found
 **
 *******************************************************************************/
-SDP_API extern UINT8  SDP_GetNumDiRecords (tSDP_DISCOVERY_DB *p_db);
+extern UINT8  SDP_GetNumDiRecords (tSDP_DISCOVERY_DB *p_db);
 
 
 /*******************************************************************************
@@ -681,9 +661,9 @@
 ** Returns          SDP_SUCCESS if record retrieved, else error
 **
 *******************************************************************************/
-SDP_API extern UINT16 SDP_GetDiRecord (UINT8 getRecordIndex,
-                                       tSDP_DI_GET_RECORD *device_info,
-                                       tSDP_DISCOVERY_DB *p_db);
+extern UINT16 SDP_GetDiRecord (UINT8 getRecordIndex,
+                               tSDP_DI_GET_RECORD *device_info,
+                               tSDP_DISCOVERY_DB *p_db);
 
 
 /*******************************************************************************
@@ -696,7 +676,7 @@
 ** Returns          the new (current) trace level
 **
 *******************************************************************************/
-SDP_API extern UINT8 SDP_SetTraceLevel (UINT8 new_level);
+extern UINT8 SDP_SetTraceLevel (UINT8 new_level);
 
 /*******************************************************************************
 **
@@ -708,8 +688,8 @@
 ** Returns          0, if failed to initiate connection. Otherwise, the handle.
 **
 *******************************************************************************/
-SDP_API UINT32 SDP_ConnOpen (UINT8 *p_bd_addr, tSDP_DISC_RES_CB *p_rcb,
-                                  tSDP_DISC_CMPL_CB *p_cb);
+UINT32 SDP_ConnOpen (UINT8 *p_bd_addr, tSDP_DISC_RES_CB *p_rcb,
+                     tSDP_DISC_CMPL_CB *p_cb);
 
 /*******************************************************************************
 **
@@ -720,7 +700,7 @@
 ** Returns          TRUE if data is sent, FALSE if failed.
 **
 *******************************************************************************/
-SDP_API BOOLEAN SDP_WriteData (UINT32 handle, BT_HDR  *p_msg);
+BOOLEAN SDP_WriteData (UINT32 handle, BT_HDR  *p_msg);
 
 /*******************************************************************************
 **
@@ -733,7 +713,7 @@
 ** Returns          TRUE if connection is closed, FALSE if failed to find the handle.
 **
 *******************************************************************************/
-SDP_API BOOLEAN SDP_ConnClose (UINT32 handle);
+BOOLEAN SDP_ConnClose (UINT32 handle);
 
 /*******************************************************************************
 **
@@ -747,7 +727,7 @@
 ** Returns          TRUE if found, otherwise FALSE.
 **
 *******************************************************************************/
-SDP_API BOOLEAN SDP_FindServiceUUIDInRec(tSDP_DISC_REC *p_rec, tBT_UUID *p_uuid);
+BOOLEAN SDP_FindServiceUUIDInRec(tSDP_DISC_REC *p_rec, tBT_UUID *p_uuid);
 
 #ifdef __cplusplus
 }
diff --git a/stack/include/sdpdefs.h b/stack/include/sdpdefs.h
index fcd4a5e..22d87c1 100644
--- a/stack/include/sdpdefs.h
+++ b/stack/include/sdpdefs.h
@@ -146,12 +146,6 @@
 #define  ATTR_ID_HDP_DATA_EXCH_SPEC         0x0301  /* Data exchange specification */
 #define  ATTR_ID_HDP_MCAP_SUP_PROC          0x0302  /* MCAP supported procedures */
 
-/* a temporary value for IOP */
-#ifndef ATTR_ID_OBX_OVR_L2CAP_PSM
-#define  ATTR_ID_OBX_OVR_L2CAP_PSM          0x0200
-#endif
-
-
 /* Define common 16-bit protocol UUIDs
 */
 #define UUID_PROTOCOL_SDP                    0x0001
diff --git a/stack/include/smp_api.h b/stack/include/smp_api.h
index e47cce3..79d1d6f 100644
--- a/stack/include/smp_api.h
+++ b/stack/include/smp_api.h
@@ -184,7 +184,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    SMP_API extern void SMP_Init(void);
+extern void SMP_Init(void);
 
 /*******************************************************************************
 **
@@ -196,7 +196,7 @@
 ** Returns          The new or current trace level
 **
 *******************************************************************************/
-    SMP_API extern UINT8 SMP_SetTraceLevel (UINT8 new_level);
+extern UINT8 SMP_SetTraceLevel (UINT8 new_level);
 
 /*******************************************************************************
 **
@@ -207,7 +207,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-    SMP_API extern BOOLEAN SMP_Register (tSMP_CALLBACK *p_cback);
+extern BOOLEAN SMP_Register (tSMP_CALLBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -218,7 +218,7 @@
 ** Returns          SMP_STARTED if bond started, else otherwise exception.
 **
 *******************************************************************************/
-    SMP_API extern tSMP_STATUS SMP_Pair (BD_ADDR bd_addr);
+extern tSMP_STATUS SMP_Pair (BD_ADDR bd_addr);
 /*******************************************************************************
 **
 ** Function         SMP_PairCancel
@@ -228,7 +228,7 @@
 ** Returns          TRUE - pairing cancelled
 **
 *******************************************************************************/
-    SMP_API extern  BOOLEAN SMP_PairCancel (BD_ADDR bd_addr);
+extern  BOOLEAN SMP_PairCancel (BD_ADDR bd_addr);
 
 /*******************************************************************************
 **
@@ -243,7 +243,7 @@
 ** Returns          None
 **
 *******************************************************************************/
-    SMP_API extern void SMP_SecurityGrant(BD_ADDR bd_addr, UINT8 res);
+extern void SMP_SecurityGrant(BD_ADDR bd_addr, UINT8 res);
 
 /*******************************************************************************
 **
@@ -258,7 +258,7 @@
 **                  BTM_MIN_PASSKEY_VAL(0) - BTM_MAX_PASSKEY_VAL(999999(0xF423F)).
 **
 *******************************************************************************/
-    SMP_API extern void SMP_PasskeyReply (BD_ADDR bd_addr, UINT8 res, UINT32 passkey);
+extern void SMP_PasskeyReply (BD_ADDR bd_addr, UINT8 res, UINT32 passkey);
 
 /*******************************************************************************
 **
@@ -272,8 +272,8 @@
 **                  p_data      - simple pairing Randomizer  C.
 **
 *******************************************************************************/
-    SMP_API extern void SMP_OobDataReply(BD_ADDR bd_addr, tSMP_STATUS res, UINT8 len,
-                                         UINT8 *p_data);
+extern void SMP_OobDataReply(BD_ADDR bd_addr, tSMP_STATUS res, UINT8 len,
+                             UINT8 *p_data);
 
 /*******************************************************************************
 **
@@ -291,9 +291,9 @@
 **
 **  Returns         Boolean - TRUE: encryption is successful
 *******************************************************************************/
-    SMP_API extern BOOLEAN SMP_Encrypt (UINT8 *key, UINT8 key_len,
-                                        UINT8 *plain_text, UINT8 pt_len,
-                                        tSMP_ENC *p_out);
+extern BOOLEAN SMP_Encrypt (UINT8 *key, UINT8 key_len,
+                            UINT8 *plain_text, UINT8 pt_len,
+                            tSMP_ENC *p_out);
 
 #ifdef __cplusplus
 }
diff --git a/stack/include/srvc_api.h b/stack/include/srvc_api.h
index d04964a..09c5b3e 100644
--- a/stack/include/srvc_api.h
+++ b/stack/include/srvc_api.h
@@ -141,7 +141,7 @@
 **                  as for a central service management.
 **
 *******************************************************************************/
-    GATT_API extern tGATT_STATUS srvc_eng_init (void);
+extern tGATT_STATUS srvc_eng_init (void);
 
 
 /*****************************************************************************
@@ -155,7 +155,7 @@
 ** Description      Initializa the Device Information Service Server.
 **
 *******************************************************************************/
-    GATT_API extern tDIS_STATUS DIS_SrInit (tDIS_ATTR_MASK dis_attr_mask);
+extern tDIS_STATUS DIS_SrInit (tDIS_ATTR_MASK dis_attr_mask);
 /*******************************************************************************
 **
 ** Function         DIS_SrUpdate
@@ -163,7 +163,7 @@
 ** Description      Update the DIS server attribute values
 **
 *******************************************************************************/
-    GATT_API extern tDIS_STATUS DIS_SrUpdate(tDIS_ATTR_BIT dis_attr_bit, tDIS_ATTR *p_info);
+extern tDIS_STATUS DIS_SrUpdate(tDIS_ATTR_BIT dis_attr_bit, tDIS_ATTR *p_info);
 /*****************************************************************************
 **  DIS Client Function
 *****************************************************************************/
@@ -176,8 +176,8 @@
 ** Returns          void
 **
 *******************************************************************************/
-    GATT_API extern BOOLEAN DIS_ReadDISInfo(BD_ADDR peer_bda, tDIS_READ_CBACK *p_cback,
-            tDIS_ATTR_MASK mask);
+extern BOOLEAN DIS_ReadDISInfo(BD_ADDR peer_bda, tDIS_READ_CBACK *p_cback,
+                               tDIS_ATTR_MASK mask);
 
 /*******************************************************************************
 **      BATTERY SERVICE API
@@ -189,7 +189,7 @@
 ** Description      Instantiate a Battery service
 **
 *******************************************************************************/
-    GATT_API extern UINT16 Battery_Instantiate (UINT8 app_id, tBA_REG_INFO *p_reg_info);
+extern UINT16 Battery_Instantiate (UINT8 app_id, tBA_REG_INFO *p_reg_info);
 
 /*******************************************************************************
 **
@@ -198,7 +198,7 @@
 ** Description      Respond to a battery service request
 **
 *******************************************************************************/
-    GATT_API extern void Battery_Rsp (UINT8 app_id, tGATT_STATUS st, UINT8 event, tBA_RSP_DATA *p_rsp);
+extern void Battery_Rsp (UINT8 app_id, tGATT_STATUS st, UINT8 event, tBA_RSP_DATA *p_rsp);
 /*******************************************************************************
 **
 ** Function         Battery_Notify
@@ -206,7 +206,7 @@
 ** Description      Send battery level notification
 **
 *******************************************************************************/
-    GATT_API extern void Battery_Notify (UINT8 app_id, BD_ADDR remote_bda, UINT8 battery_level);
+extern void Battery_Notify (UINT8 app_id, BD_ADDR remote_bda, UINT8 battery_level);
 
 
 #ifdef __cplusplus
@@ -215,5 +215,3 @@
 #endif
 
 #endif
-
-
diff --git a/stack/include/utfc.h b/stack/include/utfc.h
deleted file mode 100644
index 787efe8..0000000
--- a/stack/include/utfc.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  UTF conversion utilities.
- *
- ******************************************************************************/
-#ifndef UTFC_H
-#define UTFC_H
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/*******************************************************************************
-**
-** Function         utfc_16_to_8
-**
-** Description      Convert a UTF-16 array to a null-terminated UTF-8 string.
-**                  Illegal characters are skipped.
-**
-** Returns          Length of UTF-8 string in bytes.
-**
-*******************************************************************************/
-extern UINT16 utfc_16_to_8(UINT8 *p_utf8, UINT16 utf8_len, UINT16 *p_utf16, UINT16 utf16_len);
-
-/*******************************************************************************
-**
-** Function         utfc_8_to_16
-**
-** Description      Convert a null-terminated UTF-8 string to a UTF-16 array.
-**                  Illegal characters are skipped.  The UTF-16 array is
-**                  appended with a zero (null) character.
-**
-** Returns          Length of UTF-16 array including null character.
-**
-*******************************************************************************/
-extern UINT16 utfc_8_to_16(UINT16 *p_utf16, UINT16 utf16_len, UINT8 *p_utf8);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* UTFC_H */
diff --git a/stack/include/wbt_api.h b/stack/include/wbt_api.h
deleted file mode 100644
index 8bfb772..0000000
--- a/stack/include/wbt_api.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2003-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains definitions and constants used by the Broadcom
- *  Bluetooth Extensions API software.
- *
- ******************************************************************************/
-#ifndef WBT_API_H
-#define WBT_API_H
-
-#include "bt_target.h"
-
-/*****************************************************************************
-**  Constants and Types
-*****************************************************************************/
-
-/**************************
-* SDP Attribute IDs *
-***************************/
-#define ATTR_ID_EXT_BRCM_VERSION    0x8001  /* UINT16 (0xmmnn - major, minor [0x0001]) mandatory */
-#define ATTR_ID_EXT_PIN_CODE        0x8002  /* UINT32 4 - digit pin */
-
-/**************************
-* SDP Attribute ID Values *
-***************************/
-/* Version Attribute Value */
-#define BRCM_EXT_VERSION            0x0001  /* UINT16 (0xmmnn - major, minor [0x0001]) mandatory */
-
-/* Pin Code Attribute Value */
-#define BRCM_EXT_PIN_CODE           0x00000000  /* UINT32 ('0000') */
-
-/*****************************************************************************
-**  External Function Declarations
-*****************************************************************************/
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-BT_API extern BOOLEAN WBT_ExtCreateRecord(void);
-
-/*** Features ***/
-BT_API extern BOOLEAN WBT_ExtAddPinCode(void);
-
-
-BT_API extern UINT32 wbt_sdp_show_ext(UINT8 scn, char *service_name,
-                                      UINT8 pin_code_ext,
-                                      UINT8 active_sync_ext);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* WBT_API_H */
diff --git a/stack/include/wcassert.h b/stack/include/wcassert.h
deleted file mode 100644
index a1d7b47..0000000
--- a/stack/include/wcassert.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef WC_ASSERT_H
-#define WC_ASSERT_H
-
-
-#ifdef _DEBUG
-
-#include "bt_target.h"
-
-
-
-/* debug settings*/
-#ifndef WC_DEBUG_LEVEL
-#define WC_DEBUG_LEVEL 0
-#endif
-
-#if WC_DEBUG_LEVEL == 0
-
-#include "stdio.h"  /* for printf()*/
-
-#ifdef __cplusplus
-extern "C" wc_assert(char *message, char *file, UINT32 line);
-#else
-void wc_assert(char *message, char *file, UINT32 line);
-#endif
-
-#define WC_ASSERT(_x) if ( !(_x) ) wc_assert("ASSERT at %s line %d\n", __FILE__, __LINE__);
-#define WC_ASSERT_ALWAYS() wc_assert("ASSERT! at %s line %d\n", __FILE__, __LINE__);
-
-#elif WC_DEBUG_LEVEL == 1
-
-#include "assert.h"
-
-#define WC_ASSERT(_x)        assert(_x);
-#define WC_ASSERT_ALWAYS()   assert(0);
-#endif  /* WC_DEBUG_LEVEL*/
-
-#else /* _DEBUG*/
-
-#ifndef WC_ASSERT
-#define WC_ASSERT(_x)         ;
-#endif
-
-#ifndef WC_ASSERT_ALWAYS
-#define WC_ASSERT_ALWAYS()    ;
-#endif
-
-#endif /* _DEBUG*/
-#endif /* WC_ASSERT_H*/
diff --git a/stack/l2cap/l2c_api.c b/stack/l2cap/l2c_api.c
index b53eff0..667f717 100644
--- a/stack/l2cap/l2c_api.c
+++ b/stack/l2cap/l2c_api.c
@@ -22,18 +22,24 @@
  *
  ******************************************************************************/
 
+#define LOG_TAG "bt_l2cap"
+
+#include <assert.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
 
 #include "gki.h"
 #include "bt_types.h"
+#include "btcore/include/counter.h"
 #include "hcidefs.h"
 #include "hcimsgs.h"
 #include "l2cdefs.h"
 #include "l2c_int.h"
 #include "btu.h"
 #include "btm_api.h"
+#include "osi/include/allocator.h"
+#include "osi/include/log.h"
 
 /*******************************************************************************
 **
@@ -236,6 +242,7 @@
     tL2C_CCB        *p_ccb;
     tL2C_RCB        *p_rcb;
 
+    counter_add("l2cap.conn.req", 1);
     L2CAP_TRACE_API ("L2CA_ErtmConnectReq()  PSM: 0x%04x  BDA: %08x%04x  p_ertm_info: 0x%08x allowed:0x%x preferred:%d", psm,
                       (p_bd_addr[0]<<24)+(p_bd_addr[1]<<16)+(p_bd_addr[2]<<8)+p_bd_addr[3],
                       (p_bd_addr[4]<<8)+p_bd_addr[5], p_ertm_info,
@@ -326,6 +333,44 @@
     return (p_ccb->local_cid);
 }
 
+bool L2CA_SetConnectionCallbacks(uint16_t local_cid, const tL2CAP_APPL_INFO *callbacks) {
+  assert(callbacks != NULL);
+  assert(callbacks->pL2CA_ConnectInd_Cb == NULL);
+  assert(callbacks->pL2CA_ConnectCfm_Cb != NULL);
+  assert(callbacks->pL2CA_ConfigInd_Cb != NULL);
+  assert(callbacks->pL2CA_ConfigCfm_Cb != NULL);
+  assert(callbacks->pL2CA_DisconnectInd_Cb != NULL);
+  assert(callbacks->pL2CA_DisconnectCfm_Cb != NULL);
+  assert(callbacks->pL2CA_CongestionStatus_Cb != NULL);
+  assert(callbacks->pL2CA_DataInd_Cb != NULL);
+  assert(callbacks->pL2CA_TxComplete_Cb != NULL);
+
+  tL2C_CCB *channel_control_block = l2cu_find_ccb_by_cid(NULL, local_cid);
+  if (!channel_control_block) {
+    LOG_ERROR("%s no channel control block found for L2CAP LCID=0x%04x.", __func__, local_cid);
+    return false;
+  }
+
+  // We're making a connection-specific registration control block so we check if
+  // we already have a private one allocated to us on the heap. If not, we make a
+  // new allocation, mark it as heap-allocated, and inherit the fields from the old
+  // control block.
+  tL2C_RCB *registration_control_block = channel_control_block->p_rcb;
+  if (!channel_control_block->should_free_rcb) {
+    registration_control_block = (tL2C_RCB *)osi_calloc(sizeof(tL2C_RCB));
+    if (!registration_control_block) {
+      LOG_ERROR("%s unable to allocate registration control block.", __func__);
+      return false;
+    }
+
+    *registration_control_block = *channel_control_block->p_rcb;
+    channel_control_block->p_rcb = registration_control_block;
+    channel_control_block->should_free_rcb = true;
+  }
+
+  registration_control_block->api = *callbacks;
+  return true;
+}
 
 /*******************************************************************************
 **
@@ -362,6 +407,7 @@
     tL2C_LCB        *p_lcb;
     tL2C_CCB        *p_ccb;
 
+    counter_add("l2cap.conn.rsp", 1);
     L2CAP_TRACE_API ("L2CA_ErtmConnectRsp()  CID: 0x%04x  Result: %d  Status: %d  BDA: %08x%04x  p_ertm_info:0x%08x",
                       lcid, result, status,
                       (p_bd_addr[0]<<24)+(p_bd_addr[1]<<16)+(p_bd_addr[2]<<8)+p_bd_addr[3],
@@ -445,6 +491,7 @@
 {
     tL2C_CCB        *p_ccb;
 
+    counter_add("l2cap.cfg.req", 1);
     L2CAP_TRACE_API ("L2CA_ConfigReq()  CID 0x%04x: fcr_present:%d (mode %d) mtu_present:%d (%d)",
         cid, p_cfg->fcr_present, p_cfg->fcr.mode, p_cfg->mtu_present, p_cfg->mtu);
 
@@ -496,6 +543,7 @@
 {
     tL2C_CCB        *p_ccb;
 
+    counter_add("l2cap.cfg.rsp", 1);
     L2CAP_TRACE_API ("L2CA_ConfigRsp()  CID: 0x%04x  Result: %d MTU present:%d Flush TO:%d FCR:%d FCS:%d",
         cid, p_cfg->result, p_cfg->mtu_present, p_cfg->flush_to_present, p_cfg->fcr_present, p_cfg->fcs_present);
 
@@ -540,6 +588,7 @@
 {
     tL2C_CCB        *p_ccb;
 
+    counter_add("l2cap.disconn.req", 1);
     L2CAP_TRACE_API ("L2CA_DisconnectReq()  CID: 0x%04x", cid);
 
     /* Find the channel control block. We don't know the link it is on. */
@@ -568,6 +617,7 @@
 {
     tL2C_CCB        *p_ccb;
 
+    counter_add("l2cap.disconn.rsp", 1);
     L2CAP_TRACE_API ("L2CA_DisconnectRsp()  CID: 0x%04x", cid);
 
     /* Find the channel control block. We don't know the link it is on. */
@@ -703,6 +753,19 @@
 
 }
 
+bool L2CA_GetIdentifiers(uint16_t lcid, uint16_t *rcid, uint16_t *handle) {
+  tL2C_CCB *control_block = l2cu_find_ccb_by_cid(NULL, lcid);
+  if (!control_block)
+    return false;
+
+  if (rcid)
+    *rcid = control_block->remote_cid;
+  if (handle)
+    *handle = control_block->p_lcb->handle;
+
+  return true;
+}
+
 /*******************************************************************************
 **
 ** Function         L2CA_SetIdleTimeout
@@ -1483,7 +1546,7 @@
     {
         L2CAP_TRACE_ERROR ("L2CAP - CID: 0x%04x cannot send, already congested \
             xmit_hold_q.count: %u buff_quota: %u", fixed_cid,
-            p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->xmit_hold_q.count,
+            GKI_queue_length(&p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->xmit_hold_q),
             p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->buff_quota);
         GKI_freebuf (p_buf);
         return (L2CAP_DW_FAILED);
@@ -1796,7 +1859,6 @@
     UINT16          num_left = 0,
                     num_flushed1 = 0,
                     num_flushed2 = 0;
-    BT_HDR          *p_buf1, *p_buf;
 
     p_ccb = l2cu_find_ccb_by_cid(NULL, lcid);
 
@@ -1809,7 +1871,7 @@
     if (num_to_flush != L2CAP_FLUSH_CHANS_GET)
     {
         L2CAP_TRACE_API ("L2CA_FlushChannel (FLUSH)  CID: 0x%04x  NumToFlush: %d  QC: %u  pFirst: 0x%08x",
-                           lcid, num_to_flush, p_ccb->xmit_hold_q.count, p_ccb->xmit_hold_q.p_first);
+                           lcid, num_to_flush, GKI_queue_length(&p_ccb->xmit_hold_q), GKI_getfirst(&p_ccb->xmit_hold_q));
     }
     else
     {
@@ -1837,31 +1899,26 @@
         }
 #endif
 
-        p_buf = (BT_HDR *)p_lcb->link_xmit_data_q.p_first;
+        // Iterate though list and flush the amount requested from
+        // the transmit data queue that satisfy the layer and event conditions.
+        for (const list_node_t *node = list_begin(p_lcb->link_xmit_data_q);
+            (num_to_flush > 0) && node != list_end(p_lcb->link_xmit_data_q);) {
+          BT_HDR *p_buf = (BT_HDR *)list_node(node);
+          node = list_next(node);
+          if ((p_buf->layer_specific == 0) && (p_buf->event == lcid)) {
+            num_to_flush--;
+            num_flushed1++;
 
-        /* First flush the number we are asked to flush */
-        while ((p_buf != NULL) && (num_to_flush != 0))
-        {
-            /* Do not flush other CIDs or partial segments */
-            if ( (p_buf->layer_specific == 0) && (p_buf->event == lcid) )
-            {
-                p_buf1 = p_buf;
-                p_buf = (BT_HDR *)GKI_getnext (p_buf);
-                num_to_flush--;
-                num_flushed1++;
-
-                GKI_remove_from_queue (&p_lcb->link_xmit_data_q, p_buf1);
-                GKI_freebuf (p_buf1);
-            }
-            else
-                p_buf = (BT_HDR *)GKI_getnext (p_buf);
+            list_remove(p_lcb->link_xmit_data_q, p_buf);
+            GKI_freebuf(p_buf);
+          }
         }
     }
 
     /* If needed, flush buffers in the CCB xmit hold queue */
-    while ( (num_to_flush != 0) && (p_ccb->xmit_hold_q.count != 0) )
+    while ( (num_to_flush != 0) && (!GKI_queue_is_empty(&p_ccb->xmit_hold_q)))
     {
-        p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->xmit_hold_q);
+        BT_HDR *p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->xmit_hold_q);
         if (p_buf)
             GKI_freebuf (p_buf);
         num_to_flush--;
@@ -1873,18 +1930,17 @@
         (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, num_flushed2);
 
     /* Now count how many are left */
-    p_buf = (BT_HDR *)p_lcb->link_xmit_data_q.p_first;
+    for (const list_node_t *node = list_begin(p_lcb->link_xmit_data_q);
+        node != list_end(p_lcb->link_xmit_data_q);
+        node = list_next(node)) {
 
-    while (p_buf != NULL)
-    {
-        if (p_buf->event == lcid)
-            num_left++;
-
-        p_buf = (BT_HDR *)GKI_getnext (p_buf);
+      BT_HDR *p_buf = (BT_HDR *)list_node(node);
+      if (p_buf->event == lcid)
+        num_left++;
     }
 
     /* Add in the number in the CCB xmit queue */
-    num_left += p_ccb->xmit_hold_q.count;
+    num_left += GKI_queue_length(&p_ccb->xmit_hold_q);
 
     /* Return the local number of buffers left for the CID */
     L2CAP_TRACE_DEBUG ("L2CA_FlushChannel()  flushed: %u + %u,  num_left: %u", num_flushed1, num_flushed2, num_left);
diff --git a/stack/l2cap/l2c_ble.c b/stack/l2cap/l2c_ble.c
index d3ba6e2..61bc72a 100644
--- a/stack/l2cap/l2c_ble.c
+++ b/stack/l2cap/l2c_ble.c
@@ -30,6 +30,7 @@
 #include "btu.h"
 #include "btm_int.h"
 #include "hcimsgs.h"
+#include "device/include/controller.h"
 
 #if (BLE_INCLUDED == TRUE)
 static void l2cble_start_conn_update (tL2C_LCB *p_lcb);
@@ -416,7 +417,7 @@
 
     p_lcb->peer_chnl_mask[0] = L2CAP_FIXED_CHNL_ATT_BIT | L2CAP_FIXED_CHNL_BLE_SIG_BIT | L2CAP_FIXED_CHNL_SMP_BIT;
 
-    if (!HCI_LE_SLAVE_INIT_FEAT_EXC_SUPPORTED(btm_cb.devcb.local_le_features))
+    if (!HCI_LE_SLAVE_INIT_FEAT_EXC_SUPPORTED(controller_get_interface()->get_features_ble()->as_array))
     {
         p_lcb->link_state = LST_CONNECTED;
         l2cu_process_fixed_chnl_resp (p_lcb);
@@ -488,7 +489,7 @@
             /* if both side 4.1, or we are master device, send HCI command */
             if (p_lcb->link_role == HCI_ROLE_MASTER
 #if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE)
-                || (HCI_LE_CONN_PARAM_REQ_SUPPORTED(btm_cb.devcb.local_le_features) &&
+                || (HCI_LE_CONN_PARAM_REQ_SUPPORTED(controller_get_interface()->get_features_ble()->as_array) &&
                     HCI_LE_CONN_PARAM_REQ_SUPPORTED(p_acl_cb->peer_le_features))
 #endif
                  )
@@ -513,7 +514,7 @@
              /* if both side 4.1, or we are master device, send HCI command */
             if (p_lcb->link_role == HCI_ROLE_MASTER
 #if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE)
-                || (HCI_LE_CONN_PARAM_REQ_SUPPORTED(btm_cb.devcb.local_le_features) &&
+                || (HCI_LE_CONN_PARAM_REQ_SUPPORTED(controller_get_interface()->get_features_ble()->as_array) &&
                     HCI_LE_CONN_PARAM_REQ_SUPPORTED(p_acl_cb->peer_le_features))
 #endif
                  )
@@ -582,8 +583,7 @@
 {
     UINT8           *p_pkt_end;
     UINT8           cmd_code, id;
-    UINT16          cmd_len, rej_reason;
-    UINT16          result;
+    UINT16          cmd_len;
     UINT16          min_interval, max_interval, latency, timeout;
 
     p_pkt_end = p + pkt_len;
@@ -604,7 +604,7 @@
         case L2CAP_CMD_REJECT:
         case L2CAP_CMD_ECHO_RSP:
         case L2CAP_CMD_INFO_RSP:
-            STREAM_TO_UINT16 (rej_reason, p);
+            p += 2;
             break;
         case L2CAP_CMD_ECHO_REQ:
         case L2CAP_CMD_INFO_REQ:
@@ -647,7 +647,7 @@
             break;
 
         case L2CAP_CMD_BLE_UPDATE_RSP:
-            STREAM_TO_UINT16 (result, p);
+            p += 2;
             break;
 
         default:
@@ -915,7 +915,7 @@
             /* this link may have sent anything but some other link sent packets so  */
             /* so we may need a timer to kick off this link's transmissions.         */
             if ( (p_lcb->link_state == LST_CONNECTED)
-              && (p_lcb->link_xmit_data_q.count)
+              && (!list_is_empty(p_lcb->link_xmit_data_q))
               && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota) )
                 btu_start_timer (&p_lcb->timer_entry, BTU_TTYPE_L2CAP_LINK, L2CAP_LINK_FLOW_CONTROL_TOUT);
         }
diff --git a/stack/l2cap/l2c_csm.c b/stack/l2cap/l2c_csm.c
index fa261b2..325f720 100644
--- a/stack/l2cap/l2c_csm.c
+++ b/stack/l2cap/l2c_csm.c
@@ -183,7 +183,6 @@
 
     case L2CEVT_L2CA_CONNECT_REQ:                       /* API connect request  */
         /* Cancel sniff mode if needed */
-#if BTM_PWR_MGR_INCLUDED == TRUE
         {
             tBTM_PM_PWR_MD settings;
 // btla-specific ++
@@ -199,9 +198,6 @@
 */
             BTM_SetPowerMode (BTM_PM_SET_ONLY_ID, p_ccb->p_lcb->remote_bd_addr, &settings);
         }
-#else
-        BTM_CancelSniffMode (p_ccb->p_lcb->remote_bd_addr);
-#endif
 
         /* If sec access does not result in started SEC_COM or COMP_NEG are already processed */
         if (btm_sec_l2cap_access_req (p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm,
@@ -240,7 +236,6 @@
         btu_stop_timer (&p_ccb->p_lcb->timer_entry);
 
         /* Cancel sniff mode if needed */
-#if BTM_PWR_MGR_INCLUDED == TRUE
         {
             tBTM_PM_PWR_MD settings;
 // btla-specific ++
@@ -256,9 +251,6 @@
 */
             BTM_SetPowerMode (BTM_PM_SET_ONLY_ID, p_ccb->p_lcb->remote_bd_addr, &settings);
         }
-#else
-        BTM_CancelSniffMode (p_ccb->p_lcb->remote_bd_addr);
-#endif
 
         p_ccb->chnl_state = CST_TERM_W4_SEC_COMP;
         if (btm_sec_l2cap_access_req (p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm,
@@ -789,7 +781,7 @@
                 p_ccb->fcrb.connect_tick_count = GKI_get_os_tick_count();
 #endif
                 /* See if we can forward anything on the hold queue */
-                if (p_ccb->xmit_hold_q.count)
+                if (!GKI_queue_is_empty(&p_ccb->xmit_hold_q))
                 {
                     l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, NULL);
                 }
@@ -872,7 +864,7 @@
 #endif
 
         /* See if we can forward anything on the hold queue */
-        if ( (p_ccb->chnl_state == CST_OPEN) && (p_ccb->xmit_hold_q.count) )
+        if ( (p_ccb->chnl_state == CST_OPEN) && (!GKI_queue_is_empty(&p_ccb->xmit_hold_q)))
         {
             l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, NULL);
         }
@@ -1012,16 +1004,12 @@
     case L2CEVT_L2CAP_DISCONNECT_REQ:                  /* Peer disconnected request */
 // btla-specific ++
         /* Make sure we are not in sniff mode */
-#if BTM_PWR_MGR_INCLUDED == TRUE
         {
             tBTM_PM_PWR_MD settings;
             memset((void*)&settings, 0, sizeof(settings));
             settings.mode = BTM_PM_MD_ACTIVE;
             BTM_SetPowerMode (BTM_PM_SET_ONLY_ID, p_ccb->p_lcb->remote_bd_addr, &settings);
         }
-#else
-        BTM_CancelSniffMode (p_ccb->p_lcb->remote_bd_addr);
-#endif
 // btla-specific --
 
         p_ccb->chnl_state = CST_W4_L2CA_DISCONNECT_RSP;
@@ -1036,16 +1024,12 @@
 
     case L2CEVT_L2CA_DISCONNECT_REQ:                 /* Upper wants to disconnect */
         /* Make sure we are not in sniff mode */
-#if BTM_PWR_MGR_INCLUDED == TRUE
         {
             tBTM_PM_PWR_MD settings;
             memset((void*)&settings, 0, sizeof(settings));
             settings.mode = BTM_PM_MD_ACTIVE;
             BTM_SetPowerMode (BTM_PM_SET_ONLY_ID, p_ccb->p_lcb->remote_bd_addr, &settings);
         }
-#else
-        BTM_CancelSniffMode (p_ccb->p_lcb->remote_bd_addr);
-#endif
 
         l2cu_send_peer_disc_req (p_ccb);
         p_ccb->chnl_state = CST_W4_L2CAP_DISCONNECT_RSP;
diff --git a/stack/l2cap/l2c_fcr.c b/stack/l2cap/l2c_fcr.c
index 6e12607..ec9a4ef 100644
--- a/stack/l2cap/l2c_fcr.c
+++ b/stack/l2cap/l2c_fcr.c
@@ -23,20 +23,20 @@
  *
  ******************************************************************************/
 
+#include <assert.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <stdio.h>
 
-#include "gki.h"
 #include "bt_types.h"
+#include "gki.h"
 #include "hcimsgs.h"
-#include "l2cdefs.h"
-#include "l2c_int.h"
 #include "l2c_api.h"
-#include "btu.h"
+#include "l2c_int.h"
+#include "l2cdefs.h"
 #include "btm_api.h"
 #include "btm_int.h"
-
+#include "btu.h"
 
 /* Flag passed to retransmit_i_frames() when all packets should be retransmitted */
 #define L2C_FCR_RETX_ALL_PKTS   0xFF
@@ -94,12 +94,6 @@
 static void    process_stream_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf);
 static BOOLEAN do_sar_reassembly (tL2C_CCB *p_ccb, BT_HDR *p_buf, UINT16 ctrl_word);
 
-#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
-static BOOLEAN l2c_corrupt_the_fcr_packet (tL2C_CCB *p_ccb, BT_HDR *p_buf,
-                                           BOOLEAN is_rx, UINT16 ctrl_word);
-static BOOLEAN l2c_bypass_sframe_packet (tL2C_CCB *p_ccb);
-#endif
-
 #if (L2CAP_ERTM_STATS == TRUE)
 static void l2c_fcr_collect_ack_delay (tL2C_CCB *p_ccb, UINT8 num_bufs_acked);
 #endif
@@ -113,7 +107,7 @@
 ** Returns          CRC
 **
 *******************************************************************************/
-unsigned short l2c_fcr_updcrc(unsigned short icrc, unsigned char *icp, int icnt)
+static unsigned short l2c_fcr_updcrc(unsigned short icrc, unsigned char *icp, int icnt)
 {
     register unsigned short crc = icrc;
     register unsigned char  *cp = icp;
@@ -137,7 +131,7 @@
 ** Returns          CRC
 **
 *******************************************************************************/
-UINT16 l2c_fcr_tx_get_fcs (BT_HDR *p_buf)
+static UINT16 l2c_fcr_tx_get_fcs (BT_HDR *p_buf)
 {
     UINT8   *p = ((UINT8 *) (p_buf + 1)) + p_buf->offset;
 
@@ -153,7 +147,7 @@
 ** Returns          CRC
 **
 *******************************************************************************/
-UINT16 l2c_fcr_rx_get_fcs (BT_HDR *p_buf)
+static UINT16 l2c_fcr_rx_get_fcs (BT_HDR *p_buf)
 {
     UINT8   *p = ((UINT8 *) (p_buf + 1)) + p_buf->offset;
 
@@ -174,6 +168,7 @@
 *******************************************************************************/
 void l2c_fcr_start_timer (tL2C_CCB *p_ccb)
 {
+    assert(p_ccb != NULL);
     UINT32  tout;
 
     /* The timers which are in milliseconds */
@@ -185,10 +180,7 @@
     {
         tout = (UINT32)p_ccb->our_cfg.fcr.rtrans_tout;
     }
-/*
-    L2CAP_TRACE_DEBUG ("l2c_fcr_start_timer Tout: %u  Already Running: %u  wait_ack: %u  ack_q_count: %u",
-                        tout, p_ccb->timer_entry.in_use, p_ccb->fcrb.wait_ack, p_ccb->fcrb.waiting_for_ack_q.count);
-*/
+
     /* Only start a timer that was not started */
     if (p_ccb->fcrb.mon_retrans_timer.in_use == 0)
         btu_start_quick_timer (&p_ccb->fcrb.mon_retrans_timer, BTU_TTYPE_L2CAP_CHNL, tout*QUICK_TIMER_TICKS_PER_SEC/1000);
@@ -205,12 +197,9 @@
 *******************************************************************************/
 void l2c_fcr_stop_timer (tL2C_CCB *p_ccb)
 {
+    assert(p_ccb != NULL);
     if (p_ccb->fcrb.mon_retrans_timer.in_use)
     {
-/*
-        L2CAP_TRACE_DEBUG ("l2c_fcr_stop_timer wait_ack: %u  ack_q_count: %u",
-                            p_ccb->fcrb.wait_ack, p_ccb->fcrb.waiting_for_ack_q.count);
-*/
         btu_stop_quick_timer (&p_ccb->fcrb.mon_retrans_timer);
     }
 }
@@ -226,6 +215,7 @@
 *******************************************************************************/
 void l2c_fcr_cleanup (tL2C_CCB *p_ccb)
 {
+    assert(p_ccb != NULL);
     tL2C_FCRB *p_fcrb = &p_ccb->fcrb;
 
     l2c_fcr_stop_timer (p_ccb);
@@ -233,13 +223,13 @@
     if (p_fcrb->p_rx_sdu)
         GKI_freebuf (p_fcrb->p_rx_sdu);
 
-    while (p_fcrb->waiting_for_ack_q.p_first)
+    while (!GKI_queue_is_empty(&p_fcrb->waiting_for_ack_q))
         GKI_freebuf (GKI_dequeue (&p_fcrb->waiting_for_ack_q));
 
-    while (p_fcrb->srej_rcv_hold_q.p_first)
+    while (!GKI_queue_is_empty(&p_fcrb->srej_rcv_hold_q))
         GKI_freebuf (GKI_dequeue (&p_fcrb->srej_rcv_hold_q));
 
-    while (p_fcrb->retrans_q.p_first)
+    while (!GKI_queue_is_empty(&p_fcrb->retrans_q))
         GKI_freebuf (GKI_dequeue (&p_fcrb->retrans_q));
 
     btu_stop_quick_timer (&p_fcrb->ack_timer);
@@ -253,7 +243,6 @@
         UINT16  i;
         UINT32  throughput_avg, ack_delay_avg, ack_q_count_avg;
 
-        dur = GKI_OS_TICKS_TO_MS(dur);
         BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC,
                    "---  L2CAP ERTM  Stats for CID: 0x%04x   Duration: %08ums", p_ccb->local_cid, dur);
         BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC,
@@ -335,6 +324,7 @@
 *******************************************************************************/
 BT_HDR *l2c_fcr_clone_buf (BT_HDR *p_buf, UINT16 new_offset, UINT16 no_of_bytes, UINT8 pool)
 {
+    assert(p_buf != NULL);
     BT_HDR *p_buf2;
 
     /* If using the common pool, should be at least 10% free. */
@@ -386,14 +376,15 @@
 *******************************************************************************/
 BOOLEAN l2c_fcr_is_flow_controlled (tL2C_CCB *p_ccb)
 {
+    assert(p_ccb != NULL);
     if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
     {
         /* Check if remote side flowed us off or the transmit window is full */
         if ( (p_ccb->fcrb.remote_busy == TRUE)
-         ||  (p_ccb->fcrb.waiting_for_ack_q.count >= p_ccb->peer_cfg.fcr.tx_win_sz) )
+         ||  (GKI_queue_length(&p_ccb->fcrb.waiting_for_ack_q) >= p_ccb->peer_cfg.fcr.tx_win_sz) )
         {
 #if (L2CAP_ERTM_STATS == TRUE)
-            if (p_ccb->xmit_hold_q.count != 0)
+            if (!GKI_queue_is_empty(&p_ccb->xmit_hold_q))
             {
                 p_ccb->fcrb.xmit_window_closed++;
 
@@ -420,6 +411,8 @@
 *******************************************************************************/
 static void prepare_I_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf, BOOLEAN is_retransmission)
 {
+    assert(p_ccb != NULL);
+    assert(p_buf != NULL);
     tL2C_FCRB   *p_fcrb = &p_ccb->fcrb;
     UINT8       *p;
     UINT16      fcs;
@@ -519,17 +512,12 @@
 *******************************************************************************/
 void l2c_fcr_send_S_frame (tL2C_CCB *p_ccb, UINT16 function_code, UINT16 pf_bit)
 {
+    assert(p_ccb != NULL);
     BT_HDR      *p_buf;
     UINT8       *p;
     UINT16      ctrl_word;
     UINT16      fcs;
 
-#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
-    /* Only used for conformance testing */
-    if (l2c_bypass_sframe_packet (p_ccb))
-        return;
-#endif
-
     if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN))
         return;
 
@@ -577,11 +565,6 @@
             UINT16_TO_STREAM (p, L2CAP_FCR_OVERHEAD);
         }
 
-#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
-        /* Get out if packet was dropped */
-        if (l2c_corrupt_the_fcr_packet (p_ccb, p_buf, FALSE, ctrl_word))
-            return;
-#endif
         /* Now, the HCI transport header */
         p_buf->layer_specific = L2CAP_NON_FLUSHABLE_PKT;
         l2cu_set_acl_hci_header (p_buf, p_ccb);
@@ -637,6 +620,8 @@
 *******************************************************************************/
 void l2c_fcr_proc_pdu (tL2C_CCB *p_ccb, BT_HDR *p_buf)
 {
+    assert(p_ccb != NULL);
+    assert(p_buf != NULL);
     UINT8       *p;
     UINT16      fcs;
     UINT16      min_pdu_len;
@@ -699,19 +684,10 @@
 
     L2CAP_TRACE_EVENT ("      eRTM Rx Nxt_tx_seq %u, Lst_rx_ack %u, Nxt_seq_exp %u, Lst_ack_snt %u, wt_q.cnt %u, tries %u",
                         p_ccb->fcrb.next_tx_seq, p_ccb->fcrb.last_rx_ack, p_ccb->fcrb.next_seq_expected,
-                        p_ccb->fcrb.last_ack_sent, p_ccb->fcrb.waiting_for_ack_q.count, p_ccb->fcrb.num_tries);
+                        p_ccb->fcrb.last_ack_sent, GKI_queue_length(&p_ccb->fcrb.waiting_for_ack_q), p_ccb->fcrb.num_tries);
 
 #endif /* BT_TRACE_VERBOSE */
 
-#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
-    p = ((UINT8 *)(p_buf+1)) + p_buf->offset;
-    STREAM_TO_UINT16 (ctrl_word, p);
-
-    /* Get out if packet was dropped */
-    if (l2c_corrupt_the_fcr_packet (p_ccb, p_buf, TRUE, ctrl_word))
-        return;
-#endif  /* L2CAP_CORRUPT_ERTM_PKTS */
-
     /* Verify FCS if using */
     if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS)
     {
@@ -768,7 +744,7 @@
         if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
             ctrl_word &= ~L2CAP_FCR_P_BIT;
 
-        if (p_ccb->fcrb.waiting_for_ack_q.count == 0)
+        if (GKI_queue_is_empty(&p_ccb->fcrb.waiting_for_ack_q))
             p_ccb->fcrb.num_tries = 0;
 
         l2c_fcr_stop_timer (p_ccb);
@@ -797,7 +773,7 @@
         return;
 
     /* If we have some buffers held while doing SREJ, and SREJ has cleared, process them now */
-    if ( (!p_ccb->fcrb.local_busy) && (!p_ccb->fcrb.srej_sent) && (p_ccb->fcrb.srej_rcv_hold_q.count > 0) )
+    if ( (!p_ccb->fcrb.local_busy) && (!p_ccb->fcrb.srej_sent) && (!GKI_queue_is_empty(&p_ccb->fcrb.srej_rcv_hold_q)))
     {
         BUFFER_Q temp_q = p_ccb->fcrb.srej_rcv_hold_q;
 
@@ -845,7 +821,7 @@
     }
 
     /* If a window has opened, check if we can send any more packets */
-    if ( (p_ccb->fcrb.retrans_q.count || p_ccb->xmit_hold_q.count)
+    if ( (!GKI_queue_is_empty(&p_ccb->fcrb.retrans_q) || !GKI_queue_is_empty(&p_ccb->xmit_hold_q))
       && (p_ccb->fcrb.wait_ack == FALSE)
       && (l2c_fcr_is_flow_controlled (p_ccb) == FALSE) )
     {
@@ -864,9 +840,10 @@
 *******************************************************************************/
 void l2c_fcr_proc_tout (tL2C_CCB *p_ccb)
 {
+    assert(p_ccb != NULL);
     L2CAP_TRACE_DEBUG ("l2c_fcr_proc_tout:  CID: 0x%04x  num_tries: %u (max: %u)  wait_ack: %u  ack_q_count: %u",
                         p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit,
-                        p_ccb->fcrb.wait_ack, p_ccb->fcrb.waiting_for_ack_q.count);
+                        p_ccb->fcrb.wait_ack, GKI_queue_length(&p_ccb->fcrb.waiting_for_ack_q));
 
 #if (L2CAP_ERTM_STATS == TRUE)
     p_ccb->fcrb.retrans_touts++;
@@ -900,6 +877,7 @@
 *******************************************************************************/
 void l2c_fcr_proc_ack_tout (tL2C_CCB *p_ccb)
 {
+    assert(p_ccb != NULL);
     L2CAP_TRACE_DEBUG ("l2c_fcr_proc_ack_tout:  CID: 0x%04x State: %u  Wack:%u  Rq:%d  Acked:%d", p_ccb->local_cid,
                         p_ccb->chnl_state, p_ccb->fcrb.wait_ack, p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent);
 
@@ -928,6 +906,7 @@
 *******************************************************************************/
 static BOOLEAN process_reqseq (tL2C_CCB *p_ccb, UINT16 ctrl_word)
 {
+    assert(p_ccb != NULL);
     tL2C_FCRB   *p_fcrb = &p_ccb->fcrb;
     UINT8       req_seq, num_bufs_acked, xx;
     UINT16      ls;
@@ -939,7 +918,7 @@
      &&  ((ctrl_word & L2CAP_FCR_P_BIT) == 0) )
     {
         /* If anything still waiting for ack, restart the timer if it was stopped */
-        if (p_fcrb->waiting_for_ack_q.count)
+        if (!GKI_queue_is_empty(&p_fcrb->waiting_for_ack_q))
             l2c_fcr_start_timer (p_ccb);
 
         return (TRUE);
@@ -951,20 +930,16 @@
     num_bufs_acked = (req_seq - p_fcrb->last_rx_ack) & L2CAP_FCR_SEQ_MODULO;
 
     /* Verify the request sequence is in range before proceeding */
-    if (num_bufs_acked > p_fcrb->waiting_for_ack_q.count)
+    if (num_bufs_acked > GKI_queue_length(&p_fcrb->waiting_for_ack_q))
     {
         /* The channel is closed if ReqSeq is not in range */
         L2CAP_TRACE_WARNING ("L2CAP eRTM Frame BAD Req_Seq - ctrl_word: 0x%04x  req_seq 0x%02x  last_rx_ack: 0x%02x  QCount: %u",
-                               ctrl_word, req_seq, p_fcrb->last_rx_ack, p_fcrb->waiting_for_ack_q.count);
+                               ctrl_word, req_seq, p_fcrb->last_rx_ack, GKI_queue_length(&p_fcrb->waiting_for_ack_q));
 
         l2cu_disconnect_chnl (p_ccb);
         return (FALSE);
     }
 
-/*
-    L2CAP_TRACE_DEBUG ("L2CAP process_reqseq 0x%02x  last_rx_ack: 0x%02x  QCount: %u",
-                           req_seq, p_fcrb->last_rx_ack, p_fcrb->waiting_for_ack_q.count);
-*/
     p_fcrb->last_rx_ack = req_seq;
 
     /* Now we can release all acknowledged frames, and restart the retransmission timer if needed */
@@ -979,7 +954,7 @@
 
         for (xx = 0; xx < num_bufs_acked; xx++)
         {
-            ls = ((BT_HDR *)(p_fcrb->waiting_for_ack_q.p_first))->layer_specific & L2CAP_FCR_SAR_BITS;
+            ls = ((BT_HDR *)(GKI_getfirst(&p_fcrb->waiting_for_ack_q)))->layer_specific & L2CAP_FCR_SAR_BITS;
 
             if ( (ls == L2CAP_FCR_UNSEG_SDU) || (ls == L2CAP_FCR_END_SDU) )
                 full_sdus_xmitted++;
@@ -995,7 +970,7 @@
         if ( (p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) && (full_sdus_xmitted) )
         {
             /* Special case for eRTM, if all packets sent, send 0xFFFF */
-            if ( (p_fcrb->waiting_for_ack_q.count == 0) && (p_ccb->xmit_hold_q.count == 0) )
+            if (GKI_queue_is_empty(&p_fcrb->waiting_for_ack_q) && (GKI_queue_is_empty(&p_ccb->xmit_hold_q)))
                 full_sdus_xmitted = 0xFFFF;
 
             (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, full_sdus_xmitted);
@@ -1003,7 +978,7 @@
     }
 
     /* If anything still waiting for ack, restart the timer if it was stopped */
-    if (p_fcrb->waiting_for_ack_q.count)
+    if (!GKI_queue_is_empty(&p_fcrb->waiting_for_ack_q))
         l2c_fcr_start_timer (p_ccb);
 
     return (TRUE);
@@ -1021,6 +996,9 @@
 *******************************************************************************/
 static void process_s_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf, UINT16 ctrl_word)
 {
+    assert(p_ccb != NULL);
+    assert(p_buf != NULL);
+
     tL2C_FCRB   *p_fcrb      = &p_ccb->fcrb;
     UINT16      s_frame_type = (ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT;
     BOOLEAN     remote_was_busy;
@@ -1104,6 +1082,9 @@
 *******************************************************************************/
 static void process_i_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf, UINT16 ctrl_word, BOOLEAN delay_ack)
 {
+    assert(p_ccb != NULL);
+    assert(p_buf != NULL);
+
     tL2C_FCRB   *p_fcrb = &p_ccb->fcrb;
     UINT8       tx_seq, num_lost, num_to_ack, next_srej;
 
@@ -1165,9 +1146,9 @@
             if (p_fcrb->srej_sent)
             {
                 /* If SREJ sent, save the frame for later processing as long as it is in sequence */
-                next_srej = (((BT_HDR *)p_fcrb->srej_rcv_hold_q.p_last)->layer_specific + 1) & L2CAP_FCR_SEQ_MODULO;
+                next_srej = (((BT_HDR *)GKI_getlast(&p_fcrb->srej_rcv_hold_q))->layer_specific + 1) & L2CAP_FCR_SEQ_MODULO;
 
-                if ( (tx_seq == next_srej) && (p_fcrb->srej_rcv_hold_q.count < p_ccb->our_cfg.fcr.tx_win_sz) )
+                if ( (tx_seq == next_srej) && (GKI_queue_length(&p_fcrb->srej_rcv_hold_q) < p_ccb->our_cfg.fcr.tx_win_sz) )
                 {
                     /* If user gave us a pool for held rx buffers, use that */
                     if (p_ccb->ertm_info.fcr_rx_pool_id != HCI_ACL_POOL_ID)
@@ -1197,7 +1178,7 @@
                 else
                 {
                     L2CAP_TRACE_WARNING ("process_i_frame() CID: 0x%04x  frame dropped in Srej Sent next_srej:%u  hold_q.count:%u  win_sz:%u",
-                                         p_ccb->local_cid, next_srej, p_fcrb->srej_rcv_hold_q.count, p_ccb->our_cfg.fcr.tx_win_sz);
+                                         p_ccb->local_cid, next_srej, GKI_queue_length(&p_fcrb->srej_rcv_hold_q), p_ccb->our_cfg.fcr.tx_win_sz);
 
                     p_fcrb->rej_after_srej = TRUE;
                     GKI_freebuf (p_buf);
@@ -1225,10 +1206,10 @@
                 }
                 else
                 {
-                    if (p_fcrb->srej_rcv_hold_q.count != 0)
+                    if (!GKI_queue_is_empty(&p_fcrb->srej_rcv_hold_q))
                     {
                         L2CAP_TRACE_ERROR ("process_i_frame() CID: 0x%04x  sending SREJ tx_seq:%d hold_q.count:%u",
-                                             p_ccb->local_cid, tx_seq, p_fcrb->srej_rcv_hold_q.count);
+                                             p_ccb->local_cid, tx_seq, GKI_queue_length(&p_fcrb->srej_rcv_hold_q));
                     }
                     p_buf->layer_specific = tx_seq;
                     GKI_enqueue (&p_fcrb->srej_rcv_hold_q, p_buf);
@@ -1275,8 +1256,8 @@
                                         (L2CAP_FCR_ACK_TOUT*QUICK_TIMER_TICKS_PER_SEC)/1000);
             }
         }
-        else if ( ((p_ccb->xmit_hold_q.count == 0) || (l2c_fcr_is_flow_controlled (p_ccb)))
-               &&  (p_ccb->fcrb.srej_rcv_hold_q.count == 0) )
+        else if ( ((GKI_queue_is_empty(&p_ccb->xmit_hold_q)) || (l2c_fcr_is_flow_controlled (p_ccb)))
+               &&  (GKI_queue_is_empty(&p_ccb->fcrb.srej_rcv_hold_q)))
         {
             if (p_fcrb->local_busy)
                 l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RNR, 0);
@@ -1298,6 +1279,9 @@
 *******************************************************************************/
 static void process_stream_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf)
 {
+    assert(p_ccb != NULL);
+    assert(p_buf != NULL);
+
     UINT16      ctrl_word;
     UINT16      fcs;
     UINT8       *p;
@@ -1387,6 +1371,9 @@
 *******************************************************************************/
 static BOOLEAN do_sar_reassembly (tL2C_CCB *p_ccb, BT_HDR *p_buf, UINT16 ctrl_word)
 {
+    assert(p_ccb != NULL);
+    assert(p_buf != NULL);
+
     tL2C_FCRB   *p_fcrb = &p_ccb->fcrb;
     UINT16      sar_type = ctrl_word & L2CAP_FCR_SEG_BITS;
     BOOLEAN     packet_ok = TRUE;
@@ -1512,18 +1499,20 @@
 *******************************************************************************/
 static BOOLEAN retransmit_i_frames (tL2C_CCB *p_ccb, UINT8 tx_seq)
 {
+    assert(p_ccb != NULL);
+
     BT_HDR      *p_buf, *p_buf2;
     UINT8       *p;
     UINT8       buf_seq;
     UINT16      ctrl_word;
 
-    if ( (p_ccb->fcrb.waiting_for_ack_q.p_first)
+    if ( (GKI_getfirst(&p_ccb->fcrb.waiting_for_ack_q))
      &&  (p_ccb->peer_cfg.fcr.max_transmit != 0)
      &&  (p_ccb->fcrb.num_tries >= p_ccb->peer_cfg.fcr.max_transmit) )
     {
         L2CAP_TRACE_EVENT ("Max Tries Exceeded:  (last_acq: %d  CID: 0x%04x  num_tries: %u (max: %u) ack_q_count: %u",
                 p_ccb->fcrb.last_rx_ack, p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit,
-                p_ccb->fcrb.waiting_for_ack_q.count);
+                GKI_queue_length(&p_ccb->fcrb.waiting_for_ack_q));
 
         l2cu_disconnect_chnl (p_ccb);
         return (FALSE);
@@ -1534,7 +1523,7 @@
     {
         /* If sending only one, the sequence number tells us which one. Look for it.
         */
-        for (p_buf = (BT_HDR *)p_ccb->fcrb.waiting_for_ack_q.p_first; p_buf; p_buf = (BT_HDR *)GKI_getnext (p_buf))
+        for (p_buf = (BT_HDR *)GKI_getfirst(&p_ccb->fcrb.waiting_for_ack_q); p_buf; p_buf = (BT_HDR *)GKI_getnext (p_buf))
         {
             /* Get the old control word */
             p = ((UINT8 *) (p_buf+1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
@@ -1551,36 +1540,31 @@
 
         if (!p_buf)
         {
-            L2CAP_TRACE_ERROR ("retransmit_i_frames() UNKNOWN seq: %u  q_count: %u", tx_seq, p_ccb->fcrb.waiting_for_ack_q.count);
+            L2CAP_TRACE_ERROR ("retransmit_i_frames() UNKNOWN seq: %u  q_count: %u", tx_seq, GKI_queue_length(&p_ccb->fcrb.waiting_for_ack_q));
             return (TRUE);
         }
     }
     else
     {
-        /* Retransmitting everything. Flush buffers we already put in the link xmit queue.
-        */
-        p_buf = (BT_HDR *)p_ccb->p_lcb->link_xmit_data_q.p_first;
+        // Iterate though list and flush the amount requested from
+        // the transmit data queue that satisfy the layer and event conditions.
+        for (const list_node_t *node = list_begin(p_ccb->p_lcb->link_xmit_data_q);
+            node != list_end(p_ccb->p_lcb->link_xmit_data_q);) {
+          BT_HDR *p_buf = (BT_HDR *)list_node(node);
+          node = list_next(node);
 
-        while (p_buf != NULL)
-        {
             /* Do not flush other CIDs or partial segments */
-            if ( (p_buf->layer_specific == 0) && (p_buf->event == p_ccb->local_cid) )
-            {
-                p_buf2 = p_buf;
-                p_buf = (BT_HDR *)GKI_getnext (p_buf);
-
-                GKI_remove_from_queue (&p_ccb->p_lcb->link_xmit_data_q, p_buf2);
-                GKI_freebuf (p_buf2);
-            }
-            else
-                p_buf = (BT_HDR *)GKI_getnext (p_buf);
+          if ((p_buf->layer_specific == 0) && (p_buf->event == p_ccb->local_cid)) {
+            list_remove(p_ccb->p_lcb->link_xmit_data_q, p_buf);
+            GKI_freebuf(p_buf);
+          }
         }
 
         /* Also flush our retransmission queue */
-        while (p_ccb->fcrb.retrans_q.p_first)
+        while (!GKI_queue_is_empty(&p_ccb->fcrb.retrans_q))
             GKI_freebuf (GKI_dequeue (&p_ccb->fcrb.retrans_q));
 
-        p_buf = (BT_HDR *)p_ccb->fcrb.waiting_for_ack_q.p_first;
+        p_buf = (BT_HDR *)GKI_getfirst(&p_ccb->fcrb.waiting_for_ack_q);
     }
 
     while (p_buf != NULL)
@@ -1602,7 +1586,7 @@
 
     l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, NULL);
 
-    if (p_ccb->fcrb.waiting_for_ack_q.count)
+    if (GKI_queue_length(&p_ccb->fcrb.waiting_for_ack_q))
     {
         p_ccb->fcrb.num_tries++;
         l2c_fcr_start_timer (p_ccb);
@@ -1623,6 +1607,8 @@
 *******************************************************************************/
 BT_HDR *l2c_fcr_get_next_xmit_sdu_seg (tL2C_CCB *p_ccb, UINT16 max_packet_length)
 {
+    assert(p_ccb != NULL);
+
     BOOLEAN     first_seg    = FALSE,       /* The segment is the first part of data  */
                 mid_seg      = FALSE,       /* The segment is the middle part of data */
                 last_seg     = FALSE;       /* The segment is the last part of data   */
@@ -1633,7 +1619,7 @@
 
     /* If there is anything in the retransmit queue, that goes first
     */
-    if (p_ccb->fcrb.retrans_q.p_first)
+    if (GKI_getfirst(&p_ccb->fcrb.retrans_q))
     {
         p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->fcrb.retrans_q);
 
@@ -1642,16 +1628,6 @@
 
         p_buf->event = p_ccb->local_cid;
 
-#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
-        /* Use sdu_len to hold the control word */
-        p = ((UINT8 *) (p_buf+1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
-        STREAM_TO_UINT16 (sdu_len, p);
-
-        /* Get out if packet was dropped; just pretend it went out */
-        if (l2c_corrupt_the_fcr_packet (p_ccb, p_buf, FALSE, sdu_len))
-            return (NULL);
-#endif  /* L2CAP_CORRUPT_ERTM_PKTS */
-
 #if (L2CAP_ERTM_STATS == TRUE)
         p_ccb->fcrb.pkts_retransmitted++;
         p_ccb->fcrb.ertm_pkt_counts[0]++;
@@ -1668,7 +1644,7 @@
         max_pdu = max_packet_length - L2CAP_MAX_HEADER_FCS;
     }
 
-    p_buf = (BT_HDR *)p_ccb->xmit_hold_q.p_first;
+    p_buf = (BT_HDR *)GKI_getfirst(&p_ccb->xmit_hold_q);
 
     /* If there is more data than the MPS, it requires segmentation */
     if (p_buf->len > max_pdu)
@@ -1786,17 +1762,6 @@
             GKI_enqueue (&p_ccb->fcrb.waiting_for_ack_q, p_wack);
         }
 
-#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
-        {
-            UINT16 ctrl_word;
-            p = ((UINT8 *) (p_xmit+1)) + p_xmit->offset + L2CAP_PKT_OVERHEAD;
-            STREAM_TO_UINT16 (ctrl_word, p);
-
-            /* Get out if packet was dropped; pretend it was sent */
-            if (l2c_corrupt_the_fcr_packet (p_ccb, p_xmit, FALSE, ctrl_word))
-                return (NULL);
-        }
-#endif
 #if (L2CAP_ERTM_STATS == TRUE)
         p_ccb->fcrb.ertm_pkt_counts[0]++;
         p_ccb->fcrb.ertm_byte_counts[0] += (p_xmit->len - 8);
@@ -1830,6 +1795,8 @@
 *******************************************************************************/
 UINT8 l2c_fcr_chk_chan_modes (tL2C_CCB *p_ccb)
 {
+    assert(p_ccb != NULL);
+
     /* Remove nonbasic options that the peer does not support */
     if (!(p_ccb->p_lcb->peer_ext_fea & L2CAP_EXTFEA_ENH_RETRANS))
         p_ccb->ertm_info.allowed_modes &= ~L2CAP_FCR_CHAN_OPT_ERTM;
@@ -1858,6 +1825,9 @@
 *******************************************************************************/
 BOOLEAN l2c_fcr_adj_our_req_options (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg)
 {
+    assert(p_ccb != NULL);
+    assert(p_cfg != NULL);
+
     tL2CAP_FCR_OPTS *p_fcr = &p_cfg->fcr;
 
     if (p_fcr->mode != p_ccb->ertm_info.preferred_mode)
@@ -1974,6 +1944,8 @@
 *******************************************************************************/
 void l2c_fcr_adj_monitor_retran_timeout (tL2C_CCB *p_ccb)
 {
+    assert(p_ccb != NULL);
+
     /* adjust our monitor/retran timeout */
     if (p_ccb->out_cfg_fcr_present)
     {
@@ -2011,6 +1983,9 @@
 *******************************************************************************/
 void l2c_fcr_adj_our_rsp_options (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg)
 {
+    assert(p_ccb != NULL);
+    assert(p_cfg != NULL);
+
     /* adjust our monitor/retran timeout */
     l2c_fcr_adj_monitor_retran_timeout(p_ccb);
 
@@ -2052,6 +2027,9 @@
 *******************************************************************************/
 BOOLEAN l2c_fcr_renegotiate_chan(tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg)
 {
+    assert(p_ccb != NULL);
+    assert(p_cfg != NULL);
+
     UINT8   peer_mode = p_ccb->our_cfg.fcr.mode;
     BOOLEAN can_renegotiate;
 
@@ -2156,6 +2134,9 @@
 *******************************************************************************/
 UINT8 l2c_fcr_process_peer_cfg_req(tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg)
 {
+    assert(p_ccb != NULL);
+    assert(p_cfg != NULL);
+
     UINT16 max_retrans_size;
     UINT8  fcr_ok = L2CAP_PEER_CFG_OK;
 
@@ -2271,341 +2252,6 @@
     return (fcr_ok);
 }
 
-
-#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
-/*******************************************************************************
-**  Functions used for testing ERTM mode
-*/
-/* If FALSE, will also corrupt cid, length, control word, etc. */
-#ifndef L2CAP_CORR_FCS_ONLY
-#define L2CAP_CORR_FCS_ONLY TRUE
-#endif
-
-#define L2C_DISP_FRAME_SIZE 16
-/*******************************************************************************
-**
-** Function         l2c_corrupt_the_fcr_packet
-**
-** Description      This function is used for testing purposes only.
-**                  It systematically or randomly corrupts packets used with
-**                  ERTM channels.
-**
-** Returns          BOOLEAN   TRUE if packet was dropped,
-**                            FALSE if fcs corrupted or no corruption
-**
-*******************************************************************************/
-static BOOLEAN l2c_corrupt_the_fcr_packet (tL2C_CCB *p_ccb, BT_HDR *p_buf,
-                                           BOOLEAN is_rx, UINT16 ctrl_word)
-{
-    tL2C_FCR_TEST_CFG *p_cfg;
-    UINT32   tc;
-    UINT8   *p;
-    UINT32   xx;
-    char     buf[L2C_DISP_FRAME_SIZE];
-
-    if (!p_ccb || !p_ccb->fcrb.test_cb.cfg.in_use)
-        return FALSE;
-
-    /* Prepare bad FCS */
-    p = ((UINT8 *) (p_buf + 1)) + p_buf->offset;
-    tc = GKI_get_os_tick_count();
-    tc ^= p[p_buf->len - 1];
-    xx = tc % 47;
-
-    p_cfg = &p_ccb->fcrb.test_cb.cfg;
-#if 0
-    L2CAP_TRACE_DEBUG ("testcfg: type: %d, freq: %d (NRM-0, RDM-1), is_rx: %d, count: %d",
-        p_cfg->type, p_cfg->freq, p_cfg->is_rx, p_cfg->count);
-#endif
-    /* If not time to corrupt get out */
-    if (p_cfg->freq == L2CAP_FCR_FREQ_RANDOM)
-    {
-        if (xx != 0)
-            return FALSE;
-    }
-    else    /* check test criteria before corrupting */
-    {
-        if ( (p_cfg->count == 0)
-          || (p_cfg->is_rx != is_rx)
-          || ((UINT8)(ctrl_word & L2CAP_FCR_S_FRAME_BIT) != p_cfg->type) )
-        {
-            return FALSE;
-        }
-
-        /* Turn off if done */
-        if (--(p_cfg->count) == 0)
-        {
-            p_ccb->fcrb.test_cb.cfg.in_use = FALSE;
-        }
-    }
-
-#if L2CAP_CORR_FCS_ONLY == TRUE
-    /* Corrupt the FCS check */
-    p[p_buf->len - 1] = p[p_buf->len - 2] = 0;
-#else
-    /* If made it this far packet needs to be corrupted */
-    xx = tc % p_buf->len;
-
-    /* Make sure the value was changed */
-    if (p[xx + 1] == 0)
-        p[xx + 1] = 0x5A;
-
-    p[xx] = p[xx] ^ p[xx + 1];
-
-#if 1   /* Enable if not wishing to corrupting frame type */
-    {
-        UINT8 *p_temp = ((UINT8 *) (p_buf + 1)) + p_buf->offset;
-        p_temp += L2CAP_PKT_OVERHEAD;
-        if ((UINT16)((*p_temp) & 0x01) != (ctrl_word & 0x0001))
-        {
-            (*p_temp) |= (UINT8)(ctrl_word & 0x0001);
-        }
-    }
-#endif
-#endif
-
-    if (is_rx)
-    {
-        if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
-            BCM_STRCPY_S(buf, L2C_DISP_FRAME_SIZE, "Rx S-Frame");
-        else
-            BCM_STRCPY_S(buf, L2C_DISP_FRAME_SIZE, "Rx I-Frame");
-    }
-    else
-    {
-        if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
-            BCM_STRCPY_S(buf, L2C_DISP_FRAME_SIZE, "Tx S-Frame");
-        else
-            BCM_STRCPY_S(buf, L2C_DISP_FRAME_SIZE, "Tx I-Frame");
-    }
-
-    /* Lastly, just drop packet if FCS is not being used or if Tx */
-    if (!is_rx || p_ccb->bypass_fcs == L2CAP_BYPASS_FCS)
-    {
-        L2CAP_TRACE_ERROR ("-=-=-=-=-=-=-=-   Dropping %s packet (0x%04x) tc: %u  Buf Len: %u  xx: %u  count: %d",
-                        buf, (UINT32)p_buf, tc, p_buf->len, xx, p_cfg->count);
-        GKI_freebuf(p_buf);
-        return TRUE;
-    }
-    else
-    {
-        L2CAP_TRACE_ERROR ("-=-=-=-=-=-=-=-   Corrupting %s packet (0x%04x) tc: %u  Buf Len: %u  xx: %u  count: %d",
-                        buf, (UINT32)p_buf, tc, p_buf->len, xx, p_cfg->count);
-    }
-
-    return FALSE;
-}
-
-
-/*******************************************************************************
-**
-** Function         L2CA_SetupErtmTest
-**
-** Description      This function is used for testing purposes only.
-**                  It corrupts or drops one or more packets used with ERTM channels.
-**
-** Parameters
-**                  cid - channel ID  (0 uses RFCOMM PSM's CID)
-**
-**                  type - type of test to run (L2CAP_FCR_TTYPE_CORR_IFRAMES
-**                                              L2CAP_FCR_TTYPE_CORR_SFRAME
-**                                              L2CAP_FCR_TTYPE_STOP_TEST
-**                                              L2CAP_FCR_TTYPE_GET_CID - returns rfcomm cid only)
-**
-**                  is_rx  - TRUE to corrupt Rx packet, FALSE for Tx packet)
-**
-**                  freq - L2CAP_FCR_FREQ_RANDOM    (turns on random corruptions/drops)
-**                         L2CAP_FCR_FREQ_NORMAL    (turns on test with "count" corruptions/drops)
-**
-**                  count - number of packets in a row to drop or corrupt
-**
-** Returns          CID of channel running test
-**
-*******************************************************************************/
-UINT16 L2CA_SetupErtmTest (UINT16 cid, UINT8 type, BOOLEAN is_rx, UINT8 freq, UINT16 count)
-{
-    tL2C_CCB *p_ccb = NULL;
-    tL2C_CCB *p_temp_ccb;
-    tL2C_FCR_TEST_CB *p_test_cb;
-    UINT16 xx;
-
-    /* If '0' tests run on top of RFCOMM CID if active */
-    if (cid == 0)
-    {
-        p_temp_ccb = l2cb.ccb_pool;
-        for (xx = 0; xx < MAX_L2CAP_CHANNELS; xx++, p_temp_ccb++)
-        {
-            /* Fixed channels don't have p_rcb's */
-            if (p_temp_ccb->in_use && p_temp_ccb->p_rcb && p_temp_ccb->p_rcb->psm == BT_PSM_RFCOMM)
-            {
-                p_ccb = p_temp_ccb;
-                cid = L2CAP_BASE_APPL_CID + xx;
-                break;
-            }
-        }
-    }
-    else
-        p_ccb = l2cu_find_ccb_by_cid (NULL, cid);
-
-    if (!p_ccb || type == L2CAP_FCR_TTYPE_GET_CID)
-    {
-        if (type == L2CAP_FCR_TTYPE_GET_CID)
-        {
-            L2CAP_TRACE_API ("L2CA_SetupErtmTest (GET_CID): cid = 0x%04x", cid);
-        }
-        return (cid);
-    }
-
-    p_test_cb = &p_ccb->fcrb.test_cb;
-
-    /* Turn off the current test */
-    if (type == L2CAP_FCR_TTYPE_STOP_TEST)
-    {
-        if (p_test_cb->cfg.in_use)
-        {
-            L2CAP_TRACE_ERROR ("L2CA_SetupErtmTest (OFF): cid 0x%04x", cid);
-        }
-        p_test_cb->cfg.in_use = FALSE;
-        p_test_cb->cfg.count = 0;
-    }
-
-    /* Process the new request */
-    else if (!p_test_cb->cfg.in_use)
-    {
-        /* count must be positive unless random is used */
-        if (!count && freq != L2CAP_FCR_FREQ_RANDOM)
-        {
-            L2CAP_TRACE_ERROR ("L2CA_SetupErtmTest (FAIL): Count = 0, freq = %d", freq);
-            return (cid);
-        }
-
-        L2CAP_TRACE_ERROR ("L2CA_SetupErtmTest (START): cid 0x%04x, type %d, is_rx %d, freq %d, count %d",
-                            cid, type, is_rx, freq, count);
-
-        p_test_cb->cfg.in_use = TRUE;
-        p_test_cb->cfg.freq = freq;
-        p_test_cb->cfg.type = type;
-        p_test_cb->cfg.is_rx = is_rx;
-        p_test_cb->cfg.count = count;
-    }
-    else /* Test already in progress so ignore */
-    {
-        L2CAP_TRACE_ERROR ("L2CA_SetupErtmTest (ignoring): cid 0x%04x, type %d, is_rx %d, freq %d, count %d",
-                            cid, type, is_rx, freq, count);
-    }
-
-    return (cid);
-}
-
-
-/*******************************************************************************
-** The following routines are only used in conjunction with Conformance testing
-********************************************************************************/
-
-/*******************************************************************************
-**
-** Function         L2CA_SendPolledSFrame
-**
-** Description      This function is used for testing purposes only.
-**                  It Sends a Polled RR or RNR to the peer
-**
-** Parameters
-**                  cid - channel ID
-**
-**                  sup_type - (L2CAP_FCR_SUP_RR or L2CAP_FCR_SUP_RNR)
-**
-** Returns          void
-**
-*******************************************************************************/
-void L2CA_SendPolledSFrame (UINT16 cid, UINT16 sup_type)
-{
-    tL2C_CCB *p_ccb = l2cu_find_ccb_by_cid (NULL, cid);
-
-    if (p_ccb && (sup_type == L2CAP_FCR_SUP_RR || sup_type == L2CAP_FCR_SUP_RNR))
-    {
-        l2c_fcr_send_S_frame (p_ccb, sup_type, L2CAP_FCR_P_BIT);
-    }
-    else
-    {
-        L2CAP_TRACE_ERROR ("L2CA_SendPolledSFrame(ERROR): sup_type %u, p_ccb 0x%07x",
-                            sup_type, (UINT32)p_ccb);
-    }
-}
-
-/*******************************************************************************
-**
-** Function         l2c_bypass_sframe_packet
-**
-** Description      This function is used for testing purposes only.
-**                  It returns TRUE if S-Frame should be bypassed.
-**
-** Returns          void
-**
-*******************************************************************************/
-static BOOLEAN l2c_bypass_sframe_packet (tL2C_CCB *p_ccb)
-{
-    if (p_ccb && p_ccb->fcrb.test_cb.cfm.in_use)
-    {
-        if (p_ccb->fcrb.test_cb.cfm.skip_sframe_count > 0)
-        {
-            L2CAP_TRACE_ERROR ("l2c_bypass_sframe_packet (count %d)",
-                                p_ccb->fcrb.test_cb.cfm.skip_sframe_count);
-
-            if (--p_ccb->fcrb.test_cb.cfm.skip_sframe_count == 0)
-                p_ccb->fcrb.test_cb.cfm.in_use = FALSE;
-
-            /* Bypass sending S-Frame */
-            return TRUE;
-        }
-        else
-            p_ccb->fcrb.test_cb.cfm.in_use = FALSE;
-    }
-
-    return FALSE;
-}
-
-/*******************************************************************************
-**
-** Function         L2CA_BypassSFrame
-**
-** Description      This function is used for testing purposes only.
-**                  It skips sending 'count' S-Frames.
-**
-** Parameters
-**                  cid - channel ID
-**
-**                  count - Number of S-Frames to skip sending
-**
-** Returns          void
-**
-*******************************************************************************/
-void L2CA_BypassSFrame (UINT16 cid, UINT8 count)
-{
-    tL2C_CCB *p_ccb = l2cu_find_ccb_by_cid (NULL, cid);
-    tL2C_FCR_CFM_TEST_CB *p_test_cb;
-
-    if (!p_ccb)
-    {
-        L2CAP_TRACE_WARNING ("L2CA_BypassSFrame(ERROR): no p_ccb (0x%07x)", (UINT32)p_ccb);
-        return;
-    }
-
-    p_test_cb = &p_ccb->fcrb.test_cb.cfm;
-
-    /* Initiate test if not active */
-    if (!p_test_cb->in_use)
-    {
-        p_test_cb->in_use = TRUE;
-        p_test_cb->skip_sframe_count = count;
-    }
-    else
-    {
-        L2CAP_TRACE_WARNING ("L2CA_BypassSFrame(ERROR): already in use (ignoring...)");
-    }
-}
-
-#endif  /* L2CAP_CORRUPT_ERTM_PKTS == TRUE */
-
 #if (L2CAP_ERTM_STATS == TRUE)
 /*******************************************************************************
 **
@@ -2708,6 +2354,3 @@
     }
 }
 #endif
-
-
-
diff --git a/stack/l2cap/l2c_int.h b/stack/l2cap/l2c_int.h
index b1d0c46..9cf79a9 100644
--- a/stack/l2cap/l2c_int.h
+++ b/stack/l2cap/l2c_int.h
@@ -24,10 +24,13 @@
 #ifndef L2C_INT_H
 #define L2C_INT_H
 
+#include <stdbool.h>
+
+#include "btm_api.h"
+#include "gki.h"
 #include "l2c_api.h"
 #include "l2cdefs.h"
-#include "gki.h"
-#include "btm_api.h"
+#include "list.h"
 
 #define L2CAP_MIN_MTU   48      /* Minimum acceptable MTU is 48 bytes */
 
@@ -152,34 +155,6 @@
 
 #define L2CAP_MAX_FCR_CFG_TRIES         2       /* Config attempts before disconnecting */
 
-/* Only compiled in when in test mode. Production devices must not include
-*/
-#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
-
-/* These are used for conformance and corruption testing only */
-typedef struct
-{
-    BOOLEAN in_use;                 /* TRUE if test in progress */
-    UINT8   type;                   /* Type of test to run or turns off random test */
-    UINT8   freq;                   /* One-shot or random */
-    BOOLEAN is_rx;                  /* TRUE if incoming packets */
-    UINT16  count;                  /* How many I-frames to drop in a row; used only with one-shot tests */
-} tL2C_FCR_TEST_CFG;
-
-typedef struct
-{
-    BOOLEAN in_use;                 /* TRUE if test in progress */
-    UINT8   skip_sframe_count;      /* Number of S-Frames to skip sending */
-} tL2C_FCR_CFM_TEST_CB;
-
-typedef struct
-{
-    tL2C_FCR_TEST_CFG       cfg;    /* Current corruption test configuration */
-    tL2C_FCR_CFM_TEST_CB    cfm;    /* Conformance test structure */
-} tL2C_FCR_TEST_CB;
-
-#endif /* L2CAP_CORRUPT_ERTM_PKTS == TRUE */
-
 typedef struct
 {
     UINT8       next_tx_seq;                /* Next sequence number to be Tx'ed         */
@@ -234,11 +209,6 @@
     UINT32      ack_q_count_min[L2CAP_ERTM_STATS_NUM_AVG];
     UINT32      ack_q_count_max[L2CAP_ERTM_STATS_NUM_AVG];
 #endif
-
-#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
-    tL2C_FCR_TEST_CB test_cb;               /* Used for SVT and UPF testing */
-#endif
-
 } tL2C_FCRB;
 
 
@@ -293,6 +263,7 @@
     TIMER_LIST_ENT      timer_entry;            /* CCB Timer List Entry             */
 
     tL2C_RCB            *p_rcb;                 /* Registration CB for this Channel */
+    bool                should_free_rcb;        /* True if RCB was allocated on the heap */
 
 #define IB_CFG_DONE     0x01
 #define OB_CFG_DONE     0x02
@@ -312,7 +283,6 @@
     tL2CAP_CFG_INFO     peer_cfg;               /* Peer's saved configuration options */
 
     BUFFER_Q            xmit_hold_q;            /* Transmit data hold queue         */
-
     BOOLEAN             cong_sent;              /* Set when congested status sent   */
     UINT16              buff_quota;             /* Buffer quota before sending congestion   */
 
@@ -409,7 +379,7 @@
     BOOLEAN             w4_info_rsp;                /* TRUE when info request is active */
     UINT8               info_rx_bits;               /* set 1 if received info type */
     UINT32              peer_ext_fea;               /* Peer's extended features mask    */
-    BUFFER_Q            link_xmit_data_q;           /* Transmit data buffer queue       */
+    list_t              *link_xmit_data_q;          /* Link transmit data buffer queue  */
 
     UINT8               peer_chnl_mask[L2CAP_FIXED_CHNL_ARRAY_SIZE];
 #if (L2CAP_UCD_INCLUDED == TRUE)
@@ -418,11 +388,6 @@
     BUFFER_Q            ucd_in_sec_pending_q;       /* Security pending incoming UCD packet  */
 #endif
 
-#if (L2CAP_HOST_FLOW_CTRL == TRUE)
-    UINT16              link_pkts_unacked;          /* Packets received but not acked   */
-    UINT16              link_ack_thresh;            /* Threshold at which to ack pkts   */
-#endif
-
     BT_HDR              *p_hcit_rcv_acl;            /* Current HCIT ACL buf being rcvd  */
     UINT16              idle_timeout_sv;            /* Save current Idle timeout        */
     UINT8               acl_priority;               /* L2C_PRIORITY_NORMAL or L2C_PRIORITY_HIGH */
@@ -484,7 +449,7 @@
     UINT16          num_lm_acl_bufs;                /* # of ACL buffers on controller   */
     UINT16          idle_timeout;                   /* Idle timeout                     */
 
-    BUFFER_Q        rcv_hold_q;                     /* Recv pending queue               */
+    list_t          *rcv_pending_q;                 /* Recv pending queue               */
     TIMER_LIST_ENT  rcv_hold_tle;                   /* Timer list entry for rcv hold    */
 
     tL2C_LCB        *p_cur_hcit_lcb;                /* Current HCI Transport buffer     */
@@ -565,9 +530,9 @@
 ************************************
 */
 #if (!defined L2C_DYNAMIC_MEMORY) || (L2C_DYNAMIC_MEMORY == FALSE)
-L2C_API extern tL2C_CB  l2cb;
+extern tL2C_CB  l2cb;
 #else
-L2C_API extern tL2C_CB *l2c_cb_ptr;
+extern tL2C_CB *l2c_cb_ptr;
 #define l2cb (*l2c_cb_ptr)
 #endif
 
@@ -575,7 +540,9 @@
 /* Functions provided by l2c_main.c
 ************************************
 */
-extern void     l2c_init (void);
+void l2c_init(void);
+void l2c_free(void);
+
 extern void     l2c_process_timeout (TIMER_LIST_ENT *p_tle);
 extern UINT8    l2c_data_write (UINT16 cid, BT_HDR *p_data, UINT16 flag);
 extern void     l2c_rcv_acl_data (BT_HDR *p_msg);
@@ -715,16 +682,16 @@
 extern void     l2c_link_processs_ble_num_bufs (UINT16 num_lm_acl_bufs);
 #endif
 
-#if ((BTM_PWR_MGR_INCLUDED == TRUE) && L2CAP_WAKE_PARKED_LINK == TRUE)
+#if L2CAP_WAKE_PARKED_LINK == TRUE
 extern BOOLEAN  l2c_link_check_power_mode ( tL2C_LCB *p_lcb );
 #define L2C_LINK_CHECK_POWER_MODE(x) l2c_link_check_power_mode ((x))
-#else
+#else  // L2CAP_WAKE_PARKED_LINK
 #define L2C_LINK_CHECK_POWER_MODE(x) (FALSE)
-#endif
+#endif  // L2CAP_WAKE_PARKED_LINK
 
 #if L2CAP_CONFORMANCE_TESTING == TRUE
 /* Used only for conformance testing */
-L2C_API extern void l2cu_set_info_rsp_mask (UINT32 mask);
+extern void l2cu_set_info_rsp_mask (UINT32 mask);
 #endif
 
 /* Functions provided by l2c_csm.c
@@ -732,10 +699,7 @@
 */
 extern void l2c_csm_execute (tL2C_CCB *p_ccb, UINT16 event, void *p_data);
 
-L2C_API extern BT_HDR   *l2cap_link_chk_pkt_start(BT_HDR *);    /* Called at start of rcv to check L2CAP segmentation */
-L2C_API extern BOOLEAN   l2cap_link_chk_pkt_end (void);         /* Called at end   of rcv to check L2CAP segmentation */
-
-L2C_API extern void     l2c_enqueue_peer_data (tL2C_CCB *p_ccb, BT_HDR *p_buf);
+extern void l2c_enqueue_peer_data (tL2C_CCB *p_ccb, BT_HDR *p_buf);
 
 
 /* Functions provided by l2c_fcr.c
diff --git a/stack/l2cap/l2c_link.c b/stack/l2cap/l2c_link.c
index 5ee5faa..98d6803 100644
--- a/stack/l2cap/l2c_link.c
+++ b/stack/l2cap/l2c_link.c
@@ -28,6 +28,8 @@
 #include <string.h>
 #include <stdio.h>
 
+#include "device/include/controller.h"
+#include "btcore/include/counter.h"
 #include "gki.h"
 #include "bt_types.h"
 #include "bt_utils.h"
@@ -41,12 +43,6 @@
 
 static BOOLEAN l2c_link_send_to_lower (tL2C_LCB *p_lcb, BT_HDR *p_buf);
 
-#define L2C_LINK_SEND_ACL_DATA(x)  HCI_ACL_DATA_TO_LOWER((x))
-
-#if (BLE_INCLUDED == TRUE)
-#define L2C_LINK_SEND_BLE_ACL_DATA(x)  HCI_BLE_ACL_DATA_TO_LOWER((x))
-#endif
-
 /*******************************************************************************
 **
 ** Function         l2c_link_hci_conn_req
@@ -102,6 +98,8 @@
                 p_lcb->link_role = l2cu_get_conn_role(p_lcb);
         }
 
+        counter_add("l2cap.conn.accept", 1);
+
         /* Tell the other side we accept the connection */
         btsnd_hcic_accept_conn (bd_addr, p_lcb->link_role);
 
@@ -122,6 +120,7 @@
         else
             p_lcb->link_role = l2cu_get_conn_role(p_lcb);
 
+        counter_add("l2cap.conn.accept", 1);
         btsnd_hcic_accept_conn (bd_addr, p_lcb->link_role);
 
         p_lcb->link_state = LST_CONNECTING;
@@ -130,6 +129,7 @@
     else if (p_lcb->link_state == LST_DISCONNECTING)
     {
         /* In disconnecting state, reject the connection. */
+        counter_add("l2cap.conn.reject.disconn", 1);
         btsnd_hcic_reject_conn (bd_addr, HCI_ERR_HOST_REJECT_DEVICE);
     }
     else
@@ -137,6 +137,7 @@
         L2CAP_TRACE_ERROR("L2CAP got conn_req while connected (state:%d). Reject it",
                 p_lcb->link_state);
         /* Reject the connection with ACL Connection Already exist reason */
+        counter_add("l2cap.conn.reject.exists", 1);
         btsnd_hcic_reject_conn (bd_addr, HCI_ERR_CONNECTION_EXISTS);
     }
     return (FALSE);
@@ -159,9 +160,7 @@
     tL2C_CCB            *p_ccb;
     tBTM_SEC_DEV_REC    *p_dev_info = NULL;
 
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     btm_acl_update_busy_level (BTM_BLI_PAGE_DONE_EVT);
-#endif
 
     /* Save the parameters */
     ci.status       = status;
@@ -194,6 +193,7 @@
     {
         /* Connected OK. Change state to connected */
         p_lcb->link_state = LST_CONNECTED;
+        counter_add("l2cap.conn.ok", 1);
 
         /* Get the peer information if the l2cap flow-control/rtrans is supported */
         l2cu_send_peer_info_req (p_lcb, L2CAP_EXTENDED_FEATURES_INFO_TYPE);
@@ -790,9 +790,6 @@
                 }
             }
 
-#if L2CAP_HOST_FLOW_CTRL
-            p_lcb->link_ack_thresh = L2CAP_HOST_FC_ACL_BUFS / l2cb.num_links_active;
-#endif
             L2CAP_TRACE_EVENT ("l2c_link_adjust_allocation LCB %d   Priority: %d  XmitQuota: %d",
                                 yy, p_lcb->acl_priority, p_lcb->link_xmit_quota);
 
@@ -803,7 +800,7 @@
             /* this link may have sent anything but some other link sent packets so  */
             /* so we may need a timer to kick off this link's transmissions.         */
             if ( (p_lcb->link_state == LST_CONNECTED)
-              && (p_lcb->link_xmit_data_q.count)
+              && (!list_is_empty(p_lcb->link_xmit_data_q))
               && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota) )
                 btu_start_timer (&p_lcb->timer_entry, BTU_TTYPE_L2CAP_LINK, L2CAP_LINK_FLOW_CONTROL_TOUT);
         }
@@ -960,25 +957,8 @@
 {
     UINT8       num_found = 0;
 
-#if (L2CAP_HOST_FLOW_CTRL == TRUE)
-
-    int         xx;
-    tL2C_LCB    *p_lcb = &l2cb.lcb_pool[0];
-
-    for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++)
-    {
-        if ((p_lcb->in_use) && (p_lcb->link_pkts_unacked))
-        {
-            num_pkts[num_found] = p_lcb->link_pkts_unacked;
-            handles[num_found]  = p_lcb->handle;
-            p_lcb->link_pkts_unacked = 0;
-            num_found++;
-        }
-    }
-#else
     UNUSED(num_pkts);
     UNUSED(handles);
-#endif
 
     return (num_found);
 }
@@ -1046,7 +1026,7 @@
     }
 }
 
-#if ((BTM_PWR_MGR_INCLUDED == TRUE) && L2CAP_WAKE_PARKED_LINK == TRUE)
+#if L2CAP_WAKE_PARKED_LINK == TRUE
 /*******************************************************************************
 **
 ** Function         l2c_link_check_power_mode
@@ -1066,11 +1046,11 @@
     /*
      * We only switch park to active only if we have unsent packets
      */
-    if ( p_lcb->link_xmit_data_q.count == 0 )
+    if (list_is_empty(p_lcb->link_xmit_data_q))
     {
         for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb)
         {
-            if (p_ccb->xmit_hold_q.count != 0)
+            if (!GKI_queue_is_empty(&p_ccb->xmit_hold_q))
             {
                 need_to_active = TRUE;
                 break;
@@ -1096,7 +1076,7 @@
     }
     return FALSE;
 }
-#endif /* ((BTM_PWR_MGR_INCLUDED == TRUE) && L2CAP_WAKE_PARKED_LINK == TRUE) */
+#endif /* L2CAP_WAKE_PARKED_LINK == TRUE) */
 
 /*******************************************************************************
 **
@@ -1126,7 +1106,7 @@
             p_buf->event = 0;
 
         p_buf->layer_specific = 0;
-        GKI_enqueue (&p_lcb->link_xmit_data_q, p_buf);
+        list_append(p_lcb->link_xmit_data_q, p_buf);
 
         if (p_lcb->link_xmit_quota == 0)
         {
@@ -1182,8 +1162,9 @@
                 continue;
 
             /* See if we can send anything from the Link Queue */
-            if ((p_buf = (BT_HDR *)GKI_dequeue (&p_lcb->link_xmit_data_q)) != NULL)
-            {
+            if (!list_is_empty(p_lcb->link_xmit_data_q)) {
+                p_buf = (BT_HDR *)list_front(p_lcb->link_xmit_data_q);
+                list_remove(p_lcb->link_xmit_data_q, p_buf);
                 l2c_link_send_to_lower (p_lcb, p_buf);
             }
             else if (single_write)
@@ -1232,9 +1213,11 @@
              && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota))
 #endif
         {
-            if ((p_buf = (BT_HDR *)GKI_dequeue (&p_lcb->link_xmit_data_q)) == NULL)
+            if (list_is_empty(p_lcb->link_xmit_data_q))
                 break;
 
+            p_buf = (BT_HDR *)list_front(p_lcb->link_xmit_data_q);
+            list_remove(p_lcb->link_xmit_data_q, p_buf);
             if (!l2c_link_send_to_lower (p_lcb, p_buf))
                 break;
         }
@@ -1261,7 +1244,7 @@
         /* There is a special case where we have readjusted the link quotas and  */
         /* this link may have sent anything but some other link sent packets so  */
         /* so we may need a timer to kick off this link's transmissions.         */
-        if ( (p_lcb->link_xmit_data_q.count) && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota) )
+        if ( (!list_is_empty(p_lcb->link_xmit_data_q)) && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota) )
             btu_start_timer (&p_lcb->timer_entry, BTU_TTYPE_L2CAP_LINK, L2CAP_LINK_FLOW_CONTROL_TOUT);
     }
 
@@ -1280,11 +1263,12 @@
 {
     UINT16      num_segs;
     UINT16      xmit_window, acl_data_size;
+    const controller_t *controller = controller_get_interface();
 
-    if ((p_buf->len <= btu_cb.hcit_acl_pkt_size
+    if ((p_buf->len <= controller->get_acl_packet_size_classic()
 #if (BLE_INCLUDED == TRUE)
         && (p_lcb->transport == BT_TRANSPORT_BR_EDR)) ||
-        ((p_lcb->transport == BT_TRANSPORT_LE) && (p_buf->len <= btu_cb.hcit_ble_acl_pkt_size))
+        ((p_lcb->transport == BT_TRANSPORT_LE) && (p_buf->len <= controller->get_acl_packet_size_ble()))
 #else
         )
 #endif
@@ -1306,13 +1290,13 @@
         if (p_lcb->transport == BT_TRANSPORT_LE)
         {
             l2cb.controller_le_xmit_window--;
-            L2C_LINK_SEND_BLE_ACL_DATA (p_buf);
+            bte_main_hci_send(p_buf, (UINT16)(BT_EVT_TO_LM_HCI_ACL|LOCAL_BLE_CONTROLLER_ID));
         }
         else
 #endif
         {
             l2cb.controller_xmit_window--;
-            L2C_LINK_SEND_ACL_DATA (p_buf);
+            bte_main_hci_send(p_buf, BT_EVT_TO_LM_HCI_ACL);
         }
     }
     else
@@ -1320,14 +1304,14 @@
 #if BLE_INCLUDED == TRUE
         if (p_lcb->transport == BT_TRANSPORT_LE)
         {
-            acl_data_size = btu_cb.hcit_ble_acl_data_size;
+            acl_data_size = controller->get_acl_data_size_ble();
             xmit_window = l2cb.controller_le_xmit_window;
 
         }
         else
 #endif
         {
-            acl_data_size = btu_cb.hcit_acl_data_size;
+            acl_data_size = controller->get_acl_data_size_classic();
             xmit_window = l2cb.controller_xmit_window;
         }
         num_segs = (p_buf->len - HCI_DATA_PREAMBLE_SIZE + acl_data_size - 1) / acl_data_size;
@@ -1376,12 +1360,12 @@
 #if BLE_INCLUDED == TRUE
         if (p_lcb->transport == BT_TRANSPORT_LE)
         {
-            L2C_LINK_SEND_BLE_ACL_DATA(p_buf);
+            bte_main_hci_send(p_buf, (UINT16)(BT_EVT_TO_LM_HCI_ACL|LOCAL_BLE_CONTROLLER_ID));
         }
         else
 #endif
         {
-            L2C_LINK_SEND_ACL_DATA (p_buf);
+            bte_main_hci_send(p_buf, BT_EVT_TO_LM_HCI_ACL);
         }
     }
 
@@ -1551,188 +1535,6 @@
 
 /*******************************************************************************
 **
-** Function         l2cap_link_chk_pkt_start
-**
-** Description      This function is called from the HCI transport when the first
-**                  4 bytes of an HCI ACL packet have been received. It checks if the
-**                  packet is the next segment of a fragmented L2CAP message. If it
-**                  is, and the length is OK, it returns the address of the
-**                  starting L2CAP message segment buffer.
-**
-** Returns          the address of the receive buffer HCIT should use
-**                  (CR419: Modified to return NULL in case of error.)
-**
-** NOTE             This assumes that the L2CAP MTU size is less than the size
-**                  of an HCI ACL buffer, so the maximum L2CAP message will fit
-**                  into one buffer.
-**
-*******************************************************************************/
-BT_HDR *l2cap_link_chk_pkt_start (BT_HDR *p_cur_buf)
-{
-    UINT8       *p;
-    UINT16      handle;
-    UINT16      hci_len;
-    UINT16      pkt_type;
-    tL2C_LCB    *p_lcb;
-    BT_HDR *	p_return_buf;       /* CR419: To avoid returning from too many places */
-
-
-    if (p_cur_buf)
-    {
-        p = (UINT8 *)(p_cur_buf + 1) + p_cur_buf->offset;
-    }
-    else
-    {
-        return (NULL);
-    }
-
-    /* L2CAP expects all rcvd packets to have a layer-specific value of 0 */
-    p_cur_buf->layer_specific = 0;
-
-    STREAM_TO_UINT16 (handle, p);
-    STREAM_TO_UINT16 (hci_len, p);
-
-    pkt_type = HCID_GET_EVENT (handle);
-    handle   = HCID_GET_HANDLE (handle);
-
-    l2cb.p_cur_hcit_lcb = NULL;
-
-    /* Find the link that is associated with this handle */
-    p_lcb = l2cu_find_lcb_by_handle (handle);
-
-    /* If no link for this handle, nothing to do. */
-    if (!p_lcb)
-        return (p_cur_buf) ;
-
-    if (pkt_type == L2CAP_PKT_START)            /*** START PACKET ***/
-    {
-        /* Start of packet. If we were in the middle of receiving */
-        /* a packet, it is incomplete. Drop it.                   */
-        if (p_lcb->p_hcit_rcv_acl)
-        {
-            L2CAP_TRACE_WARNING ("L2CAP - dropping incomplete pkt");
-            GKI_freebuf (p_lcb->p_hcit_rcv_acl);
-            p_lcb->p_hcit_rcv_acl = NULL;
-        }
-
-        /* Save the active buffer address in the LCB  */
-        if ((p_return_buf = p_cur_buf) != NULL)
-        {
-            p_lcb->p_hcit_rcv_acl = p_return_buf;
-            l2cb.p_cur_hcit_lcb   = p_lcb;
-        }
-    }
-    else                                        /*** CONTINUATION PACKET ***/
-    {
-        /* Packet continuation. Check if we were expecting it */
-        if (p_lcb->p_hcit_rcv_acl)
-        {
-            UINT16  total_len;
-            BT_HDR  *p_base_buf = p_lcb->p_hcit_rcv_acl;
-            UINT8   *p_f        = (UINT8 *)(p_base_buf + 1) + p_base_buf->offset + 2;
-
-            STREAM_TO_UINT16 (total_len, p_f);
-
-            /* We were expecting the CONTINUATION packet. If length fits, it can go in the  */
-            /* current buffer.                                                              */
-            if ((total_len + hci_len) <= (L2CAP_MTU_SIZE + HCI_DATA_PREAMBLE_SIZE))
-            {
-                /* GKI_freebuf (p_cur_buf); CR419:Do not free it yet */
-                p_return_buf        = p_lcb->p_hcit_rcv_acl;	/* CR419: return base buffer */
-                l2cb.p_cur_hcit_lcb = p_lcb;
-
-                if ((p_cur_buf->len > HCI_DATA_PREAMBLE_SIZE))
-                {
-                    UINT8 *	p		= (UINT8 *)(p_cur_buf + 1)
-                                                + p_cur_buf->offset
-                                                + HCI_DATA_PREAMBLE_SIZE;
-                    UINT8 *	p1		= (UINT8 *)(p_return_buf + 1)
-                                                + p_return_buf->offset
-                                                + p_return_buf->len;
-
-                    /* Copy data from new buffer into base buffer then update the data  */
-                    /* count in the base buffer accordingly.                            */
-                    memcpy (p1, p, p_cur_buf->len - HCI_DATA_PREAMBLE_SIZE);
-                    p_return_buf->len   += (p_cur_buf->len - HCI_DATA_PREAMBLE_SIZE);
-                }
-
-                GKI_freebuf (p_cur_buf);
-                p_cur_buf = NULL;
-
-                /* Update HCI header of first segment (base buffer) with new length */
-                total_len += hci_len;
-                p_f        = (UINT8 *)(p_base_buf + 1) + p_base_buf->offset + 2;
-                UINT16_TO_STREAM (p_f, total_len);
-            }
-            else
-            {
-                /* Packet too long. Drop the base packet */
-                L2CAP_TRACE_WARNING ("L2CAP - dropping too long pkt BufLen: %d  total_len: %d  hci_len: %d",
-                                      p_lcb->p_hcit_rcv_acl->len, total_len, hci_len);
-
-                GKI_freebuf (p_lcb->p_hcit_rcv_acl);
-                p_lcb->p_hcit_rcv_acl = NULL;
-                p_return_buf          = NULL ; /* Can't hold onto it any more */
-            }
-        }
-        else                                    /*** NEITHER START OR CONTINUATION PACKET ***/
-        {
-            p_return_buf = NULL ;
-        }
-    }
-
-    if (p_return_buf == NULL)                   /* if error is indicated..  */
-    {
-        if (p_cur_buf != NULL)                  /* ..drop input buffer      */
-            GKI_freebuf(p_cur_buf);             /*     (if present)         */
-    }
-
-    return (p_return_buf);
-}
-
-/*******************************************************************************
-**
-** Function         l2cap_link_chk_pkt_end
-**
-** Description      This function is called from the HCI transport when the last
-**                  byte of an HCI ACL packet has been received. It checks if the
-**                  L2CAP message is complete, i.e. no more continuation packets
-**                  are expected.
-**
-** Returns          TRUE if message complete, FALSE if continuation expected
-**
-*******************************************************************************/
-BOOLEAN l2cap_link_chk_pkt_end (void)
-{
-    UINT8       *p;
-    BT_HDR      *p_buf;
-    UINT16      l2cap_len;
-    tL2C_LCB    *p_lcb;
-
-    /* If link or buffer pointer not set up, let main line handle it */
-    if (((p_lcb = l2cb.p_cur_hcit_lcb) == NULL) || ((p_buf = p_lcb->p_hcit_rcv_acl) == NULL))
-        return (TRUE);
-
-    /* Point to the L2CAP length */
-    p = (UINT8 *)(p_buf + 1) + p_buf->offset + HCI_DATA_PREAMBLE_SIZE;
-
-    STREAM_TO_UINT16 (l2cap_len, p);
-
-    /* If the L2CAP length has not been reached, tell HCIT not to send this buffer to BTU */
-    if (l2cap_len > (p_buf->len - (HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD)))
-    {
-        return (FALSE);
-    }
-    else
-    {
-        p_lcb->p_hcit_rcv_acl = NULL;
-        return (TRUE);
-    }
-}
-
-
-/*******************************************************************************
-**
 ** Function         l2c_link_segments_xmitted
 **
 ** Description      This function is called from the HCI Interface when an ACL
@@ -1763,7 +1565,7 @@
     {
         /* Enqueue the buffer to the head of the transmit queue, and see */
         /* if we can transmit anything more.                             */
-        GKI_enqueue_head (&p_lcb->link_xmit_data_q, p_msg);
+        list_prepend(p_lcb->link_xmit_data_q, p_msg);
 
         p_lcb->partial_segment_being_sent = FALSE;
 
diff --git a/stack/l2cap/l2c_main.c b/stack/l2cap/l2c_main.c
index c2531a7..8da881c 100755
--- a/stack/l2cap/l2c_main.c
+++ b/stack/l2cap/l2c_main.c
@@ -22,18 +22,21 @@
  *
  ******************************************************************************/
 
-#include "bt_target.h"
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
 
+#include "device/include/controller.h"
+#include "btcore/include/counter.h"
+#include "bt_target.h"
+#include "btm_int.h"
+#include "btu.h"
 #include "gki.h"
 #include "hcimsgs.h"
-#include "l2cdefs.h"
-#include "l2c_int.h"
 #include "l2c_api.h"
-#include "btu.h"
-#include "btm_int.h"
+#include "l2c_int.h"
+#include "l2cdefs.h"
+#include "osi/include/log.h"
 
 /********************************************************************************/
 /*              L O C A L    F U N C T I O N     P R O T O T Y P E S            */
@@ -47,10 +50,6 @@
 tL2C_CB l2cb;
 #endif
 
-/* Temporary - until l2cap implements group management */
-#if (TCS_BCST_SETUP_INCLUDED == TRUE && TCS_INCLUDED == TRUE)
-extern void tcs_proc_bcst_msg( BD_ADDR addr, BT_HDR *p_msg ) ;
-#endif
 /*******************************************************************************
 **
 ** Function         l2c_bcst_msg
@@ -82,10 +81,11 @@
     /* First, the HCI transport header */
     UINT16_TO_STREAM (p, 0x0050 | (L2CAP_PKT_START << 12) | (2 << 14));
 
+    uint16_t acl_data_size = controller_get_interface()->get_acl_data_size_classic();
     /* The HCI transport will segment the buffers. */
-    if (p_buf->len > btu_cb.hcit_acl_data_size)
+    if (p_buf->len > acl_data_size)
     {
-        UINT16_TO_STREAM (p, btu_cb.hcit_acl_data_size);
+        UINT16_TO_STREAM (p, acl_data_size);
     }
     else
     {
@@ -99,9 +99,12 @@
 
     p_buf->len += HCI_DATA_PREAMBLE_SIZE;
 
-    if (p_buf->len <= btu_cb.hcit_acl_pkt_size)
+    if (p_buf->len <= controller_get_interface()->get_acl_packet_size_classic())
     {
-        HCI_ACL_DATA_TO_LOWER (p_buf);
+        counter_add("l2cap.ch2.tx.bytes", p_buf->len);
+        counter_add("l2cap.ch2.tx.pkts", 1);
+
+        bte_main_hci_send(p_buf, BT_EVT_TO_LM_HCI_ACL);
     }
 }
 
@@ -148,23 +151,21 @@
             STREAM_TO_UINT8  (cmd_code, p);
 
             if ((p_msg->layer_specific == 0) && (rcv_cid == L2CAP_SIGNALLING_CID)
-                && (cmd_code == L2CAP_CMD_INFO_REQ || cmd_code == L2CAP_CMD_CONN_REQ))
-            {
-                L2CAP_TRACE_WARNING ("L2CAP - holding ACL for unknown handle:%d ls:%d cid:%d opcode:%d cur count:%d",
-                                    handle, p_msg->layer_specific, rcv_cid, cmd_code,
-                                    l2cb.rcv_hold_q.count);
+                    && (cmd_code == L2CAP_CMD_INFO_REQ || cmd_code == L2CAP_CMD_CONN_REQ)) {
+                L2CAP_TRACE_WARNING ("L2CAP - holding ACL for unknown handle:%d ls:%d"
+                        "  cid:%d opcode:%d cur count:%d", handle, p_msg->layer_specific,
+                        rcv_cid, cmd_code, list_length(l2cb.rcv_pending_q));
                 p_msg->layer_specific = 2;
-                GKI_enqueue (&l2cb.rcv_hold_q, p_msg);
+                list_append(l2cb.rcv_pending_q, p_msg);
 
-                if (l2cb.rcv_hold_q.count == 1)
+                if (list_length(l2cb.rcv_pending_q) == 1)
                     btu_start_timer (&l2cb.rcv_hold_tle, BTU_TTYPE_L2CAP_HOLD, BT_1SEC_TIMEOUT);
 
                 return;
-            }
-            else
-            {
-                L2CAP_TRACE_ERROR ("L2CAP - rcvd ACL for unknown handle:%d ls:%d cid:%d opcode:%d cur count:%d",
-                                    handle, p_msg->layer_specific, rcv_cid, cmd_code, l2cb.rcv_hold_q.count);
+            } else {
+                L2CAP_TRACE_ERROR ("L2CAP - rcvd ACL for unknown handle:%d ls:%d cid:%d"
+                        " opcode:%d cur count:%d", handle, p_msg->layer_specific, rcv_cid,
+                        cmd_code, list_length(l2cb.rcv_pending_q));
             }
             GKI_freebuf (p_msg);
             return;
@@ -181,12 +182,6 @@
     STREAM_TO_UINT16 (hci_len, p);
     p_msg->offset += 4;
 
-#if (L2CAP_HOST_FLOW_CTRL == TRUE)
-    /* Send ack if we hit the threshold */
-    if (++p_lcb->link_pkts_unacked >= p_lcb->link_ack_thresh)
-        btu_hcif_send_host_rdy_for_data();
-#endif
-
     /* Extract the length and CID */
     STREAM_TO_UINT16 (l2cap_len, p);
     STREAM_TO_UINT16 (rcv_cid, p);
@@ -226,24 +221,18 @@
     /* Send the data through the channel state machine */
     if (rcv_cid == L2CAP_SIGNALLING_CID)
     {
+        counter_add("l2cap.sig.rx.bytes", l2cap_len);
+        counter_add("l2cap.sig.rx.pkts", 1);
         process_l2cap_cmd (p_lcb, p, l2cap_len);
         GKI_freebuf (p_msg);
     }
     else if (rcv_cid == L2CAP_CONNECTIONLESS_CID)
     {
+        counter_add("l2cap.ch2.rx.bytes", l2cap_len);
+        counter_add("l2cap.ch2.rx.pkts", 1);
         /* process_connectionless_data (p_lcb); */
         STREAM_TO_UINT16 (psm, p);
         L2CAP_TRACE_DEBUG( "GOT CONNECTIONLESS DATA PSM:%d", psm ) ;
-#if (TCS_BCST_SETUP_INCLUDED == TRUE && TCS_INCLUDED == TRUE)
-        if (psm == TCS_PSM_INTERCOM || psm == TCS_PSM_CORDLESS)
-        {
-            p_msg->offset += L2CAP_BCST_OVERHEAD;
-            p_msg->len -= L2CAP_BCST_OVERHEAD;
-            tcs_proc_bcst_msg( p_lcb->remote_bd_addr, p_msg ) ;
-            GKI_freebuf (p_msg);
-        }
-        else
-#endif
 
 #if (L2CAP_UCD_INCLUDED == TRUE)
         /* if it is not broadcast, check UCD registration */
@@ -258,6 +247,8 @@
 #if (BLE_INCLUDED == TRUE)
     else if (rcv_cid == L2CAP_BLE_SIGNALLING_CID)
     {
+        counter_add("l2cap.ble.rx.bytes", l2cap_len);
+        counter_add("l2cap.ble.rx.pkts", 1);
         l2cble_process_sig_cmd (p_lcb, p, l2cap_len);
         GKI_freebuf (p_msg);
     }
@@ -266,6 +257,8 @@
     else if ((rcv_cid >= L2CAP_FIRST_FIXED_CHNL) && (rcv_cid <= L2CAP_LAST_FIXED_CHNL) &&
              (l2cb.fixed_reg[rcv_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb != NULL) )
     {
+        counter_add("l2cap.fix.rx.bytes", l2cap_len);
+        counter_add("l2cap.fix.rx.pkts", 1);
         /* If no CCB for this channel, allocate one */
         if (p_lcb &&
             /* discard fixed channel data when link is disconnecting */
@@ -290,6 +283,8 @@
 
     else
     {
+        counter_add("l2cap.dyn.rx.bytes", l2cap_len);
+        counter_add("l2cap.dyn.rx.pkts", 1);
         if (p_ccb == NULL)
             GKI_freebuf (p_msg);
         else
@@ -811,38 +806,30 @@
 ** Returns          void
 **
 *******************************************************************************/
-void l2c_process_held_packets (BOOLEAN timed_out)
-{
-    BT_HDR      *p_buf, *p_buf1;
-    BUFFER_Q    *p_rcv_hold_q = &l2cb.rcv_hold_q;
-
-    if (!p_rcv_hold_q->count)
+void l2c_process_held_packets(BOOLEAN timed_out) {
+    if (list_is_empty(l2cb.rcv_pending_q))
         return;
 
-    if (!timed_out)
-    {
+    if (!timed_out) {
         btu_stop_timer(&l2cb.rcv_hold_tle);
         L2CAP_TRACE_WARNING("L2CAP HOLD CONTINUE");
-    }
-    else
-    {
+    } else {
         L2CAP_TRACE_WARNING("L2CAP HOLD TIMEOUT");
     }
 
-    /* Update the timeouts in the hold queue */
-    for (p_buf = (BT_HDR *)GKI_getfirst (p_rcv_hold_q); p_buf; p_buf = p_buf1)
-    {
-        p_buf1 = (BT_HDR *)GKI_getnext (p_buf);
-        if (!timed_out || (!p_buf->layer_specific) || (--p_buf->layer_specific == 0))
-        {
-            GKI_remove_from_queue (p_rcv_hold_q, p_buf);
+    for (const list_node_t *node = list_begin(l2cb.rcv_pending_q);
+        node != list_end(l2cb.rcv_pending_q);)  {
+        BT_HDR *p_buf = list_node(node);
+        node = list_next(node);
+        if (!timed_out || (!p_buf->layer_specific) || (--p_buf->layer_specific == 0)) {
+            list_remove(l2cb.rcv_pending_q, p_buf);
             p_buf->layer_specific = 0xFFFF;
-            l2c_rcv_acl_data (p_buf);
+            l2c_rcv_acl_data(p_buf);
         }
     }
 
     /* If anyone still in the queue, restart the timeout */
-    if (p_rcv_hold_q->count)
+    if (!list_is_empty(l2cb.rcv_pending_q))
         btu_start_timer (&l2cb.rcv_hold_tle, BTU_TTYPE_L2CAP_HOLD, BT_1SEC_TIMEOUT);
 }
 
@@ -905,6 +892,13 @@
     l2cb.high_pri_min_xmit_quota = L2CAP_HIGH_PRI_MIN_XMIT_QUOTA;
 #endif
 
+    l2cb.rcv_pending_q = list_new(NULL);
+    if (l2cb.rcv_pending_q == NULL)
+        LOG_ERROR("%s unable to allocate memory for link layer control block", __func__);
+}
+
+void l2c_free(void) {
+    list_free(l2cb.rcv_pending_q);
 }
 
 /*******************************************************************************
@@ -984,12 +978,15 @@
     if (p_ccb->cong_sent)
     {
         L2CAP_TRACE_ERROR ("L2CAP - CID: 0x%04x cannot send, already congested  xmit_hold_q.count: %u  buff_quota: %u",
-                            p_ccb->local_cid, p_ccb->xmit_hold_q.count, p_ccb->buff_quota);
+                            p_ccb->local_cid, GKI_queue_length(&p_ccb->xmit_hold_q), p_ccb->buff_quota);
 
         GKI_freebuf (p_data);
         return (L2CAP_DW_FAILED);
     }
 
+    counter_add("l2cap.dyn.tx.bytes", p_data->len);
+    counter_add("l2cap.dyn.tx.pkts", 1);
+
     l2c_csm_execute (p_ccb, L2CEVT_L2CA_DATA_WRITE, p_data);
 
     if (p_ccb->cong_sent)
diff --git a/stack/l2cap/l2c_utils.c b/stack/l2cap/l2c_utils.c
index 77849ac..a4267a5 100644
--- a/stack/l2cap/l2c_utils.c
+++ b/stack/l2cap/l2c_utils.c
@@ -26,6 +26,8 @@
 #include <string.h>
 #include <stdio.h>
 
+#include "device/include/controller.h"
+#include "btcore/include/counter.h"
 #include "gki.h"
 #include "bt_types.h"
 #include "hcimsgs.h"
@@ -36,8 +38,8 @@
 #include "btm_api.h"
 #include "btm_int.h"
 #include "hcidefs.h"
-#include "bd.h"
 #include "bt_utils.h"
+#include "osi/include/allocator.h"
 
 /*******************************************************************************
 **
@@ -84,6 +86,7 @@
                 l2cb.num_links_active++;
                 l2c_link_adjust_allocation();
             }
+            p_lcb->link_xmit_data_q = list_new(NULL);
             return (p_lcb);
         }
     }
@@ -174,7 +177,9 @@
     }
 
 #if (BLE_INCLUDED == TRUE)
-    l2cb.is_ble_connecting = FALSE;
+    // Reset BLE connecting flag only if the address matches
+    if (!memcmp(l2cb.ble_connecting_bda, p_lcb->remote_bd_addr, BD_ADDR_LEN))
+        l2cb.is_ble_connecting = FALSE;
 #endif
 
 #if (L2CAP_NUM_FIXED_CHNLS > 0)
@@ -210,8 +215,13 @@
         btm_acl_removed (p_lcb->remote_bd_addr, BT_TRANSPORT_BR_EDR);
 #endif
     /* Release any held buffers */
-    while (p_lcb->link_xmit_data_q.p_first)
-        GKI_freebuf (GKI_dequeue (&p_lcb->link_xmit_data_q));
+    while (!list_is_empty(p_lcb->link_xmit_data_q)) {
+        BT_HDR *p_buf = list_front(p_lcb->link_xmit_data_q);
+        list_remove(p_lcb->link_xmit_data_q, p_buf);
+        GKI_freebuf(p_buf);
+    }
+    list_free(p_lcb->link_xmit_data_q);
+    p_lcb->link_xmit_data_q = NULL;
 
 #if (L2CAP_UCD_INCLUDED == TRUE)
     /* clean up any security pending UCD */
@@ -376,11 +386,16 @@
 #if (BLE_INCLUDED == TRUE)
     if (p_lcb->transport == BT_TRANSPORT_LE)
     {
+        counter_add("l2cap.ble.tx.bytes", p_buf->len);
+        counter_add("l2cap.ble.tx.pkts", 1);
+
         UINT16_TO_STREAM (p, L2CAP_BLE_SIGNALLING_CID);
     }
     else
 #endif
     {
+        counter_add("l2cap.sig.tx.bytes", p_buf->len);
+        counter_add("l2cap.sig.tx.pkts", 1);
         UINT16_TO_STREAM (p, L2CAP_SIGNALLING_CID);
     }
 
@@ -934,7 +949,7 @@
     */
     if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_BASIC_MODE)
     {
-        while (p_ccb->xmit_hold_q.p_first)
+        while (GKI_getfirst(&p_ccb->xmit_hold_q))
         {
             p_buf2 = (BT_HDR *)GKI_dequeue (&p_ccb->xmit_hold_q);
             l2cu_set_acl_hci_header (p_buf2, p_ccb);
@@ -1048,9 +1063,11 @@
         return;
     }
 
+    uint16_t acl_data_size = controller_get_interface()->get_acl_data_size_classic();
+    uint16_t acl_packet_size = controller_get_interface()->get_acl_packet_size_classic();
     /* Don't return data if it does not fit in ACL and L2CAP MTU */
-    maxlen = (GKI_get_pool_bufsize(L2CAP_CMD_POOL_ID) > btu_cb.hcit_acl_pkt_size) ?
-               btu_cb.hcit_acl_data_size : (UINT16)GKI_get_pool_bufsize(L2CAP_CMD_POOL_ID);
+    maxlen = (GKI_get_pool_bufsize(L2CAP_CMD_POOL_ID) > acl_packet_size) ?
+               acl_data_size : (UINT16)GKI_get_pool_bufsize(L2CAP_CMD_POOL_ID);
     maxlen -= (UINT16)(BT_HDR_SIZE + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD +
                 L2CAP_CMD_OVERHEAD + L2CAP_ECHO_RSP_LEN);
 
@@ -1514,6 +1531,7 @@
 
     p_ccb->p_lcb = p_lcb;
     p_ccb->p_rcb = NULL;
+    p_ccb->should_free_rcb = false;
 
     /* Set priority then insert ccb into LCB queue (if we have an LCB) */
     p_ccb->ccb_priority = L2CAP_CHNL_PRIORITY_LOW;
@@ -1680,12 +1698,19 @@
         btm_sec_clr_service_by_psm(p_rcb->psm);
     }
 
+    if (p_ccb->should_free_rcb)
+    {
+        osi_free(p_rcb);
+        p_ccb->p_rcb = NULL;
+        p_ccb->should_free_rcb = false;
+    }
+
     btm_sec_clr_temp_auth_service (p_lcb->remote_bd_addr);
 
     /* Stop the timer */
     btu_stop_timer (&p_ccb->timer_entry);
 
-    while (p_ccb->xmit_hold_q.p_first)
+    while (!GKI_queue_is_empty(&p_ccb->xmit_hold_q))
         GKI_freebuf (GKI_dequeue (&p_ccb->xmit_hold_q));
 
     l2c_fcr_cleanup (p_ccb);
@@ -2197,10 +2222,6 @@
 #endif
 }
 
-#if (TCS_WUG_MEMBER_INCLUDED == TRUE && TCS_INCLUDED == TRUE)
-extern UINT16 tcs_wug_get_clk_offset( BD_ADDR addr ) ;
-#endif
-
 /*******************************************************************************
 **
 ** Function         l2cu_create_conn
@@ -2227,7 +2248,7 @@
 
     if (transport == BT_TRANSPORT_LE)
     {
-        if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
+        if (!controller_get_interface()->supports_ble())
             return FALSE;
 
         p_lcb->ble_addr_type = addr_type;
@@ -2347,35 +2368,21 @@
 
     p_lcb->link_state = LST_CONNECTING;
 
-
-#if (TCS_WUG_MEMBER_INCLUDED == TRUE && TCS_INCLUDED == TRUE)
-    if ( (clock_offset = tcs_wug_get_clk_offset( p_lcb->remote_bd_addr )) != 0 )
+    /* Check with the BT manager if details about remote device are known */
+    if ((p_inq_info = BTM_InqDbRead(p_lcb->remote_bd_addr)) != NULL)
     {
-        page_scan_rep_mode = HCI_PAGE_SCAN_REP_MODE_R0;
-        page_scan_mode = HCI_MANDATARY_PAGE_SCAN_MODE;
+        page_scan_rep_mode = p_inq_info->results.page_scan_rep_mode;
+        page_scan_mode = p_inq_info->results.page_scan_mode;
+        clock_offset = (UINT16)(p_inq_info->results.clock_offset);
     }
     else
     {
-#endif
+        /* No info known. Use default settings */
+        page_scan_rep_mode = HCI_PAGE_SCAN_REP_MODE_R1;
+        page_scan_mode = HCI_MANDATARY_PAGE_SCAN_MODE;
 
-        /* Check with the BT manager if details about remote device are known */
-        if ((p_inq_info = BTM_InqDbRead(p_lcb->remote_bd_addr)) != NULL)
-        {
-            page_scan_rep_mode = p_inq_info->results.page_scan_rep_mode;
-            page_scan_mode = p_inq_info->results.page_scan_mode;
-            clock_offset = (UINT16)(p_inq_info->results.clock_offset);
-        }
-        else
-        {
-            /* No info known. Use default settings */
-            page_scan_rep_mode = HCI_PAGE_SCAN_REP_MODE_R1;
-            page_scan_mode = HCI_MANDATARY_PAGE_SCAN_MODE;
-
-            clock_offset = (p_dev_rec) ? p_dev_rec->clock_offset : 0;
-        }
-#if (TCS_WUG_MEMBER_INCLUDED == TRUE && TCS_INCLUDED == TRUE)
+        clock_offset = (p_dev_rec) ? p_dev_rec->clock_offset : 0;
     }
-#endif
 
     if (!btsnd_hcic_create_conn (p_lcb->remote_bd_addr,
                                  ( HCI_PKT_TYPES_MASK_DM1 | HCI_PKT_TYPES_MASK_DH1
@@ -2392,9 +2399,7 @@
         return (FALSE);
     }
 
-#if (defined(BTM_BUSY_LEVEL_CHANGE_INCLUDED) && BTM_BUSY_LEVEL_CHANGE_INCLUDED == TRUE)
     btm_acl_update_busy_level (BTM_BLI_PAGE_EVT);
-#endif
 
     btu_start_timer (&p_lcb->timer_entry, BTU_TTYPE_L2CAP_LINK,
                      L2CAP_LINK_CONNECT_TOUT);
@@ -3108,7 +3113,7 @@
             }
 
             L2CAP_TRACE_DEBUG("RR scan pri=%d, lcid=0x%04x, q_cout=%d",
-                                p_ccb->ccb_priority, p_ccb->local_cid, p_ccb->xmit_hold_q.count );
+                                p_ccb->ccb_priority, p_ccb->local_cid, GKI_queue_length(&p_ccb->xmit_hold_q));
 
             /* store the next serving channel */
             /* this channel is the last channel of its priority group */
@@ -3133,9 +3138,9 @@
                 if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy)
                     continue;
 
-                if ( p_ccb->fcrb.retrans_q.count == 0 )
+                if ( GKI_queue_is_empty(&p_ccb->fcrb.retrans_q))
                 {
-                    if ( p_ccb->xmit_hold_q.count == 0 )
+                    if ( GKI_queue_is_empty(&p_ccb->xmit_hold_q))
                         continue;
 
                     /* If using the common pool, should be at least 10% free. */
@@ -3149,7 +3154,7 @@
             }
             else
             {
-                if (p_ccb->xmit_hold_q.count == 0)
+                if (GKI_queue_is_empty(&p_ccb->xmit_hold_q))
                     continue;
             }
 
@@ -3259,9 +3264,9 @@
                 continue;
 
             /* No more checks needed if sending from the reatransmit queue */
-            if (p_ccb->fcrb.retrans_q.count == 0)
+            if (GKI_queue_is_empty(&p_ccb->fcrb.retrans_q))
             {
-                if (p_ccb->xmit_hold_q.count == 0)
+                if (GKI_queue_is_empty(&p_ccb->xmit_hold_q))
                     continue;
 
                 /* If using the common pool, should be at least 10% free. */
@@ -3282,7 +3287,7 @@
         }
         else
         {
-            if (p_ccb->xmit_hold_q.count != 0)
+            if (!GKI_queue_is_empty(&p_ccb->xmit_hold_q))
             {
                 p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->xmit_hold_q);
                 if(NULL == p_buf)
@@ -3356,10 +3361,11 @@
     {
         UINT16_TO_STREAM (p, p_ccb->p_lcb->handle | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT));
 
+        uint16_t acl_data_size = controller_get_interface()->get_acl_data_size_ble();
         /* The HCI transport will segment the buffers. */
-        if (p_buf->len > btu_cb.hcit_ble_acl_data_size)
+        if (p_buf->len > acl_data_size)
         {
-            UINT16_TO_STREAM (p, btu_cb.hcit_ble_acl_data_size);
+            UINT16_TO_STREAM (p, acl_data_size);
         }
         else
         {
@@ -3383,10 +3389,11 @@
         UINT16_TO_STREAM (p, p_ccb->p_lcb->handle | (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT));
 #endif
 
+        uint16_t acl_data_size = controller_get_interface()->get_acl_data_size_classic();
         /* The HCI transport will segment the buffers. */
-        if (p_buf->len > btu_cb.hcit_acl_data_size)
+        if (p_buf->len > acl_data_size)
         {
-            UINT16_TO_STREAM (p, btu_cb.hcit_acl_data_size);
+            UINT16_TO_STREAM (p, acl_data_size);
         }
         else
         {
@@ -3408,7 +3415,7 @@
 *******************************************************************************/
 void l2cu_check_channel_congestion (tL2C_CCB *p_ccb)
 {
-    UINT16 q_count = p_ccb->xmit_hold_q.count;
+    UINT16 q_count = GKI_queue_length(&p_ccb->xmit_hold_q);
 
 #if (L2CAP_UCD_INCLUDED == TRUE)
     if ( p_ccb->local_cid == L2CAP_CONNECTIONLESS_CID )
diff --git a/stack/l2cap/l2cap_client.c b/stack/l2cap/l2cap_client.c
new file mode 100644
index 0000000..6e671fc
--- /dev/null
+++ b/stack/l2cap/l2cap_client.c
@@ -0,0 +1,434 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  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.
+ *
+ ******************************************************************************/
+
+#define LOG_TAG "bt_l2cap_client"
+
+#include <assert.h>
+
+#include "btcore/include/bdaddr.h"
+#include "gki/common/gki.h"
+#include "osi/include/allocator.h"
+#include "osi/include/buffer.h"
+#include "osi/include/list.h"
+#include "osi/include/log.h"
+#include "osi/include/osi.h"
+#include "stack/include/l2cap_client.h"
+#include "stack/include/l2c_api.h"
+
+struct l2cap_client_t {
+  l2cap_client_callbacks_t callbacks;
+  void *context;
+
+  uint16_t local_channel_id;
+  uint16_t remote_mtu;
+  bool configured_self;
+  bool configured_peer;
+  bool is_congested;
+  list_t *outbound_fragments;
+};
+
+static void connect_completed_cb(uint16_t local_channel_id, uint16_t error_code);
+static void config_request_cb(uint16_t local_channel_id, tL2CAP_CFG_INFO *requested_parameters);
+static void config_completed_cb(uint16_t local_channel_id, tL2CAP_CFG_INFO *negotiated_parameters);
+static void disconnect_request_cb(uint16_t local_channel_id, bool ack_required);
+static void disconnect_completed_cb(uint16_t local_channel_id, uint16_t error_code);
+static void congestion_cb(uint16_t local_channel_id, bool is_congested);
+static void read_ready_cb(uint16_t local_channel_id, BT_HDR *packet);
+static void write_completed_cb(uint16_t local_channel_id, uint16_t packets_completed);
+
+static void fragment_packet(l2cap_client_t *client, buffer_t *packet);
+static void dispatch_fragments(l2cap_client_t *client);
+static l2cap_client_t *find(uint16_t local_channel_id);
+
+// From the Bluetooth Core specification.
+static const uint16_t L2CAP_MTU_DEFAULT = 672;
+static const uint16_t L2CAP_MTU_MINIMUM = 48;
+
+static const tL2CAP_APPL_INFO l2cap_callbacks = {
+  .pL2CA_ConnectCfm_Cb       = connect_completed_cb,
+  .pL2CA_ConfigInd_Cb        = config_request_cb,
+  .pL2CA_ConfigCfm_Cb        = config_completed_cb,
+  .pL2CA_DisconnectInd_Cb    = disconnect_request_cb,
+  .pL2CA_DisconnectCfm_Cb    = disconnect_completed_cb,
+  .pL2CA_CongestionStatus_Cb = congestion_cb,
+  .pL2CA_DataInd_Cb          = read_ready_cb,
+  .pL2CA_TxComplete_Cb       = write_completed_cb,
+};
+
+static list_t *l2cap_clients;  // A list of l2cap_client_t. Container does not own objects.
+
+buffer_t *l2cap_buffer_new(size_t size) {
+  buffer_t *buf = buffer_new(size + L2CAP_MIN_OFFSET);
+  buffer_t *slice = NULL;
+  if (buf)
+    slice = buffer_new_slice(buf, size);
+  buffer_free(buf);
+  return slice;
+}
+
+l2cap_client_t *l2cap_client_new(const l2cap_client_callbacks_t *callbacks, void *context) {
+  assert(callbacks != NULL);
+  assert(callbacks->connected != NULL);
+  assert(callbacks->disconnected != NULL);
+  assert(callbacks->read_ready != NULL);
+  assert(callbacks->write_ready != NULL);
+
+  if (!l2cap_clients) {
+    l2cap_clients = list_new(NULL);
+    if (!l2cap_clients) {
+      LOG_ERROR("%s unable to allocate space for L2CAP client list.", __func__);
+      return NULL;
+    }
+  }
+
+  l2cap_client_t *ret = (l2cap_client_t *)osi_calloc(sizeof(l2cap_client_t));
+  if (!ret) {
+    LOG_ERROR("%s unable to allocate L2CAP client.", __func__);
+    goto error;
+  }
+
+  ret->callbacks = *callbacks;
+  ret->context = context;
+
+  ret->remote_mtu = L2CAP_MTU_DEFAULT;
+  ret->outbound_fragments = list_new(NULL);
+  if (!ret) {
+    LOG_ERROR("%s unable to allocate outbound L2CAP fragment list.", __func__);
+    goto error;
+  }
+
+  list_append(l2cap_clients, ret);
+
+  return ret;
+
+error:;
+  osi_free(ret);
+  return NULL;
+}
+
+void l2cap_client_free(l2cap_client_t *client) {
+  if (!client)
+    return;
+
+  list_remove(l2cap_clients, client);
+  l2cap_client_disconnect(client);
+  list_free(client->outbound_fragments);
+  osi_free(client);
+}
+
+bool l2cap_client_connect(l2cap_client_t *client, const bt_bdaddr_t *remote_bdaddr, uint16_t psm) {
+  assert(client != NULL);
+  assert(remote_bdaddr != NULL);
+  assert(psm != 0);
+  assert(!bdaddr_is_empty(remote_bdaddr));
+  assert(client->local_channel_id == 0);
+  assert(!client->configured_self);
+  assert(!client->configured_peer);
+  assert(!L2C_INVALID_PSM(psm));
+
+  client->local_channel_id = L2CA_ConnectReq(psm, (uint8_t *)remote_bdaddr);
+  if (!client->local_channel_id) {
+    LOG_ERROR("%s unable to create L2CAP connection.", __func__);
+    return false;
+  }
+
+  L2CA_SetConnectionCallbacks(client->local_channel_id, &l2cap_callbacks);
+  return true;
+}
+
+void l2cap_client_disconnect(l2cap_client_t *client) {
+  assert(client != NULL);
+
+  if (client->local_channel_id && !L2CA_DisconnectReq(client->local_channel_id))
+    LOG_ERROR("%s unable to send disconnect message for LCID 0x%04x.", __func__, client->local_channel_id);
+
+  client->local_channel_id = 0;
+  client->remote_mtu = L2CAP_MTU_DEFAULT;
+  client->configured_self = false;
+  client->configured_peer = false;
+  client->is_congested = false;
+
+  for (const list_node_t *node = list_begin(client->outbound_fragments); node != list_end(client->outbound_fragments); node = list_next(node))
+    GKI_freebuf(list_node(node));
+
+  list_clear(client->outbound_fragments);
+}
+
+bool l2cap_client_is_connected(const l2cap_client_t *client) {
+  assert(client != NULL);
+
+  return client->local_channel_id != 0 && client->configured_self && client->configured_peer;
+}
+
+bool l2cap_client_write(l2cap_client_t *client, buffer_t *packet) {
+  assert(client != NULL);
+  assert(packet != NULL);
+  assert(l2cap_client_is_connected(client));
+
+  if (client->is_congested)
+    return false;
+
+  fragment_packet(client, packet);
+  dispatch_fragments(client);
+  return true;
+}
+
+static void connect_completed_cb(uint16_t local_channel_id, uint16_t error_code) {
+  assert(local_channel_id != 0);
+
+  l2cap_client_t *client = find(local_channel_id);
+  if (!client) {
+    LOG_ERROR("%s unable to find L2CAP client for LCID 0x%04x.", __func__, local_channel_id);
+    return;
+  }
+
+  if (error_code != L2CAP_CONN_OK) {
+    LOG_ERROR("%s error connecting L2CAP channel: %d.", __func__, error_code);
+    client->callbacks.disconnected(client, client->context);
+    return;
+  }
+
+  // Use default L2CAP parameters.
+  tL2CAP_CFG_INFO desired_parameters = { 0 };
+  if (!L2CA_ConfigReq(local_channel_id, &desired_parameters)) {
+    LOG_ERROR("%s error sending L2CAP config parameters.", __func__);
+    client->callbacks.disconnected(client, client->context);
+  }
+}
+
+static void config_request_cb(uint16_t local_channel_id, tL2CAP_CFG_INFO *requested_parameters) {
+  tL2CAP_CFG_INFO response = { 0 };
+  l2cap_client_t *client = find(local_channel_id);
+
+  if (!client) {
+    LOG_ERROR("%s unable to find L2CAP client matching LCID 0x%04x.", __func__, local_channel_id);
+    return;
+  }
+
+  response.result = L2CAP_CFG_OK;
+
+  if (requested_parameters->mtu_present) {
+    // Make sure the peer chose an MTU at least as large as the minimum L2CAP MTU defined
+    // by the Bluetooth Core spec.
+    if (requested_parameters->mtu < L2CAP_MTU_MINIMUM) {
+      response.mtu = L2CAP_MTU_MINIMUM;
+      response.mtu_present = true;
+      response.result = L2CAP_CFG_UNACCEPTABLE_PARAMS;
+    } else {
+      client->remote_mtu = requested_parameters->mtu;
+    }
+  }
+
+  if (requested_parameters->fcr_present) {
+    if (requested_parameters->fcr.mode != L2CAP_FCR_BASIC_MODE) {
+      response.fcr_present = true;
+      response.fcr = requested_parameters->fcr;
+      response.fcr.mode = L2CAP_FCR_BASIC_MODE;
+      response.result = L2CAP_CFG_UNACCEPTABLE_PARAMS;
+    }
+  }
+
+  if (!L2CA_ConfigRsp(local_channel_id, &response)) {
+    LOG_ERROR("%s unable to send config response for LCID 0x%04x.", __func__, local_channel_id);
+    l2cap_client_disconnect(client);
+    return;
+  }
+
+  // If we've configured both endpoints, let the listener know we've connected.
+  client->configured_peer = true;
+  if (l2cap_client_is_connected(client))
+    client->callbacks.connected(client, client->context);
+}
+
+static void config_completed_cb(uint16_t local_channel_id, tL2CAP_CFG_INFO *negotiated_parameters) {
+  l2cap_client_t *client = find(local_channel_id);
+
+  if (!client) {
+    LOG_ERROR("%s unable to find L2CAP client matching LCID 0x%04x.", __func__, local_channel_id);
+    return;
+  }
+
+  switch (negotiated_parameters->result) {
+    // We'll get another configuration response later.
+    case L2CAP_CFG_PENDING:
+      break;
+
+    case L2CAP_CFG_UNACCEPTABLE_PARAMS:
+      // TODO: see if we can renegotiate parameters instead of dropping the connection.
+      LOG_WARN("%s dropping L2CAP connection due to unacceptable config parameters.", __func__);
+      l2cap_client_disconnect(client);
+      break;
+
+    case L2CAP_CFG_OK:
+      // If we've configured both endpoints, let the listener know we've connected.
+      client->configured_self = true;
+      if (l2cap_client_is_connected(client))
+        client->callbacks.connected(client, client->context);
+      break;
+
+    // Failure, no further parameter negotiation possible.
+    default:
+      LOG_WARN("%s L2CAP parameter negotiation failed with error code %d.", __func__, negotiated_parameters->result);
+      l2cap_client_disconnect(client);
+      break;
+  }
+}
+
+static void disconnect_request_cb(uint16_t local_channel_id, bool ack_required) {
+  l2cap_client_t *client = find(local_channel_id);
+  if (!client) {
+    LOG_ERROR("%s unable to find L2CAP client with LCID 0x%04x.", __func__, local_channel_id);
+    return;
+  }
+
+  if (ack_required)
+    L2CA_DisconnectRsp(local_channel_id);
+
+  // We already sent a disconnect response so this LCID is now invalid.
+  client->local_channel_id = 0;
+  l2cap_client_disconnect(client);
+
+  client->callbacks.disconnected(client, client->context);
+}
+
+static void disconnect_completed_cb(uint16_t local_channel_id, UNUSED_ATTR uint16_t error_code) {
+  assert(local_channel_id != 0);
+
+  l2cap_client_t *client = find(local_channel_id);
+  if (!client) {
+    LOG_ERROR("%s unable to find L2CAP client with LCID 0x%04x.", __func__, local_channel_id);
+    return;
+  }
+
+  client->local_channel_id = 0;
+  l2cap_client_disconnect(client);
+
+  client->callbacks.disconnected(client, client->context);
+}
+
+static void congestion_cb(uint16_t local_channel_id, bool is_congested) {
+  assert(local_channel_id != 0);
+
+  l2cap_client_t *client = find(local_channel_id);
+  if (!client) {
+    LOG_ERROR("%s unable to find L2CAP client matching LCID 0x%04x.", __func__, local_channel_id);
+    return;
+  }
+
+  client->is_congested = is_congested;
+
+  if (!is_congested) {
+    // If we just decongested, dispatch whatever we have left over in our queue.
+    // Once that's done, if we're still decongested, notify the listener so it
+    // can start writing again.
+    dispatch_fragments(client);
+    if (!client->is_congested)
+      client->callbacks.write_ready(client, client->context);
+  }
+}
+
+static void read_ready_cb(uint16_t local_channel_id, BT_HDR *packet) {
+  assert(local_channel_id != 0);
+
+  l2cap_client_t *client = find(local_channel_id);
+  if (!client) {
+    LOG_ERROR("%s unable to find L2CAP client matching LCID 0x%04x.", __func__, local_channel_id);
+    return;
+  }
+
+  // TODO(sharvil): eliminate copy from BT_HDR.
+  buffer_t *buffer = buffer_new(packet->len);
+  memcpy(buffer_ptr(buffer), packet->data + packet->offset, packet->len);
+  GKI_freebuf(packet);
+
+  client->callbacks.read_ready(client, buffer, client->context);
+  buffer_free(buffer);
+}
+
+static void write_completed_cb(UNUSED_ATTR uint16_t local_channel_id, UNUSED_ATTR uint16_t packets_completed) {
+  // Do nothing. We update congestion state based on the congestion callback
+  // and we've already removed items from outbound_fragments list so we don't
+  // really care how many packets were successfully dispatched.
+}
+
+static void fragment_packet(l2cap_client_t *client, buffer_t *packet) {
+  assert(client != NULL);
+  assert(packet != NULL);
+
+  // TODO(sharvil): eliminate copy into BT_HDR.
+  BT_HDR *bt_packet = GKI_getbuf(buffer_length(packet) + L2CAP_MIN_OFFSET);
+  bt_packet->offset = L2CAP_MIN_OFFSET;
+  bt_packet->len = buffer_length(packet);
+  memcpy(bt_packet->data + bt_packet->offset, buffer_ptr(packet), buffer_length(packet));
+
+  for (;;) {
+    if (bt_packet->len <= client->remote_mtu) {
+      if (bt_packet->len > 0)
+        list_append(client->outbound_fragments, bt_packet);
+      else
+        GKI_freebuf(bt_packet);
+      break;
+    }
+
+    BT_HDR *fragment = GKI_getbuf(client->remote_mtu + L2CAP_MIN_OFFSET);
+    fragment->offset = L2CAP_MIN_OFFSET;
+    fragment->len = client->remote_mtu;
+    memcpy(fragment->data + fragment->offset, bt_packet->data + bt_packet->offset, client->remote_mtu);
+
+    list_append(client->outbound_fragments, fragment);
+
+    bt_packet->offset += client->remote_mtu;
+    bt_packet->len -= client->remote_mtu;
+  }
+}
+
+static void dispatch_fragments(l2cap_client_t *client) {
+  assert(client != NULL);
+  assert(!client->is_congested);
+
+  while (!list_is_empty(client->outbound_fragments)) {
+    BT_HDR *packet = (BT_HDR *)list_front(client->outbound_fragments);
+    list_remove(client->outbound_fragments, packet);
+
+    switch (L2CA_DataWrite(client->local_channel_id, packet)) {
+      case L2CAP_DW_CONGESTED:
+        client->is_congested = true;
+        return;
+
+      case L2CAP_DW_FAILED:
+        LOG_ERROR("%s error writing data to L2CAP connection LCID 0x%04x; disconnecting.", __func__, client->local_channel_id);
+        l2cap_client_disconnect(client);
+        return;
+
+      case L2CAP_DW_SUCCESS:
+        break;
+    }
+  }
+}
+
+static l2cap_client_t *find(uint16_t local_channel_id) {
+  assert(local_channel_id != 0);
+
+  for (const list_node_t *node = list_begin(l2cap_clients); node != list_end(l2cap_clients); node = list_next(node)) {
+    l2cap_client_t *client = (l2cap_client_t *)list_node(node);
+    if (client->local_channel_id == local_channel_id)
+      return client;
+  }
+
+  return NULL;
+}
diff --git a/stack/mcap/mca_api.c b/stack/mcap/mca_api.c
index 2a2ff8c..ae4cdb2 100644
--- a/stack/mcap/mca_api.c
+++ b/stack/mcap/mca_api.c
@@ -22,6 +22,7 @@
  *  Protocol (MCAP).
  *
  ******************************************************************************/
+#include <assert.h>
 #include <string.h>
 
 #include "bt_target.h"
@@ -31,7 +32,6 @@
 #include "mca_defs.h"
 #include "mca_int.h"
 
-#include "wcassert.h"
 #include "btu.h"
 
 
@@ -125,8 +125,8 @@
     tL2CAP_APPL_INFO l2c_cacp_appl;
     tL2CAP_APPL_INFO l2c_dacp_appl;
 
-    WC_ASSERT(p_reg != NULL );
-    WC_ASSERT(p_cback != NULL );
+    assert(p_reg != NULL );
+    assert(p_cback != NULL );
 
     MCA_TRACE_API ("MCA_Register: ctrl_psm:0x%x, data_psm:0x%x", p_reg->ctrl_psm, p_reg->data_psm);
 
@@ -221,9 +221,9 @@
     tMCA_RCB *p_rcb = mca_rcb_by_handle(handle);
     tMCA_CS  *p_depcs;
 
-    WC_ASSERT(p_dep != NULL );
-    WC_ASSERT(p_cs != NULL );
-    WC_ASSERT(p_cs->p_data_cback != NULL );
+    assert(p_dep != NULL );
+    assert(p_cs != NULL );
+    assert(p_cs->p_data_cback != NULL );
 
     MCA_TRACE_API ("MCA_CreateDep: %d", handle);
     if (p_rcb)
@@ -508,7 +508,7 @@
     tMCA_DCB        *p_dcb;
 
     MCA_TRACE_API ("MCA_CreateMdlRsp: %d dep=%d mdl_id=%d cfg=%d rsp_code=%d", mcl, dep, mdl_id, cfg, rsp_code);
-    WC_ASSERT(p_chnl_cfg != NULL );
+    assert(p_chnl_cfg != NULL );
     if (p_ccb)
     {
         if (p_ccb->cong)
@@ -605,7 +605,7 @@
     tMCA_DCB        *p_dcb;
 
     MCA_TRACE_API ("MCA_ReconnectMdl: %d ", mcl);
-    WC_ASSERT(p_chnl_cfg != NULL );
+    assert(p_chnl_cfg != NULL );
     if (p_ccb)
     {
         if (p_ccb->p_tx_req || p_ccb->p_rx_msg || p_ccb->cong)
@@ -674,7 +674,7 @@
     tMCA_DCB        *p_dcb;
 
     MCA_TRACE_API ("MCA_ReconnectMdlRsp: %d ", mcl);
-    WC_ASSERT(p_chnl_cfg != NULL );
+    assert(p_chnl_cfg != NULL );
     if (p_ccb)
     {
         if (p_ccb->cong)
@@ -739,7 +739,7 @@
     tMCA_TC_TBL *p_tbl;
 
     MCA_TRACE_API ("MCA_DataChnlCfg: %d ", mcl);
-    WC_ASSERT(p_chnl_cfg != NULL );
+    assert(p_chnl_cfg != NULL );
     if (p_ccb)
     {
         result = MCA_NO_RESOURCES;
diff --git a/stack/mcap/mca_cact.c b/stack/mcap/mca_cact.c
index bab3c76..7ac0efb 100644
--- a/stack/mcap/mca_cact.c
+++ b/stack/mcap/mca_cact.c
@@ -165,7 +165,6 @@
     BT_HDR  *p_pkt;
     UINT8   *p, *p_start;
     BOOLEAN chk_mdl = FALSE;
-    tMCA_DCB    *p_dcb;
 
     MCA_TRACE_DEBUG ("mca_ccb_snd_rsp cong=%d req=%d", p_ccb->cong, p_msg->op_code);
     /* assume that API functions verified the parameters */
@@ -187,7 +186,7 @@
 
         if (chk_mdl && p_msg->rsp_code == MCA_RSP_SUCCESS)
         {
-            p_dcb = mca_dcb_by_hdl(p_msg->dcb_idx);
+            mca_dcb_by_hdl(p_msg->dcb_idx);
             BTM_SetSecurityLevel(FALSE, "", BTM_SEC_SERVICE_MCAP_DATA, p_ccb->sec_mask,
                 p_ccb->p_rcb->reg.data_psm, BTM_SEC_PROTO_MCA, p_msg->dcb_idx);
             p_ccb->status = MCA_CCB_STAT_PENDING;
diff --git a/stack/mcap/mca_int.h b/stack/mcap/mca_int.h
index 54ff0c0..9a7d0fd 100644
--- a/stack/mcap/mca_int.h
+++ b/stack/mcap/mca_int.h
@@ -347,9 +347,9 @@
 ** Main Control Block
 *******************************************************************************/
 #if MCA_DYNAMIC_MEMORY == FALSE
-MCA_API extern tMCA_CB  mca_cb;
+extern tMCA_CB  mca_cb;
 #else
-MCA_API extern tMCA_CB *mca_cb_ptr;
+extern tMCA_CB *mca_cb_ptr;
 #define mca_cb (*mca_cb_ptr)
 #endif
 
diff --git a/stack/mcap/mca_main.c b/stack/mcap/mca_main.c
index 60b99d9..44307d2 100644
--- a/stack/mcap/mca_main.c
+++ b/stack/mcap/mca_main.c
@@ -22,6 +22,7 @@
  *  Utility functions.
  *
  ******************************************************************************/
+#include <assert.h>
 #include <string.h>
 
 #include "bt_target.h"
@@ -29,7 +30,6 @@
 #include "mca_api.h"
 #include "mca_defs.h"
 #include "mca_int.h"
-#include "wcassert.h"
 #include "l2c_api.h"
 
 /* Main Control block for MCA */
@@ -134,7 +134,7 @@
     }
 
     /* sanity check */
-    WC_ASSERT(i != MCA_NUM_TC_TBL);
+    assert(i != MCA_NUM_TC_TBL);
 
     /* initialize entry */
     p_tbl->peer_mtu = L2CAP_DEFAULT_MTU;
@@ -175,7 +175,7 @@
     }
 
     /* sanity check */
-    WC_ASSERT(i != MCA_NUM_TC_TBL);
+    assert(i != MCA_NUM_TC_TBL);
 
     /* initialize entry */
     p_tbl->peer_mtu = L2CAP_DEFAULT_MTU;
diff --git a/stack/pan/pan_api.c b/stack/pan/pan_api.c
index 6ba97b2..583f1d2 100644
--- a/stack/pan/pan_api.c
+++ b/stack/pan/pan_api.c
@@ -299,7 +299,6 @@
     tPAN_CONN       *pcb;
     tBNEP_RESULT    result;
     tBT_UUID        src_uuid, dst_uuid;
-    UINT8           service_id;
     UINT32 mx_chan_id;
 
     /*
@@ -343,17 +342,14 @@
         src_uuid.uu.uuid16 = UUID_SERVCLASS_PANU;
         if (dst_role == PAN_ROLE_CLIENT)
         {
-            service_id = BTM_SEC_SERVICE_BNEP_PANU;
             dst_uuid.uu.uuid16 = UUID_SERVCLASS_PANU;
         }
         else if (dst_role == PAN_ROLE_GN_SERVER)
         {
-            service_id = BTM_SEC_SERVICE_BNEP_GN;
             dst_uuid.uu.uuid16 = UUID_SERVCLASS_GN;
         }
         else
         {
-            service_id = BTM_SEC_SERVICE_BNEP_NAP;
             dst_uuid.uu.uuid16 = UUID_SERVCLASS_NAP;
         }
         mx_chan_id = dst_uuid.uu.uuid16;
@@ -370,12 +366,10 @@
         dst_uuid.uu.uuid16 = UUID_SERVCLASS_PANU;
         if (src_role == PAN_ROLE_GN_SERVER)
         {
-            service_id = BTM_SEC_SERVICE_BNEP_GN;
             src_uuid.uu.uuid16 = UUID_SERVCLASS_GN;
         }
         else
         {
-            service_id = BTM_SEC_SERVICE_BNEP_NAP;
             src_uuid.uu.uuid16 = UUID_SERVCLASS_NAP;
         }
         mx_chan_id = src_uuid.uu.uuid16;
@@ -679,7 +673,6 @@
                                     UINT16 *p_start_array,
                                     UINT16 *p_end_array)
 {
-#if (defined (BNEP_SUPPORTS_PROT_FILTERS) && BNEP_SUPPORTS_PROT_FILTERS == TRUE)
     tPAN_CONN       *pcb;
     tPAN_RESULT     result;
 
@@ -700,9 +693,6 @@
 
     PAN_TRACE_API ("PAN successfully sent protocol filters for handle %d", handle);
     return PAN_SUCCESS;
-#else
-    return PAN_FAILURE;
-#endif
 }
 
 
@@ -728,7 +718,6 @@
                                       UINT8 *p_start_array,
                                       UINT8 *p_end_array)
 {
-#if (defined (BNEP_SUPPORTS_MULTI_FILTERS) && BNEP_SUPPORTS_MULTI_FILTERS == TRUE)
     tPAN_CONN       *pcb;
     tPAN_RESULT     result;
 
@@ -750,9 +739,6 @@
 
     PAN_TRACE_API ("PAN successfully sent multicast filters for handle %d", handle);
     return PAN_SUCCESS;
-#else
-    return PAN_FAILURE;
-#endif
 }
 
 
diff --git a/stack/pan/pan_int.h b/stack/pan/pan_int.h
index 4e02236..4e463e6 100644
--- a/stack/pan/pan_int.h
+++ b/stack/pan/pan_int.h
@@ -82,7 +82,6 @@
     tPAN_MFILTER_IND_CB         *pan_mfilt_ind_cb;      /* multicast filter indication callback */
     tPAN_TX_DATA_FLOW_CB        *pan_tx_data_flow_cb;
 
-    BD_ADDR                     my_bda;                 /* BD Address of this device    */
     char                        *user_service_name;
     char                        *gn_service_name;
     char                        *nap_service_name;
@@ -101,9 +100,9 @@
 /* Global PAN data
 */
 #if PAN_DYNAMIC_MEMORY == FALSE
-PAN_API extern tPAN_CB  pan_cb;
+extern tPAN_CB  pan_cb;
 #else
-PAN_API extern tPAN_CB  *pan_cb_ptr;
+extern tPAN_CB  *pan_cb_ptr;
 #define pan_cb (*pan_cb_ptr)
 #endif
 
@@ -155,4 +154,3 @@
 #endif
 
 #endif
-
diff --git a/stack/pan/pan_main.c b/stack/pan/pan_main.c
index 8306df3..56a8f12 100644
--- a/stack/pan/pan_main.c
+++ b/stack/pan/pan_main.c
@@ -112,7 +112,6 @@
     ** is for NAP
     */
     wrong_uuid = FALSE;
-#if (defined (BNEP_SUPPORTS_ALL_UUID_LENGTHS) && BNEP_SUPPORTS_ALL_UUID_LENGTHS == TRUE)
     if (remote_uuid->len == 16)
     {
         /*
@@ -189,7 +188,6 @@
         BNEP_ConnectResp (handle, BNEP_CONN_FAILED_UUID_SIZE);
         return;
     }
-#endif
 
     /* Check if the source UUID is a valid one */
     if (remote_uuid->uu.uuid16 != UUID_SERVCLASS_PANU &&
@@ -681,15 +679,11 @@
                             UINT16 num_filters,
                             UINT8 *p_filters)
 {
-#if (defined (BNEP_SUPPORTS_PROT_FILTERS) && BNEP_SUPPORTS_PROT_FILTERS == TRUE)
     PAN_TRACE_EVENT ("pan_proto_filt_ind_cb - called for handle %d with ind %d, result %d, num %d",
                             handle, indication, result, num_filters);
 
     if (pan_cb.pan_pfilt_ind_cb)
         (*pan_cb.pan_pfilt_ind_cb) (handle, indication, result, num_filters, p_filters);
-#endif
-
-    return;
 }
 
 
@@ -719,14 +713,9 @@
                             UINT16 num_filters,
                             UINT8 *p_filters)
 {
-#if (defined (BNEP_SUPPORTS_MULTI_FILTERS) && BNEP_SUPPORTS_MULTI_FILTERS == TRUE)
     PAN_TRACE_EVENT ("pan_mcast_filt_ind_cb - called for handle %d with ind %d, result %d, num %d",
                             handle, indication, result, num_filters);
 
     if (pan_cb.pan_mfilt_ind_cb)
         (*pan_cb.pan_mfilt_ind_cb) (handle, indication, result, num_filters, p_filters);
-#endif
-
-    return;
 }
-
diff --git a/stack/rfcomm/port_api.c b/stack/rfcomm/port_api.c
index 0cbae96..3f38a71 100644
--- a/stack/rfcomm/port_api.c
+++ b/stack/rfcomm/port_api.c
@@ -24,6 +24,7 @@
 
 #include <string.h>
 #include "bt_target.h"
+#include "btcore/include/counter.h"
 #include "gki.h"
 #include "rfcdefs.h"
 #include "port_api.h"
@@ -33,15 +34,46 @@
 #include "rfc_int.h"
 #include "l2c_api.h"
 #include "sdp_api.h"
+#include "osi/include/log.h"
 
 /* duration of break in 200ms units */
 #define PORT_BREAK_DURATION     1
 
-#include <cutils/log.h>
-#define info(fmt, ...)  ALOGI ("%s: " fmt,__FUNCTION__,  ## __VA_ARGS__)
-#define debug(fmt, ...) ALOGD ("%s: " fmt,__FUNCTION__,  ## __VA_ARGS__)
-#define error(fmt, ...) ALOGE ("## ERROR : %s: " fmt "##",__FUNCTION__,  ## __VA_ARGS__)
-#define asrt(s) if(!(s)) ALOGE ("## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
+#define info(fmt, ...)  LOG_INFO ("%s: " fmt,__FUNCTION__,  ## __VA_ARGS__)
+#define debug(fmt, ...) LOG_DEBUG ("%s: " fmt,__FUNCTION__,  ## __VA_ARGS__)
+#define error(fmt, ...) LOG_ERROR ("## ERROR : %s: " fmt "##",__FUNCTION__,  ## __VA_ARGS__)
+#define asrt(s) if(!(s)) LOG_ERROR ("## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
+
+/* Mapping from PORT_* result codes to human readable strings. */
+static const char *result_code_strings[] = {
+  "Success",
+  "Unknown error",
+  "Already opened",
+  "Command pending",
+  "App not registered",
+  "No memory",
+  "No resources",
+  "Bad BD address",
+  "Unspecified error",
+  "Bad handle",
+  "Not opened",
+  "Line error",
+  "Start failed",
+  "Parameter negotiation failed",
+  "Port negotiation failed",
+  "Sec failed",
+  "Peer connection failed",
+  "Peer failed",
+  "Peer timeout",
+  "Closed",
+  "TX full",
+  "Local closed",
+  "Local timeout",
+  "TX queue disabled",
+  "Page timeout",
+  "Invalid SCN",
+  "Unknown result code"
+};
 
 /*******************************************************************************
 **
@@ -84,6 +116,8 @@
     tRFC_MCB   *p_mcb = port_find_mcb (bd_addr);
     UINT16     rfcomm_mtu;
 
+    counter_add("rfcomm.conn.created", 1);
+
     RFCOMM_TRACE_API ("RFCOMM_CreateConnection()  BDA: %02x-%02x-%02x-%02x-%02x-%02x",
                        bd_addr[0], bd_addr[1], bd_addr[2], bd_addr[3], bd_addr[4], bd_addr[5]);
 
@@ -209,6 +243,8 @@
 {
     tPORT      *p_port;
 
+    counter_add("rfcomm.conn.destroyed", 1);
+
     RFCOMM_TRACE_API ("RFCOMM_RemoveConnection() handle:%d", handle);
 
     /* Check if handle is valid to avoid crashing */
@@ -1132,7 +1168,7 @@
     {
         PORT_SCHEDULE_LOCK;  /* to prevent missing credit */
 
-        count = p_port->rx.queue.count;
+        count = GKI_queue_length(&p_port->rx.queue);
 
         while ((p_buf = (BT_HDR *)GKI_dequeue (&p_port->rx.queue)) != NULL)
             GKI_freebuf (p_buf);
@@ -1368,7 +1404,7 @@
                               (PORT_CTRL_REQ_SENT | PORT_CTRL_IND_RECEIVED)))
     {
         if ((p_port->tx.queue_size  > PORT_TX_CRITICAL_WM)
-         || (p_port->tx.queue.count > PORT_TX_BUF_CRITICAL_WM))
+         || (GKI_queue_length(&p_port->tx.queue) > PORT_TX_BUF_CRITICAL_WM))
         {
             RFCOMM_TRACE_WARNING ("PORT_Write: Queue size: %d",
                                    p_port->tx.queue_size);
@@ -1525,7 +1561,7 @@
     /* data fits into the end of the queue */
     PORT_SCHEDULE_LOCK;
 
-    if (((p_buf = (BT_HDR *)p_port->tx.queue.p_last) != NULL)
+    if (((p_buf = (BT_HDR *)GKI_getlast(&p_port->tx.queue)) != NULL)
      && (((int)p_buf->len + available) <= (int)p_port->peer_mtu)
      && (((int)p_buf->len + available) <= (int)length))
     {
@@ -1559,12 +1595,12 @@
     {
         /* if we're over buffer high water mark, we're done */
         if ((p_port->tx.queue_size  > PORT_TX_HIGH_WM)
-         || (p_port->tx.queue.count > PORT_TX_BUF_HIGH_WM))
+         || (GKI_queue_length(&p_port->tx.queue) > PORT_TX_BUF_HIGH_WM))
         {
             port_flow_control_user(p_port);
             event |= PORT_EV_FC;
             debug("tx queue is full,tx.queue_size:%d,tx.queue.count:%d,available:%d",
-                    p_port->tx.queue_size, p_port->tx.queue.count, available);
+                    p_port->tx.queue_size, GKI_queue_length(&p_port->tx.queue), available);
             break;
          }
 
@@ -1676,7 +1712,7 @@
     /* data fits into the end of the queue */
     PORT_SCHEDULE_LOCK;
 
-    if (((p_buf = (BT_HDR *)p_port->tx.queue.p_last) != NULL)
+    if (((p_buf = (BT_HDR *)GKI_getlast(&p_port->tx.queue)) != NULL)
      && ((p_buf->len + max_len) <= p_port->peer_mtu)
      && ((p_buf->len + max_len) <= length))
     {
@@ -1697,7 +1733,7 @@
     {
         /* if we're over buffer high water mark, we're done */
         if ((p_port->tx.queue_size  > PORT_TX_HIGH_WM)
-         || (p_port->tx.queue.count > PORT_TX_BUF_HIGH_WM))
+         || (GKI_queue_length(&p_port->tx.queue) > PORT_TX_BUF_HIGH_WM))
             break;
 
         /* continue with rfcomm data write */
@@ -1840,3 +1876,20 @@
     return (rfc_cb.trace_level);
 }
 
+/*******************************************************************************
+**
+** Function         PORT_GetResultString
+**
+** Description      This function returns the human-readable string for a given
+**                  result code.
+**
+** Returns          a pointer to the human-readable string for the given result.
+**
+*******************************************************************************/
+const char *PORT_GetResultString (const uint8_t result_code) {
+  if (result_code > PORT_ERR_MAX) {
+    return result_code_strings[PORT_ERR_MAX];
+  }
+
+  return result_code_strings[result_code];
+}
diff --git a/stack/rfcomm/port_rfc.c b/stack/rfcomm/port_rfc.c
index 5704c01..2a01395 100644
--- a/stack/rfcomm/port_rfc.c
+++ b/stack/rfcomm/port_rfc.c
@@ -865,7 +865,7 @@
 
     /* Check if rx queue exceeds the limit */
     if ((p_port->rx.queue_size + p_buf->len > PORT_RX_CRITICAL_WM)
-     || (p_port->rx.queue.count + 1 > p_port->rx_buf_critical))
+     || (GKI_queue_length(&p_port->rx.queue) + 1 > p_port->rx_buf_critical))
     {
         RFCOMM_TRACE_EVENT ("PORT_DataInd. Buffer over run. Dropping the buffer");
         GKI_freebuf (p_buf);
@@ -1095,6 +1095,9 @@
 
     p_port->rfc.state = RFC_STATE_CLOSED;
 
+    RFCOMM_TRACE_WARNING ("%s RFCOMM connection in state %d closed: %s (res: %d)",
+                          __func__, p_port->state, PORT_GetResultString(res), res);
+
     port_release_port (p_port);
 }
 
@@ -1115,6 +1118,3 @@
     if (p_port->credit_tx == 0)
         p_port->tx.peer_fc = TRUE;
 }
-
-
-
diff --git a/stack/rfcomm/port_utils.c b/stack/rfcomm/port_utils.c
index 642ddb8..7d29336 100644
--- a/stack/rfcomm/port_utils.c
+++ b/stack/rfcomm/port_utils.c
@@ -420,7 +420,7 @@
               || !p_port->rfc.p_mcb
               || !p_port->rfc.p_mcb->peer_ready
               || (p_port->tx.queue_size > PORT_TX_HIGH_WM)
-              || (p_port->tx.queue.count > PORT_TX_BUF_HIGH_WM);
+              || (GKI_queue_length(&p_port->tx.queue) > PORT_TX_BUF_HIGH_WM);
 
     if (p_port->tx.user_fc == fc)
         return (0);
@@ -536,7 +536,7 @@
                 p_port->rx.peer_fc = TRUE;
             }
             /* if queue count reached credit rx max, set peer fc */
-            else if (p_port->rx.queue.count >= p_port->credit_rx_max)
+            else if (GKI_queue_length(&p_port->rx.queue) >= p_port->credit_rx_max)
             {
                 p_port->rx.peer_fc = TRUE;
             }
@@ -552,7 +552,7 @@
             /* check if it can be resumed now */
             if (p_port->rx.peer_fc
              && (p_port->rx.queue_size < PORT_RX_LOW_WM)
-             && (p_port->rx.queue.count < PORT_RX_BUF_LOW_WM))
+             && (GKI_queue_length(&p_port->rx.queue) < PORT_RX_BUF_LOW_WM))
             {
                 p_port->rx.peer_fc = FALSE;
 
@@ -573,7 +573,7 @@
             /* Check the size of the rx queue.  If it exceeds certain */
             /* level and flow control has not been sent to the peer do it now */
             else if ( ((p_port->rx.queue_size > PORT_RX_HIGH_WM)
-                     || (p_port->rx.queue.count > PORT_RX_BUF_HIGH_WM))
+                     || (GKI_queue_length(&p_port->rx.queue) > PORT_RX_BUF_HIGH_WM))
                      && !p_port->rx.peer_fc)
             {
                 RFCOMM_TRACE_EVENT ("PORT_DataInd Data reached HW. Sending FC set.");
diff --git a/stack/rfcomm/rfc_int.h b/stack/rfcomm/rfc_int.h
index 302a8af..719a99d 100644
--- a/stack/rfcomm/rfc_int.h
+++ b/stack/rfcomm/rfc_int.h
@@ -235,9 +235,9 @@
 
 
 #if RFC_DYNAMIC_MEMORY == FALSE
-RFC_API extern tRFC_CB  rfc_cb;
+extern tRFC_CB  rfc_cb;
 #else
-RFC_API extern tRFC_CB *rfc_cb_ptr;
+extern tRFC_CB *rfc_cb_ptr;
 #define rfc_cb (*rfc_cb_ptr)
 #endif
 
@@ -384,4 +384,3 @@
 #endif
 
 #endif
-
diff --git a/stack/rfcomm/rfc_l2cap_if.c b/stack/rfcomm/rfc_l2cap_if.c
index 9e3ad69..087e73a 100644
--- a/stack/rfcomm/rfc_l2cap_if.c
+++ b/stack/rfcomm/rfc_l2cap_if.c
@@ -25,6 +25,7 @@
 #include <stddef.h>
 
 #include "bt_target.h"
+#include "btcore/include/counter.h"
 #include "gki.h"
 
 #include "rfcdefs.h"
@@ -106,7 +107,7 @@
             RFCOMM_TRACE_DEBUG ("RFCOMM_ConnectInd start timer for collision, initiator's LCID(0x%x), acceptor's LCID(0x%x)",
                                   p_mcb->lcid, p_mcb->pending_lcid);
 
-            rfc_timer_start(p_mcb, (UINT16)(GKI_get_tick_count()%10 + 2));
+            rfc_timer_start(p_mcb, (UINT16)(GKI_get_os_tick_count()%10 + 2));
             return;
         }
         else
@@ -366,6 +367,9 @@
 
     if (event == RFC_EVENT_UIH)
     {
+        counter_add("rfcomm.rx.frames", 1);
+        counter_add("rfcomm.rx.bytes", p_buf->len);
+
         if (p_buf->len > 0)
             rfc_port_sm_execute (p_port, event, p_buf);
         else
diff --git a/stack/rfcomm/rfc_port_fsm.c b/stack/rfcomm/rfc_port_fsm.c
index a998b6e..c0d7fbc 100644
--- a/stack/rfcomm/rfc_port_fsm.c
+++ b/stack/rfcomm/rfc_port_fsm.c
@@ -431,7 +431,7 @@
     case RFC_EVENT_DISC:
         p_port->rfc.state = RFC_STATE_CLOSED;
         rfc_send_ua (p_port->rfc.p_mcb, p_port->dlci);
-        if(p_port->rx.queue.count)
+        if(!GKI_queue_is_empty(&p_port->rx.queue))
         {
             /* give a chance to upper stack to close port properly */
             RFCOMM_TRACE_DEBUG("port queue is not empty");
diff --git a/stack/rfcomm/rfc_port_if.c b/stack/rfcomm/rfc_port_if.c
index 741df20..18be81c 100644
--- a/stack/rfcomm/rfc_port_if.c
+++ b/stack/rfcomm/rfc_port_if.c
@@ -81,15 +81,20 @@
 *******************************************************************************/
 void RFCOMM_DlcEstablishReq (tRFC_MCB *p_mcb, UINT8 dlci, UINT16 mtu)
 {
-    tPORT *p_port = port_find_mcb_dlci_port (p_mcb, dlci);
     UNUSED(mtu);
-
     if (p_mcb->state != RFC_MX_STATE_CONNECTED)
     {
         PORT_DlcEstablishCnf (p_mcb, dlci, 0, RFCOMM_ERROR);
         return;
     }
 
+    tPORT *p_port = port_find_mcb_dlci_port(p_mcb, dlci);
+    if (p_port == NULL) {
+        RFCOMM_TRACE_WARNING("%s Unable to find DLCI port dlci:%d", __func__,
+                dlci);
+        return;
+    }
+
     rfc_port_sm_execute(p_port, RFC_EVENT_OPEN, NULL);
 }
 
@@ -104,15 +109,19 @@
 *******************************************************************************/
 void RFCOMM_DlcEstablishRsp (tRFC_MCB *p_mcb, UINT8 dlci, UINT16 mtu, UINT16 result)
 {
-    tPORT *p_port = port_find_mcb_dlci_port (p_mcb, dlci);
     UNUSED(mtu);
-
     if ((p_mcb->state != RFC_MX_STATE_CONNECTED) && (result == RFCOMM_SUCCESS))
     {
         PORT_DlcReleaseInd (p_mcb, dlci);
         return;
     }
 
+    tPORT *p_port = port_find_mcb_dlci_port (p_mcb, dlci);
+    if (p_port == NULL) {
+        RFCOMM_TRACE_WARNING("%s Unable to find DLCI port dlci:%d", __func__,
+                dlci);
+        return;
+    }
     rfc_port_sm_execute(p_port, RFC_EVENT_ESTABLISH_RSP, &result);
 }
 
@@ -130,11 +139,17 @@
 *******************************************************************************/
 void RFCOMM_ParNegReq (tRFC_MCB *p_mcb, UINT8 dlci, UINT16 mtu)
 {
-    tPORT *p_port = port_find_mcb_dlci_port (p_mcb, dlci);
     UINT8 flow;
     UINT8 cl;
     UINT8 k;
 
+    tPORT *p_port = port_find_mcb_dlci_port(p_mcb, dlci);
+    if (p_port == NULL) {
+        RFCOMM_TRACE_WARNING("%s Unable to find DLCI port dlci:%d", __func__,
+                dlci);
+        return;
+    }
+
     if (p_mcb->state != RFC_MX_STATE_CONNECTED)
     {
         p_port->error = PORT_PAR_NEG_FAILED;
@@ -199,14 +214,19 @@
 *******************************************************************************/
 void RFCOMM_PortNegReq (tRFC_MCB *p_mcb, UINT8 dlci, tPORT_STATE *p_pars)
 {
-    tPORT *p_port = port_find_mcb_dlci_port (p_mcb, dlci);
-
     if (p_mcb->state != RFC_MX_STATE_CONNECTED)
     {
         PORT_PortNegCnf (p_mcb, dlci, NULL, RFCOMM_ERROR);
         return;
     }
 
+    tPORT *p_port = port_find_mcb_dlci_port(p_mcb, dlci);
+    if (p_port == NULL) {
+        RFCOMM_TRACE_WARNING("%s Unable to find DLCI port dlci:%d", __func__,
+                dlci);
+        return;
+    }
+
     /* Send Parameter Negotiation Command UIH frame */
     if (!p_pars)
         p_port->rfc.expected_rsp |= RFC_RSP_RPN_REPLY;
@@ -247,7 +267,12 @@
 *******************************************************************************/
 void RFCOMM_ControlReq (tRFC_MCB *p_mcb, UINT8 dlci, tPORT_CTRL *p_pars)
 {
-    tPORT *p_port = port_find_mcb_dlci_port (p_mcb, dlci);
+    tPORT *p_port = port_find_mcb_dlci_port(p_mcb, dlci);
+    if (p_port == NULL) {
+        RFCOMM_TRACE_WARNING("%s Unable to find DLCI port dlci:%d", __func__,
+                dlci);
+        return;
+    }
 
     if ((p_port->state != PORT_STATE_OPENED)
      || (p_port->rfc.state  != RFC_STATE_OPENED))
@@ -274,7 +299,12 @@
 *******************************************************************************/
 void RFCOMM_FlowReq (tRFC_MCB *p_mcb, UINT8 dlci, UINT8 enable)
 {
-    tPORT      *p_port = port_find_mcb_dlci_port (p_mcb, dlci);
+    tPORT *p_port = port_find_mcb_dlci_port(p_mcb, dlci);
+    if (p_port == NULL) {
+        RFCOMM_TRACE_WARNING("%s Unable to find DLCI port dlci:%d", __func__,
+                dlci);
+        return;
+    }
 
     if ((p_port->state != PORT_STATE_OPENED)
      || (p_port->rfc.state  != RFC_STATE_OPENED))
@@ -300,7 +330,12 @@
 *******************************************************************************/
 void RFCOMM_LineStatusReq (tRFC_MCB *p_mcb, UINT8 dlci, UINT8 status)
 {
-    tPORT *p_port = port_find_mcb_dlci_port (p_mcb, dlci);
+    tPORT *p_port = port_find_mcb_dlci_port(p_mcb, dlci);
+    if (p_port == NULL) {
+        RFCOMM_TRACE_WARNING("%s Unable to find DLCI port dlci:%d", __func__,
+                dlci);
+        return;
+    }
 
     if ((p_port->state != PORT_STATE_OPENED)
      || (p_port->rfc.state  != RFC_STATE_OPENED))
diff --git a/stack/rfcomm/rfc_ts_frames.c b/stack/rfcomm/rfc_ts_frames.c
index 3831ab5..9b3cdca 100644
--- a/stack/rfcomm/rfc_ts_frames.c
+++ b/stack/rfcomm/rfc_ts_frames.c
@@ -25,6 +25,7 @@
 #include <stddef.h>
 
 #include "bt_target.h"
+#include "btcore/include/counter.h"
 #include "gki.h"
 #include "rfcdefs.h"
 #include "port_api.h"
@@ -218,7 +219,8 @@
     }
     else
     {
-
+        counter_add("rfcomm.tx.frames", 1);
+        counter_add("rfcomm.tx.bytes", p_buf->len);
         L2CA_DataWrite (p_mcb->lcid, p_buf);
     }
 }
diff --git a/stack/sdp/sdp_api.c b/stack/sdp/sdp_api.c
index 558bd8b..6e84ded 100644
--- a/stack/sdp/sdp_api.c
+++ b/stack/sdp/sdp_api.c
@@ -37,13 +37,6 @@
 #include "sdpint.h"
 #include "btu.h"
 
-#include <cutils/log.h>
-#define info(fmt, ...)  LOGI ("%s: " fmt,__FUNCTION__,  ## __VA_ARGS__)
-#define debug(fmt, ...) LOGD ("%s: " fmt,__FUNCTION__,  ## __VA_ARGS__)
-#define error(fmt, ...) LOGE ("## ERROR : %s: " fmt "##",__FUNCTION__,  ## __VA_ARGS__)
-#define asrt(s) if(!(s)) LOGE ("## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
-
-
 /**********************************************************************
 **   C L I E N T    F U N C T I O N    P R O T O T Y P E S            *
 ***********************************************************************/
@@ -686,17 +679,6 @@
                 {
                     if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == UUID_DESC_TYPE)
                     {
-
-                        SDP_TRACE_DEBUG("uuid len=%d ", p_uuid->len);
-                        if (p_uuid->len == 2)
-                        {
-                            SDP_TRACE_DEBUG("uuid=0x%x \n", p_uuid->uu.uuid16);
-                        }
-                        else
-                        {
-                            SDP_TRACE_DEBUG("\n");
-                        }
-
                         if (sdpu_compare_uuid_with_attr (p_uuid, p_sattr))
                             return(p_rec);
                     }
@@ -1273,119 +1255,6 @@
 
 /*******************************************************************************
 **
-** Function         SDP_GetLocalDiRecord
-**
-** Description      This function adds a DI record to the local SDP database.
-**
-**                  Fills in the device information of the record
-**                  p_handle - if p_handle == 0, the primary record is returned
-**
-** Returns          Returns SDP_SUCCESS if record exists, else error
-**
-*******************************************************************************/
-UINT16 SDP_GetLocalDiRecord(tSDP_DI_GET_RECORD *p_device_info, UINT32 *p_handle )
-{
-    UINT16 result = SDP_NO_DI_RECORD_FOUND;
-
-#if SDP_SERVER_ENABLED == TRUE
-    tSDP_RECORD     *p_rec;
-    tSDP_ATTRIBUTE  *p_attr;
-    UINT8           *p_temp;
-    INT32            templen;
-
-    if (*p_handle == 0)
-        *p_handle = sdp_cb.server_db.di_primary_handle;
-
-    if ((p_rec = sdp_db_find_record(*p_handle)) != NULL)
-    {
-        memset(p_device_info, 0, sizeof(tSDP_DI_RECORD));
-
-        result = SDP_SUCCESS;
-
-        /* Retrieve the Specification ID */
-        if ((p_attr = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_SPECIFICATION_ID,
-                                              ATTR_ID_SPECIFICATION_ID)) != NULL)
-        {
-            p_temp = p_attr->value_ptr;
-            BE_STREAM_TO_UINT16 (p_device_info->spec_id, p_temp);
-        }
-
-        /* Retrieve the Vendor ID */
-        if ((p_attr = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_VENDOR_ID,
-                                              ATTR_ID_VENDOR_ID)) != NULL)
-        {
-            p_temp = p_attr->value_ptr;
-            BE_STREAM_TO_UINT16 (p_device_info->rec.vendor, p_temp);
-        }
-
-        /* Retrieve the Product ID */
-        if ((p_attr = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_PRODUCT_ID,
-                                              ATTR_ID_PRODUCT_ID)) != NULL)
-        {
-            p_temp = p_attr->value_ptr;
-            BE_STREAM_TO_UINT16 (p_device_info->rec.product, p_temp);
-        }
-
-        /* Retrieve the Version ID */
-        if ((p_attr = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_PRODUCT_VERSION,
-                                              ATTR_ID_PRODUCT_VERSION)) != NULL)
-        {
-            p_temp = p_attr->value_ptr;
-            BE_STREAM_TO_UINT16 (p_device_info->rec.version, p_temp);
-        }
-
-        /* Retrieve the Vendor ID Source ID */
-        if ((p_attr = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_VENDOR_ID_SOURCE,
-                                              ATTR_ID_VENDOR_ID_SOURCE)) != NULL)
-        {
-            p_temp = p_attr->value_ptr;
-            BE_STREAM_TO_UINT16 (p_device_info->rec.vendor_id_source, p_temp);
-        }
-
-        /* Retrieve the Primary Record */
-        if ((p_attr = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_PRIMARY_RECORD,
-                                              ATTR_ID_PRIMARY_RECORD)) != NULL)
-        {
-            p_device_info->rec.primary_record = *p_attr->value_ptr;
-        }
-
-        /* Retrieve the Client Executable URL */
-        if ((p_attr = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_CLIENT_EXE_URL,
-                                              ATTR_ID_CLIENT_EXE_URL)) != NULL)
-        {
-            templen = (INT32)((p_attr->len < SDP_MAX_ATTR_LEN) ? p_attr->len : SDP_MAX_ATTR_LEN);
-            p_temp = p_attr->value_ptr;
-            BE_STREAM_TO_ARRAY (p_temp, p_device_info->rec.client_executable_url, templen);
-        }
-
-        /* Retrieve the Service Description */
-        if ((p_attr = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_SERVICE_DESCRIPTION,
-                                              ATTR_ID_SERVICE_DESCRIPTION)) != NULL)
-        {
-            templen = (INT32)((p_attr->len < SDP_MAX_ATTR_LEN) ? p_attr->len : SDP_MAX_ATTR_LEN);
-            p_temp = p_attr->value_ptr;
-            BE_STREAM_TO_ARRAY (p_temp, p_device_info->rec.service_description, templen);
-        }
-
-        /* Retrieve the Documentation URL */
-        if ((p_attr = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_DOCUMENTATION_URL,
-                                              ATTR_ID_DOCUMENTATION_URL)) != NULL)
-        {
-            templen = (INT32)((p_attr->len < SDP_MAX_ATTR_LEN) ? p_attr->len : SDP_MAX_ATTR_LEN);
-            p_temp = p_attr->value_ptr;
-            BE_STREAM_TO_ARRAY (p_temp, p_device_info->rec.documentation_url, templen);
-        }
-    }
-    else
-        *p_handle = 0;
-#endif
-
-    return result;
-}
-
-
-/*******************************************************************************
-**
 ** Function         SDP_SetTraceLevel
 **
 ** Description      This function sets the trace level for SDP. If called with
@@ -1401,100 +1270,3 @@
 
     return(sdp_cb.trace_level);
 }
-
-#if SDP_FOR_JV_INCLUDED == TRUE
-/*******************************************************************************
-**
-** Function         SDP_ConnOpen
-**
-** Description      This function creates a connection to the SDP server on the
-**                  given device.
-**
-** Returns          0, if failed to initiate connection. Otherwise, the handle.
-**
-*******************************************************************************/
-UINT32 SDP_ConnOpen (UINT8 *p_bd_addr, tSDP_DISC_RES_CB *p_rcb,
-                     tSDP_DISC_CMPL_CB *p_cb)
-{
-#if SDP_CLIENT_ENABLED == TRUE
-    tCONN_CB    *p_ccb;
-    UINT32      idx = 0;
-
-    if (!p_cb || !p_rcb)
-        return(idx);
-
-    /* Specific BD address */
-    p_ccb = sdp_conn_originate (p_bd_addr);
-
-    if (!p_ccb)
-        return(idx);
-
-    p_ccb->disc_state = SDP_DISC_WAIT_CONN;
-    p_ccb->p_db       = (tSDP_DISCOVERY_DB *)p_rcb;
-    p_ccb->p_cb       = p_cb;
-
-    p_ccb->is_attr_search = SDP_IS_PASS_THRU;
-
-    idx = (UINT32)(p_ccb - sdp_cb.ccb);
-    return(UINT32)(idx + 1);
-#else
-    return(0);
-#endif
-}
-
-/*******************************************************************************
-**
-** Function         SDP_WriteData
-**
-** Description      This function sends data to the connected SDP server.
-**
-** Returns          TRUE if data is sent, FALSE if failed.
-**
-*******************************************************************************/
-BOOLEAN SDP_WriteData (UINT32 handle, BT_HDR  *p_msg)
-{
-#if SDP_CLIENT_ENABLED == TRUE
-    tCONN_CB    *p_ccb = NULL;
-
-    if (p_msg && (handle > 0) && (handle <= SDP_MAX_CONNECTIONS) )
-    {
-        p_ccb = &sdp_cb.ccb[handle - 1];
-        if ( (p_ccb->con_state == SDP_STATE_CONNECTED) &&
-             (p_ccb->con_flags & SDP_FLAGS_IS_ORIG) )
-        {
-            /* Start inactivity timer */
-            btu_start_timer (&p_ccb->timer_entry, BTU_TTYPE_SDP, SDP_INACT_TIMEOUT);
-            L2CA_DataWrite (p_ccb->connection_id, p_msg);
-            return TRUE;
-        }
-    }
-#endif
-    return FALSE;
-}
-
-/*******************************************************************************
-**
-** Function         SDP_ConnClose
-**
-** Description      This function is called to close a SDP connection.
-**
-** Parameters:      handle      - Handle of the connection returned by SDP_ConnOpen
-**
-** Returns          TRUE if connection is closed, FALSE if failed to find the handle.
-**
-*******************************************************************************/
-BOOLEAN SDP_ConnClose (UINT32 handle)
-{
-#if SDP_CLIENT_ENABLED == TRUE
-    tCONN_CB    *p_ccb = NULL;
-
-    if (handle > 0 && handle <= SDP_MAX_CONNECTIONS)
-    {
-        p_ccb = &sdp_cb.ccb[handle - 1];
-        sdp_disconnect (p_ccb, SDP_SUCCESS);
-        return TRUE;
-    }
-#endif
-    return FALSE;
-}
-#endif
diff --git a/stack/sdp/sdp_db.c b/stack/sdp/sdp_db.c
index 322e27d..ea8fa87 100644
--- a/stack/sdp/sdp_db.c
+++ b/stack/sdp/sdp_db.c
@@ -36,7 +36,6 @@
 
 #include "sdp_api.h"
 #include "sdpint.h"
-#include "wbt_api.h"
 
 #if SDP_SERVER_ENABLED == TRUE
 /********************************************************************************/
@@ -340,7 +339,6 @@
 
         /* require new DI record to be created in SDP_SetLocalDiRecord */
         sdp_cb.server_db.di_primary_handle = 0;
-        sdp_cb.server_db.brcm_di_registered = 0;
 
         return (TRUE);
     }
@@ -369,7 +367,6 @@
                 if( sdp_cb.server_db.di_primary_handle == handle )
                 {
                     sdp_cb.server_db.di_primary_handle = 0;
-                    sdp_cb.server_db.brcm_di_registered = 0;
                 }
 
                 return (TRUE);
@@ -505,12 +502,6 @@
                 return (FALSE);
             }
             p_rec->num_attributes++;
-
-            /*** Mark DI record as used by Broadcom ***/
-            if (handle == sdp_cb.server_db.di_primary_handle &&
-                attr_id == ATTR_ID_EXT_BRCM_VERSION)
-                sdp_cb.server_db.brcm_di_registered = TRUE;
-
             return (TRUE);
         }
     }
@@ -1023,6 +1014,3 @@
     return (offset);
 }
 #endif
-
-
-
diff --git a/stack/sdp/sdp_discovery.c b/stack/sdp/sdp_discovery.c
index caeeccf..646a62d 100644
--- a/stack/sdp/sdp_discovery.c
+++ b/stack/sdp/sdp_discovery.c
@@ -194,23 +194,6 @@
 *******************************************************************************/
 void sdp_disc_connected (tCONN_CB *p_ccb)
 {
-
-#if SDP_FOR_JV_INCLUDED == TRUE
-    if (SDP_IS_PASS_THRU == p_ccb->is_attr_search)
-    {
-        tSDP_DISC_RES_CB *p_rcb = (tSDP_DISC_RES_CB *) p_ccb->p_db;
-        tSDP_DR_OPEN    evt_data;
-        /* report connected */
-        p_ccb->disc_state = SDP_DISC_WAIT_PASS_THRU;
-        if (p_rcb)
-        {
-            memcpy(evt_data.peer_addr, p_ccb->device_address, BD_ADDR_LEN);
-            evt_data.peer_mtu = p_ccb->rem_mtu_size;
-            (*p_rcb)(SDP_EVT_OPEN, (void *)&evt_data);
-        }
-    }
-    else
-#endif
     if (p_ccb->is_attr_search)
     {
         p_ccb->disc_state = SDP_DISC_WAIT_SEARCH_ATTR;
@@ -251,21 +234,6 @@
     /* stop inactivity timer when we receive a response */
     btu_stop_timer (&p_ccb->timer_entry);
 
-#if SDP_FOR_JV_INCLUDED == TRUE
-    if(SDP_IS_PASS_THRU == p_ccb->is_attr_search)
-    {
-        tSDP_DISC_RES_CB    *p_rcb = (tSDP_DISC_RES_CB *) p_ccb->p_db;
-        tSDP_DR_DATA        data;
-        if (p_rcb)
-        {
-            data.p_data   = (UINT8 *)(p_msg + 1) + p_msg->offset;
-            data.data_len = p_msg->len;
-            (*p_rcb)(SDP_EVT_DATA_IND, (void *)&data);
-        }
-        return;
-    }
-#endif
-
     /* Got a reply!! Check what we got back */
     p = (UINT8 *)(p_msg + 1) + p_msg->offset;
 
@@ -383,7 +351,6 @@
     unsigned int    cpy_len;
     UINT32          list_len;
     UINT8           *p;
-    UINT8           * p_temp;
     UINT8           type;
 
 #if (SDP_DEBUG_RAW == TRUE)
@@ -401,7 +368,7 @@
     {
         cpy_len = p_ccb->p_db->raw_size - p_ccb->p_db->raw_used;
         list_len = p_ccb->list_len;
-        p_temp = p = &p_ccb->rsp_list[0];
+        p = &p_ccb->rsp_list[0];
 
         if(offset)
         {
diff --git a/stack/sdp/sdp_main.c b/stack/sdp/sdp_main.c
index 1e0c22a..86f16fb 100644
--- a/stack/sdp/sdp_main.c
+++ b/stack/sdp/sdp_main.c
@@ -563,12 +563,6 @@
     /* Transition to the next appropriate state, waiting for connection confirm. */
     p_ccb->con_state = SDP_STATE_CONN_SETUP;
 
-// btla-specific ++
-#ifndef ANDROID_APP_INCLUDED  /* Skip for Android: Do not need to set out_service for sdp, since sdp does not use sec. Prevents over-writing service_rec of a connection already in progress */
-    BTM_SetOutService(p_bd_addr, BTM_SEC_SERVICE_SDP_SERVER, 0);
-#endif
-// btla-specific --
-
     cid = L2CA_ConnectReq (SDP_PSM, p_bd_addr);
 
     /* Check if L2CAP started the connection process */
diff --git a/stack/sdp/sdp_server.c b/stack/sdp/sdp_server.c
index de42097..5f6923a 100644
--- a/stack/sdp/sdp_server.c
+++ b/stack/sdp/sdp_server.c
@@ -786,6 +786,27 @@
     len_to_send = (UINT16) (p_rsp - &p_ccb->rsp_list[0]);
     cont_offset = 0;
 
+    // The current SDP server design has a critical flaw where it can run into an infinite
+    // request/response loop with the client. Here's the scenario:
+    // - client makes SDP request
+    // - server returns the first fragment of the response with a continuation token
+    // - an SDP record is deleted from the server
+    // - client issues another request with previous continuation token
+    // - server has nothing to send back because the record is unavailable but in the
+    //   first fragment, it had specified more response bytes than are now available
+    // - server sends back no additional response bytes and returns the same continuation token
+    // - client issues another request with the continuation token, and the process repeats
+    //
+    // We work around this design flaw here by checking if we will make forward progress
+    // (i.e. we will send > 0 response bytes) on a continued request. If not, we must have
+    // run into the above situation and we tell the peer an error occurred.
+    //
+    // TODO(sharvil): rewrite SDP server.
+    if (is_cont && len_to_send == 0) {
+      sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, NULL);
+      return;
+    }
+
     /* If first response, insert sequence header */
     if (!is_cont)
     {
diff --git a/stack/sdp/sdpint.h b/stack/sdp/sdpint.h
index b300664..262ac89 100644
--- a/stack/sdp/sdpint.h
+++ b/stack/sdp/sdpint.h
@@ -141,7 +141,6 @@
 typedef struct
 {
     UINT32         di_primary_handle;       /* Device ID Primary record or NULL if nonexistent */
-    BOOLEAN        brcm_di_registered;
     UINT16         num_records;
     tSDP_RECORD    record[SDP_MAX_RECORDS];
 } tSDP_DB;
@@ -150,7 +149,6 @@
 {
     SDP_IS_SEARCH,
     SDP_IS_ATTR_SEARCH,
-    SDP_IS_PASS_THRU    /* only when SDP_FOR_JV_INCLUDED == TRUE */
 };
 
 #if SDP_SERVER_ENABLED == TRUE
@@ -204,7 +202,6 @@
 #define SDP_DISC_WAIT_HANDLES       1
 #define SDP_DISC_WAIT_ATTR          2
 #define SDP_DISC_WAIT_SEARCH_ATTR   3
-#define SDP_DISC_WAIT_PASS_THRU     4    /* only when SDP_FOR_JV_INCLUDED == TRUE */
 #define SDP_DISC_WAIT_CANCEL        5
 
     UINT8             disc_state;
@@ -238,9 +235,9 @@
 #endif
 /* Global SDP data */
 #if SDP_DYNAMIC_MEMORY == FALSE
-SDP_API extern tSDP_CB  sdp_cb;
+extern tSDP_CB  sdp_cb;
 #else
-SDP_API extern tSDP_CB *sdp_cb_ptr;
+extern tSDP_CB *sdp_cb_ptr;
 #define sdp_cb (*sdp_cb_ptr)
 #endif
 
@@ -249,11 +246,11 @@
 #endif
 
 /* Functions provided by sdp_main.c */
-SDP_API extern void     sdp_init (void);
+extern void     sdp_init (void);
 extern void     sdp_disconnect (tCONN_CB*p_ccb, UINT16 reason);
 
 #if (defined(SDP_DEBUG) && SDP_DEBUG == TRUE)
-SDP_API extern UINT16 sdp_set_max_attr_list_size (UINT16 max_size);
+extern UINT16 sdp_set_max_attr_list_size (UINT16 max_size);
 #endif
 
 /* Functions provided by sdp_conn.c
@@ -285,10 +282,10 @@
 extern UINT8    *sdpu_extract_attr_seq (UINT8 *p, UINT16 param_len, tSDP_ATTR_SEQ *p_seq);
 extern UINT8    *sdpu_extract_uid_seq (UINT8 *p, UINT16 param_len, tSDP_UUID_SEQ *p_seq);
 
-SDP_API extern UINT8    *sdpu_get_len_from_type (UINT8 *p, UINT8 type, UINT32 *p_len);
+extern UINT8    *sdpu_get_len_from_type (UINT8 *p, UINT8 type, UINT32 *p_len);
 extern BOOLEAN  sdpu_is_base_uuid (UINT8 *p_uuid);
 extern BOOLEAN  sdpu_compare_uuid_arrays (UINT8 *p_uuid1, UINT32 len1, UINT8 *p_uuid2, UINT16 len2);
-SDP_API extern BOOLEAN  sdpu_compare_bt_uuids (tBT_UUID *p_uuid1, tBT_UUID *p_uuid2);
+extern BOOLEAN  sdpu_compare_bt_uuids (tBT_UUID *p_uuid1, tBT_UUID *p_uuid2);
 extern BOOLEAN  sdpu_compare_uuid_with_attr (tBT_UUID *p_btuuid, tSDP_DISC_ATTR *p_attr);
 
 extern void     sdpu_sort_attr_list( UINT16 num_attr, tSDP_DISCOVERY_DB *p_db );
@@ -326,4 +323,3 @@
 
 
 #endif
-
diff --git a/stack/smp/smp_api.c b/stack/smp/smp_api.c
index 85d1054..2ebf953 100644
--- a/stack/smp/smp_api.c
+++ b/stack/smp/smp_api.c
@@ -82,7 +82,7 @@
 ** Returns          The new or current trace level
 **
 *******************************************************************************/
-SMP_API extern UINT8 SMP_SetTraceLevel (UINT8 new_level)
+extern UINT8 SMP_SetTraceLevel (UINT8 new_level)
 {
     if (new_level != 0xFF)
         smp_cb.trace_level = new_level;
@@ -338,5 +338,3 @@
     return status;
 }
 #endif /* SMP_INCLUDED */
-
-
diff --git a/stack/smp/smp_int.h b/stack/smp/smp_int.h
index 70c09a5..af5102d 100644
--- a/stack/smp/smp_int.h
+++ b/stack/smp/smp_int.h
@@ -227,9 +227,9 @@
 #endif
 
 #if SMP_DYNAMIC_MEMORY == FALSE
-    SMP_API extern tSMP_CB  smp_cb;
+extern tSMP_CB  smp_cb;
 #else
-    SMP_API extern tSMP_CB *smp_cb_ptr;
+extern tSMP_CB *smp_cb_ptr;
 #define smp_cb (*smp_cb_ptr)
 #endif
 
@@ -238,15 +238,15 @@
 #endif
 
 /* Functions provided by att_main.c */
-SMP_API extern void smp_init (void);
+extern void smp_init (void);
 
 #if SMP_CONFORMANCE_TESTING == TRUE
 /* Used only for conformance testing */
-SMP_API extern void  smp_set_test_confirm_value (BOOLEAN enable, UINT8 *p_c_value);
-SMP_API extern void  smp_set_test_rand_value (BOOLEAN enable, UINT8 *p_c_value);
-SMP_API extern void  smp_set_test_pair_fail_status (BOOLEAN enable, UINT8 status);
-SMP_API extern void  smp_remove_fixed_channel_disable (BOOLEAN disable);
-SMP_API extern void  smp_skip_compare_check (BOOLEAN enable);
+extern void  smp_set_test_confirm_value (BOOLEAN enable, UINT8 *p_c_value);
+extern void  smp_set_test_rand_value (BOOLEAN enable, UINT8 *p_c_value);
+extern void  smp_set_test_pair_fail_status (BOOLEAN enable, UINT8 status);
+extern void  smp_remove_fixed_channel_disable (BOOLEAN disable);
+extern void  smp_skip_compare_check (BOOLEAN enable);
 #endif
 /* smp main */
 extern void smp_sm_event(tSMP_CB *p_cb, tSMP_EVENT event, void *p_data);
@@ -321,4 +321,3 @@
 extern void smp_reject_unexp_pair_req(BD_ADDR bd_addr);
 
 #endif /* SMP_INT_H */
-
diff --git a/stack/smp/smp_utils.c b/stack/smp/smp_utils.c
index 21d93f8..ead44fc 100644
--- a/stack/smp/smp_utils.c
+++ b/stack/smp/smp_utils.c
@@ -34,6 +34,7 @@
 #include "l2c_api.h"
 #include "l2c_int.h"
 #include "smp_int.h"
+#include "device/include/controller.h"
 
 
 #define SMP_PAIRING_REQ_SIZE    7
@@ -349,7 +350,6 @@
 {
     BT_HDR      *p_buf = NULL ;
     UINT8       *p;
-    BD_ADDR     static_addr;
     UNUSED(cmd_code);
     UNUSED(p_cb);
 
@@ -360,8 +360,7 @@
 
         UINT8_TO_STREAM (p, SMP_OPCODE_ID_ADDR);
         UINT8_TO_STREAM (p, 0);     /* TODO: update with local address type */
-        BTM_GetLocalDeviceAddr(static_addr);
-        BDADDR_TO_STREAM (p, static_addr);
+        BDADDR_TO_STREAM (p, controller_get_interface()->get_address()->address);
 
         p_buf->offset = L2CAP_MIN_OFFSET;
         p_buf->len = SMP_ID_ADDR_SIZE;
diff --git a/stack/srvc/srvc_battery_int.h b/stack/srvc/srvc_battery_int.h
index 8369bdd..a9f81ae 100644
--- a/stack/srvc/srvc_battery_int.h
+++ b/stack/srvc/srvc_battery_int.h
@@ -60,9 +60,9 @@
 
 /* Global GATT data */
 #if GATT_DYNAMIC_MEMORY == FALSE
-GATT_API extern tBATTERY_CB battery_cb;
+extern tBATTERY_CB battery_cb;
 #else
-GATT_API extern tBATTERY_CB *battery_cb_ptr;
+extern tBATTERY_CB *battery_cb_ptr;
 #define battery_cb (*battery_cb_ptr)
 #endif
 
diff --git a/stack/srvc/srvc_dis.c b/stack/srvc/srvc_dis.c
index e292212..4a1e1bb 100644
--- a/stack/srvc/srvc_dis.c
+++ b/stack/srvc/srvc_dis.c
@@ -23,6 +23,9 @@
 #include "srvc_eng_int.h"
 #include "srvc_dis_int.h"
 
+#define LOG_TAG "bt_srvc"
+#include "osi/include/log.h"
+
 #if BLE_INCLUDED == TRUE
 
 #define DIS_MAX_NUM_INC_SVR       0
@@ -197,9 +200,9 @@
 ** Returns          void
 **
 *******************************************************************************/
-void dis_gatt_c_read_dis_value_cmpl(UINT16 conn_id)
+static void dis_gatt_c_read_dis_value_cmpl(UINT16 conn_id)
 {
-    tSRVC_CLCB *p_clcb =  srvc_eng_find_clcb_by_conn_id(conn_id);
+    tSRVC_CLCB *p_clcb = srvc_eng_find_clcb_by_conn_id(conn_id);
 
     dis_cb.dis_read_uuid_idx = 0xff;
 
@@ -207,13 +210,12 @@
 
     if (dis_cb.p_read_dis_cback && p_clcb)
     {
-        GATT_TRACE_ERROR("dis_gatt_c_read_dis_value_cmpl: attr_mask = 0x%04x", p_clcb->dis_value.attr_mask);
-        GATT_TRACE_EVENT("calling p_read_dis_cbackd");
+        LOG_INFO("%s conn_id:%d attr_mask = 0x%04x", __func__, conn_id,
+                p_clcb->dis_value.attr_mask);
 
         (*dis_cb.p_read_dis_cback)(p_clcb->bda, &p_clcb->dis_value);
-        dis_cb.p_read_dis_cback=NULL;
+        dis_cb.p_read_dis_cback = NULL;
     }
-
 }
 
 /*******************************************************************************
diff --git a/stack/srvc/srvc_dis_int.h b/stack/srvc/srvc_dis_int.h
index f9f4dcd..7457319 100644
--- a/stack/srvc/srvc_dis_int.h
+++ b/stack/srvc/srvc_dis_int.h
@@ -62,9 +62,9 @@
 
 /* Global GATT data */
 #if GATT_DYNAMIC_MEMORY == FALSE
-GATT_API extern tDIS_CB dis_cb;
+extern tDIS_CB dis_cb;
 #else
-GATT_API extern tDIS_CB *dis_cb_ptr;
+extern tDIS_CB *dis_cb_ptr;
 #define dis_cb (*dis_cb_ptr)
 #endif
 
diff --git a/stack/srvc/srvc_eng_int.h b/stack/srvc/srvc_eng_int.h
index 140d4e2..edd9763 100644
--- a/stack/srvc/srvc_eng_int.h
+++ b/stack/srvc/srvc_eng_int.h
@@ -64,9 +64,9 @@
 
 /* Global GATT data */
 #if GATT_DYNAMIC_MEMORY == FALSE
-GATT_API extern tSRVC_ENG_CB srvc_eng_cb;
+extern tSRVC_ENG_CB srvc_eng_cb;
 #else
-GATT_API extern tSRVC_ENG_CB srvc_eng_cb_ptr;
+extern tSRVC_ENG_CB srvc_eng_cb_ptr;
 #define srvc_eng_cb (*srvc_eng_cb_ptr)
 
 #endif
diff --git a/test/run_unit_tests.sh b/test/run_unit_tests.sh
new file mode 100755
index 0000000..cb79d87
--- /dev/null
+++ b/test/run_unit_tests.sh
@@ -0,0 +1,39 @@
+#!/usr/bin/env bash
+
+known_tests=(
+  net_test_btcore
+  net_test_device
+  net_test_hci
+  net_test_osi
+)
+
+usage() {
+  echo "Usage: $0 [--all|--help|<test names>]"
+  echo ""
+  echo "Known test names:"
+
+  for name in ${known_tests[*]}
+  do
+    echo "    $name"
+  done
+}
+
+run_tests() {
+  for name in $*
+  do
+    echo "--- $name ---"
+    echo "pushing..."
+    adb push {$ANDROID_PRODUCT_OUT,}/data/nativetest/$name/$name
+    echo "running..."
+    adb shell data/nativetest/$name/$name
+  done
+}
+
+if [ $# -eq 0 ] || [ $1 == "--help" ]; then
+  usage
+elif [ $1 == "--all" ]; then
+  run_tests ${known_tests[*]}
+else
+  run_tests $*
+fi
+
diff --git a/test/suite/Android.mk b/test/suite/Android.mk
index 2f45180..3caec79 100644
--- a/test/suite/Android.mk
+++ b/test/suite/Android.mk
@@ -19,22 +19,34 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE := bdtest
+LOCAL_MODULE := net_test_bluedroid
+
+LOCAL_C_INCLUDES += \
+    $(LOCAL_PATH)/../../
 
 LOCAL_SRC_FILES := \
-	cases/adapter.c \
-	cases/cases.c \
-	cases/pan.c \
-	support/adapter.c \
-	support/callbacks.c \
-	support/hal.c \
-	support/pan.c \
-	support/property.c \
-	main.c
+    cases/adapter.c \
+    cases/cases.c \
+    cases/gatt.c \
+    cases/pan.c \
+    cases/rfcomm.c \
+    support/adapter.c \
+    support/callbacks.c \
+    support/gatt.c \
+    support/hal.c \
+    support/pan.c \
+    support/rfcomm.c \
+    main.c
 
 LOCAL_SHARED_LIBRARIES += \
-	libhardware \
-	libhardware_legacy
+    liblog \
+    libhardware \
+    libhardware_legacy \
+    libcutils
+
+LOCAL_STATIC_LIBRARIES += \
+  libbtcore \
+  libosi
 
 LOCAL_CFLAGS += -std=c99 -Wall -Wno-unused-parameter -Wno-missing-field-initializers -Werror
 
diff --git a/test/suite/base.h b/test/suite/base.h
index 4d6f270..935ff17 100644
--- a/test/suite/base.h
+++ b/test/suite/base.h
@@ -24,7 +24,9 @@
 #include <string.h>
 
 #include <hardware/bluetooth.h>
+#include <hardware/bt_gatt.h>
 #include <hardware/bt_pan.h>
+#include <hardware/bt_sock.h>
 #include <hardware/hardware.h>
 
 #ifndef ARRAY_SIZE
diff --git a/test/suite/cases/adapter.c b/test/suite/cases/adapter.c
index 492d8f4..280cfc6 100644
--- a/test/suite/cases/adapter.c
+++ b/test/suite/cases/adapter.c
@@ -19,7 +19,7 @@
 #include "base.h"
 #include "support/adapter.h"
 #include "support/callbacks.h"
-#include "support/property.h"
+#include "btcore/include/property.h"
 
 bool adapter_enable_disable() {
   int error;
@@ -52,7 +52,7 @@
   TASSERT(error == BT_STATUS_SUCCESS, "Error setting device name.");
   TASSERT(adapter_get_property_count() == 1, "Expected 1 adapter property change, found %d instead.", adapter_get_property_count());
   TASSERT(adapter_get_property(BT_PROPERTY_BDNAME), "The Bluetooth name property did not change.");
-  TASSERT(property_equals(adapter_get_property(BT_PROPERTY_BDNAME), name), "Bluetooth name '%s' does not match test value", property_extract_name(adapter_get_property(BT_PROPERTY_BDNAME)));
+  TASSERT(property_equals(adapter_get_property(BT_PROPERTY_BDNAME), name), "Bluetooth name '%s' does not match test value", property_as_name(adapter_get_property(BT_PROPERTY_BDNAME))->name);
 
   property_free(name);
 
@@ -68,7 +68,7 @@
   TASSERT(error == BT_STATUS_SUCCESS, "Error getting device name.");
   TASSERT(adapter_get_property_count() == 1, "Expected 1 adapter property change, found %d instead.", adapter_get_property_count());
   TASSERT(adapter_get_property(BT_PROPERTY_BDNAME), "The Bluetooth name property did not change.");
-  TASSERT(property_equals(adapter_get_property(BT_PROPERTY_BDNAME), name), "Bluetooth name '%s' does not match test value", property_extract_name(adapter_get_property(BT_PROPERTY_BDNAME)));
+  TASSERT(property_equals(adapter_get_property(BT_PROPERTY_BDNAME), name), "Bluetooth name '%s' does not match test value", property_as_name(adapter_get_property(BT_PROPERTY_BDNAME))->name);
 
   property_free(name);
   return true;
diff --git a/test/suite/cases/cases.c b/test/suite/cases/cases.c
index 20d941f..476a3a1 100644
--- a/test/suite/cases/cases.c
+++ b/test/suite/cases/cases.c
@@ -26,15 +26,24 @@
 TEST_CASE_DECL(adapter_start_discovery);
 TEST_CASE_DECL(adapter_cancel_discovery);
 
+TEST_CASE_DECL(rfcomm_connect);
+TEST_CASE_DECL(rfcomm_repeated_connect);
+
 TEST_CASE_DECL(pan_enable);
 TEST_CASE_DECL(pan_connect);
 TEST_CASE_DECL(pan_disconnect);
 TEST_CASE_DECL(pan_quick_reconnect);
 
+TEST_CASE_DECL(gatt_client_register);
+TEST_CASE_DECL(gatt_client_scan);
+TEST_CASE_DECL(gatt_client_advertise);
+TEST_CASE_DECL(gatt_server_register);
+TEST_CASE_DECL(gatt_server_build);
+
 // These are run with the Bluetooth adapter disabled.
 const test_case_t sanity_suite[] = {
   TEST_CASE(adapter_enable_disable),
-  TEST_CASE(adapter_repeated_enable_disable),
+  TEST_CASE(adapter_repeated_enable_disable)
 };
 
 // The normal test suite is run with the adapter enabled.
@@ -44,9 +53,18 @@
   TEST_CASE(adapter_start_discovery),
   TEST_CASE(adapter_cancel_discovery),
 
+  TEST_CASE(rfcomm_connect),
+  TEST_CASE(rfcomm_repeated_connect),
+
   TEST_CASE(pan_enable),
   TEST_CASE(pan_connect),
   TEST_CASE(pan_disconnect),
+
+  TEST_CASE(gatt_client_register),
+  TEST_CASE(gatt_client_scan),
+  TEST_CASE(gatt_client_advertise),
+  TEST_CASE(gatt_server_register),
+  TEST_CASE(gatt_server_build)
 };
 
 const size_t sanity_suite_size = ARRAY_SIZE(sanity_suite);
diff --git a/test/suite/cases/gatt.c b/test/suite/cases/gatt.c
new file mode 100644
index 0000000..fd6835a
--- /dev/null
+++ b/test/suite/cases/gatt.c
@@ -0,0 +1,136 @@
+#include <stdlib.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "base.h"
+#include "support/gatt.h"
+#include "support/callbacks.h"
+
+#define DEFAULT_RANDOM_SEED 42
+
+static void create_random_uuid(bt_uuid_t *uuid, int seed) {
+  srand(seed < 0 ? time(NULL) : seed);
+  for (int i = 0; i < 16; ++i) {
+    uuid->uu[i] = (uint8_t) (rand() % 256);
+  }
+}
+
+bool gatt_client_register() {
+  TASSERT(gatt_interface != NULL, "Null GATT interface.");
+
+  // Registers gatt client.
+  bt_uuid_t gatt_client_uuid;
+  create_random_uuid(&gatt_client_uuid, DEFAULT_RANDOM_SEED);
+  CALL_AND_WAIT(gatt_interface->client->register_client(&gatt_client_uuid), btgattc_register_app_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error registering GATT client app callback.");
+
+  // Unregisters gatt client. No callback is expected.
+  gatt_interface->client->unregister_client(gatt_get_client_interface());
+
+  return true;
+}
+
+bool gatt_client_scan() {
+  TASSERT(gatt_interface != NULL, "Null GATT interface.");
+
+  // Starts BLE scan. NB: This test assumes there is a BLE beacon advertising nearby.
+  CALL_AND_WAIT(gatt_interface->client->scan(true), btgattc_scan_result_cb);
+
+  // Ends BLE scan. No callback is expected.
+  gatt_interface->client->scan(false);
+
+  return true;
+}
+
+bool gatt_client_advertise() {
+  TASSERT(gatt_interface != NULL, "Null GATT interface.");
+
+  // Registers a new client app.
+  bt_uuid_t gatt_client_uuid;
+  create_random_uuid(&gatt_client_uuid, DEFAULT_RANDOM_SEED);
+  CALL_AND_WAIT(gatt_interface->client->register_client(&gatt_client_uuid), btgattc_register_app_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error registering GATT client app callback.");
+
+  // Starts advertising.
+  CALL_AND_WAIT(gatt_interface->client->listen(gatt_get_client_interface(), true), btgattc_advertise_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error starting BLE advertisement.");
+
+  // Stops advertising.
+  CALL_AND_WAIT(gatt_interface->client->listen(gatt_get_client_interface(), false), btgattc_advertise_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error stopping BLE advertisement.");
+
+  // Unregisters gatt server. No callback is expected.
+  gatt_interface->client->unregister_client(gatt_get_client_interface());
+
+  return true;
+}
+
+bool gatt_server_register() {
+  TASSERT(gatt_interface != NULL, "Null GATT interface.");
+
+  // Registers gatt server.
+  bt_uuid_t gatt_server_uuid;
+  create_random_uuid(&gatt_server_uuid, DEFAULT_RANDOM_SEED);
+  CALL_AND_WAIT(gatt_interface->server->register_server(&gatt_server_uuid), btgatts_register_app_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error registering GATT server app callback.");
+
+  // Unregisters gatt server. No callback is expected.
+  gatt_interface->server->unregister_server(gatt_get_server_interface());
+  return true;
+}
+
+bool gatt_server_build() {
+  TASSERT(gatt_interface != NULL, "Null GATT interface.");
+
+  // Registers gatt server.
+  bt_uuid_t gatt_server_uuid;
+  create_random_uuid(&gatt_server_uuid, DEFAULT_RANDOM_SEED);
+  CALL_AND_WAIT(gatt_interface->server->register_server(&gatt_server_uuid), btgatts_register_app_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error registering GATT server app callback.");
+
+  // Service UUID.
+  btgatt_srvc_id_t srvc_id;
+  srvc_id.id.inst_id = 0;   // there is only one instance of this service.
+  srvc_id.is_primary = 1;   // this service is primary.
+  create_random_uuid(&srvc_id.id.uuid, -1);
+
+  // Characteristics UUID.
+  bt_uuid_t char_uuid;
+  create_random_uuid(&char_uuid, -1);
+
+  // Descriptor UUID.
+  bt_uuid_t desc_uuid;
+  create_random_uuid(&desc_uuid, -1);
+
+  // Adds service.
+  int server_if = gatt_get_server_interface();
+  CALL_AND_WAIT(gatt_interface->server->add_service(server_if, &srvc_id, 4 /* # handles */), btgatts_service_added_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error adding service.");
+
+  // Adds characteristics.
+  int srvc_handle = gatt_get_service_handle();
+  CALL_AND_WAIT(gatt_interface->server->add_characteristic(server_if, srvc_handle, &char_uuid, 0x10 /* notification */, 0x01 /* read only */), btgatts_characteristic_added_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error adding characteristics.");
+
+  // Adds descriptor.
+  int char_handle = gatt_get_characteristic_handle();
+  CALL_AND_WAIT(gatt_interface->server->add_descriptor(server_if, srvc_handle, &desc_uuid, 0x01), btgatts_descriptor_added_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error adding descriptor.");
+
+  // Starts server.
+  CALL_AND_WAIT(gatt_interface->server->start_service(server_if, srvc_handle, 2 /*BREDR/LE*/), btgatts_service_started_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error starting server.");
+
+  // Stops server.
+  CALL_AND_WAIT(gatt_interface->server->stop_service(server_if, srvc_handle), btgatts_service_stopped_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error stopping server.");
+
+  // Deletes service.
+  CALL_AND_WAIT(gatt_interface->server->delete_service(server_if, srvc_handle), btgatts_service_deleted_cb);
+  TASSERT(gatt_get_status() == BT_STATUS_SUCCESS, "Error deleting service.");
+
+  // Unregisters gatt server. No callback is expected.
+  gatt_interface->server->unregister_server(server_if);
+
+  return true;
+}
\ No newline at end of file
diff --git a/test/suite/cases/rfcomm.c b/test/suite/cases/rfcomm.c
new file mode 100644
index 0000000..27728d1
--- /dev/null
+++ b/test/suite/cases/rfcomm.c
@@ -0,0 +1,76 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include "base.h"
+#include "support/callbacks.h"
+#include "support/rfcomm.h"
+
+static const bt_uuid_t HFP_UUID = {{ 0x00, 0x00, 0x11, 0x1E, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB }};
+static const bt_uuid_t HFP_AG_UUID = {{ 0x00, 0x00, 0x11, 0x1F, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB }};
+static const char HANDSHAKE_COMMAND[] = "AT+BRSF=29\r";
+static const char HANDSHAKE_RESPONSE[] = "OK\r\n";
+
+static bool handshake(int fd) {
+  TASSERT(write(fd, HANDSHAKE_COMMAND, sizeof(HANDSHAKE_COMMAND)) == sizeof(HANDSHAKE_COMMAND), "Unable to send HFP handshake.");
+
+  char response[256] = { 0 };
+  size_t total = 0;
+  while (!strstr(response, HANDSHAKE_RESPONSE) && total < sizeof(response)) {
+    ssize_t len = read(fd, response + total, sizeof(response) - total);
+    TASSERT(len != -1 && len != 0, "Unable to read complete response from socket.");
+    total += len;
+  }
+  TASSERT(strstr(response, HANDSHAKE_RESPONSE) != NULL, "No valid response from HFP audio gateway.");
+  return true;
+}
+
+bool rfcomm_connect() {
+  int fd;
+  int error;
+
+  error = socket_interface->connect(&bt_remote_bdaddr, BTSOCK_RFCOMM, (const uint8_t *)&HFP_AG_UUID, 0, &fd, 0);
+  TASSERT(error == BT_STATUS_SUCCESS, "Error creating RFCOMM socket: %d", error);
+  TASSERT(fd != -1, "Error creating RFCOMM socket: invalid fd");
+
+  int channel;
+  sock_connect_signal_t signal;
+  TASSERT(read(fd, &channel, sizeof(channel)) == sizeof(channel), "Channel not read from RFCOMM socket.");
+  TASSERT(read(fd, &signal, sizeof(signal)) == sizeof(signal), "Connection signal not read from RFCOMM socket.");
+
+  TASSERT(!memcmp(&signal.bd_addr, &bt_remote_bdaddr, sizeof(bt_bdaddr_t)), "Connected to a different bdaddr than expected.");
+  TASSERT(channel == signal.channel, "Inconsistent channels returned: %d and %d", channel, signal.channel);
+
+  if (!handshake(fd))
+    return false;
+
+  close(fd);
+  return true;
+}
+
+bool rfcomm_repeated_connect() {
+  static const int max_iterations = 128;
+
+  for (int i = 0; i < max_iterations; ++i) {
+    TASSERT(rfcomm_connect(), "Connection failed on attempt %d/%d", i, max_iterations);
+  }
+
+  return true;
+}
diff --git a/test/suite/main.c b/test/suite/main.c
index 7a3af5b..24cb862 100644
--- a/test/suite/main.c
+++ b/test/suite/main.c
@@ -16,39 +16,148 @@
  *
  ******************************************************************************/
 
+#include <cutils/properties.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <unistd.h>
+
 #include "base.h"
+#include "btcore/include/bdaddr.h"
 #include "cases/cases.h"
+#include "osi/include/config.h"
 #include "support/callbacks.h"
 #include "support/hal.h"
+#include "support/gatt.h"
 #include "support/pan.h"
+#include "support/rfcomm.h"
 
-#define GRAY  "\x1b[0;37m"
-#define GREEN "\x1b[0;32m"
-#define RED   "\x1b[0;31m"
+// How long the watchdog thread should wait before checking if a test has completed.
+// Any individual test will have at least WATCHDOG_PERIOD_SEC and at most
+// 2 * WATCHDOG_PERIOD_SEC seconds to complete.
+static const int WATCHDOG_PERIOD_SEC = 1 * 60;
+static const char *CONFIG_FILE_PATH = "/data/misc/bluedroid/bt_config.conf";
 
 const bt_interface_t *bt_interface;
 bt_bdaddr_t bt_remote_bdaddr;
 
-static bool parse_bdaddr(const char *str, bt_bdaddr_t *addr) {
-  if (!addr) {
-    return false;
-  }
+static pthread_t watchdog_thread;
+static int watchdog_id;
+static bool watchdog_running;
 
-  int v[6];
-  if (sscanf(str, "%02x:%02x:%02x:%02x:%02x:%02x", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]) != 6) {
-    return false;
-  }
+static void *watchdog_fn(void *arg) {
+  int current_id = 0;
+  for (;;) {
+    // Check every second whether this thread should exit and check
+    // every WATCHDOG_PERIOD_SEC whether we should terminate the process.
+    for (int i = 0; watchdog_running && i < WATCHDOG_PERIOD_SEC; ++i) {
+      sleep(1);
+    }
 
-  for (int i = 0; i < 6; ++i) {
-    addr->address[i] = (uint8_t)v[i];
-  }
+    if (!watchdog_running)
+      break;
 
-  return true;
+    if (current_id == watchdog_id) {
+      printf("Watchdog detected hanging test suite, aborting...\n");
+      exit(-1);
+    }
+    current_id = watchdog_id;
+  }
+  return NULL;
+}
+
+static bool is_shell_running(void) {
+  char property_str[100];
+  property_get("init.svc.zygote", property_str, NULL);
+  if (!strcmp("running", property_str)) {
+    return true;
+  }
+  return false;
+}
+
+static void print_usage(const char *program_name) {
+  printf("Usage: %s [options] [test name]\n", program_name);
+  printf("\n");
+  printf("Options:\n");
+  printf("  %-20sdisplay this help text.\n", "--help");
+  printf("  %-20sdo not run sanity suite.\n", "--insanity");
+  printf("\n");
+  printf("Valid test names are:\n");
+  for (size_t i = 0; i < sanity_suite_size; ++i) {
+    printf("  %s\n", sanity_suite[i].function_name);
+  }
+  for (size_t i = 0; i < test_suite_size; ++i) {
+    printf("  %s\n", test_suite[i].function_name);
+  }
+}
+
+static bool is_valid(const char *test_name) {
+  for (size_t i = 0; i < sanity_suite_size; ++i) {
+    if (!strcmp(test_name, sanity_suite[i].function_name)) {
+      return true;
+    }
+  }
+  for (size_t i = 0; i < test_suite_size; ++i) {
+    if (!strcmp(test_name, test_suite[i].function_name)) {
+      return true;
+    }
+  }
+  return false;
 }
 
 int main(int argc, char **argv) {
-  if (argc < 2 || !parse_bdaddr(argv[1], &bt_remote_bdaddr)) {
-    printf("Usage: %s <bdaddr>\n", argv[0]);
+  const char *test_name = NULL;
+  bool skip_sanity_suite = false;
+
+  for (int i = 1; i < argc; ++i) {
+    if (!strcmp("--help", argv[i])) {
+      print_usage(argv[0]);
+      return 0;
+    }
+
+    if (!strcmp("--insanity", argv[i])) {
+      skip_sanity_suite = true;
+      continue;
+    }
+
+    if (!is_valid(argv[i])) {
+      printf("Error: invalid test name.\n");
+      print_usage(argv[0]);
+      return -1;
+    }
+
+    if (test_name != NULL) {
+      printf("Error: invalid arguments.\n");
+      print_usage(argv[0]);
+      return -1;
+    }
+
+    test_name = argv[i];
+  }
+
+  if (is_shell_running()) {
+    printf("Run 'adb shell stop' before running %s.\n", argv[0]);
+    return -1;
+  }
+
+  config_t *config = config_new(CONFIG_FILE_PATH);
+  if (!config) {
+    printf("Error: unable to open stack config file.\n");
+    print_usage(argv[0]);
+    return -1;
+  }
+
+  for (const config_section_node_t *node = config_section_begin(config); node != config_section_end(config); node = config_section_next(node)) {
+    const char *name = config_section_name(node);
+    if (config_has_key(config, name, "LinkKey") && string_to_bdaddr(name, &bt_remote_bdaddr)) {
+      break;
+    }
+  }
+
+  config_free(config);
+
+  if (bdaddr_is_empty(&bt_remote_bdaddr)) {
+    printf("Error: unable to find paired device in config file.\n");
+    print_usage(argv[0]);
     return -1;
   }
 
@@ -57,58 +166,94 @@
     return 1;
   }
 
+  if (!btsocket_init()) {
+    printf("Unable to initialize Bluetooth sockets.\n");
+    return 2;
+  }
+
   if (!pan_init()) {
     printf("Unable to initialize PAN.\n");
-    return 2;
+    return 3;
+  }
+
+  if (!gatt_init()) {
+    printf("Unable to initialize GATT.\n");
+    return 4;
+  }
+
+  watchdog_running = true;
+  pthread_create(&watchdog_thread, NULL, watchdog_fn, NULL);
+
+  static const char *DEFAULT  = "\x1b[0m";
+  static const char *GREEN = "\x1b[0;32m";
+  static const char *RED   = "\x1b[0;31m";
+
+  // If the output is not a TTY device, don't colorize output.
+  if (!isatty(fileno(stdout))) {
+    DEFAULT = GREEN = RED = "";
   }
 
   int pass = 0;
   int fail = 0;
   int case_num = 0;
 
-  // Run through the sanity suite.
-  for (size_t i = 0; i < sanity_suite_size; ++i) {
-    callbacks_init();
-    if (sanity_suite[i].function()) {
-      printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, sanity_suite[i].function_name, GREEN, GRAY);
-      ++pass;
-    } else {
-      printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, sanity_suite[i].function_name, RED, GRAY);
-      ++fail;
+  // If test name is specified, run that specific test.
+  // Otherwise run through the sanity suite.
+  if (!skip_sanity_suite) {
+    for (size_t i = 0; i < sanity_suite_size; ++i) {
+      if (!test_name || !strcmp(test_name, sanity_suite[i].function_name)) {
+        callbacks_init();
+        if (sanity_suite[i].function()) {
+          printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, sanity_suite[i].function_name, GREEN, DEFAULT);
+          ++pass;
+        } else {
+          printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, sanity_suite[i].function_name, RED, DEFAULT);
+          ++fail;
+        }
+        callbacks_cleanup();
+        ++watchdog_id;
+      }
     }
-    callbacks_cleanup();
   }
 
   // If there was a failure in the sanity suite, don't bother running the rest of the tests.
   if (fail) {
-    printf("\n%sSanity suite failed with %d errors.%s\n", RED, fail, GRAY);
+    printf("\n%sSanity suite failed with %d errors.%s\n", RED, fail, DEFAULT);
     hal_close();
-    return 0;
+    return 4;
   }
 
-  // Run the full test suite.
+  // If test name is specified, run that specific test.
+  // Otherwise run through the full test suite.
   for (size_t i = 0; i < test_suite_size; ++i) {
-    callbacks_init();
-    CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
-    if (test_suite[i].function()) {
-      printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, test_suite[i].function_name, GREEN, GRAY);
-      ++pass;
-    } else {
-      printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, test_suite[i].function_name, RED, GRAY);
-      ++fail;
+    if (!test_name || !strcmp(test_name, test_suite[i].function_name)) {
+      callbacks_init();
+      CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
+      if (test_suite[i].function()) {
+        printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, test_suite[i].function_name, GREEN, DEFAULT);
+        ++pass;
+      } else {
+        printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, test_suite[i].function_name, RED, DEFAULT);
+        ++fail;
+      }
+      CALL_AND_WAIT(bt_interface->disable(), adapter_state_changed);
+      callbacks_cleanup();
+      ++watchdog_id;
     }
-    CALL_AND_WAIT(bt_interface->disable(), adapter_state_changed);
-    callbacks_cleanup();
   }
 
   printf("\n");
 
   if (fail) {
-    printf("%d/%d tests failed. See above for failed test cases.\n", fail, test_suite_size);
+    printf("%d/%d tests failed. See above for failed test cases.\n", fail, sanity_suite_size + test_suite_size);
   } else {
     printf("All tests passed!\n");
   }
 
+  watchdog_running = false;
+  pthread_join(watchdog_thread, NULL);
+
   hal_close();
+
   return 0;
 }
diff --git a/test/suite/support/adapter.c b/test/suite/support/adapter.c
index 0a78253..d6b8ab3 100644
--- a/test/suite/support/adapter.c
+++ b/test/suite/support/adapter.c
@@ -17,14 +17,17 @@
  ******************************************************************************/
 
 #include "base.h"
+#include "btcore/include/bdaddr.h"
+#include "btcore/include/property.h"
 #include "support/adapter.h"
 #include "support/callbacks.h"
-#include "support/property.h"
 
 static bt_state_t state;
 static int property_count = 0;
 static bt_property_t *properties = NULL;
 static bt_discovery_state_t discovery_state;
+static bt_acl_state_t acl_state;
+static bt_bond_state_t bond_state;
 
 bt_state_t adapter_get_state() {
   return state;
@@ -48,6 +51,21 @@
   return discovery_state;
 }
 
+bt_acl_state_t adapter_get_acl_state() {
+  return acl_state;
+}
+
+// Returns the device bond state.
+bt_bond_state_t adapter_get_bond_state() {
+  return bond_state;
+}
+
+// callback
+void acl_state_changed(bt_status_t status, bt_bdaddr_t *remote_bd_addr, bt_acl_state_t state) {
+  acl_state = state;
+  CALLBACK_RET();
+}
+
 // callback
 void adapter_state_changed(bt_state_t new_state) {
   state = new_state;
@@ -56,8 +74,8 @@
 
 // callback
 void adapter_properties(bt_status_t status,
-                        int num_properties,
-                        bt_property_t *new_properties) {
+    int num_properties,
+    bt_property_t *new_properties) {
   property_free_array(properties, property_count);
   properties = property_copy_array(new_properties, num_properties);
   property_count = num_properties;
@@ -66,7 +84,42 @@
 }
 
 // callback
+void bond_state_changed(bt_status_t status,
+    bt_bdaddr_t *bdaddr,
+    bt_bond_state_t state) {
+  bond_state = state;
+  CALLBACK_RET();
+}
+
+// callback
+void device_found(int num_properties, bt_property_t *properties) {
+  CALLBACK_RET();
+}
+
+// callback
 void discovery_state_changed(bt_discovery_state_t state) {
   discovery_state = state;
   CALLBACK_RET();
 }
+
+// callback
+void remote_device_properties(bt_status_t status, bt_bdaddr_t *bd_addr,
+    int num_properties, bt_property_t *properties) {
+  CALLBACK_RET();
+}
+
+// callback
+void ssp_request(
+    bt_bdaddr_t *remote_bd_addr,
+    bt_bdname_t *bd_name,
+    uint32_t cod,
+    bt_ssp_variant_t pairing_variant,
+    uint32_t pass_key) {
+
+  CALLBACK_RET();
+}
+
+// callback
+void thread_evt(bt_cb_thread_evt evt) {
+  CALLBACK_RET();
+}
diff --git a/test/suite/support/callbacks.c b/test/suite/support/callbacks.c
index 08a69a5..bbec5d2 100644
--- a/test/suite/support/callbacks.c
+++ b/test/suite/support/callbacks.c
@@ -19,25 +19,56 @@
 #include "base.h"
 #include "support/callbacks.h"
 
+// Bluetooth callbacks
+void acl_state_changed(bt_status_t status, bt_bdaddr_t *remote_bd_addr, bt_acl_state_t state);
+void adapter_properties(bt_status_t status, int num_properties, bt_property_t *properties);
 void adapter_state_changed(bt_state_t state);
-void adapter_properties(bt_status_t status,
-                        int num_properties,
-                        bt_property_t *properties);
+void bond_state_changed(bt_status_t status, bt_bdaddr_t *remote_bd_addr, bt_bond_state_t state);
+
+void device_found(int num_properties, bt_property_t *properties);
 void discovery_state_changed(bt_discovery_state_t state);
+void remote_device_properties(bt_status_t status, bt_bdaddr_t *bd_addr, int num_properties, bt_property_t *properties);
+void ssp_request(bt_bdaddr_t *remote_bd_addr, bt_bdname_t *bd_name, uint32_t cod, bt_ssp_variant_t pairing_variant, uint32_t pass_key);
+void thread_evt(bt_cb_thread_evt evt);
 
-void pan_control_state_changed(btpan_control_state_t state, int local_role, bt_status_t error, const char *ifname);
+// PAN callbacks
 void pan_connection_state_changed(btpan_connection_state_t state, bt_status_t error, const bt_bdaddr_t *bd_addr, int local_role, int remote_role);
+void pan_control_state_changed(btpan_control_state_t state, int local_role, bt_status_t error, const char *ifname);
 
-static void remote_device_properties(bt_status_t status,
-                                     bt_bdaddr_t *bd_addr,
-                                     int num_properties,
-                                     bt_property_t *properties) {
-  CALLBACK_RET();
-}
+// GATT client callbacks
+void btgattc_register_app_cb(int status, int clientIf, bt_uuid_t *app_uuid);
+void btgattc_scan_result_cb(bt_bdaddr_t* bda, int rssi, uint8_t* adv_data);
+void btgattc_open_cb(int conn_id, int status, int clientIf, bt_bdaddr_t* bda);
+void btgattc_close_cb(int conn_id, int status, int clientIf, bt_bdaddr_t* bda);
+void btgattc_search_complete_cb(int conn_id, int status);
+void btgattc_search_result_cb(int conn_id, btgatt_srvc_id_t *srvc_id);
+void btgattc_get_characteristic_cb(int conn_id, int status, btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, int char_prop);
+void btgattc_get_descriptor_cb(int conn_id, int status, btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, btgatt_gatt_id_t *descr_id);
+void btgattc_get_included_service_cb(int conn_id, int status, btgatt_srvc_id_t *srvc_id, btgatt_srvc_id_t *incl_srvc_id);
+void btgattc_register_for_notification_cb(int conn_id, int registered, int status, btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id);
+void btgattc_notify_cb(int conn_id, btgatt_notify_params_t *p_data);
+void btgattc_read_characteristic_cb(int conn_id, int status, btgatt_read_params_t *p_data);
+void btgattc_write_characteristic_cb(int conn_id, int status, btgatt_write_params_t *p_data);
+void btgattc_execute_write_cb(int conn_id, int status);
+void btgattc_read_descriptor_cb(int conn_id, int status, btgatt_read_params_t *p_data);
+void btgattc_write_descriptor_cb(int conn_id, int status, btgatt_write_params_t *p_data);
+void btgattc_remote_rssi_cb(int client_if,bt_bdaddr_t* bda, int rssi, int status);
+void btgattc_advertise_cb(int status, int client_if);
 
-static void thread_evt(bt_cb_thread_evt evt) {
-  CALLBACK_RET();
-}
+// GATT server callbacks
+void btgatts_register_app_cb(int status, int server_if, bt_uuid_t *uuid);
+void btgatts_connection_cb(int conn_id, int server_if, int connected, bt_bdaddr_t *bda);
+void btgatts_service_added_cb(int status, int server_if, btgatt_srvc_id_t *srvc_id, int srvc_handle);
+void btgatts_included_service_added_cb(int status, int server_if, int srvc_handle, int incl_srvc_handle);
+void btgatts_characteristic_added_cb(int status, int server_if, bt_uuid_t *char_id, int srvc_handle, int char_handle);
+void btgatts_descriptor_added_cb(int status, int server_if, bt_uuid_t *descr_id, int srvc_handle, int descr_handle);
+void btgatts_service_started_cb(int status, int server_if, int srvc_handle);
+void btgatts_service_stopped_cb(int status, int server_if, int srvc_handle);
+void btgatts_service_deleted_cb(int status, int server_if, int srvc_handle);
+void btgatts_request_read_cb(int conn_id, int trans_id, bt_bdaddr_t *bda, int attr_handle, int offset, bool is_long);
+void btgatts_request_write_cb(int conn_id, int trans_id, bt_bdaddr_t *bda, int attr_handle, int offset, int length, bool need_rsp, bool is_prep, uint8_t* value);
+void btgatts_request_exec_write_cb(int conn_id, int trans_id, bt_bdaddr_t *bda, int exec_write);
+void btgatts_response_confirmation_cb(int status, int handle);
 
 static struct {
   const char *name;
@@ -47,12 +78,12 @@
   { "adapter_state_changed" },
   { "adapter_properties" },
   { "remote_device_properties" },
-  {},
+  { "device_found" },
   { "discovery_state_changed" },
   {},
-  {},
-  {},
-  {},
+  { "ssp_request" },
+  { "bond_state_changed" },
+  { "acl_state_changed" },
   { "thread_evt" },
   {},
   {},
@@ -60,6 +91,48 @@
   // PAN callbacks
   { "pan_control_state_changed" },
   { "pan_connection_state_changed" },
+
+  // GATT client callbacks
+  { "btgattc_register_app_cb" },
+  { "btgattc_scan_result_cb" },
+  { "btgattc_open_cb" },
+  { "btgattc_close_cb" },
+  { "btgattc_search_complete_cb" },
+  { "btgattc_search_result_cb" },
+  { "btgattc_get_characteristic_cb" },
+  { "btgattc_get_descriptor_cb" },
+  { "btgattc_get_included_service_cb" },
+  { "btgattc_register_for_notification_cb" },
+  { "btgattc_notify_cb" },
+  { "btgattc_read_characteristic_cb" },
+  { "btgattc_write_characteristic_cb" },
+  { "btgattc_execute_write_cb" },
+  { "btgattc_read_descriptor_cb" },
+  { "btgattc_write_descriptor_cb" },
+  { "btgattc_remote_rssi_cb" },
+  { "btgattc_advertise_cb" },
+  {},
+  {},
+  {},
+  {},
+  {},
+  {},
+
+  // GATT server callbacks
+  { "btgatts_register_app_cb" },
+  { "btgatts_connection_cb" },
+  { "btgatts_service_added_cb" },
+  { "btgatts_included_service_added_cb" },
+  { "btgatts_characteristic_added_cb" },
+  { "btgatts_descriptor_added_cb" },
+  { "btgatts_service_started_cb" },
+  { "btgatts_service_stopped_cb" },
+  { "btgatts_service_deleted_cb" },
+  { "btgatts_request_read_cb" },
+  { "btgatts_request_write_cb" },
+  { "btgatts_request_exec_write_cb" },
+  { "btgatts_response_confirmation_cb" },
+
 };
 
 static bt_callbacks_t bt_callbacks = {
@@ -67,12 +140,12 @@
   adapter_state_changed,     // adapter_state_changed_callback
   adapter_properties,        // adapter_properties_callback
   remote_device_properties,  // remote_device_properties_callback
-  NULL,                      // device_found_callback
+  device_found,              // device_found_callback
   discovery_state_changed,   // discovery_state_changed_callback
   NULL,                      // pin_request_callback
-  NULL,                      // ssp_request_callback
-  NULL,                      // bond_state_changed_callback
-  NULL,                      // acl_state_changed_callback
+  ssp_request,               // ssp_request_callback
+  bond_state_changed,        // bond_state_changed_callback
+  acl_state_changed,         // acl_state_changed_callback
   thread_evt,                // callback_thread_event
   NULL,                      // dut_mode_recv_callback
   NULL,                      // le_test_mode_callback
@@ -85,6 +158,55 @@
   pan_connection_state_changed,  // btpan_connection_state_callback
 };
 
+static const btgatt_client_callbacks_t gatt_client_callbacks = {
+  btgattc_register_app_cb,
+  btgattc_scan_result_cb,
+  btgattc_open_cb,
+  btgattc_close_cb,
+  btgattc_search_complete_cb,
+  btgattc_search_result_cb,
+  btgattc_get_characteristic_cb,
+  btgattc_get_descriptor_cb,
+  btgattc_get_included_service_cb,
+  btgattc_register_for_notification_cb,
+  btgattc_notify_cb,
+  btgattc_read_characteristic_cb,
+  btgattc_write_characteristic_cb,
+  btgattc_read_descriptor_cb,
+  btgattc_write_descriptor_cb,
+  btgattc_execute_write_cb,
+  btgattc_remote_rssi_cb,
+  btgattc_advertise_cb,
+  NULL,
+  NULL,
+  NULL,
+  NULL,
+  NULL,
+  NULL,
+};
+
+static const btgatt_server_callbacks_t gatt_server_callbacks = {
+  btgatts_register_app_cb,
+  btgatts_connection_cb,
+  btgatts_service_added_cb,
+  btgatts_included_service_added_cb,
+  btgatts_characteristic_added_cb,
+  btgatts_descriptor_added_cb,
+  btgatts_service_started_cb,
+  btgatts_service_stopped_cb,
+  btgatts_service_deleted_cb,
+  btgatts_request_read_cb,
+  btgatts_request_write_cb,
+  btgatts_request_exec_write_cb,
+  btgatts_response_confirmation_cb
+};
+
+static btgatt_callbacks_t gatt_callbacks = {
+  sizeof(btgatt_callbacks_t),
+  &gatt_client_callbacks,
+  &gatt_server_callbacks
+};
+
 void callbacks_init() {
   for (size_t i = 0; i < ARRAY_SIZE(callback_data); ++i) {
     sem_init(&callback_data[i].semaphore, 0, 0);
@@ -105,6 +227,10 @@
   return &pan_callbacks;
 }
 
+btgatt_callbacks_t *callbacks_get_gatt_struct() {
+  return &gatt_callbacks;
+}
+
 sem_t *callbacks_get_semaphore(const char *name) {
   for (size_t i = 0; i < ARRAY_SIZE(callback_data); ++i) {
     if (callback_data[i].name && !strcmp(name, callback_data[i].name)) {
diff --git a/test/suite/support/callbacks.h b/test/suite/support/callbacks.h
index 102e13f..e01de39 100644
--- a/test/suite/support/callbacks.h
+++ b/test/suite/support/callbacks.h
@@ -49,4 +49,5 @@
 
 bt_callbacks_t *callbacks_get_adapter_struct();
 btpan_callbacks_t *callbacks_get_pan_struct();
+btgatt_callbacks_t *callbacks_get_gatt_struct();
 sem_t *callbacks_get_semaphore(const char *name);
diff --git a/test/suite/support/gatt.c b/test/suite/support/gatt.c
new file mode 100644
index 0000000..9896afd
--- /dev/null
+++ b/test/suite/support/gatt.c
@@ -0,0 +1,230 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include "base.h"
+#include "btcore/include/bdaddr.h"
+#include "support/callbacks.h"
+#include "support/gatt.h"
+
+const btgatt_interface_t *gatt_interface;
+static bt_bdaddr_t remote_bd_addr;
+static int gatt_client_interface;
+static int gatt_server_interface;
+static int gatt_service_handle;
+static int gatt_included_service_handle;
+static int gatt_characteristic_handle;
+static int gatt_descriptor_handle;
+static int gatt_connection_id;
+static int gatt_status;
+
+bool gatt_init() {
+  gatt_interface = bt_interface->get_profile_interface(BT_PROFILE_GATT_ID);
+  return gatt_interface->init(callbacks_get_gatt_struct()) == BT_STATUS_SUCCESS;
+}
+
+int gatt_get_connection_id() {
+  return gatt_connection_id;
+}
+
+int gatt_get_client_interface() {
+  return gatt_client_interface;
+}
+
+int gatt_get_server_interface() {
+  return gatt_server_interface;
+}
+
+int gatt_get_service_handle() {
+  return gatt_service_handle;
+}
+
+int gatt_get_included_service_handle() {
+  return gatt_included_service_handle;
+}
+
+int gatt_get_characteristic_handle() {
+  return gatt_characteristic_handle;
+}
+
+int gatt_get_descriptor_handle() {
+  return gatt_descriptor_handle;
+}
+
+int gatt_get_status() {
+  return gatt_status;
+}
+
+// GATT client callbacks
+void btgattc_register_app_cb(int status, int clientIf, bt_uuid_t *app_uuid) {
+  gatt_status = status;
+  gatt_client_interface = clientIf;
+  CALLBACK_RET();
+}
+
+void btgattc_scan_result_cb(bt_bdaddr_t* bda, int rssi, uint8_t* adv_data) {
+  CALLBACK_RET();
+}
+
+void btgattc_open_cb(int conn_id, int status, int clientIf, bt_bdaddr_t* bda) {
+  CALLBACK_RET();
+}
+
+void btgattc_close_cb(int conn_id, int status, int clientIf, bt_bdaddr_t* bda) {
+  CALLBACK_RET();
+}
+
+void btgattc_search_complete_cb(int conn_id, int status) {
+  CALLBACK_RET();
+}
+
+void btgattc_search_result_cb(int conn_id, btgatt_srvc_id_t *srvc_id) {
+  CALLBACK_RET();
+}
+
+void btgattc_get_characteristic_cb(int conn_id, int status, btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, int char_prop) {
+  CALLBACK_RET();
+}
+
+void btgattc_get_descriptor_cb(int conn_id, int status, btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, btgatt_gatt_id_t *descr_id) {
+  CALLBACK_RET();
+}
+
+void btgattc_get_included_service_cb(int conn_id, int status, btgatt_srvc_id_t *srvc_id, btgatt_srvc_id_t *incl_srvc_id) {
+  CALLBACK_RET();
+}
+
+void btgattc_register_for_notification_cb(int conn_id, int registered, int status, btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id) {
+  CALLBACK_RET();
+}
+
+void btgattc_notify_cb(int conn_id, btgatt_notify_params_t *p_data) {
+  CALLBACK_RET();
+}
+
+void btgattc_read_characteristic_cb(int conn_id, int status, btgatt_read_params_t *p_data) {
+  CALLBACK_RET();
+}
+
+void btgattc_write_characteristic_cb(int conn_id, int status, btgatt_write_params_t *p_data) {
+  CALLBACK_RET();
+}
+
+void btgattc_execute_write_cb(int conn_id, int status) {
+  CALLBACK_RET();
+}
+
+void btgattc_read_descriptor_cb(int conn_id, int status, btgatt_read_params_t *p_data) {
+  CALLBACK_RET();
+}
+
+void btgattc_write_descriptor_cb(int conn_id, int status, btgatt_write_params_t *p_data) {
+  CALLBACK_RET();
+}
+
+void btgattc_remote_rssi_cb(int client_if,bt_bdaddr_t* bda, int rssi, int status) {
+  CALLBACK_RET();
+}
+
+void btgattc_advertise_cb(int status, int client_if) {
+  gatt_status = status;
+  gatt_client_interface = client_if;
+  CALLBACK_RET();
+}
+
+// GATT server callbacks
+void btgatts_register_app_cb(int status, int server_if, bt_uuid_t *uuid) {
+  gatt_status = status;
+  gatt_server_interface = server_if;
+  CALLBACK_RET();
+}
+
+void btgatts_connection_cb(int conn_id, int server_if, int connected, bt_bdaddr_t *bda) {
+  gatt_connection_id = conn_id;
+  for (int i = 0; i < 6; ++i) {
+    remote_bd_addr.address[i] = bda->address[i];
+  }
+  CALLBACK_RET();
+}
+
+void btgatts_service_added_cb(int status, int server_if, btgatt_srvc_id_t *srvc_id, int srvc_handle) {
+  gatt_status = status;
+  gatt_server_interface = server_if;
+  gatt_service_handle = srvc_handle;
+  CALLBACK_RET();
+}
+
+void btgatts_included_service_added_cb(int status, int server_if, int srvc_handle, int incl_srvc_handle) {
+  gatt_status = status;
+  gatt_server_interface = server_if;
+  gatt_service_handle = srvc_handle;
+  gatt_included_service_handle = incl_srvc_handle;
+  CALLBACK_RET();
+}
+
+void btgatts_characteristic_added_cb(int status, int server_if, bt_uuid_t *char_id, int srvc_handle, int char_handle) {
+  gatt_status = status;
+  gatt_server_interface = server_if;
+  gatt_service_handle = srvc_handle;
+  gatt_characteristic_handle = char_handle;
+  CALLBACK_RET();
+}
+
+void btgatts_descriptor_added_cb(int status, int server_if, bt_uuid_t *descr_id, int srvc_handle, int descr_handle) {
+  gatt_status = status;
+  gatt_server_interface = server_if;
+  gatt_service_handle = srvc_handle;
+  gatt_descriptor_handle = descr_handle;
+  CALLBACK_RET();
+}
+
+void btgatts_service_started_cb(int status, int server_if, int srvc_handle) {
+  gatt_status = status;
+  gatt_server_interface = server_if;
+  gatt_service_handle = srvc_handle;
+  CALLBACK_RET();
+}
+
+void btgatts_service_stopped_cb(int status, int server_if, int srvc_handle) {
+  gatt_status = status;
+  gatt_server_interface = server_if;
+  gatt_service_handle = srvc_handle;
+  CALLBACK_RET();
+}
+
+void btgatts_service_deleted_cb(int status, int server_if, int srvc_handle) {
+  gatt_status = status;
+  gatt_server_interface = server_if;
+  gatt_service_handle = srvc_handle;
+  CALLBACK_RET();
+}
+
+void btgatts_request_read_cb(int conn_id, int trans_id, bt_bdaddr_t *bda, int attr_handle, int offset, bool is_long) {
+  CALLBACK_RET();
+}
+
+void btgatts_request_write_cb(int conn_id, int trans_id, bt_bdaddr_t *bda, int attr_handle, int offset, int length, bool need_rsp, bool is_prep, uint8_t* value) {
+  CALLBACK_RET();
+}
+
+void btgatts_request_exec_write_cb(int conn_id, int trans_id, bt_bdaddr_t *bda, int exec_write) {
+  CALLBACK_RET();
+}
+
+void btgatts_response_confirmation_cb(int status, int handle) {
+  CALLBACK_RET();
+}
\ No newline at end of file
diff --git a/test/suite/support/property.h b/test/suite/support/gatt.h
similarity index 63%
copy from test/suite/support/property.h
copy to test/suite/support/gatt.h
index a8b77c7..d438cdf 100644
--- a/test/suite/support/property.h
+++ b/test/suite/support/gatt.h
@@ -20,13 +20,14 @@
 
 #include "base.h"
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+extern const btgatt_interface_t *gatt_interface;
 
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+bool gatt_init();
+int gatt_get_connection_id();
+int gatt_get_client_interface();
+int gatt_get_server_interface();
+int gatt_get_service_handle();
+int gatt_get_included_service_handle();
+int gatt_get_characteristic_handle();
+int gatt_get_descriptor_handle();
+int gatt_get_status();
diff --git a/test/suite/support/hal.c b/test/suite/support/hal.c
index ff4952c..3ebcf74 100644
--- a/test/suite/support/hal.c
+++ b/test/suite/support/hal.c
@@ -21,6 +21,10 @@
 
 #include "base.h"
 #include "support/hal.h"
+#include "osi/include/hash_functions.h"
+#include "osi/include/hash_map.h"
+
+#define TIMER_BUCKET_COUNT 4
 
 static bool set_wake_alarm(uint64_t delay_millis, bool should_wake, alarm_cb cb, void *data);
 static int acquire_wake_lock(const char *lock_name);
@@ -72,17 +76,23 @@
 }
 
 static bool set_wake_alarm(uint64_t delay_millis, bool should_wake, alarm_cb cb, void *data) {
-  static timer_t timer;
-  static bool timer_created;
+  static hash_map_t *timers;
 
-  if (!timer_created) {
+  if (!timers) {
+    timers = hash_map_new(TIMER_BUCKET_COUNT, hash_function_pointer, NULL, NULL, NULL);
+  }
+
+  timer_t *timer = hash_map_get(timers, cb);
+  if (!timer) {
+    timer = malloc(sizeof(timer_t));
+    hash_map_set(timers, cb, timer);
+
     struct sigevent sigevent;
     memset(&sigevent, 0, sizeof(sigevent));
     sigevent.sigev_notify = SIGEV_THREAD;
     sigevent.sigev_notify_function = (void (*)(union sigval))cb;
     sigevent.sigev_value.sival_ptr = data;
-    timer_create(CLOCK_MONOTONIC, &sigevent, &timer);
-    timer_created = true;
+    timer_create(CLOCK_MONOTONIC, &sigevent, timer);
   }
 
   struct itimerspec new_value;
@@ -90,7 +100,7 @@
   new_value.it_value.tv_nsec = (delay_millis % 1000) * 1000 * 1000;
   new_value.it_interval.tv_sec = 0;
   new_value.it_interval.tv_nsec = 0;
-  timer_settime(timer, 0, &new_value, NULL);
+  timer_settime(*timer, 0, &new_value, NULL);
 
   return true;
 }
diff --git a/test/suite/support/property.c b/test/suite/support/property.c
deleted file mode 100644
index ea2c5c4..0000000
--- a/test/suite/support/property.c
+++ /dev/null
@@ -1,113 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 Google, Inc.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-#include "base.h"
-#include "support/property.h"
-
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count) {
-  bt_property_t *clone = calloc(sizeof(bt_property_t), count);
-  if (!clone) {
-    return NULL;
-  }
-
-  memcpy(&clone[0], &properties[0], sizeof(bt_property_t) * count);
-  for (size_t i = 0; i < count; ++i) {
-    clone[i].val = calloc(clone[i].len, 1);
-    memcpy(clone[i].val, properties[i].val, clone[i].len);
-  }
-
-  return clone;
-}
-
-bt_property_t *property_new_name(const char *name) {
-  bt_bdname_t *bdname = calloc(sizeof(bt_bdname_t), 1);
-  bt_property_t *property = calloc(sizeof(bt_property_t), 1);
-
-  property->type = BT_PROPERTY_BDNAME;
-  property->val = bdname;
-  property->len = sizeof(bt_bdname_t);
-
-  strlcpy((char *)bdname->name, name, sizeof(bdname->name));
-
-  return property;
-}
-
-bt_property_t *property_new_discovery_timeout(uint32_t timeout) {
-  uint32_t *val = malloc(sizeof(uint32_t));
-  bt_property_t *property = malloc(sizeof(bt_property_t));
-
-  property->type = BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT;
-  property->val = val;
-  property->len = sizeof(uint32_t);
-
-  *val = timeout;
-
-  return property;
-}
-
-// Warning: not thread safe.
-const char *property_extract_name(const bt_property_t *property) {
-  static char name[250] = { 0 };
-  if (!property || property->type != BT_PROPERTY_BDNAME || !property->val) {
-    return NULL;
-  }
-
-  strncpy(name, (const char *)((bt_bdname_t *)property->val)->name, property->len);
-  name[sizeof(name) - 1] = '\0';
-
-  return name;
-}
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2) {
-  // Two null properties are not the same. May need to revisit that
-  // decision when we have a test case that exercises that condition.
-  if (!p1 || !p2 || p1->type != p2->type) {
-    return false;
-  }
-
-  // Although the Bluetooth name is a 249-byte array, the implementation
-  // treats it like a variable-length array with its size specified in the
-  // property's `len` field. We special-case the equivalence of BDNAME
-  // types here by truncating the larger, zero-padded name to its string
-  // length and comparing against the shorter name.
-  //
-  // Note: it may be the case that both strings are zero-padded but that
-  // hasn't come up yet so this implementation doesn't handle it.
-  if (p1->type == BT_PROPERTY_BDNAME && p1->len != p2->len) {
-    const bt_property_t *shorter = p1, *longer = p2;
-    if (p1->len > p2->len) {
-      shorter = p2;
-      longer = p1;
-    }
-    return strlen((const char *)longer->val) == (size_t)shorter->len && !memcmp(longer->val, shorter->val, shorter->len);
-  }
-
-  return p1->len == p2->len && !memcmp(p1->val, p2->val, p1->len);
-}
-
-void property_free(bt_property_t *property) {
-  property_free_array(property, 1);
-}
-
-void property_free_array(bt_property_t *properties, size_t count) {
-  for (size_t i = 0; i < count; ++i) {
-    free(properties[i].val);
-  }
-
-  free(properties);
-}
diff --git a/test/suite/support/property.h b/test/suite/support/rfcomm.c
similarity index 62%
copy from test/suite/support/property.h
copy to test/suite/support/rfcomm.c
index a8b77c7..8bb8b4d 100644
--- a/test/suite/support/property.h
+++ b/test/suite/support/rfcomm.c
@@ -16,17 +16,13 @@
  *
  ******************************************************************************/
 
-#pragma once
-
 #include "base.h"
+#include "support/callbacks.h"
+#include "support/rfcomm.h"
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+const btsock_interface_t *socket_interface;
 
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+bool btsocket_init(void) {
+  socket_interface = bt_interface->get_profile_interface(BT_PROFILE_SOCKETS_ID);
+  return socket_interface != NULL;
+}
diff --git a/test/suite/support/property.h b/test/suite/support/rfcomm.h
similarity index 63%
rename from test/suite/support/property.h
rename to test/suite/support/rfcomm.h
index a8b77c7..6b861d1 100644
--- a/test/suite/support/property.h
+++ b/test/suite/support/rfcomm.h
@@ -20,13 +20,6 @@
 
 #include "base.h"
 
-bt_property_t *property_copy_array(const bt_property_t *properties, size_t count);
-bt_property_t *property_new_name(const char *name);
-bt_property_t *property_new_discovery_timeout(uint32_t timeout);
+extern const btsock_interface_t *socket_interface;
 
-const char *property_extract_name(const bt_property_t *property);
-
-bool property_equals(const bt_property_t *p1, const bt_property_t *p2);
-
-void property_free(bt_property_t *property);
-void property_free_array(bt_property_t *properties, size_t count);
+bool btsocket_init(void);
diff --git a/tools/Android.mk b/tools/Android.mk
new file mode 100644
index 0000000..5053e7d
--- /dev/null
+++ b/tools/Android.mk
@@ -0,0 +1 @@
+include $(call all-subdir-makefiles)
diff --git a/tools/bdtool/Android.mk b/tools/bdtool/Android.mk
new file mode 100644
index 0000000..345f037
--- /dev/null
+++ b/tools/bdtool/Android.mk
@@ -0,0 +1,44 @@
+#
+# Copyright (C) 2014 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE := net_bdtool
+
+LOCAL_SRC_FILES := \
+  adapter.c \
+  bdtool.c \
+  ../../test/suite/support/callbacks.c \
+  ../../test/suite/support/hal.c \
+  ../../test/suite/support/pan.c
+
+LOCAL_STATIC_LIBRARIES := \
+  libbtcore \
+  libosi
+
+LOCAL_CFLAGS := -std=c99 $(bdroid_CFLAGS) -Wno-unused-parameter -Wno-missing-field-initializers
+
+LOCAL_C_INCLUDES := \
+  $(LOCAL_PATH)/../../test/suite \
+  $(LOCAL_PATH)/../..
+
+LOCAL_SHARED_LIBRARIES += \
+  libhardware
+
+include $(BUILD_EXECUTABLE)
diff --git a/tools/bdtool/adapter.c b/tools/bdtool/adapter.c
new file mode 100644
index 0000000..cd49167
--- /dev/null
+++ b/tools/bdtool/adapter.c
@@ -0,0 +1,306 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include "base.h"
+#include "btcore/include/bdaddr.h"
+#include "btcore/include/property.h"
+#include "support/adapter.h"
+#include "support/callbacks.h"
+
+static bt_state_t state;
+static int property_count = 0;
+static bt_property_t *properties = NULL;
+static bt_discovery_state_t discovery_state;
+static bt_acl_state_t acl_state;
+static bt_bond_state_t bond_state;
+
+static void parse_properties(int num_properties, bt_property_t *property);
+
+// Returns the current adapter state.
+bt_state_t adapter_get_state() {
+  return state;
+}
+
+// Returns the number of adapter properties.
+int adapter_get_property_count() {
+  return property_count;
+}
+
+// Returns the specified property.
+bt_property_t *adapter_get_property(bt_property_type_t type) {
+  for (int i = 0; i < property_count; ++i) {
+    if (properties[i].type == type) {
+      return &properties[i];
+    }
+  }
+
+  return NULL;
+}
+
+// Returns the device discovery state.
+bt_discovery_state_t adapter_get_discovery_state() {
+  return discovery_state;
+}
+
+// Returns the device acl state.
+bt_acl_state_t adapter_get_acl_state() {
+  return acl_state;
+}
+
+// Returns the device bond state.
+bt_bond_state_t adapter_get_bond_state() {
+  return bond_state;
+}
+
+// callback
+void acl_state_changed(bt_status_t status, bt_bdaddr_t *remote_bd_addr, bt_acl_state_t state) {
+  acl_state = state;
+  CALLBACK_RET();
+}
+
+// callback
+void adapter_properties(bt_status_t status,
+    int num_properties,
+    bt_property_t *new_properties) {
+  property_free_array(properties, property_count);
+  properties = property_copy_array(new_properties, num_properties);
+  property_count = num_properties;
+
+  CALLBACK_RET();
+}
+
+// callback
+void adapter_state_changed(bt_state_t new_state) {
+  state = new_state;
+  CALLBACK_RET();
+}
+
+// callback
+void bond_state_changed(bt_status_t status,
+    bt_bdaddr_t *bdaddr,
+    bt_bond_state_t state) {
+  char buf[18];
+  bond_state = state;
+
+  const char *state_name = "Bond state unknown";
+  switch (bond_state) {
+    case BT_BOND_STATE_NONE:
+      state_name = "Bond state none";
+      break;
+
+    case BT_BOND_STATE_BONDING:
+      state_name = "Bond state bonding";
+      break;
+
+    case BT_BOND_STATE_BONDED:
+      state_name = "Bond state bonded";
+      break;
+
+      // default none
+  }
+  fprintf(stdout, "Bond state changed callback addr:%s state:%s\n", bdaddr_to_string(bdaddr, buf, sizeof(buf)), state_name);
+
+  CALLBACK_RET();
+}
+
+// callback
+void device_found(int num_properties, bt_property_t *property) {
+  fprintf(stdout, "Device found num_properties:%d\n", num_properties);
+  parse_properties(num_properties, property);
+
+  CALLBACK_RET();
+}
+
+// callback
+void discovery_state_changed(bt_discovery_state_t state) {
+  const char *state_name = "Unknown";
+  discovery_state = state;
+
+  switch (discovery_state) {
+    case BT_DISCOVERY_STOPPED:
+      state_name = "Discovery stopped";
+      break;
+
+    case BT_DISCOVERY_STARTED:
+      state_name = "Discovery started";
+      break;
+
+      // default omitted
+  }
+  fprintf(stdout, "Discover state %s\n", state_name);
+
+  CALLBACK_RET();
+}
+
+// callback
+void remote_device_properties(bt_status_t status,
+    bt_bdaddr_t *bdaddr,
+    int num_properties,
+    bt_property_t *properties) {
+  char buf[18];
+  fprintf(stdout, "Device found bdaddr:%s num_properties:%d\n",
+      bdaddr_to_string(bdaddr, buf, sizeof(buf)), num_properties);
+
+  parse_properties(num_properties, properties);
+
+  CALLBACK_RET();
+}
+
+// callback
+void ssp_request(
+    bt_bdaddr_t *remote_bd_addr,
+    bt_bdname_t *bd_name,
+    uint32_t cod,
+    bt_ssp_variant_t pairing_variant,
+    uint32_t pass_key) {
+  char *pairing_variant_name = "Unknown";
+
+  switch (pairing_variant) {
+    case BT_SSP_VARIANT_PASSKEY_CONFIRMATION:
+      pairing_variant_name = "Passkey confirmation";
+      break;
+    case BT_SSP_VARIANT_PASSKEY_ENTRY:
+      pairing_variant_name = "Passkey entry";
+      break;
+
+    case BT_SSP_VARIANT_CONSENT:
+      pairing_variant_name = "Passkey consent";
+      break;
+
+    case BT_SSP_VARIANT_PASSKEY_NOTIFICATION:
+      pairing_variant_name = "Passkey notification";
+      break;
+  }
+
+  fprintf(stdout, "Got ssp request device_class:%u passkey:%x pairing_variant:%s\n", cod, pass_key, pairing_variant_name);
+  char buf[18];
+  fprintf(stdout, "Device found:%s %s\n", bdaddr_to_string(remote_bd_addr, buf, sizeof(buf)), bd_name->name);
+
+
+  fprintf(stdout, "auto-accepting bond\n");
+  bool accept = true;
+  int rc = bt_interface->ssp_reply(remote_bd_addr, pairing_variant,
+      (uint8_t)accept, pass_key);
+  CALLBACK_RET();
+}
+
+// callback
+void thread_evt(bt_cb_thread_evt evt) {
+  CALLBACK_RET();
+}
+
+static void parse_properties(int num_properties, bt_property_t *property) {
+  while (num_properties-- > 0) {
+    switch(property->type) {
+      case BT_PROPERTY_BDNAME:
+        {
+          const bt_bdname_t *name = property_as_name(property);
+          if (name)
+            fprintf(stdout, " name:%s\n", name->name);
+        }
+        break;
+
+      case BT_PROPERTY_BDADDR:
+        {
+          char buf[18];
+          const bt_bdaddr_t *addr = property_as_addr(property);
+          if (addr)
+            fprintf(stdout, " addr:%s\n", bdaddr_to_string(addr, buf, sizeof(buf)));
+        }
+        break;
+
+      case BT_PROPERTY_UUIDS:
+        {
+          size_t num_uuid;
+          const bt_uuid_t *uuid = property_as_uuids(property, &num_uuid);
+          if (uuid) {
+            for (size_t i = 0; i < num_uuid; i++) {
+              fprintf(stdout, " uuid:%d: ", i);
+              for (size_t j = 0; j < sizeof(uuid); j++) {
+                fprintf(stdout, "%02x", uuid->uu[j]);
+              }
+              fprintf(stdout, "\n");
+            }
+          }
+        }
+        break;
+
+      case BT_PROPERTY_TYPE_OF_DEVICE:
+        {
+          bt_device_type_t device_type = property_as_device_type(property);
+          if (device_type) {
+            const struct {
+              const char * device_type;
+            } device_type_lookup[] = {
+              { "Unknown" },
+              { "Classic Only" },
+              { "BLE Only" },
+              { "Both Classic and BLE" },
+            };
+            int idx = (int)device_type;
+            if (idx > BT_DEVICE_DEVTYPE_DUAL)
+              idx = 0;
+            fprintf(stdout, " device_type:%s\n", device_type_lookup[idx].device_type);
+          }
+        }
+        break;
+
+      case BT_PROPERTY_CLASS_OF_DEVICE:
+        {
+          const bt_device_class_t *dc = property_as_device_class(property);
+          int dc_int = device_class_to_int(dc);
+          fprintf(stdout, " device_class:0x%x\n", dc_int);
+        }
+        break;
+
+      case BT_PROPERTY_REMOTE_RSSI:
+        {
+          int8_t rssi = property_as_rssi(property);
+          fprintf(stdout, " rssi:%d\n", rssi);
+        }
+        break;
+
+      case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
+        {
+          const bt_bdname_t *name = property_as_name(property);
+          if (name)
+            fprintf(stdout, " remote_name:%s\n", name->name);
+        }
+        break;
+
+      case BT_PROPERTY_SERVICE_RECORD:
+      case BT_PROPERTY_ADAPTER_SCAN_MODE:
+      case BT_PROPERTY_ADAPTER_BONDED_DEVICES:
+      case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
+      case BT_PROPERTY_REMOTE_VERSION_INFO:
+      case BT_PROPERTY_LOCAL_LE_FEATURES:
+      case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
+      default:
+        {
+          fprintf(stderr, "Unhandled property type:%d len:%d\n", property->type, property->len);
+          uint8_t *p = (uint8_t *)property->val;
+          for (int i = 0; i < property->len; ++i, p++) {
+            fprintf(stderr, " %02x", *p);
+          }
+          if (property->len != 0)
+            fprintf(stderr, "\n");
+        }
+    }
+    property++;
+  }
+}
diff --git a/tools/bdtool/bdtool.c b/tools/bdtool/bdtool.c
new file mode 100644
index 0000000..d0d0cc7
--- /dev/null
+++ b/tools/bdtool/bdtool.c
@@ -0,0 +1,334 @@
+/******************************************************************************
+ *
+ *  Copyright (C) 2014 Google, Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at:
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ ******************************************************************************/
+
+#include <getopt.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "btcore/include/bdaddr.h"
+#include "btcore/include/property.h"
+#include "osi/include/osi.h"
+#include "test/suite/support/callbacks.h"
+#include "test/suite/support/hal.h"
+
+static const bt_uuid_t HFP_UUID = {{ 0x00, 0x00, 0x11, 0x1E, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB }};
+static const bt_uuid_t HFP_AG_UUID = {{ 0x00, 0x00, 0x11, 0x1F, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB }};
+
+const bt_interface_t *bt_interface;
+
+bt_bdaddr_t bt_remote_bdaddr;
+
+static int f_verbose;
+static bool discover = false;
+static bool discoverable = false;
+static bool bond = false;
+static bool up = false;
+static bool get_name = false;
+static bool set_name = false;
+static bool sco_listen = false;
+static bool sco_connect = false;
+
+static int timeout_in_sec = 30;
+static char *bd_name;
+
+static struct option long_options[] = {
+  {"bdaddr", required_argument, 0, 0 },
+  {"discover", no_argument, 0, 0 },
+  {"discoverable", no_argument, 0, 0 },
+  {"time", required_argument, 0, 0 },
+  {"bond", no_argument, 0, 0 },
+  {"up", no_argument, 0, 0 },
+  {"verbose", no_argument, 0, 0 },
+  {"get_name", no_argument, 0, 0 },
+  {"set_name", required_argument, 0, 0 },
+  {"sco_listen", no_argument, 0, 0 },
+  {"sco_connect", no_argument, 0, 0 },
+  {0, 0, 0, 0 }
+};
+
+static void usage(const char *name);
+static bool parse_args(int argc, char **argv);
+static void sig_handler(int signo);
+
+bt_property_t *adapter_get_property(bt_property_type_t type);
+
+int main(int argc, char **argv) {
+  if (!parse_args(argc, argv)) {
+    usage(argv[0]);
+  }
+
+  if (bond && discoverable) {
+    fprintf(stderr, "Can only select either bond or discoverable, not both\n");
+    usage(argv[0]);
+  }
+
+  if (sco_listen && sco_connect) {
+    fprintf(stderr, "Can only select either sco_listen or sco_connect, not both\n");
+    usage(argv[0]);
+  }
+
+  if (!bond && !discover && !discoverable && !up && !get_name && !set_name && !sco_listen && !sco_connect) {
+    fprintf(stderr, "Must specify one command\n");
+    usage(argv[0]);
+  }
+
+  if (signal(SIGINT, sig_handler) == SIG_ERR) {
+    fprintf(stderr, "Will be unable to catch signals\n");
+  }
+
+  fprintf(stdout, "Bringing up bluetooth adapter\n");
+  if (!hal_open(callbacks_get_adapter_struct())) {
+    fprintf(stderr, "Unable to open Bluetooth HAL.\n");
+    return 1;
+  }
+
+  if (discover) {
+    CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
+    fprintf(stdout, "BT adapter is up\n");
+
+    fprintf(stdout, "Starting to start discovery\n");
+    CALL_AND_WAIT(bt_interface->start_discovery(), discovery_state_changed);
+    fprintf(stdout, "Started discovery for %d seconds\n", timeout_in_sec);
+
+    sleep(timeout_in_sec);
+
+    fprintf(stdout, "Starting to cancel discovery\n");
+    CALL_AND_WAIT(bt_interface->cancel_discovery(), discovery_state_changed);
+    fprintf(stdout, "Cancelled discovery after %d seconds\n", timeout_in_sec);
+  }
+
+  if (discoverable) {
+    CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
+    fprintf(stdout, "BT adapter is up\n");
+
+    bt_property_t *property = property_new_scan_mode(BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE);
+
+    int rc = bt_interface->set_adapter_property(property);
+    fprintf(stdout, "Set rc:%d device as discoverable for %d seconds\n", rc, timeout_in_sec);
+
+    sleep(timeout_in_sec);
+
+    property_free(property);
+  }
+
+   if (bond) {
+    if (bdaddr_is_empty(&bt_remote_bdaddr)) {
+      fprintf(stderr, "Must specify a remote device address [ --bdaddr=xx:yy:zz:aa:bb:cc ]\n");
+      exit(1);
+    }
+
+    CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
+    fprintf(stdout, "BT adapter is up\n");
+
+    int rc = bt_interface->create_bond(&bt_remote_bdaddr, 0 /* UNKNOWN; Currently not documented :( */);
+    fprintf(stdout, "Started bonding:%d for %d seconds\n", rc, timeout_in_sec);
+
+    sleep(timeout_in_sec);
+  }
+
+  if (up) {
+    CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
+    fprintf(stdout, "BT adapter is up\n");
+
+    fprintf(stdout, "Waiting for %d seconds\n", timeout_in_sec);
+    sleep(timeout_in_sec);
+  }
+
+  if (get_name) {
+    CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
+    fprintf(stdout, "BT adapter is up\n");
+    int error;
+    CALL_AND_WAIT(error = bt_interface->get_adapter_property(BT_PROPERTY_BDNAME), adapter_properties);
+    if (error != BT_STATUS_SUCCESS) {
+      fprintf(stderr, "Unable to get adapter property\n");
+      exit(1);
+    }
+    bt_property_t *property = adapter_get_property(BT_PROPERTY_BDNAME);
+    const bt_bdname_t *name = property_as_name(property);
+    if (name)
+      printf("Queried bluetooth device name:%s\n", name->name);
+    else
+      printf("No name\n");
+  }
+
+  if (set_name) {
+    CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
+    fprintf(stdout, "BT adapter is up\n");
+
+    bt_property_t *property = property_new_name(bd_name);
+    printf("Setting bluetooth device name to:%s\n", bd_name);
+    int error;
+    CALL_AND_WAIT(error = bt_interface->set_adapter_property(property), adapter_properties);
+    if (error != BT_STATUS_SUCCESS) {
+      fprintf(stderr, "Unable to set adapter property\n");
+      exit(1);
+    }
+    CALL_AND_WAIT(error = bt_interface->get_adapter_property(BT_PROPERTY_BDNAME), adapter_properties);
+    if (error != BT_STATUS_SUCCESS) {
+      fprintf(stderr, "Unable to get adapter property\n");
+      exit(1);
+    }
+    property_free(property);
+    sleep(timeout_in_sec);
+  }
+
+  if (sco_listen) {
+    CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
+    fprintf(stdout, "BT adapter is up\n");
+
+    bt_property_t *property = property_new_scan_mode(BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE);
+    CALL_AND_WAIT(bt_interface->set_adapter_property(property), adapter_properties);
+    property_free(property);
+
+    const btsock_interface_t *sock = bt_interface->get_profile_interface(BT_PROFILE_SOCKETS_ID);
+
+    int rfcomm_fd = INVALID_FD;
+    int error = sock->listen(BTSOCK_RFCOMM, "meow", (const uint8_t *)&HFP_AG_UUID, 0, &rfcomm_fd, 0);
+    if (error != BT_STATUS_SUCCESS) {
+      fprintf(stderr, "Unable to listen for incoming RFCOMM socket: %d\n", error);
+      exit(1);
+    }
+
+    int sock_fd = INVALID_FD;
+    error = sock->listen(BTSOCK_SCO, NULL, NULL, 5, &sock_fd, 0);
+    if (error != BT_STATUS_SUCCESS) {
+      fprintf(stderr, "Unable to listen for incoming SCO sockets: %d\n", error);
+      exit(1);
+    }
+    fprintf(stdout, "Waiting for incoming SCO connections...\n");
+    sleep(timeout_in_sec);
+  }
+
+  if (sco_connect) {
+    if (bdaddr_is_empty(&bt_remote_bdaddr)) {
+      fprintf(stderr, "Must specify a remote device address [ --bdaddr=xx:yy:zz:aa:bb:cc ]\n");
+      exit(1);
+    }
+
+    CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
+    fprintf(stdout, "BT adapter is up\n");
+
+    const btsock_interface_t *sock = bt_interface->get_profile_interface(BT_PROFILE_SOCKETS_ID);
+
+    int rfcomm_fd = INVALID_FD;
+    int error = sock->connect(&bt_remote_bdaddr, BTSOCK_RFCOMM, (const uint8_t *)&HFP_AG_UUID, 0, &rfcomm_fd, 0);
+    if (error != BT_STATUS_SUCCESS) {
+      fprintf(stderr, "Unable to connect to RFCOMM socket: %d.\n", error);
+      exit(1);
+    }
+
+    WAIT(acl_state_changed);
+
+    fprintf(stdout, "Establishing SCO connection...\n");
+
+    int sock_fd = INVALID_FD;
+    error = sock->connect(&bt_remote_bdaddr, BTSOCK_SCO, NULL, 5, &sock_fd, 0);
+    if (error != BT_STATUS_SUCCESS) {
+      fprintf(stderr, "Unable to connect to SCO socket: %d.\n", error);
+      exit(1);
+    }
+    sleep(timeout_in_sec);
+  }
+
+  CALL_AND_WAIT(bt_interface->disable(), adapter_state_changed);
+  fprintf(stdout, "BT adapter is down\n");
+}
+
+static void sig_handler(int signo) {
+  if (signo == SIGINT) {
+    fprintf(stderr, "Received SIGINT\n");
+    CALL_AND_WAIT(bt_interface->disable(), adapter_state_changed);
+    fprintf(stderr, "BT adapter is down\n");
+    exit(1);
+  }
+}
+
+static void usage(const char *name) {
+  fprintf(stderr, "Usage: %s [--bond|--discover|--discoverable|--up|--sco_listen|--sco_connect] [--bdaddr=<bdaddr>] [--time=<time_in_sec>] --verbose\n", name);
+  fprintf(stderr, "     bond: Discover actively advertising devices\n");
+  fprintf(stderr, "     discover: Discover actively advertising devices\n");
+  fprintf(stderr, "     discoverable: Set into a connectable and discoverable mode\n");
+  fprintf(stderr, "     up: Only bring up stack\n");
+  fprintf(stderr, "     sco_listen: Listen for incoming SCO connections\n");
+  fprintf(stderr, "     sco_connect: Establish a SCO connection with another device\n");
+  fprintf(stderr, "     time: Time to hold in the specified mode\n");
+  exit(1);
+}
+
+static bool parse_args(int argc, char **argv) {
+  while (1) {
+    int option_index = 0;
+    int c = getopt_long_only(argc, argv, "", long_options, &option_index);
+    if (c != 0)
+      break;
+
+    switch (c) {
+      case 0:
+        if (option_index == 0) {
+          if (!string_to_bdaddr(optarg, &bt_remote_bdaddr)) {
+            return false;
+          }
+        }
+        if (option_index == 1) {
+          discover = true;
+        }
+        if (option_index == 2) {
+          discoverable = true;
+        }
+        if (option_index == 3) {
+          timeout_in_sec = atoi(optarg);
+        }
+        if (option_index == 4) {
+          bond  = true;
+        }
+        if (option_index == 5) {
+          up = true;
+        }
+        if (option_index == 6) {
+          f_verbose++;
+        }
+        if (option_index == 7) {
+          get_name = true;
+        }
+        if (option_index == 8) {
+          bd_name = (char *)optarg;
+          set_name = true;
+        }
+        if (option_index == 9) {
+          sco_listen = true;
+        }
+        if (option_index == 10) {
+          sco_connect = true;
+        }
+        break;
+
+      default:
+        fprintf(stderr, "?? getopt returned character code 0%o ??\n", c);
+    }
+  }
+
+  if (optind < argc) {
+    fprintf(stderr, "non-option ARGV-elements: ");
+    while (optind < argc)
+      fprintf(stderr, "%s ", argv[optind++]);
+    fprintf(stderr, "\n");
+    return false;
+  }
+  return true;
+}
diff --git a/tools/gen-buildcfg.sh b/tools/gen-buildcfg.sh
deleted file mode 100755
index a09cb20..0000000
--- a/tools/gen-buildcfg.sh
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/usr/bin/env bash
-
-if [[ "" == "$2" ]]
-then
-    echo "Usage: $0 <in-file> <out-file>"
-    exit 1
-fi
-
-if [ ! -f "$1" ]
-then
-    echo "Error: Can't find input file $1..."
-    exit 2
-fi
-
-DATE=`/usr/bin/env date`
-BASE=`basename $2`
-BASE=`echo ${BASE} | tr "[:lower:]" "[:upper:]"`
-BASE=`echo ${BASE} | sed -e "s/\\./_/"`
-PROTECT="_${BASE}"
-
-echo "/* Auto-generated from $1 on ${DATE} */" > $2
-echo "#ifndef ${PROTECT}" >> $2
-echo "#define ${PROTECT}" >> $2
-sed -e '/^#/d' -e '/^$$/d' -e '/# Makefile only$$/d' -e 's/^/#define /' -e 's/=/ /' $1 >> $2
-echo "#endif" >> $2
-
diff --git a/tools/hci/Android.mk b/tools/hci/Android.mk
new file mode 100644
index 0000000..9477db3
--- /dev/null
+++ b/tools/hci/Android.mk
@@ -0,0 +1,29 @@
+#
+# Copyright (C) 2014 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE := net_hci
+
+LOCAL_SRC_FILES := main.c
+LOCAL_STATIC_LIBRARIES := libosi
+LOCAL_CFLAGS := -std=c99 $(bdroid_CFLAGS)
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../
+
+include $(BUILD_EXECUTABLE)
diff --git a/tools/hci/main.c b/tools/hci/main.c
new file mode 100644
index 0000000..fc433bc
--- /dev/null
+++ b/tools/hci/main.c
@@ -0,0 +1,185 @@
+#include <hardware/bluetooth.h>
+#include <netinet/in.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "osi/include/osi.h"
+
+typedef int (*handler_t)(int argc, char **argv);
+
+typedef enum {
+  HCI_PACKET_COMMAND  = 1,
+  HCI_PACKET_ACL_DATA = 2,
+  HCI_PACKET_SCO_DATA = 3,
+  HCI_PACKET_EVENT    = 4,
+} hci_packet_t;
+
+typedef struct {
+  const char *name;
+  const char *help;
+  handler_t handler;
+} command_t;
+
+static int help(int argc, char **argv);
+static int set_discoverable(int argc, char **argv);
+static int set_name(int argc, char **argv);
+static int set_pcm_loopback(int argc, char **argv);
+
+static bool write_hci_command(hci_packet_t type, const void *packet, size_t length);
+static const command_t *find_command(const char *name);
+static void usage(const char *name);
+
+static const command_t commands[] = {
+  { "help", "<command> - shows help text for <command>.", help },
+  { "setDiscoverable", "(true|false) - whether the controller should be discoverable.", set_discoverable },
+  { "setName", "<name> - sets the device's Bluetooth name to <name>.", set_name },
+  { "setPcmLoopback", "(true|false) - enables or disables PCM loopback on the controller.", set_pcm_loopback },
+};
+
+static int help(int argc, char **argv) {
+  if (!argc) {
+    printf("No help command specified.\n");
+    return 1;
+  }
+
+  const command_t *command = find_command(argv[0]);
+  if (!command) {
+    printf("No command named '%s'.\n", argv[0]);
+    return 2;
+  }
+
+  printf("%s %s\n", argv[0], command->help);
+  return 0;
+}
+
+static int set_discoverable(int argc, char **argv) {
+  if (argc != 1) {
+    printf("Discoverable mode not specified.\n");
+    return 1;
+  }
+
+  if (strcmp(argv[0], "true") && strcmp(argv[0], "false")) {
+    printf("Invalid discoverable mode '%s'.\n", argv[0]);
+    return 2;
+  }
+
+  uint8_t packet[] = { 0x1A, 0x0C, 0x01, 0x00 };
+  if (argv[0][0] == 't')
+    packet[ARRAY_SIZE(packet) - 1] = 0x03;
+
+  return !write_hci_command(HCI_PACKET_COMMAND, packet, ARRAY_SIZE(packet));
+}
+
+static int set_name(int argc, char **argv) {
+  if (argc != 1) {
+    printf("Device name not specified.\n");
+    return 1;
+  }
+
+  size_t len = strlen(argv[0]);
+  if (len > 247) {
+    printf("Device name cannot exceed 247 bytes.\n");
+    return 2;
+  }
+
+  uint8_t packet[251] = { 0x13, 0x0C, 248 };
+  memcpy(&packet[3], argv[0], len + 1);
+
+  if (!write_hci_command(HCI_PACKET_COMMAND, packet, sizeof(packet)))
+    return 1;
+
+  memset(&packet[0], sizeof(packet), 0);
+  packet[0] = 0x52;
+  packet[1] = 0x0C;
+  packet[2] = 0xF1;  // HCI command packet length.
+  packet[3] = 0x01;  // FEC required.
+  packet[4] = len + 1;
+  packet[5] = 0x09;  // Device name field tag.
+  memcpy(&packet[6], argv[0], len);
+  return !write_hci_command(HCI_PACKET_COMMAND, packet, 0xF4);
+}
+
+static int set_pcm_loopback(int argc, char **argv) {
+  if (argc != 1) {
+    printf("PCM loopback mode not specified.\n");
+    return 1;
+  }
+
+  if (strcmp(argv[0], "true") && strcmp(argv[0], "false")) {
+    printf("Invalid PCM mode '%s'.\n", argv[0]);
+    return 2;
+  }
+
+  uint8_t packet[] = { 0x24, 0xFC, 0x01, 0x00 };
+  if (argv[0][0] == 't')
+    packet[ARRAY_SIZE(packet) - 1] = 0x01;
+
+  return !write_hci_command(HCI_PACKET_COMMAND, packet, ARRAY_SIZE(packet));
+}
+
+int main(int argc, char **argv) {
+  if (argc < 2) {
+    usage(argv[0]);
+    return -1;
+  }
+
+  const command_t *command = find_command(argv[1]);
+  if (!command) {
+    printf("Unrecognized command '%s'.\n", argv[1]);
+    return -2;
+  }
+
+  if (!command->handler) {
+    printf("Unhandled command '%s'.\n", argv[1]);
+    return -3;
+  }
+
+  return command->handler(argc - 2, &argv[2]);
+}
+
+static bool write_hci_command(hci_packet_t type, const void *packet, size_t length) {
+  int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (sock == INVALID_FD)
+    goto error;
+
+  struct sockaddr_in addr;
+  addr.sin_family = AF_INET;
+  addr.sin_addr.s_addr = htonl(0x7F000001);
+  addr.sin_port = htons(8873);
+  if (connect(sock, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
+    goto error;
+
+  if (send(sock, &type, 1, 0) != 1)
+    goto error;
+
+  if (send(sock, &length, 2, 0) != 2)
+    goto error;
+
+  if (send(sock, packet, length, 0) != (ssize_t)length)
+    goto error;
+
+  close(sock);
+  return true;
+
+error:;
+  close(sock);
+  return false;
+}
+
+static const command_t *find_command(const char *name) {
+  for (size_t i = 0; i < ARRAY_SIZE(commands); ++i)
+    if (!strcmp(commands[i].name, name))
+      return &commands[i];
+  return NULL;
+}
+
+static void usage(const char *name) {
+  printf("Usage: %s <command> [options]\n", name);
+  printf("Commands:\n");
+  for (size_t i = 0; i < ARRAY_SIZE(commands); ++i)
+    printf("  %s\n", commands[i].name);
+  printf("For detailed help on a command, run '%s help <command>'.\n", name);
+}
diff --git a/udrv/include/uipc.h b/udrv/include/uipc.h
index 37d508c..b5efbd7 100644
--- a/udrv/include/uipc.h
+++ b/udrv/include/uipc.h
@@ -18,10 +18,6 @@
 #ifndef UIPC_H
 #define UIPC_H
 
-#ifndef UDRV_API
-#define UDRV_API
-#endif
-
 #define UIPC_CH_ID_AV_CTRL  0
 #define UIPC_CH_ID_AV_AUDIO 1
 #define UIPC_CH_NUM         2
@@ -52,14 +48,8 @@
 
 typedef void (tUIPC_RCV_CBACK)(tUIPC_CH_ID ch_id, tUIPC_EVENT event); /* points to BT_HDR which describes event type and length of data; len contains the number of bytes of entire message (sizeof(BT_HDR) + offset + size of data) */
 
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
 const char* dump_uipc_event(tUIPC_EVENT event);
 
-
 /*******************************************************************************
 **
 ** Function         UIPC_Init
@@ -69,7 +59,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-UDRV_API extern void UIPC_Init(void *);
+void UIPC_Init(void *);
 
 /*******************************************************************************
 **
@@ -80,7 +70,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-UDRV_API extern BOOLEAN UIPC_Open(tUIPC_CH_ID ch_id, tUIPC_RCV_CBACK *p_cback);
+BOOLEAN UIPC_Open(tUIPC_CH_ID ch_id, tUIPC_RCV_CBACK *p_cback);
 
 /*******************************************************************************
 **
@@ -91,7 +81,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-UDRV_API extern void UIPC_Close(tUIPC_CH_ID ch_id);
+void UIPC_Close(tUIPC_CH_ID ch_id);
 
 /*******************************************************************************
 **
@@ -103,7 +93,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-UDRV_API extern BOOLEAN UIPC_SendBuf(tUIPC_CH_ID ch_id, BT_HDR *p_msg);
+BOOLEAN UIPC_SendBuf(tUIPC_CH_ID ch_id, BT_HDR *p_msg);
 
 /*******************************************************************************
 **
@@ -114,7 +104,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-UDRV_API extern BOOLEAN UIPC_Send(tUIPC_CH_ID ch_id, UINT16 msg_evt, UINT8 *p_buf, UINT16 msglen);
+BOOLEAN UIPC_Send(tUIPC_CH_ID ch_id, UINT16 msg_evt, UINT8 *p_buf, UINT16 msglen);
 
 /*******************************************************************************
 **
@@ -125,7 +115,7 @@
 ** Returns          void
 **
 *******************************************************************************/
-UDRV_API extern UINT32 UIPC_Read(tUIPC_CH_ID ch_id, UINT16 *p_msg_evt, UINT8 *p_buf, UINT32 len);
+UINT32 UIPC_Read(tUIPC_CH_ID ch_id, UINT16 *p_msg_evt, UINT8 *p_buf, UINT32 len);
 
 /*******************************************************************************
 **
@@ -136,14 +126,6 @@
 ** Returns          void
 **
 *******************************************************************************/
-UDRV_API extern BOOLEAN UIPC_Ioctl(tUIPC_CH_ID ch_id, UINT32 request, void *param);
-
-
-#ifdef __cplusplus
-}
-#endif
-
+BOOLEAN UIPC_Ioctl(tUIPC_CH_ID ch_id, UINT32 request, void *param);
 
 #endif  /* UIPC_H */
-
-
diff --git a/udrv/ulinux/uipc.c b/udrv/ulinux/uipc.c
index db58a21..0143826 100644
--- a/udrv/ulinux/uipc.c
+++ b/udrv/ulinux/uipc.c
@@ -45,7 +45,7 @@
 
 
 #include "gki.h"
-#include "data_types.h"
+#include "bt_types.h"
 #include "uipc.h"
 
 #include <cutils/sockets.h>
@@ -581,7 +581,7 @@
  **
  *******************************************************************************/
 
-UDRV_API void UIPC_Init(void *p_data)
+void UIPC_Init(void *p_data)
 {
     UNUSED(p_data);
 
@@ -603,7 +603,7 @@
  ** Returns          TRUE in case of success, FALSE in case of failure.
  **
  *******************************************************************************/
-UDRV_API BOOLEAN UIPC_Open(tUIPC_CH_ID ch_id, tUIPC_RCV_CBACK *p_cback)
+BOOLEAN UIPC_Open(tUIPC_CH_ID ch_id, tUIPC_RCV_CBACK *p_cback)
 {
     BTIF_TRACE_DEBUG("UIPC_Open : ch_id %d, p_cback %x", ch_id, p_cback);
 
@@ -648,7 +648,7 @@
  **
  *******************************************************************************/
 
-UDRV_API void UIPC_Close(tUIPC_CH_ID ch_id)
+void UIPC_Close(tUIPC_CH_ID ch_id)
 {
     BTIF_TRACE_DEBUG("UIPC_Close : ch_id %d", ch_id);
 
@@ -677,7 +677,7 @@
  ** Returns          TRUE in case of success, FALSE in case of failure.
  **
  *******************************************************************************/
-UDRV_API BOOLEAN UIPC_SendBuf(tUIPC_CH_ID ch_id, BT_HDR *p_msg)
+BOOLEAN UIPC_SendBuf(tUIPC_CH_ID ch_id, BT_HDR *p_msg)
 {
     UNUSED(p_msg);
 
@@ -701,7 +701,7 @@
  ** Returns          TRUE in case of success, FALSE in case of failure.
  **
  *******************************************************************************/
-UDRV_API BOOLEAN UIPC_Send(tUIPC_CH_ID ch_id, UINT16 msg_evt, UINT8 *p_buf,
+BOOLEAN UIPC_Send(tUIPC_CH_ID ch_id, UINT16 msg_evt, UINT8 *p_buf,
         UINT16 msglen)
 {
     UNUSED(msg_evt);
@@ -729,7 +729,7 @@
  ** Returns          void
  **
  *******************************************************************************/
-UDRV_API void UIPC_ReadBuf(tUIPC_CH_ID ch_id, BT_HDR *p_msg)
+void UIPC_ReadBuf(tUIPC_CH_ID ch_id, BT_HDR *p_msg)
 {
     UNUSED(p_msg);
 
@@ -749,7 +749,7 @@
  **
  *******************************************************************************/
 
-UDRV_API UINT32 UIPC_Read(tUIPC_CH_ID ch_id, UINT16 *p_msg_evt, UINT8 *p_buf, UINT32 len)
+UINT32 UIPC_Read(tUIPC_CH_ID ch_id, UINT16 *p_msg_evt, UINT8 *p_buf, UINT32 len)
 {
     int n;
     int n_read = 0;
@@ -832,7 +832,7 @@
 **
 *******************************************************************************/
 
-UDRV_API extern BOOLEAN UIPC_Ioctl(tUIPC_CH_ID ch_id, UINT32 request, void *param)
+extern BOOLEAN UIPC_Ioctl(tUIPC_CH_ID ch_id, UINT32 request, void *param)
 {
     BTIF_TRACE_DEBUG("#### UIPC_Ioctl : ch_id %d, request %d ####", ch_id, request);
 
diff --git a/utils/Android.mk b/utils/Android.mk
index c7c59f1..8e3fe39 100644
--- a/utils/Android.mk
+++ b/utils/Android.mk
@@ -4,7 +4,10 @@
 
 LOCAL_C_INCLUDES := \
 	$(LOCAL_PATH)/include \
-	$(LOCAL_PATH)/../gki/ulinux \
+	$(LOCAL_PATH)/../btcore/include \
+	$(LOCAL_PATH)/../osi/include \
+	$(LOCAL_PATH)/../stack/include \
+	$(LOCAL_PATH)/../ \
 	$(bdroid_C_INCLUDES)
 
 LOCAL_CFLAGS += $(bdroid_CFLAGS) -std=c99
diff --git a/utils/include/bt_utils.h b/utils/include/bt_utils.h
index f2bd2ed..fa397f9 100644
--- a/utils/include/bt_utils.h
+++ b/utils/include/bt_utils.h
@@ -19,6 +19,8 @@
 #ifndef BT_UTILS_H
 #define BT_UTILS_H
 
+static const char BT_UTILS_MODULE[] = "bt_utils_module";
+
 /*******************************************************************************
 **  Type definitions
 ********************************************************************************/
@@ -38,8 +40,6 @@
 **  Functions
 ********************************************************************************/
 
-void bt_utils_init();
-void bt_utils_cleanup();
 void raise_priority_a2dp(tHIGH_PRIORITY_TASK high_task);
 void adjust_priority_a2dp(int start);
 #define UNUSED(x) (void)(x)
diff --git a/utils/src/bt_utils.c b/utils/src/bt_utils.c
index ab618b0..1d1dcdd 100644
--- a/utils/src/bt_utils.c
+++ b/utils/src/bt_utils.c
@@ -25,6 +25,8 @@
  *
  ***********************************************************************************/
 
+#define LOG_TAG "bt_utils"
+
 #include <cutils/properties.h>
 #include <cutils/sched_policy.h>
 #include <errno.h>
@@ -35,13 +37,10 @@
 #include <unistd.h>
 #include <utils/ThreadDefs.h>
 
-#define LOG_TAG "BT_UTILS"
-
-#include <utils/Log.h>
-
-#include "data_types.h"
+#include "bt_types.h"
 #include "bt_utils.h"
-
+#include "btcore/include/module.h"
+#include "osi/include/log.h"
 
 /*******************************************************************************
 **  Type definitions for callback functions
@@ -53,41 +52,38 @@
 static int g_TaskIDs[TASK_HIGH_MAX];
 #define INVALID_TASK_ID  (-1)
 
-/*****************************************************************************
-**
-** Function        bt_utils_init
-**
-** Description     Initialize bluedroid util
-**
-** Returns         void
-**
-*******************************************************************************/
-void bt_utils_init() {
-    int i;
-    pthread_mutexattr_t lock_attr;
+static future_t *init(void) {
+  int i;
+  pthread_mutexattr_t lock_attr;
 
-    for(i = 0; i < TASK_HIGH_MAX; i++) {
-        g_DoSchedulingGroupOnce[i] = PTHREAD_ONCE_INIT;
-        g_DoSchedulingGroup[i] = TRUE;
-        g_TaskIDs[i] = INVALID_TASK_ID;
-    }
-    pthread_mutexattr_init(&lock_attr);
-    pthread_mutex_init(&gIdxLock, &lock_attr);
+  for(i = 0; i < TASK_HIGH_MAX; i++) {
+    g_DoSchedulingGroupOnce[i] = PTHREAD_ONCE_INIT;
+    g_DoSchedulingGroup[i] = TRUE;
+    g_TaskIDs[i] = INVALID_TASK_ID;
+  }
+
+  pthread_mutexattr_init(&lock_attr);
+  pthread_mutex_init(&gIdxLock, &lock_attr);
+  return NULL;
 }
 
-/*****************************************************************************
-**
-** Function        bt_utils_cleanup
-**
-** Description     Clean up bluedroid util
-**
-** Returns         void
-**
-*******************************************************************************/
-void bt_utils_cleanup() {
-    pthread_mutex_destroy(&gIdxLock);
+static future_t *clean_up(void) {
+  pthread_mutex_destroy(&gIdxLock);
+  return NULL;
 }
 
+const module_t bt_utils_module = {
+  .name = BT_UTILS_MODULE,
+  .init = init,
+  .start_up = NULL,
+  .shut_down = NULL,
+  .clean_up = clean_up,
+  .dependencies = {
+    NULL
+  }
+};
+
+
 /*****************************************************************************
 **
 ** Function        check_do_scheduling_group
@@ -134,7 +130,7 @@
     pthread_mutex_unlock(&gIdxLock);
 
     if (rc) {
-        ALOGW("failed to change sched policy, tid %d, err: %d", tid, errno);
+        LOG_WARN("failed to change sched policy, tid %d, err: %d", tid, errno);
     }
 
     // always use urgent priority for HCI worker thread until we can adjust
@@ -145,7 +141,7 @@
        priority = ANDROID_PRIORITY_URGENT_AUDIO;
 
     if (setpriority(PRIO_PROCESS, tid, priority) < 0) {
-        ALOGW("failed to change priority tid: %d to %d", tid, priority);
+        LOG_WARN("failed to change priority tid: %d to %d", tid, priority);
     }
 }
 
@@ -172,7 +168,7 @@
         {
             if (setpriority(PRIO_PROCESS, tid, priority) < 0)
             {
-                ALOGW("failed to change priority tid: %d to %d", tid, priority);
+                LOG_WARN("failed to change priority tid: %d to %d", tid, priority);
             }
         }
     }
diff --git a/vnd/ble/vendor_ble.c b/vnd/ble/vendor_ble.c
index bfdfc58..c23d0bc 100644
--- a/vnd/ble/vendor_ble.c
+++ b/vnd/ble/vendor_ble.c
@@ -33,6 +33,7 @@
 #include "vendor_ble.h"
 #include "vendor_hcidefs.h"
 #include "gatt_int.h"
+#include "device/include/controller.h"
 
 /*** This needs to be moved to a VSC control block eventually per coding conventions ***/
 #if VENDOR_DYNAMIC_MEMORY == FALSE
@@ -685,7 +686,6 @@
     return BTM_MODE_UNSUPPORTED;
 }
 
-
 /*******************************************************************************
 **
 ** Function         btm_ble_vendor_init
@@ -715,9 +715,6 @@
     }
 
     btm_ble_vendor_cb.irk_avail_size = max_irk_list_sz;
-
-    if (!HCI_LE_HOST_SUPPORTED(btm_cb.devcb.local_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
-        return;
 #endif
 }
 
diff --git a/vnd/include/vendor_api.h b/vnd/include/vendor_api.h
index 12519cd..3c1d30f 100644
--- a/vnd/include/vendor_api.h
+++ b/vnd/include/vendor_api.h
@@ -40,7 +40,6 @@
 ******************************************************************************/
 #if BLE_ANDROID_CONTROLLER_SCAN_FILTER == TRUE
 
-
 #endif
 
 #ifdef __cplusplus
diff --git a/vnd/include/vendor_ble.h b/vnd/include/vendor_ble.h
index 6207c84..b235ea9 100644
--- a/vnd/include/vendor_ble.h
+++ b/vnd/include/vendor_ble.h
@@ -105,9 +105,9 @@
 #endif
 
 #if VENDOR_DYNAMIC_MEMORY == FALSE
-BTM_API extern tBTM_BLE_VENDOR_CB  btm_ble_vendor_cb;
+extern tBTM_BLE_VENDOR_CB  btm_ble_vendor_cb;
 #else
-BTM_API extern tBTM_BLE_VENDOR_CB *btm_ble_vendor_ptr;
+extern tBTM_BLE_VENDOR_CB *btm_ble_vendor_ptr;
 #define btm_ble_vendor_cb (*btm_ble_vendor_ptr)
 #endif
 
@@ -128,5 +128,3 @@
 #endif
 
 #endif
-
-