Merge "audio: Skip AudioModuleRemoteSubmixTest on Android U" into main
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 25246d8..92cafbd 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -11,6 +11,9 @@
     },
     {
       "name": "VtsHalTvInputV1_0TargetTest"
+    },
+    {
+      "name": "CtsStrictJavaPackagesTestCases"
     }
   ],
   "auto-presubmit": [
diff --git a/audio/aidl/TEST_MAPPING b/audio/aidl/TEST_MAPPING
index 2b6207e..b5fcd86 100644
--- a/audio/aidl/TEST_MAPPING
+++ b/audio/aidl/TEST_MAPPING
@@ -55,6 +55,29 @@
   "postsubmit": [
     {
       "name": "VtsHalSpatializerTargetTest"
+    },
+    {
+      "name": "audiorecord_tests"
+    },
+    {
+      "name": "audioeffect_tests"
+    },
+    {
+      "name": "audiorouting_tests"
+    },
+    {
+      "name": "trackplayerbase_tests"
+    },
+    {
+      "name": "audiosystem_tests"
+    },
+    {
+      "name": "CtsVirtualDevicesTestCases",
+      "options" : [
+        {
+          "include-filter": "android.virtualdevice.cts.VirtualAudioTest"
+        }
+      ]
     }
   ]
 }
diff --git a/audio/aidl/aidl_api/android.hardware.audio.effect/current/android/hardware/audio/effect/IEffect.aidl b/audio/aidl/aidl_api/android.hardware.audio.effect/current/android/hardware/audio/effect/IEffect.aidl
index 8c196e7..a1b00be 100644
--- a/audio/aidl/aidl_api/android.hardware.audio.effect/current/android/hardware/audio/effect/IEffect.aidl
+++ b/audio/aidl/aidl_api/android.hardware.audio.effect/current/android/hardware/audio/effect/IEffect.aidl
@@ -41,6 +41,7 @@
   android.hardware.audio.effect.State getState();
   void setParameter(in android.hardware.audio.effect.Parameter param);
   android.hardware.audio.effect.Parameter getParameter(in android.hardware.audio.effect.Parameter.Id paramId);
+  android.hardware.audio.effect.IEffect.OpenEffectReturn reopen();
   @FixedSize @VintfStability
   parcelable Status {
     int status;
diff --git a/audio/aidl/android/hardware/audio/effect/IEffect.aidl b/audio/aidl/android/hardware/audio/effect/IEffect.aidl
index 6097f34..266adec 100644
--- a/audio/aidl/android/hardware/audio/effect/IEffect.aidl
+++ b/audio/aidl/android/hardware/audio/effect/IEffect.aidl
@@ -54,7 +54,16 @@
     }
 
     /**
-     * Return data structure of IEffect.open() interface.
+     * Return data structure of the IEffect.open() and IEffect.reopen() method.
+     *
+     * Contains Fast Message Queues (FMQs) for effect processing status and input/output data.
+     * The status FMQ remains valid and unchanged after opening, while input/output data FMQs can be
+     * modified with changes in input/output AudioConfig. If reallocation of data FMQ is necessary,
+     * the effect instance must release the existing data FMQs to signal the need to the audio
+     * framework.
+     * When the audio framework encounters a valid status FMQ and invalid input/output data FMQs,
+     * it must invoke the IEffect.reopen() method to request the effect instance to reallocate
+     * the FMQ and return to the audio framework.
      */
     @VintfStability
     parcelable OpenEffectReturn {
@@ -97,7 +106,7 @@
      * client responsibility to make sure all parameter/buffer is correct if client wants to reopen
      * a closed instance.
      *
-     * Effect instance close interface should always succeed unless:
+     * Effect instance close method should always succeed unless:
      * 1. The effect instance is not in a proper state to be closed, for example it's still in
      * State::PROCESSING state.
      * 2. There is system/hardware related failure when close.
@@ -154,8 +163,8 @@
     /**
      * Get a parameter from the effect instance with parameter ID.
      *
-     * This interface must return the current parameter of the effect instance, if no parameter
-     * has been set by client yet, the default value must be returned.
+     * This method must return the current parameter of the effect instance, if no parameter has
+     * been set by client yet, the default value must be returned.
      *
      * Must be available for the effect instance after open().
      *
@@ -165,4 +174,24 @@
      * @throws EX_ILLEGAL_ARGUMENT if the effect instance receive unsupported parameter tag.
      */
     Parameter getParameter(in Parameter.Id paramId);
+
+    /**
+     * Reopen the effect instance, keeping all previous parameters unchanged, and reallocate only
+     * the Fast Message Queues (FMQs) allocated during the open time as needed.
+     *
+     * When the audio framework encounters a valid status FMQ and invalid data FMQ(s), it calls
+     * this method to reopen the effect and request the latest data FMQ.
+     * Upon receiving this call, if the effect instance's data FMQ(s) is invalid, it must reallocate
+     * the necessary data FMQ(s) and return them to the audio framework. All previous parameters and
+     * states keep unchanged.
+     * Once the audio framework successfully completes the call, it must validate the returned FMQs,
+     * deprecate all old FMQs, and exclusively use the FMQs returned from this method.
+     *
+     * @return The reallocated data FMQ and the original status FMQ.
+     *
+     * @throws EX_ILLEGAL_STATE if the effect instance is not in a proper state  to reallocate FMQ.
+     * This may occur if the effect instance has already been closed or if there is no need to
+     * update any data FMQ.
+     */
+    OpenEffectReturn reopen();
 }
diff --git a/audio/aidl/android/hardware/audio/effect/state.gv b/audio/aidl/android/hardware/audio/effect/state.gv
index ce369ba..22c70c8 100644
--- a/audio/aidl/android/hardware/audio/effect/state.gv
+++ b/audio/aidl/android/hardware/audio/effect/state.gv
@@ -31,6 +31,8 @@
     IDLE -> INIT[label = "IEffect.close()"];
 
     INIT -> INIT[label = "IEffect.getState\nIEffect.getDescriptor"];
-    IDLE -> IDLE[label = "IEffect.getParameter\nIEffect.setParameter\nIEffect.getDescriptor\nIEffect.command(RESET)"];
-    PROCESSING -> PROCESSING[label = "IEffect.getParameter\nIEffect.setParameter\nIEffect.getDescriptor"];
+    IDLE -> IDLE[label = "IEffect.getParameter\nIEffect.setParameter\nIEffect.getDescriptor\nIEffect.command(RESET)\nIEffect.reopen"];
+    PROCESSING
+            -> PROCESSING
+                    [label = "IEffect.getParameter\nIEffect.setParameter\nIEffect.getDescriptor\nIEffect.reopen"];
 }
diff --git a/audio/aidl/default/Android.bp b/audio/aidl/default/Android.bp
index 6d0b95e..20682d6 100644
--- a/audio/aidl/default/Android.bp
+++ b/audio/aidl/default/Android.bp
@@ -226,6 +226,7 @@
 filegroup {
     name: "effectCommonFile",
     srcs: [
+        "EffectContext.cpp",
         "EffectThread.cpp",
         "EffectImpl.cpp",
     ],
diff --git a/audio/aidl/default/EffectContext.cpp b/audio/aidl/default/EffectContext.cpp
new file mode 100644
index 0000000..2e12918
--- /dev/null
+++ b/audio/aidl/default/EffectContext.cpp
@@ -0,0 +1,227 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <memory>
+#define LOG_TAG "AHAL_EffectContext"
+#include "effect-impl/EffectContext.h"
+#include "include/effect-impl/EffectTypes.h"
+
+using aidl::android::hardware::audio::common::getChannelCount;
+using aidl::android::hardware::audio::common::getFrameSizeInBytes;
+using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::media::audio::common::PcmType;
+using ::android::hardware::EventFlag;
+
+namespace aidl::android::hardware::audio::effect {
+
+EffectContext::EffectContext(size_t statusDepth, const Parameter::Common& common) {
+    LOG_ALWAYS_FATAL_IF(RetCode::SUCCESS != setCommon(common), "illegalCommonParameter");
+
+    // in/outBuffer size in float (FMQ data format defined for DataMQ)
+    size_t inBufferSizeInFloat = common.input.frameCount * mInputFrameSize / sizeof(float);
+    size_t outBufferSizeInFloat = common.output.frameCount * mOutputFrameSize / sizeof(float);
+
+    // only status FMQ use the EventFlag
+    mStatusMQ = std::make_shared<StatusMQ>(statusDepth, true /*configureEventFlagWord*/);
+    mInputMQ = std::make_shared<DataMQ>(inBufferSizeInFloat);
+    mOutputMQ = std::make_shared<DataMQ>(outBufferSizeInFloat);
+
+    if (!mStatusMQ->isValid() || !mInputMQ->isValid() || !mOutputMQ->isValid()) {
+        LOG(ERROR) << __func__ << " created invalid FMQ";
+    }
+
+    ::android::status_t status =
+            EventFlag::createEventFlag(mStatusMQ->getEventFlagWord(), &mEfGroup);
+    LOG_ALWAYS_FATAL_IF(status != ::android::OK || !mEfGroup, " create EventFlagGroup failed ");
+    mWorkBuffer.reserve(std::max(inBufferSizeInFloat, outBufferSizeInFloat));
+}
+
+// reset buffer status by abandon input data in FMQ
+void EffectContext::resetBuffer() {
+    auto buffer = static_cast<float*>(mWorkBuffer.data());
+    std::vector<IEffect::Status> status(mStatusMQ->availableToRead());
+    if (mInputMQ) {
+        mInputMQ->read(buffer, mInputMQ->availableToRead());
+    }
+}
+
+void EffectContext::dupeFmqWithReopen(IEffect::OpenEffectReturn* effectRet) {
+    if (!mInputMQ) {
+        mInputMQ = std::make_shared<DataMQ>(mCommon.input.frameCount * mInputFrameSize /
+                                            sizeof(float));
+    }
+    if (!mOutputMQ) {
+        mOutputMQ = std::make_shared<DataMQ>(mCommon.output.frameCount * mOutputFrameSize /
+                                             sizeof(float));
+    }
+    dupeFmq(effectRet);
+}
+
+void EffectContext::dupeFmq(IEffect::OpenEffectReturn* effectRet) {
+    if (effectRet) {
+        effectRet->statusMQ = mStatusMQ->dupeDesc();
+        effectRet->inputDataMQ = mInputMQ->dupeDesc();
+        effectRet->outputDataMQ = mOutputMQ->dupeDesc();
+    }
+}
+
+float* EffectContext::getWorkBuffer() {
+    return static_cast<float*>(mWorkBuffer.data());
+}
+
+std::shared_ptr<EffectContext::StatusMQ> EffectContext::getStatusFmq() const {
+    return mStatusMQ;
+}
+
+std::shared_ptr<EffectContext::DataMQ> EffectContext::getInputDataFmq() const {
+    return mInputMQ;
+}
+
+std::shared_ptr<EffectContext::DataMQ> EffectContext::getOutputDataFmq() const {
+    return mOutputMQ;
+}
+
+size_t EffectContext::getInputFrameSize() const {
+    return mInputFrameSize;
+}
+
+size_t EffectContext::getOutputFrameSize() const {
+    return mOutputFrameSize;
+}
+
+int EffectContext::getSessionId() const {
+    return mCommon.session;
+}
+
+int EffectContext::getIoHandle() const {
+    return mCommon.ioHandle;
+}
+
+RetCode EffectContext::setOutputDevice(
+        const std::vector<aidl::android::media::audio::common::AudioDeviceDescription>& device) {
+    mOutputDevice = device;
+    return RetCode::SUCCESS;
+}
+
+std::vector<aidl::android::media::audio::common::AudioDeviceDescription>
+EffectContext::getOutputDevice() {
+    return mOutputDevice;
+}
+
+RetCode EffectContext::setAudioMode(const aidl::android::media::audio::common::AudioMode& mode) {
+    mMode = mode;
+    return RetCode::SUCCESS;
+}
+aidl::android::media::audio::common::AudioMode EffectContext::getAudioMode() {
+    return mMode;
+}
+
+RetCode EffectContext::setAudioSource(
+        const aidl::android::media::audio::common::AudioSource& source) {
+    mSource = source;
+    return RetCode::SUCCESS;
+}
+
+aidl::android::media::audio::common::AudioSource EffectContext::getAudioSource() {
+    return mSource;
+}
+
+RetCode EffectContext::setVolumeStereo(const Parameter::VolumeStereo& volumeStereo) {
+    mVolumeStereo = volumeStereo;
+    return RetCode::SUCCESS;
+}
+
+Parameter::VolumeStereo EffectContext::getVolumeStereo() {
+    return mVolumeStereo;
+}
+
+RetCode EffectContext::setCommon(const Parameter::Common& common) {
+    LOG(VERBOSE) << __func__ << common.toString();
+    auto& input = common.input;
+    auto& output = common.output;
+
+    if (input.base.format.pcm != aidl::android::media::audio::common::PcmType::FLOAT_32_BIT ||
+        output.base.format.pcm != aidl::android::media::audio::common::PcmType::FLOAT_32_BIT) {
+        LOG(ERROR) << __func__ << " illegal IO, input "
+                   << ::android::internal::ToString(input.base.format) << ", output "
+                   << ::android::internal::ToString(output.base.format);
+        return RetCode::ERROR_ILLEGAL_PARAMETER;
+    }
+
+    if (auto ret = updateIOFrameSize(common); ret != RetCode::SUCCESS) {
+        return ret;
+    }
+
+    mInputChannelCount = getChannelCount(input.base.channelMask);
+    mOutputChannelCount = getChannelCount(output.base.channelMask);
+    if (mInputChannelCount == 0 || mOutputChannelCount == 0) {
+        LOG(ERROR) << __func__ << " illegal channel count input " << mInputChannelCount
+                   << ", output " << mOutputChannelCount;
+        return RetCode::ERROR_ILLEGAL_PARAMETER;
+    }
+
+    mCommon = common;
+    return RetCode::SUCCESS;
+}
+
+Parameter::Common EffectContext::getCommon() {
+    LOG(VERBOSE) << __func__ << mCommon.toString();
+    return mCommon;
+}
+
+EventFlag* EffectContext::getStatusEventFlag() {
+    return mEfGroup;
+}
+
+RetCode EffectContext::updateIOFrameSize(const Parameter::Common& common) {
+    const auto iFrameSize = ::aidl::android::hardware::audio::common::getFrameSizeInBytes(
+            common.input.base.format, common.input.base.channelMask);
+    const auto oFrameSize = ::aidl::android::hardware::audio::common::getFrameSizeInBytes(
+            common.output.base.format, common.output.base.channelMask);
+
+    bool needUpdateMq = false;
+    if (mInputMQ &&
+        (mInputFrameSize != iFrameSize || mCommon.input.frameCount != common.input.frameCount)) {
+        mInputMQ.reset();
+        needUpdateMq = true;
+    }
+    if (mOutputMQ &&
+        (mOutputFrameSize != oFrameSize || mCommon.output.frameCount != common.output.frameCount)) {
+        mOutputMQ.reset();
+        needUpdateMq = true;
+    }
+    mInputFrameSize = iFrameSize;
+    mOutputFrameSize = oFrameSize;
+    if (needUpdateMq) {
+        return notifyDataMqUpdate();
+    }
+    return RetCode::SUCCESS;
+}
+
+RetCode EffectContext::notifyDataMqUpdate() {
+    if (!mEfGroup) {
+        LOG(ERROR) << __func__ << ": invalid EventFlag group";
+        return RetCode::ERROR_EVENT_FLAG_ERROR;
+    }
+
+    if (const auto ret = mEfGroup->wake(kEventFlagDataMqUpdate); ret != ::android::OK) {
+        LOG(ERROR) << __func__ << ": wake failure with ret " << ret;
+        return RetCode::ERROR_EVENT_FLAG_ERROR;
+    }
+    LOG(DEBUG) << __func__ << " : signal client for reopen";
+    return RetCode::SUCCESS;
+}
+}  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/EffectImpl.cpp b/audio/aidl/default/EffectImpl.cpp
index c81c731..b76269a 100644
--- a/audio/aidl/default/EffectImpl.cpp
+++ b/audio/aidl/default/EffectImpl.cpp
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <memory>
 #define LOG_TAG "AHAL_EffectImpl"
 #include "effect-impl/EffectImpl.h"
 #include "effect-impl/EffectTypes.h"
@@ -22,6 +23,7 @@
 using aidl::android::hardware::audio::effect::IEffect;
 using aidl::android::hardware::audio::effect::State;
 using aidl::android::media::audio::common::PcmType;
+using ::android::hardware::EventFlag;
 
 extern "C" binder_exception_t destroyEffect(const std::shared_ptr<IEffect>& instanceSp) {
     State state;
@@ -45,40 +47,62 @@
     RETURN_IF(common.input.base.format.pcm != common.output.base.format.pcm ||
                       common.input.base.format.pcm != PcmType::FLOAT_32_BIT,
               EX_ILLEGAL_ARGUMENT, "dataMustBe32BitsFloat");
+    std::lock_guard lg(mImplMutex);
     RETURN_OK_IF(mState != State::INIT);
-    auto context = createContext(common);
-    RETURN_IF(!context, EX_NULL_POINTER, "createContextFailed");
+    mImplContext = createContext(common);
+    RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext");
+    mEventFlag = mImplContext->getStatusEventFlag();
 
     if (specific.has_value()) {
         RETURN_IF_ASTATUS_NOT_OK(setParameterSpecific(specific.value()), "setSpecParamErr");
     }
 
     mState = State::IDLE;
-    context->dupeFmq(ret);
-    RETURN_IF(createThread(context, getEffectName()) != RetCode::SUCCESS, EX_UNSUPPORTED_OPERATION,
+    mImplContext->dupeFmq(ret);
+    RETURN_IF(createThread(getEffectName()) != RetCode::SUCCESS, EX_UNSUPPORTED_OPERATION,
               "FailedToCreateWorker");
     return ndk::ScopedAStatus::ok();
 }
 
-ndk::ScopedAStatus EffectImpl::close() {
-    RETURN_OK_IF(mState == State::INIT);
-    RETURN_IF(mState == State::PROCESSING, EX_ILLEGAL_STATE, "closeAtProcessing");
+ndk::ScopedAStatus EffectImpl::reopen(OpenEffectReturn* ret) {
+    std::lock_guard lg(mImplMutex);
+    RETURN_IF(mState == State::INIT, EX_ILLEGAL_STATE, "alreadyClosed");
 
+    // TODO: b/302036943 add reopen implementation
+    RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext");
+    mImplContext->dupeFmqWithReopen(ret);
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus EffectImpl::close() {
+    {
+        std::lock_guard lg(mImplMutex);
+        RETURN_OK_IF(mState == State::INIT);
+        RETURN_IF(mState == State::PROCESSING, EX_ILLEGAL_STATE, "closeAtProcessing");
+        mState = State::INIT;
+    }
+
+    RETURN_IF(notifyEventFlag(kEventFlagNotEmpty) != RetCode::SUCCESS, EX_ILLEGAL_STATE,
+              "notifyEventFlagFailed");
     // stop the worker thread, ignore the return code
     RETURN_IF(destroyThread() != RetCode::SUCCESS, EX_UNSUPPORTED_OPERATION,
               "FailedToDestroyWorker");
-    mState = State::INIT;
-    RETURN_IF(releaseContext() != RetCode::SUCCESS, EX_UNSUPPORTED_OPERATION,
-              "FailedToCreateWorker");
+
+    {
+        std::lock_guard lg(mImplMutex);
+        releaseContext();
+        mImplContext.reset();
+    }
 
     LOG(DEBUG) << getEffectName() << __func__;
     return ndk::ScopedAStatus::ok();
 }
 
 ndk::ScopedAStatus EffectImpl::setParameter(const Parameter& param) {
+    std::lock_guard lg(mImplMutex);
     LOG(VERBOSE) << getEffectName() << __func__ << " with: " << param.toString();
 
-    const auto tag = param.getTag();
+    const auto& tag = param.getTag();
     switch (tag) {
         case Parameter::common:
         case Parameter::deviceDescription:
@@ -100,8 +124,8 @@
 }
 
 ndk::ScopedAStatus EffectImpl::getParameter(const Parameter::Id& id, Parameter* param) {
-    auto tag = id.getTag();
-    switch (tag) {
+    std::lock_guard lg(mImplMutex);
+    switch (id.getTag()) {
         case Parameter::Id::commonTag: {
             RETURN_IF_ASTATUS_NOT_OK(getParameterCommon(id.get<Parameter::Id::commonTag>(), param),
                                      "CommonParamNotSupported");
@@ -121,30 +145,30 @@
 }
 
 ndk::ScopedAStatus EffectImpl::setParameterCommon(const Parameter& param) {
-    auto context = getContext();
-    RETURN_IF(!context, EX_NULL_POINTER, "nullContext");
+    RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext");
 
-    auto tag = param.getTag();
+    const auto& tag = param.getTag();
     switch (tag) {
         case Parameter::common:
-            RETURN_IF(context->setCommon(param.get<Parameter::common>()) != RetCode::SUCCESS,
+            RETURN_IF(mImplContext->setCommon(param.get<Parameter::common>()) != RetCode::SUCCESS,
                       EX_ILLEGAL_ARGUMENT, "setCommFailed");
             break;
         case Parameter::deviceDescription:
-            RETURN_IF(context->setOutputDevice(param.get<Parameter::deviceDescription>()) !=
+            RETURN_IF(mImplContext->setOutputDevice(param.get<Parameter::deviceDescription>()) !=
                               RetCode::SUCCESS,
                       EX_ILLEGAL_ARGUMENT, "setDeviceFailed");
             break;
         case Parameter::mode:
-            RETURN_IF(context->setAudioMode(param.get<Parameter::mode>()) != RetCode::SUCCESS,
+            RETURN_IF(mImplContext->setAudioMode(param.get<Parameter::mode>()) != RetCode::SUCCESS,
                       EX_ILLEGAL_ARGUMENT, "setModeFailed");
             break;
         case Parameter::source:
-            RETURN_IF(context->setAudioSource(param.get<Parameter::source>()) != RetCode::SUCCESS,
+            RETURN_IF(mImplContext->setAudioSource(param.get<Parameter::source>()) !=
+                              RetCode::SUCCESS,
                       EX_ILLEGAL_ARGUMENT, "setSourceFailed");
             break;
         case Parameter::volumeStereo:
-            RETURN_IF(context->setVolumeStereo(param.get<Parameter::volumeStereo>()) !=
+            RETURN_IF(mImplContext->setVolumeStereo(param.get<Parameter::volumeStereo>()) !=
                               RetCode::SUCCESS,
                       EX_ILLEGAL_ARGUMENT, "setVolumeStereoFailed");
             break;
@@ -159,28 +183,27 @@
 }
 
 ndk::ScopedAStatus EffectImpl::getParameterCommon(const Parameter::Tag& tag, Parameter* param) {
-    auto context = getContext();
-    RETURN_IF(!context, EX_NULL_POINTER, "nullContext");
+    RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext");
 
     switch (tag) {
         case Parameter::common: {
-            param->set<Parameter::common>(context->getCommon());
+            param->set<Parameter::common>(mImplContext->getCommon());
             break;
         }
         case Parameter::deviceDescription: {
-            param->set<Parameter::deviceDescription>(context->getOutputDevice());
+            param->set<Parameter::deviceDescription>(mImplContext->getOutputDevice());
             break;
         }
         case Parameter::mode: {
-            param->set<Parameter::mode>(context->getAudioMode());
+            param->set<Parameter::mode>(mImplContext->getAudioMode());
             break;
         }
         case Parameter::source: {
-            param->set<Parameter::source>(context->getAudioSource());
+            param->set<Parameter::source>(mImplContext->getAudioSource());
             break;
         }
         case Parameter::volumeStereo: {
-            param->set<Parameter::volumeStereo>(context->getVolumeStereo());
+            param->set<Parameter::volumeStereo>(mImplContext->getVolumeStereo());
             break;
         }
         default: {
@@ -192,30 +215,34 @@
     return ndk::ScopedAStatus::ok();
 }
 
-ndk::ScopedAStatus EffectImpl::getState(State* state) {
+ndk::ScopedAStatus EffectImpl::getState(State* state) NO_THREAD_SAFETY_ANALYSIS {
     *state = mState;
     return ndk::ScopedAStatus::ok();
 }
 
 ndk::ScopedAStatus EffectImpl::command(CommandId command) {
-    RETURN_IF(mState == State::INIT, EX_ILLEGAL_STATE, "CommandStateError");
+    std::lock_guard lg(mImplMutex);
+    RETURN_IF(mState == State::INIT, EX_ILLEGAL_STATE, "instanceNotOpen");
     LOG(DEBUG) << getEffectName() << __func__ << ": receive command: " << toString(command)
                << " at state " << toString(mState);
 
     switch (command) {
         case CommandId::START:
-            RETURN_IF(mState == State::INIT, EX_ILLEGAL_STATE, "instanceNotOpen");
             RETURN_OK_IF(mState == State::PROCESSING);
             RETURN_IF_ASTATUS_NOT_OK(commandImpl(command), "commandImplFailed");
-            startThread();
             mState = State::PROCESSING;
+            RETURN_IF(notifyEventFlag(kEventFlagNotEmpty) != RetCode::SUCCESS, EX_ILLEGAL_STATE,
+                      "notifyEventFlagFailed");
+            startThread();
             break;
         case CommandId::STOP:
         case CommandId::RESET:
             RETURN_OK_IF(mState == State::IDLE);
+            mState = State::IDLE;
+            RETURN_IF(notifyEventFlag(kEventFlagNotEmpty) != RetCode::SUCCESS, EX_ILLEGAL_STATE,
+                      "notifyEventFlagFailed");
             stopThread();
             RETURN_IF_ASTATUS_NOT_OK(commandImpl(command), "commandImplFailed");
-            mState = State::IDLE;
             break;
         default:
             LOG(ERROR) << getEffectName() << __func__ << " instance still processing";
@@ -227,19 +254,41 @@
 }
 
 ndk::ScopedAStatus EffectImpl::commandImpl(CommandId command) {
-    auto context = getContext();
-    RETURN_IF(!context, EX_NULL_POINTER, "nullContext");
+    RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext");
     if (command == CommandId::RESET) {
-        context->resetBuffer();
+        mImplContext->resetBuffer();
     }
     return ndk::ScopedAStatus::ok();
 }
 
+std::shared_ptr<EffectContext> EffectImpl::createContext(const Parameter::Common& common) {
+    return std::make_shared<EffectContext>(1 /* statusMqDepth */, common);
+}
+
+RetCode EffectImpl::releaseContext() {
+    if (mImplContext) {
+        mImplContext.reset();
+    }
+    return RetCode::SUCCESS;
+}
+
 void EffectImpl::cleanUp() {
     command(CommandId::STOP);
     close();
 }
 
+RetCode EffectImpl::notifyEventFlag(uint32_t flag) {
+    if (!mEventFlag) {
+        LOG(ERROR) << getEffectName() << __func__ << ": StatusEventFlag invalid";
+        return RetCode::ERROR_EVENT_FLAG_ERROR;
+    }
+    if (const auto ret = mEventFlag->wake(flag); ret != ::android::OK) {
+        LOG(ERROR) << getEffectName() << __func__ << ": wake failure with ret " << ret;
+        return RetCode::ERROR_EVENT_FLAG_ERROR;
+    }
+    return RetCode::SUCCESS;
+}
+
 IEffect::Status EffectImpl::status(binder_status_t status, size_t consumed, size_t produced) {
     IEffect::Status ret;
     ret.status = status;
@@ -248,6 +297,48 @@
     return ret;
 }
 
+void EffectImpl::process() {
+    /**
+     * wait for the EventFlag without lock, it's ok because the mEfGroup pointer will not change
+     * in the life cycle of workerThread (threadLoop).
+     */
+    uint32_t efState = 0;
+    if (!mEventFlag ||
+        ::android::OK != mEventFlag->wait(kEventFlagNotEmpty, &efState, 0 /* no timeout */,
+                                          true /* retry */) ||
+        !(efState & kEventFlagNotEmpty)) {
+        LOG(ERROR) << getEffectName() << __func__ << ": StatusEventFlag - " << mEventFlag
+                   << " efState - " << std::hex << efState;
+        return;
+    }
+
+    {
+        std::lock_guard lg(mImplMutex);
+        if (mState != State::PROCESSING) {
+            LOG(DEBUG) << getEffectName() << " skip process in state: " << toString(mState);
+            return;
+        }
+        RETURN_VALUE_IF(!mImplContext, void(), "nullContext");
+        auto statusMQ = mImplContext->getStatusFmq();
+        auto inputMQ = mImplContext->getInputDataFmq();
+        auto outputMQ = mImplContext->getOutputDataFmq();
+        auto buffer = mImplContext->getWorkBuffer();
+        if (!inputMQ || !outputMQ) {
+            return;
+        }
+
+        auto processSamples = inputMQ->availableToRead();
+        if (processSamples) {
+            inputMQ->read(buffer, processSamples);
+            IEffect::Status status = effectProcessImpl(buffer, buffer, processSamples);
+            outputMQ->write(buffer, status.fmqProduced);
+            statusMQ->writeBlocking(&status, 1);
+            LOG(VERBOSE) << getEffectName() << __func__ << ": done processing, effect consumed "
+                         << status.fmqConsumed << " produced " << status.fmqProduced;
+        }
+    }
+}
+
 // A placeholder processing implementation to copy samples from input to output
 IEffect::Status EffectImpl::effectProcessImpl(float* in, float* out, int samples) {
     for (int i = 0; i < samples; i++) {
diff --git a/audio/aidl/default/EffectThread.cpp b/audio/aidl/default/EffectThread.cpp
index 47ba9f4..fdd4803 100644
--- a/audio/aidl/default/EffectThread.cpp
+++ b/audio/aidl/default/EffectThread.cpp
@@ -25,8 +25,6 @@
 #include "effect-impl/EffectThread.h"
 #include "effect-impl/EffectTypes.h"
 
-using ::android::hardware::EventFlag;
-
 namespace aidl::android::hardware::audio::effect {
 
 EffectThread::EffectThread() {
@@ -38,31 +36,18 @@
     LOG(DEBUG) << __func__ << " done";
 }
 
-RetCode EffectThread::createThread(std::shared_ptr<EffectContext> context, const std::string& name,
-                                   int priority) {
+RetCode EffectThread::createThread(const std::string& name, int priority) {
     if (mThread.joinable()) {
         LOG(WARNING) << mName << __func__ << " thread already created, no-op";
         return RetCode::SUCCESS;
     }
+
     mName = name;
     mPriority = priority;
     {
         std::lock_guard lg(mThreadMutex);
         mStop = true;
         mExit = false;
-        mThreadContext = std::move(context);
-        auto statusMQ = mThreadContext->getStatusFmq();
-        EventFlag* efGroup = nullptr;
-        ::android::status_t status =
-                EventFlag::createEventFlag(statusMQ->getEventFlagWord(), &efGroup);
-        if (status != ::android::OK || !efGroup) {
-            LOG(ERROR) << mName << __func__ << " create EventFlagGroup failed " << status
-                       << " efGroup " << efGroup;
-            return RetCode::ERROR_THREAD;
-        }
-        mEfGroup.reset(efGroup);
-        // kickoff and wait for commands (CommandId::START/STOP) or IEffect.close from client
-        mEfGroup->wake(kEventFlagNotEmpty);
     }
 
     mThread = std::thread(&EffectThread::threadLoop, this);
@@ -75,16 +60,12 @@
         std::lock_guard lg(mThreadMutex);
         mStop = mExit = true;
     }
-    mCv.notify_one();
 
+    mCv.notify_one();
     if (mThread.joinable()) {
         mThread.join();
     }
 
-    {
-        std::lock_guard lg(mThreadMutex);
-        mThreadContext.reset();
-    }
     LOG(DEBUG) << mName << __func__;
     return RetCode::SUCCESS;
 }
@@ -96,7 +77,6 @@
         mCv.notify_one();
     }
 
-    mEfGroup->wake(kEventFlagNotEmpty);
     LOG(DEBUG) << mName << __func__;
     return RetCode::SUCCESS;
 }
@@ -108,7 +88,6 @@
         mCv.notify_one();
     }
 
-    mEfGroup->wake(kEventFlagNotEmpty);
     LOG(DEBUG) << mName << __func__;
     return RetCode::SUCCESS;
 }
@@ -117,13 +96,6 @@
     pthread_setname_np(pthread_self(), mName.substr(0, kMaxTaskNameLen - 1).c_str());
     setpriority(PRIO_PROCESS, 0, mPriority);
     while (true) {
-        /**
-         * wait for the EventFlag without lock, it's ok because the mEfGroup pointer will not change
-         * in the life cycle of workerThread (threadLoop).
-         */
-        uint32_t efState = 0;
-        mEfGroup->wait(kEventFlagNotEmpty, &efState);
-
         {
             std::unique_lock l(mThreadMutex);
             ::android::base::ScopedLockAssertion lock_assertion(mThreadMutex);
@@ -132,27 +104,8 @@
                 LOG(INFO) << __func__ << " EXIT!";
                 return;
             }
-            process_l();
         }
-    }
-}
-
-void EffectThread::process_l() {
-    RETURN_VALUE_IF(!mThreadContext, void(), "nullContext");
-
-    auto statusMQ = mThreadContext->getStatusFmq();
-    auto inputMQ = mThreadContext->getInputDataFmq();
-    auto outputMQ = mThreadContext->getOutputDataFmq();
-    auto buffer = mThreadContext->getWorkBuffer();
-
-    auto processSamples = inputMQ->availableToRead();
-    if (processSamples) {
-        inputMQ->read(buffer, processSamples);
-        IEffect::Status status = effectProcessImpl(buffer, buffer, processSamples);
-        outputMQ->write(buffer, status.fmqProduced);
-        statusMQ->writeBlocking(&status, 1);
-        LOG(VERBOSE) << mName << __func__ << ": done processing, effect consumed "
-                     << status.fmqConsumed << " produced " << status.fmqProduced;
+        process();
     }
 }
 
diff --git a/audio/aidl/default/acousticEchoCanceler/AcousticEchoCancelerSw.cpp b/audio/aidl/default/acousticEchoCanceler/AcousticEchoCancelerSw.cpp
index 5e18f1b..be0927c 100644
--- a/audio/aidl/default/acousticEchoCanceler/AcousticEchoCancelerSw.cpp
+++ b/audio/aidl/default/acousticEchoCanceler/AcousticEchoCancelerSw.cpp
@@ -168,10 +168,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> AcousticEchoCancelerSw::getContext() {
-    return mContext;
-}
-
 RetCode AcousticEchoCancelerSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/acousticEchoCanceler/AcousticEchoCancelerSw.h b/audio/aidl/default/acousticEchoCanceler/AcousticEchoCancelerSw.h
index 73cf42b..95738f8 100644
--- a/audio/aidl/default/acousticEchoCanceler/AcousticEchoCancelerSw.h
+++ b/audio/aidl/default/acousticEchoCanceler/AcousticEchoCancelerSw.h
@@ -52,21 +52,23 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
     std::string getEffectName() override { return kEffectName; };
     IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
 
   private:
     static const std::vector<Range::AcousticEchoCancelerRange> kRanges;
-    std::shared_ptr<AcousticEchoCancelerSwContext> mContext;
+    std::shared_ptr<AcousticEchoCancelerSwContext> mContext GUARDED_BY(mImplMutex);
     ndk::ScopedAStatus getParameterAcousticEchoCanceler(const AcousticEchoCanceler::Tag& tag,
-                                                        Parameter::Specific* specific);
+                                                        Parameter::Specific* specific)
+            REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/automaticGainControlV1/AutomaticGainControlV1Sw.cpp b/audio/aidl/default/automaticGainControlV1/AutomaticGainControlV1Sw.cpp
index ce10ae1..d865b7e 100644
--- a/audio/aidl/default/automaticGainControlV1/AutomaticGainControlV1Sw.cpp
+++ b/audio/aidl/default/automaticGainControlV1/AutomaticGainControlV1Sw.cpp
@@ -177,10 +177,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> AutomaticGainControlV1Sw::getContext() {
-    return mContext;
-}
-
 RetCode AutomaticGainControlV1Sw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/automaticGainControlV1/AutomaticGainControlV1Sw.h b/audio/aidl/default/automaticGainControlV1/AutomaticGainControlV1Sw.h
index 7d2a69f..76b91ae 100644
--- a/audio/aidl/default/automaticGainControlV1/AutomaticGainControlV1Sw.h
+++ b/audio/aidl/default/automaticGainControlV1/AutomaticGainControlV1Sw.h
@@ -53,21 +53,24 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
     std::string getEffectName() override { return kEffectName; };
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
 
   private:
     static const std::vector<Range::AutomaticGainControlV1Range> kRanges;
-    std::shared_ptr<AutomaticGainControlV1SwContext> mContext;
+    std::shared_ptr<AutomaticGainControlV1SwContext> mContext GUARDED_BY(mImplMutex);
     ndk::ScopedAStatus getParameterAutomaticGainControlV1(const AutomaticGainControlV1::Tag& tag,
-                                                          Parameter::Specific* specific);
+                                                          Parameter::Specific* specific)
+            REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/automaticGainControlV2/AutomaticGainControlV2Sw.cpp b/audio/aidl/default/automaticGainControlV2/AutomaticGainControlV2Sw.cpp
index 1e336ac..3ff6e38 100644
--- a/audio/aidl/default/automaticGainControlV2/AutomaticGainControlV2Sw.cpp
+++ b/audio/aidl/default/automaticGainControlV2/AutomaticGainControlV2Sw.cpp
@@ -180,10 +180,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> AutomaticGainControlV2Sw::getContext() {
-    return mContext;
-}
-
 RetCode AutomaticGainControlV2Sw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/automaticGainControlV2/AutomaticGainControlV2Sw.h b/audio/aidl/default/automaticGainControlV2/AutomaticGainControlV2Sw.h
index 9aa60ea..863d470 100644
--- a/audio/aidl/default/automaticGainControlV2/AutomaticGainControlV2Sw.h
+++ b/audio/aidl/default/automaticGainControlV2/AutomaticGainControlV2Sw.h
@@ -59,21 +59,24 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
     std::string getEffectName() override { return kEffectName; };
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
 
   private:
     static const std::vector<Range::AutomaticGainControlV2Range> kRanges;
-    std::shared_ptr<AutomaticGainControlV2SwContext> mContext;
+    std::shared_ptr<AutomaticGainControlV2SwContext> mContext GUARDED_BY(mImplMutex);
     ndk::ScopedAStatus getParameterAutomaticGainControlV2(const AutomaticGainControlV2::Tag& tag,
-                                                          Parameter::Specific* specific);
+                                                          Parameter::Specific* specific)
+            REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/bassboost/BassBoostSw.cpp b/audio/aidl/default/bassboost/BassBoostSw.cpp
index 6072d89..60adc30 100644
--- a/audio/aidl/default/bassboost/BassBoostSw.cpp
+++ b/audio/aidl/default/bassboost/BassBoostSw.cpp
@@ -151,10 +151,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> BassBoostSw::getContext() {
-    return mContext;
-}
-
 RetCode BassBoostSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/bassboost/BassBoostSw.h b/audio/aidl/default/bassboost/BassBoostSw.h
index 1132472..901e455 100644
--- a/audio/aidl/default/bassboost/BassBoostSw.h
+++ b/audio/aidl/default/bassboost/BassBoostSw.h
@@ -51,21 +51,23 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
     std::string getEffectName() override { return kEffectName; };
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
 
   private:
     static const std::vector<Range::BassBoostRange> kRanges;
-    std::shared_ptr<BassBoostSwContext> mContext;
+    std::shared_ptr<BassBoostSwContext> mContext GUARDED_BY(mImplMutex);
     ndk::ScopedAStatus getParameterBassBoost(const BassBoost::Tag& tag,
-                                             Parameter::Specific* specific);
+                                             Parameter::Specific* specific) REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/downmix/DownmixSw.cpp b/audio/aidl/default/downmix/DownmixSw.cpp
index ce5fe20..19ab2e8 100644
--- a/audio/aidl/default/downmix/DownmixSw.cpp
+++ b/audio/aidl/default/downmix/DownmixSw.cpp
@@ -144,10 +144,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> DownmixSw::getContext() {
-    return mContext;
-}
-
 RetCode DownmixSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/downmix/DownmixSw.h b/audio/aidl/default/downmix/DownmixSw.h
index 3f8a09b..1a9f0f0 100644
--- a/audio/aidl/default/downmix/DownmixSw.h
+++ b/audio/aidl/default/downmix/DownmixSw.h
@@ -55,20 +55,23 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
     std::string getEffectName() override { return kEffectName; };
-    IEffect::Status effectProcessImpl(float* in, float* out, int sample) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int sample)
+            REQUIRES(mImplMutex) override;
 
   private:
-    std::shared_ptr<DownmixSwContext> mContext;
+    std::shared_ptr<DownmixSwContext> mContext GUARDED_BY(mImplMutex);
 
-    ndk::ScopedAStatus getParameterDownmix(const Downmix::Tag& tag, Parameter::Specific* specific);
+    ndk::ScopedAStatus getParameterDownmix(const Downmix::Tag& tag, Parameter::Specific* specific)
+            REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.cpp b/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.cpp
index e8f90b2..36face1 100644
--- a/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.cpp
+++ b/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.cpp
@@ -260,10 +260,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> DynamicsProcessingSw::getContext() {
-    return mContext;
-}
-
 RetCode DynamicsProcessingSw::releaseContext() {
     if (mContext) {
         mContext.reset();
@@ -282,6 +278,9 @@
 }
 
 RetCode DynamicsProcessingSwContext::setCommon(const Parameter::Common& common) {
+    if (auto ret = updateIOFrameSize(common); ret != RetCode::SUCCESS) {
+        return ret;
+    }
     mCommon = common;
     mChannelCount = ::aidl::android::hardware::audio::common::getChannelCount(
             common.input.base.channelMask);
diff --git a/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.h b/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.h
index 641cf71..98edca0 100644
--- a/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.h
+++ b/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.h
@@ -113,15 +113,17 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
     std::string getEffectName() override { return kEffectName; };
 
   private:
@@ -130,9 +132,10 @@
     static const Range::DynamicsProcessingRange kPreEqBandRange;
     static const Range::DynamicsProcessingRange kPostEqBandRange;
     static const std::vector<Range::DynamicsProcessingRange> kRanges;
-    std::shared_ptr<DynamicsProcessingSwContext> mContext;
+    std::shared_ptr<DynamicsProcessingSwContext> mContext GUARDED_BY(mImplMutex);
     ndk::ScopedAStatus getParameterDynamicsProcessing(const DynamicsProcessing::Tag& tag,
-                                                      Parameter::Specific* specific);
+                                                      Parameter::Specific* specific)
+            REQUIRES(mImplMutex);
 
 };  // DynamicsProcessingSw
 
diff --git a/audio/aidl/default/envReverb/EnvReverbSw.cpp b/audio/aidl/default/envReverb/EnvReverbSw.cpp
index 73975c6..7937a6a 100644
--- a/audio/aidl/default/envReverb/EnvReverbSw.cpp
+++ b/audio/aidl/default/envReverb/EnvReverbSw.cpp
@@ -267,10 +267,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> EnvReverbSw::getContext() {
-    return mContext;
-}
-
 RetCode EnvReverbSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/envReverb/EnvReverbSw.h b/audio/aidl/default/envReverb/EnvReverbSw.h
index 5e31e2f..367462b 100644
--- a/audio/aidl/default/envReverb/EnvReverbSw.h
+++ b/audio/aidl/default/envReverb/EnvReverbSw.h
@@ -100,21 +100,23 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
     IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
     std::string getEffectName() override { return kEffectName; }
 
   private:
     static const std::vector<Range::EnvironmentalReverbRange> kRanges;
-    std::shared_ptr<EnvReverbSwContext> mContext;
+    std::shared_ptr<EnvReverbSwContext> mContext GUARDED_BY(mImplMutex);
     ndk::ScopedAStatus getParameterEnvironmentalReverb(const EnvironmentalReverb::Tag& tag,
-                                                       Parameter::Specific* specific);
+                                                       Parameter::Specific* specific)
+            REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/equalizer/EqualizerSw.cpp b/audio/aidl/default/equalizer/EqualizerSw.cpp
index b2add31..640b3ba 100644
--- a/audio/aidl/default/equalizer/EqualizerSw.cpp
+++ b/audio/aidl/default/equalizer/EqualizerSw.cpp
@@ -198,10 +198,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> EqualizerSw::getContext() {
-    return mContext;
-}
-
 RetCode EqualizerSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/equalizer/EqualizerSw.h b/audio/aidl/default/equalizer/EqualizerSw.h
index 56af3b5..caaa129 100644
--- a/audio/aidl/default/equalizer/EqualizerSw.h
+++ b/audio/aidl/default/equalizer/EqualizerSw.h
@@ -97,15 +97,17 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
     std::string getEffectName() override { return kEffectName; }
 
   private:
@@ -113,7 +115,7 @@
     static const std::vector<Equalizer::Preset> kPresets;
     static const std::vector<Range::EqualizerRange> kRanges;
     ndk::ScopedAStatus getParameterEqualizer(const Equalizer::Tag& tag,
-                                             Parameter::Specific* specific);
+                                             Parameter::Specific* specific) REQUIRES(mImplMutex);
     std::shared_ptr<EqualizerSwContext> mContext;
 };
 
diff --git a/audio/aidl/default/extension/ExtensionEffect.cpp b/audio/aidl/default/extension/ExtensionEffect.cpp
index 4a4d71b6..11916c8 100644
--- a/audio/aidl/default/extension/ExtensionEffect.cpp
+++ b/audio/aidl/default/extension/ExtensionEffect.cpp
@@ -123,10 +123,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> ExtensionEffect::getContext() {
-    return mContext;
-}
-
 RetCode ExtensionEffect::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/extension/ExtensionEffect.h b/audio/aidl/default/extension/ExtensionEffect.h
index e7a068b..b560860 100644
--- a/audio/aidl/default/extension/ExtensionEffect.h
+++ b/audio/aidl/default/extension/ExtensionEffect.h
@@ -54,18 +54,20 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
     std::string getEffectName() override { return kEffectName; };
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
 
   private:
-    std::shared_ptr<ExtensionEffectContext> mContext;
+    std::shared_ptr<ExtensionEffectContext> mContext GUARDED_BY(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/hapticGenerator/HapticGeneratorSw.cpp b/audio/aidl/default/hapticGenerator/HapticGeneratorSw.cpp
index 27cdac8..7469ab9 100644
--- a/audio/aidl/default/hapticGenerator/HapticGeneratorSw.cpp
+++ b/audio/aidl/default/hapticGenerator/HapticGeneratorSw.cpp
@@ -158,10 +158,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> HapticGeneratorSw::getContext() {
-    return mContext;
-}
-
 RetCode HapticGeneratorSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/hapticGenerator/HapticGeneratorSw.h b/audio/aidl/default/hapticGenerator/HapticGeneratorSw.h
index 3bbe41a..47f3848 100644
--- a/audio/aidl/default/hapticGenerator/HapticGeneratorSw.h
+++ b/audio/aidl/default/hapticGenerator/HapticGeneratorSw.h
@@ -67,21 +67,24 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
     std::string getEffectName() override { return kEffectName; }
 
   private:
-    std::shared_ptr<HapticGeneratorSwContext> mContext;
+    std::shared_ptr<HapticGeneratorSwContext> mContext GUARDED_BY(mImplMutex);
 
     ndk::ScopedAStatus getParameterHapticGenerator(const HapticGenerator::Tag& tag,
-                                                   Parameter::Specific* specific);
+                                                   Parameter::Specific* specific)
+            REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/include/core-impl/ModuleRemoteSubmix.h b/audio/aidl/default/include/core-impl/ModuleRemoteSubmix.h
index 613ac62..9d8c027 100644
--- a/audio/aidl/default/include/core-impl/ModuleRemoteSubmix.h
+++ b/audio/aidl/default/include/core-impl/ModuleRemoteSubmix.h
@@ -57,7 +57,7 @@
     ndk::ScopedAStatus onMasterVolumeChanged(float volume) override;
     int32_t getNominalLatencyMs(
             const ::aidl::android::media::audio::common::AudioPortConfig& portConfig) override;
-    // TODO(b/307586684): Report proper minimum stream buffer size by overriding 'setAudioPatch'.
+    binder_status_t dump(int fd, const char** args, uint32_t numArgs) override;
 };
 
 }  // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/StreamRemoteSubmix.h b/audio/aidl/default/include/core-impl/StreamRemoteSubmix.h
index 477c30e..b2cdc28 100644
--- a/audio/aidl/default/include/core-impl/StreamRemoteSubmix.h
+++ b/audio/aidl/default/include/core-impl/StreamRemoteSubmix.h
@@ -67,6 +67,7 @@
     int64_t mStartTimeNs = 0;
     long mFramesSinceStart = 0;
     int mReadErrorCount = 0;
+    int mReadFailureCount = 0;
 };
 
 class StreamInRemoteSubmix final : public StreamIn, public StreamSwitcher {
diff --git a/audio/aidl/default/include/effect-impl/EffectContext.h b/audio/aidl/default/include/effect-impl/EffectContext.h
index 698e7a5..24f3b5d 100644
--- a/audio/aidl/default/include/effect-impl/EffectContext.h
+++ b/audio/aidl/default/include/effect-impl/EffectContext.h
@@ -21,6 +21,7 @@
 #include <Utils.h>
 #include <android-base/logging.h>
 #include <fmq/AidlMessageQueue.h>
+#include <fmq/EventFlag.h>
 
 #include <aidl/android/hardware/audio/effect/BnEffect.h>
 #include "EffectTypes.h"
@@ -36,119 +37,73 @@
             float, ::aidl::android::hardware::common::fmq::SynchronizedReadWrite>
             DataMQ;
 
-    EffectContext(size_t statusDepth, const Parameter::Common& common) {
-        auto& input = common.input;
-        auto& output = common.output;
-
-        LOG_ALWAYS_FATAL_IF(
-                input.base.format.pcm != aidl::android::media::audio::common::PcmType::FLOAT_32_BIT,
-                "inputFormatNotFloat");
-        LOG_ALWAYS_FATAL_IF(output.base.format.pcm !=
-                                    aidl::android::media::audio::common::PcmType::FLOAT_32_BIT,
-                            "outputFormatNotFloat");
-        mInputFrameSize = ::aidl::android::hardware::audio::common::getFrameSizeInBytes(
-                input.base.format, input.base.channelMask);
-        mOutputFrameSize = ::aidl::android::hardware::audio::common::getFrameSizeInBytes(
-                output.base.format, output.base.channelMask);
-        // in/outBuffer size in float (FMQ data format defined for DataMQ)
-        size_t inBufferSizeInFloat = input.frameCount * mInputFrameSize / sizeof(float);
-        size_t outBufferSizeInFloat = output.frameCount * mOutputFrameSize / sizeof(float);
-
-        // only status FMQ use the EventFlag
-        mStatusMQ = std::make_shared<StatusMQ>(statusDepth, true /*configureEventFlagWord*/);
-        mInputMQ = std::make_shared<DataMQ>(inBufferSizeInFloat);
-        mOutputMQ = std::make_shared<DataMQ>(outBufferSizeInFloat);
-
-        if (!mStatusMQ->isValid() || !mInputMQ->isValid() || !mOutputMQ->isValid()) {
-            LOG(ERROR) << __func__ << " created invalid FMQ";
+    EffectContext(size_t statusDepth, const Parameter::Common& common);
+    virtual ~EffectContext() {
+        if (mEfGroup) {
+            ::android::hardware::EventFlag::deleteEventFlag(&mEfGroup);
         }
-        mWorkBuffer.reserve(std::max(inBufferSizeInFloat, outBufferSizeInFloat));
-        mCommon = common;
     }
-    virtual ~EffectContext() {}
 
-    std::shared_ptr<StatusMQ> getStatusFmq() { return mStatusMQ; }
-    std::shared_ptr<DataMQ> getInputDataFmq() { return mInputMQ; }
-    std::shared_ptr<DataMQ> getOutputDataFmq() { return mOutputMQ; }
+    std::shared_ptr<StatusMQ> getStatusFmq() const;
+    std::shared_ptr<DataMQ> getInputDataFmq() const;
+    std::shared_ptr<DataMQ> getOutputDataFmq() const;
 
-    float* getWorkBuffer() { return static_cast<float*>(mWorkBuffer.data()); }
+    float* getWorkBuffer();
 
     // reset buffer status by abandon input data in FMQ
-    void resetBuffer() {
-        auto buffer = static_cast<float*>(mWorkBuffer.data());
-        std::vector<IEffect::Status> status(mStatusMQ->availableToRead());
-        mInputMQ->read(buffer, mInputMQ->availableToRead());
-    }
+    void resetBuffer();
+    void dupeFmq(IEffect::OpenEffectReturn* effectRet);
+    size_t getInputFrameSize() const;
+    size_t getOutputFrameSize() const;
+    int getSessionId() const;
+    int getIoHandle() const;
 
-    void dupeFmq(IEffect::OpenEffectReturn* effectRet) {
-        if (effectRet) {
-            effectRet->statusMQ = mStatusMQ->dupeDesc();
-            effectRet->inputDataMQ = mInputMQ->dupeDesc();
-            effectRet->outputDataMQ = mOutputMQ->dupeDesc();
-        }
-    }
-    size_t getInputFrameSize() { return mInputFrameSize; }
-    size_t getOutputFrameSize() { return mOutputFrameSize; }
-    int getSessionId() { return mCommon.session; }
-    int getIoHandle() { return mCommon.ioHandle; }
+    virtual void dupeFmqWithReopen(IEffect::OpenEffectReturn* effectRet);
 
     virtual RetCode setOutputDevice(
-            const std::vector<aidl::android::media::audio::common::AudioDeviceDescription>&
-                    device) {
-        mOutputDevice = device;
-        return RetCode::SUCCESS;
-    }
+            const std::vector<aidl::android::media::audio::common::AudioDeviceDescription>& device);
 
     virtual std::vector<aidl::android::media::audio::common::AudioDeviceDescription>
-    getOutputDevice() {
-        return mOutputDevice;
-    }
+    getOutputDevice();
 
-    virtual RetCode setAudioMode(const aidl::android::media::audio::common::AudioMode& mode) {
-        mMode = mode;
-        return RetCode::SUCCESS;
-    }
-    virtual aidl::android::media::audio::common::AudioMode getAudioMode() { return mMode; }
+    virtual RetCode setAudioMode(const aidl::android::media::audio::common::AudioMode& mode);
+    virtual aidl::android::media::audio::common::AudioMode getAudioMode();
 
-    virtual RetCode setAudioSource(const aidl::android::media::audio::common::AudioSource& source) {
-        mSource = source;
-        return RetCode::SUCCESS;
-    }
-    virtual aidl::android::media::audio::common::AudioSource getAudioSource() { return mSource; }
+    virtual RetCode setAudioSource(const aidl::android::media::audio::common::AudioSource& source);
+    virtual aidl::android::media::audio::common::AudioSource getAudioSource();
 
-    virtual RetCode setVolumeStereo(const Parameter::VolumeStereo& volumeStereo) {
-        mVolumeStereo = volumeStereo;
-        return RetCode::SUCCESS;
-    }
-    virtual Parameter::VolumeStereo getVolumeStereo() { return mVolumeStereo; }
+    virtual RetCode setVolumeStereo(const Parameter::VolumeStereo& volumeStereo);
+    virtual Parameter::VolumeStereo getVolumeStereo();
 
-    virtual RetCode setCommon(const Parameter::Common& common) {
-        mCommon = common;
-        LOG(VERBOSE) << __func__ << mCommon.toString();
-        return RetCode::SUCCESS;
-    }
-    virtual Parameter::Common getCommon() {
-        LOG(VERBOSE) << __func__ << mCommon.toString();
-        return mCommon;
-    }
+    virtual RetCode setCommon(const Parameter::Common& common);
+    virtual Parameter::Common getCommon();
+
+    virtual ::android::hardware::EventFlag* getStatusEventFlag();
 
   protected:
-    // common parameters
     size_t mInputFrameSize;
     size_t mOutputFrameSize;
-    Parameter::Common mCommon;
-    std::vector<aidl::android::media::audio::common::AudioDeviceDescription> mOutputDevice;
-    aidl::android::media::audio::common::AudioMode mMode;
-    aidl::android::media::audio::common::AudioSource mSource;
-    Parameter::VolumeStereo mVolumeStereo;
+    size_t mInputChannelCount;
+    size_t mOutputChannelCount;
+    Parameter::Common mCommon = {};
+    std::vector<aidl::android::media::audio::common::AudioDeviceDescription> mOutputDevice = {};
+    aidl::android::media::audio::common::AudioMode mMode =
+            aidl::android::media::audio::common::AudioMode::SYS_RESERVED_INVALID;
+    aidl::android::media::audio::common::AudioSource mSource =
+            aidl::android::media::audio::common::AudioSource::SYS_RESERVED_INVALID;
+    Parameter::VolumeStereo mVolumeStereo = {};
+    RetCode updateIOFrameSize(const Parameter::Common& common);
+    RetCode notifyDataMqUpdate();
 
   private:
     // fmq and buffers
     std::shared_ptr<StatusMQ> mStatusMQ;
     std::shared_ptr<DataMQ> mInputMQ;
     std::shared_ptr<DataMQ> mOutputMQ;
-    // TODO handle effect process input and output
+    // std::shared_ptr<IEffect::OpenEffectReturn> mRet;
     // work buffer set by effect instances, the access and update are in same thread
     std::vector<float> mWorkBuffer;
+
+    ::android::hardware::EventFlag* mEfGroup;
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/include/effect-impl/EffectImpl.h b/audio/aidl/default/include/effect-impl/EffectImpl.h
index e7d081f..21f6502 100644
--- a/audio/aidl/default/include/effect-impl/EffectImpl.h
+++ b/audio/aidl/default/include/effect-impl/EffectImpl.h
@@ -43,38 +43,60 @@
                                     OpenEffectReturn* ret) override;
     virtual ndk::ScopedAStatus close() override;
     virtual ndk::ScopedAStatus command(CommandId id) override;
+    virtual ndk::ScopedAStatus reopen(OpenEffectReturn* ret) override;
 
     virtual ndk::ScopedAStatus getState(State* state) override;
     virtual ndk::ScopedAStatus setParameter(const Parameter& param) override;
     virtual ndk::ScopedAStatus getParameter(const Parameter::Id& id, Parameter* param) override;
 
-    virtual ndk::ScopedAStatus setParameterCommon(const Parameter& param);
-    virtual ndk::ScopedAStatus getParameterCommon(const Parameter::Tag& tag, Parameter* param);
+    virtual ndk::ScopedAStatus setParameterCommon(const Parameter& param) REQUIRES(mImplMutex);
+    virtual ndk::ScopedAStatus getParameterCommon(const Parameter::Tag& tag, Parameter* param)
+            REQUIRES(mImplMutex);
 
     /* Methods MUST be implemented by each effect instances */
     virtual ndk::ScopedAStatus getDescriptor(Descriptor* desc) = 0;
-    virtual ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) = 0;
+    virtual ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) = 0;
     virtual ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                                    Parameter::Specific* specific) = 0;
+                                                    Parameter::Specific* specific)
+            REQUIRES(mImplMutex) = 0;
 
     virtual std::string getEffectName() = 0;
-    virtual IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    virtual std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex);
+    virtual RetCode releaseContext() REQUIRES(mImplMutex) = 0;
 
     /**
-     * Effect context methods must be implemented by each effect.
-     * Each effect can derive from EffectContext and define its own context, but must upcast to
-     * EffectContext for EffectImpl to use.
+     * @brief effectProcessImpl is running in worker thread which created in EffectThread.
+     *
+     * EffectThread will make sure effectProcessImpl only be called after startThread() successful
+     * and before stopThread() successful.
+     *
+     * effectProcessImpl implementation must not call any EffectThread interface, otherwise it will
+     * cause deadlock.
+     *
+     * @param in address of input float buffer.
+     * @param out address of output float buffer.
+     * @param samples number of samples to process.
+     * @return IEffect::Status
      */
-    virtual std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) = 0;
-    virtual std::shared_ptr<EffectContext> getContext() = 0;
-    virtual RetCode releaseContext() = 0;
+    virtual IEffect::Status effectProcessImpl(float* in, float* out, int samples) = 0;
+
+    /**
+     * process() get data from data MQs, and call effectProcessImpl() for effect data processing.
+     * Its important for the implementation to use mImplMutex for context synchronization.
+     */
+    void process() override;
 
   protected:
-    State mState = State::INIT;
+    State mState GUARDED_BY(mImplMutex) = State::INIT;
 
     IEffect::Status status(binder_status_t status, size_t consumed, size_t produced);
     void cleanUp();
 
+    std::mutex mImplMutex;
+    std::shared_ptr<EffectContext> mImplContext GUARDED_BY(mImplMutex);
+
     /**
      * Optional CommandId handling methods for effects to override.
      * For CommandId::START, EffectImpl call commandImpl before starting the EffectThread
@@ -82,6 +104,9 @@
      * For CommandId::STOP and CommandId::RESET, EffectImpl call commandImpl after stop the
      * EffectThread processing.
      */
-    virtual ndk::ScopedAStatus commandImpl(CommandId id);
+    virtual ndk::ScopedAStatus commandImpl(CommandId id) REQUIRES(mImplMutex);
+
+    RetCode notifyEventFlag(uint32_t flag);
+    ::android::hardware::EventFlag* mEventFlag;
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/include/effect-impl/EffectThread.h b/audio/aidl/default/include/effect-impl/EffectThread.h
index ae51ef7..3dbb0e6 100644
--- a/audio/aidl/default/include/effect-impl/EffectThread.h
+++ b/audio/aidl/default/include/effect-impl/EffectThread.h
@@ -36,8 +36,7 @@
     virtual ~EffectThread();
 
     // called by effect implementation.
-    RetCode createThread(std::shared_ptr<EffectContext> context, const std::string& name,
-                         int priority = ANDROID_PRIORITY_URGENT_AUDIO);
+    RetCode createThread(const std::string& name, int priority = ANDROID_PRIORITY_URGENT_AUDIO);
     RetCode destroyThread();
     RetCode startThread();
     RetCode stopThread();
@@ -46,32 +45,11 @@
     void threadLoop();
 
     /**
-     * @brief effectProcessImpl is running in worker thread which created in EffectThread.
-     *
-     * Effect implementation should think about concurrency in the implementation if necessary.
-     * Parameter setting usually implemented in context (derived from EffectContext), and some
-     * parameter maybe used in the processing, then effect implementation should consider using a
-     * mutex to protect these parameter.
-     *
-     * EffectThread will make sure effectProcessImpl only be called after startThread() successful
-     * and before stopThread() successful.
-     *
-     * effectProcessImpl implementation must not call any EffectThread interface, otherwise it will
-     * cause deadlock.
-     *
-     * @param in address of input float buffer.
-     * @param out address of output float buffer.
-     * @param samples number of samples to process.
-     * @return IEffect::Status
-     */
-    virtual IEffect::Status effectProcessImpl(float* in, float* out, int samples) = 0;
-
-    /**
      * process() call effectProcessImpl() for effect data processing, it is necessary for the
      * processing to be called under Effect thread mutex mThreadMutex, to avoid the effect state
      * change before/during data processing, and keep the thread and effect state consistent.
      */
-    virtual void process_l() REQUIRES(mThreadMutex);
+    virtual void process() = 0;
 
   private:
     static constexpr int kMaxTaskNameLen = 15;
@@ -80,16 +58,7 @@
     std::condition_variable mCv;
     bool mStop GUARDED_BY(mThreadMutex) = true;
     bool mExit GUARDED_BY(mThreadMutex) = false;
-    std::shared_ptr<EffectContext> mThreadContext GUARDED_BY(mThreadMutex);
 
-    struct EventFlagDeleter {
-        void operator()(::android::hardware::EventFlag* flag) const {
-            if (flag) {
-                ::android::hardware::EventFlag::deleteEventFlag(&flag);
-            }
-        }
-    };
-    std::unique_ptr<::android::hardware::EventFlag, EventFlagDeleter> mEfGroup;
     std::thread mThread;
     int mPriority;
     std::string mName;
diff --git a/audio/aidl/default/include/effect-impl/EffectTypes.h b/audio/aidl/default/include/effect-impl/EffectTypes.h
index 4bda7be..9740d6e 100644
--- a/audio/aidl/default/include/effect-impl/EffectTypes.h
+++ b/audio/aidl/default/include/effect-impl/EffectTypes.h
@@ -46,7 +46,8 @@
     ERROR_NULL_POINTER,      /* NULL pointer */
     ERROR_ALIGNMENT_ERROR,   /* Memory alignment error */
     ERROR_BLOCK_SIZE_EXCEED, /* Maximum block size exceeded */
-    ERROR_EFFECT_LIB_ERROR
+    ERROR_EFFECT_LIB_ERROR,  /* Effect implementation library error */
+    ERROR_EVENT_FLAG_ERROR   /* Error with effect event flags */
 };
 
 static const int INVALID_AUDIO_SESSION_ID = -1;
@@ -67,6 +68,8 @@
             return out << "ERROR_BLOCK_SIZE_EXCEED";
         case RetCode::ERROR_EFFECT_LIB_ERROR:
             return out << "ERROR_EFFECT_LIB_ERROR";
+        case RetCode::ERROR_EVENT_FLAG_ERROR:
+            return out << "ERROR_EVENT_FLAG_ERROR";
     }
 
     return out << "EnumError: " << code;
diff --git a/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.cpp b/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.cpp
index 7954316..1e70716 100644
--- a/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.cpp
+++ b/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.cpp
@@ -147,10 +147,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> LoudnessEnhancerSw::getContext() {
-    return mContext;
-}
-
 RetCode LoudnessEnhancerSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.h b/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.h
index 25824f2..cf71a5f 100644
--- a/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.h
+++ b/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.h
@@ -54,20 +54,23 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
     std::string getEffectName() override { return kEffectName; }
 
   private:
-    std::shared_ptr<LoudnessEnhancerSwContext> mContext;
+    std::shared_ptr<LoudnessEnhancerSwContext> mContext GUARDED_BY(mImplMutex);
     ndk::ScopedAStatus getParameterLoudnessEnhancer(const LoudnessEnhancer::Tag& tag,
-                                                    Parameter::Specific* specific);
+                                                    Parameter::Specific* specific)
+            REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/noiseSuppression/NoiseSuppressionSw.cpp b/audio/aidl/default/noiseSuppression/NoiseSuppressionSw.cpp
index a3208df..d304416 100644
--- a/audio/aidl/default/noiseSuppression/NoiseSuppressionSw.cpp
+++ b/audio/aidl/default/noiseSuppression/NoiseSuppressionSw.cpp
@@ -155,10 +155,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> NoiseSuppressionSw::getContext() {
-    return mContext;
-}
-
 RetCode NoiseSuppressionSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/noiseSuppression/NoiseSuppressionSw.h b/audio/aidl/default/noiseSuppression/NoiseSuppressionSw.h
index fc1e028..acef8ee 100644
--- a/audio/aidl/default/noiseSuppression/NoiseSuppressionSw.h
+++ b/audio/aidl/default/noiseSuppression/NoiseSuppressionSw.h
@@ -55,20 +55,23 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
     std::string getEffectName() override { return kEffectName; };
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
 
   private:
-    std::shared_ptr<NoiseSuppressionSwContext> mContext;
+    std::shared_ptr<NoiseSuppressionSwContext> mContext GUARDED_BY(mImplMutex);
     ndk::ScopedAStatus getParameterNoiseSuppression(const NoiseSuppression::Tag& tag,
-                                                    Parameter::Specific* specific);
+                                                    Parameter::Specific* specific)
+            REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/presetReverb/PresetReverbSw.cpp b/audio/aidl/default/presetReverb/PresetReverbSw.cpp
index 3f02eb7..2ac2010 100644
--- a/audio/aidl/default/presetReverb/PresetReverbSw.cpp
+++ b/audio/aidl/default/presetReverb/PresetReverbSw.cpp
@@ -161,10 +161,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> PresetReverbSw::getContext() {
-    return mContext;
-}
-
 RetCode PresetReverbSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/presetReverb/PresetReverbSw.h b/audio/aidl/default/presetReverb/PresetReverbSw.h
index 9ceee7c..61fc88c 100644
--- a/audio/aidl/default/presetReverb/PresetReverbSw.h
+++ b/audio/aidl/default/presetReverb/PresetReverbSw.h
@@ -56,21 +56,23 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
     std::string getEffectName() override { return kEffectName; }
 
   private:
-    std::shared_ptr<PresetReverbSwContext> mContext;
+    std::shared_ptr<PresetReverbSwContext> mContext GUARDED_BY(mImplMutex);
 
     ndk::ScopedAStatus getParameterPresetReverb(const PresetReverb::Tag& tag,
-                                                Parameter::Specific* specific);
+                                                Parameter::Specific* specific) REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp b/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp
index 7bc783c..b44f37b 100644
--- a/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp
+++ b/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp
@@ -16,6 +16,7 @@
 
 #define LOG_TAG "AHAL_ModuleRemoteSubmix"
 
+#include <stdio.h>
 #include <vector>
 
 #include <android-base/logging.h>
@@ -174,4 +175,9 @@
     return kMinLatencyMs;
 }
 
+binder_status_t ModuleRemoteSubmix::dump(int fd, const char** /*args*/, uint32_t /*numArgs*/) {
+    dprintf(fd, "\nSubmixRoutes:\n%s\n", r_submix::SubmixRoute::dumpRoutes().c_str());
+    return STATUS_OK;
+}
+
 }  // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp b/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp
index 3ee354b..fa4135d 100644
--- a/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp
+++ b/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp
@@ -267,6 +267,7 @@
         }
         return ::android::OK;
     }
+    mReadErrorCount = 0;
 
     LOG(VERBOSE) << __func__ << ": " << mDeviceAddress.toString() << ", " << frameCount
                  << " frames";
@@ -294,7 +295,12 @@
         }
     }
     if (actuallyRead < frameCount) {
-        LOG(WARNING) << __func__ << ": read " << actuallyRead << " vs. requested " << frameCount;
+        if (++mReadFailureCount < kMaxReadFailureAttempts) {
+            LOG(WARNING) << __func__ << ": read " << actuallyRead << " vs. requested " << frameCount
+                         << " (not all errors will be logged)";
+        }
+    } else {
+        mReadFailureCount = 0;
     }
     mCurrentRoute->updateReadCounterFrames(*actualFrameCount);
     return ::android::OK;
diff --git a/audio/aidl/default/r_submix/SubmixRoute.cpp b/audio/aidl/default/r_submix/SubmixRoute.cpp
index 7d706c2..325a012 100644
--- a/audio/aidl/default/r_submix/SubmixRoute.cpp
+++ b/audio/aidl/default/r_submix/SubmixRoute.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <mutex>
+
 #define LOG_TAG "AHAL_SubmixRoute"
 #include <android-base/logging.h>
 #include <media/AidlConversionCppNdk.h>
@@ -28,10 +30,11 @@
 namespace aidl::android::hardware::audio::core::r_submix {
 
 // static
-SubmixRoute::RoutesMonitor SubmixRoute::getRoutes() {
+SubmixRoute::RoutesMonitor SubmixRoute::getRoutes(bool tryLock) {
     static std::mutex submixRoutesLock;
     static RoutesMap submixRoutes;
-    return RoutesMonitor(submixRoutesLock, submixRoutes);
+    return !tryLock ? RoutesMonitor(submixRoutesLock, submixRoutes)
+                    : RoutesMonitor(submixRoutesLock, submixRoutes, tryLock);
 }
 
 // static
@@ -66,6 +69,21 @@
     getRoutes()->erase(deviceAddress);
 }
 
+// static
+std::string SubmixRoute::dumpRoutes() {
+    auto routes = getRoutes(true /*tryLock*/);
+    std::string result;
+    if (routes->empty()) result.append(" <Empty>");
+    for (const auto& r : *(routes.operator->())) {
+        result.append(" - ")
+                .append(r.first.toString())
+                .append(": ")
+                .append(r.second->dump())
+                .append("\n");
+    }
+    return result;
+}
+
 // Verify a submix input or output stream can be opened.
 bool SubmixRoute::isStreamConfigValid(bool isInput, const AudioConfig& streamConfig) {
     // If the stream is already open, don't open it again.
@@ -258,4 +276,23 @@
     }
 }
 
+std::string SubmixRoute::dump() NO_THREAD_SAFETY_ANALYSIS {
+    const bool isLocked = mLock.try_lock();
+    std::string result = std::string(isLocked ? "" : "! ")
+                                 .append("Input ")
+                                 .append(mStreamInOpen ? "open" : "closed")
+                                 .append(mStreamInStandby ? ", standby" : ", active")
+                                 .append(", refcount: ")
+                                 .append(std::to_string(mInputRefCount))
+                                 .append(", framesRead: ")
+                                 .append(mSource ? std::to_string(mSource->framesRead()) : "<null>")
+                                 .append("; Output ")
+                                 .append(mStreamOutOpen ? "open" : "closed")
+                                 .append(mStreamOutStandby ? ", standby" : ", active")
+                                 .append(", framesWritten: ")
+                                 .append(mSink ? std::to_string(mSink->framesWritten()) : "<null>");
+    if (isLocked) mLock.unlock();
+    return result;
+}
+
 }  // namespace aidl::android::hardware::audio::core::r_submix
diff --git a/audio/aidl/default/r_submix/SubmixRoute.h b/audio/aidl/default/r_submix/SubmixRoute.h
index 160df41..5425f12 100644
--- a/audio/aidl/default/r_submix/SubmixRoute.h
+++ b/audio/aidl/default/r_submix/SubmixRoute.h
@@ -17,6 +17,7 @@
 #pragma once
 
 #include <mutex>
+#include <string>
 
 #include <android-base/thread_annotations.h>
 #include <audio_utils/clock.h>
@@ -68,6 +69,7 @@
             const ::aidl::android::media::audio::common::AudioDeviceAddress& deviceAddress);
     static void removeRoute(
             const ::aidl::android::media::audio::common::AudioDeviceAddress& deviceAddress);
+    static std::string dumpRoutes();
 
     bool isStreamInOpen() {
         std::lock_guard guard(mLock);
@@ -115,20 +117,24 @@
     void standby(bool isInput);
     long updateReadCounterFrames(size_t frameCount);
 
+    std::string dump();
+
   private:
     using RoutesMap = std::map<::aidl::android::media::audio::common::AudioDeviceAddress,
                                std::shared_ptr<r_submix::SubmixRoute>>;
     class RoutesMonitor {
       public:
         RoutesMonitor(std::mutex& mutex, RoutesMap& routes) : mLock(mutex), mRoutes(routes) {}
+        RoutesMonitor(std::mutex& mutex, RoutesMap& routes, bool /*tryLock*/)
+            : mLock(mutex, std::try_to_lock), mRoutes(routes) {}
         RoutesMap* operator->() { return &mRoutes; }
 
       private:
-        std::lock_guard<std::mutex> mLock;
+        std::unique_lock<std::mutex> mLock;
         RoutesMap& mRoutes;
     };
 
-    static RoutesMonitor getRoutes();
+    static RoutesMonitor getRoutes(bool tryLock = false);
 
     bool isStreamConfigCompatible(const AudioConfig& streamConfig);
 
diff --git a/audio/aidl/default/spatializer/SpatializerSw.cpp b/audio/aidl/default/spatializer/SpatializerSw.cpp
index 434ed5a..6d3c4bd 100644
--- a/audio/aidl/default/spatializer/SpatializerSw.cpp
+++ b/audio/aidl/default/spatializer/SpatializerSw.cpp
@@ -141,10 +141,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> SpatializerSw::getContext() {
-    return mContext;
-}
-
 RetCode SpatializerSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/spatializer/SpatializerSw.h b/audio/aidl/default/spatializer/SpatializerSw.h
index b205704..b321e83 100644
--- a/audio/aidl/default/spatializer/SpatializerSw.h
+++ b/audio/aidl/default/spatializer/SpatializerSw.h
@@ -50,19 +50,21 @@
     ~SpatializerSw();
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
     std::string getEffectName() override { return kEffectName; };
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
 
   private:
     static const std::vector<Range::SpatializerRange> kRanges;
-    std::shared_ptr<SpatializerSwContext> mContext = nullptr;
+    std::shared_ptr<SpatializerSwContext> mContext GUARDED_BY(mImplMutex) = nullptr;
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/virtualizer/VirtualizerSw.cpp b/audio/aidl/default/virtualizer/VirtualizerSw.cpp
index 0e8435e..091b0b7 100644
--- a/audio/aidl/default/virtualizer/VirtualizerSw.cpp
+++ b/audio/aidl/default/virtualizer/VirtualizerSw.cpp
@@ -203,10 +203,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> VirtualizerSw::getContext() {
-    return mContext;
-}
-
 RetCode VirtualizerSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/virtualizer/VirtualizerSw.h b/audio/aidl/default/virtualizer/VirtualizerSw.h
index 5e114d9..9287838 100644
--- a/audio/aidl/default/virtualizer/VirtualizerSw.h
+++ b/audio/aidl/default/virtualizer/VirtualizerSw.h
@@ -59,24 +59,25 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
     IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
     std::string getEffectName() override { return kEffectName; }
 
   private:
     static const std::vector<Range::VirtualizerRange> kRanges;
-    std::shared_ptr<VirtualizerSwContext> mContext;
+    std::shared_ptr<VirtualizerSwContext> mContext GUARDED_BY(mImplMutex);
 
     ndk::ScopedAStatus getParameterVirtualizer(const Virtualizer::Tag& tag,
-                                               Parameter::Specific* specific);
+                                               Parameter::Specific* specific) REQUIRES(mImplMutex);
     ndk::ScopedAStatus getSpeakerAngles(const Virtualizer::SpeakerAnglesPayload payload,
-                                        Parameter::Specific* specific);
+                                        Parameter::Specific* specific) REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/visualizer/VisualizerSw.cpp b/audio/aidl/default/visualizer/VisualizerSw.cpp
index 285c102..54f7f1c 100644
--- a/audio/aidl/default/visualizer/VisualizerSw.cpp
+++ b/audio/aidl/default/visualizer/VisualizerSw.cpp
@@ -190,10 +190,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> VisualizerSw::getContext() {
-    return mContext;
-}
-
 RetCode VisualizerSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/visualizer/VisualizerSw.h b/audio/aidl/default/visualizer/VisualizerSw.h
index 995774e..4b87b04 100644
--- a/audio/aidl/default/visualizer/VisualizerSw.h
+++ b/audio/aidl/default/visualizer/VisualizerSw.h
@@ -72,21 +72,23 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
     std::string getEffectName() override { return kEffectName; }
 
   private:
     static const std::vector<Range::VisualizerRange> kRanges;
-    std::shared_ptr<VisualizerSwContext> mContext;
+    std::shared_ptr<VisualizerSwContext> mContext GUARDED_BY(mImplMutex);
     ndk::ScopedAStatus getParameterVisualizer(const Visualizer::Tag& tag,
-                                              Parameter::Specific* specific);
+                                              Parameter::Specific* specific) REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/volume/VolumeSw.cpp b/audio/aidl/default/volume/VolumeSw.cpp
index 8902584..dd019f6 100644
--- a/audio/aidl/default/volume/VolumeSw.cpp
+++ b/audio/aidl/default/volume/VolumeSw.cpp
@@ -160,10 +160,6 @@
     return mContext;
 }
 
-std::shared_ptr<EffectContext> VolumeSw::getContext() {
-    return mContext;
-}
-
 RetCode VolumeSw::releaseContext() {
     if (mContext) {
         mContext.reset();
diff --git a/audio/aidl/default/volume/VolumeSw.h b/audio/aidl/default/volume/VolumeSw.h
index 1432b2b..3fc0d97 100644
--- a/audio/aidl/default/volume/VolumeSw.h
+++ b/audio/aidl/default/volume/VolumeSw.h
@@ -57,21 +57,24 @@
     }
 
     ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
-    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override;
-    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id,
-                                            Parameter::Specific* specific) override;
+    ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific)
+            REQUIRES(mImplMutex) override;
+    ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, Parameter::Specific* specific)
+            REQUIRES(mImplMutex) override;
 
-    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common) override;
-    std::shared_ptr<EffectContext> getContext() override;
-    RetCode releaseContext() override;
+    std::shared_ptr<EffectContext> createContext(const Parameter::Common& common)
+            REQUIRES(mImplMutex) override;
+    RetCode releaseContext() REQUIRES(mImplMutex) override;
 
-    IEffect::Status effectProcessImpl(float* in, float* out, int samples) override;
+    IEffect::Status effectProcessImpl(float* in, float* out, int samples)
+            REQUIRES(mImplMutex) override;
     std::string getEffectName() override { return kEffectName; }
 
   private:
     static const std::vector<Range::VolumeRange> kRanges;
-    std::shared_ptr<VolumeSwContext> mContext;
+    std::shared_ptr<VolumeSwContext> mContext GUARDED_BY(mImplMutex);
 
-    ndk::ScopedAStatus getParameterVolume(const Volume::Tag& tag, Parameter::Specific* specific);
+    ndk::ScopedAStatus getParameterVolume(const Volume::Tag& tag, Parameter::Specific* specific)
+            REQUIRES(mImplMutex);
 };
 }  // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/vts/EffectHelper.h b/audio/aidl/vts/EffectHelper.h
index 4a5c537..9fa7f9f 100644
--- a/audio/aidl/vts/EffectHelper.h
+++ b/audio/aidl/vts/EffectHelper.h
@@ -43,6 +43,7 @@
 using aidl::android::hardware::audio::effect::CommandId;
 using aidl::android::hardware::audio::effect::Descriptor;
 using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::hardware::audio::effect::kEventFlagDataMqUpdate;
 using aidl::android::hardware::audio::effect::kEventFlagNotEmpty;
 using aidl::android::hardware::audio::effect::Parameter;
 using aidl::android::hardware::audio::effect::Range;
@@ -191,6 +192,16 @@
             ASSERT_TRUE(dataMq->read(buffer.data(), expectFloats));
         }
     }
+    static void expectDataMqUpdateEventFlag(std::unique_ptr<StatusMQ>& statusMq) {
+        EventFlag* efGroup;
+        ASSERT_EQ(::android::OK,
+                  EventFlag::createEventFlag(statusMq->getEventFlagWord(), &efGroup));
+        ASSERT_NE(nullptr, efGroup);
+        uint32_t efState = 0;
+        EXPECT_EQ(::android::OK, efGroup->wait(kEventFlagDataMqUpdate, &efState, 1'000'000 /*1ms*/,
+                                               true /* retry */));
+        EXPECT_TRUE(efState & kEventFlagDataMqUpdate);
+    }
     static Parameter::Common createParamCommon(
             int session = 0, int ioHandle = -1, int iSampleRate = 48000, int oSampleRate = 48000,
             long iFrameCount = 0x100, long oFrameCount = 0x100,
diff --git a/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp b/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
index 418fedb..01cdd81 100644
--- a/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
@@ -609,6 +609,49 @@
     ASSERT_NO_FATAL_FAILURE(destroy(mFactory, mEffect));
 }
 
+// Verify Parameters kept after reset.
+TEST_P(AudioEffectTest, SetCommonParameterAndReopen) {
+    ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
+
+    Parameter::Common common = EffectHelper::createParamCommon(
+            0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+            kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+    IEffect::OpenEffectReturn ret;
+    ASSERT_NO_FATAL_FAILURE(open(mEffect, common, std::nullopt /* specific */, &ret, EX_NONE));
+    auto statusMQ = std::make_unique<EffectHelper::StatusMQ>(ret.statusMQ);
+    ASSERT_TRUE(statusMQ->isValid());
+    auto inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+    ASSERT_TRUE(inputMQ->isValid());
+    auto outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+    ASSERT_TRUE(outputMQ->isValid());
+
+    Parameter::Id id = Parameter::Id::make<Parameter::Id::commonTag>(Parameter::common);
+    common.input.frameCount++;
+    ASSERT_NO_FATAL_FAILURE(setAndGetParameter(id, Parameter::make<Parameter::common>(common)));
+    ASSERT_TRUE(statusMQ->isValid());
+    expectDataMqUpdateEventFlag(statusMQ);
+    EXPECT_IS_OK(mEffect->reopen(&ret));
+    inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+    outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+    ASSERT_TRUE(statusMQ->isValid());
+    ASSERT_TRUE(inputMQ->isValid());
+    ASSERT_TRUE(outputMQ->isValid());
+
+    common.output.frameCount++;
+    ASSERT_NO_FATAL_FAILURE(setAndGetParameter(id, Parameter::make<Parameter::common>(common)));
+    ASSERT_TRUE(statusMQ->isValid());
+    expectDataMqUpdateEventFlag(statusMQ);
+    EXPECT_IS_OK(mEffect->reopen(&ret));
+    inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+    outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+    ASSERT_TRUE(statusMQ->isValid());
+    ASSERT_TRUE(inputMQ->isValid());
+    ASSERT_TRUE(outputMQ->isValid());
+
+    ASSERT_NO_FATAL_FAILURE(close(mEffect));
+    ASSERT_NO_FATAL_FAILURE(destroy(mFactory, mEffect));
+}
+
 /// Data processing test
 // Send data to effects and expect it to be consumed by checking statusMQ.
 // Effects exposing bypass flags or operating in offload mode will be skipped.
@@ -684,6 +727,59 @@
     ASSERT_NO_FATAL_FAILURE(destroy(mFactory, mEffect));
 }
 
+// Send data to effects and expect it to be consumed after effect reopen (IO AudioConfig change).
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ConsumeDataAfterReopen) {
+    ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
+
+    Parameter::Common common = EffectHelper::createParamCommon(
+            0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+            kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+    IEffect::OpenEffectReturn ret;
+    ASSERT_NO_FATAL_FAILURE(open(mEffect, common, std::nullopt /* specific */, &ret, EX_NONE));
+    auto statusMQ = std::make_unique<EffectHelper::StatusMQ>(ret.statusMQ);
+    ASSERT_TRUE(statusMQ->isValid());
+    auto inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+    ASSERT_TRUE(inputMQ->isValid());
+    auto outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+    ASSERT_TRUE(outputMQ->isValid());
+
+    std::vector<float> buffer;
+    ASSERT_NO_FATAL_FAILURE(command(mEffect, CommandId::START));
+    ASSERT_NO_FATAL_FAILURE(expectState(mEffect, State::PROCESSING));
+    EXPECT_NO_FATAL_FAILURE(EffectHelper::allocateInputData(common, inputMQ, buffer));
+    EXPECT_NO_FATAL_FAILURE(EffectHelper::writeToFmq(statusMQ, inputMQ, buffer));
+    EXPECT_NO_FATAL_FAILURE(
+            EffectHelper::readFromFmq(statusMQ, 1, outputMQ, buffer.size(), buffer));
+
+    // set a new common parameter with different IO frameCount, reopen
+    Parameter::Id id = Parameter::Id::make<Parameter::Id::commonTag>(Parameter::common);
+    common.input.frameCount += 4;
+    common.output.frameCount += 4;
+    ASSERT_NO_FATAL_FAILURE(setAndGetParameter(id, Parameter::make<Parameter::common>(common)));
+    ASSERT_TRUE(statusMQ->isValid());
+    expectDataMqUpdateEventFlag(statusMQ);
+    EXPECT_IS_OK(mEffect->reopen(&ret));
+    inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+    outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+    ASSERT_TRUE(statusMQ->isValid());
+    ASSERT_TRUE(inputMQ->isValid());
+    ASSERT_TRUE(outputMQ->isValid());
+
+    // verify data consume again
+    EXPECT_NO_FATAL_FAILURE(EffectHelper::allocateInputData(common, inputMQ, buffer));
+    EXPECT_NO_FATAL_FAILURE(EffectHelper::writeToFmq(statusMQ, inputMQ, buffer));
+    EXPECT_NO_FATAL_FAILURE(
+            EffectHelper::readFromFmq(statusMQ, 1, outputMQ, buffer.size(), buffer));
+
+    ASSERT_NO_FATAL_FAILURE(command(mEffect, CommandId::STOP));
+    ASSERT_NO_FATAL_FAILURE(expectState(mEffect, State::IDLE));
+    EXPECT_NO_FATAL_FAILURE(EffectHelper::readFromFmq(statusMQ, 0, outputMQ, 0, buffer));
+
+    ASSERT_NO_FATAL_FAILURE(close(mEffect));
+    ASSERT_NO_FATAL_FAILURE(destroy(mFactory, mEffect));
+}
+
 // Send data to IDLE effects and expect it to be consumed after effect start.
 // Effects exposing bypass flags or operating in offload mode will be skipped.
 TEST_P(AudioEffectDataPathTest, SendDataAtIdleAndConsumeDataInProcessing) {
diff --git a/automotive/audiocontrol/aidl/default/AudioControl.cpp b/automotive/audiocontrol/aidl/default/AudioControl.cpp
index cf7307d..7e7e145 100644
--- a/automotive/audiocontrol/aidl/default/AudioControl.cpp
+++ b/automotive/audiocontrol/aidl/default/AudioControl.cpp
@@ -244,15 +244,15 @@
 template <typename aidl_type>
 static inline std::string toString(const std::vector<aidl_type>& in_values) {
     return std::accumulate(std::begin(in_values), std::end(in_values), std::string{},
-                           [](std::string& ls, const aidl_type& rs) {
-                               return ls += (ls.empty() ? "" : ",") + rs.toString();
+                           [](const std::string& ls, const aidl_type& rs) {
+                               return ls + (ls.empty() ? "" : ",") + rs.toString();
                            });
 }
 template <typename aidl_enum_type>
 static inline std::string toEnumString(const std::vector<aidl_enum_type>& in_values) {
     return std::accumulate(std::begin(in_values), std::end(in_values), std::string{},
-                           [](std::string& ls, const aidl_enum_type& rs) {
-                               return ls += (ls.empty() ? "" : ",") + toString(rs);
+                           [](const std::string& ls, const aidl_enum_type& rs) {
+                               return ls + (ls.empty() ? "" : ",") + toString(rs);
                            });
 }
 
diff --git a/automotive/can/1.0/default/CanSocket.h b/automotive/can/1.0/default/CanSocket.h
index fd956b5..f3e8e60 100644
--- a/automotive/can/1.0/default/CanSocket.h
+++ b/automotive/can/1.0/default/CanSocket.h
@@ -22,6 +22,7 @@
 
 #include <atomic>
 #include <chrono>
+#include <functional>
 #include <thread>
 
 namespace android::hardware::automotive::can::V1_0::implementation {
diff --git a/automotive/can/1.0/default/libnetdevice/ifreqs.h b/automotive/can/1.0/default/libnetdevice/ifreqs.h
index d8d6fe0..aa7030b 100644
--- a/automotive/can/1.0/default/libnetdevice/ifreqs.h
+++ b/automotive/can/1.0/default/libnetdevice/ifreqs.h
@@ -18,6 +18,7 @@
 
 #include <net/if.h>
 
+#include <atomic>
 #include <string>
 
 namespace android::netdevice::ifreqs {
diff --git a/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp b/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp
index fe749f6..413b4b1 100644
--- a/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp
+++ b/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp
@@ -27,6 +27,8 @@
 #include <linux/rtnetlink.h>
 #include <net/if.h>
 
+#include <algorithm>
+#include <iterator>
 #include <sstream>
 
 namespace android::netdevice {
diff --git a/automotive/can/1.0/default/libnl++/common.cpp b/automotive/can/1.0/default/libnl++/common.cpp
index 23c2d94..1287bb5 100644
--- a/automotive/can/1.0/default/libnl++/common.cpp
+++ b/automotive/can/1.0/default/libnl++/common.cpp
@@ -20,6 +20,8 @@
 
 #include <net/if.h>
 
+#include <algorithm>
+
 namespace android::nl {
 
 unsigned int nametoindex(const std::string& ifname) {
diff --git a/automotive/evs/aidl/vts/VtsHalEvsTargetTest.cpp b/automotive/evs/aidl/vts/VtsHalEvsTargetTest.cpp
index 3419b3c..477de31 100644
--- a/automotive/evs/aidl/vts/VtsHalEvsTargetTest.cpp
+++ b/automotive/evs/aidl/vts/VtsHalEvsTargetTest.cpp
@@ -1399,6 +1399,12 @@
 
     // Test each reported camera
     for (auto&& cam : mCameraInfo) {
+        bool isLogicalCam = false;
+        if (getPhysicalCameraIds(cam.id, isLogicalCam); isLogicalCam) {
+            LOG(INFO) << "Skip a logical device, " << cam.id;
+            continue;
+        }
+
         // Request available display IDs
         uint8_t targetDisplayId = 0;
         std::vector<uint8_t> displayIds;
@@ -1973,6 +1979,13 @@
 
     // Test each reported camera
     for (auto&& cam : mCameraInfo) {
+        bool isLogicalCam = false;
+        getPhysicalCameraIds(cam.id, isLogicalCam);
+        if (isLogicalCam) {
+            LOG(INFO) << "Skip a logical device, " << cam.id;
+            continue;
+        }
+
         // Read a target resolution from the metadata
         Stream targetCfg = getFirstStreamConfiguration(
                 reinterpret_cast<camera_metadata_t*>(cam.metadata.data()));
@@ -2014,9 +2027,6 @@
             }
         }
 
-        bool isLogicalCam = false;
-        getPhysicalCameraIds(cam.id, isLogicalCam);
-
         std::shared_ptr<IEvsCamera> pCam;
         ASSERT_TRUE(mEnumerator->openCamera(cam.id, targetCfg, &pCam).isOk());
         EXPECT_NE(pCam, nullptr);
@@ -2027,11 +2037,6 @@
         // Request to import buffers
         int delta = 0;
         auto status = pCam->importExternalBuffers(buffers, &delta);
-        if (isLogicalCam) {
-            ASSERT_FALSE(status.isOk());
-            continue;
-        }
-
         ASSERT_TRUE(status.isOk());
         EXPECT_GE(delta, kBuffersToHold);
 
diff --git a/automotive/vehicle/aidl/Android.bp b/automotive/vehicle/aidl/Android.bp
index 3b93bca..7405d4c 100644
--- a/automotive/vehicle/aidl/Android.bp
+++ b/automotive/vehicle/aidl/Android.bp
@@ -41,6 +41,9 @@
                 "com.android.car.framework",
             ],
         },
+        rust: {
+            enabled: true,
+        },
     },
     versions_with_info: [
         {
diff --git a/automotive/vehicle/aidl_property/Android.bp b/automotive/vehicle/aidl_property/Android.bp
index 19fa4a3..580be68 100644
--- a/automotive/vehicle/aidl_property/Android.bp
+++ b/automotive/vehicle/aidl_property/Android.bp
@@ -42,6 +42,9 @@
                 "com.android.car.framework",
             ],
         },
+        rust: {
+            enabled: true,
+        },
     },
     versions_with_info: [
         {
diff --git a/bluetooth/audio/aidl/aidl_api/android.hardware.bluetooth.audio/current/android/hardware/bluetooth/audio/IBluetoothAudioProvider.aidl b/bluetooth/audio/aidl/aidl_api/android.hardware.bluetooth.audio/current/android/hardware/bluetooth/audio/IBluetoothAudioProvider.aidl
index f155634..87401ff 100644
--- a/bluetooth/audio/aidl/aidl_api/android.hardware.bluetooth.audio/current/android/hardware/bluetooth/audio/IBluetoothAudioProvider.aidl
+++ b/bluetooth/audio/aidl/aidl_api/android.hardware.bluetooth.audio/current/android/hardware/bluetooth/audio/IBluetoothAudioProvider.aidl
@@ -45,7 +45,7 @@
   void setCodecPriority(in android.hardware.bluetooth.audio.CodecId codecId, int priority);
   List<android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioAseConfigurationSetting> getLeAudioAseConfiguration(in @nullable List<android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioDeviceCapabilities> remoteSinkAudioCapabilities, in @nullable List<android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioDeviceCapabilities> remoteSourceAudioCapabilities, in List<android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioConfigurationRequirement> requirements);
   android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioAseQosConfigurationPair getLeAudioAseQosConfiguration(in android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioAseQosConfigurationRequirement qosRequirement);
-  android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioDataPathConfigurationPair getLeAudioAseDatapathConfiguration(in android.hardware.bluetooth.audio.AudioContext context, in android.hardware.bluetooth.audio.LeAudioConfiguration.StreamMap[] streamMap);
+  android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioDataPathConfigurationPair getLeAudioAseDatapathConfiguration(in @nullable android.hardware.bluetooth.audio.IBluetoothAudioProvider.StreamConfig sinkConfig, in @nullable android.hardware.bluetooth.audio.IBluetoothAudioProvider.StreamConfig sourceConfig);
   void onSinkAseMetadataChanged(in android.hardware.bluetooth.audio.IBluetoothAudioProvider.AseState state, int cigId, int cisId, in @nullable android.hardware.bluetooth.audio.MetadataLtv[] metadata);
   void onSourceAseMetadataChanged(in android.hardware.bluetooth.audio.IBluetoothAudioProvider.AseState state, int cigId, int cisId, in @nullable android.hardware.bluetooth.audio.MetadataLtv[] metadata);
   android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioBroadcastConfigurationSetting getLeAudioBroadcastConfiguration(in @nullable List<android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioDeviceCapabilities> remoteSinkAudioCapabilities, in android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioBroadcastConfigurationRequirement requirement);
@@ -146,6 +146,10 @@
     @nullable android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioDataPathConfiguration inputConfig;
     @nullable android.hardware.bluetooth.audio.IBluetoothAudioProvider.LeAudioDataPathConfiguration outputConfig;
   }
+  parcelable StreamConfig {
+    android.hardware.bluetooth.audio.AudioContext context;
+    android.hardware.bluetooth.audio.LeAudioConfiguration.StreamMap[] streamMap;
+  }
   @Backing(type="byte") @VintfStability
   enum AseState {
     ENABLING = 0x00,
diff --git a/bluetooth/audio/aidl/android/hardware/bluetooth/audio/IBluetoothAudioProvider.aidl b/bluetooth/audio/aidl/android/hardware/bluetooth/audio/IBluetoothAudioProvider.aidl
index 2e16f4e..8c6fe69 100644
--- a/bluetooth/audio/aidl/android/hardware/bluetooth/audio/IBluetoothAudioProvider.aidl
+++ b/bluetooth/audio/aidl/android/hardware/bluetooth/audio/IBluetoothAudioProvider.aidl
@@ -519,14 +519,37 @@
     }
 
     /**
+     * Stream Configuration
+     */
+    parcelable StreamConfig {
+        /**
+         * Streaming Audio Context.
+         * This can serve as a hint for selecting the proper configuration by
+         * the offloader.
+         */
+        AudioContext context;
+        /**
+         * Stream configuration, including connection handles and audio channel
+         * allocations.
+         */
+        StreamMap[] streamMap;
+    }
+
+    /**
      * Used to get a data path configuration which dynamically depends on CIS
      * connection handles in StreamMap. This is used if non-dynamic data path
      * was not provided in LeAudioAseConfigurationSetting. Calling this during
      * the unicast audio stream establishment might slightly delay the stream
      * start.
+     *
+     * @param sinkConfig - remote sink device stream configuration
+     * @param sourceConfig - remote source device stream configuration
+     *
+     * @return LeAudioDataPathConfigurationPair
      */
     LeAudioDataPathConfigurationPair getLeAudioAseDatapathConfiguration(
-            in AudioContext context, in StreamMap[] streamMap);
+            in @nullable StreamConfig sinkConfig,
+            in @nullable StreamConfig sourceConfig);
 
     /*
      * Audio Stream Endpoint state used to report Metadata changes on the remote
diff --git a/bluetooth/audio/aidl/default/BluetoothAudioProvider.cpp b/bluetooth/audio/aidl/default/BluetoothAudioProvider.cpp
index bdba898..8d03fae 100644
--- a/bluetooth/audio/aidl/default/BluetoothAudioProvider.cpp
+++ b/bluetooth/audio/aidl/default/BluetoothAudioProvider.cpp
@@ -229,14 +229,17 @@
 };
 
 ndk::ScopedAStatus BluetoothAudioProvider::getLeAudioAseDatapathConfiguration(
-    const ::aidl::android::hardware::bluetooth::audio::AudioContext& in_context,
-    const std::vector<::aidl::android::hardware::bluetooth::audio::
-                          LeAudioConfiguration::StreamMap>& in_streamMap,
+    const std::optional<::aidl::android::hardware::bluetooth::audio::
+                            IBluetoothAudioProvider::StreamConfig>&
+        in_sinkConfig,
+    const std::optional<::aidl::android::hardware::bluetooth::audio::
+                            IBluetoothAudioProvider::StreamConfig>&
+        in_sourceConfig,
     ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider::
         LeAudioDataPathConfigurationPair* _aidl_return) {
   /* TODO: Implement */
-  (void)in_context;
-  (void)in_streamMap;
+  (void)in_sinkConfig;
+  (void)in_sourceConfig;
   (void)_aidl_return;
   return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
 }
diff --git a/bluetooth/audio/aidl/default/BluetoothAudioProvider.h b/bluetooth/audio/aidl/default/BluetoothAudioProvider.h
index 5064869..2c21440 100644
--- a/bluetooth/audio/aidl/default/BluetoothAudioProvider.h
+++ b/bluetooth/audio/aidl/default/BluetoothAudioProvider.h
@@ -71,10 +71,12 @@
       ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider::
           LeAudioAseQosConfigurationPair* _aidl_return) override;
   ndk::ScopedAStatus getLeAudioAseDatapathConfiguration(
-      const ::aidl::android::hardware::bluetooth::audio::AudioContext&
-          in_context,
-      const std::vector<::aidl::android::hardware::bluetooth::audio::
-                            LeAudioConfiguration::StreamMap>& in_streamMap,
+      const std::optional<::aidl::android::hardware::bluetooth::audio::
+                              IBluetoothAudioProvider::StreamConfig>&
+          in_sinkConfig,
+      const std::optional<::aidl::android::hardware::bluetooth::audio::
+                              IBluetoothAudioProvider::StreamConfig>&
+          in_sourceConfig,
       ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider::
           LeAudioDataPathConfigurationPair* _aidl_return) override;
   ndk::ScopedAStatus onSinkAseMetadataChanged(
diff --git a/bluetooth/audio/aidl/vts/VtsHalBluetoothAudioTargetTest.cpp b/bluetooth/audio/aidl/vts/VtsHalBluetoothAudioTargetTest.cpp
index 88f2f97..85bc48a 100644
--- a/bluetooth/audio/aidl/vts/VtsHalBluetoothAudioTargetTest.cpp
+++ b/bluetooth/audio/aidl/vts/VtsHalBluetoothAudioTargetTest.cpp
@@ -120,6 +120,16 @@
     ChannelMode::UNKNOWN, ChannelMode::MONO, ChannelMode::STEREO};
 static std::vector<LatencyMode> latency_modes = {LatencyMode::FREE};
 
+enum class BluetoothAudioHalVersion : int32_t {
+  VERSION_UNAVAILABLE = 0,
+  VERSION_2_0,
+  VERSION_2_1,
+  VERSION_AIDL_V1,
+  VERSION_AIDL_V2,
+  VERSION_AIDL_V3,
+  VERSION_AIDL_V4,
+};
+
 // Some valid configs for HFP PCM configuration (software sessions)
 static constexpr int32_t hfp_sample_rates_[] = {8000, 16000, 32000};
 static constexpr int8_t hfp_bits_per_samples_[] = {16};
@@ -221,7 +231,6 @@
     temp_provider_info_ = std::nullopt;
     auto aidl_reval =
         provider_factory_->getProviderInfo(session_type, &temp_provider_info_);
-    ASSERT_TRUE(aidl_reval.isOk());
   }
 
   void GetProviderCapabilitiesHelper(const SessionType& session_type) {
@@ -623,9 +632,38 @@
       SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH,
       SessionType::A2DP_SOFTWARE_DECODING_DATAPATH,
       SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH,
+  };
+
+  static constexpr SessionType kAndroidVSessionType[] = {
       SessionType::HFP_SOFTWARE_ENCODING_DATAPATH,
       SessionType::HFP_SOFTWARE_DECODING_DATAPATH,
   };
+
+  BluetoothAudioHalVersion GetProviderFactoryInterfaceVersion() {
+    int32_t aidl_version = 0;
+    if (provider_factory_ == nullptr) {
+      return BluetoothAudioHalVersion::VERSION_UNAVAILABLE;
+    }
+
+    auto aidl_retval = provider_factory_->getInterfaceVersion(&aidl_version);
+    if (!aidl_retval.isOk()) {
+      return BluetoothAudioHalVersion::VERSION_UNAVAILABLE;
+    }
+    switch (aidl_version) {
+      case 1:
+        return BluetoothAudioHalVersion::VERSION_AIDL_V1;
+      case 2:
+        return BluetoothAudioHalVersion::VERSION_AIDL_V2;
+      case 3:
+        return BluetoothAudioHalVersion::VERSION_AIDL_V3;
+      case 4:
+        return BluetoothAudioHalVersion::VERSION_AIDL_V4;
+      default:
+        return BluetoothAudioHalVersion::VERSION_UNAVAILABLE;
+    }
+
+    return BluetoothAudioHalVersion::VERSION_UNAVAILABLE;
+  }
 };
 
 /**
@@ -647,6 +685,15 @@
     EXPECT_TRUE(temp_provider_capabilities_.empty() ||
                 audio_provider_ != nullptr);
   }
+  if (GetProviderFactoryInterfaceVersion() >=
+      BluetoothAudioHalVersion::VERSION_AIDL_V4) {
+    for (auto session_type : kAndroidVSessionType) {
+      GetProviderCapabilitiesHelper(session_type);
+      OpenProviderHelper(session_type);
+      EXPECT_TRUE(temp_provider_capabilities_.empty() ||
+                  audio_provider_ != nullptr);
+    }
+  }
 }
 
 /**
@@ -736,8 +783,7 @@
       ASSERT_NE(codec_info.id.getTag(), CodecId::a2dp);
       // The codec info must contain the information
       // for le audio transport.
-      // ASSERT_EQ(codec_info.transport.getTag(),
-      // CodecInfo::Transport::le_audio);
+      ASSERT_EQ(codec_info.transport.getTag(), CodecInfo::Transport::leAudio);
     }
   }
 }
@@ -1465,8 +1511,8 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH can be started and stopped with
- * different PCM config
+ * SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH can be started and stopped
+ * with different PCM config
  */
 TEST_P(BluetoothAudioProviderA2dpEncodingSoftwareAidl,
        StartAndEndA2dpEncodingSoftwareSessionWithPossiblePcmConfig) {
@@ -1503,6 +1549,10 @@
  public:
   virtual void SetUp() override {
     BluetoothAudioProviderFactoryAidl::SetUp();
+    if (GetProviderFactoryInterfaceVersion() <
+        BluetoothAudioHalVersion::VERSION_AIDL_V4) {
+      GTEST_SKIP();
+    }
     GetProviderCapabilitiesHelper(SessionType::HFP_SOFTWARE_ENCODING_DATAPATH);
     OpenProviderHelper(SessionType::HFP_SOFTWARE_ENCODING_DATAPATH);
     ASSERT_NE(audio_provider_, nullptr);
@@ -1570,6 +1620,10 @@
  public:
   virtual void SetUp() override {
     BluetoothAudioProviderFactoryAidl::SetUp();
+    if (GetProviderFactoryInterfaceVersion() <
+        BluetoothAudioHalVersion::VERSION_AIDL_V4) {
+      GTEST_SKIP();
+    }
     GetProviderCapabilitiesHelper(SessionType::HFP_SOFTWARE_DECODING_DATAPATH);
     OpenProviderHelper(SessionType::HFP_SOFTWARE_DECODING_DATAPATH);
     ASSERT_NE(audio_provider_, nullptr);
@@ -1658,13 +1712,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped with
- * SBC hardware encoding config
+ * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped
+ * with SBC hardware encoding config
  */
 TEST_P(BluetoothAudioProviderA2dpEncodingHardwareAidl,
        StartAndEndA2dpSbcEncodingHardwareSession) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   CodecConfiguration codec_config = {
@@ -1688,13 +1742,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped with
- * AAC hardware encoding config
+ * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped
+ * with AAC hardware encoding config
  */
 TEST_P(BluetoothAudioProviderA2dpEncodingHardwareAidl,
        StartAndEndA2dpAacEncodingHardwareSession) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   CodecConfiguration codec_config = {
@@ -1718,13 +1772,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped with
- * LDAC hardware encoding config
+ * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped
+ * with LDAC hardware encoding config
  */
 TEST_P(BluetoothAudioProviderA2dpEncodingHardwareAidl,
        StartAndEndA2dpLdacEncodingHardwareSession) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   CodecConfiguration codec_config = {
@@ -1748,13 +1802,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped with
- * Opus hardware encoding config
+ * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped
+ * with Opus hardware encoding config
  */
 TEST_P(BluetoothAudioProviderA2dpEncodingHardwareAidl,
        StartAndEndA2dpOpusEncodingHardwareSession) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   CodecConfiguration codec_config = {
@@ -1778,13 +1832,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped with
- * AptX hardware encoding config
+ * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped
+ * with AptX hardware encoding config
  */
 TEST_P(BluetoothAudioProviderA2dpEncodingHardwareAidl,
        StartAndEndA2dpAptxEncodingHardwareSession) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   for (auto codec_type : {CodecType::APTX, CodecType::APTX_HD}) {
@@ -1814,13 +1868,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped with
- * an invalid codec config
+ * SessionType::A2DP_HARDWARE_ENCODING_DATAPATH can be started and stopped
+ * with an invalid codec config
  */
 TEST_P(BluetoothAudioProviderA2dpEncodingHardwareAidl,
        StartAndEndA2dpEncodingHardwareSessionInvalidCodecConfig) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
   ASSERT_NE(audio_provider_, nullptr);
 
@@ -1886,6 +1940,10 @@
  public:
   virtual void SetUp() override {
     BluetoothAudioProviderFactoryAidl::SetUp();
+    if (GetProviderFactoryInterfaceVersion() <
+        BluetoothAudioHalVersion::VERSION_AIDL_V4) {
+      GTEST_SKIP();
+    }
     OpenProviderHelper(SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH);
     // Can open or empty capability
     ASSERT_TRUE(temp_provider_capabilities_.empty() ||
@@ -2419,8 +2477,12 @@
 TEST_P(
     BluetoothAudioProviderLeAudioOutputHardwareAidl,
     StartAndEndLeAudioOutputSessionWithPossibleUnicastConfigFromProviderInfo) {
+  if (GetProviderFactoryInterfaceVersion() <
+      BluetoothAudioHalVersion::VERSION_AIDL_V4) {
+    GTEST_SKIP();
+  }
   if (!IsOffloadOutputProviderInfoSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   auto lc3_codec_configs = GetUnicastLc3SupportedListFromProviderInfo();
@@ -2444,6 +2506,10 @@
 
 TEST_P(BluetoothAudioProviderLeAudioOutputHardwareAidl,
        GetEmptyAseConfigurationEmptyCapability) {
+  if (GetProviderFactoryInterfaceVersion() <
+      BluetoothAudioHalVersion::VERSION_AIDL_V4) {
+    GTEST_SKIP();
+  }
   std::vector<std::optional<LeAudioDeviceCapabilities>> empty_capability;
   std::vector<LeAudioConfigurationRequirement> empty_requirement;
   std::vector<LeAudioAseConfigurationSetting> configurations;
@@ -2465,6 +2531,10 @@
 
 TEST_P(BluetoothAudioProviderLeAudioOutputHardwareAidl,
        GetEmptyAseConfigurationMismatchedRequirement) {
+  if (GetProviderFactoryInterfaceVersion() <
+      BluetoothAudioHalVersion::VERSION_AIDL_V4) {
+    GTEST_SKIP();
+  }
   std::vector<std::optional<LeAudioDeviceCapabilities>> capabilities = {
       GetDefaultRemoteCapability()};
 
@@ -2489,6 +2559,10 @@
 }
 
 TEST_P(BluetoothAudioProviderLeAudioOutputHardwareAidl, GetQoSConfiguration) {
+  if (GetProviderFactoryInterfaceVersion() <
+      BluetoothAudioHalVersion::VERSION_AIDL_V4) {
+    GTEST_SKIP();
+  }
   IBluetoothAudioProvider::LeAudioAseQosConfigurationRequirement requirement;
   std::vector<IBluetoothAudioProvider::LeAudioAseQosConfiguration>
       QoSConfigurations;
@@ -2506,6 +2580,40 @@
   // QoS Configurations should not be empty, as we searched for all contexts
   ASSERT_FALSE(QoSConfigurations.empty());
 }
+
+TEST_P(BluetoothAudioProviderLeAudioOutputHardwareAidl,
+       GetDataPathConfiguration) {
+  IBluetoothAudioProvider::StreamConfig sink_requirement;
+  IBluetoothAudioProvider::StreamConfig source_requirement;
+  std::vector<IBluetoothAudioProvider::LeAudioDataPathConfiguration>
+      DataPathConfigurations;
+  bool is_supported = false;
+
+  for (auto bitmask : all_context_bitmasks) {
+    sink_requirement.context = GetAudioContext(bitmask);
+    source_requirement.context = GetAudioContext(bitmask);
+    IBluetoothAudioProvider::LeAudioDataPathConfigurationPair result;
+    auto aidl_retval = audio_provider_->getLeAudioAseDatapathConfiguration(
+        sink_requirement, source_requirement, &result);
+    if (!aidl_retval.isOk()) {
+      // If not OK, then it could be not supported, as it is an optional feature
+      ASSERT_EQ(aidl_retval.getExceptionCode(), EX_UNSUPPORTED_OPERATION);
+    } else {
+      is_supported = true;
+      if (result.inputConfig.has_value())
+        DataPathConfigurations.push_back(result.inputConfig.value());
+      if (result.inputConfig.has_value())
+        DataPathConfigurations.push_back(result.inputConfig.value());
+    }
+  }
+
+  if (is_supported) {
+    // Datapath Configurations should not be empty, as we searched for all
+    // contexts
+    ASSERT_FALSE(DataPathConfigurations.empty());
+  }
+}
+
 /**
  * Test whether each provider of type
  * SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH can be started and
@@ -2514,7 +2622,7 @@
 TEST_P(BluetoothAudioProviderLeAudioOutputHardwareAidl,
        StartAndEndLeAudioOutputSessionWithPossibleUnicastConfig) {
   if (!IsOffloadOutputSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   auto lc3_codec_configs =
@@ -2547,7 +2655,7 @@
 TEST_P(BluetoothAudioProviderLeAudioOutputHardwareAidl,
        DISABLED_StartAndEndLeAudioOutputSessionWithInvalidAudioConfiguration) {
   if (!IsOffloadOutputSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   auto lc3_codec_configs =
@@ -2585,7 +2693,7 @@
 TEST_P(BluetoothAudioProviderLeAudioOutputHardwareAidl,
        StartAndEndLeAudioOutputSessionWithAptxAdaptiveLeUnicastConfig) {
   if (!IsOffloadOutputSupported()) {
-    return;
+    GTEST_SKIP();
   }
   for (auto codec_type :
        {CodecType::APTX_ADAPTIVE_LE, CodecType::APTX_ADAPTIVE_LEX}) {
@@ -2622,7 +2730,7 @@
     BluetoothAudioProviderLeAudioOutputHardwareAidl,
     BluetoothAudioProviderLeAudioOutputHardwareAidl_StartAndEndLeAudioOutputSessionWithInvalidAptxAdaptiveLeAudioConfiguration) {
   if (!IsOffloadOutputSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   for (auto codec_type :
@@ -2708,7 +2816,7 @@
     BluetoothAudioProviderLeAudioInputHardwareAidl,
     StartAndEndLeAudioInputSessionWithPossibleUnicastConfigFromProviderInfo) {
   if (!IsOffloadOutputProviderInfoSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   auto lc3_codec_configs = GetUnicastLc3SupportedListFromProviderInfo();
@@ -2738,7 +2846,7 @@
 TEST_P(BluetoothAudioProviderLeAudioInputHardwareAidl,
        StartAndEndLeAudioInputSessionWithPossibleUnicastConfig) {
   if (!IsOffloadInputSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   auto lc3_codec_configs =
@@ -2771,7 +2879,7 @@
 TEST_P(BluetoothAudioProviderLeAudioInputHardwareAidl,
        DISABLED_StartAndEndLeAudioInputSessionWithInvalidAudioConfiguration) {
   if (!IsOffloadInputSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   auto lc3_codec_configs =
@@ -2829,16 +2937,16 @@
 
 /**
  * Test whether each provider of type
- * SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH can be started and
- * stopped
+ * SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH can be started
+ * and stopped
  */
 TEST_P(BluetoothAudioProviderLeAudioBroadcastSoftwareAidl,
        OpenLeAudioOutputSoftwareProvider) {}
 
 /**
  * Test whether each provider of type
- * SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH can be started and
- * stopped with different PCM config
+ * SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH can be started
+ * and stopped with different PCM config
  */
 TEST_P(BluetoothAudioProviderLeAudioBroadcastSoftwareAidl,
        StartAndEndLeAudioOutputSessionWithPossiblePcmConfig) {
@@ -3012,6 +3120,10 @@
 TEST_P(
     BluetoothAudioProviderLeAudioBroadcastHardwareAidl,
     StartAndEndLeAudioBroadcastSessionWithPossibleUnicastConfigFromProviderInfo) {
+  if (GetProviderFactoryInterfaceVersion() <
+      BluetoothAudioHalVersion::VERSION_AIDL_V4) {
+    GTEST_SKIP();
+  }
   if (!IsBroadcastOffloadProviderInfoSupported()) {
     return;
   }
@@ -3043,6 +3155,10 @@
 
 TEST_P(BluetoothAudioProviderLeAudioBroadcastHardwareAidl,
        GetEmptyBroadcastConfigurationEmptyCapability) {
+  if (GetProviderFactoryInterfaceVersion() <
+      BluetoothAudioHalVersion::VERSION_AIDL_V4) {
+    GTEST_SKIP();
+  }
   std::vector<std::optional<LeAudioDeviceCapabilities>> empty_capability;
   IBluetoothAudioProvider::LeAudioBroadcastConfigurationRequirement
       empty_requirement;
@@ -3157,8 +3273,8 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_SOFTWARE_DECODING_DATAPATH can be started and stopped with
- * different PCM config
+ * SessionType::A2DP_SOFTWARE_DECODING_DATAPATH can be started and stopped
+ * with different PCM config
  */
 TEST_P(BluetoothAudioProviderA2dpDecodingSoftwareAidl,
        StartAndEndA2dpDecodingSoftwareSessionWithPossiblePcmConfig) {
@@ -3219,13 +3335,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped with
- * SBC hardware encoding config
+ * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped
+ * with SBC hardware encoding config
  */
 TEST_P(BluetoothAudioProviderA2dpDecodingHardwareAidl,
        StartAndEndA2dpSbcDecodingHardwareSession) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   CodecConfiguration codec_config = {
@@ -3249,13 +3365,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped with
- * AAC hardware encoding config
+ * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped
+ * with AAC hardware encoding config
  */
 TEST_P(BluetoothAudioProviderA2dpDecodingHardwareAidl,
        StartAndEndA2dpAacDecodingHardwareSession) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   CodecConfiguration codec_config = {
@@ -3279,13 +3395,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped with
- * LDAC hardware encoding config
+ * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped
+ * with LDAC hardware encoding config
  */
 TEST_P(BluetoothAudioProviderA2dpDecodingHardwareAidl,
        StartAndEndA2dpLdacDecodingHardwareSession) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   CodecConfiguration codec_config = {
@@ -3309,13 +3425,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped with
- * Opus hardware encoding config
+ * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped
+ * with Opus hardware encoding config
  */
 TEST_P(BluetoothAudioProviderA2dpDecodingHardwareAidl,
        StartAndEndA2dpOpusDecodingHardwareSession) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   CodecConfiguration codec_config = {
@@ -3339,13 +3455,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped with
- * AptX hardware encoding config
+ * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped
+ * with AptX hardware encoding config
  */
 TEST_P(BluetoothAudioProviderA2dpDecodingHardwareAidl,
        StartAndEndA2dpAptxDecodingHardwareSession) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
 
   for (auto codec_type : {CodecType::APTX, CodecType::APTX_HD}) {
@@ -3375,13 +3491,13 @@
 
 /**
  * Test whether each provider of type
- * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped with
- * an invalid codec config
+ * SessionType::A2DP_HARDWARE_DECODING_DATAPATH can be started and stopped
+ * with an invalid codec config
  */
 TEST_P(BluetoothAudioProviderA2dpDecodingHardwareAidl,
        StartAndEndA2dpDecodingHardwareSessionInvalidCodecConfig) {
   if (!IsOffloadSupported()) {
-    return;
+    GTEST_SKIP();
   }
   ASSERT_NE(audio_provider_, nullptr);
 
diff --git a/bluetooth/audio/utils/aidl_session/BluetoothAudioCodecs.cpp b/bluetooth/audio/utils/aidl_session/BluetoothAudioCodecs.cpp
index 216e169..d37825a 100644
--- a/bluetooth/audio/utils/aidl_session/BluetoothAudioCodecs.cpp
+++ b/bluetooth/audio/utils/aidl_session/BluetoothAudioCodecs.cpp
@@ -428,7 +428,7 @@
   if (kDefaultOffloadLeAudioCodecInfoMap.empty()) {
     auto le_audio_offload_setting =
         BluetoothLeAudioCodecsProvider::ParseFromLeAudioOffloadSettingFile();
-    auto kDefaultOffloadLeAudioCodecInfoMap =
+    kDefaultOffloadLeAudioCodecInfoMap =
         BluetoothLeAudioCodecsProvider::GetLeAudioCodecInfo(
             le_audio_offload_setting);
   }
diff --git a/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.cpp b/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.cpp
index b6df67e..473777c 100644
--- a/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.cpp
+++ b/bluetooth/audio/utils/aidl_session/BluetoothLeAudioCodecsProvider.cpp
@@ -43,9 +43,6 @@
 
 std::optional<setting::LeAudioOffloadSetting>
 BluetoothLeAudioCodecsProvider::ParseFromLeAudioOffloadSettingFile() {
-  if (!leAudioCodecCapabilities.empty() || isInvalidFileContent) {
-    return std::nullopt;
-  }
   auto le_audio_offload_setting =
       setting::readLeAudioOffloadSetting(kLeAudioCodecCapabilitiesFile);
   if (!le_audio_offload_setting.has_value()) {
@@ -77,8 +74,6 @@
   for (auto& p : configuration_map_) {
     // Initialize new CodecInfo for the config
     auto config_name = p.first;
-    if (config_codec_info_map_.count(config_name) == 0)
-      config_codec_info_map_[config_name] = CodecInfo();
 
     // Getting informations from codecConfig and strategyConfig
     const auto codec_config_name = p.second.getCodecConfiguration();
@@ -92,6 +87,9 @@
     if (strategy_configuration_map_iter == strategy_configuration_map_.end())
       continue;
 
+    if (config_codec_info_map_.count(config_name) == 0)
+      config_codec_info_map_[config_name] = CodecInfo();
+
     const auto& codec_config = codec_configuration_map_iter->second;
     const auto codec = codec_config.getCodec();
     const auto& strategy_config = strategy_configuration_map_iter->second;
@@ -137,12 +135,19 @@
     }
   }
 
-  // Goes through every scenario, deduplicate configuration
+  // Goes through every scenario, deduplicate configuration, skip the invalid
+  // config references (e.g. the "invalid" entries in the xml file).
   std::set<std::string> encoding_config, decoding_config, broadcast_config;
   for (auto& s : supported_scenarios_) {
-    if (s.hasEncode()) encoding_config.insert(s.getEncode());
-    if (s.hasDecode()) decoding_config.insert(s.getDecode());
-    if (s.hasBroadcast()) broadcast_config.insert(s.getBroadcast());
+    if (s.hasEncode() && config_codec_info_map_.count(s.getEncode())) {
+      encoding_config.insert(s.getEncode());
+    }
+    if (s.hasDecode() && config_codec_info_map_.count(s.getDecode())) {
+      decoding_config.insert(s.getDecode());
+    }
+    if (s.hasBroadcast() && config_codec_info_map_.count(s.getBroadcast())) {
+      broadcast_config.insert(s.getBroadcast());
+    }
   }
 
   // Split by session types and add results
diff --git a/bluetooth/finder/aidl/Android.bp b/bluetooth/finder/aidl/Android.bp
index e606d2d..24f5ca5 100644
--- a/bluetooth/finder/aidl/Android.bp
+++ b/bluetooth/finder/aidl/Android.bp
@@ -28,7 +28,11 @@
         },
         java: {
             enabled: true,
-            platform_apis: true,
+            sdk_version: "module_current",
+            min_sdk_version: "30",
+            apex_available: [
+                "com.android.tethering",
+            ],
         },
     },
 }
diff --git a/bluetooth/finder/aidl/android/hardware/bluetooth/finder/Eid.aidl b/bluetooth/finder/aidl/android/hardware/bluetooth/finder/Eid.aidl
index ae9b159..0de306f 100644
--- a/bluetooth/finder/aidl/android/hardware/bluetooth/finder/Eid.aidl
+++ b/bluetooth/finder/aidl/android/hardware/bluetooth/finder/Eid.aidl
@@ -17,7 +17,7 @@
 package android.hardware.bluetooth.finder;
 
 /**
- * Ephemeral Identifier
+ * Find My Device network ephemeral identifier
  */
 @VintfStability
 parcelable Eid {
diff --git a/bluetooth/finder/aidl/android/hardware/bluetooth/finder/IBluetoothFinder.aidl b/bluetooth/finder/aidl/android/hardware/bluetooth/finder/IBluetoothFinder.aidl
index 615739b..a374c2a 100644
--- a/bluetooth/finder/aidl/android/hardware/bluetooth/finder/IBluetoothFinder.aidl
+++ b/bluetooth/finder/aidl/android/hardware/bluetooth/finder/IBluetoothFinder.aidl
@@ -21,7 +21,7 @@
 @VintfStability
 interface IBluetoothFinder {
     /**
-     * API to set the EIDs to the Bluetooth Controller
+     * API to set Find My Device network EIDs to the Bluetooth Controller
      *
      * @param eids array of 20 bytes EID to the Bluetooth
      * controller
diff --git a/health/2.0/README.md b/health/2.0/README.md
index 8a7c922..1c636c7 100644
--- a/health/2.0/README.md
+++ b/health/2.0/README.md
@@ -1,181 +1,7 @@
-# Implement the 2.1 HAL instead!
+# Deprecated.
 
-It is strongly recommended that you implement the 2.1 HAL directly. See
-`hardware/interfaces/health/2.1/README.md` for more details.
+Health HIDL HAL 2.0 is deprecated and subject to removal. Please
+implement the Health AIDL HAL instead.
 
-# Upgrading from Health 1.0 HAL
-
-1. Remove `android.hardware.health@1.0*` from `PRODUCT_PACKAGES`
-   in `device/<manufacturer>/<device>/device.mk`
-
-1. If the device does not have a vendor-specific `libhealthd` AND does not
-   implement storage-related APIs, just do the following:
-
-   ```mk
-   PRODUCT_PACKAGES += android.hardware.health@2.0-service
-   ```
-
-   Otherwise, continue to the next step.
-
-1. Create directory
-   `device/<manufacturer>/<device>/health`
-
-1. Create `device/<manufacturer>/<device>/health/Android.bp`
-   (or equivalent `device/<manufacturer>/<device>/health/Android.mk`)
-
-    ```bp
-    cc_binary {
-        name: "android.hardware.health@2.0-service.<device>",
-        init_rc: ["android.hardware.health@2.0-service.<device>.rc"],
-        proprietary: true,
-        relative_install_path: "hw",
-        srcs: [
-            "HealthService.cpp",
-        ],
-
-        cflags: [
-            "-Wall",
-            "-Werror",
-        ],
-
-        static_libs: [
-            "android.hardware.health@2.0-impl",
-            "android.hardware.health@1.0-convert",
-            "libhealthservice",
-            "libbatterymonitor",
-        ],
-
-        shared_libs: [
-            "libbase",
-            "libcutils",
-            "libhidlbase",
-            "libutils",
-            "android.hardware.health@2.0",
-        ],
-
-        header_libs: ["libhealthd_headers"],
-
-        overrides: [
-            "healthd",
-        ],
-    }
-    ```
-
-    1. (recommended) To remove `healthd` from the build, keep "overrides" section.
-    1. To keep `healthd` in the build, remove "overrides" section.
-
-1. Create `device/<manufacturer>/<device>/health/android.hardware.health@2.0-service.<device>.rc`
-
-    ```rc
-    service vendor.health-hal-2-0 /vendor/bin/hw/android.hardware.health@2.0-service.<device>
-        class hal
-        user system
-        group system
-        capabilities WAKE_ALARM
-        file /dev/kmsg w
-    ```
-
-1. Create `device/<manufacturer>/<device>/health/HealthService.cpp`:
-
-    ```c++
-    #include <health2/service.h>
-    int main() { return health_service_main(); }
-    ```
-
-1. `libhealthd` dependency:
-
-    1. If the device has a vendor-specific `libhealthd.<soc>`, add it to static_libs.
-
-    1. If the device does not have a vendor-specific `libhealthd`, add the following
-        lines to `HealthService.cpp`:
-
-        ```c++
-        #include <healthd/healthd.h>
-        void healthd_board_init(struct healthd_config*) {}
-
-        int healthd_board_battery_update(struct android::BatteryProperties*) {
-            // return 0 to log periodic polled battery status to kernel log
-            return 0;
-        }
-        ```
-
-1. Storage related APIs:
-
-    1. If the device does not implement `IHealth.getDiskStats` and
-        `IHealth.getStorageInfo`, add `libhealthstoragedefault` to `static_libs`.
-
-    1. If the device implements one of these two APIs, add and implement the
-        following functions in `HealthService.cpp`:
-
-        ```c++
-        void get_storage_info(std::vector<struct StorageInfo>& info) {
-            // ...
-        }
-        void get_disk_stats(std::vector<struct DiskStats>& stats) {
-            // ...
-        }
-        ```
-
-1. Update necessary SELinux permissions. For example,
-
-    ```
-    # device/<manufacturer>/<device>/sepolicy/vendor/file_contexts
-    /vendor/bin/hw/android\.hardware\.health@2\.0-service\.<device> u:object_r:hal_health_default_exec:s0
-
-    # device/<manufacturer>/<device>/sepolicy/vendor/hal_health_default.te
-    # Add device specific permissions to hal_health_default domain, especially
-    # if a device-specific libhealthd is used and/or device-specific storage related
-    # APIs are implemented.
-    ```
-
-1. Implementing health HAL in recovery. The health HAL is used for battery
-status checks during OTA for non-A/B devices. If the health HAL is not
-implemented in recovery, `is_battery_ok()` will always return `true`.
-
-    1. If the device does not have a vendor-specific `libhealthd`, nothing needs to
-    be done. A "backup" implementation is provided in
-    `android.hardware.health@2.0-impl-default`, which is always installed to recovery
-    image by default.
-
-    1. If the device does have a vendor-specific `libhealthd`, implement the following
-    module and include it in `PRODUCT_PACKAGES` (replace `<device>` with appropriate
-    strings):
-
-    ```bp
-    // Android.bp
-    cc_library_shared {
-        name: "android.hardware.health@2.0-impl-<device>",
-        recovery_available: true,
-        relative_install_path: "hw",
-        static_libs: [
-            "android.hardware.health@2.0-impl",
-            "libhealthd.<device>"
-            // Include the following or implement device-specific storage APIs
-            "libhealthstoragedefault",
-        ],
-        srcs: [
-            "HealthImpl.cpp",
-        ],
-        overrides: [
-            "android.hardware.health@2.0-impl-default",
-        ],
-    }
-    ```
-
-    ```c++
-    // HealthImpl.cpp
-    #include <health2/Health.h>
-    #include <healthd/healthd.h>
-    using android::hardware::health::V2_0::IHealth;
-    using android::hardware::health::V2_0::implementation::Health;
-    extern "C" IHealth* HIDL_FETCH_IHealth(const char* name) {
-        const static std::string providedInstance{"default"};
-        if (providedInstance != name) return nullptr;
-        return Health::initInstance(&gHealthdConfig).get();
-    }
-    ```
-
-    ```mk
-    # device.mk
-    PRODUCT_PACKAGES += android.hardware.health@2.0-impl-<device>
-    ```
+See [`hardware/interfaces/health/aidl/README.md`](../aidl/README.md) for
+details.
diff --git a/health/2.0/default/Android.bp b/health/2.0/default/Android.bp
deleted file mode 100644
index 73cd553..0000000
--- a/health/2.0/default/Android.bp
+++ /dev/null
@@ -1,72 +0,0 @@
-package {
-    // See: http://go/android-license-faq
-    // A large-scale-change added 'default_applicable_licenses' to import
-    // all of the 'license_kinds' from "hardware_interfaces_license"
-    // to get the below license kinds:
-    //   SPDX-license-identifier-Apache-2.0
-    default_applicable_licenses: ["hardware_interfaces_license"],
-}
-
-cc_defaults {
-    name: "android.hardware.health@2.0-impl_defaults",
-
-    recovery_available: true,
-    cflags: [
-        "-Wall",
-        "-Werror",
-    ],
-
-    shared_libs: [
-        "libbase",
-        "libhidlbase",
-        "liblog",
-        "libutils",
-        "libcutils",
-        "android.hardware.health@2.0",
-    ],
-
-    static_libs: [
-        "libbatterymonitor",
-        "android.hardware.health@1.0-convert",
-    ],
-}
-
-// Helper library for implementing health HAL. It is recommended that a health
-// service or passthrough HAL link to this library.
-cc_library_static {
-    name: "android.hardware.health@2.0-impl",
-    defaults: ["android.hardware.health@2.0-impl_defaults"],
-
-    vendor_available: true,
-    srcs: [
-        "Health.cpp",
-        "healthd_common_adapter.cpp",
-    ],
-
-    whole_static_libs: [
-        "libhealthloop",
-    ],
-
-    export_include_dirs: ["include"],
-}
-
-// Default passthrough implementation for recovery. Vendors can implement
-// android.hardware.health@2.0-impl-recovery-<device> to customize the behavior
-// of the HAL in recovery.
-// The implementation does NOT start the uevent loop for polling.
-cc_library_shared {
-    name: "android.hardware.health@2.0-impl-default",
-    defaults: ["android.hardware.health@2.0-impl_defaults"],
-
-    recovery_available: true,
-    relative_install_path: "hw",
-
-    static_libs: [
-        "android.hardware.health@2.0-impl",
-        "libhealthstoragedefault",
-    ],
-
-    srcs: [
-        "HealthImplDefault.cpp",
-    ],
-}
diff --git a/health/2.0/default/Health.cpp b/health/2.0/default/Health.cpp
deleted file mode 100644
index 65eada8..0000000
--- a/health/2.0/default/Health.cpp
+++ /dev/null
@@ -1,306 +0,0 @@
-/*
- * Copyright (C) 2018 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.
- */
-#define LOG_TAG "android.hardware.health@2.0-impl"
-#include <android-base/logging.h>
-
-#include <android-base/file.h>
-#include <android/hardware/health/2.0/types.h>
-#include <health2/Health.h>
-
-#include <hal_conversion.h>
-#include <hidl/HidlTransportSupport.h>
-
-using HealthInfo_1_0 = android::hardware::health::V1_0::HealthInfo;
-using android::hardware::health::V1_0::hal_conversion::convertFromHealthInfo;
-
-extern void healthd_battery_update_internal(bool);
-
-namespace android {
-namespace hardware {
-namespace health {
-namespace V2_0 {
-namespace implementation {
-
-sp<Health> Health::instance_;
-
-Health::Health(struct healthd_config* c) {
-    // TODO(b/69268160): remove when libhealthd is removed.
-    healthd_board_init(c);
-    battery_monitor_ = std::make_unique<BatteryMonitor>();
-    battery_monitor_->init(c);
-}
-
-// Methods from IHealth follow.
-Return<Result> Health::registerCallback(const sp<IHealthInfoCallback>& callback) {
-    if (callback == nullptr) {
-        return Result::SUCCESS;
-    }
-
-    {
-        std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
-        callbacks_.push_back(callback);
-        // unlock
-    }
-
-    auto linkRet = callback->linkToDeath(this, 0u /* cookie */);
-    if (!linkRet.withDefault(false)) {
-        LOG(WARNING) << __func__ << "Cannot link to death: "
-                     << (linkRet.isOk() ? "linkToDeath returns false" : linkRet.description());
-        // ignore the error
-    }
-
-    return updateAndNotify(callback);
-}
-
-bool Health::unregisterCallbackInternal(const sp<IBase>& callback) {
-    if (callback == nullptr) return false;
-
-    bool removed = false;
-    std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
-    for (auto it = callbacks_.begin(); it != callbacks_.end();) {
-        if (interfacesEqual(*it, callback)) {
-            it = callbacks_.erase(it);
-            removed = true;
-        } else {
-            ++it;
-        }
-    }
-    (void)callback->unlinkToDeath(this).isOk();  // ignore errors
-    return removed;
-}
-
-Return<Result> Health::unregisterCallback(const sp<IHealthInfoCallback>& callback) {
-    return unregisterCallbackInternal(callback) ? Result::SUCCESS : Result::NOT_FOUND;
-}
-
-template <typename T>
-void getProperty(const std::unique_ptr<BatteryMonitor>& monitor, int id, T defaultValue,
-                 const std::function<void(Result, T)>& callback) {
-    struct BatteryProperty prop;
-    T ret = defaultValue;
-    Result result = Result::SUCCESS;
-    status_t err = monitor->getProperty(static_cast<int>(id), &prop);
-    if (err != OK) {
-        LOG(DEBUG) << "getProperty(" << id << ")"
-                   << " fails: (" << err << ") " << strerror(-err);
-    } else {
-        ret = static_cast<T>(prop.valueInt64);
-    }
-    switch (err) {
-        case OK:
-            result = Result::SUCCESS;
-            break;
-        case NAME_NOT_FOUND:
-            result = Result::NOT_SUPPORTED;
-            break;
-        default:
-            result = Result::UNKNOWN;
-            break;
-    }
-    callback(result, static_cast<T>(ret));
-}
-
-Return<void> Health::getChargeCounter(getChargeCounter_cb _hidl_cb) {
-    getProperty<int32_t>(battery_monitor_, BATTERY_PROP_CHARGE_COUNTER, 0, _hidl_cb);
-    return Void();
-}
-
-Return<void> Health::getCurrentNow(getCurrentNow_cb _hidl_cb) {
-    getProperty<int32_t>(battery_monitor_, BATTERY_PROP_CURRENT_NOW, 0, _hidl_cb);
-    return Void();
-}
-
-Return<void> Health::getCurrentAverage(getCurrentAverage_cb _hidl_cb) {
-    getProperty<int32_t>(battery_monitor_, BATTERY_PROP_CURRENT_AVG, 0, _hidl_cb);
-    return Void();
-}
-
-Return<void> Health::getCapacity(getCapacity_cb _hidl_cb) {
-    getProperty<int32_t>(battery_monitor_, BATTERY_PROP_CAPACITY, 0, _hidl_cb);
-    return Void();
-}
-
-Return<void> Health::getEnergyCounter(getEnergyCounter_cb _hidl_cb) {
-    getProperty<int64_t>(battery_monitor_, BATTERY_PROP_ENERGY_COUNTER, 0, _hidl_cb);
-    return Void();
-}
-
-Return<void> Health::getChargeStatus(getChargeStatus_cb _hidl_cb) {
-    getProperty(battery_monitor_, BATTERY_PROP_BATTERY_STATUS, BatteryStatus::UNKNOWN, _hidl_cb);
-    return Void();
-}
-
-Return<Result> Health::update() {
-    if (!healthd_mode_ops || !healthd_mode_ops->battery_update) {
-        LOG(WARNING) << "health@2.0: update: not initialized. "
-                     << "update() should not be called in charger";
-        return Result::UNKNOWN;
-    }
-
-    // Retrieve all information and call healthd_mode_ops->battery_update, which calls
-    // notifyListeners.
-    battery_monitor_->updateValues();
-    const HealthInfo_1_0& health_info = battery_monitor_->getHealthInfo_1_0();
-    struct BatteryProperties props;
-    convertFromHealthInfo(health_info, &props);
-    bool log = (healthd_board_battery_update(&props) == 0);
-    if (log) {
-        battery_monitor_->logValues();
-    }
-    healthd_mode_ops->battery_update(&props);
-    bool chargerOnline = battery_monitor_->isChargerOnline();
-
-    // adjust uevent / wakealarm periods
-    healthd_battery_update_internal(chargerOnline);
-
-    return Result::SUCCESS;
-}
-
-Return<Result> Health::updateAndNotify(const sp<IHealthInfoCallback>& callback) {
-    std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
-    std::vector<sp<IHealthInfoCallback>> storedCallbacks{std::move(callbacks_)};
-    callbacks_.clear();
-    if (callback != nullptr) {
-        callbacks_.push_back(callback);
-    }
-    Return<Result> result = update();
-    callbacks_ = std::move(storedCallbacks);
-    return result;
-}
-
-void Health::notifyListeners(HealthInfo* healthInfo) {
-    std::vector<StorageInfo> info;
-    get_storage_info(info);
-
-    std::vector<DiskStats> stats;
-    get_disk_stats(stats);
-
-    int32_t currentAvg = 0;
-
-    struct BatteryProperty prop;
-    status_t ret = battery_monitor_->getProperty(BATTERY_PROP_CURRENT_AVG, &prop);
-    if (ret == OK) {
-        currentAvg = static_cast<int32_t>(prop.valueInt64);
-    }
-
-    healthInfo->batteryCurrentAverage = currentAvg;
-    healthInfo->diskStats = stats;
-    healthInfo->storageInfos = info;
-
-    std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
-    for (auto it = callbacks_.begin(); it != callbacks_.end();) {
-        auto ret = (*it)->healthInfoChanged(*healthInfo);
-        if (!ret.isOk() && ret.isDeadObject()) {
-            it = callbacks_.erase(it);
-        } else {
-            ++it;
-        }
-    }
-}
-
-Return<void> Health::debug(const hidl_handle& handle, const hidl_vec<hidl_string>&) {
-    if (handle != nullptr && handle->numFds >= 1) {
-        int fd = handle->data[0];
-        battery_monitor_->dumpState(fd);
-
-        getHealthInfo([fd](auto res, const auto& info) {
-            android::base::WriteStringToFd("\ngetHealthInfo -> ", fd);
-            if (res == Result::SUCCESS) {
-                android::base::WriteStringToFd(toString(info), fd);
-            } else {
-                android::base::WriteStringToFd(toString(res), fd);
-            }
-            android::base::WriteStringToFd("\n", fd);
-        });
-
-        fsync(fd);
-    }
-    return Void();
-}
-
-Return<void> Health::getStorageInfo(getStorageInfo_cb _hidl_cb) {
-    std::vector<struct StorageInfo> info;
-    get_storage_info(info);
-    hidl_vec<struct StorageInfo> info_vec(info);
-    if (!info.size()) {
-        _hidl_cb(Result::NOT_SUPPORTED, info_vec);
-    } else {
-        _hidl_cb(Result::SUCCESS, info_vec);
-    }
-    return Void();
-}
-
-Return<void> Health::getDiskStats(getDiskStats_cb _hidl_cb) {
-    std::vector<struct DiskStats> stats;
-    get_disk_stats(stats);
-    hidl_vec<struct DiskStats> stats_vec(stats);
-    if (!stats.size()) {
-        _hidl_cb(Result::NOT_SUPPORTED, stats_vec);
-    } else {
-        _hidl_cb(Result::SUCCESS, stats_vec);
-    }
-    return Void();
-}
-
-Return<void> Health::getHealthInfo(getHealthInfo_cb _hidl_cb) {
-    using android::hardware::health::V1_0::hal_conversion::convertToHealthInfo;
-
-    updateAndNotify(nullptr);
-    HealthInfo healthInfo = battery_monitor_->getHealthInfo_2_0();
-
-    std::vector<StorageInfo> info;
-    get_storage_info(info);
-
-    std::vector<DiskStats> stats;
-    get_disk_stats(stats);
-
-    int32_t currentAvg = 0;
-
-    struct BatteryProperty prop;
-    status_t ret = battery_monitor_->getProperty(BATTERY_PROP_CURRENT_AVG, &prop);
-    if (ret == OK) {
-        currentAvg = static_cast<int32_t>(prop.valueInt64);
-    }
-
-    healthInfo.batteryCurrentAverage = currentAvg;
-    healthInfo.diskStats = stats;
-    healthInfo.storageInfos = info;
-
-    _hidl_cb(Result::SUCCESS, healthInfo);
-    return Void();
-}
-
-void Health::serviceDied(uint64_t /* cookie */, const wp<IBase>& who) {
-    (void)unregisterCallbackInternal(who.promote());
-}
-
-sp<IHealth> Health::initInstance(struct healthd_config* c) {
-    if (instance_ == nullptr) {
-        instance_ = new Health(c);
-    }
-    return instance_;
-}
-
-sp<Health> Health::getImplementation() {
-    CHECK(instance_ != nullptr);
-    return instance_;
-}
-
-}  // namespace implementation
-}  // namespace V2_0
-}  // namespace health
-}  // namespace hardware
-}  // namespace android
diff --git a/health/2.0/default/HealthImplDefault.cpp b/health/2.0/default/HealthImplDefault.cpp
deleted file mode 100644
index 08fee9e..0000000
--- a/health/2.0/default/HealthImplDefault.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <health2/Health.h>
-#include <healthd/healthd.h>
-
-using android::hardware::health::V2_0::IHealth;
-using android::hardware::health::V2_0::implementation::Health;
-
-static struct healthd_config gHealthdConfig = {
-    .energyCounter = nullptr,
-    .boot_min_cap = 0,
-    .screen_on = nullptr};
-
-void healthd_board_init(struct healthd_config*) {
-    // use defaults
-}
-
-int healthd_board_battery_update(struct android::BatteryProperties*) {
-    // return 0 to log periodic polled battery status to kernel log
-    return 0;
-}
-
-void healthd_mode_default_impl_init(struct healthd_config*) {
-    // noop
-}
-
-int healthd_mode_default_impl_preparetowait(void) {
-    return -1;
-}
-
-void healthd_mode_default_impl_heartbeat(void) {
-    // noop
-}
-
-void healthd_mode_default_impl_battery_update(struct android::BatteryProperties*) {
-    // noop
-}
-
-static struct healthd_mode_ops healthd_mode_default_impl_ops = {
-    .init = healthd_mode_default_impl_init,
-    .preparetowait = healthd_mode_default_impl_preparetowait,
-    .heartbeat = healthd_mode_default_impl_heartbeat,
-    .battery_update = healthd_mode_default_impl_battery_update,
-};
-
-extern "C" IHealth* HIDL_FETCH_IHealth(const char* name) {
-    const static std::string providedInstance{"backup"};
-    healthd_mode_ops = &healthd_mode_default_impl_ops;
-    if (providedInstance == name) {
-        // use defaults
-        // Health class stores static instance
-        return Health::initInstance(&gHealthdConfig).get();
-    }
-    return nullptr;
-}
diff --git a/health/2.0/default/healthd_common_adapter.cpp b/health/2.0/default/healthd_common_adapter.cpp
deleted file mode 100644
index 0b5d869..0000000
--- a/health/2.0/default/healthd_common_adapter.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2019 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.
- */
-
-// Support legacy functions in healthd/healthd.h using healthd_mode_ops.
-// New code should use HealthLoop directly instead.
-
-#include <memory>
-
-#include <cutils/klog.h>
-#include <health/HealthLoop.h>
-#include <health2/Health.h>
-#include <healthd/healthd.h>
-
-using android::hardware::health::HealthLoop;
-using android::hardware::health::V2_0::implementation::Health;
-
-struct healthd_mode_ops* healthd_mode_ops = nullptr;
-
-// Adapter of HealthLoop to use legacy healthd_mode_ops.
-class HealthLoopAdapter : public HealthLoop {
-   public:
-    // Expose internal functions, assuming clients calls them in the same thread
-    // where StartLoop is called.
-    int RegisterEvent(int fd, BoundFunction func, EventWakeup wakeup) {
-        return HealthLoop::RegisterEvent(fd, func, wakeup);
-    }
-    void AdjustWakealarmPeriods(bool charger_online) {
-        return HealthLoop::AdjustWakealarmPeriods(charger_online);
-    }
-   protected:
-    void Init(healthd_config* config) override { healthd_mode_ops->init(config); }
-    void Heartbeat() override { healthd_mode_ops->heartbeat(); }
-    int PrepareToWait() override { return healthd_mode_ops->preparetowait(); }
-    void ScheduleBatteryUpdate() override { Health::getImplementation()->update(); }
-};
-static std::unique_ptr<HealthLoopAdapter> health_loop;
-
-int healthd_register_event(int fd, void (*handler)(uint32_t), EventWakeup wakeup) {
-    if (!health_loop) return -1;
-
-    auto wrapped_handler = [handler](auto*, uint32_t epevents) { handler(epevents); };
-    return health_loop->RegisterEvent(fd, wrapped_handler, wakeup);
-}
-
-void healthd_battery_update_internal(bool charger_online) {
-    if (!health_loop) return;
-    health_loop->AdjustWakealarmPeriods(charger_online);
-}
-
-int healthd_main() {
-    if (!healthd_mode_ops) {
-        KLOG_ERROR("healthd ops not set, exiting\n");
-        exit(1);
-    }
-
-    health_loop = std::make_unique<HealthLoopAdapter>();
-
-    int ret = health_loop->StartLoop();
-
-    // Should not reach here. The following will exit().
-    health_loop.reset();
-
-    return ret;
-}
diff --git a/health/2.0/default/include/health2/Health.h b/health/2.0/default/include/health2/Health.h
deleted file mode 100644
index 6410474..0000000
--- a/health/2.0/default/include/health2/Health.h
+++ /dev/null
@@ -1,79 +0,0 @@
-#ifndef ANDROID_HARDWARE_HEALTH_V2_0_HEALTH_H
-#define ANDROID_HARDWARE_HEALTH_V2_0_HEALTH_H
-
-#include <memory>
-#include <vector>
-
-#include <android/hardware/health/1.0/types.h>
-#include <android/hardware/health/2.0/IHealth.h>
-#include <healthd/BatteryMonitor.h>
-#include <hidl/Status.h>
-
-using android::hardware::health::V2_0::StorageInfo;
-using android::hardware::health::V2_0::DiskStats;
-
-void get_storage_info(std::vector<struct StorageInfo>& info);
-void get_disk_stats(std::vector<struct DiskStats>& stats);
-
-namespace android {
-namespace hardware {
-namespace health {
-namespace V2_0 {
-namespace implementation {
-
-using V1_0::BatteryStatus;
-
-using ::android::hidl::base::V1_0::IBase;
-
-struct Health : public IHealth, hidl_death_recipient {
-   public:
-    static sp<IHealth> initInstance(struct healthd_config* c);
-    // Should only be called by implementation itself (-impl, -service).
-    // Clients should not call this function. Instead, initInstance() initializes and returns the
-    // global instance that has fewer functions.
-    static sp<Health> getImplementation();
-
-    Health(struct healthd_config* c);
-
-    void notifyListeners(HealthInfo* info);
-
-    // Methods from IHealth follow.
-    Return<Result> registerCallback(const sp<IHealthInfoCallback>& callback) override;
-    Return<Result> unregisterCallback(const sp<IHealthInfoCallback>& callback) override;
-    Return<Result> update() override;
-    Return<void> getChargeCounter(getChargeCounter_cb _hidl_cb) override;
-    Return<void> getCurrentNow(getCurrentNow_cb _hidl_cb) override;
-    Return<void> getCurrentAverage(getCurrentAverage_cb _hidl_cb) override;
-    Return<void> getCapacity(getCapacity_cb _hidl_cb) override;
-    Return<void> getEnergyCounter(getEnergyCounter_cb _hidl_cb) override;
-    Return<void> getChargeStatus(getChargeStatus_cb _hidl_cb) override;
-    Return<void> getStorageInfo(getStorageInfo_cb _hidl_cb) override;
-    Return<void> getDiskStats(getDiskStats_cb _hidl_cb) override;
-    Return<void> getHealthInfo(getHealthInfo_cb _hidl_cb) override;
-
-    // Methods from ::android::hidl::base::V1_0::IBase follow.
-    Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override;
-
-    void serviceDied(uint64_t cookie, const wp<IBase>& /* who */) override;
-
-   private:
-    static sp<Health> instance_;
-
-    std::recursive_mutex callbacks_lock_;
-    std::vector<sp<IHealthInfoCallback>> callbacks_;
-    std::unique_ptr<BatteryMonitor> battery_monitor_;
-
-    bool unregisterCallbackInternal(const sp<IBase>& cb);
-
-    // update() and only notify the given callback, but none of the other callbacks.
-    // If cb is null, do not notify any callback at all.
-    Return<Result> updateAndNotify(const sp<IHealthInfoCallback>& cb);
-};
-
-}  // namespace implementation
-}  // namespace V2_0
-}  // namespace health
-}  // namespace hardware
-}  // namespace android
-
-#endif  // ANDROID_HARDWARE_HEALTH_V2_0_HEALTH_H
diff --git a/health/2.0/utils/README.md b/health/2.0/utils/README.md
index c59b3f3..3fc8dab 100644
--- a/health/2.0/utils/README.md
+++ b/health/2.0/utils/README.md
@@ -6,25 +6,3 @@
 calling `IHealth::getService()` directly.
 
 Its Java equivalent can be found in `BatteryService.HealthServiceWrapper`.
-
-# libhealthservice
-
-Common code for all (hwbinder) services of the health HAL, including healthd and
-vendor health service `android.hardware.health@2.0-service(.<vendor>)`. `main()` in
-those binaries calls `health_service_main()` directly.
-
-# libhealthstoragedefault
-
-Default implementation for storage related APIs for (hwbinder) services of the
-health HAL. If an implementation of the health HAL do not wish to provide any
-storage info, include this library. Otherwise, it should implement the following
-two functions:
-
-```c++
-void get_storage_info(std::vector<struct StorageInfo>& info) {
-    // ...
-}
-void get_disk_stats(std::vector<struct DiskStats>& stats) {
-    // ...
-}
-```
diff --git a/health/2.0/utils/libhealthhalutils/HealthHalUtils.cpp b/health/2.0/utils/libhealthhalutils/HealthHalUtils.cpp
index 3c353e6..67f0ecc 100644
--- a/health/2.0/utils/libhealthhalutils/HealthHalUtils.cpp
+++ b/health/2.0/utils/libhealthhalutils/HealthHalUtils.cpp
@@ -24,34 +24,14 @@
 namespace health {
 namespace V2_0 {
 
+// Deprecated. Kept to minimize migration cost.
+// The function can be removed once Health 2.1 is removed
+// (i.e. compatibility_matrix.7.xml is the lowest supported level).
 sp<IHealth> get_health_service() {
-    // For the core and vendor variant, the "backup" instance points to healthd,
-    // which is removed.
-    // For the recovery variant, the "backup" instance has a different
-    // meaning. It points to android.hardware.health@2.0-impl-default.recovery
-    // which was assumed by OEMs to be always installed when a
-    // vendor-specific libhealthd is not necessary. Hence, its behavior
-    // is kept. See health/2.0/README.md.
-    // android.hardware.health@2.0-impl-default.recovery, and subsequently the
-    // special handling of recovery mode below, can be removed once health@2.1
-    // is the minimum required version (i.e. compatibility matrix level 5 is the
-    // minimum supported level). Health 2.1 requires OEMs to install the
+    // Health 2.1 requires OEMs to install the
     // implementation to the recovery partition when it is necessary (i.e. on
     // non-A/B devices, where IsBatteryOk() is needed in recovery).
-    for (auto&& instanceName :
-#ifdef __ANDROID_RECOVERY__
-         { "default", "backup" }
-#else
-         {"default"}
-#endif
-    ) {
-        auto ret = IHealth::getService(instanceName);
-        if (ret != nullptr) {
-            return ret;
-        }
-        LOG(INFO) << "health: cannot get " << instanceName << " service";
-    }
-    return nullptr;
+    return IHealth::getService();
 }
 
 }  // namespace V2_0
diff --git a/health/2.0/utils/libhealthservice/Android.bp b/health/2.0/utils/libhealthservice/Android.bp
deleted file mode 100644
index 8023692..0000000
--- a/health/2.0/utils/libhealthservice/Android.bp
+++ /dev/null
@@ -1,38 +0,0 @@
-// Reasonable defaults for android.hardware.health@2.0-service.<device>.
-// Vendor service can customize by implementing functions defined in
-// libhealthd and libhealthstoragedefault.
-
-
-package {
-    // See: http://go/android-license-faq
-    // A large-scale-change added 'default_applicable_licenses' to import
-    // all of the 'license_kinds' from "hardware_interfaces_license"
-    // to get the below license kinds:
-    //   SPDX-license-identifier-Apache-2.0
-    default_applicable_licenses: ["hardware_interfaces_license"],
-}
-
-cc_library_static {
-    name: "libhealthservice",
-    vendor_available: true,
-    srcs: ["HealthServiceCommon.cpp"],
-
-    export_include_dirs: ["include"],
-
-    cflags: [
-        "-Wall",
-        "-Werror",
-    ],
-    shared_libs: [
-        "android.hardware.health@2.0",
-    ],
-    static_libs: [
-        "android.hardware.health@2.0-impl",
-        "android.hardware.health@1.0-convert",
-    ],
-    export_static_lib_headers: [
-        "android.hardware.health@1.0-convert",
-    ],
-    header_libs: ["libhealthd_headers"],
-    export_header_lib_headers: ["libhealthd_headers"],
-}
diff --git a/health/2.0/utils/libhealthservice/HealthServiceCommon.cpp b/health/2.0/utils/libhealthservice/HealthServiceCommon.cpp
deleted file mode 100644
index 039570a..0000000
--- a/health/2.0/utils/libhealthservice/HealthServiceCommon.cpp
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "health@2.0/"
-#include <android-base/logging.h>
-
-#include <android/hardware/health/1.0/types.h>
-#include <hal_conversion.h>
-#include <health2/Health.h>
-#include <health2/service.h>
-#include <healthd/healthd.h>
-#include <hidl/HidlTransportSupport.h>
-#include <hwbinder/IPCThreadState.h>
-
-using android::hardware::IPCThreadState;
-using android::hardware::configureRpcThreadpool;
-using android::hardware::handleTransportPoll;
-using android::hardware::setupTransportPolling;
-using android::hardware::health::V2_0::HealthInfo;
-using android::hardware::health::V1_0::hal_conversion::convertToHealthInfo;
-using android::hardware::health::V2_0::IHealth;
-using android::hardware::health::V2_0::implementation::Health;
-
-extern int healthd_main(void);
-
-static int gBinderFd = -1;
-static std::string gInstanceName;
-
-static void binder_event(uint32_t /*epevents*/) {
-    if (gBinderFd >= 0) handleTransportPoll(gBinderFd);
-}
-
-void healthd_mode_service_2_0_init(struct healthd_config* config) {
-    LOG(INFO) << LOG_TAG << gInstanceName << " Hal is starting up...";
-
-    gBinderFd = setupTransportPolling();
-
-    if (gBinderFd >= 0) {
-        if (healthd_register_event(gBinderFd, binder_event))
-            LOG(ERROR) << LOG_TAG << gInstanceName << ": Register for binder events failed";
-    }
-
-    android::sp<IHealth> service = Health::initInstance(config);
-    CHECK_EQ(service->registerAsService(gInstanceName), android::OK)
-        << LOG_TAG << gInstanceName << ": Failed to register HAL";
-
-    LOG(INFO) << LOG_TAG << gInstanceName << ": Hal init done";
-}
-
-int healthd_mode_service_2_0_preparetowait(void) {
-    IPCThreadState::self()->flushCommands();
-    return -1;
-}
-
-void healthd_mode_service_2_0_heartbeat(void) {
-    // noop
-}
-
-void healthd_mode_service_2_0_battery_update(struct android::BatteryProperties* prop) {
-    HealthInfo info;
-    convertToHealthInfo(prop, info.legacy);
-    Health::getImplementation()->notifyListeners(&info);
-}
-
-static struct healthd_mode_ops healthd_mode_service_2_0_ops = {
-    .init = healthd_mode_service_2_0_init,
-    .preparetowait = healthd_mode_service_2_0_preparetowait,
-    .heartbeat = healthd_mode_service_2_0_heartbeat,
-    .battery_update = healthd_mode_service_2_0_battery_update,
-};
-
-int health_service_main(const char* instance) {
-    gInstanceName = instance;
-    if (gInstanceName.empty()) {
-        gInstanceName = "default";
-    }
-    healthd_mode_ops = &healthd_mode_service_2_0_ops;
-    LOG(INFO) << LOG_TAG << gInstanceName << ": Hal starting main loop...";
-    return healthd_main();
-}
diff --git a/health/2.0/utils/libhealthservice/include/health2/service.h b/health/2.0/utils/libhealthservice/include/health2/service.h
deleted file mode 100644
index d260568..0000000
--- a/health/2.0/utils/libhealthservice/include/health2/service.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_HARDWARE_HEALTH_V2_0_SERVICE_COMMON
-#define ANDROID_HARDWARE_HEALTH_V2_0_SERVICE_COMMON
-
-int health_service_main(const char* instance = "");
-
-#endif  // ANDROID_HARDWARE_HEALTH_V2_0_SERVICE_COMMON
diff --git a/health/2.0/utils/libhealthstoragedefault/Android.bp b/health/2.0/utils/libhealthstoragedefault/Android.bp
deleted file mode 100644
index 3de8789..0000000
--- a/health/2.0/utils/libhealthstoragedefault/Android.bp
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2018 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.
- */
-
-// Default implementation for (passthrough) clients that statically links to
-// android.hardware.health@2.0-impl but do no query for storage related
-// information.
-package {
-    // See: http://go/android-license-faq
-    // A large-scale-change added 'default_applicable_licenses' to import
-    // all of the 'license_kinds' from "hardware_interfaces_license"
-    // to get the below license kinds:
-    //   SPDX-license-identifier-Apache-2.0
-    default_applicable_licenses: ["hardware_interfaces_license"],
-}
-
-cc_library_static {
-    srcs: ["StorageHealthDefault.cpp"],
-    name: "libhealthstoragedefault",
-    vendor_available: true,
-    recovery_available: true,
-    cflags: ["-Werror"],
-    shared_libs: [
-        "android.hardware.health@2.0",
-    ],
-}
diff --git a/health/2.0/utils/libhealthstoragedefault/StorageHealthDefault.cpp b/health/2.0/utils/libhealthstoragedefault/StorageHealthDefault.cpp
deleted file mode 100644
index aba6cc3..0000000
--- a/health/2.0/utils/libhealthstoragedefault/StorageHealthDefault.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "include/StorageHealthDefault.h"
-
-void get_storage_info(std::vector<struct StorageInfo>&) {
-    // Use defaults.
-}
-
-void get_disk_stats(std::vector<struct DiskStats>&) {
-    // Use defaults
-}
diff --git a/health/2.0/utils/libhealthstoragedefault/include/StorageHealthDefault.h b/health/2.0/utils/libhealthstoragedefault/include/StorageHealthDefault.h
deleted file mode 100644
index 85eb210..0000000
--- a/health/2.0/utils/libhealthstoragedefault/include/StorageHealthDefault.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef ANDROID_HARDWARE_HEALTH_V2_0_STORAGE_HEALTH_H
-#define ANDROID_HARDWARE_HEALTH_V2_0_STORAGE_HEALTH_H
-
-#include <android/hardware/health/2.0/types.h>
-
-using android::hardware::health::V2_0::StorageInfo;
-using android::hardware::health::V2_0::DiskStats;
-
-/*
- * Get storage information.
- */
-void get_storage_info(std::vector<struct StorageInfo>& info);
-
-/*
- * Get disk statistics.
- */
-void get_disk_stats(std::vector<struct DiskStats>& stats);
-
-#endif  // ANDROID_HARDWARE_HEALTH_V2_0_STORAGE_HEALTH_H
diff --git a/media/c2/aidl/Android.bp b/media/c2/aidl/Android.bp
index 84cb382..b511e45 100644
--- a/media/c2/aidl/Android.bp
+++ b/media/c2/aidl/Android.bp
@@ -22,6 +22,9 @@
         "android.hardware.common-V2",
         "android.hardware.media.bufferpool2-V1",
     ],
+    include_dirs: [
+        "frameworks/native/aidl/gui",
+    ],
     stability: "vintf",
     backend: {
         cpp: {
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponent.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponent.aidl
index 7d58340..4439bc5 100644
--- a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponent.aidl
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponent.aidl
@@ -45,6 +45,8 @@
   void reset();
   void start();
   void stop();
+  android.hardware.media.c2.IInputSurfaceConnection connectToInputSurface(in android.hardware.media.c2.IInputSurface inputSurface);
+  android.hardware.media.c2.IInputSink asInputSink();
   parcelable BlockPool {
     long blockPoolId;
     android.hardware.media.c2.IConfigurable configurable;
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentStore.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentStore.aidl
index d1b5915..d7a4706 100644
--- a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentStore.aidl
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentStore.aidl
@@ -41,6 +41,7 @@
   android.hardware.media.bufferpool2.IClientManager getPoolClientManager();
   android.hardware.media.c2.StructDescriptor[] getStructDescriptors(in int[] indices);
   android.hardware.media.c2.IComponentStore.ComponentTraits[] listComponents();
+  android.hardware.media.c2.IInputSurface createInputSurface();
   @VintfStability
   parcelable ComponentTraits {
     String name;
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IInputSink.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IInputSink.aidl
new file mode 100644
index 0000000..e6ea4d5
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IInputSink.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+interface IInputSink {
+  void queue(in android.hardware.media.c2.WorkBundle workBundle);
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IInputSurface.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IInputSurface.aidl
new file mode 100644
index 0000000..14455cb
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IInputSurface.aidl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+interface IInputSurface {
+  android.view.Surface getSurface();
+  android.hardware.media.c2.IConfigurable getConfigurable();
+  android.hardware.media.c2.IInputSurfaceConnection connect(in android.hardware.media.c2.IInputSink sink);
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IInputSurfaceConnection.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IInputSurfaceConnection.aidl
new file mode 100644
index 0000000..28fff65
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IInputSurfaceConnection.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+interface IInputSurfaceConnection {
+  void disconnect();
+  void signalEndOfStream();
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/IComponent.aidl b/media/c2/aidl/android/hardware/media/c2/IComponent.aidl
index e96cae5..6bd30b4 100644
--- a/media/c2/aidl/android/hardware/media/c2/IComponent.aidl
+++ b/media/c2/aidl/android/hardware/media/c2/IComponent.aidl
@@ -20,6 +20,9 @@
 import android.hardware.media.c2.IComponentInterface;
 import android.hardware.media.c2.IConfigurable;
 import android.hardware.media.c2.IGraphicBufferAllocator;
+import android.hardware.media.c2.IInputSink;
+import android.hardware.media.c2.IInputSurface;
+import android.hardware.media.c2.IInputSurfaceConnection;
 import android.hardware.media.c2.WorkBundle;
 import android.os.ParcelFileDescriptor;
 
@@ -307,4 +310,32 @@
      *   - `Status::CORRUPTED` - Some unknown error occurred.
      */
     void stop();
+
+    /**
+     * Starts using an input surface.
+     *
+     * The component must be in running state.
+     *
+     * @param inputSurface Input surface to connect to.
+     * @return connection `IInputSurfaceConnection` object, which can be used to
+     *     query and configure properties of the connection. This cannot be
+     *     null.
+     * @throws ServiceSpecificException with one of the following values:
+     *   - `Status::CANNOT_DO` - The component does not support an input surface.
+     *   - `Status::BAD_STATE` - The component is not in running state.
+     *   - `Status::DUPLICATE` - The component is already connected to an input surface.
+     *   - `Status::REFUSED`   - The input surface is already in use.
+     *   - `Status::NO_MEMORY` - Not enough memory to start the component.
+     *   - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+     *   - `Status::CORRUPTED` - Some unknown error occurred.
+     */
+    IInputSurfaceConnection connectToInputSurface(in IInputSurface inputSurface);
+
+    /**
+     * Returns an @ref IInputSink instance that has the component as the
+     * underlying implementation.
+     *
+     * @return sink `IInputSink` instance.
+     */
+    IInputSink asInputSink();
 }
diff --git a/media/c2/aidl/android/hardware/media/c2/IComponentStore.aidl b/media/c2/aidl/android/hardware/media/c2/IComponentStore.aidl
index 1435a7e..019405d 100644
--- a/media/c2/aidl/android/hardware/media/c2/IComponentStore.aidl
+++ b/media/c2/aidl/android/hardware/media/c2/IComponentStore.aidl
@@ -21,6 +21,7 @@
 import android.hardware.media.c2.IComponentInterface;
 import android.hardware.media.c2.IComponentListener;
 import android.hardware.media.c2.IConfigurable;
+import android.hardware.media.c2.IInputSurface;
 import android.hardware.media.c2.StructDescriptor;
 
 /**
@@ -182,4 +183,16 @@
      *   - `Status::CORRUPTED` - Some unknown error occurred.
      */
     ComponentTraits[] listComponents();
+
+    /**
+     * Creates a persistent input surface that can be used as an input surface
+     * for any IComponent instance
+     *
+     * @return IInputSurface A persistent input surface.
+     * @throws ServiceSpecificException with one of following values:
+     *   - `Status::NO_MEMORY` - Not enough memory to complete this method.
+     *   - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+     *   - `Status::CORRUPTED` - Some unknown error occurred.
+     */
+    IInputSurface createInputSurface();
 }
diff --git a/media/c2/aidl/android/hardware/media/c2/IInputSink.aidl b/media/c2/aidl/android/hardware/media/c2/IInputSink.aidl
new file mode 100644
index 0000000..eb8ad3d
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/IInputSink.aidl
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.WorkBundle;
+
+/**
+ * An `IInputSink` is a receiver of work items.
+ *
+ * An @ref IComponent instance can present itself as an `IInputSink` via a thin
+ * wrapper.
+ *
+ * @sa IInputSurface, IComponent.
+ */
+@VintfStability
+interface IInputSink {
+    /**
+     * Feeds work to the sink.
+     *
+     * @param workBundle `WorkBundle` object containing a list of `Work` objects
+     *     to queue to the component.
+     * @throws ServiceSpecificException with one of the following values:
+     *   - `Status::BAD_INDEX` - Some component id in some `Worklet` is not valid.
+     *   - `Status::CANNOT_DO` - Tunneling has not been set up for this sink, but some
+     *                   `Work` object contains tunneling information.
+     *   - `Status::NO_MEMORY` - Not enough memory to queue @p workBundle.
+     *   - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+     *   - `Status::CORRUPTED` - Some unknown error occurred.
+     */
+    void queue(in WorkBundle workBundle);
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/IInputSurface.aidl b/media/c2/aidl/android/hardware/media/c2/IInputSurface.aidl
new file mode 100644
index 0000000..77cb1fd
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/IInputSurface.aidl
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.IConfigurable;
+import android.hardware.media.c2.IInputSink;
+import android.hardware.media.c2.IInputSurfaceConnection;
+import android.view.Surface;
+
+/**
+ * Input surface for a Codec2 component.
+ *
+ * An <em>input surface</em> is an instance of `IInputSurface`, which may be
+ * created by calling IComponentStore::createInputSurface(). Once created, the
+ * client may
+ *   1. write data to it via the `NativeWindow` interface; and
+ *   2. use it as input to a Codec2 encoder.
+ *
+ * @sa IInputSurfaceConnection, IComponentStore::createInputSurface(),
+ *     IComponent::connectToInputSurface().
+ */
+@VintfStability
+interface IInputSurface {
+    /**
+     * Returns the producer interface into the internal buffer queue.
+     *
+     * @return producer `Surface` instance(actually ANativeWindow). This must not
+     * be null.
+     */
+    Surface getSurface();
+
+    /**
+     * Returns the @ref IConfigurable instance associated to this input surface.
+     *
+     * @return configurable `IConfigurable` instance. This must not be null.
+     */
+    IConfigurable getConfigurable();
+
+    /**
+     * Connects the input surface to an input sink.
+     *
+     * This function is generally called from inside the implementation of
+     * IComponent::connectToInputSurface(), where @p sink is a thin wrapper of
+     * the component that consumes buffers from this surface.
+     *
+     * @param sink Input sink. See `IInputSink` for more information.
+     * @return connection `IInputSurfaceConnection` object. This must not be
+     *     null if @p status is `OK`.
+     * @throws ServiceSpecificException with one of following values:
+     *   - `Status::BAD_VALUE` - @p sink is invalid.
+     *   - `Status::CORRUPTED` - Some unknown error occurred.
+     */
+    IInputSurfaceConnection connect(in IInputSink sink);
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/IInputSurfaceConnection.aidl b/media/c2/aidl/android/hardware/media/c2/IInputSurfaceConnection.aidl
new file mode 100644
index 0000000..36524eb
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/IInputSurfaceConnection.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+
+package android.hardware.media.c2;
+
+/**
+ * Connection between an IInputSink and an IInpuSurface.
+ */
+@VintfStability
+interface IInputSurfaceConnection {
+    /**
+     * Destroys the connection between an input surface and a component.
+     *
+     * @throws ServiceSpecificException with one of following values:
+     *   - `Status::BAD_STATE` - The component is not in running state.
+     *   - `Status::NOT_FOUND` - The surface is not connected to a component.
+     *   - `Status::CORRUPTED` - Some unknown error occurred.
+     */
+    void disconnect();
+
+    /**
+     * Signal the end of stream.
+
+     * @throws ServiceSpecificException with one of following values:
+     *   - `Status::BAD_STATE` - The component is not in running state.
+     */
+    void signalEndOfStream();
+}
diff --git a/nfc/1.0/vts/functional/VtsHalNfcV1_0TargetTest.cpp b/nfc/1.0/vts/functional/VtsHalNfcV1_0TargetTest.cpp
index 4d997e6..8210ff0 100644
--- a/nfc/1.0/vts/functional/VtsHalNfcV1_0TargetTest.cpp
+++ b/nfc/1.0/vts/functional/VtsHalNfcV1_0TargetTest.cpp
@@ -296,12 +296,6 @@
     res = nfc_cb_->WaitForCallback(kCallbackNameSendData);
     EXPECT_TRUE(res.no_timeout);
     EXPECT_EQ((int)NfcStatus::OK, res.args->last_data_[3]);
-    if (nci_version == NCI_VERSION_2 && res.args->last_data_.size() > 13 &&
-        res.args->last_data_[13] == 0x00) {
-        // Wait for CORE_CONN_CREDITS_NTF
-        res = nfc_cb_->WaitForCallback(kCallbackNameSendData);
-        EXPECT_TRUE(res.no_timeout);
-    }
     // Send an Error Data Packet
     cmd = INVALID_COMMAND;
     data = cmd;
@@ -360,13 +354,6 @@
     res = nfc_cb_->WaitForCallback(kCallbackNameSendData);
     EXPECT_TRUE(res.no_timeout);
     EXPECT_EQ((int)NfcStatus::OK, res.args->last_data_[3]);
-    if (nci_version == NCI_VERSION_2 && res.args->last_data_.size() > 13 &&
-        res.args->last_data_[13] == 0x00) {
-        // Wait for CORE_CONN_CREDITS_NTF
-        res = nfc_cb_->WaitForCallback(kCallbackNameSendData);
-        EXPECT_TRUE(res.no_timeout);
-    }
-
     cmd = CORE_CONN_CREATE_CMD;
     data = cmd;
     EXPECT_EQ(data.size(), nfc_->write(data));
diff --git a/power/aidl/vts/VtsHalPowerTargetTest.cpp b/power/aidl/vts/VtsHalPowerTargetTest.cpp
index c2216f8..907cf00 100644
--- a/power/aidl/vts/VtsHalPowerTargetTest.cpp
+++ b/power/aidl/vts/VtsHalPowerTargetTest.cpp
@@ -73,8 +73,6 @@
 
 const std::vector<int32_t> kEmptyTids = {};
 
-const std::vector<WorkDuration> kNoDurations = {};
-
 const std::vector<WorkDuration> kDurationsWithZero = {
         DurationWrapper(1000L, 1L),
         DurationWrapper(0L, 2L),
diff --git a/radio/aidl/vts/radio_network_test.cpp b/radio/aidl/vts/radio_network_test.cpp
index 6643c1e..a48abb8 100644
--- a/radio/aidl/vts/radio_network_test.cpp
+++ b/radio/aidl/vts/radio_network_test.cpp
@@ -1167,19 +1167,12 @@
     EXPECT_EQ(RadioResponseType::SOLICITED, radioRsp_network->rspInfo.type);
     EXPECT_EQ(serial, radioRsp_network->rspInfo.serial);
 
-    if (cardStatus.cardState == CardStatus::STATE_ABSENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(
-                radioRsp_network->rspInfo.error,
-                {RadioError::NONE, RadioError::ILLEGAL_SIM_OR_ME, RadioError::INVALID_ARGUMENTS,
-                 RadioError::INVALID_STATE, RadioError::RADIO_NOT_AVAILABLE, RadioError::NO_MEMORY,
-                 RadioError::INTERNAL_ERR, RadioError::SYSTEM_ERR, RadioError::CANCELLED}));
-    } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
-        ASSERT_TRUE(CheckAnyOfErrors(
-                radioRsp_network->rspInfo.error,
-                {RadioError::NONE, RadioError::RADIO_NOT_AVAILABLE, RadioError::INVALID_ARGUMENTS,
-                 RadioError::INVALID_STATE, RadioError::NO_MEMORY, RadioError::INTERNAL_ERR,
-                 RadioError::SYSTEM_ERR, RadioError::CANCELLED}));
-    }
+    ASSERT_TRUE(CheckAnyOfErrors(
+            radioRsp_network->rspInfo.error,
+            {RadioError::NONE, RadioError::ILLEGAL_SIM_OR_ME, RadioError::RADIO_NOT_AVAILABLE,
+             RadioError::INVALID_ARGUMENTS, RadioError::INVALID_STATE, RadioError::NO_MEMORY,
+             RadioError::INTERNAL_ERR, RadioError::SYSTEM_ERR, RadioError::CANCELLED,
+             RadioError::MODEM_ERR, RadioError::OPERATION_NOT_ALLOWED, RadioError::NO_RESOURCES}));
 }
 
 /*
diff --git a/secure_element/aidl/vts/AndroidTest.xml b/secure_element/aidl/vts/AndroidTest.xml
new file mode 100644
index 0000000..94dfa82
--- /dev/null
+++ b/secure_element/aidl/vts/AndroidTest.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2024 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.
+-->
+<configuration description="Runs VtsHalSecureElementTargetTest.">
+    <option name="test-suite-tag" value="apct" />
+    <option name="test-suite-tag" value="apct-native" />
+    <option name="config-descriptor:metadata" key="token" value="SECURE_ELEMENT_SIM_CARD" />
+
+    <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer">
+    </target_preparer>
+
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push" value="VtsHalSecureElementTargetTest->/data/local/tmp/VtsHalSecureElementTargetTest" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="VtsHalSecureElementTargetTest" />
+    </test>
+</configuration>
diff --git a/security/authgraph/aidl/android/hardware/security/authgraph/ExplicitKeyDiceCertChain.cddl b/security/authgraph/aidl/android/hardware/security/authgraph/ExplicitKeyDiceCertChain.cddl
index 3de5617..2d6c696 100644
--- a/security/authgraph/aidl/android/hardware/security/authgraph/ExplicitKeyDiceCertChain.cddl
+++ b/security/authgraph/aidl/android/hardware/security/authgraph/ExplicitKeyDiceCertChain.cddl
@@ -19,11 +19,10 @@
     * DiceChainEntry
 ]
 
-DiceCertChainInitialPayload = {
-    -4670552 : bstr .cbor PubKeyEd25519 /
-               bstr .cbor PubKeyECDSA256 /
-               bstr .cbor PubKeyECDSA384 ; subjectPublicKey
-}
+; Encoded in accordance with Core Deterministic Encoding Requirements [RFC 8949 s4.2.1]
+DiceCertChainInitialPayload = bstr .cbor PubKeyEd25519
+                            / bstr .cbor PubKeyECDSA256
+                            / bstr .cbor PubKeyECDSA384 ; subjectPublicKey
 
 ; INCLUDE generateCertificateRequestV2.cddl for: PubKeyEd25519, PubKeyECDSA256, PubKeyECDSA384,
 ;                                                DiceChainEntry
diff --git a/security/secretkeeper/aidl/vts/Android.bp b/security/secretkeeper/aidl/vts/Android.bp
index 7de9d6a..720b8a2 100644
--- a/security/secretkeeper/aidl/vts/Android.bp
+++ b/security/secretkeeper/aidl/vts/Android.bp
@@ -21,12 +21,17 @@
 rust_test {
     name: "VtsSecretkeeperTargetTest",
     srcs: ["secretkeeper_test_client.rs"],
+    defaults: [
+        "rdroidtest.defaults",
+    ],
     test_suites: [
         "general-tests",
         "vts",
     ],
     test_config: "AndroidTest.xml",
     rustlibs: [
+        "libdiced_open_dice",
+        "libdice_policy",
         "libsecretkeeper_client",
         "libsecretkeeper_comm_nostd",
         "libsecretkeeper_core_nostd",
@@ -36,9 +41,9 @@
         "libcoset",
         "libauthgraph_vts_test",
         "libbinder_rs",
+        "libciborium",
         "libcoset",
         "liblog_rust",
-        "liblogger",
     ],
     require_root: true,
 }
diff --git a/security/secretkeeper/aidl/vts/dice_sample.rs b/security/secretkeeper/aidl/vts/dice_sample.rs
new file mode 100644
index 0000000..db532b1
--- /dev/null
+++ b/security/secretkeeper/aidl/vts/dice_sample.rs
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+
+//! This module provides a set of sample DICE chains for testing purpose only. Note that this
+//! module duplicates a large chunk of code in libdiced_sample_inputs. We avoid modifying the
+//! latter for testing purposes because it is installed on device.
+
+use ciborium::{de, ser, value::Value};
+use core::ffi::CStr;
+use coset::{iana, Algorithm, AsCborValue, CoseKey, KeyOperation, KeyType, Label};
+use diced_open_dice::{
+    derive_cdi_private_key_seed, keypair_from_seed, retry_bcc_format_config_descriptor,
+    retry_bcc_main_flow, retry_dice_main_flow, Config, DiceArtifacts, DiceConfigValues, DiceError,
+    DiceMode, InputValues, OwnedDiceArtifacts, CDI_SIZE, HASH_SIZE, HIDDEN_SIZE,
+};
+use log::error;
+use secretkeeper_client::dice::OwnedDiceArtifactsWithExplicitKey;
+
+/// Sample UDS used to perform the root DICE flow by `make_sample_bcc_and_cdis`.
+const UDS: &[u8; CDI_SIZE] = &[
+    0x65, 0x4f, 0xab, 0xa9, 0xa5, 0xad, 0x0f, 0x5e, 0x15, 0xc3, 0x12, 0xf7, 0x77, 0x45, 0xfa, 0x55,
+    0x18, 0x6a, 0xa6, 0x34, 0xb6, 0x7c, 0x82, 0x7b, 0x89, 0x4c, 0xc5, 0x52, 0xd3, 0x27, 0x35, 0x8e,
+];
+
+const CODE_HASH_ABL: [u8; HASH_SIZE] = [
+    0x16, 0x48, 0xf2, 0x55, 0x53, 0x23, 0xdd, 0x15, 0x2e, 0x83, 0x38, 0xc3, 0x64, 0x38, 0x63, 0x26,
+    0x0f, 0xcf, 0x5b, 0xd1, 0x3a, 0xd3, 0x40, 0x3e, 0x23, 0xf8, 0x34, 0x4c, 0x6d, 0xa2, 0xbe, 0x25,
+    0x1c, 0xb0, 0x29, 0xe8, 0xc3, 0xfb, 0xb8, 0x80, 0xdc, 0xb1, 0xd2, 0xb3, 0x91, 0x4d, 0xd3, 0xfb,
+    0x01, 0x0f, 0xe4, 0xe9, 0x46, 0xa2, 0xc0, 0x26, 0x57, 0x5a, 0xba, 0x30, 0xf7, 0x15, 0x98, 0x14,
+];
+const AUTHORITY_HASH_ABL: [u8; HASH_SIZE] = [
+    0xf9, 0x00, 0x9d, 0xc2, 0x59, 0x09, 0xe0, 0xb6, 0x98, 0xbd, 0xe3, 0x97, 0x4a, 0xcb, 0x3c, 0xe7,
+    0x6b, 0x24, 0xc3, 0xe4, 0x98, 0xdd, 0xa9, 0x6a, 0x41, 0x59, 0x15, 0xb1, 0x23, 0xe6, 0xc8, 0xdf,
+    0xfb, 0x52, 0xb4, 0x52, 0xc1, 0xb9, 0x61, 0xdd, 0xbc, 0x5b, 0x37, 0x0e, 0x12, 0x12, 0xb2, 0xfd,
+    0xc1, 0x09, 0xb0, 0xcf, 0x33, 0x81, 0x4c, 0xc6, 0x29, 0x1b, 0x99, 0xea, 0xae, 0xfd, 0xaa, 0x0d,
+];
+const HIDDEN_ABL: [u8; HIDDEN_SIZE] = [
+    0xa2, 0x01, 0xd0, 0xc0, 0xaa, 0x75, 0x3c, 0x06, 0x43, 0x98, 0x6c, 0xc3, 0x5a, 0xb5, 0x5f, 0x1f,
+    0x0f, 0x92, 0x44, 0x3b, 0x0e, 0xd4, 0x29, 0x75, 0xe3, 0xdb, 0x36, 0xda, 0xc8, 0x07, 0x97, 0x4d,
+    0xff, 0xbc, 0x6a, 0xa4, 0x8a, 0xef, 0xc4, 0x7f, 0xf8, 0x61, 0x7d, 0x51, 0x4d, 0x2f, 0xdf, 0x7e,
+    0x8c, 0x3d, 0xa3, 0xfc, 0x63, 0xd4, 0xd4, 0x74, 0x8a, 0xc4, 0x14, 0x45, 0x83, 0x6b, 0x12, 0x7e,
+];
+const CODE_HASH_AVB: [u8; HASH_SIZE] = [
+    0xa4, 0x0c, 0xcb, 0xc1, 0xbf, 0xfa, 0xcc, 0xfd, 0xeb, 0xf4, 0xfc, 0x43, 0x83, 0x7f, 0x46, 0x8d,
+    0xd8, 0xd8, 0x14, 0xc1, 0x96, 0x14, 0x1f, 0x6e, 0xb3, 0xa0, 0xd9, 0x56, 0xb3, 0xbf, 0x2f, 0xfa,
+    0x88, 0x70, 0x11, 0x07, 0x39, 0xa4, 0xd2, 0xa9, 0x6b, 0x18, 0x28, 0xe8, 0x29, 0x20, 0x49, 0x0f,
+    0xbb, 0x8d, 0x08, 0x8c, 0xc6, 0x54, 0xe9, 0x71, 0xd2, 0x7e, 0xa4, 0xfe, 0x58, 0x7f, 0xd3, 0xc7,
+];
+const AUTHORITY_HASH_AVB: [u8; HASH_SIZE] = [
+    0xb2, 0x69, 0x05, 0x48, 0x56, 0xb5, 0xfa, 0x55, 0x6f, 0xac, 0x56, 0xd9, 0x02, 0x35, 0x2b, 0xaa,
+    0x4c, 0xba, 0x28, 0xdd, 0x82, 0x3a, 0x86, 0xf5, 0xd4, 0xc2, 0xf1, 0xf9, 0x35, 0x7d, 0xe4, 0x43,
+    0x13, 0xbf, 0xfe, 0xd3, 0x36, 0xd8, 0x1c, 0x12, 0x78, 0x5c, 0x9c, 0x3e, 0xf6, 0x66, 0xef, 0xab,
+    0x3d, 0x0f, 0x89, 0xa4, 0x6f, 0xc9, 0x72, 0xee, 0x73, 0x43, 0x02, 0x8a, 0xef, 0xbc, 0x05, 0x98,
+];
+const HIDDEN_AVB: [u8; HIDDEN_SIZE] = [
+    0x5b, 0x3f, 0xc9, 0x6b, 0xe3, 0x95, 0x59, 0x40, 0x5e, 0x64, 0xe5, 0x64, 0x3f, 0xfd, 0x21, 0x09,
+    0x9d, 0xf3, 0xcd, 0xc7, 0xa4, 0x2a, 0xe2, 0x97, 0xdd, 0xe2, 0x4f, 0xb0, 0x7d, 0x7e, 0xf5, 0x8e,
+    0xd6, 0x4d, 0x84, 0x25, 0x54, 0x41, 0x3f, 0x8f, 0x78, 0x64, 0x1a, 0x51, 0x27, 0x9d, 0x55, 0x8a,
+    0xe9, 0x90, 0x35, 0xab, 0x39, 0x80, 0x4b, 0x94, 0x40, 0x84, 0xa2, 0xfd, 0x73, 0xeb, 0x35, 0x7a,
+];
+const AUTHORITY_HASH_ANDROID: [u8; HASH_SIZE] = [
+    0x04, 0x25, 0x5d, 0x60, 0x5f, 0x5c, 0x45, 0x0d, 0xf2, 0x9a, 0x6e, 0x99, 0x30, 0x03, 0xb8, 0xd6,
+    0xe1, 0x99, 0x71, 0x1b, 0xf8, 0x44, 0xfa, 0xb5, 0x31, 0x79, 0x1c, 0x37, 0x68, 0x4e, 0x1d, 0xc0,
+    0x24, 0x74, 0x68, 0xf8, 0x80, 0x20, 0x3e, 0x44, 0xb1, 0x43, 0xd2, 0x9c, 0xfc, 0x12, 0x9e, 0x77,
+    0x0a, 0xde, 0x29, 0x24, 0xff, 0x2e, 0xfa, 0xc7, 0x10, 0xd5, 0x73, 0xd4, 0xc6, 0xdf, 0x62, 0x9f,
+];
+
+/// Encode the public key to CBOR Value. The input (raw 32 bytes) is wrapped into CoseKey.
+fn ed25519_public_key_to_cbor_value(public_key: &[u8]) -> Value {
+    let key = CoseKey {
+        kty: KeyType::Assigned(iana::KeyType::OKP),
+        alg: Some(Algorithm::Assigned(iana::Algorithm::EdDSA)),
+        key_ops: vec![KeyOperation::Assigned(iana::KeyOperation::Verify)].into_iter().collect(),
+        params: vec![
+            (
+                Label::Int(iana::Ec2KeyParameter::Crv as i64),
+                Value::from(iana::EllipticCurve::Ed25519 as u64),
+            ),
+            (Label::Int(iana::Ec2KeyParameter::X as i64), Value::Bytes(public_key.to_vec())),
+        ],
+        ..Default::default()
+    };
+    key.to_cbor_value().unwrap()
+}
+
+/// Makes a DICE chain (BCC) from the sample input.
+///
+/// The DICE chain is of the following format:
+/// public key derived from UDS -> ABL certificate -> AVB certificate -> Android certificate
+/// The `security_version` is included in the Android certificate.
+pub fn make_explicit_owned_dice(security_version: u64) -> OwnedDiceArtifactsWithExplicitKey {
+    let dice = make_sample_bcc_and_cdis(security_version);
+    OwnedDiceArtifactsWithExplicitKey::from_owned_artifacts(dice).unwrap()
+}
+
+fn make_sample_bcc_and_cdis(security_version: u64) -> OwnedDiceArtifacts {
+    let private_key_seed = derive_cdi_private_key_seed(UDS).unwrap();
+
+    // Gets the root public key in DICE chain (BCC).
+    let (public_key, _) = keypair_from_seed(private_key_seed.as_array()).unwrap();
+    let ed25519_public_key_value = ed25519_public_key_to_cbor_value(&public_key);
+
+    // Gets the ABL certificate to as the root certificate of DICE chain.
+    let config_values = DiceConfigValues {
+        component_name: Some(CStr::from_bytes_with_nul(b"ABL\0").unwrap()),
+        component_version: Some(1),
+        resettable: true,
+        ..Default::default()
+    };
+    let config_descriptor = retry_bcc_format_config_descriptor(&config_values).unwrap();
+    let input_values = InputValues::new(
+        CODE_HASH_ABL,
+        Config::Descriptor(config_descriptor.as_slice()),
+        AUTHORITY_HASH_ABL,
+        DiceMode::kDiceModeNormal,
+        HIDDEN_ABL,
+    );
+    let (cdi_values, cert) = retry_dice_main_flow(UDS, UDS, &input_values).unwrap();
+    let bcc_value =
+        Value::Array(vec![ed25519_public_key_value, de::from_reader(&cert[..]).unwrap()]);
+    let mut bcc: Vec<u8> = vec![];
+    ser::into_writer(&bcc_value, &mut bcc).unwrap();
+
+    // Appends AVB certificate to DICE chain.
+    let config_values = DiceConfigValues {
+        component_name: Some(CStr::from_bytes_with_nul(b"AVB\0").unwrap()),
+        component_version: Some(1),
+        resettable: true,
+        ..Default::default()
+    };
+    let config_descriptor = retry_bcc_format_config_descriptor(&config_values).unwrap();
+    let input_values = InputValues::new(
+        CODE_HASH_AVB,
+        Config::Descriptor(config_descriptor.as_slice()),
+        AUTHORITY_HASH_AVB,
+        DiceMode::kDiceModeNormal,
+        HIDDEN_AVB,
+    );
+    let dice_artifacts =
+        retry_bcc_main_flow(&cdi_values.cdi_attest, &cdi_values.cdi_seal, &bcc, &input_values)
+            .unwrap();
+
+    // Appends Android certificate to DICE chain.
+    let config_values = DiceConfigValues {
+        component_name: Some(CStr::from_bytes_with_nul(b"Android\0").unwrap()),
+        component_version: Some(12),
+        security_version: Some(security_version),
+        resettable: true,
+        ..Default::default()
+    };
+    let config_descriptor = retry_bcc_format_config_descriptor(&config_values).unwrap();
+    let input_values = InputValues::new(
+        [0u8; HASH_SIZE], // code_hash
+        Config::Descriptor(config_descriptor.as_slice()),
+        AUTHORITY_HASH_ANDROID,
+        DiceMode::kDiceModeNormal,
+        [0u8; HIDDEN_SIZE], // hidden
+    );
+    retry_bcc_main_flow(
+        dice_artifacts.cdi_attest(),
+        dice_artifacts.cdi_seal(),
+        dice_artifacts
+            .bcc()
+            .ok_or_else(|| {
+                error!("bcc is none");
+                DiceError::InvalidInput
+            })
+            .unwrap(),
+        &input_values,
+    )
+    .unwrap()
+}
diff --git a/security/secretkeeper/aidl/vts/secretkeeper_test_client.rs b/security/secretkeeper/aidl/vts/secretkeeper_test_client.rs
index c457d24..4c0f659 100644
--- a/security/secretkeeper/aidl/vts/secretkeeper_test_client.rs
+++ b/security/secretkeeper/aidl/vts/secretkeeper_test_client.rs
@@ -15,15 +15,19 @@
  */
 
 #![cfg(test)]
+mod dice_sample;
 
+use crate::dice_sample::make_explicit_owned_dice;
+
+use rdroidtest_macro::{ignore_if, rdroidtest};
 use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::ISecretkeeper;
 use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
 use authgraph_vts_test as ag_vts;
 use authgraph_boringssl as boring;
 use authgraph_core::key;
-use binder::StatusCode;
 use coset::{CborSerializable, CoseEncrypt0};
-use log::{info, warn};
+use dice_policy::{ConstraintSpec, ConstraintType, DicePolicy};
+use secretkeeper_client::dice::OwnedDiceArtifactsWithExplicitKey;
 use secretkeeper_client::SkSession;
 use secretkeeper_core::cipher;
 use secretkeeper_comm::data_types::error::SecretkeeperError;
@@ -36,18 +40,8 @@
 use secretkeeper_comm::data_types::packet::{ResponsePacket, ResponseType};
 
 const SECRETKEEPER_SERVICE: &str = "android.hardware.security.secretkeeper.ISecretkeeper";
-const SECRETKEEPER_INSTANCES: [&'static str; 2] = ["default", "nonsecure"];
 const CURRENT_VERSION: u64 = 1;
 
-// TODO(b/291238565): This will change once libdice_policy switches to Explicit-key DiceCertChain
-// This is generated by patching libdice_policy such that it dumps an example dice chain &
-// a policy, such that the former matches the latter.
-const HYPOTHETICAL_DICE_POLICY: [u8; 43] = [
-    0x83, 0x01, 0x81, 0x83, 0x01, 0x80, 0xA1, 0x01, 0x00, 0x82, 0x83, 0x01, 0x81, 0x01, 0x73, 0x74,
-    0x65, 0x73, 0x74, 0x69, 0x6E, 0x67, 0x5F, 0x64, 0x69, 0x63, 0x65, 0x5F, 0x70, 0x6F, 0x6C, 0x69,
-    0x63, 0x79, 0x83, 0x02, 0x82, 0x03, 0x18, 0x64, 0x19, 0xE9, 0x75,
-];
-
 // Random bytes (of ID_SIZE/SECRET_SIZE) generated for tests.
 const ID_EXAMPLE: Id = Id([
     0xF1, 0xB2, 0xED, 0x3B, 0xD1, 0xBD, 0xF0, 0x7D, 0xE1, 0xF0, 0x01, 0xFC, 0x61, 0x71, 0xD3, 0x42,
@@ -72,59 +66,25 @@
     0x06, 0xAC, 0x36, 0x8B, 0x3C, 0x95, 0x50, 0x16, 0x67, 0x71, 0x65, 0x26, 0xEB, 0xD0, 0xC3, 0x98,
 ]);
 
-fn get_connection() -> Option<(binder::Strong<dyn ISecretkeeper>, String)> {
-    // Initialize logging (which is OK to call multiple times).
-    logger::init(logger::Config::default().with_min_level(log::Level::Debug));
-
+fn get_instances() -> Vec<(String, String)> {
     // Determine which instances are available.
-    let available = binder::get_declared_instances(SECRETKEEPER_SERVICE).unwrap_or_default();
-
-    // TODO: replace this with a parameterized set of tests that run for each available instance of
-    // ISecretkeeper (rather than having a fixed set of instance names to look for).
-    for instance in &SECRETKEEPER_INSTANCES {
-        if available.iter().find(|s| s == instance).is_none() {
-            // Skip undeclared instances.
-            continue;
-        }
-        let name = format!("{SECRETKEEPER_SERVICE}/{instance}");
-        match binder::get_interface(&name) {
-            Ok(sk) => {
-                info!("Running test against /{instance}");
-                return Some((sk, name));
-            }
-            Err(StatusCode::NAME_NOT_FOUND) => {
-                info!("No /{instance} instance of ISecretkeeper present");
-            }
-            Err(e) => {
-                panic!(
-                    "unexpected error while fetching connection to Secretkeeper {:?}",
-                    e
-                );
-            }
-        }
-    }
-    info!("no Secretkeeper instances in {SECRETKEEPER_INSTANCES:?} are declared and present");
-    None
+    binder::get_declared_instances(SECRETKEEPER_SERVICE)
+        .unwrap_or_default()
+        .into_iter()
+        .map(|v| (v.clone(), v))
+        .collect()
 }
 
-/// Macro to perform test setup. Invokes `return` if no Secretkeeper instance available.
-macro_rules! setup_client {
-    {} => {
-        match SkClient::new() {
-            Some(sk) => sk,
-            None => {
-                warn!("Secretkeeper HAL is unavailable, skipping test");
-                return;
-            }
-        }
-    }
+fn get_connection(instance: &str) -> binder::Strong<dyn ISecretkeeper> {
+    let name = format!("{SECRETKEEPER_SERVICE}/{instance}");
+    binder::get_interface(&name).unwrap()
 }
 
 /// Secretkeeper client information.
 struct SkClient {
     sk: binder::Strong<dyn ISecretkeeper>,
-    name: String,
     session: SkSession,
+    dice_artifacts: OwnedDiceArtifactsWithExplicitKey,
 }
 
 impl Drop for SkClient {
@@ -135,19 +95,26 @@
 }
 
 impl SkClient {
-    fn new() -> Option<Self> {
-        let (sk, name) = get_connection()?;
-        Some(Self {
+    /// Create an `SkClient` using the default `OwnedDiceArtifactsWithExplicitKey` for identity.
+    fn new(instance: &str) -> Self {
+        let default_dice = make_explicit_owned_dice(/*Security version in a node */ 5);
+        Self::with_identity(instance, default_dice)
+    }
+
+    /// Create an `SkClient` using the given `OwnedDiceArtifactsWithExplicitKey` for identity.
+    fn with_identity(instance: &str, dice_artifacts: OwnedDiceArtifactsWithExplicitKey) -> Self {
+        let sk = get_connection(instance);
+        Self {
             sk: sk.clone(),
-            name,
-            session: SkSession::new(sk).unwrap(),
-        })
+            session: SkSession::new(sk, &dice_artifacts).unwrap(),
+            dice_artifacts,
+        }
     }
 
     /// This method is wrapper that use `SkSession::secret_management_request` which handles
     /// encryption and decryption.
-    fn secret_management_request(&mut self, req_data: &[u8]) -> Vec<u8> {
-        self.session.secret_management_request(req_data).unwrap()
+    fn secret_management_request(&mut self, req_data: &[u8]) -> Result<Vec<u8>, Error> {
+        Ok(self.session.secret_management_request(req_data)?)
     }
 
     /// Unlike the method [`secret_management_request`], this method directly uses
@@ -158,7 +125,7 @@
         req_data: &[u8],
         req_aad: &[u8],
         expected_res_aad: &[u8],
-    ) -> Vec<u8> {
+    ) -> Result<Vec<u8>, Error> {
         let aes_gcm = boring::BoringAes;
         let rng = boring::BoringRng;
         let request_bytes = cipher::encrypt_message(
@@ -169,72 +136,60 @@
             &req_data,
             req_aad,
         )
-        .unwrap();
+        .map_err(|e| secretkeeper_client::Error::CipherError(e))?;
 
         // Binder call!
-        let response_bytes = self
-            .sk
-            .processSecretManagementRequest(&request_bytes)
-            .unwrap();
+        let response_bytes = self.sk.processSecretManagementRequest(&request_bytes)?;
 
-        let response_encrypt0 = CoseEncrypt0::from_slice(&response_bytes).unwrap();
-        cipher::decrypt_message(
+        let response_encrypt0 = CoseEncrypt0::from_slice(&response_bytes)?;
+        Ok(cipher::decrypt_message(
             &aes_gcm,
             self.session.decryption_key(),
             &response_encrypt0,
             expected_res_aad,
         )
-        .unwrap()
+        .map_err(|e| secretkeeper_client::Error::CipherError(e))?)
     }
 
-    /// Helper method to store a secret.
-    fn store(&mut self, id: &Id, secret: &Secret) {
-        let store_request = StoreSecretRequest {
-            id: id.clone(),
-            secret: secret.clone(),
-            sealing_policy: HYPOTHETICAL_DICE_POLICY.to_vec(),
-        };
-        let store_request = store_request.serialize_to_packet().to_vec().unwrap();
-
-        let store_response = self.secret_management_request(&store_request);
-        let store_response = ResponsePacket::from_slice(&store_response).unwrap();
-
-        assert_eq!(
-            store_response.response_type().unwrap(),
-            ResponseType::Success
+    /// Helper method to store a secret. This uses the default compatible sealing_policy on
+    /// dice_chain.
+    fn store(&mut self, id: &Id, secret: &Secret) -> Result<(), Error> {
+        let sealing_policy = sealing_policy(
+            self.dice_artifacts.explicit_key_dice_chain().ok_or(Error::UnexpectedError)?,
         );
+        let store_request =
+            StoreSecretRequest { id: id.clone(), secret: secret.clone(), sealing_policy };
+        let store_request = store_request.serialize_to_packet().to_vec()?;
+
+        let store_response = self.secret_management_request(&store_request)?;
+        let store_response = ResponsePacket::from_slice(&store_response)?;
+
+        assert_eq!(store_response.response_type()?, ResponseType::Success);
         // Really just checking that the response is indeed StoreSecretResponse
-        let _ = StoreSecretResponse::deserialize_from_packet(store_response).unwrap();
+        let _ = StoreSecretResponse::deserialize_from_packet(store_response)?;
+        Ok(())
     }
 
     /// Helper method to get a secret.
-    fn get(&mut self, id: &Id) -> Option<Secret> {
-        let get_request = GetSecretRequest {
-            id: id.clone(),
-            updated_sealing_policy: None,
-        };
-        let get_request = get_request.serialize_to_packet().to_vec().unwrap();
+    fn get(&mut self, id: &Id) -> Result<Secret, Error> {
+        let get_request = GetSecretRequest { id: id.clone(), updated_sealing_policy: None };
+        let get_request = get_request.serialize_to_packet().to_vec()?;
 
-        let get_response = self.secret_management_request(&get_request);
-        let get_response = ResponsePacket::from_slice(&get_response).unwrap();
+        let get_response = self.secret_management_request(&get_request)?;
+        let get_response = ResponsePacket::from_slice(&get_response)?;
 
-        if get_response.response_type().unwrap() == ResponseType::Success {
-            let get_response = *GetSecretResponse::deserialize_from_packet(get_response).unwrap();
-            Some(Secret(get_response.secret.0))
+        if get_response.response_type()? == ResponseType::Success {
+            let get_response = *GetSecretResponse::deserialize_from_packet(get_response)?;
+            Ok(Secret(get_response.secret.0))
         } else {
-            // Only expect a not-found failure.
-            let err = *SecretkeeperError::deserialize_from_packet(get_response).unwrap();
-            assert_eq!(err, SecretkeeperError::EntryNotFound);
-            None
+            let err = *SecretkeeperError::deserialize_from_packet(get_response)?;
+            Err(Error::SecretkeeperError(err))
         }
     }
 
     /// Helper method to delete secrets.
     fn delete(&self, ids: &[&Id]) {
-        let ids: Vec<SecretId> = ids
-            .iter()
-            .map(|id| SecretId { id: id.0 })
-            .collect();
+        let ids: Vec<SecretId> = ids.iter().map(|id| SecretId { id: id.0 }).collect();
         self.sk.deleteIds(&ids).unwrap();
     }
 
@@ -244,6 +199,78 @@
     }
 }
 
+#[derive(Debug)]
+enum Error {
+    // Errors from Secretkeeper API errors. These are thrown by core SecretManagement and
+    // not visible without decryption.
+    SecretkeeperError(SecretkeeperError),
+    InfraError(secretkeeper_client::Error),
+    UnexpectedError,
+}
+
+impl From<secretkeeper_client::Error> for Error {
+    fn from(e: secretkeeper_client::Error) -> Self {
+        Self::InfraError(e)
+    }
+}
+
+impl From<SecretkeeperError> for Error {
+    fn from(e: SecretkeeperError) -> Self {
+        Self::SecretkeeperError(e)
+    }
+}
+
+impl From<coset::CoseError> for Error {
+    fn from(e: coset::CoseError) -> Self {
+        Self::InfraError(secretkeeper_client::Error::from(e))
+    }
+}
+
+impl From<binder::Status> for Error {
+    fn from(s: binder::Status) -> Self {
+        Self::InfraError(secretkeeper_client::Error::from(s))
+    }
+}
+
+impl From<secretkeeper_comm::data_types::error::Error> for Error {
+    fn from(e: secretkeeper_comm::data_types::error::Error) -> Self {
+        Self::InfraError(secretkeeper_client::Error::from(e))
+    }
+}
+
+// Assert that the error is EntryNotFound
+fn assert_entry_not_found(res: Result<Secret, Error>) {
+    assert!(matches!(res.unwrap_err(), Error::SecretkeeperError(SecretkeeperError::EntryNotFound)))
+}
+
+/// Construct a sealing policy on the dice chain. This method uses the following set of
+/// constraints which are compatible with sample DICE chains used in VTS.
+/// 1. ExactMatch on AUTHORITY_HASH (non-optional).
+/// 2. ExactMatch on KEY_MODE (non-optional).
+/// 3. GreaterOrEqual on SECURITY_VERSION (optional).
+fn sealing_policy(dice: &[u8]) -> Vec<u8> {
+    let authority_hash: i64 = -4670549;
+    let key_mode: i64 = -4670551;
+    let config_desc: i64 = -4670548;
+    let security_version: i64 = -70005;
+
+    let constraint_spec = [
+        ConstraintSpec::new(
+            ConstraintType::ExactMatch,
+            vec![authority_hash],
+            /* Optional */ false,
+        ),
+        ConstraintSpec::new(ConstraintType::ExactMatch, vec![key_mode], false),
+        ConstraintSpec::new(
+            ConstraintType::GreaterOrEqual,
+            vec![config_desc, security_version],
+            true,
+        ),
+    ];
+
+    DicePolicy::from_dice_chain(dice, &constraint_spec).unwrap().to_vec().unwrap()
+}
+
 /// Perform AuthGraph key exchange, returning the session keys and session ID.
 fn authgraph_key_exchange(sk: binder::Strong<dyn ISecretkeeper>) -> ([key::AesKey; 2], Vec<u8>) {
     let sink = sk.getAuthGraphKe().expect("failed to get AuthGraph");
@@ -251,47 +278,29 @@
     ag_vts::sink::test_mainline(&mut source, sink)
 }
 
-/// Test that the AuthGraph instance returned by SecretKeeper correctly performs
-/// mainline key exchange against a local source implementation.
-#[test]
-fn authgraph_mainline() {
-    let (sk, _) = match get_connection() {
-        Some(sk) => sk,
-        None => {
-            warn!("Secretkeeper HAL is unavailable, skipping test");
-            return;
-        }
-    };
+// Test that the AuthGraph instance returned by SecretKeeper correctly performs
+// mainline key exchange against a local source implementation.
+#[rdroidtest(get_instances())]
+fn authgraph_mainline(instance: String) {
+    let sk = get_connection(&instance);
     let (_aes_keys, _session_id) = authgraph_key_exchange(sk);
 }
 
-/// Test that the AuthGraph instance returned by SecretKeeper correctly rejects
-/// a corrupted session ID signature.
-#[test]
-fn authgraph_corrupt_sig() {
-    let (sk, _) = match get_connection() {
-        Some(sk) => sk,
-        None => {
-            warn!("Secretkeeper HAL is unavailable, skipping test");
-            return;
-        }
-    };
+// Test that the AuthGraph instance returned by SecretKeeper correctly rejects
+// a corrupted session ID signature.
+#[rdroidtest(get_instances())]
+fn authgraph_corrupt_sig(instance: String) {
+    let sk = get_connection(&instance);
     let sink = sk.getAuthGraphKe().expect("failed to get AuthGraph");
     let mut source = ag_vts::test_ag_participant().expect("failed to create a local source");
     ag_vts::sink::test_corrupt_sig(&mut source, sink);
 }
 
-/// Test that the AuthGraph instance returned by SecretKeeper correctly detects
-/// when corrupted keys are returned to it.
-#[test]
-fn authgraph_corrupt_keys() {
-    let (sk, _) = match get_connection() {
-        Some(sk) => sk,
-        None => {
-            warn!("Secretkeeper HAL is unavailable, skipping test");
-            return;
-        }
-    };
+// Test that the AuthGraph instance returned by SecretKeeper correctly detects
+// when corrupted keys are returned to it.
+#[rdroidtest(get_instances())]
+fn authgraph_corrupt_keys(instance: String) {
+    let sk = get_connection(&instance);
     let sink = sk.getAuthGraphKe().expect("failed to get AuthGraph");
     let mut source = ag_vts::test_ag_participant().expect("failed to create a local source");
     ag_vts::sink::test_corrupt_keys(&mut source, sink);
@@ -300,29 +309,26 @@
 // TODO(b/2797757): Add tests that match different HAL defined objects (like request/response)
 // with expected bytes.
 
-#[test]
-fn secret_management_get_version() {
-    let mut sk_client = setup_client!();
+#[rdroidtest(get_instances())]
+fn secret_management_get_version(instance: String) {
+    let mut sk_client = SkClient::new(&instance);
 
     let request = GetVersionRequest {};
     let request_packet = request.serialize_to_packet();
     let request_bytes = request_packet.to_vec().unwrap();
 
-    let response_bytes = sk_client.secret_management_request(&request_bytes);
+    let response_bytes = sk_client.secret_management_request(&request_bytes).unwrap();
 
     let response_packet = ResponsePacket::from_slice(&response_bytes).unwrap();
-    assert_eq!(
-        response_packet.response_type().unwrap(),
-        ResponseType::Success
-    );
+    assert_eq!(response_packet.response_type().unwrap(), ResponseType::Success);
     let get_version_response =
         *GetVersionResponse::deserialize_from_packet(response_packet).unwrap();
     assert_eq!(get_version_response.version, CURRENT_VERSION);
 }
 
-#[test]
-fn secret_management_malformed_request() {
-    let mut sk_client = setup_client!();
+#[rdroidtest(get_instances())]
+fn secret_management_malformed_request(instance: String) {
+    let mut sk_client = SkClient::new(&instance);
 
     let request = GetVersionRequest {};
     let request_packet = request.serialize_to_packet();
@@ -331,130 +337,122 @@
     // Deform the request
     request_bytes[0] = !request_bytes[0];
 
-    let response_bytes = sk_client.secret_management_request(&request_bytes);
+    let response_bytes = sk_client.secret_management_request(&request_bytes).unwrap();
 
     let response_packet = ResponsePacket::from_slice(&response_bytes).unwrap();
-    assert_eq!(
-        response_packet.response_type().unwrap(),
-        ResponseType::Error
-    );
+    assert_eq!(response_packet.response_type().unwrap(), ResponseType::Error);
     let err = *SecretkeeperError::deserialize_from_packet(response_packet).unwrap();
     assert_eq!(err, SecretkeeperError::RequestMalformed);
 }
 
-#[test]
-fn secret_management_store_get_secret_found() {
-    let mut sk_client = setup_client!();
+#[rdroidtest(get_instances())]
+fn secret_management_store_get_secret_found(instance: String) {
+    let mut sk_client = SkClient::new(&instance);
 
-    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE);
+    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE).unwrap();
 
     // Get the secret that was just stored
-    assert_eq!(sk_client.get(&ID_EXAMPLE), Some(SECRET_EXAMPLE));
+    assert_eq!(sk_client.get(&ID_EXAMPLE).unwrap(), SECRET_EXAMPLE);
 }
 
-#[test]
-fn secret_management_store_get_secret_not_found() {
-    let mut sk_client = setup_client!();
+#[rdroidtest(get_instances())]
+fn secret_management_store_get_secret_not_found(instance: String) {
+    let mut sk_client = SkClient::new(&instance);
 
     // Store a secret (corresponding to an id).
-    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE);
+    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE).unwrap();
 
     // Get the secret that was never stored
-    assert_eq!(sk_client.get(&ID_NOT_STORED), None);
+    assert_entry_not_found(sk_client.get(&ID_NOT_STORED));
 }
 
-#[test]
-fn secretkeeper_store_delete_ids() {
-    let mut sk_client = setup_client!();
+#[rdroidtest(get_instances())]
+fn secretkeeper_store_delete_ids(instance: String) {
+    let mut sk_client = SkClient::new(&instance);
 
-    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE);
-    sk_client.store(&ID_EXAMPLE_2, &SECRET_EXAMPLE);
+    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE).unwrap();
+    sk_client.store(&ID_EXAMPLE_2, &SECRET_EXAMPLE).unwrap();
     sk_client.delete(&[&ID_EXAMPLE]);
-
-    assert_eq!(sk_client.get(&ID_EXAMPLE), None);
-    assert_eq!(sk_client.get(&ID_EXAMPLE_2), Some(SECRET_EXAMPLE));
+    assert_entry_not_found(sk_client.get(&ID_EXAMPLE));
+    assert_eq!(sk_client.get(&ID_EXAMPLE_2).unwrap(), SECRET_EXAMPLE);
 
     sk_client.delete(&[&ID_EXAMPLE_2]);
 
-    assert_eq!(sk_client.get(&ID_EXAMPLE), None);
-    assert_eq!(sk_client.get(&ID_EXAMPLE_2), None);
+    assert_entry_not_found(sk_client.get(&ID_EXAMPLE));
+    assert_entry_not_found(sk_client.get(&ID_EXAMPLE_2));
 }
 
-#[test]
-fn secretkeeper_store_delete_multiple_ids() {
-    let mut sk_client = setup_client!();
+#[rdroidtest(get_instances())]
+fn secretkeeper_store_delete_multiple_ids(instance: String) {
+    let mut sk_client = SkClient::new(&instance);
 
-    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE);
-    sk_client.store(&ID_EXAMPLE_2, &SECRET_EXAMPLE);
+    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE).unwrap();
+    sk_client.store(&ID_EXAMPLE_2, &SECRET_EXAMPLE).unwrap();
     sk_client.delete(&[&ID_EXAMPLE, &ID_EXAMPLE_2]);
 
-    assert_eq!(sk_client.get(&ID_EXAMPLE), None);
-    assert_eq!(sk_client.get(&ID_EXAMPLE_2), None);
+    assert_entry_not_found(sk_client.get(&ID_EXAMPLE));
+    assert_entry_not_found(sk_client.get(&ID_EXAMPLE_2));
 }
+#[rdroidtest(get_instances())]
+fn secretkeeper_store_delete_duplicate_ids(instance: String) {
+    let mut sk_client = SkClient::new(&instance);
 
-#[test]
-fn secretkeeper_store_delete_duplicate_ids() {
-    let mut sk_client = setup_client!();
-
-    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE);
-    sk_client.store(&ID_EXAMPLE_2, &SECRET_EXAMPLE);
+    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE).unwrap();
+    sk_client.store(&ID_EXAMPLE_2, &SECRET_EXAMPLE).unwrap();
     // Delete the same secret twice.
     sk_client.delete(&[&ID_EXAMPLE, &ID_EXAMPLE]);
 
-    assert_eq!(sk_client.get(&ID_EXAMPLE), None);
-    assert_eq!(sk_client.get(&ID_EXAMPLE_2), Some(SECRET_EXAMPLE));
+    assert_entry_not_found(sk_client.get(&ID_EXAMPLE));
+    assert_eq!(sk_client.get(&ID_EXAMPLE_2).unwrap(), SECRET_EXAMPLE);
 }
 
-#[test]
-fn secretkeeper_store_delete_nonexistent() {
-    let mut sk_client = setup_client!();
+#[rdroidtest(get_instances())]
+fn secretkeeper_store_delete_nonexistent(instance: String) {
+    let mut sk_client = SkClient::new(&instance);
 
-    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE);
-    sk_client.store(&ID_EXAMPLE_2, &SECRET_EXAMPLE);
+    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE).unwrap();
+    sk_client.store(&ID_EXAMPLE_2, &SECRET_EXAMPLE).unwrap();
     sk_client.delete(&[&ID_NOT_STORED]);
 
-    assert_eq!(sk_client.get(&ID_EXAMPLE), Some(SECRET_EXAMPLE));
-    assert_eq!(sk_client.get(&ID_EXAMPLE_2), Some(SECRET_EXAMPLE));
-    assert_eq!(sk_client.get(&ID_NOT_STORED), None);
+    assert_eq!(sk_client.get(&ID_EXAMPLE).unwrap(), SECRET_EXAMPLE);
+    assert_eq!(sk_client.get(&ID_EXAMPLE_2).unwrap(), SECRET_EXAMPLE);
+    assert_entry_not_found(sk_client.get(&ID_NOT_STORED));
 }
 
-#[test]
-fn secretkeeper_store_delete_all() {
-    let mut sk_client = setup_client!();
+// Don't run deleteAll() on a secure device, as it might affect real secrets.
+#[rdroidtest(get_instances())]
+#[ignore_if(|p| p != "nonsecure")]
+fn secretkeeper_store_delete_all(instance: String) {
+    let mut sk_client = SkClient::new(&instance);
 
-    if sk_client.name != "nonsecure" {
-        // Don't run deleteAll() on a secure device, as it might affect
-        // real secrets.
-        warn!("skipping deleteAll test due to real impl");
-        return;
-    }
-
-    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE);
-    sk_client.store(&ID_EXAMPLE_2, &SECRET_EXAMPLE);
+    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE).unwrap();
+    sk_client.store(&ID_EXAMPLE_2, &SECRET_EXAMPLE).unwrap();
 
     sk_client.delete_all();
 
-    assert_eq!(sk_client.get(&ID_EXAMPLE), None);
-    assert_eq!(sk_client.get(&ID_EXAMPLE_2), None);
+    assert_entry_not_found(sk_client.get(&ID_EXAMPLE));
+    assert_entry_not_found(sk_client.get(&ID_EXAMPLE_2));
 
     // Store a new secret (corresponding to an id).
-    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE);
+    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE).unwrap();
 
     // Get the restored secret.
-    assert_eq!(sk_client.get(&ID_EXAMPLE), Some(SECRET_EXAMPLE));
+    assert_eq!(sk_client.get(&ID_EXAMPLE).unwrap(), SECRET_EXAMPLE);
 
     // (Try to) Get the secret that was never stored
-    assert_eq!(sk_client.get(&ID_NOT_STORED), None);
+    assert_entry_not_found(sk_client.get(&ID_NOT_STORED));
 }
 
 // This test checks that Secretkeeper uses the expected [`RequestSeqNum`] as aad while
 // decrypting requests and the responses are encrypted with correct [`ResponseSeqNum`] for the
 // first few messages.
-#[test]
-fn secret_management_replay_protection_seq_num() {
-    let sk_client = setup_client!();
+#[rdroidtest(get_instances())]
+fn secret_management_replay_protection_seq_num(instance: String) {
+    let dice_chain = make_explicit_owned_dice(/*Security version in a node */ 5);
+    let sealing_policy = sealing_policy(dice_chain.explicit_key_dice_chain().unwrap());
+    let sk_client = SkClient::with_identity(&instance, dice_chain);
     // Construct encoded request packets for the test
-    let (req_1, req_2, req_3) = construct_secret_management_requests();
+    let (req_1, req_2, req_3) = construct_secret_management_requests(sealing_policy);
 
     // Lets now construct the seq_numbers(in request & expected in response)
     let mut seq_a = SeqNum::new();
@@ -462,21 +460,21 @@
 
     // Check first request/response is successful
     let res = ResponsePacket::from_slice(
-        &sk_client.secret_management_request_custom_aad(&req_1, &seq_0, &seq_0),
+        &sk_client.secret_management_request_custom_aad(&req_1, &seq_0, &seq_0).unwrap(),
     )
     .unwrap();
     assert_eq!(res.response_type().unwrap(), ResponseType::Success);
 
     // Check 2nd request/response is successful
     let res = ResponsePacket::from_slice(
-        &sk_client.secret_management_request_custom_aad(&req_2, &seq_1, &seq_1),
+        &sk_client.secret_management_request_custom_aad(&req_2, &seq_1, &seq_1).unwrap(),
     )
     .unwrap();
     assert_eq!(res.response_type().unwrap(), ResponseType::Success);
 
     // Check 3rd request/response is successful
     let res = ResponsePacket::from_slice(
-        &sk_client.secret_management_request_custom_aad(&req_3, &seq_2, &seq_2),
+        &sk_client.secret_management_request_custom_aad(&req_3, &seq_2, &seq_2).unwrap(),
     )
     .unwrap();
     assert_eq!(res.response_type().unwrap(), ResponseType::Success);
@@ -484,69 +482,94 @@
 
 // This test checks that Secretkeeper uses fresh [`RequestSeqNum`] & [`ResponseSeqNum`]
 // for new sessions.
-#[test]
-fn secret_management_replay_protection_seq_num_per_session() {
-    let sk_client = setup_client!();
+#[rdroidtest(get_instances())]
+fn secret_management_replay_protection_seq_num_per_session(instance: String) {
+    let dice_chain = make_explicit_owned_dice(/*Security version in a node */ 5);
+    let sealing_policy = sealing_policy(dice_chain.explicit_key_dice_chain().unwrap());
+    let sk_client = SkClient::with_identity(&instance, dice_chain);
 
     // Construct encoded request packets for the test
-    let (req_1, _, _) = construct_secret_management_requests();
+    let (req_1, _, _) = construct_secret_management_requests(sealing_policy);
 
     // Lets now construct the seq_number (in request & expected in response)
     let mut seq_a = SeqNum::new();
     let seq_0 = seq_a.get_then_increment().unwrap();
     // Check first request/response is successful
     let res = ResponsePacket::from_slice(
-        &sk_client.secret_management_request_custom_aad(&req_1, &seq_0, &seq_0),
+        &sk_client.secret_management_request_custom_aad(&req_1, &seq_0, &seq_0).unwrap(),
     )
     .unwrap();
     assert_eq!(res.response_type().unwrap(), ResponseType::Success);
 
     // Start another session
-    let sk_client_diff = setup_client!();
+    let sk_client_diff = SkClient::new(&instance);
     // Check first request/response is with seq_0 is successful
     let res = ResponsePacket::from_slice(
-        &sk_client_diff.secret_management_request_custom_aad(&req_1, &seq_0, &seq_0),
+        &sk_client_diff.secret_management_request_custom_aad(&req_1, &seq_0, &seq_0).unwrap(),
     )
     .unwrap();
     assert_eq!(res.response_type().unwrap(), ResponseType::Success);
 }
 
 // This test checks that Secretkeeper rejects requests with out of order [`RequestSeqNum`]
-#[test]
 // TODO(b/317416663): This test fails, when HAL is not present in the device. Refactor to fix this.
-#[ignore]
-#[should_panic]
-fn secret_management_replay_protection_out_of_seq_req_not_accepted() {
-    let sk_client = setup_client!();
+#[rdroidtest(get_instances())]
+fn secret_management_replay_protection_out_of_seq_req_not_accepted(instance: String) {
+    let dice_chain = make_explicit_owned_dice(/*Security version in a node */ 5);
+    let sealing_policy = sealing_policy(dice_chain.explicit_key_dice_chain().unwrap());
+    let sk_client = SkClient::with_identity(&instance, dice_chain);
 
     // Construct encoded request packets for the test
-    let (req_1, req_2, _) = construct_secret_management_requests();
+    let (req_1, req_2, _) = construct_secret_management_requests(sealing_policy);
 
     // Lets now construct the seq_numbers(in request & expected in response)
     let mut seq_a = SeqNum::new();
     let [seq_0, seq_1, seq_2] = std::array::from_fn(|_| seq_a.get_then_increment().unwrap());
 
     // Assume First request/response is successful
-    sk_client.secret_management_request_custom_aad(&req_1, &seq_0, &seq_0);
+    sk_client.secret_management_request_custom_aad(&req_1, &seq_0, &seq_0).unwrap();
 
     // Check 2nd request/response with skipped seq_num in request is a binder error
-    // This should panic!
-    sk_client.secret_management_request_custom_aad(&req_2, /*Skipping seq_1*/ &seq_2, &seq_1);
+    let res = sk_client
+        .secret_management_request_custom_aad(&req_2, /*Skipping seq_1*/ &seq_2, &seq_1);
+    let err = res.expect_err("Out of Seq messages accepted!");
+    // Incorrect sequence numbers lead to failed decryption. The resultant error should be
+    // thrown in clear text & wrapped in Binder errors.
+    assert!(matches!(err, Error::InfraError(secretkeeper_client::Error::BinderStatus(_e))));
 }
 
-fn construct_secret_management_requests() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
+// This test checks DICE policy based access control of Secretkeeper.
+#[rdroidtest(get_instances())]
+fn secret_management_policy_gate(instance: String) {
+    let dice_chain = make_explicit_owned_dice(/*Security version in a node */ 100);
+    let mut sk_client = SkClient::with_identity(&instance, dice_chain);
+    sk_client.store(&ID_EXAMPLE, &SECRET_EXAMPLE).unwrap();
+
+    // Start a session with higher security_version & get the stored secret.
+    let dice_chain_upgraded = make_explicit_owned_dice(/*Security version in a node */ 101);
+    let mut sk_client_upgraded = SkClient::with_identity(&instance, dice_chain_upgraded);
+    assert_eq!(sk_client_upgraded.get(&ID_EXAMPLE).unwrap(), SECRET_EXAMPLE);
+
+    // Start a session with lower security_version (This should be denied access to the secret).
+    let dice_chain_downgraded = make_explicit_owned_dice(/*Security version in a node */ 99);
+    let mut sk_client_downgraded = SkClient::with_identity(&instance, dice_chain_downgraded);
+    assert!(matches!(
+        sk_client_downgraded.get(&ID_EXAMPLE).unwrap_err(),
+        Error::SecretkeeperError(SecretkeeperError::DicePolicyError)
+    ));
+}
+
+// Helper method that constructs 3 SecretManagement requests. Callers would usually not care about
+// what each of the request concretely is.
+fn construct_secret_management_requests(sealing_policy: Vec<u8>) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
     let version_request = GetVersionRequest {};
     let version_request = version_request.serialize_to_packet().to_vec().unwrap();
-    let store_request = StoreSecretRequest {
-        id: ID_EXAMPLE,
-        secret: SECRET_EXAMPLE,
-        sealing_policy: HYPOTHETICAL_DICE_POLICY.to_vec(),
-    };
+    let store_request =
+        StoreSecretRequest { id: ID_EXAMPLE, secret: SECRET_EXAMPLE, sealing_policy };
     let store_request = store_request.serialize_to_packet().to_vec().unwrap();
-    let get_request = GetSecretRequest {
-        id: ID_EXAMPLE,
-        updated_sealing_policy: None,
-    };
+    let get_request = GetSecretRequest { id: ID_EXAMPLE, updated_sealing_policy: None };
     let get_request = get_request.serialize_to_packet().to_vec().unwrap();
     (version_request, store_request, get_request)
 }
+
+rdroidtest::test_main!();
diff --git a/security/secretkeeper/default/Android.bp b/security/secretkeeper/default/Android.bp
index 1d75c74..d8ccb63 100644
--- a/security/secretkeeper/default/Android.bp
+++ b/security/secretkeeper/default/Android.bp
@@ -34,6 +34,7 @@
         "libauthgraph_core",
         "libauthgraph_hal",
         "libbinder_rs",
+        "libcoset",
         "liblog_rust",
         "libsecretkeeper_core_nostd",
         "libsecretkeeper_comm_nostd",
diff --git a/security/secretkeeper/default/src/lib.rs b/security/secretkeeper/default/src/lib.rs
index 412ad45..eb7817c 100644
--- a/security/secretkeeper/default/src/lib.rs
+++ b/security/secretkeeper/default/src/lib.rs
@@ -53,8 +53,12 @@
             let mut crypto_impls = boring::crypto_trait_impls();
             let storage_impl = Box::new(store::InMemoryStore::default());
             let sk_ta = Rc::new(RefCell::new(
-                SecretkeeperTa::new(&mut crypto_impls, storage_impl)
-                    .expect("Failed to create local Secretkeeper TA"),
+                SecretkeeperTa::new(
+                    &mut crypto_impls,
+                    storage_impl,
+                    coset::iana::EllipticCurve::Ed25519,
+                )
+                .expect("Failed to create local Secretkeeper TA"),
             ));
             let mut ag_ta = AuthGraphTa::new(
                 AuthGraphParticipant::new(crypto_impls, sk_ta.clone(), MAX_OPENED_SESSIONS)
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
index 21951b6..58919d1 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
@@ -46,6 +46,7 @@
   CCC_SUPPORTED_MAX_RANGING_SESSION_NUMBER = 0xA8,
   CCC_SUPPORTED_MIN_UWB_INITIATION_TIME_MS = 0xA9,
   CCC_PRIORITIZED_CHANNEL_LIST = 0xAA,
+  CCC_SUPPORTED_UWBS_MAX_PPM = 0xAB,
   RADAR_SUPPORT = 0xB0,
   SUPPORTED_AOA_RESULT_REQ_ANTENNA_INTERLEAVING = 0xE3,
   SUPPORTED_MIN_RANGING_INTERVAL_MS = 0xE4,
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
index 2141b5a..4df45b6 100644
--- a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
@@ -154,6 +154,11 @@
      */
     CCC_PRIORITIZED_CHANNEL_LIST = 0xAA,
 
+    /**
+     * Short (2-octet) value to indicate the UWBS Max Clock Skew PPM value.
+     */
+    CCC_SUPPORTED_UWBS_MAX_PPM = 0xAB,
+
     /*********************************************
      * RADAR specific
      ********************************************/
diff --git a/wifi/1.0/Android.bp b/wifi/1.0/Android.bp
index 94f8462..21a5d15 100644
--- a/wifi/1.0/Android.bp
+++ b/wifi/1.0/Android.bp
@@ -33,4 +33,8 @@
     ],
     gen_java: true,
     gen_java_constants: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/1.1/Android.bp b/wifi/1.1/Android.bp
index 7b4116a..b5e4105 100644
--- a/wifi/1.1/Android.bp
+++ b/wifi/1.1/Android.bp
@@ -21,4 +21,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/1.2/Android.bp b/wifi/1.2/Android.bp
index f0edb81..83b156e 100644
--- a/wifi/1.2/Android.bp
+++ b/wifi/1.2/Android.bp
@@ -27,4 +27,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/1.3/Android.bp b/wifi/1.3/Android.bp
index 030d7f6..2ba612e 100644
--- a/wifi/1.3/Android.bp
+++ b/wifi/1.3/Android.bp
@@ -25,4 +25,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/1.4/Android.bp b/wifi/1.4/Android.bp
index 1523f79..48578f8 100644
--- a/wifi/1.4/Android.bp
+++ b/wifi/1.4/Android.bp
@@ -30,4 +30,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/aidl/vts/functional/wifi_sta_iface_aidl_test.cpp b/wifi/aidl/vts/functional/wifi_sta_iface_aidl_test.cpp
index 1ea1237..f09a26b 100644
--- a/wifi/aidl/vts/functional/wifi_sta_iface_aidl_test.cpp
+++ b/wifi/aidl/vts/functional/wifi_sta_iface_aidl_test.cpp
@@ -69,18 +69,9 @@
 
     std::shared_ptr<IWifiStaIface> wifi_sta_iface_;
 
-    // Checks if the MdnsOffloadManagerService is installed.
-    bool isMdnsOffloadServicePresent() {
-        int status =
-                // --query-flags MATCH_SYSTEM_ONLY(1048576) will only return matched service
-                // installed on system or system_ext partition. The MdnsOffloadManagerService should
-                // be installed on system_ext partition.
-                // NOLINTNEXTLINE(cert-env33-c)
-                system("pm query-services --query-flags 1048576"
-                       " com.android.tv.mdnsoffloadmanager/"
-                       "com.android.tv.mdnsoffloadmanager.MdnsOffloadManagerService"
-                       " | egrep -q mdnsoffloadmanager");
-        return status == 0;
+    // Checks if the mDNS Offload is supported by any NIC.
+    bool isMdnsOffloadPresentInNIC() {
+        return testing::deviceSupportsFeature("android.hardware.mdns_offload");
     }
 
     // Detected panel TV device by using ro.oem.key1 property.
@@ -146,7 +137,7 @@
 TEST_P(WifiStaIfaceAidlTest, CheckApfIsSupported) {
     // Flat panel TV devices that support MDNS offload do not have to implement APF if the WiFi
     // chipset does not have sufficient RAM to do so.
-    if (isPanelTvDevice() && isMdnsOffloadServicePresent()) {
+    if (isPanelTvDevice() && isMdnsOffloadPresentInNIC()) {
         GTEST_SKIP() << "Panel TV supports mDNS offload. It is not required to support APF";
     }
     int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
diff --git a/wifi/hostapd/1.0/Android.bp b/wifi/hostapd/1.0/Android.bp
index afcd45c..b9a84d6 100644
--- a/wifi/hostapd/1.0/Android.bp
+++ b/wifi/hostapd/1.0/Android.bp
@@ -21,4 +21,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/hostapd/1.1/Android.bp b/wifi/hostapd/1.1/Android.bp
index f5f2fbe..c90b68d 100644
--- a/wifi/hostapd/1.1/Android.bp
+++ b/wifi/hostapd/1.1/Android.bp
@@ -22,4 +22,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/hostapd/1.2/Android.bp b/wifi/hostapd/1.2/Android.bp
index 4ca41aa..c8bf2f8 100644
--- a/wifi/hostapd/1.2/Android.bp
+++ b/wifi/hostapd/1.2/Android.bp
@@ -23,4 +23,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/netlinkinterceptor/aidl/default/InterceptorRelay.h b/wifi/netlinkinterceptor/aidl/default/InterceptorRelay.h
index 0178c90..915b5ff 100644
--- a/wifi/netlinkinterceptor/aidl/default/InterceptorRelay.h
+++ b/wifi/netlinkinterceptor/aidl/default/InterceptorRelay.h
@@ -18,6 +18,7 @@
 
 #include <libnl++/Socket.h>
 
+#include <atomic>
 #include <mutex>
 #include <thread>
 
diff --git a/wifi/supplicant/1.0/Android.bp b/wifi/supplicant/1.0/Android.bp
index 66e9353..89a0907 100644
--- a/wifi/supplicant/1.0/Android.bp
+++ b/wifi/supplicant/1.0/Android.bp
@@ -31,4 +31,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/supplicant/1.1/Android.bp b/wifi/supplicant/1.1/Android.bp
index c624374..f925671 100644
--- a/wifi/supplicant/1.1/Android.bp
+++ b/wifi/supplicant/1.1/Android.bp
@@ -23,4 +23,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/supplicant/1.2/Android.bp b/wifi/supplicant/1.2/Android.bp
index d5d937f..f61d9b9 100644
--- a/wifi/supplicant/1.2/Android.bp
+++ b/wifi/supplicant/1.2/Android.bp
@@ -26,4 +26,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }
diff --git a/wifi/supplicant/1.3/Android.bp b/wifi/supplicant/1.3/Android.bp
index fbe7f75..173a1ef 100644
--- a/wifi/supplicant/1.3/Android.bp
+++ b/wifi/supplicant/1.3/Android.bp
@@ -27,4 +27,8 @@
         "android.hidl.base@1.0",
     ],
     gen_java: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.wifi",
+    ],
 }