Merge "Properly remove callbacks when scanning stopped"
diff --git a/binder/android/bluetooth/IBluetooth.aidl b/binder/android/bluetooth/IBluetooth.aidl
index e7b82cc..5c17563 100644
--- a/binder/android/bluetooth/IBluetooth.aidl
+++ b/binder/android/bluetooth/IBluetooth.aidl
@@ -146,4 +146,6 @@
 
     boolean connectAllEnabledProfiles(in BluetoothDevice device);
     boolean disconnectAllEnabledProfiles(in BluetoothDevice device);
+
+    boolean setActiveDevice(in BluetoothDevice device, in int profiles);
 }
diff --git a/binder/android/bluetooth/IBluetoothA2dp.aidl b/binder/android/bluetooth/IBluetoothA2dp.aidl
index 9cbd9ca..3b406cc 100644
--- a/binder/android/bluetooth/IBluetoothA2dp.aidl
+++ b/binder/android/bluetooth/IBluetoothA2dp.aidl
@@ -39,9 +39,8 @@
     int getConnectionState(in BluetoothDevice device);
     boolean setActiveDevice(in BluetoothDevice device);
     BluetoothDevice getActiveDevice();
-    boolean setPriority(in BluetoothDevice device, int priority);
-    @UnsupportedAppUsage
-    int getPriority(in BluetoothDevice device);
+    boolean setConnectionPolicy(in BluetoothDevice device, int connectionPolicy);
+    int getConnectionPolicy(in BluetoothDevice device);
     boolean isAvrcpAbsoluteVolumeSupported();
     oneway void setAvrcpAbsoluteVolume(int volume);
     boolean isA2dpPlaying(in BluetoothDevice device);
diff --git a/binder/android/bluetooth/IBluetoothA2dpSink.aidl b/binder/android/bluetooth/IBluetoothA2dpSink.aidl
index 557eefc..946b8f4 100644
--- a/binder/android/bluetooth/IBluetoothA2dpSink.aidl
+++ b/binder/android/bluetooth/IBluetoothA2dpSink.aidl
@@ -31,7 +31,7 @@
     List<BluetoothDevice> getDevicesMatchingConnectionStates(in int[] states);
     int getConnectionState(in BluetoothDevice device);
     BluetoothAudioConfig getAudioConfig(in BluetoothDevice device);
-    boolean setPriority(in BluetoothDevice device, int priority);
-    int getPriority(in BluetoothDevice device);
+    boolean setConnectionPolicy(in BluetoothDevice device, int connectionPolicy);
+    int getConnectionPolicy(in BluetoothDevice device);
     boolean isA2dpPlaying(in BluetoothDevice device);
 }
diff --git a/binder/android/bluetooth/IBluetoothHeadset.aidl b/binder/android/bluetooth/IBluetoothHeadset.aidl
index c59cab1..bc8fa05 100644
--- a/binder/android/bluetooth/IBluetoothHeadset.aidl
+++ b/binder/android/bluetooth/IBluetoothHeadset.aidl
@@ -46,10 +46,8 @@
     boolean connect(in BluetoothDevice device);
     @UnsupportedAppUsage
     boolean disconnect(in BluetoothDevice device);
-    @UnsupportedAppUsage
-    boolean setPriority(in BluetoothDevice device, int priority);
-    @UnsupportedAppUsage
-    int getPriority(in BluetoothDevice device);
+    boolean setConnectionPolicy(in BluetoothDevice device, int connectionPolicy);
+    int getConnectionPolicy(in BluetoothDevice device);
     int getAudioState(in BluetoothDevice device);
     boolean isAudioOn();
     boolean connectAudio();
diff --git a/binder/android/bluetooth/IBluetoothHeadsetClient.aidl b/binder/android/bluetooth/IBluetoothHeadsetClient.aidl
index 6341af4..f767b27 100644
--- a/binder/android/bluetooth/IBluetoothHeadsetClient.aidl
+++ b/binder/android/bluetooth/IBluetoothHeadsetClient.aidl
@@ -32,8 +32,8 @@
     List<BluetoothDevice> getConnectedDevices();
     List<BluetoothDevice> getDevicesMatchingConnectionStates(in int[] states);
     int getConnectionState(in BluetoothDevice device);
-    boolean setPriority(in BluetoothDevice device, int priority);
-    int getPriority(in BluetoothDevice device);
+    boolean setConnectionPolicy(in BluetoothDevice device, int connectionPolicy);
+    int getConnectionPolicy(in BluetoothDevice device);
 
     boolean startVoiceRecognition(in BluetoothDevice device);
     boolean stopVoiceRecognition(in BluetoothDevice device);
diff --git a/binder/android/bluetooth/IBluetoothHearingAid.aidl b/binder/android/bluetooth/IBluetoothHearingAid.aidl
index ad14192..9ea9dae 100644
--- a/binder/android/bluetooth/IBluetoothHearingAid.aidl
+++ b/binder/android/bluetooth/IBluetoothHearingAid.aidl
@@ -32,8 +32,8 @@
     int getConnectionState(in BluetoothDevice device);
     boolean setActiveDevice(in BluetoothDevice device);
     List<BluetoothDevice> getActiveDevices();
-    boolean setPriority(in BluetoothDevice device, int priority);
-    int getPriority(in BluetoothDevice device);
+    boolean setConnectionPolicy(in BluetoothDevice device, int connectionPolicy);
+    int getConnectionPolicy(in BluetoothDevice device);
     void adjustVolume(int direction);
     void setVolume(int volume);
     int getVolume();
diff --git a/binder/android/bluetooth/IBluetoothHidHost.aidl b/binder/android/bluetooth/IBluetoothHidHost.aidl
index 609da1b..ca3e33c 100644
--- a/binder/android/bluetooth/IBluetoothHidHost.aidl
+++ b/binder/android/bluetooth/IBluetoothHidHost.aidl
@@ -30,8 +30,8 @@
     List<BluetoothDevice> getConnectedDevices();
     List<BluetoothDevice> getDevicesMatchingConnectionStates(in int[] states);
     int getConnectionState(in BluetoothDevice device);
-    boolean setPriority(in BluetoothDevice device, int priority);
-    int getPriority(in BluetoothDevice device);
+    boolean setConnectionPolicy(in BluetoothDevice device, int connectionPolicy);
+    int getConnectionPolicy(in BluetoothDevice device);
     /**
     * @hide
     */
diff --git a/binder/android/bluetooth/IBluetoothMap.aidl b/binder/android/bluetooth/IBluetoothMap.aidl
index 1274787..4f221e4 100644
--- a/binder/android/bluetooth/IBluetoothMap.aidl
+++ b/binder/android/bluetooth/IBluetoothMap.aidl
@@ -31,6 +31,6 @@
     List<BluetoothDevice> getConnectedDevices();
     List<BluetoothDevice> getDevicesMatchingConnectionStates(in int[] states);
     int getConnectionState(in BluetoothDevice device);
-    boolean setPriority(in BluetoothDevice device, int priority);
-    int getPriority(in BluetoothDevice device);
+    boolean setConnectionPolicy(in BluetoothDevice device, int connectionPolicy);
+    int getConnectionPolicy(in BluetoothDevice device);
 }
diff --git a/binder/android/bluetooth/IBluetoothMapClient.aidl b/binder/android/bluetooth/IBluetoothMapClient.aidl
index 54e2dd7..3da40d3 100644
--- a/binder/android/bluetooth/IBluetoothMapClient.aidl
+++ b/binder/android/bluetooth/IBluetoothMapClient.aidl
@@ -32,8 +32,8 @@
     List<BluetoothDevice> getConnectedDevices();
     List<BluetoothDevice> getDevicesMatchingConnectionStates(in int[] states);
     int getConnectionState(in BluetoothDevice device);
-    boolean setPriority(in BluetoothDevice device,in int priority);
-    int getPriority(in BluetoothDevice device);
+    boolean setConnectionPolicy(in BluetoothDevice device,in int connectionPolicy);
+    int getConnectionPolicy(in BluetoothDevice device);
     boolean sendMessage(in BluetoothDevice device, in Uri[] contacts, in  String message,
         in PendingIntent sentIntent, in PendingIntent deliveryIntent);
     boolean getUnreadMessages(in BluetoothDevice device);
diff --git a/binder/android/bluetooth/IBluetoothPbapClient.aidl b/binder/android/bluetooth/IBluetoothPbapClient.aidl
index 52f9845..e4bfc4e 100644
--- a/binder/android/bluetooth/IBluetoothPbapClient.aidl
+++ b/binder/android/bluetooth/IBluetoothPbapClient.aidl
@@ -29,6 +29,6 @@
     List<BluetoothDevice> getConnectedDevices();
     List<BluetoothDevice> getDevicesMatchingConnectionStates(in int[] states);
     int getConnectionState(in BluetoothDevice device);
-    boolean setPriority(in BluetoothDevice device, int priority);
-    int getPriority(in BluetoothDevice device);
+    boolean setConnectionPolicy(in BluetoothDevice device, int connectionPolicy);
+    int getConnectionPolicy(in BluetoothDevice device);
 }
diff --git a/binder/android/bluetooth/IBluetoothSap.aidl b/binder/android/bluetooth/IBluetoothSap.aidl
index 0ea7afb..00f1f1a 100644
--- a/binder/android/bluetooth/IBluetoothSap.aidl
+++ b/binder/android/bluetooth/IBluetoothSap.aidl
@@ -32,6 +32,6 @@
     List<BluetoothDevice> getConnectedDevices();
     List<BluetoothDevice> getDevicesMatchingConnectionStates(in int[] states);
     int getConnectionState(in BluetoothDevice device);
-    boolean setPriority(in BluetoothDevice device, int priority);
-    int getPriority(in BluetoothDevice device);
+    boolean setConnectionPolicy(in BluetoothDevice device, int connectionPolicy);
+    int getConnectionPolicy(in BluetoothDevice device);
 }
diff --git a/bta/av/bta_av_aact.cc b/bta/av/bta_av_aact.cc
index d175d62..bb88777 100644
--- a/bta/av/bta_av_aact.cc
+++ b/bta/av/bta_av_aact.cc
@@ -3079,14 +3079,14 @@
 }
 
 void offload_vendor_callback(tBTM_VSC_CMPL* param) {
-  uint8_t status = 0;
+  tBTA_AV value{0};
   uint8_t sub_opcode = 0;
   if (param->param_len) {
     APPL_TRACE_DEBUG("%s: param_len = %d status = %d", __func__,
                      param->param_len, param->p_param_buf[0]);
-    status = param->p_param_buf[0];
+    value.status = param->p_param_buf[0];
   }
-  if (status == 0) {
+  if (value.status == 0) {
     sub_opcode = param->p_param_buf[1];
     APPL_TRACE_DEBUG("%s: subopcode = %d", __func__, sub_opcode);
     switch (sub_opcode) {
@@ -3094,7 +3094,7 @@
         APPL_TRACE_DEBUG("%s: VS_HCI_STOP_A2DP_MEDIA successful", __func__);
         break;
       case VS_HCI_A2DP_OFFLOAD_START:
-        (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, (tBTA_AV*)&status);
+        (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, &value);
         break;
       default:
         break;
@@ -3103,7 +3103,7 @@
     APPL_TRACE_DEBUG("%s: Offload failed for subopcode= %d", __func__,
                      sub_opcode);
     if (param->opcode != VS_HCI_A2DP_OFFLOAD_STOP)
-      (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, (tBTA_AV*)&status);
+      (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, &value);
   }
 }
 
diff --git a/btcore/src/device_class.cc b/btcore/src/device_class.cc
index 911eeee..1788024 100644
--- a/btcore/src/device_class.cc
+++ b/btcore/src/device_class.cc
@@ -88,7 +88,9 @@
 int device_class_to_int(const bt_device_class_t* dc) {
   CHECK(dc != NULL);
   // Careful with endianess.
-  return (int)(le32toh(*(int*)dc) & 0xffffff);
+  int val = 0;
+  memcpy(&val, dc, sizeof(*dc));
+  return static_cast<int>(le32toh(val) & 0xffffff);
 }
 
 bool device_class_equals(const bt_device_class_t* p1,
diff --git a/btcore/test/device_class_test.cc b/btcore/test/device_class_test.cc
index 5ce1523..cc1a1fe 100644
--- a/btcore/test/device_class_test.cc
+++ b/btcore/test/device_class_test.cc
@@ -22,9 +22,6 @@
 
 #include "btcore/include/device_class.h"
 
-// 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();
@@ -84,8 +81,9 @@
     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);
+    uint32_t val = 0;
+    memcpy(&val, &dc, sizeof(dc));
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x00000000, val);
 
     EXPECT_PRED_FORMAT2(check_bitfield, 0x00, dc_stream1[0]);
     EXPECT_PRED_FORMAT2(check_bitfield, 0x00, dc_stream1[1]);
@@ -101,8 +99,9 @@
 
     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);
+    uint32_t val = 0;
+    memcpy(&val, &dc, sizeof(dc));
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x00aa55aa, val);
 
     EXPECT_PRED_FORMAT2(check_bitfield, 0xaa, dc_stream1[0]);
     EXPECT_PRED_FORMAT2(check_bitfield, 0x55, dc_stream1[1]);
@@ -118,8 +117,9 @@
 
     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);
+    uint32_t val = 0;
+    memcpy(&val, &dc, sizeof(dc));
+    EXPECT_PRED_FORMAT2(check_bitfield, 0x452301, val);
 
     EXPECT_PRED_FORMAT2(check_bitfield, 0x01, dc_stream1[0]);
     EXPECT_PRED_FORMAT2(check_bitfield, 0x23, dc_stream1[1]);
@@ -131,24 +131,33 @@
   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;
+  uint32_t test = 0;
+  memcpy(&test, &dc, sizeof(dc));
 
   EXPECT_FALSE(device_class_get_limited(&dc));
-  EXPECT_EQ((unsigned)0x00000000, *test & DC_MASK);
+  EXPECT_EQ((unsigned)0x00000000, test);
 
   device_class_set_limited(&dc, true);
+  test = 0;
+  memcpy(&test, &dc, sizeof(dc));
   EXPECT_TRUE(device_class_get_limited(&dc));
-  EXPECT_EQ((unsigned)0x00002000, *test & DC_MASK);
+  EXPECT_EQ((unsigned)0x00002000, test);
 
   device_class_set_limited(&dc, false);
+  test = 0;
+  memcpy(&test, &dc, sizeof(dc));
   EXPECT_FALSE(device_class_get_limited(&dc));
-  EXPECT_EQ((unsigned)0x00000000, *test & DC_MASK);
+  EXPECT_EQ((unsigned)0x00000000, test);
 
   device_class_set_limited(&dc, true);
-  EXPECT_PRED_FORMAT2(check_bitfield, 0x00002000, *test & DC_MASK);
+  test = 0;
+  memcpy(&test, &dc, sizeof(dc));
+  EXPECT_PRED_FORMAT2(check_bitfield, 0x00002000, test);
 
   device_class_set_limited(&dc, false);
-  EXPECT_PRED_FORMAT2(check_bitfield, 0x00000000, *test & DC_MASK);
+  test = 0;
+  memcpy(&test, &dc, sizeof(dc));
+  EXPECT_PRED_FORMAT2(check_bitfield, 0x00000000, test);
 }
 
 TEST_F(DeviceClassTest, equals) {
diff --git a/btif/include/btif_keystore.h b/btif/include/btif_keystore.h
index cc06a98..4762350 100644
--- a/btif/include/btif_keystore.h
+++ b/btif/include/btif_keystore.h
@@ -59,14 +59,6 @@
    */
   std::string Decrypt(const std::string& input_filename);
 
-  /**
-   * Check for existence of keystore key.
-   *
-   * This key can be cleared if a user manually wipes bluetooth storage data
-   * b/133214365
-   */
-  bool DoesKeyExist();
-
  private:
   std::unique_ptr<keystore::KeystoreClient> keystore_client_;
   std::mutex api_mutex_;
diff --git a/btif/src/btif_dm.cc b/btif/src/btif_dm.cc
index a450c27..5543988 100644
--- a/btif/src/btif_dm.cc
+++ b/btif/src/btif_dm.cc
@@ -973,21 +973,12 @@
 
   /* If JustWorks auto-accept */
   if (p_ssp_cfm_req->just_works) {
-    /* Pairing consent for JustWorks needed if:
-     * 1. Incoming (non-temporary) pairing is detected AND
-     * 2. local IO capabilities are DisplayYesNo AND
-     * 3. remote IO capabiltiies are DisplayOnly or NoInputNoOutput;
+    /* Pairing consent for JustWorks NOT needed if:
+     * 1. Incoming temporary pairing is detected
      */
-    if (is_incoming && pairing_cb.bond_type != BOND_TYPE_TEMPORARY &&
-        ((p_ssp_cfm_req->loc_io_caps == HCI_IO_CAP_DISPLAY_YESNO) &&
-         (p_ssp_cfm_req->rmt_io_caps == HCI_IO_CAP_DISPLAY_ONLY ||
-          p_ssp_cfm_req->rmt_io_caps == HCI_IO_CAP_NO_IO))) {
+    if (is_incoming && pairing_cb.bond_type == BOND_TYPE_TEMPORARY) {
       BTIF_TRACE_EVENT(
-          "%s: User consent needed for incoming pairing request. loc_io_caps: "
-          "%d, rmt_io_caps: %d",
-          __func__, p_ssp_cfm_req->loc_io_caps, p_ssp_cfm_req->rmt_io_caps);
-    } else {
-      BTIF_TRACE_EVENT("%s: Auto-accept JustWorks pairing", __func__);
+          "%s: Auto-accept JustWorks pairing for temporary incoming", __func__);
       btif_dm_ssp_reply(&bd_addr, BT_SSP_VARIANT_CONSENT, true, 0);
       return;
     }
diff --git a/btif/src/btif_keystore.cc b/btif/src/btif_keystore.cc
index 0af03e1..fe9d3dd 100644
--- a/btif/src/btif_keystore.cc
+++ b/btif/src/btif_keystore.cc
@@ -98,8 +98,4 @@
                                        &software_enforced_characteristics);
 }
 
-bool BtifKeystore::DoesKeyExist() {
-  return keystore_client_->doesKeyExist(kKeyStore);
-}
-
 }  // namespace bluetooth
diff --git a/gd/hci/acl_manager_test.cc b/gd/hci/acl_manager_test.cc
index 3e3f1b5..805f926 100644
--- a/gd/hci/acl_manager_test.cc
+++ b/gd/hci/acl_manager_test.cc
@@ -102,14 +102,26 @@
                       common::OnceCallback<void(CommandStatusView)> on_status, os::Handler* handler) override {
     command_queue_.push(std::move(command));
     command_status_callbacks.push_front(std::move(on_status));
-    not_empty_.notify_all();
+    if (command_promise_ != nullptr) {
+      command_promise_->set_value();
+      command_promise_.reset();
+    }
   }
 
   void EnqueueCommand(std::unique_ptr<CommandPacketBuilder> command,
                       common::OnceCallback<void(CommandCompleteView)> on_complete, os::Handler* handler) override {
     command_queue_.push(std::move(command));
     command_complete_callbacks.push_front(std::move(on_complete));
-    not_empty_.notify_all();
+    if (command_promise_ != nullptr) {
+      command_promise_->set_value();
+      command_promise_.reset();
+    }
+  }
+
+  void SetCommandFuture() {
+    ASSERT_LOG(command_promise_ == nullptr, "Promises, Promises, ... Only one at a time.");
+    command_promise_ = std::make_unique<std::promise<void>>();
+    command_future_ = std::make_unique<std::future<void>>(command_promise_->get_future());
   }
 
   std::unique_ptr<CommandPacketBuilder> GetLastCommand() {
@@ -122,10 +134,11 @@
   }
 
   ConnectionManagementCommandView GetCommandPacket(OpCode op_code) {
-    std::unique_lock<std::mutex> lock(mutex_);
-    std::chrono::milliseconds time = std::chrono::milliseconds(3000);
-
-    ASSERT(not_empty_.wait_for(lock, time) != std::cv_status::timeout);
+    if (command_future_ != nullptr) {
+      auto result = command_future_->wait_for(std::chrono::milliseconds(1000));
+      EXPECT_NE(std::future_status::timeout, result);
+    }
+    ASSERT(command_queue_.size() > 0);
     auto packet_view = GetPacketView(GetLastCommand());
     CommandPacketView command_packet_view = CommandPacketView::Create(packet_view);
     ConnectionManagementCommandView command = ConnectionManagementCommandView::Create(command_packet_view);
@@ -241,8 +254,8 @@
   BidiQueue<AclPacketView, AclPacketBuilder> acl_queue_{3 /* TODO: Set queue depth */};
 
   std::queue<std::unique_ptr<CommandPacketBuilder>> command_queue_;
-  mutable std::mutex mutex_;
-  std::condition_variable not_empty_;
+  std::unique_ptr<std::promise<void>> command_promise_;
+  std::unique_ptr<std::future<void>> command_future_;
 };
 
 class AclManagerNoCallbacksTest : public ::testing::Test {
@@ -435,6 +448,7 @@
 TEST_F(AclManagerTest, invoke_registered_callback_connection_complete_success) {
   uint16_t handle = 1;
 
+  test_hci_layer_->SetCommandFuture();
   acl_manager_->CreateConnection(remote);
 
   // Wait for the connection request
@@ -458,6 +472,7 @@
 TEST_F(AclManagerTest, invoke_registered_callback_connection_complete_fail) {
   uint16_t handle = 0x123;
 
+  test_hci_layer_->SetCommandFuture();
   acl_manager_->CreateConnection(remote);
 
   // Wait for the connection request
@@ -476,6 +491,7 @@
 
 TEST_F(AclManagerTest, invoke_registered_callback_le_connection_complete_success) {
   AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS);
+  test_hci_layer_->SetCommandFuture();
   acl_manager_->CreateLeConnection(remote_with_type);
 
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::LE_CREATE_CONNECTION);
@@ -502,6 +518,7 @@
 
 TEST_F(AclManagerTest, invoke_registered_callback_le_connection_complete_fail) {
   AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS);
+  test_hci_layer_->SetCommandFuture();
   acl_manager_->CreateLeConnection(remote_with_type);
 
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::LE_CREATE_CONNECTION);
@@ -523,6 +540,7 @@
 TEST_F(AclManagerTest, invoke_registered_callback_disconnection_complete) {
   uint16_t handle = 0x123;
 
+  test_hci_layer_->SetCommandFuture();
   acl_manager_->CreateConnection(remote);
 
   // Wait for the connection request
@@ -562,6 +580,7 @@
 TEST_F(AclManagerTest, acl_connection_finish_after_disconnected) {
   uint16_t handle = 0x123;
 
+  test_hci_layer_->SetCommandFuture();
   acl_manager_->CreateConnection(remote);
 
   // Wait for the connection request
@@ -693,6 +712,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_switch_role) {
+  test_hci_layer_->SetCommandFuture();
   acl_manager_->SwitchRole(connection_->GetAddress(), Role::SLAVE);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::SWITCH_ROLE);
   auto command_view = SwitchRoleView::Create(packet);
@@ -705,11 +725,13 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_default_link_policy_settings) {
+  test_hci_layer_->SetCommandFuture();
   acl_manager_->ReadDefaultLinkPolicySettings();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_DEFAULT_LINK_POLICY_SETTINGS);
   auto command_view = ReadDefaultLinkPolicySettingsView::Create(packet);
   ASSERT(command_view.IsValid());
 
+  test_hci_layer_->SetCommandFuture();
   EXPECT_CALL(mock_acl_manager_callbacks_, OnReadDefaultLinkPolicySettingsComplete(0x07));
   uint8_t num_packets = 1;
   test_hci_layer_->IncomingEvent(
@@ -717,6 +739,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_write_default_link_policy_settings) {
+  test_hci_layer_->SetCommandFuture();
   acl_manager_->WriteDefaultLinkPolicySettings(0x05);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::WRITE_DEFAULT_LINK_POLICY_SETTINGS);
   auto command_view = WriteDefaultLinkPolicySettingsView::Create(packet);
@@ -729,6 +752,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_change_connection_packet_type) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ChangeConnectionPacketType(0xEE1C);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::CHANGE_CONNECTION_PACKET_TYPE);
   auto command_view = ChangeConnectionPacketTypeView::Create(packet);
@@ -740,6 +764,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_authentication_requested) {
+  test_hci_layer_->SetCommandFuture();
   connection_->AuthenticationRequested();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::AUTHENTICATION_REQUESTED);
   auto command_view = AuthenticationRequestedView::Create(packet);
@@ -750,6 +775,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_clock_offset) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ReadClockOffset();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_CLOCK_OFFSET);
   auto command_view = ReadClockOffsetView::Create(packet);
@@ -760,6 +786,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_hold_mode) {
+  test_hci_layer_->SetCommandFuture();
   connection_->HoldMode(0x0500, 0x0020);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::HOLD_MODE);
   auto command_view = HoldModeView::Create(packet);
@@ -772,6 +799,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_sniff_mode) {
+  test_hci_layer_->SetCommandFuture();
   connection_->SniffMode(0x0500, 0x0020, 0x0040, 0x0014);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::SNIFF_MODE);
   auto command_view = SniffModeView::Create(packet);
@@ -786,6 +814,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_exit_sniff_mode) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ExitSniffMode();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::EXIT_SNIFF_MODE);
   auto command_view = ExitSniffModeView::Create(packet);
@@ -796,6 +825,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_qos_setup) {
+  test_hci_layer_->SetCommandFuture();
   connection_->QosSetup(ServiceType::BEST_EFFORT, 0x1234, 0x1233, 0x1232, 0x1231);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::QOS_SETUP);
   auto command_view = QosSetupView::Create(packet);
@@ -813,6 +843,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_flow_specification) {
+  test_hci_layer_->SetCommandFuture();
   connection_->FlowSpecification(FlowDirection::OUTGOING_FLOW, ServiceType::BEST_EFFORT, 0x1234, 0x1233, 0x1232,
                                  0x1231);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::FLOW_SPECIFICATION);
@@ -834,6 +865,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_flush) {
+  test_hci_layer_->SetCommandFuture();
   connection_->Flush();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::FLUSH);
   auto command_view = FlushView::Create(packet);
@@ -844,6 +876,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_role_discovery) {
+  test_hci_layer_->SetCommandFuture();
   connection_->RoleDiscovery();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::ROLE_DISCOVERY);
   auto command_view = RoleDiscoveryView::Create(packet);
@@ -856,6 +889,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_link_policy_settings) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ReadLinkPolicySettings();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_LINK_POLICY_SETTINGS);
   auto command_view = ReadLinkPolicySettingsView::Create(packet);
@@ -868,6 +902,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_write_link_policy_settings) {
+  test_hci_layer_->SetCommandFuture();
   connection_->WriteLinkPolicySettings(0x05);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::WRITE_LINK_POLICY_SETTINGS);
   auto command_view = WriteLinkPolicySettingsView::Create(packet);
@@ -880,6 +915,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_sniff_subrating) {
+  test_hci_layer_->SetCommandFuture();
   connection_->SniffSubrating(0x1234, 0x1235, 0x1236);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::SNIFF_SUBRATING);
   auto command_view = SniffSubratingView::Create(packet);
@@ -893,6 +929,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_automatic_flush_timeout) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ReadAutomaticFlushTimeout();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_AUTOMATIC_FLUSH_TIMEOUT);
   auto command_view = ReadAutomaticFlushTimeoutView::Create(packet);
@@ -905,6 +942,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_write_automatic_flush_timeout) {
+  test_hci_layer_->SetCommandFuture();
   connection_->WriteAutomaticFlushTimeout(0x07FF);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::WRITE_AUTOMATIC_FLUSH_TIMEOUT);
   auto command_view = WriteAutomaticFlushTimeoutView::Create(packet);
@@ -917,6 +955,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_transmit_power_level) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ReadTransmitPowerLevel(TransmitPowerLevelType::CURRENT);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_TRANSMIT_POWER_LEVEL);
   auto command_view = ReadTransmitPowerLevelView::Create(packet);
@@ -930,6 +969,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_link_supervision_timeout) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ReadLinkSupervisionTimeout();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_LINK_SUPERVISION_TIMEOUT);
   auto command_view = ReadLinkSupervisionTimeoutView::Create(packet);
@@ -942,6 +982,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_write_link_supervision_timeout) {
+  test_hci_layer_->SetCommandFuture();
   connection_->WriteLinkSupervisionTimeout(0x5678);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::WRITE_LINK_SUPERVISION_TIMEOUT);
   auto command_view = WriteLinkSupervisionTimeoutView::Create(packet);
@@ -954,6 +995,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_failed_contact_counter) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ReadFailedContactCounter();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_FAILED_CONTACT_COUNTER);
   auto command_view = ReadFailedContactCounterView::Create(packet);
@@ -966,6 +1008,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_reset_failed_contact_counter) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ResetFailedContactCounter();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::RESET_FAILED_CONTACT_COUNTER);
   auto command_view = ResetFailedContactCounterView::Create(packet);
@@ -977,6 +1020,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_link_quality) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ReadLinkQuality();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_LINK_QUALITY);
   auto command_view = ReadLinkQualityView::Create(packet);
@@ -989,6 +1033,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_afh_channel_map) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ReadAfhChannelMap();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_AFH_CHANNEL_MAP);
   auto command_view = ReadAfhChannelMapView::Create(packet);
@@ -1003,6 +1048,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_rssi) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ReadRssi();
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_RSSI);
   auto command_view = ReadRssiView::Create(packet);
@@ -1014,6 +1060,7 @@
 }
 
 TEST_F(AclManagerWithConnectionTest, send_read_clock) {
+  test_hci_layer_->SetCommandFuture();
   connection_->ReadClock(WhichClock::LOCAL);
   auto packet = test_hci_layer_->GetCommandPacket(OpCode::READ_CLOCK);
   auto command_view = ReadClockView::Create(packet);
diff --git a/gd/hci/le_scanning_manager.cc b/gd/hci/le_scanning_manager.cc
index d43eb41..c3b96d9 100644
--- a/gd/hci/le_scanning_manager.cc
+++ b/gd/hci/le_scanning_manager.cc
@@ -29,6 +29,9 @@
 namespace bluetooth {
 namespace hci {
 
+constexpr uint16_t kDefaultLeScanWindow = 4800;
+constexpr uint16_t kDefaultLeScanInterval = 4800;
+
 const ModuleFactory LeScanningManager::Factory = ModuleFactory([]() { return new LeScanningManager(); });
 
 enum class ScanApiType {
@@ -109,8 +112,8 @@
   void configure_scan() {
     std::vector<PhyScanParameters> parameter_vector;
     PhyScanParameters phy_scan_parameters;
-    phy_scan_parameters.le_scan_window_ = 0;
-    phy_scan_parameters.le_scan_interval_ = 0;
+    phy_scan_parameters.le_scan_window_ = kDefaultLeScanWindow;
+    phy_scan_parameters.le_scan_interval_ = kDefaultLeScanInterval;
     phy_scan_parameters.le_scan_type_ = LeScanType::ACTIVE;
     parameter_vector.push_back(phy_scan_parameters);
     uint8_t phys_in_use = 1;
diff --git a/gd/neighbor/inquiry.cc b/gd/neighbor/inquiry.cc
index eb94701..4246cb2 100644
--- a/gd/neighbor/inquiry.cc
+++ b/gd/neighbor/inquiry.cc
@@ -32,37 +32,18 @@
 static constexpr uint8_t kGeneralInquiryAccessCode = 0x33;
 static constexpr uint8_t kLimitedInquiryAccessCode = 0x00;
 
-static inline std::string LapText(uint8_t lap) {
-  switch (lap) {
-    case kGeneralInquiryAccessCode:
-      return "General Lap";
-    case kLimitedInquiryAccessCode:
-      return "Limited Lap";
-    default:
-      return "Unknown Lap";
-  }
-}
-
-static hci::Lap general_lap_;
-static hci::Lap limited_lap_;
-
 struct InquiryModule::impl {
   void RegisterCallbacks(InquiryCallbacks inquiry_callbacks);
   void UnregisterCallbacks();
 
-  void StartOneShotInquiry(hci::Lap& lap, InquiryLength inquiry_length, NumResponses num_responses);
+  void StartOneShotInquiry(bool limited, InquiryLength inquiry_length, NumResponses num_responses);
   void StopOneShotInquiry();
 
-  void StartPeriodicInquiry(hci::Lap& lap, InquiryLength inquiry_length, NumResponses num_responses,
+  void StartPeriodicInquiry(bool limited, InquiryLength inquiry_length, NumResponses num_responses,
                             PeriodLength max_delay, PeriodLength min_delay);
   void StopPeriodicInquiry();
 
-  bool IsInquiryActive() const;
-  bool IsOneShotInquiryActive(hci::Lap& lap) const;
-  bool IsPeriodicInquiryActive(hci::Lap& lap) const;
-
   void SetScanActivity(ScanParameters params);
-  ScanParameters GetScanActivity() const;
 
   void SetScanType(hci::InquiryScanType scan_type);
 
@@ -80,14 +61,18 @@
 
   InquiryModule& module_;
 
-  hci::Lap* active_one_shot_{nullptr};
-  hci::Lap* active_periodic_{nullptr};
+  bool active_general_one_shot_{false};
+  bool active_limited_one_shot_{false};
+  bool active_general_periodic_{false};
+  bool active_limited_periodic_{false};
 
   ScanParameters inquiry_scan_;
   hci::InquiryMode inquiry_mode_;
   hci::InquiryScanType inquiry_scan_type_;
   int8_t inquiry_response_tx_power_;
 
+  bool IsInquiryActive() const;
+
   void EnqueueCommandComplete(std::unique_ptr<hci::CommandPacketBuilder> command);
   void EnqueueCommandStatus(std::unique_ptr<hci::CommandPacketBuilder> command);
   void OnCommandComplete(hci::CommandCompleteView view);
@@ -106,10 +91,7 @@
 
 const ModuleFactory neighbor::InquiryModule::Factory = ModuleFactory([]() { return new neighbor::InquiryModule(); });
 
-neighbor::InquiryModule::impl::impl(neighbor::InquiryModule& module) : module_(module) {
-  general_lap_.lap_ = kGeneralInquiryAccessCode;
-  limited_lap_.lap_ = kLimitedInquiryAccessCode;
-}
+neighbor::InquiryModule::impl::impl(neighbor::InquiryModule& module) : module_(module) {}
 
 void neighbor::InquiryModule::impl::OnCommandCompleteSync(hci::CommandCompleteView view) {
   OnCommandComplete(view);
@@ -129,9 +111,6 @@
       auto packet = hci::PeriodicInquiryModeCompleteView::Create(view);
       ASSERT(packet.IsValid());
       ASSERT(packet.GetStatus() == hci::ErrorCode::SUCCESS);
-      if (active_periodic_ != nullptr) {
-        LOG_DEBUG("Periodic inquiry started lap:%s", LapText(active_periodic_->lap_).c_str());
-      }
     } break;
 
     case hci::OpCode::EXIT_PERIODIC_INQUIRY_MODE: {
@@ -200,8 +179,8 @@
     case hci::OpCode::INQUIRY: {
       auto packet = hci::InquiryStatusView::Create(status);
       ASSERT(packet.IsValid());
-      if (active_one_shot_ != nullptr) {
-        LOG_DEBUG("Inquiry started lap:%s", LapText(active_one_shot_->lap_).c_str());
+      if (active_limited_one_shot_ || active_general_one_shot_) {
+        LOG_DEBUG("Inquiry started lap: %s", active_limited_one_shot_ ? "Limited" : "General");
       }
     } break;
 
@@ -217,7 +196,8 @@
       auto packet = hci::InquiryCompleteView::Create(view);
       ASSERT(packet.IsValid());
       LOG_DEBUG("inquiry complete");
-      active_one_shot_ = nullptr;
+      active_limited_one_shot_ = false;
+      active_general_one_shot_ = false;
       inquiry_callbacks_.complete(packet.GetStatus());
     } break;
 
@@ -303,46 +283,54 @@
   command_sync_ = nullptr;
 }
 
-void neighbor::InquiryModule::impl::StartOneShotInquiry(hci::Lap& lap, InquiryLength inquiry_length,
+void neighbor::InquiryModule::impl::StartOneShotInquiry(bool limited, InquiryLength inquiry_length,
                                                         NumResponses num_responses) {
   ASSERT(HasCallbacks());
-  ASSERT(active_one_shot_ == nullptr);
-  active_one_shot_ = &lap;
+  ASSERT(!IsInquiryActive());
+  hci::Lap lap;
+  if (limited) {
+    active_limited_one_shot_ = true;
+    lap.lap_ = kLimitedInquiryAccessCode;
+  } else {
+    active_general_one_shot_ = true;
+    lap.lap_ = kGeneralInquiryAccessCode;
+  }
   EnqueueCommandStatus(hci::InquiryBuilder::Create(lap, inquiry_length, num_responses));
 }
 
 void neighbor::InquiryModule::impl::StopOneShotInquiry() {
-  ASSERT(active_one_shot_ != nullptr);
-  active_one_shot_ = nullptr;
+  ASSERT(active_general_one_shot_ || active_limited_one_shot_);
+  active_general_one_shot_ = false;
+  active_limited_one_shot_ = false;
   EnqueueCommandComplete(hci::InquiryCancelBuilder::Create());
 }
 
-bool neighbor::InquiryModule::impl::IsOneShotInquiryActive(hci::Lap& lap) const {
-  return active_one_shot_ == &lap;
-}
-
-void neighbor::InquiryModule::impl::StartPeriodicInquiry(hci::Lap& lap, InquiryLength inquiry_length,
+void neighbor::InquiryModule::impl::StartPeriodicInquiry(bool limited, InquiryLength inquiry_length,
                                                          NumResponses num_responses, PeriodLength max_delay,
                                                          PeriodLength min_delay) {
   ASSERT(HasCallbacks());
-  ASSERT(active_periodic_ == nullptr);
-  active_periodic_ = &lap;
+  ASSERT(!IsInquiryActive());
+  hci::Lap lap;
+  if (limited) {
+    active_limited_periodic_ = true;
+    lap.lap_ = kLimitedInquiryAccessCode;
+  } else {
+    active_general_periodic_ = true;
+    lap.lap_ = kGeneralInquiryAccessCode;
+  }
   EnqueueCommandComplete(
-      hci::PeriodicInquiryModeBuilder::Create(inquiry_length, num_responses, lap, max_delay, min_delay));
+      hci::PeriodicInquiryModeBuilder::Create(max_delay, min_delay, lap, inquiry_length, num_responses));
 }
 
 void neighbor::InquiryModule::impl::StopPeriodicInquiry() {
-  ASSERT(active_periodic_ != nullptr);
-  active_periodic_ = nullptr;
+  ASSERT(active_general_periodic_ || active_limited_periodic_);
+  active_general_periodic_ = false;
+  active_limited_periodic_ = false;
   EnqueueCommandComplete(hci::ExitPeriodicInquiryModeBuilder::Create());
 }
 
-bool neighbor::InquiryModule::impl::IsPeriodicInquiryActive(hci::Lap& lap) const {
-  return active_periodic_ == &lap;
-}
-
 bool neighbor::InquiryModule::impl::IsInquiryActive() const {
-  return active_one_shot_ != nullptr || active_periodic_ != nullptr;
+  return active_general_one_shot_ || active_limited_one_shot_ || active_limited_periodic_ || active_general_periodic_;
 }
 
 void neighbor::InquiryModule::impl::Start() {
@@ -378,10 +366,6 @@
             ScanIntervalTimeMs(params.interval), params.window, ScanWindowTimeMs(params.window));
 }
 
-ScanParameters neighbor::InquiryModule::impl::GetScanActivity() const {
-  return inquiry_scan_;
-}
-
 void neighbor::InquiryModule::impl::SetScanType(hci::InquiryScanType scan_type) {
   EnqueueCommandComplete(hci::WriteInquiryScanTypeBuilder::Create(scan_type));
   LOG_DEBUG("Set scan type:%s", hci::InquiryScanTypeText(scan_type).c_str());
@@ -410,103 +394,67 @@
 }
 
 void neighbor::InquiryModule::StartGeneralInquiry(InquiryLength inquiry_length, NumResponses num_responses) {
-  if (pimpl_->IsInquiryActive()) {
-    LOG_WARN("Ignoring start general one shot inquiry as an inquiry is already active");
-    return;
-  }
-  pimpl_->StartOneShotInquiry(general_lap_, inquiry_length, num_responses);
-  LOG_DEBUG("Started general one shot inquiry");
+  GetHandler()->Post(common::BindOnce(&neighbor::InquiryModule::impl::StartOneShotInquiry,
+                                      common::Unretained(pimpl_.get()), false, inquiry_length, num_responses));
 }
 
 void neighbor::InquiryModule::StartLimitedInquiry(InquiryLength inquiry_length, NumResponses num_responses) {
-  if (pimpl_->IsInquiryActive()) {
-    LOG_WARN("Ignoring start limited one shot inquiry as an inquiry is already active");
-    return;
-  }
-  pimpl_->StartOneShotInquiry(limited_lap_, inquiry_length, num_responses);
-  LOG_DEBUG("Started limited one shot inquiry");
+  GetHandler()->Post(common::BindOnce(&neighbor::InquiryModule::impl::StartOneShotInquiry,
+                                      common::Unretained(pimpl_.get()), true, inquiry_length, num_responses));
 }
 
 void neighbor::InquiryModule::StopInquiry() {
-  if (!pimpl_->IsInquiryActive()) {
-    LOG_WARN("Ignoring stop one shot inquiry as an inquiry is not active");
-    return;
-  }
-  pimpl_->StopOneShotInquiry();
-  LOG_DEBUG("Stopped one shot inquiry");
-}
-
-bool neighbor::InquiryModule::IsGeneralInquiryActive() const {
-  return pimpl_->IsOneShotInquiryActive(general_lap_);
-}
-
-bool neighbor::InquiryModule::IsLimitedInquiryActive() const {
-  return pimpl_->IsOneShotInquiryActive(limited_lap_);
+  GetHandler()->Post(
+      common::BindOnce(&neighbor::InquiryModule::impl::StopOneShotInquiry, common::Unretained(pimpl_.get())));
 }
 
 void neighbor::InquiryModule::StartGeneralPeriodicInquiry(InquiryLength inquiry_length, NumResponses num_responses,
                                                           PeriodLength max_delay, PeriodLength min_delay) {
-  if (pimpl_->IsInquiryActive()) {
-    LOG_WARN("Ignoring start general periodic inquiry as an inquiry is already active");
-    return;
-  }
-  pimpl_->StartPeriodicInquiry(general_lap_, inquiry_length, num_responses, max_delay, min_delay);
-  LOG_DEBUG("Started general periodic inquiry");
+  GetHandler()->Post(common::BindOnce(&neighbor::InquiryModule::impl::StartPeriodicInquiry,
+                                      common::Unretained(pimpl_.get()), false, inquiry_length, num_responses, max_delay,
+                                      min_delay));
 }
 
 void neighbor::InquiryModule::StartLimitedPeriodicInquiry(InquiryLength inquiry_length, NumResponses num_responses,
                                                           PeriodLength max_delay, PeriodLength min_delay) {
-  if (pimpl_->IsInquiryActive()) {
-    LOG_WARN("Ignoring start limited periodic inquiry as an inquiry is already active");
-    return;
-  }
-  pimpl_->StartPeriodicInquiry(limited_lap_, inquiry_length, num_responses, max_delay, min_delay);
-  LOG_DEBUG("Started limited periodic inquiry");
+  GetHandler()->Post(common::BindOnce(&neighbor::InquiryModule::impl::StartPeriodicInquiry,
+                                      common::Unretained(pimpl_.get()), true, inquiry_length, num_responses, max_delay,
+                                      min_delay));
 }
 
 void neighbor::InquiryModule::StopPeriodicInquiry() {
-  if (!pimpl_->IsInquiryActive()) {
-    LOG_WARN("Ignoring stop periodic inquiry as an inquiry is not active");
-    return;
-  }
-  pimpl_->StopPeriodicInquiry();
-  LOG_DEBUG("Stopped periodic inquiry");
-}
-
-bool neighbor::InquiryModule::IsGeneralPeriodicInquiryActive() const {
-  return pimpl_->IsPeriodicInquiryActive(general_lap_);
-}
-
-bool neighbor::InquiryModule::IsLimitedPeriodicInquiryActive() const {
-  return pimpl_->IsPeriodicInquiryActive(limited_lap_);
+  GetHandler()->Post(
+      common::BindOnce(&neighbor::InquiryModule::impl::StopPeriodicInquiry, common::Unretained(pimpl_.get())));
 }
 
 void neighbor::InquiryModule::SetScanActivity(ScanParameters params) {
-  pimpl_->SetScanActivity(params);
-}
-
-ScanParameters neighbor::InquiryModule::GetScanActivity() const {
-  return pimpl_->GetScanActivity();
+  GetHandler()->Post(
+      common::BindOnce(&neighbor::InquiryModule::impl::SetScanActivity, common::Unretained(pimpl_.get()), params));
 }
 
 void neighbor::InquiryModule::SetInterlacedScan() {
-  pimpl_->SetScanType(hci::InquiryScanType::INTERLACED);
+  GetHandler()->Post(common::BindOnce(&neighbor::InquiryModule::impl::SetScanType, common::Unretained(pimpl_.get()),
+                                      hci::InquiryScanType::INTERLACED));
 }
 
 void neighbor::InquiryModule::SetStandardScan() {
-  pimpl_->SetScanType(hci::InquiryScanType::STANDARD);
+  GetHandler()->Post(common::BindOnce(&neighbor::InquiryModule::impl::SetScanType, common::Unretained(pimpl_.get()),
+                                      hci::InquiryScanType::STANDARD));
 }
 
 void neighbor::InquiryModule::SetStandardInquiryResultMode() {
-  pimpl_->SetInquiryMode(hci::InquiryMode::STANDARD);
+  GetHandler()->Post(common::BindOnce(&neighbor::InquiryModule::impl::SetInquiryMode, common::Unretained(pimpl_.get()),
+                                      hci::InquiryMode::STANDARD));
 }
 
 void neighbor::InquiryModule::SetInquiryWithRssiResultMode() {
-  pimpl_->SetInquiryMode(hci::InquiryMode::RSSI);
+  GetHandler()->Post(common::BindOnce(&neighbor::InquiryModule::impl::SetInquiryMode, common::Unretained(pimpl_.get()),
+                                      hci::InquiryMode::RSSI));
 }
 
 void neighbor::InquiryModule::SetExtendedInquiryResultMode() {
-  pimpl_->SetInquiryMode(hci::InquiryMode::RSSI_OR_EXTENDED);
+  GetHandler()->Post(common::BindOnce(&neighbor::InquiryModule::impl::SetInquiryMode, common::Unretained(pimpl_.get()),
+                                      hci::InquiryMode::RSSI_OR_EXTENDED));
 }
 
 /**
diff --git a/gd/neighbor/inquiry.h b/gd/neighbor/inquiry.h
index 2da2a56..33e3d6c 100644
--- a/gd/neighbor/inquiry.h
+++ b/gd/neighbor/inquiry.h
@@ -48,19 +48,14 @@
   void StartGeneralInquiry(InquiryLength inquiry_length, NumResponses num_responses);
   void StartLimitedInquiry(InquiryLength inquiry_length, NumResponses num_responses);
   void StopInquiry();
-  bool IsGeneralInquiryActive() const;
-  bool IsLimitedInquiryActive() const;
 
   void StartGeneralPeriodicInquiry(InquiryLength inquiry_length, NumResponses num_responses, PeriodLength max_delay,
                                    PeriodLength min_delay);
   void StartLimitedPeriodicInquiry(InquiryLength inquiry_length, NumResponses num_responses, PeriodLength max_delay,
                                    PeriodLength min_delay);
   void StopPeriodicInquiry();
-  bool IsGeneralPeriodicInquiryActive() const;
-  bool IsLimitedPeriodicInquiryActive() const;
 
   void SetScanActivity(ScanParameters parms);
-  ScanParameters GetScanActivity() const;
 
   void SetInterlacedScan();
   void SetStandardScan();
diff --git a/gd/neighbor/inquiry_test.cc b/gd/neighbor/inquiry_test.cc
index 05d1a70..936a897 100644
--- a/gd/neighbor/inquiry_test.cc
+++ b/gd/neighbor/inquiry_test.cc
@@ -57,6 +57,10 @@
   uint16_t inquiry_scan_window;
   hci::InquiryScanType inquiry_scan_type;
   hci::InquiryMode inquiry_mode;
+  uint8_t inquiry_length;
+  uint8_t num_responses;
+  uint16_t min_period_length;
+  uint16_t max_period_length;
 } hci_register_{
     .one_shot_inquiry_active = false,
     .periodic_inquiry_active = false,
@@ -65,6 +69,10 @@
     .inquiry_scan_window = kInitialInquiryScanWindow,
     .inquiry_scan_type = hci::InquiryScanType::STANDARD,
     .inquiry_mode = hci::InquiryMode::STANDARD,
+    .inquiry_length = 0,
+    .num_responses = 0,
+    .min_period_length = 0,
+    .max_period_length = 0,
 };
 
 hci::PacketView<hci::kLittleEndian> GetPacketView(std::unique_ptr<packet::BasePacketBuilder> packet) {
@@ -102,11 +110,17 @@
         hci_register_.one_shot_inquiry_active = false;
         break;
 
-      case hci::OpCode::PERIODIC_INQUIRY_MODE:
+      case hci::OpCode::PERIODIC_INQUIRY_MODE: {
+        auto inquiry = hci::PeriodicInquiryModeView::Create(hci::DiscoveryCommandView::Create(command));
+        ASSERT(inquiry.IsValid());
         event_builder =
             hci::PeriodicInquiryModeCompleteBuilder::Create(kNumberPacketsReadyToReceive, hci::ErrorCode::SUCCESS);
         hci_register_.periodic_inquiry_active = true;
-        break;
+        hci_register_.inquiry_length = inquiry.GetInquiryLength();
+        hci_register_.num_responses = inquiry.GetNumResponses();
+        hci_register_.max_period_length = inquiry.GetMaxPeriodLength();
+        hci_register_.min_period_length = inquiry.GetMinPeriodLength();
+      } break;
 
       case hci::OpCode::EXIT_PERIODIC_INQUIRY_MODE:
         event_builder =
@@ -177,7 +191,7 @@
     handler->Post(common::BindOnce(std::move(on_complete), std::move(command_complete)));
 
     if (promise_sync_complete_ != nullptr) {
-      promise_sync_complete_->set_value(true);
+      promise_sync_complete_->set_value(command.GetOpCode());
     }
   }
 
@@ -188,10 +202,14 @@
 
     std::unique_ptr<packet::BasePacketBuilder> event_builder;
     switch (command.GetOpCode()) {
-      case hci::OpCode::INQUIRY:
+      case hci::OpCode::INQUIRY: {
+        auto inquiry = hci::InquiryView::Create(hci::DiscoveryCommandView::Create(command));
+        ASSERT(inquiry.IsValid());
         event_builder = hci::InquiryStatusBuilder::Create(hci::ErrorCode::SUCCESS, kNumberPacketsReadyToReceive);
         hci_register_.one_shot_inquiry_active = true;
-        break;
+        hci_register_.num_responses = inquiry.GetNumResponses();
+        hci_register_.inquiry_length = inquiry.GetInquiryLength();
+      } break;
       default:
         LOG_INFO("Dropping unhandled status expecting command:%s", hci::OpCodeText(command.GetOpCode()).c_str());
         return;
@@ -203,7 +221,7 @@
     handler->Post(common::BindOnce(std::move(on_status), std::move(command_status)));
 
     if (promise_sync_complete_ != nullptr) {
-      promise_sync_complete_->set_value(true);
+      promise_sync_complete_->set_value(command.GetOpCode());
     }
   }
 
@@ -261,12 +279,14 @@
     }
   }
 
-  void Synchronize(std::function<void()> func) {
+  void Synchronize(std::function<void()> func, hci::OpCode op_code) {
     ASSERT(promise_sync_complete_ == nullptr);
-    promise_sync_complete_ = new std::promise<bool>();
+    promise_sync_complete_ = new std::promise<hci::OpCode>();
     auto future = promise_sync_complete_->get_future();
     func();
-    future.wait();
+    auto result = future.wait_for(std::chrono::milliseconds(100));
+    ASSERT_EQ(std::future_status::ready, result);
+    ASSERT_EQ(op_code, future.get());
     delete promise_sync_complete_;
     promise_sync_complete_ = nullptr;
   }
@@ -284,7 +304,7 @@
   void Stop() override {}
 
  private:
-  std::promise<bool>* promise_sync_complete_{nullptr};
+  std::promise<hci::OpCode>* promise_sync_complete_{nullptr};
 
   os::Handler* inquiry_result_handler_{nullptr};
   common::Callback<void(hci::EventPacketView)> inquiry_result_callback_;
@@ -354,33 +374,27 @@
   std::promise<bool>* promise_result_complete_{nullptr};
 };
 
-TEST_F(InquiryTest, Module) {
-  ScanParameters params{
-      .interval = 0,
-      .window = 0,
-  };
-  params = inquiry_module_->GetScanActivity();
-
-  ASSERT_EQ(kInitialInquiryScanInterval, params.interval);
-  ASSERT_EQ(kInitialInquiryScanWindow, params.window);
-}
+TEST_F(InquiryTest, Module) {}
 
 TEST_F(InquiryTest, SetInquiryModes) {
-  test_hci_layer_->Synchronize([this] { inquiry_module_->SetInquiryWithRssiResultMode(); });
+  test_hci_layer_->Synchronize([this] { inquiry_module_->SetInquiryWithRssiResultMode(); },
+                               hci::OpCode::WRITE_INQUIRY_MODE);
   ASSERT_EQ(hci_register_.inquiry_mode, hci::InquiryMode::RSSI);
 
-  test_hci_layer_->Synchronize([this] { inquiry_module_->SetExtendedInquiryResultMode(); });
+  test_hci_layer_->Synchronize([this] { inquiry_module_->SetExtendedInquiryResultMode(); },
+                               hci::OpCode::WRITE_INQUIRY_MODE);
   ASSERT_EQ(hci_register_.inquiry_mode, hci::InquiryMode::RSSI_OR_EXTENDED);
 
-  test_hci_layer_->Synchronize([this] { inquiry_module_->SetStandardInquiryResultMode(); });
+  test_hci_layer_->Synchronize([this] { inquiry_module_->SetStandardInquiryResultMode(); },
+                               hci::OpCode::WRITE_INQUIRY_MODE);
   ASSERT_EQ(hci_register_.inquiry_mode, hci::InquiryMode::STANDARD);
 }
 
 TEST_F(InquiryTest, SetScanType) {
-  test_hci_layer_->Synchronize([this] { inquiry_module_->SetInterlacedScan(); });
+  test_hci_layer_->Synchronize([this] { inquiry_module_->SetInterlacedScan(); }, hci::OpCode::WRITE_INQUIRY_SCAN_TYPE);
   ASSERT_EQ(hci_register_.inquiry_scan_type, hci::InquiryScanType::INTERLACED);
 
-  test_hci_layer_->Synchronize([this] { inquiry_module_->SetStandardScan(); });
+  test_hci_layer_->Synchronize([this] { inquiry_module_->SetStandardScan(); }, hci::OpCode::WRITE_INQUIRY_SCAN_TYPE);
   ASSERT_EQ(hci_register_.inquiry_scan_type, hci::InquiryScanType::STANDARD);
 }
 
@@ -390,85 +404,59 @@
       .window = 0x5678,
   };
 
-  test_hci_layer_->Synchronize([this, params] { inquiry_module_->SetScanActivity(params); });
-
-  ASSERT_EQ(0x1234, hci_register_.inquiry_scan_interval);
-  ASSERT_EQ(0x5678, hci_register_.inquiry_scan_window);
-
-  params = inquiry_module_->GetScanActivity();
-
-  EXPECT_EQ(0x1234, params.interval);
-  EXPECT_EQ(0x5678, params.window);
+  test_hci_layer_->Synchronize([this, params] { inquiry_module_->SetScanActivity(params); },
+                               hci::OpCode::WRITE_INQUIRY_SCAN_ACTIVITY);
+  ASSERT_EQ(params.interval, hci_register_.inquiry_scan_interval);
+  ASSERT_EQ(params.window, hci_register_.inquiry_scan_window);
 }
 
 TEST_F(InquiryTest, OneShotGeneralInquiry) {
-  ASSERT(!inquiry_module_->IsGeneralInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedInquiryActive());
+  uint8_t inquiry_length = 128;
+  uint8_t num_responses = 100;
+  test_hci_layer_->Synchronize(
+      [this, inquiry_length, num_responses] { inquiry_module_->StartGeneralInquiry(inquiry_length, num_responses); },
+      hci::OpCode::INQUIRY);
+  ASSERT_EQ(inquiry_length, hci_register_.inquiry_length);
+  ASSERT_EQ(num_responses, hci_register_.num_responses);
 
-  test_hci_layer_->Synchronize([this] { inquiry_module_->StartGeneralInquiry(128, 100); });
-
-  ASSERT(inquiry_module_->IsGeneralInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedInquiryActive());
-
-  test_hci_layer_->Synchronize([this] { inquiry_module_->StopInquiry(); });
-
-  ASSERT(!inquiry_module_->IsGeneralInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedInquiryActive());
+  test_hci_layer_->Synchronize([this] { inquiry_module_->StopInquiry(); }, hci::OpCode::INQUIRY_CANCEL);
 }
 
 TEST_F(InquiryTest, OneShotLimitedInquiry) {
-  ASSERT(!inquiry_module_->IsGeneralInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedInquiryActive());
+  test_hci_layer_->Synchronize([this] { inquiry_module_->StartLimitedInquiry(128, 100); }, hci::OpCode::INQUIRY);
 
-  test_hci_layer_->Synchronize([this] { inquiry_module_->StartLimitedInquiry(128, 100); });
-
-  ASSERT(!inquiry_module_->IsGeneralInquiryActive());
-  ASSERT(inquiry_module_->IsLimitedInquiryActive());
-
-  test_hci_layer_->Synchronize([this] { inquiry_module_->StopInquiry(); });
-
-  ASSERT(!inquiry_module_->IsGeneralInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedInquiryActive());
+  test_hci_layer_->Synchronize([this] { inquiry_module_->StopInquiry(); }, hci::OpCode::INQUIRY_CANCEL);
 }
 
 TEST_F(InquiryTest, GeneralPeriodicInquiry) {
-  ASSERT(!inquiry_module_->IsGeneralPeriodicInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedPeriodicInquiryActive());
+  uint8_t inquiry_length = 128;
+  uint8_t num_responses = 100;
+  uint16_t max_delay = 1100;
+  uint16_t min_delay = 200;
+  test_hci_layer_->Synchronize(
+      [this, inquiry_length, num_responses, max_delay, min_delay] {
+        inquiry_module_->StartGeneralPeriodicInquiry(inquiry_length, num_responses, max_delay, min_delay);
+      },
+      hci::OpCode::PERIODIC_INQUIRY_MODE);
+  ASSERT_EQ(inquiry_length, hci_register_.inquiry_length);
+  ASSERT_EQ(num_responses, hci_register_.num_responses);
+  ASSERT_EQ(max_delay, hci_register_.max_period_length);
+  ASSERT_EQ(min_delay, hci_register_.min_period_length);
 
-  test_hci_layer_->Synchronize([this] { inquiry_module_->StartGeneralPeriodicInquiry(128, 100, 1100, 200); });
-
-  ASSERT(inquiry_module_->IsGeneralPeriodicInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedPeriodicInquiryActive());
-
-  test_hci_layer_->Synchronize([this] { inquiry_module_->StopPeriodicInquiry(); });
-
-  ASSERT(!inquiry_module_->IsGeneralPeriodicInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedPeriodicInquiryActive());
+  test_hci_layer_->Synchronize([this] { inquiry_module_->StopPeriodicInquiry(); },
+                               hci::OpCode::EXIT_PERIODIC_INQUIRY_MODE);
 }
 
 TEST_F(InquiryTest, LimitedPeriodicInquiry) {
-  ASSERT(!inquiry_module_->IsGeneralPeriodicInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedPeriodicInquiryActive());
+  test_hci_layer_->Synchronize([this] { inquiry_module_->StartLimitedPeriodicInquiry(128, 100, 1100, 200); },
+                               hci::OpCode::PERIODIC_INQUIRY_MODE);
 
-  test_hci_layer_->Synchronize([this] { inquiry_module_->StartLimitedPeriodicInquiry(128, 100, 1100, 200); });
-
-  ASSERT(!inquiry_module_->IsGeneralPeriodicInquiryActive());
-  ASSERT(inquiry_module_->IsLimitedPeriodicInquiryActive());
-
-  test_hci_layer_->Synchronize([this] { inquiry_module_->StopPeriodicInquiry(); });
-
-  ASSERT(!inquiry_module_->IsGeneralPeriodicInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedPeriodicInquiryActive());
+  test_hci_layer_->Synchronize([this] { inquiry_module_->StopPeriodicInquiry(); },
+                               hci::OpCode::EXIT_PERIODIC_INQUIRY_MODE);
 }
 
 TEST_F(InquiryTest, InjectInquiryResult) {
-  ASSERT(!inquiry_module_->IsGeneralInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedInquiryActive());
-
-  test_hci_layer_->Synchronize([this] { inquiry_module_->StartGeneralInquiry(128, 100); });
-
-  ASSERT(inquiry_module_->IsGeneralInquiryActive());
-  ASSERT(!inquiry_module_->IsLimitedInquiryActive());
+  test_hci_layer_->Synchronize([this] { inquiry_module_->StartGeneralInquiry(128, 100); }, hci::OpCode::INQUIRY);
 
   WaitForInquiryResult([this] {
     uint8_t num_responses = 1;
@@ -482,7 +470,7 @@
                                                     clock_offset);
     test_hci_layer_->InjectInquiryResult(std::move(packet));
   });
-  test_hci_layer_->Synchronize([this] { inquiry_module_->StopInquiry(); });
+  test_hci_layer_->Synchronize([this] { inquiry_module_->StopInquiry(); }, hci::OpCode::INQUIRY_CANCEL);
 }
 
 }  // namespace
diff --git a/gd/shim/inquiry.cc b/gd/shim/inquiry.cc
index 4c3a174..20eb155 100644
--- a/gd/shim/inquiry.cc
+++ b/gd/shim/inquiry.cc
@@ -59,6 +59,15 @@
 
   impl(neighbor::InquiryModule* module);
   ~impl();
+
+  neighbor::ScanParameters params_{
+      .interval = static_cast<neighbor::ScanInterval>(0),
+      .window = static_cast<neighbor::ScanWindow>(0),
+  };
+  bool general_inquiry_active_{false};
+  bool limited_inquiry_active_{false};
+  bool general_periodic_inquiry_active_{false};
+  bool limited_periodic_inquiry_active_{false};
 };
 
 const ModuleFactory Inquiry::Factory = ModuleFactory([]() { return new Inquiry(); });
@@ -174,45 +183,53 @@
 }
 
 void Inquiry::StartGeneralInquiry(uint8_t inquiry_length, uint8_t num_responses) {
+  pimpl_->general_inquiry_active_ = true;
   return pimpl_->module_->StartGeneralInquiry(inquiry_length, num_responses);
 }
 
 void Inquiry::StartLimitedInquiry(uint8_t inquiry_length, uint8_t num_responses) {
+  pimpl_->limited_inquiry_active_ = true;
   return pimpl_->module_->StartLimitedInquiry(inquiry_length, num_responses);
 }
 
 void Inquiry::StopInquiry() {
+  pimpl_->limited_inquiry_active_ = false;
+  pimpl_->general_inquiry_active_ = false;
   return pimpl_->module_->StopInquiry();
 }
 
 bool Inquiry::IsGeneralInquiryActive() const {
-  return pimpl_->module_->IsGeneralInquiryActive();
+  return pimpl_->general_inquiry_active_;
 }
 
 bool Inquiry::IsLimitedInquiryActive() const {
-  return pimpl_->module_->IsLimitedInquiryActive();
+  return pimpl_->limited_inquiry_active_;
 }
 
 void Inquiry::StartGeneralPeriodicInquiry(uint8_t inquiry_length, uint8_t num_responses, uint16_t max_delay,
                                           uint16_t min_delay) {
+  pimpl_->general_periodic_inquiry_active_ = true;
   return pimpl_->module_->StartGeneralPeriodicInquiry(inquiry_length, num_responses, max_delay, min_delay);
 }
 
 void Inquiry::StartLimitedPeriodicInquiry(uint8_t inquiry_length, uint8_t num_responses, uint16_t max_delay,
                                           uint16_t min_delay) {
+  pimpl_->limited_periodic_inquiry_active_ = true;
   return pimpl_->module_->StartLimitedPeriodicInquiry(inquiry_length, num_responses, max_delay, min_delay);
 }
 
 void Inquiry::StopPeriodicInquiry() {
+  pimpl_->limited_periodic_inquiry_active_ = false;
+  pimpl_->general_periodic_inquiry_active_ = false;
   return pimpl_->module_->StopPeriodicInquiry();
 }
 
 bool Inquiry::IsGeneralPeriodicInquiryActive() const {
-  return pimpl_->module_->IsGeneralPeriodicInquiryActive();
+  return pimpl_->general_periodic_inquiry_active_;
 }
 
 bool Inquiry::IsLimitedPeriodicInquiryActive() const {
-  return pimpl_->module_->IsLimitedPeriodicInquiryActive();
+  return pimpl_->limited_periodic_inquiry_active_;
 }
 
 void Inquiry::SetInterlacedScan() {
@@ -224,18 +241,14 @@
 }
 
 void Inquiry::SetScanActivity(uint16_t interval, uint16_t window) {
-  neighbor::ScanParameters params{
-      .interval = static_cast<neighbor::ScanInterval>(interval),
-      .window = static_cast<neighbor::ScanWindow>(window),
-  };
-  pimpl_->module_->SetScanActivity(params);
+  pimpl_->params_.interval = interval;
+  pimpl_->params_.window = window;
+  pimpl_->module_->SetScanActivity(pimpl_->params_);
 }
 
 void Inquiry::GetScanActivity(uint16_t& interval, uint16_t& window) const {
-  neighbor::ScanParameters params = pimpl_->module_->GetScanActivity();
-
-  interval = static_cast<uint16_t>(params.interval);
-  window = static_cast<uint16_t>(params.window);
+  interval = static_cast<uint16_t>(pimpl_->params_.interval);
+  window = static_cast<uint16_t>(pimpl_->params_.window);
 }
 
 void Inquiry::SetStandardInquiryResultMode() {
diff --git a/stack/sdp/sdp_discovery.cc b/stack/sdp/sdp_discovery.cc
index 55259ca..baadd7a 100644
--- a/stack/sdp/sdp_discovery.cc
+++ b/stack/sdp/sdp_discovery.cc
@@ -334,11 +334,13 @@
  * Description      copy the raw data
  *
  *
- * Returns          void
+ * Returns          bool
+ *                          true if successful
+ *                          false if not copied
  *
  ******************************************************************************/
 #if (SDP_RAW_DATA_INCLUDED == TRUE)
-static void sdp_copy_raw_data(tCONN_CB* p_ccb, bool offset) {
+static bool sdp_copy_raw_data(tCONN_CB* p_ccb, bool offset) {
   unsigned int cpy_len, rem_len;
   uint32_t list_len;
   uint8_t* p;
@@ -358,11 +360,11 @@
       p = sdpu_get_len_from_type(p, p_end, type, &list_len);
       if (p == NULL || (p + list_len) > p_end) {
         SDP_TRACE_WARNING("%s: bad length", __func__);
-        return;
+        return false;
       }
       if ((int)cpy_len < (p - old_p)) {
         SDP_TRACE_WARNING("%s: no bytes left for data", __func__);
-        return;
+        return false;
       }
       cpy_len -= (p - old_p);
     }
@@ -377,6 +379,7 @@
     memcpy(&p_ccb->p_db->raw_data[p_ccb->p_db->raw_used], p, cpy_len);
     p_ccb->p_db->raw_used += cpy_len;
   }
+  return true;
 }
 #endif
 
@@ -430,7 +433,11 @@
     } else {
 #if (SDP_RAW_DATA_INCLUDED == TRUE)
       SDP_TRACE_WARNING("process_service_attr_rsp");
-      sdp_copy_raw_data(p_ccb, false);
+      if (!sdp_copy_raw_data(p_ccb, false)) {
+        SDP_TRACE_ERROR("sdp_copy_raw_data failed");
+        sdp_disconnect(p_ccb, SDP_ILLEGAL_PARAMETER);
+      }
+
 #endif
 
       /* Save the response in the database. Stop on any error */
@@ -632,7 +639,10 @@
 
 #if (SDP_RAW_DATA_INCLUDED == TRUE)
   SDP_TRACE_WARNING("process_service_search_attr_rsp");
-  sdp_copy_raw_data(p_ccb, true);
+  if (!sdp_copy_raw_data(p_ccb, true)) {
+    SDP_TRACE_ERROR("sdp_copy_raw_data failed");
+    sdp_disconnect(p_ccb, SDP_ILLEGAL_PARAMETER);
+  }
 #endif
 
   p = &p_ccb->rsp_list[0];
@@ -647,6 +657,7 @@
   p = sdpu_get_len_from_type(p, p + p_ccb->list_len, type, &seq_len);
   if (p == NULL || (p + seq_len) > (p + p_ccb->list_len)) {
     SDP_TRACE_WARNING("%s: bad length", __func__);
+    sdp_disconnect(p_ccb, SDP_ILLEGAL_PARAMETER);
     return;
   }
   p_end = &p_ccb->rsp_list[p_ccb->list_len];