Merge changes from topic "revert-2649121-cm_vintf_workaround-PMVOGMKMBW"

* changes:
  Revert "Only allow cuttlefish to use FCM 9 HALs"
  Revert "Allow fingerprint HAL to be updated via apex in U"
diff --git a/audio/aidl/default/Android.bp b/audio/aidl/default/Android.bp
index bda0de2..e9294cf 100644
--- a/audio/aidl/default/Android.bp
+++ b/audio/aidl/default/Android.bp
@@ -18,6 +18,7 @@
         "libbinder_ndk",
         "libcutils",
         "libfmq",
+        "libnbaio_mono",
         "libstagefright_foundation",
         "libtinyalsav2",
         "libutils",
@@ -76,6 +77,10 @@
         "Stream.cpp",
         "StreamStub.cpp",
         "Telephony.cpp",
+        "r_submix/ModuleRemoteSubmix.cpp",
+        "r_submix/RemoteSubmixUtils.cpp",
+        "r_submix/SubmixRoute.cpp",
+        "r_submix/StreamRemoteSubmix.cpp",
         "usb/ModuleUsb.cpp",
         "usb/StreamUsb.cpp",
         "usb/UsbAlsaMixerControl.cpp",
diff --git a/audio/aidl/default/EffectConfig.cpp b/audio/aidl/default/EffectConfig.cpp
index 71d111b..f3f674f 100644
--- a/audio/aidl/default/EffectConfig.cpp
+++ b/audio/aidl/default/EffectConfig.cpp
@@ -18,6 +18,7 @@
 #include <string>
 #define LOG_TAG "AHAL_EffectConfig"
 #include <android-base/logging.h>
+#include <system/audio_aidl_utils.h>
 #include <system/audio_effects/audio_effects_conf.h>
 #include <system/audio_effects/effect_uuid.h>
 
@@ -162,7 +163,7 @@
     RETURN_VALUE_IF((libraryUuid.uuid == getEffectUuidZero()), false, "invalidUuidAttribute");
 
     LOG(DEBUG) << __func__ << (isProxy ? " proxy " : libraryUuid.name) << " : "
-               << libraryUuid.uuid.toString();
+               << ::android::audio::utils::toString(libraryUuid.uuid);
     return true;
 }
 
@@ -250,6 +251,7 @@
     V("downmix", Downmix)                                  \
     V("dynamics_processing", DynamicsProcessing)           \
     V("equalizer", Equalizer)                              \
+    V("extensioneffect", Extension)                        \
     V("haptic_generator", HapticGenerator)                 \
     V("loudness_enhancer", LoudnessEnhancer)               \
     V("env_reverb", EnvReverb)                             \
diff --git a/audio/aidl/default/EffectFactory.cpp b/audio/aidl/default/EffectFactory.cpp
index 7073a10..8ed62c9 100644
--- a/audio/aidl/default/EffectFactory.cpp
+++ b/audio/aidl/default/EffectFactory.cpp
@@ -25,6 +25,7 @@
 
 #include <android-base/logging.h>
 #include <android/binder_ibinder_platform.h>
+#include <system/audio_aidl_utils.h>
 #include <system/audio_effects/effect_uuid.h>
 #include <system/thread_defs.h>
 
@@ -47,7 +48,7 @@
         for (const auto& it : mEffectMap) {
             if (auto spEffect = it.first.lock()) {
                 LOG(ERROR) << __func__ << " erase remaining instance UUID "
-                           << it.second.first.toString();
+                           << ::android::audio::utils::toString(it.second.first);
                 destroyEffectImpl(spEffect);
             }
         }
@@ -123,7 +124,7 @@
 
 ndk::ScopedAStatus Factory::createEffect(const AudioUuid& in_impl_uuid,
                                          std::shared_ptr<IEffect>* _aidl_return) {
-    LOG(DEBUG) << __func__ << ": UUID " << in_impl_uuid.toString();
+    LOG(DEBUG) << __func__ << ": UUID " << ::android::audio::utils::toString(in_impl_uuid);
     if (mEffectLibMap.count(in_impl_uuid)) {
         auto& entry = mEffectLibMap[in_impl_uuid];
         getDlSyms(entry);
@@ -163,7 +164,8 @@
                       "dlNulldestroyEffectFunc");
             RETURN_IF_BINDER_EXCEPTION(interface->destroyEffectFunc(in_handle));
         } else {
-            LOG(ERROR) << __func__ << ": UUID " << uuid.toString() << " does not exist in libMap!";
+            LOG(ERROR) << __func__ << ": UUID " << ::android::audio::utils::toString(uuid)
+                       << " does not exist in libMap!";
             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
         }
         mEffectMap.erase(effectIt);
@@ -207,8 +209,8 @@
         return false;
     }
 
-    LOG(INFO) << __func__ << " dlopen lib:" << path << "\nimpl:" << impl.toString()
-              << "\nhandle:" << libHandle;
+    LOG(INFO) << __func__ << " dlopen lib:" << path
+              << "\nimpl:" << ::android::audio::utils::toString(impl) << "\nhandle:" << libHandle;
     auto interface = new effect_dl_interface_s{nullptr, nullptr, nullptr};
     mEffectLibMap.insert(
             {impl,
@@ -228,8 +230,10 @@
         id.uuid = configLib.uuid;
         id.proxy = proxyUuid;
         LOG(DEBUG) << __func__ << " loading lib " << path->second << ": typeUuid "
-                   << id.type.toString() << "\nimplUuid " << id.uuid.toString() << " proxyUuid "
-                   << (proxyUuid.has_value() ? proxyUuid->toString() : "null");
+                   << ::android::audio::utils::toString(id.type) << "\nimplUuid "
+                   << ::android::audio::utils::toString(id.uuid) << " proxyUuid "
+                   << (proxyUuid.has_value() ? ::android::audio::utils::toString(proxyUuid.value())
+                                             : "null");
         if (openEffectLibrary(id.uuid, path->second)) {
             mIdentitySet.insert(std::move(id));
         }
diff --git a/audio/aidl/default/Module.cpp b/audio/aidl/default/Module.cpp
index 6f89d4b..48d1458 100644
--- a/audio/aidl/default/Module.cpp
+++ b/audio/aidl/default/Module.cpp
@@ -27,6 +27,7 @@
 
 #include "core-impl/Bluetooth.h"
 #include "core-impl/Module.h"
+#include "core-impl/ModuleRemoteSubmix.h"
 #include "core-impl/ModuleUsb.h"
 #include "core-impl/SoundDose.h"
 #include "core-impl/StreamStub.h"
@@ -111,8 +112,9 @@
     switch (type) {
         case Module::Type::USB:
             return ndk::SharedRefBase::make<ModuleUsb>(type);
-        case Type::DEFAULT:
         case Type::R_SUBMIX:
+            return ndk::SharedRefBase::make<ModuleRemoteSubmix>(type);
+        case Type::DEFAULT:
         default:
             return ndk::SharedRefBase::make<Module>(type);
     }
@@ -181,8 +183,8 @@
         StreamContext temp(
                 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
                 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
-                portConfigIt->format.value(), portConfigIt->channelMask.value(),
-                portConfigIt->sampleRate.value().value, flags,
+                portConfigIt->portId, portConfigIt->format.value(),
+                portConfigIt->channelMask.value(), portConfigIt->sampleRate.value().value, flags,
                 portConfigIt->ext.get<AudioPortExt::mix>().handle,
                 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
                 asyncCallback, outEventCallback, params);
@@ -490,6 +492,17 @@
         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
     }
 
+    for (auto profile : connectedPort.profiles) {
+        if (profile.channelMasks.empty()) {
+            LOG(ERROR) << __func__ << ": the profile " << profile.name << " has no channel masks";
+            return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+        }
+        if (profile.sampleRates.empty()) {
+            LOG(ERROR) << __func__ << ": the profile " << profile.name << " has no sample rates";
+            return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+        }
+    }
+
     connectedPort.id = ++getConfig().nextPortId;
     auto [connectedPortsIt, _] =
             mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::vector<int32_t>()));
diff --git a/audio/aidl/default/Stream.cpp b/audio/aidl/default/Stream.cpp
index 73f1293..251dea0 100644
--- a/audio/aidl/default/Stream.cpp
+++ b/audio/aidl/default/Stream.cpp
@@ -166,10 +166,15 @@
         case Tag::start:
             if (mState == StreamDescriptor::State::STANDBY ||
                 mState == StreamDescriptor::State::DRAINING) {
-                populateReply(&reply, mIsConnected);
-                mState = mState == StreamDescriptor::State::STANDBY
-                                 ? StreamDescriptor::State::IDLE
-                                 : StreamDescriptor::State::ACTIVE;
+                if (::android::status_t status = mDriver->start(); status == ::android::OK) {
+                    populateReply(&reply, mIsConnected);
+                    mState = mState == StreamDescriptor::State::STANDBY
+                                     ? StreamDescriptor::State::IDLE
+                                     : StreamDescriptor::State::ACTIVE;
+                } else {
+                    LOG(ERROR) << __func__ << ": start failed: " << status;
+                    mState = StreamDescriptor::State::ERROR;
+                }
             } else {
                 populateReplyWrongState(&reply, command);
             }
@@ -377,26 +382,36 @@
             populateReply(&reply, mIsConnected);
             break;
         case Tag::start: {
-            bool commandAccepted = true;
+            std::optional<StreamDescriptor::State> nextState;
             switch (mState) {
                 case StreamDescriptor::State::STANDBY:
-                    mState = StreamDescriptor::State::IDLE;
+                    nextState = StreamDescriptor::State::IDLE;
                     break;
                 case StreamDescriptor::State::PAUSED:
-                    mState = StreamDescriptor::State::ACTIVE;
+                    nextState = StreamDescriptor::State::ACTIVE;
                     break;
                 case StreamDescriptor::State::DRAIN_PAUSED:
-                    switchToTransientState(StreamDescriptor::State::DRAINING);
+                    nextState = StreamDescriptor::State::DRAINING;
                     break;
                 case StreamDescriptor::State::TRANSFER_PAUSED:
-                    switchToTransientState(StreamDescriptor::State::TRANSFERRING);
+                    nextState = StreamDescriptor::State::TRANSFERRING;
                     break;
                 default:
                     populateReplyWrongState(&reply, command);
-                    commandAccepted = false;
             }
-            if (commandAccepted) {
-                populateReply(&reply, mIsConnected);
+            if (nextState.has_value()) {
+                if (::android::status_t status = mDriver->start(); status == ::android::OK) {
+                    populateReply(&reply, mIsConnected);
+                    if (*nextState == StreamDescriptor::State::IDLE ||
+                        *nextState == StreamDescriptor::State::ACTIVE) {
+                        mState = *nextState;
+                    } else {
+                        switchToTransientState(*nextState);
+                    }
+                } else {
+                    LOG(ERROR) << __func__ << ": start failed: " << status;
+                    mState = StreamDescriptor::State::ERROR;
+                }
             }
         } break;
         case Tag::burst:
diff --git a/audio/aidl/default/StreamStub.cpp b/audio/aidl/default/StreamStub.cpp
index d88dfbc..2dcf4d4 100644
--- a/audio/aidl/default/StreamStub.cpp
+++ b/audio/aidl/default/StreamStub.cpp
@@ -33,33 +33,67 @@
 
 StreamStub::StreamStub(const Metadata& metadata, StreamContext&& context)
     : StreamCommonImpl(metadata, std::move(context)),
-      mFrameSizeBytes(context.getFrameSize()),
-      mSampleRate(context.getSampleRate()),
-      mIsAsynchronous(!!context.getAsyncCallback()),
+      mFrameSizeBytes(getContext().getFrameSize()),
+      mSampleRate(getContext().getSampleRate()),
+      mIsAsynchronous(!!getContext().getAsyncCallback()),
       mIsInput(isInput(metadata)) {}
 
 ::android::status_t StreamStub::init() {
+    mIsInitialized = true;
     usleep(500);
     return ::android::OK;
 }
 
 ::android::status_t StreamStub::drain(StreamDescriptor::DrainMode) {
+    if (!mIsInitialized) {
+        LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+    }
     usleep(500);
     return ::android::OK;
 }
 
 ::android::status_t StreamStub::flush() {
+    if (!mIsInitialized) {
+        LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+    }
     usleep(500);
     return ::android::OK;
 }
 
 ::android::status_t StreamStub::pause() {
+    if (!mIsInitialized) {
+        LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+    }
     usleep(500);
     return ::android::OK;
 }
 
+::android::status_t StreamStub::standby() {
+    if (!mIsInitialized) {
+        LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+    }
+    usleep(500);
+    mIsStandby = true;
+    return ::android::OK;
+}
+
+::android::status_t StreamStub::start() {
+    if (!mIsInitialized) {
+        LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+    }
+    usleep(500);
+    mIsStandby = false;
+    return ::android::OK;
+}
+
 ::android::status_t StreamStub::transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
                                          int32_t* latencyMs) {
+    if (!mIsInitialized) {
+        LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+    }
+    if (mIsStandby) {
+        LOG(FATAL) << __func__ << ": must not happen while in standby";
+    }
     static constexpr float kMicrosPerSecond = MICROS_PER_SECOND;
     static constexpr float kScaleFactor = .8f;
     if (mIsAsynchronous) {
@@ -80,13 +114,10 @@
     return ::android::OK;
 }
 
-::android::status_t StreamStub::standby() {
-    usleep(500);
-    return ::android::OK;
+void StreamStub::shutdown() {
+    mIsInitialized = false;
 }
 
-void StreamStub::shutdown() {}
-
 StreamInStub::StreamInStub(const SinkMetadata& sinkMetadata, StreamContext&& context,
                            const std::vector<MicrophoneInfo>& microphones)
     : StreamStub(sinkMetadata, std::move(context)), StreamIn(microphones) {}
diff --git a/audio/aidl/default/extension/ExtensionEffect.cpp b/audio/aidl/default/extension/ExtensionEffect.cpp
index c4eebc0..4a4d71b6 100644
--- a/audio/aidl/default/extension/ExtensionEffect.cpp
+++ b/audio/aidl/default/extension/ExtensionEffect.cpp
@@ -30,8 +30,8 @@
 using aidl::android::hardware::audio::effect::DefaultExtension;
 using aidl::android::hardware::audio::effect::Descriptor;
 using aidl::android::hardware::audio::effect::ExtensionEffect;
-using aidl::android::hardware::audio::effect::getEffectUuidExtensionImpl;
-using aidl::android::hardware::audio::effect::getEffectUuidExtensionType;
+using aidl::android::hardware::audio::effect::getEffectImplUuidExtension;
+using aidl::android::hardware::audio::effect::getEffectTypeUuidExtension;
 using aidl::android::hardware::audio::effect::IEffect;
 using aidl::android::hardware::audio::effect::Range;
 using aidl::android::hardware::audio::effect::VendorExtension;
@@ -39,7 +39,7 @@
 
 extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
                                            std::shared_ptr<IEffect>* instanceSpp) {
-    if (!in_impl_uuid || *in_impl_uuid != getEffectUuidExtensionImpl()) {
+    if (!in_impl_uuid || *in_impl_uuid != getEffectImplUuidExtension()) {
         LOG(ERROR) << __func__ << "uuid not supported";
         return EX_ILLEGAL_ARGUMENT;
     }
@@ -54,7 +54,7 @@
 }
 
 extern "C" binder_exception_t queryEffect(const AudioUuid* in_impl_uuid, Descriptor* _aidl_return) {
-    if (!in_impl_uuid || *in_impl_uuid != getEffectUuidExtensionImpl()) {
+    if (!in_impl_uuid || *in_impl_uuid != getEffectImplUuidExtension()) {
         LOG(ERROR) << __func__ << "uuid not supported";
         return EX_ILLEGAL_ARGUMENT;
     }
@@ -67,8 +67,8 @@
 const std::string ExtensionEffect::kEffectName = "ExtensionEffectExample";
 
 const Descriptor ExtensionEffect::kDescriptor = {
-        .common = {.id = {.type = getEffectUuidExtensionType(),
-                          .uuid = getEffectUuidExtensionImpl(),
+        .common = {.id = {.type = getEffectTypeUuidExtension(),
+                          .uuid = getEffectImplUuidExtension(),
                           .proxy = std::nullopt},
                    .name = ExtensionEffect::kEffectName,
                    .implementor = "The Android Open Source Project"}};
diff --git a/audio/aidl/default/include/core-impl/ModuleRemoteSubmix.h b/audio/aidl/default/include/core-impl/ModuleRemoteSubmix.h
new file mode 100644
index 0000000..7b1d375
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/ModuleRemoteSubmix.h
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include "core-impl/Module.h"
+
+namespace aidl::android::hardware::audio::core {
+
+class ModuleRemoteSubmix : public Module {
+  public:
+    explicit ModuleRemoteSubmix(Module::Type type) : Module(type) {}
+
+  private:
+    // IModule interfaces
+    ndk::ScopedAStatus getTelephony(std::shared_ptr<ITelephony>* _aidl_return) override;
+    ndk::ScopedAStatus getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) override;
+    ndk::ScopedAStatus getMicMute(bool* _aidl_return) override;
+    ndk::ScopedAStatus setMicMute(bool in_mute) override;
+
+    // Module interfaces
+    ndk::ScopedAStatus createInputStream(
+            const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+            StreamContext&& context,
+            const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
+            std::shared_ptr<StreamIn>* result) override;
+    ndk::ScopedAStatus createOutputStream(
+            const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+            StreamContext&& context,
+            const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+                    offloadInfo,
+            std::shared_ptr<StreamOut>* result) override;
+    ndk::ScopedAStatus populateConnectedDevicePort(
+            ::aidl::android::media::audio::common::AudioPort* audioPort) override;
+    ndk::ScopedAStatus checkAudioPatchEndpointsMatch(
+            const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sources,
+            const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sinks)
+            override;
+    void onExternalDeviceConnectionChanged(
+            const ::aidl::android::media::audio::common::AudioPort& audioPort,
+            bool connected) override;
+    ndk::ScopedAStatus onMasterMuteChanged(bool mute) override;
+    ndk::ScopedAStatus onMasterVolumeChanged(float volume) override;
+};
+
+}  // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/Stream.h b/audio/aidl/default/include/core-impl/Stream.h
index c20a421..aaf5860 100644
--- a/audio/aidl/default/include/core-impl/Stream.h
+++ b/audio/aidl/default/include/core-impl/Stream.h
@@ -78,6 +78,7 @@
 
     StreamContext() = default;
     StreamContext(std::unique_ptr<CommandMQ> commandMQ, std::unique_ptr<ReplyMQ> replyMQ,
+                  int portId,
                   const ::aidl::android::media::audio::common::AudioFormatDescription& format,
                   const ::aidl::android::media::audio::common::AudioChannelLayout& channelLayout,
                   int sampleRate, const ::aidl::android::media::audio::common::AudioIoFlags& flags,
@@ -88,6 +89,7 @@
         : mCommandMQ(std::move(commandMQ)),
           mInternalCommandCookie(std::rand()),
           mReplyMQ(std::move(replyMQ)),
+          mPortId(portId),
           mFormat(format),
           mChannelLayout(channelLayout),
           mSampleRate(sampleRate),
@@ -101,6 +103,7 @@
         : mCommandMQ(std::move(other.mCommandMQ)),
           mInternalCommandCookie(other.mInternalCommandCookie),
           mReplyMQ(std::move(other.mReplyMQ)),
+          mPortId(other.mPortId),
           mFormat(other.mFormat),
           mChannelLayout(other.mChannelLayout),
           mSampleRate(other.mSampleRate),
@@ -114,6 +117,7 @@
         mCommandMQ = std::move(other.mCommandMQ);
         mInternalCommandCookie = other.mInternalCommandCookie;
         mReplyMQ = std::move(other.mReplyMQ);
+        mPortId = std::move(other.mPortId);
         mFormat = std::move(other.mFormat);
         mChannelLayout = std::move(other.mChannelLayout);
         mSampleRate = other.mSampleRate;
@@ -145,6 +149,7 @@
     std::shared_ptr<IStreamOutEventCallback> getOutEventCallback() const {
         return mOutEventCallback;
     }
+    int getPortId() const { return mPortId; }
     ReplyMQ* getReplyMQ() const { return mReplyMQ.get(); }
     int getTransientStateDelayMs() const { return mDebugParameters.transientStateDelayMs; }
     int getSampleRate() const { return mSampleRate; }
@@ -155,6 +160,7 @@
     std::unique_ptr<CommandMQ> mCommandMQ;
     int mInternalCommandCookie;  // The value used to confirm that the command was posted internally
     std::unique_ptr<ReplyMQ> mReplyMQ;
+    int mPortId;
     ::aidl::android::media::audio::common::AudioFormatDescription mFormat;
     ::aidl::android::media::audio::common::AudioChannelLayout mChannelLayout;
     int mSampleRate;
@@ -174,9 +180,10 @@
     virtual ::android::status_t drain(StreamDescriptor::DrainMode mode) = 0;
     virtual ::android::status_t flush() = 0;
     virtual ::android::status_t pause() = 0;
+    virtual ::android::status_t standby() = 0;
+    virtual ::android::status_t start() = 0;
     virtual ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
                                          int32_t* latencyMs) = 0;
-    virtual ::android::status_t standby() = 0;
     virtual void shutdown() = 0;  // This function is only called once.
 };
 
diff --git a/audio/aidl/default/include/core-impl/StreamRemoteSubmix.h b/audio/aidl/default/include/core-impl/StreamRemoteSubmix.h
new file mode 100644
index 0000000..2253ec7
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/StreamRemoteSubmix.h
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <mutex>
+#include <vector>
+
+#include "core-impl/Stream.h"
+#include "r_submix/SubmixRoute.h"
+
+namespace aidl::android::hardware::audio::core {
+
+using aidl::android::hardware::audio::core::r_submix::AudioConfig;
+using aidl::android::hardware::audio::core::r_submix::SubmixRoute;
+
+class StreamRemoteSubmix : public StreamCommonImpl {
+  public:
+    StreamRemoteSubmix(const Metadata& metadata, StreamContext&& context);
+
+    ::android::status_t init() override;
+    ::android::status_t drain(StreamDescriptor::DrainMode) override;
+    ::android::status_t flush() override;
+    ::android::status_t pause() override;
+    ::android::status_t standby() override;
+    ::android::status_t start() override;
+    ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
+                                 int32_t* latencyMs) override;
+    void shutdown() override;
+
+    // Overridden methods of 'StreamCommonImpl', called on a Binder thread.
+    ndk::ScopedAStatus prepareToClose() override;
+
+  private:
+    size_t getPipeSizeInFrames();
+    size_t getStreamPipeSizeInFrames();
+    ::android::status_t outWrite(void* buffer, size_t frameCount, size_t* actualFrameCount);
+    ::android::status_t inRead(void* buffer, size_t frameCount, size_t* actualFrameCount);
+
+    const int mPortId;
+    const bool mIsInput;
+    AudioConfig mStreamConfig;
+    std::shared_ptr<SubmixRoute> mCurrentRoute = nullptr;
+
+    // Mutex lock to protect vector of submix routes, each of these submix routes have their mutex
+    // locks and none of the mutex locks should be taken together.
+    static std::mutex sSubmixRoutesLock;
+    static std::map<int32_t, std::shared_ptr<SubmixRoute>> sSubmixRoutes
+            GUARDED_BY(sSubmixRoutesLock);
+
+    // limit for number of read error log entries to avoid spamming the logs
+    static constexpr int kMaxReadErrorLogs = 5;
+    // The duration of kMaxReadFailureAttempts * READ_ATTEMPT_SLEEP_MS must be strictly inferior
+    // to the duration of a record buffer at the current record sample rate (of the device, not of
+    // the recording itself). Here we have: 3 * 5ms = 15ms < 1024 frames * 1000 / 48000 = 21.333ms
+    static constexpr int kMaxReadFailureAttempts = 3;
+    // 5ms between two read attempts when pipe is empty
+    static constexpr int kReadAttemptSleepUs = 5000;
+};
+
+class StreamInRemoteSubmix final : public StreamRemoteSubmix, public StreamIn {
+  public:
+    friend class ndk::SharedRefBase;
+    StreamInRemoteSubmix(
+            const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+            StreamContext&& context,
+            const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones);
+
+  private:
+    ndk::ScopedAStatus getActiveMicrophones(
+            std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo>* _aidl_return)
+            override;
+};
+
+class StreamOutRemoteSubmix final : public StreamRemoteSubmix, public StreamOut {
+  public:
+    friend class ndk::SharedRefBase;
+    StreamOutRemoteSubmix(
+            const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+            StreamContext&& context,
+            const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+                    offloadInfo);
+};
+
+}  // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/StreamStub.h b/audio/aidl/default/include/core-impl/StreamStub.h
index c8900f3..6b1b2dd 100644
--- a/audio/aidl/default/include/core-impl/StreamStub.h
+++ b/audio/aidl/default/include/core-impl/StreamStub.h
@@ -28,9 +28,10 @@
     ::android::status_t drain(StreamDescriptor::DrainMode) override;
     ::android::status_t flush() override;
     ::android::status_t pause() override;
+    ::android::status_t standby() override;
+    ::android::status_t start() override;
     ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
                                  int32_t* latencyMs) override;
-    ::android::status_t standby() override;
     void shutdown() override;
 
   private:
@@ -38,6 +39,8 @@
     const int mSampleRate;
     const bool mIsAsynchronous;
     const bool mIsInput;
+    bool mIsInitialized = false;  // Used for validating the state machine logic.
+    bool mIsStandby = true;       // Used for validating the state machine logic.
 };
 
 class StreamInStub final : public StreamStub, public StreamIn {
diff --git a/audio/aidl/default/include/core-impl/StreamUsb.h b/audio/aidl/default/include/core-impl/StreamUsb.h
index 5e55cd8..8c40782 100644
--- a/audio/aidl/default/include/core-impl/StreamUsb.h
+++ b/audio/aidl/default/include/core-impl/StreamUsb.h
@@ -16,7 +16,10 @@
 
 #pragma once
 
+#include <atomic>
+#include <functional>
 #include <mutex>
+#include <optional>
 #include <vector>
 
 #include <aidl/android/media/audio/common/AudioChannelLayout.h>
@@ -38,9 +41,10 @@
     ::android::status_t drain(StreamDescriptor::DrainMode) override;
     ::android::status_t flush() override;
     ::android::status_t pause() override;
+    ::android::status_t standby() override;
+    ::android::status_t start() override;
     ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
                                  int32_t* latencyMs) override;
-    ::android::status_t standby() override;
     void shutdown() override;
 
     // Overridden methods of 'StreamCommonImpl', called on a Binder thread.
@@ -48,15 +52,20 @@
     ndk::ScopedAStatus setConnectedDevices(const ConnectedDevices& devices) override;
 
   private:
-    ::android::status_t exitStandby();
+    using AlsaDeviceProxyDeleter = std::function<void(alsa_device_proxy*)>;
+    using AlsaDeviceProxy = std::unique_ptr<alsa_device_proxy, AlsaDeviceProxyDeleter>;
+
+    static std::optional<struct pcm_config> maybePopulateConfig(const StreamContext& context,
+                                                                bool isInput);
 
     mutable std::mutex mLock;
 
     const size_t mFrameSizeBytes;
-    std::optional<struct pcm_config> mConfig;
     const bool mIsInput;
-    std::vector<std::shared_ptr<alsa_device_proxy>> mAlsaDeviceProxies GUARDED_BY(mLock);
-    bool mIsStandby = true;
+    const std::optional<struct pcm_config> mConfig;
+    std::atomic<bool> mConnectedDevicesUpdated = false;
+    // All fields below are only used on the worker thread.
+    std::vector<AlsaDeviceProxy> mAlsaDeviceProxies;
 };
 
 class StreamInUsb final : public StreamUsb, public StreamIn {
diff --git a/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp b/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp
new file mode 100644
index 0000000..2b79f51
--- /dev/null
+++ b/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp
@@ -0,0 +1,125 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "AHAL_ModuleRemoteSubmix"
+
+#include <vector>
+
+#include <android-base/logging.h>
+
+#include "RemoteSubmixUtils.h"
+#include "core-impl/ModuleRemoteSubmix.h"
+#include "core-impl/StreamRemoteSubmix.h"
+
+using aidl::android::hardware::audio::common::SinkMetadata;
+using aidl::android::hardware::audio::common::SourceMetadata;
+using aidl::android::media::audio::common::AudioOffloadInfo;
+using aidl::android::media::audio::common::AudioPort;
+using aidl::android::media::audio::common::AudioPortConfig;
+using aidl::android::media::audio::common::MicrophoneInfo;
+
+namespace aidl::android::hardware::audio::core {
+
+ndk::ScopedAStatus ModuleRemoteSubmix::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
+    *_aidl_return = nullptr;
+    LOG(DEBUG) << __func__ << ": returning null";
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
+    *_aidl_return = nullptr;
+    LOG(DEBUG) << __func__ << ": returning null";
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::getMicMute(bool* _aidl_return __unused) {
+    LOG(DEBUG) << __func__ << ": is not supported";
+    return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::setMicMute(bool in_mute __unused) {
+    LOG(DEBUG) << __func__ << ": is not supported";
+    return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::createInputStream(
+        const SinkMetadata& sinkMetadata, StreamContext&& context,
+        const std::vector<MicrophoneInfo>& microphones, std::shared_ptr<StreamIn>* result) {
+    return createStreamInstance<StreamInRemoteSubmix>(result, sinkMetadata, std::move(context),
+                                                      microphones);
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::createOutputStream(
+        const SourceMetadata& sourceMetadata, StreamContext&& context,
+        const std::optional<AudioOffloadInfo>& offloadInfo, std::shared_ptr<StreamOut>* result) {
+    return createStreamInstance<StreamOutRemoteSubmix>(result, sourceMetadata, std::move(context),
+                                                       offloadInfo);
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::populateConnectedDevicePort(AudioPort* audioPort) {
+    LOG(VERBOSE) << __func__ << ": Profiles already populated by Configuration";
+    for (auto profile : audioPort->profiles) {
+        for (auto channelMask : profile.channelMasks) {
+            if (!r_submix::isChannelMaskSupported(channelMask)) {
+                LOG(ERROR) << __func__ << ": the profile " << profile.name
+                           << " has unsupported channel mask : " << channelMask.toString();
+                return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+            }
+        }
+        for (auto sampleRate : profile.sampleRates) {
+            if (!r_submix::isSampleRateSupported(sampleRate)) {
+                LOG(ERROR) << __func__ << ": the profile " << profile.name
+                           << " has unsupported sample rate : " << sampleRate;
+                return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+            }
+        }
+    }
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::checkAudioPatchEndpointsMatch(
+        const std::vector<AudioPortConfig*>& sources, const std::vector<AudioPortConfig*>& sinks) {
+    for (const auto& source : sources) {
+        for (const auto& sink : sinks) {
+            if (source->sampleRate != sink->sampleRate ||
+                source->channelMask != sink->channelMask || source->format != sink->format) {
+                LOG(ERROR) << __func__
+                           << ": mismatch port configuration, source=" << source->toString()
+                           << ", sink=" << sink->toString();
+                return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+            }
+        }
+    }
+    return ndk::ScopedAStatus::ok();
+}
+
+void ModuleRemoteSubmix::onExternalDeviceConnectionChanged(
+        const ::aidl::android::media::audio::common::AudioPort& audioPort __unused,
+        bool connected __unused) {
+    LOG(DEBUG) << __func__ << ": do nothing and return";
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::onMasterMuteChanged(bool __unused) {
+    LOG(DEBUG) << __func__ << ": is not supported";
+    return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::onMasterVolumeChanged(float __unused) {
+    LOG(DEBUG) << __func__ << ": is not supported";
+    return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+}  // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/r_submix/RemoteSubmixUtils.cpp b/audio/aidl/default/r_submix/RemoteSubmixUtils.cpp
new file mode 100644
index 0000000..2f5d17d
--- /dev/null
+++ b/audio/aidl/default/r_submix/RemoteSubmixUtils.cpp
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+#include <vector>
+
+#include "RemoteSubmixUtils.h"
+
+namespace aidl::android::hardware::audio::core::r_submix {
+
+bool isChannelMaskSupported(const AudioChannelLayout& channelMask) {
+    const static std::vector<AudioChannelLayout> kSupportedChannelMask = {
+            AudioChannelLayout::make<AudioChannelLayout::Tag::layoutMask>(
+                    AudioChannelLayout::LAYOUT_MONO),
+            AudioChannelLayout::make<AudioChannelLayout::Tag::layoutMask>(
+                    AudioChannelLayout::LAYOUT_STEREO)};
+
+    if (std::find(kSupportedChannelMask.begin(), kSupportedChannelMask.end(), channelMask) !=
+        kSupportedChannelMask.end()) {
+        return true;
+    }
+    return false;
+}
+
+bool isSampleRateSupported(int sampleRate) {
+    const static std::vector<int> kSupportedSampleRates = {8000,  11025, 12000, 16000, 22050,
+                                                           24000, 32000, 44100, 48000};
+
+    if (std::find(kSupportedSampleRates.begin(), kSupportedSampleRates.end(), sampleRate) !=
+        kSupportedSampleRates.end()) {
+        return true;
+    }
+    return false;
+}
+
+}  // namespace aidl::android::hardware::audio::core::r_submix
diff --git a/audio/aidl/default/r_submix/RemoteSubmixUtils.h b/audio/aidl/default/r_submix/RemoteSubmixUtils.h
new file mode 100644
index 0000000..952a992
--- /dev/null
+++ b/audio/aidl/default/r_submix/RemoteSubmixUtils.h
@@ -0,0 +1,30 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <aidl/android/media/audio/common/AudioChannelLayout.h>
+#include <aidl/android/media/audio/common/AudioFormatDescription.h>
+
+using aidl::android::media::audio::common::AudioChannelLayout;
+
+namespace aidl::android::hardware::audio::core::r_submix {
+
+bool isChannelMaskSupported(const AudioChannelLayout& channelMask);
+
+bool isSampleRateSupported(int sampleRate);
+
+}  // namespace aidl::android::hardware::audio::core::r_submix
diff --git a/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp b/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp
new file mode 100644
index 0000000..5af0d91
--- /dev/null
+++ b/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp
@@ -0,0 +1,352 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "AHAL_StreamRemoteSubmix"
+#include <android-base/logging.h>
+
+#include <cmath>
+
+#include "core-impl/StreamRemoteSubmix.h"
+
+using aidl::android::hardware::audio::common::SinkMetadata;
+using aidl::android::hardware::audio::common::SourceMetadata;
+using aidl::android::media::audio::common::AudioOffloadInfo;
+using aidl::android::media::audio::common::MicrophoneDynamicInfo;
+using aidl::android::media::audio::common::MicrophoneInfo;
+
+namespace aidl::android::hardware::audio::core {
+
+StreamRemoteSubmix::StreamRemoteSubmix(const Metadata& metadata, StreamContext&& context)
+    : StreamCommonImpl(metadata, std::move(context)),
+      mPortId(context.getPortId()),
+      mIsInput(isInput(metadata)) {
+    mStreamConfig.frameSize = context.getFrameSize();
+    mStreamConfig.format = context.getFormat();
+    mStreamConfig.channelLayout = context.getChannelLayout();
+    mStreamConfig.sampleRate = context.getSampleRate();
+}
+
+std::mutex StreamRemoteSubmix::sSubmixRoutesLock;
+std::map<int32_t, std::shared_ptr<SubmixRoute>> StreamRemoteSubmix::sSubmixRoutes;
+
+::android::status_t StreamRemoteSubmix::init() {
+    {
+        std::lock_guard guard(sSubmixRoutesLock);
+        if (sSubmixRoutes.find(mPortId) != sSubmixRoutes.end()) {
+            mCurrentRoute = sSubmixRoutes[mPortId];
+        }
+    }
+    // If route is not available for this port, add it.
+    if (mCurrentRoute == nullptr) {
+        // Initialize the pipe.
+        mCurrentRoute = std::make_shared<SubmixRoute>();
+        if (::android::OK != mCurrentRoute->createPipe(mStreamConfig)) {
+            LOG(ERROR) << __func__ << ": create pipe failed";
+            return ::android::NO_INIT;
+        }
+        {
+            std::lock_guard guard(sSubmixRoutesLock);
+            sSubmixRoutes.emplace(mPortId, mCurrentRoute);
+        }
+    } else {
+        if (!mCurrentRoute->isStreamConfigValid(mIsInput, mStreamConfig)) {
+            LOG(ERROR) << __func__ << ": invalid stream config";
+            return ::android::NO_INIT;
+        }
+        sp<MonoPipe> sink = mCurrentRoute->getSink();
+        if (sink == nullptr) {
+            LOG(ERROR) << __func__ << ": nullptr sink when opening stream";
+            return ::android::NO_INIT;
+        }
+        // If the sink has been shutdown or pipe recreation is forced, delete the pipe and
+        // recreate it.
+        if (sink->isShutdown()) {
+            LOG(DEBUG) << __func__ << ": Non-nullptr shut down sink when opening stream";
+            if (::android::OK != mCurrentRoute->resetPipe()) {
+                LOG(ERROR) << __func__ << ": reset pipe failed";
+                return ::android::NO_INIT;
+            }
+        }
+    }
+
+    mCurrentRoute->openStream(mIsInput);
+    return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::drain(StreamDescriptor::DrainMode) {
+    usleep(1000);
+    return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::flush() {
+    usleep(1000);
+    return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::pause() {
+    usleep(1000);
+    return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::standby() {
+    mCurrentRoute->standby(mIsInput);
+    return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::start() {
+    mCurrentRoute->exitStandby(mIsInput);
+    return ::android::OK;
+}
+
+ndk::ScopedAStatus StreamRemoteSubmix::prepareToClose() {
+    if (!mIsInput) {
+        std::shared_ptr<SubmixRoute> route = nullptr;
+        {
+            std::lock_guard guard(sSubmixRoutesLock);
+            if (sSubmixRoutes.find(mPortId) != sSubmixRoutes.end()) {
+                route = sSubmixRoutes[mPortId];
+            }
+        }
+        if (route != nullptr) {
+            sp<MonoPipe> sink = route->getSink();
+            if (sink == nullptr) {
+                ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+            }
+            LOG(DEBUG) << __func__ << ": shutting down MonoPipe sink";
+
+            sink->shutdown(true);
+        } else {
+            LOG(DEBUG) << __func__ << ": stream already closed.";
+            ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+        }
+    }
+    return ndk::ScopedAStatus::ok();
+}
+
+// Remove references to the specified input and output streams.  When the device no longer
+// references input and output streams destroy the associated pipe.
+void StreamRemoteSubmix::shutdown() {
+    mCurrentRoute->closeStream(mIsInput);
+    // If all stream instances are closed, we can remove route information for this port.
+    if (!mCurrentRoute->hasAtleastOneStreamOpen()) {
+        mCurrentRoute->releasePipe();
+        LOG(DEBUG) << __func__ << ": pipe destroyed";
+
+        std::lock_guard guard(sSubmixRoutesLock);
+        sSubmixRoutes.erase(mPortId);
+    }
+    mCurrentRoute.reset();
+}
+
+::android::status_t StreamRemoteSubmix::transfer(void* buffer, size_t frameCount,
+                                                 size_t* actualFrameCount, int32_t* latencyMs) {
+    *latencyMs = (getStreamPipeSizeInFrames() * MILLIS_PER_SECOND) / mStreamConfig.sampleRate;
+    LOG(VERBOSE) << __func__ << ": Latency " << *latencyMs << "ms";
+
+    sp<MonoPipe> sink = mCurrentRoute->getSink();
+    if (sink != nullptr) {
+        if (sink->isShutdown()) {
+            sink.clear();
+            LOG(VERBOSE) << __func__ << ": pipe shutdown, ignoring the transfer.";
+            // the pipe has already been shutdown, this buffer will be lost but we must simulate
+            // timing so we don't drain the output faster than realtime
+            const size_t delayUs = static_cast<size_t>(
+                    std::roundf(frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate));
+            usleep(delayUs);
+
+            *actualFrameCount = frameCount;
+            return ::android::OK;
+        }
+    } else {
+        LOG(ERROR) << __func__ << ": transfer without a pipe!";
+        return ::android::UNEXPECTED_NULL;
+    }
+
+    return (mIsInput ? inRead(buffer, frameCount, actualFrameCount)
+                     : outWrite(buffer, frameCount, actualFrameCount));
+}
+
+// Calculate the maximum size of the pipe buffer in frames for the specified stream.
+size_t StreamRemoteSubmix::getStreamPipeSizeInFrames() {
+    auto pipeConfig = mCurrentRoute->mPipeConfig;
+    const size_t maxFrameSize = std::max(mStreamConfig.frameSize, pipeConfig.frameSize);
+    return (pipeConfig.frameCount * pipeConfig.frameSize) / maxFrameSize;
+}
+
+::android::status_t StreamRemoteSubmix::outWrite(void* buffer, size_t frameCount,
+                                                 size_t* actualFrameCount) {
+    sp<MonoPipe> sink = mCurrentRoute->getSink();
+    if (sink != nullptr) {
+        if (sink->isShutdown()) {
+            sink.clear();
+            LOG(VERBOSE) << __func__ << ": pipe shutdown, ignoring the write.";
+            // the pipe has already been shutdown, this buffer will be lost but we must
+            // simulate timing so we don't drain the output faster than realtime
+            const size_t delayUs = static_cast<size_t>(
+                    std::roundf(frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate));
+            usleep(delayUs);
+            *actualFrameCount = frameCount;
+            return ::android::OK;
+        }
+    } else {
+        LOG(FATAL) << __func__ << ": without a pipe!";
+        return ::android::UNKNOWN_ERROR;
+    }
+
+    const size_t availableToWrite = sink->availableToWrite();
+    // NOTE: sink has been checked above and sink and source life cycles are synchronized
+    sp<MonoPipeReader> source = mCurrentRoute->getSource();
+    // If the write to the sink should be blocked, flush enough frames from the pipe to make space
+    // to write the most recent data.
+    if (!mCurrentRoute->shouldBlockWrite() && availableToWrite < frameCount) {
+        static uint8_t flushBuffer[64];
+        const size_t flushBufferSizeFrames = sizeof(flushBuffer) / mStreamConfig.frameSize;
+        size_t framesToFlushFromSource = frameCount - availableToWrite;
+        LOG(VERBOSE) << __func__ << ": flushing " << framesToFlushFromSource
+                     << " frames from the pipe to avoid blocking";
+        while (framesToFlushFromSource) {
+            const size_t flushSize = std::min(framesToFlushFromSource, flushBufferSizeFrames);
+            framesToFlushFromSource -= flushSize;
+            // read does not block
+            source->read(flushBuffer, flushSize);
+        }
+    }
+
+    ssize_t writtenFrames = sink->write(buffer, frameCount);
+    if (writtenFrames < 0) {
+        if (writtenFrames == (ssize_t)::android::NEGOTIATE) {
+            LOG(ERROR) << __func__ << ": write to pipe returned NEGOTIATE";
+            sink.clear();
+            *actualFrameCount = 0;
+            return ::android::UNKNOWN_ERROR;
+        } else {
+            // write() returned UNDERRUN or WOULD_BLOCK, retry
+            LOG(ERROR) << __func__ << ": write to pipe returned unexpected " << writtenFrames;
+            writtenFrames = sink->write(buffer, frameCount);
+        }
+    }
+    sink.clear();
+
+    if (writtenFrames < 0) {
+        LOG(ERROR) << __func__ << ": failed writing to pipe with " << writtenFrames;
+        *actualFrameCount = 0;
+        return ::android::UNKNOWN_ERROR;
+    }
+    LOG(VERBOSE) << __func__ << ": wrote " << writtenFrames << "frames";
+    *actualFrameCount = writtenFrames;
+    return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::inRead(void* buffer, size_t frameCount,
+                                               size_t* actualFrameCount) {
+    // about to read from audio source
+    sp<MonoPipeReader> source = mCurrentRoute->getSource();
+    if (source == nullptr) {
+        int readErrorCount = mCurrentRoute->notifyReadError();
+        if (readErrorCount < kMaxReadErrorLogs) {
+            LOG(ERROR)
+                    << __func__
+                    << ": no audio pipe yet we're trying to read! (not all errors will be logged)";
+        } else {
+            LOG(ERROR) << __func__ << ": Read errors " << readErrorCount;
+        }
+        const size_t delayUs = static_cast<size_t>(
+                std::roundf(frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate));
+        usleep(delayUs);
+        memset(buffer, 0, mStreamConfig.frameSize * frameCount);
+        *actualFrameCount = frameCount;
+        return ::android::OK;
+    }
+
+    // read the data from the pipe
+    int attempts = 0;
+    const size_t delayUs = static_cast<size_t>(std::roundf(kReadAttemptSleepUs));
+    char* buff = (char*)buffer;
+    size_t remainingFrames = frameCount;
+
+    while ((remainingFrames > 0) && (attempts < kMaxReadFailureAttempts)) {
+        LOG(VERBOSE) << __func__ << ": frames available to read " << source->availableToRead();
+
+        ssize_t framesRead = source->read(buff, remainingFrames);
+
+        LOG(VERBOSE) << __func__ << ": frames read " << framesRead;
+
+        if (framesRead > 0) {
+            remainingFrames -= framesRead;
+            buff += framesRead * mStreamConfig.frameSize;
+            LOG(VERBOSE) << __func__ << ": (attempts = " << attempts << ") got " << framesRead
+                         << " frames, remaining=" << remainingFrames;
+        } else {
+            attempts++;
+            LOG(WARNING) << __func__ << ": read returned " << framesRead
+                         << " , read failure attempts = " << attempts;
+            usleep(delayUs);
+        }
+    }
+    // done using the source
+    source.clear();
+
+    if (remainingFrames > 0) {
+        const size_t remainingBytes = remainingFrames * mStreamConfig.frameSize;
+        LOG(VERBOSE) << __func__ << ": clearing remaining_frames = " << remainingFrames;
+        memset(((char*)buffer) + (mStreamConfig.frameSize * frameCount) - remainingBytes, 0,
+               remainingBytes);
+    }
+
+    long readCounterFrames = mCurrentRoute->updateReadCounterFrames(frameCount);
+    *actualFrameCount = frameCount;
+
+    // compute how much we need to sleep after reading the data by comparing the wall clock with
+    //   the projected time at which we should return.
+    // wall clock after reading from the pipe
+    auto recordDurationUs = std::chrono::steady_clock::now() - mCurrentRoute->getRecordStartTime();
+
+    // readCounterFrames contains the number of frames that have been read since the beginning of
+    // recording (including this call): it's converted to usec and compared to how long we've been
+    // recording for, which gives us how long we must wait to sync the projected recording time, and
+    // the observed recording time.
+    static constexpr float kScaleFactor = .8f;
+    const size_t projectedVsObservedOffsetUs =
+            kScaleFactor * (static_cast<size_t>(std::roundf((readCounterFrames * MICROS_PER_SECOND /
+                                                             mStreamConfig.sampleRate) -
+                                                            recordDurationUs.count())));
+
+    LOG(VERBOSE) << __func__ << ": record duration " << recordDurationUs.count()
+                 << " microseconds, will wait: " << projectedVsObservedOffsetUs << " microseconds";
+    if (projectedVsObservedOffsetUs > 0) {
+        usleep(projectedVsObservedOffsetUs);
+    }
+    return ::android::OK;
+}
+
+StreamInRemoteSubmix::StreamInRemoteSubmix(const SinkMetadata& sinkMetadata,
+                                           StreamContext&& context,
+                                           const std::vector<MicrophoneInfo>& microphones)
+    : StreamRemoteSubmix(sinkMetadata, std::move(context)), StreamIn(microphones) {}
+
+ndk::ScopedAStatus StreamInRemoteSubmix::getActiveMicrophones(
+        std::vector<MicrophoneDynamicInfo>* _aidl_return) {
+    LOG(DEBUG) << __func__ << ": not supported";
+    *_aidl_return = std::vector<MicrophoneDynamicInfo>();
+    return ndk::ScopedAStatus::ok();
+}
+
+StreamOutRemoteSubmix::StreamOutRemoteSubmix(const SourceMetadata& sourceMetadata,
+                                             StreamContext&& context,
+                                             const std::optional<AudioOffloadInfo>& offloadInfo)
+    : StreamRemoteSubmix(sourceMetadata, std::move(context)), StreamOut(offloadInfo) {}
+
+}  // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/r_submix/SubmixRoute.cpp b/audio/aidl/default/r_submix/SubmixRoute.cpp
new file mode 100644
index 0000000..8f5b8cb
--- /dev/null
+++ b/audio/aidl/default/r_submix/SubmixRoute.cpp
@@ -0,0 +1,230 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "AHAL_SubmixRoute"
+#include <android-base/logging.h>
+#include <media/AidlConversionCppNdk.h>
+
+#include <Utils.h>
+
+#include "SubmixRoute.h"
+
+using aidl::android::hardware::audio::common::getChannelCount;
+
+namespace aidl::android::hardware::audio::core::r_submix {
+
+// 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.
+    // ENABLE_LEGACY_INPUT_OPEN is default behaviour
+    if (!isInput && isStreamOutOpen()) {
+        LOG(ERROR) << __func__ << ": output stream already open.";
+        return false;
+    }
+    // If either stream is open, verify the existing pipe config matches the stream config.
+    if (hasAtleastOneStreamOpen() && !isStreamConfigCompatible(streamConfig)) {
+        return false;
+    }
+    return true;
+}
+
+// Compare this stream config with existing pipe config, returning false if they do *not*
+// match, true otherwise.
+bool SubmixRoute::isStreamConfigCompatible(const AudioConfig streamConfig) {
+    if (streamConfig.channelLayout != mPipeConfig.channelLayout) {
+        LOG(ERROR) << __func__ << ": channel count mismatch, stream channels = "
+                   << streamConfig.channelLayout.toString()
+                   << " pipe config channels = " << mPipeConfig.channelLayout.toString();
+        return false;
+    }
+    if (streamConfig.sampleRate != mPipeConfig.sampleRate) {
+        LOG(ERROR) << __func__
+                   << ": sample rate mismatch, stream sample rate = " << streamConfig.sampleRate
+                   << " pipe config sample rate = " << mPipeConfig.sampleRate;
+        return false;
+    }
+    if (streamConfig.format != mPipeConfig.format) {
+        LOG(ERROR) << __func__
+                   << ": format mismatch, stream format = " << streamConfig.format.toString()
+                   << " pipe config format = " << mPipeConfig.format.toString();
+        return false;
+    }
+    return true;
+}
+
+bool SubmixRoute::hasAtleastOneStreamOpen() {
+    std::lock_guard guard(mLock);
+    return (mStreamInOpen || mStreamOutOpen);
+}
+
+// We DO NOT block if:
+// - no peer input stream is present
+// - the peer input is in standby AFTER having been active.
+// We DO block if:
+// - the input was never activated to avoid discarding first frames in the pipe in case capture
+// start was delayed
+bool SubmixRoute::shouldBlockWrite() {
+    std::lock_guard guard(mLock);
+    return (mStreamInOpen || (mStreamInStandby && (mReadCounterFrames != 0)));
+}
+
+int SubmixRoute::notifyReadError() {
+    std::lock_guard guard(mLock);
+    return ++mReadErrorCount;
+}
+
+long SubmixRoute::updateReadCounterFrames(size_t frameCount) {
+    std::lock_guard guard(mLock);
+    mReadCounterFrames += frameCount;
+    return mReadCounterFrames;
+}
+
+void SubmixRoute::openStream(bool isInput) {
+    std::lock_guard guard(mLock);
+    if (isInput) {
+        if (mStreamInOpen) {
+            mInputRefCount++;
+        } else {
+            mInputRefCount = 1;
+            mStreamInOpen = true;
+        }
+        mStreamInStandby = true;
+        mReadCounterFrames = 0;
+        mReadErrorCount = 0;
+    } else {
+        mStreamOutOpen = true;
+    }
+}
+
+void SubmixRoute::closeStream(bool isInput) {
+    std::lock_guard guard(mLock);
+    if (isInput) {
+        mInputRefCount--;
+        if (mInputRefCount == 0) {
+            mStreamInOpen = false;
+            if (mSink != nullptr) {
+                mSink->shutdown(true);
+            }
+        }
+    } else {
+        mStreamOutOpen = false;
+    }
+}
+
+// If SubmixRoute doesn't exist for a port, create a pipe for the submix audio device of size
+// buffer_size_frames and store config of the submix audio device.
+::android::status_t SubmixRoute::createPipe(const AudioConfig streamConfig) {
+    const int channelCount = getChannelCount(streamConfig.channelLayout);
+    const audio_format_t audioFormat = VALUE_OR_RETURN_STATUS(
+            aidl2legacy_AudioFormatDescription_audio_format_t(streamConfig.format));
+    const ::android::NBAIO_Format format =
+            ::android::Format_from_SR_C(streamConfig.sampleRate, channelCount, audioFormat);
+    const ::android::NBAIO_Format offers[1] = {format};
+    size_t numCounterOffers = 0;
+
+    const size_t pipeSizeInFrames =
+            r_submix::kDefaultPipeSizeInFrames *
+            ((float)streamConfig.sampleRate / r_submix::kDefaultSampleRateHz);
+    LOG(VERBOSE) << __func__ << ": creating pipe, rate : " << streamConfig.sampleRate
+                 << ", pipe size : " << pipeSizeInFrames;
+
+    // Create a MonoPipe with optional blocking set to true.
+    sp<MonoPipe> sink = sp<MonoPipe>::make(pipeSizeInFrames, format, true /*writeCanBlock*/);
+    if (sink == nullptr) {
+        LOG(FATAL) << __func__ << ": sink is null";
+        return ::android::UNEXPECTED_NULL;
+    }
+
+    // Negotiation between the source and sink cannot fail as the device open operation
+    // creates both ends of the pipe using the same audio format.
+    ssize_t index = sink->negotiate(offers, 1, nullptr, numCounterOffers);
+    if (index != 0) {
+        LOG(FATAL) << __func__ << ": Negotiation for the sink failed, index = " << index;
+        return ::android::BAD_INDEX;
+    }
+    sp<MonoPipeReader> source = sp<MonoPipeReader>::make(sink.get());
+    if (source == nullptr) {
+        LOG(FATAL) << __func__ << ": source is null";
+        return ::android::UNEXPECTED_NULL;
+    }
+    numCounterOffers = 0;
+    index = source->negotiate(offers, 1, nullptr, numCounterOffers);
+    if (index != 0) {
+        LOG(FATAL) << __func__ << ": Negotiation for the source failed, index = " << index;
+        return ::android::BAD_INDEX;
+    }
+    LOG(VERBOSE) << __func__ << ": created pipe";
+
+    mPipeConfig = streamConfig;
+    mPipeConfig.frameCount = sink->maxFrames();
+
+    LOG(VERBOSE) << __func__ << ": Pipe frame size : " << mPipeConfig.frameSize
+                 << ", pipe frames : " << mPipeConfig.frameCount;
+
+    // Save references to the source and sink.
+    {
+        std::lock_guard guard(mLock);
+        mSink = std::move(sink);
+        mSource = std::move(source);
+    }
+
+    return ::android::OK;
+}
+
+// Release references to the sink and source.
+void SubmixRoute::releasePipe() {
+    std::lock_guard guard(mLock);
+    mSink.clear();
+    mSource.clear();
+}
+
+::android::status_t SubmixRoute::resetPipe() {
+    releasePipe();
+    return createPipe(mPipeConfig);
+}
+
+void SubmixRoute::standby(bool isInput) {
+    std::lock_guard guard(mLock);
+
+    if (isInput) {
+        mStreamInStandby = true;
+    } else {
+        mStreamOutStandby = true;
+        mStreamOutStandbyTransition = !mStreamOutStandbyTransition;
+    }
+}
+
+void SubmixRoute::exitStandby(bool isInput) {
+    std::lock_guard guard(mLock);
+
+    if (isInput) {
+        if (mStreamInStandby || mStreamOutStandbyTransition) {
+            mStreamInStandby = false;
+            mStreamOutStandbyTransition = false;
+            // keep track of when we exit input standby (== first read == start "real recording")
+            // or when we start recording silence, and reset projected time
+            mRecordStartTime = std::chrono::steady_clock::now();
+            mReadCounterFrames = 0;
+        }
+    } else {
+        if (mStreamOutStandby) {
+            mStreamOutStandby = false;
+            mStreamOutStandbyTransition = true;
+        }
+    }
+}
+
+}  // 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
new file mode 100644
index 0000000..5f7ea75
--- /dev/null
+++ b/audio/aidl/default/r_submix/SubmixRoute.h
@@ -0,0 +1,138 @@
+/*
+ * 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.
+ */
+
+#include <mutex>
+
+#include <audio_utils/clock.h>
+
+#include <media/nbaio/MonoPipe.h>
+#include <media/nbaio/MonoPipeReader.h>
+
+#include <aidl/android/media/audio/common/AudioChannelLayout.h>
+
+#include "core-impl/Stream.h"
+
+using aidl::android::media::audio::common::AudioChannelLayout;
+using aidl::android::media::audio::common::AudioFormatDescription;
+using aidl::android::media::audio::common::AudioFormatType;
+using aidl::android::media::audio::common::PcmType;
+using ::android::MonoPipe;
+using ::android::MonoPipeReader;
+using ::android::sp;
+
+namespace aidl::android::hardware::audio::core::r_submix {
+
+static constexpr int kDefaultSampleRateHz = 48000;
+// Size at default sample rate
+// NOTE: This value will be rounded up to the nearest power of 2 by MonoPipe().
+static constexpr int kDefaultPipeSizeInFrames = (1024 * 4);
+
+// Configuration of the audio stream.
+struct AudioConfig {
+    int sampleRate = kDefaultSampleRateHz;
+    AudioFormatDescription format =
+            AudioFormatDescription{.type = AudioFormatType::PCM, .pcm = PcmType::INT_16_BIT};
+    AudioChannelLayout channelLayout =
+            AudioChannelLayout::make<AudioChannelLayout::Tag::layoutMask>(
+                    AudioChannelLayout::LAYOUT_STEREO);
+    size_t frameSize;
+    size_t frameCount;
+};
+
+class SubmixRoute {
+  public:
+    AudioConfig mPipeConfig;
+
+    bool isStreamInOpen() {
+        std::lock_guard guard(mLock);
+        return mStreamInOpen;
+    }
+    bool getStreamInStandby() {
+        std::lock_guard guard(mLock);
+        return mStreamInStandby;
+    }
+    bool isStreamOutOpen() {
+        std::lock_guard guard(mLock);
+        return mStreamOutOpen;
+    }
+    bool getStreamOutStandby() {
+        std::lock_guard guard(mLock);
+        return mStreamOutStandby;
+    }
+    long getReadCounterFrames() {
+        std::lock_guard guard(mLock);
+        return mReadCounterFrames;
+    }
+    int getReadErrorCount() {
+        std::lock_guard guard(mLock);
+        return mReadErrorCount;
+    }
+    std::chrono::time_point<std::chrono::steady_clock> getRecordStartTime() {
+        std::lock_guard guard(mLock);
+        return mRecordStartTime;
+    }
+    sp<MonoPipe> getSink() {
+        std::lock_guard guard(mLock);
+        return mSink;
+    }
+    sp<MonoPipeReader> getSource() {
+        std::lock_guard guard(mLock);
+        return mSource;
+    }
+
+    bool isStreamConfigValid(bool isInput, const AudioConfig streamConfig);
+    void closeStream(bool isInput);
+    ::android::status_t createPipe(const AudioConfig streamConfig);
+    void exitStandby(bool isInput);
+    bool hasAtleastOneStreamOpen();
+    int notifyReadError();
+    void openStream(bool isInput);
+    void releasePipe();
+    ::android::status_t resetPipe();
+    bool shouldBlockWrite();
+    void standby(bool isInput);
+    long updateReadCounterFrames(size_t frameCount);
+
+  private:
+    bool isStreamConfigCompatible(const AudioConfig streamConfig);
+
+    std::mutex mLock;
+
+    bool mStreamInOpen GUARDED_BY(mLock) = false;
+    int mInputRefCount GUARDED_BY(mLock) = 0;
+    bool mStreamInStandby GUARDED_BY(mLock) = true;
+    bool mStreamOutStandbyTransition GUARDED_BY(mLock) = false;
+    bool mStreamOutOpen GUARDED_BY(mLock) = false;
+    bool mStreamOutStandby GUARDED_BY(mLock) = true;
+    // how many frames have been requested to be read since standby
+    long mReadCounterFrames GUARDED_BY(mLock) = 0;
+    int mReadErrorCount GUARDED_BY(mLock) = 0;
+    // wall clock when recording starts
+    std::chrono::time_point<std::chrono::steady_clock> mRecordStartTime GUARDED_BY(mLock);
+
+    // Pipe variables: they handle the ring buffer that "pipes" audio:
+    //  - from the submix virtual audio output == what needs to be played
+    //    remotely, seen as an output for the client
+    //  - to the virtual audio source == what is captured by the component
+    //    which "records" the submix / virtual audio source, and handles it as needed.
+    // A usecase example is one where the component capturing the audio is then sending it over
+    // Wifi for presentation on a remote Wifi Display device (e.g. a dongle attached to a TV, or a
+    // TV with Wifi Display capabilities), or to a wireless audio player.
+    sp<MonoPipe> mSink GUARDED_BY(mLock);
+    sp<MonoPipeReader> mSource GUARDED_BY(mLock);
+};
+
+}  // namespace aidl::android::hardware::audio::core::r_submix
diff --git a/audio/aidl/default/usb/StreamUsb.cpp b/audio/aidl/default/usb/StreamUsb.cpp
index 49bc1d6..17e1ab4 100644
--- a/audio/aidl/default/usb/StreamUsb.cpp
+++ b/audio/aidl/default/usb/StreamUsb.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <limits>
+
 #define LOG_TAG "AHAL_StreamUsb"
 #include <android-base/logging.h>
 
@@ -45,25 +47,30 @@
 
 StreamUsb::StreamUsb(const Metadata& metadata, StreamContext&& context)
     : StreamCommonImpl(metadata, std::move(context)),
-      mFrameSizeBytes(context.getFrameSize()),
-      mIsInput(isInput(metadata)) {
+      mFrameSizeBytes(getContext().getFrameSize()),
+      mIsInput(isInput(metadata)),
+      mConfig(maybePopulateConfig(getContext(), mIsInput)) {}
+
+// static
+std::optional<struct pcm_config> StreamUsb::maybePopulateConfig(const StreamContext& context,
+                                                                bool isInput) {
     struct pcm_config config;
-    config.channels = usb::getChannelCountFromChannelMask(context.getChannelLayout(), mIsInput);
+    config.channels = usb::getChannelCountFromChannelMask(context.getChannelLayout(), isInput);
     if (config.channels == 0) {
         LOG(ERROR) << __func__ << ": invalid channel=" << context.getChannelLayout().toString();
-        return;
+        return std::nullopt;
     }
     config.format = usb::aidl2legacy_AudioFormatDescription_pcm_format(context.getFormat());
     if (config.format == PCM_FORMAT_INVALID) {
         LOG(ERROR) << __func__ << ": invalid format=" << context.getFormat().toString();
-        return;
+        return std::nullopt;
     }
     config.rate = context.getSampleRate();
     if (config.rate == 0) {
         LOG(ERROR) << __func__ << ": invalid sample rate=" << config.rate;
-        return;
+        return std::nullopt;
     }
-    mConfig = config;
+    return config;
 }
 
 ::android::status_t StreamUsb::init() {
@@ -89,8 +96,8 @@
         }
     }
     std::lock_guard guard(mLock);
-    mAlsaDeviceProxies.clear();
     RETURN_STATUS_IF_ERROR(StreamCommonImpl::setConnectedDevices(connectedDevices));
+    mConnectedDevicesUpdated.store(true, std::memory_order_release);
     return ndk::ScopedAStatus::ok();
 }
 
@@ -111,59 +118,53 @@
 
 ::android::status_t StreamUsb::transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
                                         int32_t* latencyMs) {
-    {
-        std::lock_guard guard(mLock);
-        if (!mConfig.has_value() || mConnectedDevices.empty()) {
-            LOG(ERROR) << __func__ << ": failed, has config: " << mConfig.has_value()
-                       << ", has connected devices: " << mConnectedDevices.empty();
-            return ::android::NO_INIT;
-        }
-    }
-    if (mIsStandby) {
-        if (::android::status_t status = exitStandby(); status != ::android::OK) {
-            LOG(ERROR) << __func__ << ": failed to exit standby, status=" << status;
-            return status;
-        }
-    }
-    std::vector<std::shared_ptr<alsa_device_proxy>> alsaDeviceProxies;
-    {
-        std::lock_guard guard(mLock);
-        alsaDeviceProxies = mAlsaDeviceProxies;
+    if (mConnectedDevicesUpdated.load(std::memory_order_acquire)) {
+        // 'setConnectedDevices' has been called. I/O will be restarted.
+        *actualFrameCount = 0;
+        *latencyMs = StreamDescriptor::LATENCY_UNKNOWN;
+        return ::android::OK;
     }
     const size_t bytesToTransfer = frameCount * mFrameSizeBytes;
+    unsigned maxLatency = 0;
     if (mIsInput) {
+        if (mAlsaDeviceProxies.empty()) {
+            LOG(FATAL) << __func__ << ": no input devices";
+            return ::android::NO_INIT;
+        }
         // For input case, only support single device.
-        proxy_read(alsaDeviceProxies[0].get(), buffer, bytesToTransfer);
+        proxy_read(mAlsaDeviceProxies[0].get(), buffer, bytesToTransfer);
+        maxLatency = proxy_get_latency(mAlsaDeviceProxies[0].get());
     } else {
-        for (auto& proxy : alsaDeviceProxies) {
+        for (auto& proxy : mAlsaDeviceProxies) {
             proxy_write(proxy.get(), buffer, bytesToTransfer);
+            maxLatency = std::max(maxLatency, proxy_get_latency(proxy.get()));
         }
     }
     *actualFrameCount = frameCount;
-    *latencyMs = Module::kLatencyMs;
+    maxLatency = std::min(maxLatency, static_cast<unsigned>(std::numeric_limits<int32_t>::max()));
+    *latencyMs = maxLatency;
     return ::android::OK;
 }
 
 ::android::status_t StreamUsb::standby() {
-    if (!mIsStandby) {
-        std::lock_guard guard(mLock);
-        mAlsaDeviceProxies.clear();
-        mIsStandby = true;
-    }
+    mAlsaDeviceProxies.clear();
     return ::android::OK;
 }
 
-void StreamUsb::shutdown() {}
+void StreamUsb::shutdown() {
+    mAlsaDeviceProxies.clear();
+}
 
-::android::status_t StreamUsb::exitStandby() {
+::android::status_t StreamUsb::start() {
     std::vector<AudioDeviceAddress> connectedDevices;
     {
         std::lock_guard guard(mLock);
         std::transform(mConnectedDevices.begin(), mConnectedDevices.end(),
                        std::back_inserter(connectedDevices),
                        [](const auto& device) { return device.address; });
+        mConnectedDevicesUpdated.store(false, std::memory_order_release);
     }
-    std::vector<std::shared_ptr<alsa_device_proxy>> alsaDeviceProxies;
+    decltype(mAlsaDeviceProxies) alsaDeviceProxies;
     for (const auto& device : connectedDevices) {
         alsa_device_profile profile;
         profile_init(&profile, mIsInput ? PCM_IN : PCM_OUT);
@@ -175,16 +176,16 @@
             return ::android::UNKNOWN_ERROR;
         }
 
-        auto proxy = std::shared_ptr<alsa_device_proxy>(new alsa_device_proxy(),
-                                                        [](alsa_device_proxy* proxy) {
-                                                            proxy_close(proxy);
-                                                            free(proxy);
-                                                        });
+        AlsaDeviceProxy proxy(new alsa_device_proxy, [](alsa_device_proxy* proxy) {
+            proxy_close(proxy);
+            free(proxy);
+        });
         // Always ask for alsa configure as required since the configuration should be supported
         // by the connected device. That is guaranteed by `setAudioPortConfig` and
         // `setAudioPatch`.
-        if (int err =
-                    proxy_prepare(proxy.get(), &profile, &mConfig.value(), true /*is_bit_perfect*/);
+        if (int err = proxy_prepare(proxy.get(), &profile,
+                                    const_cast<struct pcm_config*>(&mConfig.value()),
+                                    true /*is_bit_perfect*/);
             err != 0) {
             LOG(ERROR) << __func__ << ": fail to prepare for device address=" << device.toString()
                        << " error=" << err;
@@ -197,11 +198,7 @@
         }
         alsaDeviceProxies.push_back(std::move(proxy));
     }
-    {
-        std::lock_guard guard(mLock);
-        mAlsaDeviceProxies = alsaDeviceProxies;
-    }
-    mIsStandby = false;
+    mAlsaDeviceProxies = std::move(alsaDeviceProxies);
     return ::android::OK;
 }
 
diff --git a/audio/aidl/vts/TestUtils.h b/audio/aidl/vts/TestUtils.h
index 72ca56f..10c2fc6 100644
--- a/audio/aidl/vts/TestUtils.h
+++ b/audio/aidl/vts/TestUtils.h
@@ -77,3 +77,10 @@
 #define EXPECT_STATUS(expected, ret)                                                       \
     EXPECT_PRED_FORMAT2(::android::hardware::audio::common::testing::detail::assertResult, \
                         expected, ret)
+
+#define SKIP_TEST_IF_DATA_UNSUPPORTED(flags)                                                  \
+    ({                                                                                        \
+        if ((flags).hwAcceleratorMode == Flags::HardwareAccelerator::TUNNEL || (flags).bypass) {  \
+            GTEST_SKIP() << "Skip data path for offload";                                     \
+        }                                                                                     \
+    })
\ No newline at end of file
diff --git a/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp b/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
index 4ad9b2d..3011a5e 100644
--- a/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
@@ -46,6 +46,7 @@
 using aidl::android::hardware::audio::effect::IFactory;
 using aidl::android::hardware::audio::effect::Parameter;
 using aidl::android::hardware::audio::effect::State;
+using aidl::android::hardware::audio::effect::Flags;
 using aidl::android::media::audio::common::AudioDeviceDescription;
 using aidl::android::media::audio::common::AudioDeviceType;
 using aidl::android::media::audio::common::AudioMode;
@@ -85,6 +86,14 @@
     }
 };
 
+class AudioEffectDataPathTest : public AudioEffectTest {
+    public:
+        void SetUp() override {
+            AudioEffectTest::SetUp();
+            SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
+        }
+};
+
 TEST_P(AudioEffectTest, SetupAndTearDown) {
     // Intentionally empty test body.
 }
@@ -577,7 +586,8 @@
 
 /// Data processing test
 // Send data to effects and expect it to be consumed by checking statusMQ.
-TEST_P(AudioEffectTest, ConsumeDataInProcessingState) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ConsumeDataInProcessingState) {
     ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
 
     Parameter::Common common = EffectHelper::createParamCommon(
@@ -610,7 +620,8 @@
 }
 
 // Send data to effects and expect it to be consumed after effect restart.
-TEST_P(AudioEffectTest, ConsumeDataAfterRestart) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ConsumeDataAfterRestart) {
     ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
 
     Parameter::Common common = EffectHelper::createParamCommon(
@@ -649,7 +660,8 @@
 }
 
 // Send data to IDLE effects and expect it to be consumed after effect start.
-TEST_P(AudioEffectTest, SendDataAtIdleAndConsumeDataInProcessing) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, SendDataAtIdleAndConsumeDataInProcessing) {
     ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
 
     Parameter::Common common = EffectHelper::createParamCommon(
@@ -682,7 +694,8 @@
 }
 
 // Send data multiple times.
-TEST_P(AudioEffectTest, ProcessDataMultipleTimes) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ProcessDataMultipleTimes) {
     ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
 
     Parameter::Common common = EffectHelper::createParamCommon(
@@ -721,7 +734,8 @@
 }
 
 // Send data to processing state effects, stop, and restart.
-TEST_P(AudioEffectTest, ConsumeDataAndRestart) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ConsumeDataAndRestart) {
     ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
 
     Parameter::Common common = EffectHelper::createParamCommon(
@@ -762,7 +776,8 @@
 }
 
 // Send data to closed effects and expect it not be consumed.
-TEST_P(AudioEffectTest, NotConsumeDataByClosedEffect) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, NotConsumeDataByClosedEffect) {
     ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
 
     Parameter::Common common = EffectHelper::createParamCommon(
@@ -788,7 +803,8 @@
 }
 
 // Send data to multiple effects.
-TEST_P(AudioEffectTest, ConsumeDataMultipleEffects) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ConsumeDataMultipleEffects) {
     std::shared_ptr<IEffect> effect1, effect2;
     ASSERT_NO_FATAL_FAILURE(create(mFactory, effect1, mDescriptor));
     ASSERT_NO_FATAL_FAILURE(create(mFactory, effect2, mDescriptor));
@@ -855,6 +871,20 @@
         });
 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AudioEffectTest);
 
+INSTANTIATE_TEST_SUITE_P(
+        SingleEffectInstanceTest, AudioEffectDataPathTest,
+        ::testing::Combine(testing::ValuesIn(
+                EffectFactoryHelper::getAllEffectDescriptors(IFactory::descriptor))),
+        [](const testing::TestParamInfo<AudioEffectDataPathTest::ParamType>& info) {
+            auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
+            std::string name = getPrefix(descriptor);
+            std::replace_if(
+                    name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
+            return name;
+        });
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AudioEffectDataPathTest);
+
 int main(int argc, char** argv) {
     ::testing::InitGoogleTest(&argc, argv);
     ABinderProcess_setThreadPoolMaxThreadCount(1);
diff --git a/bluetooth/1.0/default/bluetooth_hci.cc b/bluetooth/1.0/default/bluetooth_hci.cc
index 869c723..a2211f4 100644
--- a/bluetooth/1.0/default/bluetooth_hci.cc
+++ b/bluetooth/1.0/default/bluetooth_hci.cc
@@ -33,8 +33,7 @@
 
 class BluetoothDeathRecipient : public hidl_death_recipient {
  public:
-  BluetoothDeathRecipient(const sp<IBluetoothHci> hci)
-    : mHci(hci), has_died_(false) {}
+  BluetoothDeathRecipient(const sp<IBluetoothHci> hci) : mHci(hci) {}
 
   virtual void serviceDied(
       uint64_t /*cookie*/,
@@ -52,7 +51,7 @@
 };
 
 BluetoothHci::BluetoothHci()
-    : death_recipient_(new BluetoothDeathRecipient(this)) {bt_enabled = 0;}
+    : death_recipient_(new BluetoothDeathRecipient(this)) {}
 
 Return<void> BluetoothHci::initialize(
     const ::android::sp<IBluetoothHciCallbacks>& cb) {
@@ -62,19 +61,8 @@
     return Void();
   }
 
-  if (bt_enabled == 1) {
-    ALOGE("initialize was called!");
-    return Void();
-  }
-  bt_enabled = 1;
   death_recipient_->setHasDied(false);
   cb->linkToDeath(death_recipient_, 0);
-  unlink_cb_ = [cb](sp<BluetoothDeathRecipient>& death_recipient) {
-    if (death_recipient->getHasDied())
-      ALOGI("Skipping unlink call, service died.");
-    else
-      cb->unlinkToDeath(death_recipient);
-  };
 
   bool rc = VendorInterface::Initialize(
       [cb](bool status) {
@@ -124,12 +112,6 @@
 
 Return<void> BluetoothHci::close() {
   ALOGI("BluetoothHci::close()");
-
-  if (bt_enabled != 1) {
-    ALOGE("should initialize first!");
-    return Void();
-  }
-  bt_enabled = 0;
   unlink_cb_(death_recipient_);
   VendorInterface::Shutdown();
   return Void();
@@ -152,11 +134,6 @@
 
 void BluetoothHci::sendDataToController(const uint8_t type,
                                         const hidl_vec<uint8_t>& data) {
-  if (bt_enabled != 1) {
-    ALOGE("should initialize first!");
-    return;
-  }
-
   VendorInterface::get()->Send(type, data.data(), data.size());
 }
 
diff --git a/bluetooth/1.0/default/bluetooth_hci.h b/bluetooth/1.0/default/bluetooth_hci.h
index 5130c87..c966990 100644
--- a/bluetooth/1.0/default/bluetooth_hci.h
+++ b/bluetooth/1.0/default/bluetooth_hci.h
@@ -48,7 +48,6 @@
   void sendDataToController(const uint8_t type, const hidl_vec<uint8_t>& data);
   ::android::sp<BluetoothDeathRecipient> death_recipient_;
   std::function<void(sp<BluetoothDeathRecipient>&)> unlink_cb_;
-  int bt_enabled;
 };
 
 extern "C" IBluetoothHci* HIDL_FETCH_IBluetoothHci(const char* name);
diff --git a/bluetooth/1.0/default/vendor_interface.cc b/bluetooth/1.0/default/vendor_interface.cc
index c23d667..1d15dd6 100644
--- a/bluetooth/1.0/default/vendor_interface.cc
+++ b/bluetooth/1.0/default/vendor_interface.cc
@@ -36,8 +36,6 @@
     "BLUETOOTH_VENDOR_LIB_INTERFACE";
 
 static const int INVALID_FD = -1;
-std::mutex vendor_mutex_;
-std::mutex initcb_mutex_;
 
 namespace {
 
@@ -49,25 +47,13 @@
   uint16_t opcode;
 } internal_command;
 
-enum {
-  VENDOR_STATE_INIT = 1,
-  VENDOR_STATE_OPENING,	/* during opening */
-  VENDOR_STATE_OPENED,	/* open in fops_open */
-  VENDOR_STATE_CLOSING,	/* during closing */
-  VENDOR_STATE_CLOSED,	/* closed */
-
-  VENDOR_STATE_MSG_NUM
-} ;
-
-uint8_t vstate = VENDOR_STATE_INIT;
-
 // True when LPM is not enabled yet or wake is not asserted.
 bool lpm_wake_deasserted;
 uint32_t lpm_timeout_ms;
 bool recent_activity_flag;
 
 VendorInterface* g_vendor_interface = nullptr;
-static VendorInterface vendor_interface;
+std::mutex wakeup_mutex_;
 
 HC_BT_HDR* WrapPacketAndCopy(uint16_t event, const hidl_vec<uint8_t>& data) {
   size_t packet_size = data.size() + sizeof(HC_BT_HDR);
@@ -181,8 +167,11 @@
     InitializeCompleteCallback initialize_complete_cb,
     PacketReadCallback event_cb, PacketReadCallback acl_cb,
     PacketReadCallback sco_cb, PacketReadCallback iso_cb) {
-  ALOGI("%s: VendorInterface::Initialize", __func__);
-  g_vendor_interface = &vendor_interface;
+  if (g_vendor_interface) {
+    ALOGE("%s: No previous Shutdown()?", __func__);
+    return false;
+  }
+  g_vendor_interface = new VendorInterface();
   return g_vendor_interface->Open(initialize_complete_cb, event_cb, acl_cb,
                                   sco_cb, iso_cb);
 }
@@ -190,8 +179,9 @@
 void VendorInterface::Shutdown() {
   LOG_ALWAYS_FATAL_IF(!g_vendor_interface, "%s: No Vendor interface!",
                       __func__);
-  ALOGI("%s: VendorInterface::Shutdown", __func__);
   g_vendor_interface->Close();
+  delete g_vendor_interface;
+  g_vendor_interface = nullptr;
 }
 
 VendorInterface* VendorInterface::get() { return g_vendor_interface; }
@@ -201,189 +191,144 @@
                            PacketReadCallback acl_cb,
                            PacketReadCallback sco_cb,
                            PacketReadCallback iso_cb) {
-  {
-    std::unique_lock<std::mutex> guard(vendor_mutex_);
-    if (vstate == VENDOR_STATE_OPENED) {
-      ALOGW("VendorInterface opened!");
-      return true;
-    }
+  initialize_complete_cb_ = initialize_complete_cb;
 
-    if ((vstate == VENDOR_STATE_CLOSING) ||
-        (vstate == VENDOR_STATE_OPENING)) {
-      ALOGW("VendorInterface open/close is on-going !");
-      return true;
-    }
+  // Initialize vendor interface
 
-    vstate = VENDOR_STATE_OPENING;
-    ALOGI("%s: VendorInterface::Open", __func__);
+  lib_handle_ = dlopen(VENDOR_LIBRARY_NAME, RTLD_NOW);
+  if (!lib_handle_) {
+    ALOGE("%s unable to open %s (%s)", __func__, VENDOR_LIBRARY_NAME,
+          dlerror());
+    return false;
+  }
 
-    initialize_complete_cb_ = initialize_complete_cb;
-    // Initialize vendor interface
-
-    lib_handle_ = dlopen(VENDOR_LIBRARY_NAME, RTLD_NOW);
-    if (!lib_handle_) {
-      ALOGE("%s unable to open %s (%s)", __func__, VENDOR_LIBRARY_NAME,
-            dlerror());
-      return false;
-    }
-
-    lib_interface_ = reinterpret_cast<bt_vendor_interface_t*>(
-        dlsym(lib_handle_, VENDOR_LIBRARY_SYMBOL_NAME));
-    if (!lib_interface_) {
-      ALOGE("%s unable to find symbol %s in %s (%s)", __func__,
-            VENDOR_LIBRARY_SYMBOL_NAME, VENDOR_LIBRARY_NAME, dlerror());
-      return false;
-    }
+  lib_interface_ = reinterpret_cast<bt_vendor_interface_t*>(
+      dlsym(lib_handle_, VENDOR_LIBRARY_SYMBOL_NAME));
+  if (!lib_interface_) {
+    ALOGE("%s unable to find symbol %s in %s (%s)", __func__,
+          VENDOR_LIBRARY_SYMBOL_NAME, VENDOR_LIBRARY_NAME, dlerror());
+    return false;
+  }
 
   // Get the local BD address
 
-    uint8_t local_bda[BluetoothAddress::kBytes] = {0, 0, 0, 0, 0, 0};
-    if (!BluetoothAddress::get_local_address(local_bda)) {
-      // BT driver will get BD address from NVRAM for MTK solution
-      ALOGW("%s: No pre-set Bluetooth Address!", __func__);
-    }
-    int status = lib_interface_->init(&lib_callbacks, (unsigned char*)local_bda);
-    if (status) {
-      ALOGE("%s unable to initialize vendor library: %d", __func__, status);
-      return false;
-    }
+  uint8_t local_bda[BluetoothAddress::kBytes];
+  if (!BluetoothAddress::get_local_address(local_bda)) {
+    LOG_ALWAYS_FATAL("%s: No Bluetooth Address!", __func__);
+  }
+  int status = lib_interface_->init(&lib_callbacks, (unsigned char*)local_bda);
+  if (status) {
+    ALOGE("%s unable to initialize vendor library: %d", __func__, status);
+    return false;
+  }
 
-    ALOGD("%s vendor library loaded", __func__);
+  ALOGD("%s vendor library loaded", __func__);
 
   // Power on the controller
 
-    int power_state = BT_VND_PWR_ON;
-    lib_interface_->op(BT_VND_OP_POWER_CTRL, &power_state);
+  int power_state = BT_VND_PWR_ON;
+  lib_interface_->op(BT_VND_OP_POWER_CTRL, &power_state);
 
   // Get the UART socket(s)
 
-    int fd_list[CH_MAX] = {0};
-    int fd_count = lib_interface_->op(BT_VND_OP_USERIAL_OPEN, &fd_list);
+  int fd_list[CH_MAX] = {0};
+  int fd_count = lib_interface_->op(BT_VND_OP_USERIAL_OPEN, &fd_list);
 
-    if (fd_count < 1 || fd_count > CH_MAX - 1) {
-      ALOGE("%s: fd_count %d is invalid!", __func__, fd_count);
+  if (fd_count < 1 || fd_count > CH_MAX - 1) {
+    ALOGE("%s: fd_count %d is invalid!", __func__, fd_count);
+    return false;
+  }
+
+  for (int i = 0; i < fd_count; i++) {
+    if (fd_list[i] == INVALID_FD) {
+      ALOGE("%s: fd %d is invalid!", __func__, fd_list[i]);
       return false;
     }
+  }
 
-    for (int i = 0; i < fd_count; i++) {
-      if (fd_list[i] == INVALID_FD) {
-        ALOGE("%s: fd %d is invalid!", __func__, fd_list[i]);
-        return false;
-      }
-    }
+  event_cb_ = event_cb;
+  PacketReadCallback intercept_events = [this](const hidl_vec<uint8_t>& event) {
+    HandleIncomingEvent(event);
+  };
 
-    event_cb_ = event_cb;
-    PacketReadCallback intercept_events = [this](const hidl_vec<uint8_t>& event) {
-      HandleIncomingEvent(event);
-    };
-
-    if (fd_count == 1) {
-      hci::H4Protocol* h4_hci =
-          new hci::H4Protocol(fd_list[0], intercept_events, acl_cb, sco_cb, iso_cb);
-      fd_watcher_.WatchFdForNonBlockingReads(
-          fd_list[0], [h4_hci](int fd) { h4_hci->OnDataReady(fd); });
-      hci_ = h4_hci;
-    } else {
-      hci::MctProtocol* mct_hci =
-          new hci::MctProtocol(fd_list, intercept_events, acl_cb);
-      fd_watcher_.WatchFdForNonBlockingReads(
-          fd_list[CH_EVT], [mct_hci](int fd) { mct_hci->OnEventDataReady(fd); });
-      fd_watcher_.WatchFdForNonBlockingReads(
-          fd_list[CH_ACL_IN],
-          [mct_hci](int fd) { mct_hci->OnAclDataReady(fd); });
-      hci_ = mct_hci;
-    }
+  if (fd_count == 1) {
+    hci::H4Protocol* h4_hci =
+        new hci::H4Protocol(fd_list[0], intercept_events, acl_cb, sco_cb, iso_cb);
+    fd_watcher_.WatchFdForNonBlockingReads(
+        fd_list[0], [h4_hci](int fd) { h4_hci->OnDataReady(fd); });
+    hci_ = h4_hci;
+  } else {
+    hci::MctProtocol* mct_hci =
+        new hci::MctProtocol(fd_list, intercept_events, acl_cb);
+    fd_watcher_.WatchFdForNonBlockingReads(
+        fd_list[CH_EVT], [mct_hci](int fd) { mct_hci->OnEventDataReady(fd); });
+    fd_watcher_.WatchFdForNonBlockingReads(
+        fd_list[CH_ACL_IN], [mct_hci](int fd) { mct_hci->OnAclDataReady(fd); });
+    hci_ = mct_hci;
+  }
 
   // Initially, the power management is off.
-    lpm_wake_deasserted = true;
+  lpm_wake_deasserted = true;
 
   // Start configuring the firmware
-    firmware_startup_timer_ = new FirmwareStartupTimer();
-    lib_interface_->op(BT_VND_OP_FW_CFG, nullptr);
+  firmware_startup_timer_ = new FirmwareStartupTimer();
+  lib_interface_->op(BT_VND_OP_FW_CFG, nullptr);
 
-    vstate = VENDOR_STATE_OPENED;
-    ALOGI("%s: VendorInterface::Open done!!!", __func__);
-  }  // vendor_mutex_ done
   return true;
 }
 
 void VendorInterface::Close() {
   // These callbacks may send HCI events (vendor-dependent), so make sure to
   // StopWatching the file descriptor after this.
-
-  if (vstate != VENDOR_STATE_OPENED) {
-    ALOGW("VendorInterface is not allow close(%d)", vstate);
-    return;
-  }
-  vstate = VENDOR_STATE_CLOSING;
-  ALOGI("%s: VendorInterface::Close", __func__);
-
   if (lib_interface_ != nullptr) {
-    lib_interface_->cleanup();
     bt_vendor_lpm_mode_t mode = BT_VND_LPM_DISABLE;
     lib_interface_->op(BT_VND_OP_LPM_SET_MODE, &mode);
   }
 
-  {
-    std::unique_lock<std::mutex> guard(vendor_mutex_);
+  fd_watcher_.StopWatchingFileDescriptors();
 
-    fd_watcher_.StopWatchingFileDescriptors();
-    if (hci_ != nullptr) {
-      delete hci_;
-      hci_ = nullptr;
-    }
+  if (hci_ != nullptr) {
+    delete hci_;
+    hci_ = nullptr;
+  }
 
-    if (lib_interface_ != nullptr) {
-      lib_interface_->op(BT_VND_OP_USERIAL_CLOSE, nullptr);
+  if (lib_interface_ != nullptr) {
+    lib_interface_->op(BT_VND_OP_USERIAL_CLOSE, nullptr);
 
-      int power_state = BT_VND_PWR_OFF;
-      lib_interface_->op(BT_VND_OP_POWER_CTRL, &power_state);
+    int power_state = BT_VND_PWR_OFF;
+    lib_interface_->op(BT_VND_OP_POWER_CTRL, &power_state);
 
-      lib_interface_ = nullptr;
-    }
+    lib_interface_->cleanup();
+    lib_interface_ = nullptr;
+  }
 
-    if (lib_handle_ != nullptr) {
-      dlclose(lib_handle_);
-      lib_handle_ = nullptr;
-    }
+  if (lib_handle_ != nullptr) {
+    dlclose(lib_handle_);
+    lib_handle_ = nullptr;
+  }
 
-    if (firmware_startup_timer_ != nullptr) {
-      delete firmware_startup_timer_;
-      firmware_startup_timer_ = nullptr;
-    }
-    vstate = VENDOR_STATE_CLOSED;
-  }  // vendor_mutex_ done
-  ALOGI("%s: VendorInterface::Close done!!!", __func__);
+  if (firmware_startup_timer_ != nullptr) {
+    delete firmware_startup_timer_;
+    firmware_startup_timer_ = nullptr;
+  }
 }
 
 size_t VendorInterface::Send(uint8_t type, const uint8_t* data, size_t length) {
-  {
-    std::unique_lock<std::mutex> guard(vendor_mutex_);
+  std::unique_lock<std::mutex> lock(wakeup_mutex_);
+  recent_activity_flag = true;
 
-    if (vstate != VENDOR_STATE_OPENED) {
-      ALOGW("VendorInterface is not open yet(%d)!", vstate);
-      return 0;
-    }
-    ALOGI("%s: VendorInterface::Send", __func__);
-
-    if (lib_interface_ == nullptr) {
-      ALOGE("lib_interface_ is null");
-      return 0;
-    }
-    recent_activity_flag = true;
-    if (lpm_wake_deasserted == true) {
-      // Restart the timer.
-      fd_watcher_.ConfigureTimeout(std::chrono::milliseconds(lpm_timeout_ms),
+  if (lpm_wake_deasserted == true) {
+    // Restart the timer.
+    fd_watcher_.ConfigureTimeout(std::chrono::milliseconds(lpm_timeout_ms),
                                  [this]() { OnTimeout(); });
-      // Assert wake.
-      lpm_wake_deasserted = false;
-      bt_vendor_lpm_wake_state_t wakeState = BT_VND_LPM_WAKE_ASSERT;
-      lib_interface_->op(BT_VND_OP_LPM_WAKE_SET_STATE, &wakeState);
-      ALOGV("%s: Sent wake before (%02x)", __func__, data[0] | (data[1] << 8));
-    }
+    // Assert wake.
+    lpm_wake_deasserted = false;
+    bt_vendor_lpm_wake_state_t wakeState = BT_VND_LPM_WAKE_ASSERT;
+    lib_interface_->op(BT_VND_OP_LPM_WAKE_SET_STATE, &wakeState);
+    ALOGV("%s: Sent wake before (%02x)", __func__, data[0] | (data[1] << 8));
+  }
 
-    return hci_ ? hci_->Send(type, data, length) : 0;
-  }  // vendor_mutex_ done
+  return hci_->Send(type, data, length);
 }
 
 void VendorInterface::OnFirmwareConfigured(uint8_t result) {
@@ -394,36 +339,25 @@
     firmware_startup_timer_ = nullptr;
   }
 
-  {
-    std::unique_lock<std::mutex> guard(initcb_mutex_);
-    ALOGD("%s OnFirmwareConfigured get lock", __func__);
-    if (initialize_complete_cb_ != nullptr) {
-      LOG_ALWAYS_FATAL_IF((result != 0),
-          "%s: Failed to init firmware!", __func__);
-      initialize_complete_cb_(result == 0);
-    }
-  }  // initcb_mutex_ done
-
-  if (lib_interface_ != nullptr) {
-    lib_interface_->op(BT_VND_OP_GET_LPM_IDLE_TIMEOUT, &lpm_timeout_ms);
-    ALOGI("%s: lpm_timeout_ms %d", __func__, lpm_timeout_ms);
-
-    bt_vendor_lpm_mode_t mode = BT_VND_LPM_ENABLE;
-    lib_interface_->op(BT_VND_OP_LPM_SET_MODE, &mode);
-
-    ALOGD("%s Calling StartLowPowerWatchdog()", __func__);
-    fd_watcher_.ConfigureTimeout(std::chrono::milliseconds(lpm_timeout_ms),
-                                 [this]() { OnTimeout(); });
-  }
-  else {
-    ALOGE("lib_interface_ is null");
+  if (initialize_complete_cb_ != nullptr) {
+    initialize_complete_cb_(result == 0);
+    initialize_complete_cb_ = nullptr;
   }
 
-  initialize_complete_cb_ = nullptr;
+  lib_interface_->op(BT_VND_OP_GET_LPM_IDLE_TIMEOUT, &lpm_timeout_ms);
+  ALOGI("%s: lpm_timeout_ms %d", __func__, lpm_timeout_ms);
+
+  bt_vendor_lpm_mode_t mode = BT_VND_LPM_ENABLE;
+  lib_interface_->op(BT_VND_OP_LPM_SET_MODE, &mode);
+
+  ALOGD("%s Calling StartLowPowerWatchdog()", __func__);
+  fd_watcher_.ConfigureTimeout(std::chrono::milliseconds(lpm_timeout_ms),
+                               [this]() { OnTimeout(); });
 }
 
 void VendorInterface::OnTimeout() {
   ALOGV("%s", __func__);
+  std::unique_lock<std::mutex> lock(wakeup_mutex_);
   if (recent_activity_flag == false) {
     lpm_wake_deasserted = true;
     bt_vendor_lpm_wake_state_t wakeState = BT_VND_LPM_WAKE_DEASSERT;
diff --git a/bluetooth/1.0/default/vendor_interface.h b/bluetooth/1.0/default/vendor_interface.h
index 2df3946..040f31a 100644
--- a/bluetooth/1.0/default/vendor_interface.h
+++ b/bluetooth/1.0/default/vendor_interface.h
@@ -22,8 +22,6 @@
 #include "bt_vendor_lib.h"
 #include "hci_protocol.h"
 
-extern std::mutex initcb_mutex_;
-
 namespace android {
 namespace hardware {
 namespace bluetooth {
@@ -47,9 +45,10 @@
   size_t Send(uint8_t type, const uint8_t* data, size_t length);
 
   void OnFirmwareConfigured(uint8_t result);
-  virtual ~VendorInterface() = default;
 
  private:
+  virtual ~VendorInterface() = default;
+
   bool Open(InitializeCompleteCallback initialize_complete_cb,
             PacketReadCallback event_cb, PacketReadCallback acl_cb,
             PacketReadCallback sco_cb, PacketReadCallback iso_cb);
diff --git a/bluetooth/aidl/default/BluetoothHci.cpp b/bluetooth/aidl/default/BluetoothHci.cpp
index 18a371d..782122f 100644
--- a/bluetooth/aidl/default/BluetoothHci.cpp
+++ b/bluetooth/aidl/default/BluetoothHci.cpp
@@ -224,6 +224,7 @@
     ALOGI("Unable to open Linux interface, trying default path.");
     mFd = getFdFromDevPath();
     if (mFd < 0) {
+      mState = HalState::READY;
       cb->initializationComplete(Status::UNABLE_TO_OPEN_INTERFACE);
       return ndk::ScopedAStatus::ok();
     }
@@ -281,6 +282,7 @@
   {
     std::lock_guard<std::mutex> guard(mStateMutex);
     if (mState != HalState::ONE_CLIENT) {
+      ASSERT(mState != HalState::INITIALIZING);
       ALOGI("Already closed");
       return ndk::ScopedAStatus::ok();
     }
diff --git a/compatibility_matrices/compatibility_matrix.9.xml b/compatibility_matrices/compatibility_matrix.9.xml
index e23f2ae..60bb2ab 100644
--- a/compatibility_matrices/compatibility_matrix.9.xml
+++ b/compatibility_matrices/compatibility_matrix.9.xml
@@ -794,4 +794,12 @@
             <regex-instance>.*</regex-instance>
         </interface>
     </hal>
+    <hal format="aidl" optional="true">
+        <name>android.hardware.threadnetwork</name>
+        <version>1</version>
+        <interface>
+            <name>IThreadChip</name>
+            <regex-instance>chip[0-9]+</regex-instance>
+        </interface>
+    </hal>
 </compatibility-matrix>
diff --git a/light/aidl/Android.bp b/light/aidl/Android.bp
index c11934f..c9fba95 100644
--- a/light/aidl/Android.bp
+++ b/light/aidl/Android.bp
@@ -18,6 +18,9 @@
         java: {
             sdk_version: "module_current",
         },
+        rust: {
+            enabled: true,
+        },
     },
     versions_with_info: [
         {
diff --git a/light/aidl/aidl_api/android.hardware.light/2/.hash b/light/aidl/aidl_api/android.hardware.light/2/.hash
index d27f4ad..2d4e7f0 100644
--- a/light/aidl/aidl_api/android.hardware.light/2/.hash
+++ b/light/aidl/aidl_api/android.hardware.light/2/.hash
@@ -1 +1,2 @@
 c8b1e8ebb88c57dcb2c350a8d9b722e77dd864c8
+c7d3d941d303c70d1c22759a0b09e41930c1cddb
diff --git a/light/aidl/aidl_api/android.hardware.light/2/android/hardware/light/HwLight.aidl b/light/aidl/aidl_api/android.hardware.light/2/android/hardware/light/HwLight.aidl
index 25a2dce..5ac2a34 100644
--- a/light/aidl/aidl_api/android.hardware.light/2/android/hardware/light/HwLight.aidl
+++ b/light/aidl/aidl_api/android.hardware.light/2/android/hardware/light/HwLight.aidl
@@ -32,7 +32,7 @@
 // later when a module using the interface is updated, e.g., Mainline modules.
 
 package android.hardware.light;
-@VintfStability
+@RustDerive(Clone=true, Copy=true) @VintfStability
 parcelable HwLight {
   int id;
   int ordinal;
diff --git a/light/aidl/aidl_api/android.hardware.light/2/android/hardware/light/HwLightState.aidl b/light/aidl/aidl_api/android.hardware.light/2/android/hardware/light/HwLightState.aidl
index 40e520b..2878ce2 100644
--- a/light/aidl/aidl_api/android.hardware.light/2/android/hardware/light/HwLightState.aidl
+++ b/light/aidl/aidl_api/android.hardware.light/2/android/hardware/light/HwLightState.aidl
@@ -32,7 +32,7 @@
 // later when a module using the interface is updated, e.g., Mainline modules.
 
 package android.hardware.light;
-@VintfStability
+@RustDerive(Clone=true, Copy=true) @VintfStability
 parcelable HwLightState {
   int color;
   android.hardware.light.FlashMode flashMode;
diff --git a/light/aidl/aidl_api/android.hardware.light/current/android/hardware/light/HwLight.aidl b/light/aidl/aidl_api/android.hardware.light/current/android/hardware/light/HwLight.aidl
index 25a2dce..5ac2a34 100644
--- a/light/aidl/aidl_api/android.hardware.light/current/android/hardware/light/HwLight.aidl
+++ b/light/aidl/aidl_api/android.hardware.light/current/android/hardware/light/HwLight.aidl
@@ -32,7 +32,7 @@
 // later when a module using the interface is updated, e.g., Mainline modules.
 
 package android.hardware.light;
-@VintfStability
+@RustDerive(Clone=true, Copy=true) @VintfStability
 parcelable HwLight {
   int id;
   int ordinal;
diff --git a/light/aidl/aidl_api/android.hardware.light/current/android/hardware/light/HwLightState.aidl b/light/aidl/aidl_api/android.hardware.light/current/android/hardware/light/HwLightState.aidl
index 40e520b..2878ce2 100644
--- a/light/aidl/aidl_api/android.hardware.light/current/android/hardware/light/HwLightState.aidl
+++ b/light/aidl/aidl_api/android.hardware.light/current/android/hardware/light/HwLightState.aidl
@@ -32,7 +32,7 @@
 // later when a module using the interface is updated, e.g., Mainline modules.
 
 package android.hardware.light;
-@VintfStability
+@RustDerive(Clone=true, Copy=true) @VintfStability
 parcelable HwLightState {
   int color;
   android.hardware.light.FlashMode flashMode;
diff --git a/light/aidl/android/hardware/light/HwLight.aidl b/light/aidl/android/hardware/light/HwLight.aidl
index 43fdb4b..8db32cc 100644
--- a/light/aidl/android/hardware/light/HwLight.aidl
+++ b/light/aidl/android/hardware/light/HwLight.aidl
@@ -22,7 +22,7 @@
  * A description of a single light. Multiple lights can map to the same physical
  * LED. Separate physical LEDs are always represented by separate instances.
  */
-@VintfStability
+@RustDerive(Clone=true, Copy=true) @VintfStability
 parcelable HwLight {
     /**
      * Integer ID used for controlling this light
diff --git a/light/aidl/android/hardware/light/HwLightState.aidl b/light/aidl/android/hardware/light/HwLightState.aidl
index 24d3250..3ba6c78 100644
--- a/light/aidl/android/hardware/light/HwLightState.aidl
+++ b/light/aidl/android/hardware/light/HwLightState.aidl
@@ -25,7 +25,7 @@
  * Not all lights must support all parameters. If you
  * can do something backward-compatible, do it.
  */
-@VintfStability
+@RustDerive(Clone=true, Copy=true) @VintfStability
 parcelable HwLightState {
     /**
      * The color of the LED in ARGB.
diff --git a/light/aidl/default/Android.bp b/light/aidl/default/Android.bp
index 7920503..285329e 100644
--- a/light/aidl/default/Android.bp
+++ b/light/aidl/default/Android.bp
@@ -7,19 +7,17 @@
     default_applicable_licenses: ["hardware_interfaces_license"],
 }
 
-cc_binary {
+rust_binary {
     name: "android.hardware.lights-service.example",
     relative_install_path: "hw",
     init_rc: ["lights-default.rc"],
     vintf_fragments: ["lights-default.xml"],
     vendor: true,
-    shared_libs: [
-        "libbase",
-        "libbinder_ndk",
-        "android.hardware.light-V2-ndk",
+    rustlibs: [
+        "liblogger",
+        "liblog_rust",
+        "libbinder_rs",
+        "android.hardware.light-V2-rust",
     ],
-    srcs: [
-        "Lights.cpp",
-        "main.cpp",
-    ],
+    srcs: [ "main.rs" ],
 }
diff --git a/light/aidl/default/Lights.cpp b/light/aidl/default/Lights.cpp
deleted file mode 100644
index 9bf3b20..0000000
--- a/light/aidl/default/Lights.cpp
+++ /dev/null
@@ -1,48 +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.
- */
-
-#include "Lights.h"
-
-#include <android-base/logging.h>
-
-namespace aidl {
-namespace android {
-namespace hardware {
-namespace light {
-
-static constexpr int kNumDefaultLights = 3;
-
-ndk::ScopedAStatus Lights::setLightState(int id, const HwLightState& state) {
-    LOG(INFO) << "Lights setting state for id=" << id << " to color " << std::hex << state.color;
-    if (id <= 0 || id > kNumDefaultLights) {
-        return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
-    } else {
-        return ndk::ScopedAStatus::ok();
-    }
-}
-
-ndk::ScopedAStatus Lights::getLights(std::vector<HwLight>* lights) {
-    for (int i = 1; i <= kNumDefaultLights; i++) {
-        lights->push_back({i, i});
-    }
-    LOG(INFO) << "Lights reporting supported lights";
-    return ndk::ScopedAStatus::ok();
-}
-
-}  // namespace light
-}  // namespace hardware
-}  // namespace android
-}  // namespace aidl
diff --git a/light/aidl/default/lights.rs b/light/aidl/default/lights.rs
new file mode 100644
index 0000000..6c8aa3f
--- /dev/null
+++ b/light/aidl/default/lights.rs
@@ -0,0 +1,80 @@
+/*
+ * 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 implements the ILights AIDL interface.
+
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+use log::info;
+
+use android_hardware_light::aidl::android::hardware::light::{
+    HwLight::HwLight, HwLightState::HwLightState, ILights::ILights, LightType::LightType,
+};
+
+use binder::{ExceptionCode, Interface, Status};
+
+struct Light {
+    hw_light: HwLight,
+    state: HwLightState,
+}
+
+const NUM_DEFAULT_LIGHTS: i32 = 3;
+
+/// Defined so we can implement the ILights AIDL interface.
+pub struct LightsService {
+    lights: Mutex<HashMap<i32, Light>>,
+}
+
+impl Interface for LightsService {}
+
+impl LightsService {
+    fn new(hw_lights: impl IntoIterator<Item = HwLight>) -> Self {
+        let mut lights_map = HashMap::new();
+
+        for hw_light in hw_lights {
+            lights_map.insert(hw_light.id, Light { hw_light, state: Default::default() });
+        }
+
+        Self { lights: Mutex::new(lights_map) }
+    }
+}
+
+impl Default for LightsService {
+    fn default() -> Self {
+        let id_mapping_closure =
+            |light_id| HwLight { id: light_id, ordinal: light_id, r#type: LightType::BACKLIGHT };
+
+        Self::new((1..=NUM_DEFAULT_LIGHTS).map(id_mapping_closure))
+    }
+}
+
+impl ILights for LightsService {
+    fn setLightState(&self, id: i32, state: &HwLightState) -> binder::Result<()> {
+        info!("Lights setting state for id={} to color {:x}", id, state.color);
+
+        if let Some(light) = self.lights.lock().unwrap().get_mut(&id) {
+            light.state = *state;
+            Ok(())
+        } else {
+            Err(Status::new_exception(ExceptionCode::UNSUPPORTED_OPERATION, None))
+        }
+    }
+
+    fn getLights(&self) -> binder::Result<Vec<HwLight>> {
+        info!("Lights reporting supported lights");
+        Ok(self.lights.lock().unwrap().values().map(|light| light.hw_light).collect())
+    }
+}
diff --git a/light/aidl/default/main.cpp b/light/aidl/default/main.cpp
deleted file mode 100644
index 54e1316..0000000
--- a/light/aidl/default/main.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2020 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 "Lights.h"
-
-#include <android-base/logging.h>
-#include <android/binder_manager.h>
-#include <android/binder_process.h>
-
-using ::aidl::android::hardware::light::Lights;
-
-int main() {
-    ABinderProcess_setThreadPoolMaxThreadCount(0);
-    std::shared_ptr<Lights> lights = ndk::SharedRefBase::make<Lights>();
-
-    const std::string instance = std::string() + Lights::descriptor + "/default";
-    binder_status_t status = AServiceManager_addService(lights->asBinder().get(), instance.c_str());
-    CHECK_EQ(status, STATUS_OK);
-
-    ABinderProcess_joinThreadPool();
-    return EXIT_FAILURE;  // should not reached
-}
diff --git a/light/aidl/default/main.rs b/light/aidl/default/main.rs
new file mode 100644
index 0000000..8f32470
--- /dev/null
+++ b/light/aidl/default/main.rs
@@ -0,0 +1,46 @@
+/*
+ * 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 implements the Lights Example Service.
+
+use android_hardware_light::aidl::android::hardware::light::ILights::{BnLights, ILights};
+use binder::BinderFeatures;
+
+mod lights;
+use lights::LightsService;
+
+const LOG_TAG: &str = "lights_service_example_rust";
+
+use log::Level;
+
+fn main() {
+    let logger_success = logger::init(
+        logger::Config::default().with_tag_on_device(LOG_TAG).with_min_level(Level::Trace),
+    );
+    if !logger_success {
+        panic!("{LOG_TAG}: Failed to start logger.");
+    }
+
+    binder::ProcessState::set_thread_pool_max_thread_count(0);
+
+    let lights_service = LightsService::default();
+    let lights_service_binder = BnLights::new_binder(lights_service, BinderFeatures::default());
+
+    let service_name = format!("{}/default", LightsService::get_descriptor());
+    binder::add_service(&service_name, lights_service_binder.as_binder())
+        .expect("Failed to register service");
+
+    binder::ProcessState::join_thread_pool()
+}
diff --git a/radio/1.0/vts/functional/vts_test_util.cpp b/radio/1.0/vts/functional/vts_test_util.cpp
index 5b31acc..0515778 100644
--- a/radio/1.0/vts/functional/vts_test_util.cpp
+++ b/radio/1.0/vts/functional/vts_test_util.cpp
@@ -138,3 +138,7 @@
     count_--;
     return status;
 }
+
+bool isLteConnected(){
+    return testing::checkSubstringInCommandOutput("getprop gsm.network.type", "LTE");
+}
diff --git a/radio/1.0/vts/functional/vts_test_util.h b/radio/1.0/vts/functional/vts_test_util.h
index fa338a3..39c7545 100644
--- a/radio/1.0/vts/functional/vts_test_util.h
+++ b/radio/1.0/vts/functional/vts_test_util.h
@@ -104,6 +104,11 @@
  */
 bool isVoiceInService(RegState state);
 
+/*
+ * Check if device is in Lte Connected status.
+ */
+bool isLteConnected();
+
 /**
  * Used when waiting for an asynchronous response from the HAL.
  */
diff --git a/radio/1.5/vts/functional/radio_hidl_hal_api.cpp b/radio/1.5/vts/functional/radio_hidl_hal_api.cpp
index fd44e93..3d3abe4 100644
--- a/radio/1.5/vts/functional/radio_hidl_hal_api.cpp
+++ b/radio/1.5/vts/functional/radio_hidl_hal_api.cpp
@@ -597,7 +597,7 @@
     } else if (cardStatus.base.base.base.cardState == CardState::PRESENT) {
         // Modems support 3GPP RAT family need to
         // support scanning requests combined with some parameters.
-        if (deviceSupportsFeature(FEATURE_TELEPHONY_GSM)) {
+        if (deviceSupportsFeature(FEATURE_TELEPHONY_GSM) && isLteConnected()) {
             ASSERT_TRUE(CheckAnyOfErrors(radioRsp_v1_5->rspInfo.error,
                                          {RadioError::NONE, RadioError::OPERATION_NOT_ALLOWED}));
         } else {
diff --git a/radio/aidl/vts/radio_aidl_hal_utils.cpp b/radio/aidl/vts/radio_aidl_hal_utils.cpp
index f18da55..5781b42 100644
--- a/radio/aidl/vts/radio_aidl_hal_utils.cpp
+++ b/radio/aidl/vts/radio_aidl_hal_utils.cpp
@@ -227,3 +227,7 @@
         slotStatus = radioConfigRsp->simSlotStatus[physicalSlotId];
     }
 }
+
+bool isLteConnected(){
+    return testing::checkSubstringInCommandOutput("getprop gsm.network.type", "LTE");
+}
diff --git a/radio/aidl/vts/radio_aidl_hal_utils.h b/radio/aidl/vts/radio_aidl_hal_utils.h
index 8170a01..e68c5c1 100644
--- a/radio/aidl/vts/radio_aidl_hal_utils.h
+++ b/radio/aidl/vts/radio_aidl_hal_utils.h
@@ -128,6 +128,11 @@
  */
 bool isServiceValidForDeviceConfiguration(std::string& serviceName);
 
+/*
+ * Check if device is in Lte Connected status.
+ */
+bool isLteConnected();
+
 /**
  * RadioServiceTest base class
  */
diff --git a/radio/aidl/vts/radio_network_test.cpp b/radio/aidl/vts/radio_network_test.cpp
index 95ab2b1..6423329 100644
--- a/radio/aidl/vts/radio_network_test.cpp
+++ b/radio/aidl/vts/radio_network_test.cpp
@@ -861,7 +861,7 @@
     if (cardStatus.cardState == CardStatus::STATE_ABSENT) {
         ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error, {RadioError::SIM_ABSENT}));
     } else if (cardStatus.cardState == CardStatus::STATE_PRESENT) {
-        if (deviceSupportsFeature(FEATURE_TELEPHONY_GSM)) {
+        if (deviceSupportsFeature(FEATURE_TELEPHONY_GSM) && isLteConnected()) {
             // Modems support 3GPP RAT family need to
             // support scanning requests combined with some parameters.
             ASSERT_TRUE(CheckAnyOfErrors(radioRsp_network->rspInfo.error,
diff --git a/security/keymint/aidl/default/android.hardware.security.keymint-service.xml b/security/keymint/aidl/default/android.hardware.security.keymint-service.xml
index a4d0302..0568ae6 100644
--- a/security/keymint/aidl/default/android.hardware.security.keymint-service.xml
+++ b/security/keymint/aidl/default/android.hardware.security.keymint-service.xml
@@ -1,12 +1,12 @@
 <manifest version="1.0" type="device">
     <hal format="aidl">
         <name>android.hardware.security.keymint</name>
-        <version>2</version>
+        <version>3</version>
         <fqname>IKeyMintDevice/default</fqname>
     </hal>
     <hal format="aidl">
         <name>android.hardware.security.keymint</name>
-        <version>2</version>
+        <version>3</version>
         <fqname>IRemotelyProvisionedComponent/default</fqname>
     </hal>
 </manifest>
diff --git a/security/keymint/aidl/vts/functional/AttestKeyTest.cpp b/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
index 0fc359a..0499079 100644
--- a/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
+++ b/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
@@ -82,7 +82,7 @@
 
     string imei = ::android::base::Trim(out[0]);
     if (imei.compare("null") == 0) {
-        LOG(ERROR) << "Error in getting IMEI from Telephony service: value is null. Cmd: " << cmd;
+        LOG(WARNING) << "Failed to get IMEI from Telephony service: value is null. Cmd: " << cmd;
         return "";
     }
 
diff --git a/security/keymint/aidl/vts/functional/KeyBlobUpgradeTest.cpp b/security/keymint/aidl/vts/functional/KeyBlobUpgradeTest.cpp
index 4830422..7ccd246 100644
--- a/security/keymint/aidl/vts/functional/KeyBlobUpgradeTest.cpp
+++ b/security/keymint/aidl/vts/functional/KeyBlobUpgradeTest.cpp
@@ -74,6 +74,9 @@
 
 namespace {
 
+// Names for individual key types to create and use.  Note that some the names
+// induce specific behaviour, as indicated by the functions below.
+
 std::vector<std::string> keyblob_names_tee = {
         "aes-key",        "aes-key-rr",      "des-key",           "hmac-key",
         "rsa-key",        "p256-key",        "ed25519-key",       "x25519-key",
@@ -87,6 +90,11 @@
                                              "hmac-key",       "rsa-key",        "p256-key",
                                              "rsa-attest-key", "p256-attest-key"};
 
+// Helper functions to detect particular key types based on the name.
+bool requires_attest_key(const std::string& name) {
+    return name.find("-attest-key") != std::string::npos;
+}
+
 bool requires_rr(const std::string& name) {
     return name.find("-rr") != std::string::npos;
 }
@@ -210,6 +218,11 @@
         }
 
         for (std::string name : keyblob_names()) {
+            if (requires_attest_key(name) && shouldSkipAttestKeyTest()) {
+                std::cerr << "Skipping variant '" << name
+                          << "' which requires ATTEST_KEY support that has been waivered\n";
+                continue;
+            }
             for (bool with_hidden : {false, true}) {
                 std::string app_id;
                 std::string app_data;
@@ -358,6 +371,11 @@
             }};
 
     for (std::string name : keyblob_names()) {
+        if (requires_attest_key(name) && shouldSkipAttestKeyTest()) {
+            std::cerr << "Skipping variant '" << name
+                      << "' which requires ATTEST_KEY support that has been waivered\n";
+            continue;
+        }
         auto entry = keys_info.find(name);
         ASSERT_NE(entry, keys_info.end()) << "no builder for " << name;
         auto builder = entry->second;
@@ -441,6 +459,11 @@
     }
 
     for (std::string name : keyblob_names()) {
+        if (requires_attest_key(name) && shouldSkipAttestKeyTest()) {
+            std::cerr << "Skipping variant '" << name
+                      << "' which requires ATTEST_KEY support that has been waivered\n";
+            continue;
+        }
         for (bool with_hidden : {false, true}) {
             auto builder = AuthorizationSetBuilder();
             if (with_hidden) {
@@ -540,7 +563,7 @@
 
                 // Both ways round should agree.
                 EXPECT_EQ(keymint_data, local_data);
-            } else if (name.find("-attest-key") != std::string::npos) {
+            } else if (requires_attest_key(name)) {
                 // Covers rsa-attest-key, p256-attest-key, ed25519-attest-key.
 
                 // Use attestation key to sign RSA signing key
diff --git a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
index 12b21c1..9f8593c 100644
--- a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
+++ b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
@@ -1623,17 +1623,39 @@
     return false;
 }
 
-// Skip the test if all the following conditions hold:
-// 1. ATTEST_KEY feature is disabled
-// 2. STRONGBOX is enabled
-// 3. The device is running one of the chipsets that have received a waiver
-//     allowing it to be launched with Android S (or later) with Keymaster 4.0
+// Indicate whether a test that involves use of the ATTEST_KEY feature should be
+// skipped.
+//
+// In general, every KeyMint implementation should support ATTEST_KEY;
+// however, there is a waiver for some specific devices that ship with a
+// combination of Keymaster/StrongBox and KeyMint/TEE.  On these devices, the
+// ATTEST_KEY feature is disabled in the KeyMint/TEE implementation so that
+// the device has consistent ATTEST_KEY behavior (ie. UNIMPLEMENTED) across both
+// HAL implementations.
+//
+// This means that a test involving ATTEST_KEY test should be skipped if all of
+// the following conditions hold:
+// 1. The device is running one of the chipsets that have received a waiver
+//     allowing it to be launched with Android S or T with Keymaster 4.0
 //     in StrongBox
-void KeyMintAidlTestBase::skipAttestKeyTest(void) const {
+// 2. The device has a STRONGBOX implementation present.
+// 3. ATTEST_KEY feature is advertised as disabled.
+//
+// Note that in this scenario, ATTEST_KEY tests should be skipped for both
+// the StrongBox implementation (which is Keymaster, therefore not tested here)
+// and for the TEE implementation (which is adjusted to return UNIMPLEMENTED
+// specifically for this waiver).
+bool KeyMintAidlTestBase::shouldSkipAttestKeyTest(void) const {
     // Check the chipset first as that doesn't require a round-trip to Package Manager.
-    if (is_chipset_allowed_km4_strongbox() && is_strongbox_enabled() &&
-        is_attest_key_feature_disabled()) {
-        GTEST_SKIP() << "Test is not applicable";
+    return (is_chipset_allowed_km4_strongbox() && is_strongbox_enabled() &&
+            is_attest_key_feature_disabled());
+}
+
+// Skip a test that involves use of the ATTEST_KEY feature in specific configurations
+// where ATTEST_KEY is not supported (for either StrongBox or TEE).
+void KeyMintAidlTestBase::skipAttestKeyTest(void) const {
+    if (shouldSkipAttestKeyTest()) {
+        GTEST_SKIP() << "Test using ATTEST_KEY is not applicable on waivered device";
     }
 }
 
@@ -2049,6 +2071,27 @@
     return retval;
 }
 
+void assert_mgf_digests_present_in_key_characteristics(
+        const vector<KeyCharacteristics>& key_characteristics,
+        std::vector<android::hardware::security::keymint::Digest>& expected_mgf_digests) {
+    AuthorizationSet auths;
+    for (auto& entry : key_characteristics) {
+        auths.push_back(AuthorizationSet(entry.authorizations));
+    }
+    for (auto digest : expected_mgf_digests) {
+        ASSERT_TRUE(auths.Contains(TAG_RSA_OAEP_MGF_DIGEST, digest));
+    }
+}
+
+bool is_mgf_digest_present(const vector<KeyCharacteristics>& key_characteristics,
+                           android::hardware::security::keymint::Digest expected_mgf_digest) {
+    AuthorizationSet auths;
+    for (auto& entry : key_characteristics) {
+        auths.push_back(AuthorizationSet(entry.authorizations));
+    }
+    return auths.Contains(TAG_RSA_OAEP_MGF_DIGEST, expected_mgf_digest);
+}
+
 namespace {
 
 void check_cose_key(const vector<uint8_t>& data, bool testMode) {
@@ -2171,30 +2214,26 @@
 
 // Check the error code from an attempt to perform device ID attestation with an invalid value.
 void device_id_attestation_check_acceptable_error(Tag tag, const ErrorCode& result) {
-    // Standard/default error code for ID mismatch.
     if (result == ErrorCode::CANNOT_ATTEST_IDS) {
-        return;
-    }
-
-    // Depending on the situation, other error codes may be acceptable.  First, allow older
-    // implementations to use INVALID_TAG.
-    if (result == ErrorCode::INVALID_TAG) {
+        // Standard/default error code for ID mismatch.
+    } else if (result == ErrorCode::INVALID_TAG) {
+        // Depending on the situation, other error codes may be acceptable.  First, allow older
+        // implementations to use INVALID_TAG.
         ASSERT_FALSE(get_vsr_api_level() > __ANDROID_API_T__)
                 << "It is a specification violation for INVALID_TAG to be returned due to ID "
                 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
                 << "be used for a case where updateAad() is called after update(). As of "
                 << "VSR-14, this is now enforced as an error.";
-    }
-
-    // If the device is not a phone, it will not have IMEI/MEID values available.  Allow
-    // ATTESTATION_IDS_NOT_PROVISIONED in this case.
-    if (result == ErrorCode::ATTESTATION_IDS_NOT_PROVISIONED) {
+    } else if (result == ErrorCode::ATTESTATION_IDS_NOT_PROVISIONED) {
+        // If the device is not a phone, it will not have IMEI/MEID values available.  Allow
+        // ATTESTATION_IDS_NOT_PROVISIONED in this case.
         ASSERT_TRUE((tag == TAG_ATTESTATION_ID_IMEI || tag == TAG_ATTESTATION_ID_MEID ||
                      tag == TAG_ATTESTATION_ID_SECOND_IMEI))
                 << "incorrect error code on attestation ID mismatch";
+    } else {
+        ADD_FAILURE() << "Error code " << result
+                      << " returned on attestation ID mismatch, should be CANNOT_ATTEST_IDS";
     }
-    ADD_FAILURE() << "Error code " << result
-                  << " returned on attestation ID mismatch, should be CANNOT_ATTEST_IDS";
 }
 
 // Check whether the given named feature is available.
diff --git a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
index 0d0790f..8934a57 100644
--- a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
+++ b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
@@ -370,6 +370,7 @@
     bool is_attest_key_feature_disabled(void) const;
     bool is_strongbox_enabled(void) const;
     bool is_chipset_allowed_km4_strongbox(void) const;
+    bool shouldSkipAttestKeyTest(void) const;
     void skipAttestKeyTest(void) const;
 
   protected:
@@ -429,6 +430,11 @@
 X509_Ptr parse_cert_blob(const vector<uint8_t>& blob);
 ASN1_OCTET_STRING* get_attestation_record(X509* certificate);
 vector<uint8_t> make_name_from_str(const string& name);
+void assert_mgf_digests_present_in_key_characteristics(
+        const vector<KeyCharacteristics>& key_characteristics,
+        std::vector<android::hardware::security::keymint::Digest>& expected_mgf_digests);
+bool is_mgf_digest_present(const vector<KeyCharacteristics>& key_characteristics,
+                           android::hardware::security::keymint::Digest expected_mgf_digest);
 void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
                         vector<uint8_t>* payload_value);
 void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey);
diff --git a/security/keymint/aidl/vts/functional/KeyMintTest.cpp b/security/keymint/aidl/vts/functional/KeyMintTest.cpp
index 43dc626..1e61a18 100644
--- a/security/keymint/aidl/vts/functional/KeyMintTest.cpp
+++ b/security/keymint/aidl/vts/functional/KeyMintTest.cpp
@@ -2070,7 +2070,8 @@
                         builder, &key_blob, &key_characteristics);
             }
         }
-        ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
+
+        device_id_attestation_check_acceptable_error(tag.tag, error);
     }
 }
 
@@ -3430,7 +3431,6 @@
  * Verifies ECDSA signature/verification for all digests and required curves.
  */
 TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
-
     string message = "1234567890";
     string corrupt_message = "2234567890";
     for (auto curve : ValidCurves()) {
@@ -4727,6 +4727,102 @@
     }
 }
 
+/*
+ * ImportKeyTest.RsaOaepMGFDigestSuccess
+ *
+ * Include MGF-Digest explicitly in import key authorization list.
+ * Test should import RSA key with OAEP padding and mgf-digests and verify that imported key
+ * should have the correct characteristics.
+ */
+TEST_P(ImportKeyTest, RsaOaepMGFDigestSuccess) {
+    auto mgf_digests = ValidDigests(false /* withNone */, true /* withMD5 */);
+    size_t key_size = 2048;
+
+    ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
+                                               .OaepMGFDigest(mgf_digests)
+                                               .Authorization(TAG_NO_AUTH_REQUIRED)
+                                               .RsaEncryptionKey(key_size, 65537)
+                                               .Digest(Digest::SHA_2_256)
+                                               .Padding(PaddingMode::RSA_OAEP)
+                                               .SetDefaultValidity(),
+                                       KeyFormat::PKCS8, rsa_2048_key));
+
+    CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
+    CheckCryptoParam(TAG_KEY_SIZE, key_size);
+    CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
+    CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
+    CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
+    CheckOrigin();
+
+    // Make sure explicitly specified mgf-digests exist in key characteristics.
+    assert_mgf_digests_present_in_key_characteristics(key_characteristics_, mgf_digests);
+
+    string message = "Hello";
+
+    for (auto digest : mgf_digests) {
+        SCOPED_TRACE(testing::Message() << "digest-" << digest);
+        auto params = AuthorizationSetBuilder()
+                              .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
+                              .Digest(Digest::SHA_2_256)
+                              .Padding(PaddingMode::RSA_OAEP);
+        string ciphertext1 = LocalRsaEncryptMessage(message, params);
+        if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
+        EXPECT_EQ(key_size / 8, ciphertext1.size());
+
+        string ciphertext2 = LocalRsaEncryptMessage(message, params);
+        if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
+        EXPECT_EQ(key_size / 8, ciphertext2.size());
+
+        // OAEP randomizes padding so every result should be different (with astronomically high
+        // probability).
+        EXPECT_NE(ciphertext1, ciphertext2);
+
+        string plaintext1 = DecryptMessage(ciphertext1, params);
+        EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
+        string plaintext2 = DecryptMessage(ciphertext2, params);
+        EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
+
+        // Decrypting corrupted ciphertext should fail.
+        size_t offset_to_corrupt = ciphertext1.size() - 1;
+        char corrupt_byte = ~ciphertext1[offset_to_corrupt];
+        ciphertext1[offset_to_corrupt] = corrupt_byte;
+
+        EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
+        string result;
+        EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
+        EXPECT_EQ(0U, result.size());
+    }
+}
+
+/*
+ * ImportKeyTest.RsaOaepMGFDigestDefaultSuccess
+ *
+ * Don't specify MGF-Digest explicitly in import key authorization list.
+ * Test should import RSA key with OAEP padding and default mgf-digest (SHA1) and
+ * verify that imported key should have the correct characteristics. Default
+ * mgf-digest shouldn't be included in key charecteristics.
+ */
+TEST_P(ImportKeyTest, RsaOaepMGFDigestDefaultSuccess) {
+    size_t key_size = 2048;
+    ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
+                                               .Authorization(TAG_NO_AUTH_REQUIRED)
+                                               .RsaEncryptionKey(key_size, 65537)
+                                               .Digest(Digest::SHA_2_256)
+                                               .Padding(PaddingMode::RSA_OAEP)
+                                               .SetDefaultValidity(),
+                                       KeyFormat::PKCS8, rsa_2048_key));
+
+    CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
+    CheckCryptoParam(TAG_KEY_SIZE, key_size);
+    CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
+    CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
+    CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
+    CheckOrigin();
+
+    // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
+    ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
+}
+
 INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
 
 auto wrapped_key = hex2str(
@@ -5152,16 +5248,19 @@
  */
 TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
     auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
+    auto mgf_digest = Digest::SHA1;
 
     size_t key_size = 2048;  // Need largish key for SHA-512 test.
-    ASSERT_EQ(ErrorCode::OK,
-              GenerateKey(AuthorizationSetBuilder()
-                                  .Authorization(TAG_NO_AUTH_REQUIRED)
-                                  .RsaEncryptionKey(key_size, 65537)
-                                  .Padding(PaddingMode::RSA_OAEP)
-                                  .Digest(digests)
-                                  .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
-                                  .SetDefaultValidity()));
+    ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
+                                                 .Authorization(TAG_NO_AUTH_REQUIRED)
+                                                 .RsaEncryptionKey(key_size, 65537)
+                                                 .Padding(PaddingMode::RSA_OAEP)
+                                                 .Digest(digests)
+                                                 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
+                                                 .SetDefaultValidity()));
+
+    // Make sure explicitly specified mgf-digest exist in key characteristics.
+    ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
 
     string message = "Hello";
 
@@ -5355,6 +5454,9 @@
                                                  .Digest(Digest::SHA_2_256)
                                                  .SetDefaultValidity()));
 
+    // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
+    ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
+
     // Do local RSA encryption using the default MGF digest of SHA-1.
     string message = "Hello";
     auto params =
@@ -5389,14 +5491,19 @@
  */
 TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
     size_t key_size = 2048;
-    ASSERT_EQ(ErrorCode::OK,
-              GenerateKey(AuthorizationSetBuilder()
-                                  .Authorization(TAG_NO_AUTH_REQUIRED)
-                                  .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
-                                  .RsaEncryptionKey(key_size, 65537)
-                                  .Padding(PaddingMode::RSA_OAEP)
-                                  .Digest(Digest::SHA_2_256)
-                                  .SetDefaultValidity()));
+    auto mgf_digest = Digest::SHA_2_256;
+    ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
+                                                 .Authorization(TAG_NO_AUTH_REQUIRED)
+                                                 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
+                                                 .RsaEncryptionKey(key_size, 65537)
+                                                 .Padding(PaddingMode::RSA_OAEP)
+                                                 .Digest(Digest::SHA_2_256)
+                                                 .SetDefaultValidity()));
+
+    // Make sure explicitly specified mgf-digest exist in key characteristics.
+    ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
+    // Make sure default mgf-digest is not included in key characteristics.
+    ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
 
     // Do local RSA encryption using the default MGF digest of SHA-1.
     string message = "Hello";
@@ -5420,14 +5527,17 @@
  * with incompatible MGF digest.
  */
 TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
-    ASSERT_EQ(ErrorCode::OK,
-              GenerateKey(AuthorizationSetBuilder()
-                                  .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
-                                  .Authorization(TAG_NO_AUTH_REQUIRED)
-                                  .RsaEncryptionKey(2048, 65537)
-                                  .Padding(PaddingMode::RSA_OAEP)
-                                  .Digest(Digest::SHA_2_256)
-                                  .SetDefaultValidity()));
+    auto mgf_digest = Digest::SHA_2_256;
+    ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
+                                                 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
+                                                 .Authorization(TAG_NO_AUTH_REQUIRED)
+                                                 .RsaEncryptionKey(2048, 65537)
+                                                 .Padding(PaddingMode::RSA_OAEP)
+                                                 .Digest(Digest::SHA_2_256)
+                                                 .SetDefaultValidity()));
+    // Make sure explicitly specified mgf-digest exist in key characteristics.
+    ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
+
     string message = "Hello World!";
 
     auto params = AuthorizationSetBuilder()
@@ -5444,14 +5554,17 @@
  * with unsupported MGF digest.
  */
 TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
-    ASSERT_EQ(ErrorCode::OK,
-              GenerateKey(AuthorizationSetBuilder()
-                                  .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
-                                  .Authorization(TAG_NO_AUTH_REQUIRED)
-                                  .RsaEncryptionKey(2048, 65537)
-                                  .Padding(PaddingMode::RSA_OAEP)
-                                  .Digest(Digest::SHA_2_256)
-                                  .SetDefaultValidity()));
+    auto mgf_digest = Digest::SHA_2_256;
+    ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
+                                                 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
+                                                 .Authorization(TAG_NO_AUTH_REQUIRED)
+                                                 .RsaEncryptionKey(2048, 65537)
+                                                 .Padding(PaddingMode::RSA_OAEP)
+                                                 .Digest(Digest::SHA_2_256)
+                                                 .SetDefaultValidity()));
+    // Make sure explicitly specified mgf-digest exist in key characteristics.
+    ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
+
     string message = "Hello World!";
 
     auto params = AuthorizationSetBuilder()
diff --git a/threadnetwork/aidl/Android.bp b/threadnetwork/aidl/Android.bp
new file mode 100644
index 0000000..480ac0f
--- /dev/null
+++ b/threadnetwork/aidl/Android.bp
@@ -0,0 +1,22 @@
+aidl_interface {
+    name: "android.hardware.threadnetwork",
+    vendor_available: true,
+    srcs: [
+        "android/hardware/threadnetwork/*.aidl",
+    ],
+
+    stability: "vintf",
+
+    backend: {
+        java: {
+            platform_apis: true,
+        },
+        ndk: {
+            apex_available: [
+                "//apex_available:platform",
+                "com.android.threadnetwork",
+            ],
+            min_sdk_version: "33",
+        },
+    },
+}
diff --git a/threadnetwork/aidl/OWNERS b/threadnetwork/aidl/OWNERS
new file mode 100644
index 0000000..e3111c8
--- /dev/null
+++ b/threadnetwork/aidl/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 1288834
+zhanglongxia@google.com
+xyk@google.com
diff --git a/threadnetwork/aidl/aidl_api/android.hardware.threadnetwork/current/android/hardware/threadnetwork/IThreadChip.aidl b/threadnetwork/aidl/aidl_api/android.hardware.threadnetwork/current/android/hardware/threadnetwork/IThreadChip.aidl
new file mode 100644
index 0000000..e4d4cbe
--- /dev/null
+++ b/threadnetwork/aidl/aidl_api/android.hardware.threadnetwork/current/android/hardware/threadnetwork/IThreadChip.aidl
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2022 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.threadnetwork;
+@VintfStability
+interface IThreadChip {
+  void open(in android.hardware.threadnetwork.IThreadChipCallback callback);
+  void close();
+  void reset();
+  void sendSpinelFrame(in byte[] frame);
+  const int ERROR_FAILED = 1;
+  const int ERROR_INVALID_ARGS = 2;
+  const int ERROR_NO_BUFS = 3;
+  const int ERROR_BUSY = 4;
+}
diff --git a/threadnetwork/aidl/aidl_api/android.hardware.threadnetwork/current/android/hardware/threadnetwork/IThreadChipCallback.aidl b/threadnetwork/aidl/aidl_api/android.hardware.threadnetwork/current/android/hardware/threadnetwork/IThreadChipCallback.aidl
new file mode 100644
index 0000000..e86b3ec
--- /dev/null
+++ b/threadnetwork/aidl/aidl_api/android.hardware.threadnetwork/current/android/hardware/threadnetwork/IThreadChipCallback.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2022 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.threadnetwork;
+@VintfStability
+interface IThreadChipCallback {
+  oneway void onReceiveSpinelFrame(in byte[] frame);
+}
diff --git a/threadnetwork/aidl/android/hardware/threadnetwork/IThreadChip.aidl b/threadnetwork/aidl/android/hardware/threadnetwork/IThreadChip.aidl
new file mode 100644
index 0000000..eebaa46
--- /dev/null
+++ b/threadnetwork/aidl/android/hardware/threadnetwork/IThreadChip.aidl
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2022 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.threadnetwork;
+
+import android.hardware.threadnetwork.IThreadChipCallback;
+
+/**
+ * Controls a Thread radio chip on the device.
+ */
+
+@VintfStability
+interface IThreadChip {
+    /**
+     * The operation failed for the internal error.
+     */
+    const int ERROR_FAILED = 1;
+
+    /**
+     * The invalid arguments.
+     */
+    const int ERROR_INVALID_ARGS = 2;
+
+    /**
+     * Insufficient buffers available to send frames.
+     */
+    const int ERROR_NO_BUFS = 3;
+
+    /**
+     * Service is busy and could not service the operation.
+     */
+    const int ERROR_BUSY = 4;
+
+    /**
+     * This method initializes the Thread HAL instance. If open completes
+     * successfully, then the Thread HAL instance is ready to accept spinel
+     * messages through sendSpinelFrame() API.
+     *
+     * @param callback  A IThreadChipCallback callback instance.
+     *
+     * @throws ServiceSpecificException with one of the following values:
+     *     - ERROR_FAILED        The interface cannot be opened due to an internal error.
+     *     - ERROR_INVALID_ARGS  The callback handle is invalid (for example, it is null).
+     *     - ERROR_BUSY          This interface is in use.
+     */
+    void open(in IThreadChipCallback callback);
+
+    /**
+     * Close the Thread HAL instance. Must free all resources.
+     */
+    void close();
+
+    /**
+     * This method resets the Thread HAL internal state. The callback registered by
+     * `open()` won’t be reset and the resource allocated by `open()` won’t be free.
+     *
+     */
+    void reset();
+
+    /**
+     * This method sends a spinel frame to the Thread HAL.
+     *
+     * This method should block until the frame is sent out successfully or
+     * the method throws errors immediately.
+     *
+     * Spinel Protocol:
+     *     https://github.com/openthread/openthread/blob/main/src/lib/spinel/spinel.h
+     *
+     * @param frame  The spinel frame to be sent.
+     *
+     * @throws ServiceSpecificException with one of the following values:
+     *         - ERROR_FAILED The Thread HAL failed to send the frame for an internal reason.
+     *         - ERROR_NO_BUFS Insufficient buffer space to send the frame.
+     *         - ERROR_BUSY The Thread HAL is busy.
+     */
+    void sendSpinelFrame(in byte[] frame);
+}
diff --git a/threadnetwork/aidl/android/hardware/threadnetwork/IThreadChipCallback.aidl b/threadnetwork/aidl/android/hardware/threadnetwork/IThreadChipCallback.aidl
new file mode 100644
index 0000000..046edc3
--- /dev/null
+++ b/threadnetwork/aidl/android/hardware/threadnetwork/IThreadChipCallback.aidl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2022 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.threadnetwork;
+
+@VintfStability
+interface IThreadChipCallback {
+    /**
+     * This method is called when a spinel frame is received. Thread network
+     * will process the received spinel frame.
+     *
+     * Spinel Protocol:
+     *     https://github.com/openthread/openthread/blob/main/src/lib/spinel/spinel.h
+     *
+     * @param frame  The received spinel frame.
+     */
+    oneway void onReceiveSpinelFrame(in byte[] frame);
+}
diff --git a/threadnetwork/aidl/default/Android.bp b/threadnetwork/aidl/default/Android.bp
new file mode 100644
index 0000000..8b938d2
--- /dev/null
+++ b/threadnetwork/aidl/default/Android.bp
@@ -0,0 +1,88 @@
+//
+//  Copyright (c) 2022 Google LLC.
+//  All rights reserved.
+//
+//  This document is the property of Google LLC, Inc. It is
+//  considered proprietary and confidential information.
+//
+//  This document may not be reproduced or transmitted in any form,
+//  in whole or in part, without the express written permission of
+//  Google LLC.
+
+cc_defaults {
+    name: "threadnetwork_service_default",
+    vintf_fragments: ["threadnetwork-default.xml"],
+    vendor: true,
+    relative_install_path: "hw",
+
+    shared_libs: [
+        "android.hardware.threadnetwork-V1-ndk",
+        "libbase",
+        "libbinder_ndk",
+        "libcutils",
+        "liblog",
+        "libutils",
+    ],
+
+    static_libs: [
+        "openthread-common",
+        "openthread-hdlc",
+        "openthread-platform",
+        "openthread-posix",
+        "openthread-spi",
+        "openthread-url",
+    ],
+
+    srcs: [
+        "main.cpp",
+        "service.cpp",
+        "thread_chip.cpp",
+        "utils.cpp",
+    ],
+}
+
+cc_binary {
+    name: "android.hardware.threadnetwork-service.sim",
+    defaults: ["threadnetwork_service_default"],
+    init_rc: ["android.hardware.threadnetwork-service.sim.rc"],
+    required: ["ot-rcp"],
+}
+
+cc_binary {
+    name: "android.hardware.threadnetwork-service",
+    defaults: ["threadnetwork_service_default"],
+}
+
+cc_fuzz {
+    name: "android.hardware.threadnetwork-service.fuzzer",
+
+    defaults:["service_fuzzer_defaults"],
+    shared_libs: [
+        "libbinder_ndk",
+    ],
+
+    static_libs: [
+        "android.hardware.threadnetwork-V1-ndk",
+        "libbase",
+        "liblog",
+        "openthread-common",
+        "openthread-hdlc",
+        "openthread-platform",
+        "openthread-posix",
+        "openthread-spi",
+        "openthread-url",
+    ],
+
+    srcs: [
+        "thread_chip.cpp",
+        "utils.cpp",
+        "fuzzer.cpp",
+    ],
+
+    required: ["ot-rcp"],
+    fuzz_config: {
+        cc: [
+            "zhanglongxia@google.com",
+        ],
+    },
+}
diff --git a/threadnetwork/aidl/default/android.hardware.threadnetwork-service.sim.rc b/threadnetwork/aidl/default/android.hardware.threadnetwork-service.sim.rc
new file mode 100644
index 0000000..2fb409c
--- /dev/null
+++ b/threadnetwork/aidl/default/android.hardware.threadnetwork-service.sim.rc
@@ -0,0 +1,3 @@
+service vendor.threadnetwork_hal /vendor/bin/hw/android.hardware.threadnetwork-service.sim spinel+hdlc+forkpty:///vendor/bin/ot-rcp?forkpty-arg=1
+    class hal
+    user thread_network
diff --git a/threadnetwork/aidl/default/fuzzer.cpp b/threadnetwork/aidl/default/fuzzer.cpp
new file mode 100644
index 0000000..512708d
--- /dev/null
+++ b/threadnetwork/aidl/default/fuzzer.cpp
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+#include <fuzzbinder/libbinder_ndk_driver.h>
+#include <fuzzer/FuzzedDataProvider.h>
+#include "thread_chip.hpp"
+
+using aidl::android::hardware::threadnetwork::ThreadChip;
+using android::fuzzService;
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    char url[] = "spinel+hdlc+forkpty:///vendor/bin/ot-rcp?forkpty-arg=2";
+    auto service = ndk::SharedRefBase::make<ThreadChip>(url);
+
+    fuzzService(service->asBinder().get(), FuzzedDataProvider(data, size));
+
+    return 0;
+}
+
diff --git a/threadnetwork/aidl/default/main.cpp b/threadnetwork/aidl/default/main.cpp
new file mode 100644
index 0000000..8419041
--- /dev/null
+++ b/threadnetwork/aidl/default/main.cpp
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2022 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 <aidl/android/hardware/threadnetwork/IThreadChip.h>
+#include <android-base/logging.h>
+#include <android/binder_manager.h>
+#include <android/binder_process.h>
+#include <utils/Log.h>
+
+#include "service.hpp"
+#include "thread_chip.hpp"
+
+using aidl::android::hardware::threadnetwork::IThreadChip;
+using aidl::android::hardware::threadnetwork::ThreadChip;
+
+int main(int argc, char* argv[]) {
+    CHECK_GT(argc, 1);
+    std::vector<std::shared_ptr<ThreadChip>> threadChips;
+    aidl::android::hardware::threadnetwork::Service service;
+
+    for (int id = 0; id < argc - 1; id++) {
+        binder_status_t status;
+        const std::string serviceName(std::string() + IThreadChip::descriptor + "/chip" +
+                                      std::to_string(id));
+        auto threadChip = ndk::SharedRefBase::make<ThreadChip>(argv[id + 1]);
+
+        CHECK_NE(threadChip, nullptr);
+
+        status = AServiceManager_addService(threadChip->asBinder().get(), serviceName.c_str());
+        CHECK_EQ(status, STATUS_OK);
+
+        ALOGI("ServiceName: %s, Url: %s", serviceName.c_str(), argv[id + 1]);
+        threadChips.push_back(std::move(threadChip));
+    }
+
+    ALOGI("Thread Network HAL is running");
+
+    service.startLoop();
+    return EXIT_FAILURE;  // should not reach
+}
diff --git a/threadnetwork/aidl/default/service.cpp b/threadnetwork/aidl/default/service.cpp
new file mode 100644
index 0000000..7f583f4
--- /dev/null
+++ b/threadnetwork/aidl/default/service.cpp
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2022 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 "service.hpp"
+
+#include <android-base/logging.h>
+#include <android/binder_manager.h>
+#include <android/binder_process.h>
+#include <utils/Log.h>
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace threadnetwork {
+
+Service::Service(void) : mBinderFd(-1) {
+    binder_status_t status = ABinderProcess_setupPolling(&mBinderFd);
+    CHECK_EQ(status, ::STATUS_OK);
+    CHECK_GE(mBinderFd, 0);
+}
+
+void Service::Update(otSysMainloopContext& context) {
+    FD_SET(mBinderFd, &context.mReadFdSet);
+    context.mMaxFd = std::max(context.mMaxFd, mBinderFd);
+}
+
+void Service::Process(const otSysMainloopContext& context) {
+    if (FD_ISSET(mBinderFd, &context.mReadFdSet)) {
+        ABinderProcess_handlePolledCommands();
+    }
+}
+
+void Service::startLoop(void) {
+    const struct timeval kPollTimeout = {1, 0};
+    otSysMainloopContext context;
+    int rval;
+
+    ot::Posix::Mainloop::Manager::Get().Add(*this);
+
+    while (true) {
+        context.mMaxFd = -1;
+        context.mTimeout = kPollTimeout;
+
+        FD_ZERO(&context.mReadFdSet);
+        FD_ZERO(&context.mWriteFdSet);
+        FD_ZERO(&context.mErrorFdSet);
+
+        ot::Posix::Mainloop::Manager::Get().Update(context);
+
+        rval = select(context.mMaxFd + 1, &context.mReadFdSet, &context.mWriteFdSet,
+                      &context.mErrorFdSet, &context.mTimeout);
+
+        if (rval >= 0) {
+            ot::Posix::Mainloop::Manager::Get().Process(context);
+        } else if (errno != EINTR) {
+            ALOGE("select() failed: %s", strerror(errno));
+            break;
+        }
+    }
+}
+}  // namespace threadnetwork
+}  // namespace hardware
+}  // namespace android
+}  // namespace aidl
diff --git a/light/aidl/default/Lights.h b/threadnetwork/aidl/default/service.hpp
similarity index 62%
rename from light/aidl/default/Lights.h
rename to threadnetwork/aidl/default/service.hpp
index cba147f..6a94791 100644
--- a/light/aidl/default/Lights.h
+++ b/threadnetwork/aidl/default/service.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2020 The Android Open Source Project
+ * Copyright (C) 2022 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.
@@ -14,22 +14,25 @@
  * limitations under the License.
  */
 
-#pragma once
-
-#include <aidl/android/hardware/light/BnLights.h>
+#include "mainloop.hpp"
 
 namespace aidl {
 namespace android {
 namespace hardware {
-namespace light {
+namespace threadnetwork {
 
-// Default implementation that reports a few placeholder lights.
-class Lights : public BnLights {
-    ndk::ScopedAStatus setLightState(int id, const HwLightState& state) override;
-    ndk::ScopedAStatus getLights(std::vector<HwLight>* lights) override;
+class Service : public ot::Posix::Mainloop::Source {
+  public:
+    Service(void);
+
+    void Update(otSysMainloopContext& context) override;
+    void Process(const otSysMainloopContext& context) override;
+    void startLoop(void);
+
+  private:
+    int mBinderFd;
 };
-
-}  // namespace light
+}  // namespace threadnetwork
 }  // namespace hardware
 }  // namespace android
 }  // namespace aidl
diff --git a/threadnetwork/aidl/default/thread_chip.cpp b/threadnetwork/aidl/default/thread_chip.cpp
new file mode 100644
index 0000000..94d1e93
--- /dev/null
+++ b/threadnetwork/aidl/default/thread_chip.cpp
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2022 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 "thread_chip.hpp"
+
+#include <android-base/logging.h>
+#include <android/binder_manager.h>
+#include <android/binder_process.h>
+#include <utils/Log.h>
+
+#include "hdlc_interface.hpp"
+#include "spi_interface.hpp"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace threadnetwork {
+
+ThreadChip::ThreadChip(char* url) : mUrl(), mRxFrameBuffer(), mCallback(nullptr) {
+    static const char kHdlcProtocol[] = "spinel+hdlc";
+    static const char kSpiProtocol[] = "spinel+spi";
+    const char* protocol;
+
+    CHECK_EQ(mUrl.Init(url), 0);
+
+    protocol = mUrl.GetProtocol();
+    CHECK_NE(protocol, nullptr);
+
+    if (memcmp(protocol, kSpiProtocol, strlen(kSpiProtocol)) == 0) {
+        mSpinelInterface = std::make_shared<ot::Posix::SpiInterface>(handleReceivedFrameJump, this,
+                                                                     mRxFrameBuffer);
+    } else if (memcmp(protocol, kHdlcProtocol, strlen(kHdlcProtocol)) == 0) {
+        mSpinelInterface = std::make_shared<ot::Posix::HdlcInterface>(handleReceivedFrameJump, this,
+                                                                      mRxFrameBuffer);
+    } else {
+        ALOGE("The protocol \"%s\" is not supported!", protocol);
+        exit(1);
+    }
+
+    CHECK_NE(mSpinelInterface, nullptr);
+}
+
+void ThreadChip::clientDeathCallback(void* context) {
+    reinterpret_cast<ThreadChip*>(context)->clientDeathCallback();
+}
+
+void ThreadChip::clientDeathCallback(void) {
+    ALOGW("Thread Network HAL client is dead.");
+    close();
+}
+
+void ThreadChip::handleReceivedFrameJump(void* context) {
+    static_cast<ThreadChip*>(context)->handleReceivedFrame();
+}
+
+void ThreadChip::handleReceivedFrame(void) {
+    if (mCallback != nullptr) {
+        mCallback->onReceiveSpinelFrame(std::vector<uint8_t>(
+                mRxFrameBuffer.GetFrame(), mRxFrameBuffer.GetFrame() + mRxFrameBuffer.GetLength()));
+    }
+
+    mRxFrameBuffer.DiscardFrame();
+}
+
+ndk::ScopedAStatus ThreadChip::open(const std::shared_ptr<IThreadChipCallback>& in_callback) {
+    ndk::ScopedAStatus status;
+    AIBinder* binder;
+
+    VerifyOrExit(mCallback == nullptr,
+                 status = errorStatus(ERROR_BUSY, "Interface is already opened"));
+    VerifyOrExit(in_callback != nullptr,
+                 status = errorStatus(ERROR_INVALID_ARGS, "The callback is NULL"));
+    binder = in_callback->asBinder().get();
+    VerifyOrExit(binder != nullptr,
+                 status = errorStatus(ERROR_FAILED, "Failed to get the callback binder"));
+    mBinderDeathRecipient = AIBinder_DeathRecipient_new(clientDeathCallback);
+    VerifyOrExit(AIBinder_linkToDeath(binder, mBinderDeathRecipient, this) == STATUS_OK,
+                 status = errorStatus(ERROR_FAILED, "Failed to link the binder to death"));
+    VerifyOrExit(mSpinelInterface->Init(mUrl) == OT_ERROR_NONE,
+                 status = errorStatus(ERROR_FAILED, "Failed to initialize the interface"));
+
+    mCallback = in_callback;
+    ot::Posix::Mainloop::Manager::Get().Add(*this);
+    status = ndk::ScopedAStatus::ok();
+
+exit:
+    if (!status.isOk()) {
+        if (mBinderDeathRecipient != nullptr) {
+            AIBinder_DeathRecipient_delete(mBinderDeathRecipient);
+            mBinderDeathRecipient = nullptr;
+        }
+        ALOGW("Open failed, error: %s", status.getDescription().c_str());
+    } else {
+        ALOGI("open()");
+    }
+
+    return status;
+}
+
+ndk::ScopedAStatus ThreadChip::close() {
+    VerifyOrExit(mCallback != nullptr);
+    mCallback = nullptr;
+    mSpinelInterface->Deinit();
+
+    ot::Posix::Mainloop::Manager::Get().Remove(*this);
+
+    AIBinder_DeathRecipient_delete(mBinderDeathRecipient);
+    mBinderDeathRecipient = nullptr;
+
+exit:
+    ALOGI("close()");
+    return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ThreadChip::sendSpinelFrame(const std::vector<uint8_t>& in_frame) {
+    ndk::ScopedAStatus status;
+    otError error;
+
+    VerifyOrExit(mCallback != nullptr,
+                 status = errorStatus(ERROR_FAILED, "The interface is not open"));
+
+    error = mSpinelInterface->SendFrame(reinterpret_cast<const uint8_t*>(in_frame.data()),
+                                        in_frame.size());
+    if (error == OT_ERROR_NONE) {
+        status = ndk::ScopedAStatus::ok();
+    } else if (error == OT_ERROR_NO_BUFS) {
+        status = errorStatus(ERROR_NO_BUFS, "Insufficient buffer space to send");
+    } else if (error == OT_ERROR_BUSY) {
+        status = errorStatus(ERROR_BUSY, "The interface is busy");
+    } else {
+        status = errorStatus(ERROR_FAILED, "Failed to send the spinel frame");
+    }
+
+exit:
+    if (!status.isOk()) {
+        ALOGW("Send spinel frame failed, error: %s", status.getDescription().c_str());
+    }
+
+    return status;
+}
+
+ndk::ScopedAStatus ThreadChip::reset() {
+    mSpinelInterface->HardwareReset();
+    ALOGI("reset()");
+    return ndk::ScopedAStatus::ok();
+}
+
+void ThreadChip::Update(otSysMainloopContext& context) {
+    if (mCallback != nullptr) {
+        mSpinelInterface->UpdateFdSet(&context);
+    }
+}
+
+void ThreadChip::Process(const otSysMainloopContext& context) {
+    if (mCallback != nullptr) {
+        mSpinelInterface->Process(&context);
+    }
+}
+
+ndk::ScopedAStatus ThreadChip::errorStatus(int32_t error, const char* message) {
+    return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(error, message));
+}
+}  // namespace threadnetwork
+}  // namespace hardware
+}  // namespace android
+}  // namespace aidl
diff --git a/threadnetwork/aidl/default/thread_chip.hpp b/threadnetwork/aidl/default/thread_chip.hpp
new file mode 100644
index 0000000..294190a
--- /dev/null
+++ b/threadnetwork/aidl/default/thread_chip.hpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <aidl/android/hardware/threadnetwork/BnThreadChip.h>
+#include <aidl/android/hardware/threadnetwork/IThreadChipCallback.h>
+
+#include "lib/spinel/spinel_interface.hpp"
+#include "mainloop.hpp"
+
+#include <android/binder_ibinder.h>
+#include <utils/Mutex.h>
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace threadnetwork {
+
+class ThreadChip : public BnThreadChip, ot::Posix::Mainloop::Source {
+  public:
+    ThreadChip(char* url);
+
+    ndk::ScopedAStatus open(const std::shared_ptr<IThreadChipCallback>& in_callback) override;
+    ndk::ScopedAStatus close() override;
+    ndk::ScopedAStatus sendSpinelFrame(const std::vector<uint8_t>& in_frame) override;
+    ndk::ScopedAStatus reset() override;
+    void Update(otSysMainloopContext& context) override;
+    void Process(const otSysMainloopContext& context) override;
+
+  private:
+    static void clientDeathCallback(void* context);
+    void clientDeathCallback(void);
+    static void handleReceivedFrameJump(void* context);
+    void handleReceivedFrame(void);
+    ndk::ScopedAStatus errorStatus(int32_t error, const char* message);
+
+    ot::Url::Url mUrl;
+    std::shared_ptr<ot::Spinel::SpinelInterface> mSpinelInterface;
+    ot::Spinel::SpinelInterface::RxFrameBuffer mRxFrameBuffer;
+    std::shared_ptr<IThreadChipCallback> mCallback;
+    AIBinder_DeathRecipient* mBinderDeathRecipient;
+};
+
+}  // namespace threadnetwork
+}  // namespace hardware
+}  // namespace android
+}  // namespace aidl
diff --git a/threadnetwork/aidl/default/threadnetwork-default.xml b/threadnetwork/aidl/default/threadnetwork-default.xml
new file mode 100644
index 0000000..d7dee1e
--- /dev/null
+++ b/threadnetwork/aidl/default/threadnetwork-default.xml
@@ -0,0 +1,6 @@
+<manifest version="1.0" type="device">
+    <hal format="aidl">
+        <name>android.hardware.threadnetwork</name>
+        <fqname>IThreadChip/chip0</fqname>
+    </hal>
+</manifest>
diff --git a/threadnetwork/aidl/default/utils.cpp b/threadnetwork/aidl/default/utils.cpp
new file mode 100644
index 0000000..1cb42ec
--- /dev/null
+++ b/threadnetwork/aidl/default/utils.cpp
@@ -0,0 +1,80 @@
+
+/*
+ * Copyright (C) 2022 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 <openthread/instance.h>
+#include <openthread/logging.h>
+#include <openthread/platform/alarm-milli.h>
+#include <utils/Log.h>
+
+void otLogCritPlat(const char* format, ...) {
+    va_list args;
+
+    va_start(args, format);
+    __android_log_vprint(ANDROID_LOG_FATAL, LOG_TAG, format, args);
+    va_end(args);
+}
+
+void otLogWarnPlat(const char* format, ...) {
+    va_list args;
+
+    va_start(args, format);
+    __android_log_vprint(ANDROID_LOG_WARN, LOG_TAG, format, args);
+    va_end(args);
+}
+
+void otLogNotePlat(const char* format, ...) {
+    va_list args;
+
+    va_start(args, format);
+    __android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, format, args);
+    va_end(args);
+}
+
+void otLogInfoPlat(const char* format, ...) {
+    va_list args;
+
+    va_start(args, format);
+    __android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, format, args);
+    va_end(args);
+}
+
+void otLogDebgPlat(const char* format, ...) {
+    va_list args;
+
+    va_start(args, format);
+    __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
+    va_end(args);
+}
+
+void otDumpDebgPlat(const char* aText, const void* aData, uint16_t aDataLength) {
+    constexpr uint16_t kBufSize = 512;
+    char buf[kBufSize];
+
+    if ((aText != nullptr) && (aData != nullptr)) {
+        const uint8_t* data = reinterpret_cast<const uint8_t*>(aData);
+
+        for (uint16_t i = 0; (i < aDataLength) && (i < (kBufSize - 1) / 3); i++) {
+            snprintf(buf + (i * 3), (kBufSize - 1) - (i * 3), "%02x ", data[i]);
+        }
+
+        __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "%s: %s", aText, buf);
+    }
+}
+
+OT_TOOL_WEAK void otPlatAlarmMilliFired(otInstance* aInstance) {
+    OT_UNUSED_VARIABLE(aInstance);
+}
diff --git a/threadnetwork/aidl/vts/Android.bp b/threadnetwork/aidl/vts/Android.bp
new file mode 100644
index 0000000..864e885
--- /dev/null
+++ b/threadnetwork/aidl/vts/Android.bp
@@ -0,0 +1,38 @@
+//
+// Copyright (C) 2022 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.
+//
+
+cc_test {
+    name: "VtsHalThreadNetworkTargetTest",
+    defaults: [
+        "VtsHalTargetTestDefaults",
+        "use_libaidlvintf_gtest_helper_static",
+    ],
+    srcs: [
+        "VtsHalThreadNetworkTargetTest.cpp",
+    ],
+
+    shared_libs: [
+        "libbinder",
+        "libbinder_ndk",
+    ],
+    static_libs: [
+        "android.hardware.threadnetwork-V1-ndk",
+    ],
+    test_suites: [
+        "general-tests",
+        "vts",
+    ],
+}
diff --git a/threadnetwork/aidl/vts/VtsHalThreadNetworkTargetTest.cpp b/threadnetwork/aidl/vts/VtsHalThreadNetworkTargetTest.cpp
new file mode 100644
index 0000000..04c6dea
--- /dev/null
+++ b/threadnetwork/aidl/vts/VtsHalThreadNetworkTargetTest.cpp
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2022 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 "ThreadNetworkHalTargetTest"
+
+#include <future>
+
+#include <aidl/Gtest.h>
+#include <aidl/Vintf.h>
+#include <android-base/logging.h>
+#include <android/binder_auto_utils.h>
+#include <android/binder_manager.h>
+#include <binder/IServiceManager.h>
+#include <binder/ProcessState.h>
+#include <log/log.h>
+
+#include <aidl/android/hardware/threadnetwork/BnThreadChipCallback.h>
+#include <aidl/android/hardware/threadnetwork/IThreadChip.h>
+
+using aidl::android::hardware::threadnetwork::BnThreadChipCallback;
+using aidl::android::hardware::threadnetwork::IThreadChip;
+using android::ProcessState;
+using ndk::ScopedAStatus;
+using ndk::SpAIBinder;
+
+namespace {
+constexpr static int kCallbackTimeoutMs = 5000;
+}  // namespace
+
+class ThreadChipCallback : public BnThreadChipCallback {
+  public:
+    ThreadChipCallback(const std::function<void(const std::vector<uint8_t>&)>& on_spinel_message_cb)
+        : on_spinel_message_cb_(on_spinel_message_cb) {}
+
+    ScopedAStatus onReceiveSpinelFrame(const std::vector<uint8_t>& in_aFrame) {
+        on_spinel_message_cb_(in_aFrame);
+        return ScopedAStatus::ok();
+    }
+
+  private:
+    std::function<void(const std::vector<uint8_t>&)> on_spinel_message_cb_;
+};
+
+class ThreadNetworkAidl : public testing::TestWithParam<std::string> {
+  public:
+    virtual void SetUp() override {
+        std::string serviceName = GetParam();
+
+        ALOGI("serviceName: %s", serviceName.c_str());
+
+        thread_chip = IThreadChip::fromBinder(
+                SpAIBinder(AServiceManager_waitForService(serviceName.c_str())));
+        ASSERT_NE(thread_chip, nullptr);
+    }
+
+    virtual void TearDown() override { thread_chip->close(); }
+
+    std::shared_ptr<IThreadChip> thread_chip;
+};
+
+TEST_P(ThreadNetworkAidl, Open) {
+    std::shared_ptr<ThreadChipCallback> callback =
+            ndk::SharedRefBase::make<ThreadChipCallback>([](auto /* data */) {});
+
+    EXPECT_TRUE(thread_chip->open(callback).isOk());
+}
+
+TEST_P(ThreadNetworkAidl, Close) {
+    std::shared_ptr<ThreadChipCallback> callback =
+            ndk::SharedRefBase::make<ThreadChipCallback>([](auto /* data */) {});
+
+    EXPECT_TRUE(thread_chip->open(callback).isOk());
+    EXPECT_TRUE(thread_chip->close().isOk());
+}
+
+TEST_P(ThreadNetworkAidl, Reset) {
+    std::shared_ptr<ThreadChipCallback> callback =
+            ndk::SharedRefBase::make<ThreadChipCallback>([](auto /* data */) {});
+
+    EXPECT_TRUE(thread_chip->open(callback).isOk());
+    EXPECT_TRUE(thread_chip->reset().isOk());
+}
+
+TEST_P(ThreadNetworkAidl, SendSpinelFrame) {
+    const uint8_t kCmdOffset = 2;
+    const uint8_t kMajorVersionOffset = 3;
+    const uint8_t kMinorVersionOffset = 4;
+    const std::vector<uint8_t> kGetSpinelProtocolVersion({0x81, 0x02, 0x01});
+    const std::vector<uint8_t> kGetSpinelProtocolVersionResponse({0x81, 0x06, 0x01, 0x04, 0x03});
+    uint8_t min_major_version = kGetSpinelProtocolVersionResponse[kMajorVersionOffset];
+    uint8_t min_minor_version = kGetSpinelProtocolVersionResponse[kMinorVersionOffset];
+    uint8_t major_version;
+    uint8_t minor_version;
+    std::promise<void> open_cb_promise;
+    std::future<void> open_cb_future{open_cb_promise.get_future()};
+    std::shared_ptr<ThreadChipCallback> callback;
+    std::vector<uint8_t> received_frame;
+    std::chrono::milliseconds timeout{kCallbackTimeoutMs};
+
+    callback = ndk::SharedRefBase::make<ThreadChipCallback>(
+            [&](const std::vector<uint8_t>& in_aFrame) {
+                if (in_aFrame.size() == kGetSpinelProtocolVersionResponse.size() &&
+                    in_aFrame[kCmdOffset] == kGetSpinelProtocolVersionResponse[kCmdOffset]) {
+                    major_version = in_aFrame[kMajorVersionOffset];
+                    minor_version = in_aFrame[kMinorVersionOffset];
+                    open_cb_promise.set_value();
+                }
+            });
+
+    ASSERT_NE(callback, nullptr);
+
+    EXPECT_TRUE(thread_chip->open(callback).isOk());
+
+    EXPECT_TRUE(thread_chip->sendSpinelFrame(kGetSpinelProtocolVersion).isOk());
+    EXPECT_EQ(open_cb_future.wait_for(timeout), std::future_status::ready);
+
+    EXPECT_GE(major_version, min_major_version);
+    if (major_version == min_major_version) {
+        EXPECT_GE(minor_version, min_minor_version);
+    }
+}
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(ThreadNetworkAidl);
+INSTANTIATE_TEST_SUITE_P(
+        Thread, ThreadNetworkAidl,
+        testing::ValuesIn(android::getAidlHalInstanceNames(IThreadChip::descriptor)),
+        android::PrintInstanceNameToString);
+
+int main(int argc, char** argv) {
+    ::testing::InitGoogleTest(&argc, argv);
+    ProcessState::self()->setThreadPoolMaxThreadCount(1);
+    ProcessState::self()->startThreadPool();
+    return RUN_ALL_TESTS();
+}
diff --git a/tv/tuner/1.1/vts/functional/FilterTests.cpp b/tv/tuner/1.1/vts/functional/FilterTests.cpp
index 8bdf8f6..a24cd63 100644
--- a/tv/tuner/1.1/vts/functional/FilterTests.cpp
+++ b/tv/tuner/1.1/vts/functional/FilterTests.cpp
@@ -311,12 +311,6 @@
             android::hardware::tv::tuner::V1_1::IFilter::castFrom(mFilters[filterId]);
     if (filter_v1_1 != NULL) {
         status = filter_v1_1->configureMonitorEvent(monitorEventTypes);
-        if (monitorEventTypes & DemuxFilterMonitorEventType::SCRAMBLING_STATUS) {
-            mFilterCallbacks[filterId]->testFilterScramblingEvent();
-        }
-        if (monitorEventTypes & DemuxFilterMonitorEventType::IP_CID_CHANGE) {
-            mFilterCallbacks[filterId]->testFilterIpCidEvent();
-        }
     } else {
         ALOGW("[vts] Can't cast IFilter into v1_1.");
         return failure();
@@ -324,6 +318,17 @@
     return AssertionResult(status == Result::SUCCESS);
 }
 
+AssertionResult FilterTests::testMonitorEvent(uint64_t filterId, uint32_t monitorEventTypes) {
+    EXPECT_TRUE(mFilterCallbacks[filterId]) << "Test with getNewlyOpenedFilterId first.";
+    if (monitorEventTypes & DemuxFilterMonitorEventType::SCRAMBLING_STATUS) {
+        mFilterCallbacks[filterId]->testFilterScramblingEvent();
+    }
+    if (monitorEventTypes & DemuxFilterMonitorEventType::IP_CID_CHANGE) {
+        mFilterCallbacks[filterId]->testFilterIpCidEvent();
+    }
+    return AssertionResult(true);
+}
+
 AssertionResult FilterTests::startIdTest(uint64_t filterId) {
     EXPECT_TRUE(mFilterCallbacks[filterId]) << "Test with getNewlyOpenedFilterId first.";
     mFilterCallbacks[filterId]->testStartIdAfterReconfigure();
diff --git a/tv/tuner/1.1/vts/functional/FilterTests.h b/tv/tuner/1.1/vts/functional/FilterTests.h
index 1a1273e..e652154 100644
--- a/tv/tuner/1.1/vts/functional/FilterTests.h
+++ b/tv/tuner/1.1/vts/functional/FilterTests.h
@@ -159,6 +159,7 @@
     AssertionResult configAvFilterStreamType(AvStreamType type, uint64_t filterId);
     AssertionResult configIpFilterCid(uint32_t ipCid, uint64_t filterId);
     AssertionResult configureMonitorEvent(uint64_t filterId, uint32_t monitorEventTypes);
+    AssertionResult testMonitorEvent(uint64_t filterId, uint32_t monitorEventTypes);
     AssertionResult getFilterMQDescriptor(uint64_t filterId, bool getMqDesc);
     AssertionResult startFilter(uint64_t filterId);
     AssertionResult stopFilter(uint64_t filterId);
diff --git a/tv/tuner/1.1/vts/functional/VtsHalTvTunerV1_1TargetTest.cpp b/tv/tuner/1.1/vts/functional/VtsHalTvTunerV1_1TargetTest.cpp
index 41acaa1..fccd2ed 100644
--- a/tv/tuner/1.1/vts/functional/VtsHalTvTunerV1_1TargetTest.cpp
+++ b/tv/tuner/1.1/vts/functional/VtsHalTvTunerV1_1TargetTest.cpp
@@ -48,6 +48,11 @@
     }
     ASSERT_TRUE(mFilterTests.getFilterMQDescriptor(filterId, filterConf.config1_0.getMqDesc));
     ASSERT_TRUE(mFilterTests.startFilter(filterId));
+    ASSERT_TRUE(mFrontendTests.tuneFrontend(frontendConf, true /*testWithDemux*/));
+    if (filterConf.monitorEventTypes > 0) {
+        ASSERT_TRUE(mFilterTests.testMonitorEvent(filterId, filterConf.monitorEventTypes));
+    }
+    ASSERT_TRUE(mFrontendTests.stopTuneFrontend(true /*testWithDemux*/));
     ASSERT_TRUE(mFilterTests.stopFilter(filterId));
     ASSERT_TRUE(mFilterTests.closeFilter(filterId));
     ASSERT_TRUE(mDemuxTests.closeDemux());
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 25d704e..ff9c247 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
@@ -34,23 +34,24 @@
 package android.hardware.uwb.fira_android;
 @Backing(type="int") @VintfStability
 enum UwbVendorCapabilityTlvTypes {
-  SUPPORTED_POWER_STATS_QUERY = 192,
-  CCC_SUPPORTED_CHAPS_PER_SLOT = 160,
-  CCC_SUPPORTED_SYNC_CODES = 161,
-  CCC_SUPPORTED_HOPPING_CONFIG_MODES_AND_SEQUENCES = 162,
-  CCC_SUPPORTED_CHANNELS = 163,
-  CCC_SUPPORTED_VERSIONS = 164,
-  CCC_SUPPORTED_UWB_CONFIGS = 165,
-  CCC_SUPPORTED_PULSE_SHAPE_COMBOS = 166,
-  CCC_SUPPORTED_RAN_MULTIPLIER = 167,
-  CCC_SUPPORTED_MAX_RANGING_SESSION_NUMBER = 168,
-  CCC_SUPPORTED_MIN_UWB_INITIATION_TIME_MS = 169,
-  SUPPORTED_AOA_RESULT_REQ_ANTENNA_INTERLEAVING = 227,
-  SUPPORTED_MIN_RANGING_INTERVAL_MS = 228,
-  SUPPORTED_RANGE_DATA_NTF_CONFIG = 229,
-  SUPPORTED_RSSI_REPORTING = 230,
-  SUPPORTED_DIAGNOSTICS = 231,
-  SUPPORTED_MIN_SLOT_DURATION_RSTU = 232,
-  SUPPORTED_MAX_RANGING_SESSION_NUMBER = 233,
-  SUPPORTED_CHANNELS_AOA = 234,
+  SUPPORTED_POWER_STATS_QUERY = 0xC0,
+  CCC_SUPPORTED_CHAPS_PER_SLOT = 0xA0,
+  CCC_SUPPORTED_SYNC_CODES = 0xA1,
+  CCC_SUPPORTED_HOPPING_CONFIG_MODES_AND_SEQUENCES = 0xA2,
+  CCC_SUPPORTED_CHANNELS = 0xA3,
+  CCC_SUPPORTED_VERSIONS = 0xA4,
+  CCC_SUPPORTED_UWB_CONFIGS = 0xA5,
+  CCC_SUPPORTED_PULSE_SHAPE_COMBOS = 0xA6,
+  CCC_SUPPORTED_RAN_MULTIPLIER = 0xA7,
+  CCC_SUPPORTED_MAX_RANGING_SESSION_NUMBER = 0xA8,
+  CCC_SUPPORTED_MIN_UWB_INITIATION_TIME_MS = 0xA9,
+  RADAR_SUPPORT = 0xB0,
+  SUPPORTED_AOA_RESULT_REQ_ANTENNA_INTERLEAVING = 0xE3,
+  SUPPORTED_MIN_RANGING_INTERVAL_MS = 0xE4,
+  SUPPORTED_RANGE_DATA_NTF_CONFIG = 0xE5,
+  SUPPORTED_RSSI_REPORTING = 0xE6,
+  SUPPORTED_DIAGNOSTICS = 0xE7,
+  SUPPORTED_MIN_SLOT_DURATION_RSTU = 0xE8,
+  SUPPORTED_MAX_RANGING_SESSION_NUMBER = 0xE9,
+  SUPPORTED_CHANNELS_AOA = 0xEA,
 }
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvValues.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvValues.aidl
index 0e33f70..702e561 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvValues.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvValues.aidl
@@ -40,17 +40,19 @@
   PULSE_SHAPE_PRECURSOR_FREE = 1,
   PULSE_SHAPE_PRECURSOR_FREE_SPECIAL = 2,
   CHAPS_PER_SLOT_3 = 1,
-  CHAPS_PER_SLOT_4 = 2,
-  CHAPS_PER_SLOT_6 = 4,
-  CHAPS_PER_SLOT_8 = 8,
-  CHAPS_PER_SLOT_9 = 16,
-  CHAPS_PER_SLOT_12 = 32,
-  CHAPS_PER_SLOT_24 = 64,
-  HOPPING_SEQUENCE_DEFAULT = 16,
-  HOPPING_SEQUENCE_AES = 8,
-  HOPPING_CONFIG_MODE_NONE = 128,
-  HOPPING_CONFIG_MODE_CONTINUOUS = 64,
-  HOPPING_CONFIG_MODE_ADAPTIVE = 32,
+  CHAPS_PER_SLOT_4 = (1 << 1) /* 2 */,
+  CHAPS_PER_SLOT_6 = (1 << 2) /* 4 */,
+  CHAPS_PER_SLOT_8 = (1 << 3) /* 8 */,
+  CHAPS_PER_SLOT_9 = (1 << 4) /* 16 */,
+  CHAPS_PER_SLOT_12 = (1 << 5) /* 32 */,
+  CHAPS_PER_SLOT_24 = (1 << 6) /* 64 */,
+  HOPPING_SEQUENCE_DEFAULT = (1 << 4) /* 16 */,
+  HOPPING_SEQUENCE_AES = (1 << 3) /* 8 */,
+  HOPPING_CONFIG_MODE_NONE = (1 << 7) /* 128 */,
+  HOPPING_CONFIG_MODE_CONTINUOUS = (1 << 6) /* 64 */,
+  HOPPING_CONFIG_MODE_ADAPTIVE = (1 << 5) /* 32 */,
   CCC_CHANNEL_5 = 1,
-  CCC_CHANNEL_9 = 2,
+  CCC_CHANNEL_9 = (1 << 1) /* 2 */,
+  RADAR_NOT_SUPPORTED = 0,
+  RADAR_SWEEP_SAMPLES_SUPPORTED = 1,
 }
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
index fbcfbff..34bc4ec 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
@@ -34,7 +34,10 @@
 package android.hardware.uwb.fira_android;
 @Backing(type="byte") @VintfStability
 enum UwbVendorGidAndroidOids {
-  ANDROID_GET_POWER_STATS = 0,
-  ANDROID_SET_COUNTRY_CODE = 1,
-  ANDROID_RANGE_DIAGNOSTICS = 2,
+  ANDROID_GET_POWER_STATS = 0x0,
+  ANDROID_SET_COUNTRY_CODE = 0x1,
+  ANDROID_RANGE_DIAGNOSTICS = 0x2,
+  RADAR_SET_APP_CONFIG = 0x11,
+  RADAR_GET_APP_CONFIG = 0x12,
+  RADAR_DATA_NTF = 0x13,
 }
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGids.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGids.aidl
index 5515c67..f02ed70 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGids.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorGids.aidl
@@ -34,5 +34,5 @@
 package android.hardware.uwb.fira_android;
 @Backing(type="byte") @VintfStability
 enum UwbVendorGids {
-  ANDROID = 12,
+  ANDROID = 0xC,
 }
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvTypes.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvTypes.aidl
new file mode 100644
index 0000000..760166c
--- /dev/null
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvTypes.aidl
@@ -0,0 +1,49 @@
+/*
+ * 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.uwb.fira_android;
+@Backing(type="int") @VintfStability
+enum UwbVendorRadarAppConfigTlvTypes {
+  RADAR_TIMING_PARAMS = 0x0,
+  SAMPLES_PER_SWEEP = 0x1,
+  RADAR_CHANNEL_NUMBER = 0x2,
+  SWEEP_OFFSET = 0x3,
+  RADAR_RFRAME_CONFIG = 0x4,
+  RADAR_PREAMBLE_DURATION = 0x5,
+  RADAR_PREAMBLE_CODE_INDEX = 0x6,
+  RADAR_SESSION_PRIORITY = 0x7,
+  BITS_PER_SAMPLE = 0x8,
+  RADAR_PRF_MODE = 0x9,
+  NUMBER_OF_BURSTS = 0xA,
+  RADAR_DATA_TYPE = 0xB,
+}
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvValues.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvValues.aidl
new file mode 100644
index 0000000..1eb2ce9
--- /dev/null
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvValues.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.uwb.fira_android;
+@Backing(type="int") @VintfStability
+enum UwbVendorRadarAppConfigTlvValues {
+  RADAR_DATA_TYPE_RADAR_SWEEP_SAMPLES = 0x0,
+}
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorReasonCodes.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorReasonCodes.aidl
index a438cbe..db1e0db 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorReasonCodes.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorReasonCodes.aidl
@@ -34,7 +34,7 @@
 package android.hardware.uwb.fira_android;
 @Backing(type="int") @VintfStability
 enum UwbVendorReasonCodes {
-  REASON_ERROR_INVALID_CHANNEL_WITH_AOA = 128,
-  REASON_ERROR_STOPPED_DUE_TO_OTHER_SESSION_CONFLICT = 129,
-  REASON_REGULATION_UWB_OFF = 130,
+  REASON_ERROR_INVALID_CHANNEL_WITH_AOA = 0x80,
+  REASON_ERROR_STOPPED_DUE_TO_OTHER_SESSION_CONFLICT = 0x81,
+  REASON_REGULATION_UWB_OFF = 0x82,
 }
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl
index c3ac401..d02cf4d 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvTypes.aidl
@@ -34,16 +34,16 @@
 package android.hardware.uwb.fira_android;
 @Backing(type="int") @VintfStability
 enum UwbVendorSessionAppConfigTlvTypes {
-  CCC_HOP_MODE_KEY = 160,
-  CCC_UWB_TIME0 = 161,
-  CCC_RANGING_PROTOCOL_VER = 163,
-  CCC_UWB_CONFIG_ID = 164,
-  CCC_PULSESHAPE_COMBO = 165,
-  CCC_URSK_TTL = 166,
-  CCC_LAST_INDEX_USED = 168,
-  NB_OF_RANGE_MEASUREMENTS = 227,
-  NB_OF_AZIMUTH_MEASUREMENTS = 228,
-  NB_OF_ELEVATION_MEASUREMENTS = 229,
-  ENABLE_DIAGNOSTICS = 232,
-  DIAGRAMS_FRAME_REPORTS_FIELDS = 233,
+  CCC_HOP_MODE_KEY = 0xA0,
+  CCC_UWB_TIME0 = 0xA1,
+  CCC_RANGING_PROTOCOL_VER = 0xA3,
+  CCC_UWB_CONFIG_ID = 0xA4,
+  CCC_PULSESHAPE_COMBO = 0xA5,
+  CCC_URSK_TTL = 0xA6,
+  CCC_LAST_INDEX_USED = 0xA8,
+  NB_OF_RANGE_MEASUREMENTS = 0xE3,
+  NB_OF_AZIMUTH_MEASUREMENTS = 0xE4,
+  NB_OF_ELEVATION_MEASUREMENTS = 0xE5,
+  ENABLE_DIAGNOSTICS = 0xE8,
+  DIAGRAMS_FRAME_REPORTS_FIELDS = 0xE9,
 }
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvValues.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvValues.aidl
index a7f487b..5216e1f 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvValues.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionAppConfigTlvValues.aidl
@@ -34,5 +34,5 @@
 package android.hardware.uwb.fira_android;
 @Backing(type="int") @VintfStability
 enum UwbVendorSessionAppConfigTlvValues {
-  AOA_RESULT_REQ_ANTENNA_INTERLEAVING = 240,
+  AOA_RESULT_REQ_ANTENNA_INTERLEAVING = 0xF0,
 }
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionInitSessionType.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionInitSessionType.aidl
index 30a0a1b..bf968bd 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionInitSessionType.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionInitSessionType.aidl
@@ -34,5 +34,6 @@
 package android.hardware.uwb.fira_android;
 @Backing(type="int") @VintfStability
 enum UwbVendorSessionInitSessionType {
-  CCC = 160,
+  CCC = 0xA0,
+  RADAR = 0xA1,
 }
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorStatusCodes.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorStatusCodes.aidl
index 28cf7fe..52f1350 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorStatusCodes.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorStatusCodes.aidl
@@ -34,8 +34,8 @@
 package android.hardware.uwb.fira_android;
 @Backing(type="byte") @VintfStability
 enum UwbVendorStatusCodes {
-  STATUS_ERROR_CCC_SE_BUSY = 80,
-  STATUS_ERROR_CCC_LIFECYCLE = 81,
-  STATUS_ERROR_STOPPED_DUE_TO_OTHER_SESSION_CONFLICT = 82,
-  STATUS_REGULATION_UWB_OFF = 83,
+  STATUS_ERROR_CCC_SE_BUSY = 0x50,
+  STATUS_ERROR_CCC_LIFECYCLE = 0x51,
+  STATUS_ERROR_STOPPED_DUE_TO_OTHER_SESSION_CONFLICT = 0x52,
+  STATUS_REGULATION_UWB_OFF = 0x53,
 }
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/README.md b/uwb/aidl/android/hardware/uwb/fira_android/README.md
index e658d93..7912bbc 100644
--- a/uwb/aidl/android/hardware/uwb/fira_android/README.md
+++ b/uwb/aidl/android/hardware/uwb/fira_android/README.md
@@ -10,6 +10,3 @@
 All other interactions sent/received over the HAL interface is expected to
 comply with the UCI specification that can be found [here](
 https://groups.firaconsortium.org/wg/Technical/document/folder/127).
-
-TODO([b/196004116](b/196004116)): Link to the published specification.
-
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
index 22b7bfe..ceef1be 100644
--- a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvTypes.aidl
@@ -150,6 +150,16 @@
     CCC_SUPPORTED_MIN_UWB_INITIATION_TIME_MS = 0xA9,
 
     /*********************************************
+     * RADAR specific
+     ********************************************/
+    /**
+     * 1 byte bitmask to indicate the supported Radar data types.
+     * Each "1" in this bitmap corresponds to a specific radar data type where:
+     * 0x01 = "Radar Sweep Samples",
+     */
+    RADAR_SUPPORT = 0xB0,
+
+    /*********************************************
      * FIRA specific
      ********************************************/
     /**
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvValues.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvValues.aidl
index 7c86b79..6ef52fe 100644
--- a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvValues.aidl
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorCapabilityTlvValues.aidl
@@ -51,4 +51,10 @@
 
     CCC_CHANNEL_5 = 1,
     CCC_CHANNEL_9 = 1 << 1,
+
+    /*********************************************
+     * RADAR specific
+     ********************************************/
+    RADAR_NOT_SUPPORTED = 0,
+    RADAR_SWEEP_SAMPLES_SUPPORTED = 1,
 }
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
index 4768f55..203b940 100644
--- a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorGidAndroidOids.aidl
@@ -37,4 +37,15 @@
     // Supported only if the UwbVendorCapabilityTlvTypes.SUPPORTED_DIAGNOSTICS set
     // to 1.
     ANDROID_RANGE_DIAGNOSTICS = 0x2,
+
+    /*********************************************
+     * Range 0x10 - 0x1F reserved for RADAR specific
+     * Supported only if the UwbVendorCapabilityTlvTypes.RADAR_SUPPORT is not 0x00.
+     ********************************************/
+    // Used to set application configurations for radar session.
+    RADAR_SET_APP_CONFIG = 0x11,
+    // Used to get application configurations for radar session.
+    RADAR_GET_APP_CONFIG = 0x12,
+    // Used to report radar data for certain radar data types.
+    RADAR_DATA_NTF = 0x13,
 }
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvTypes.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvTypes.aidl
new file mode 100644
index 0000000..a5ea688
--- /dev/null
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvTypes.aidl
@@ -0,0 +1,110 @@
+/*
+ * 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.uwb.fira_android;
+
+/**
+ * Android specific radar app params set/expected in UCI command:
+ * GID: 1100b (Android specific Group)
+ * OID: 010001b (RADAR_SET_APP_CONFIG_CMD)
+ * OID: 010010b (RADAR_GET_APP_CONFIG_CMD)
+ */
+@VintfStability
+@Backing(type="int")
+enum UwbVendorRadarAppConfigTlvTypes {
+    /**
+     * 7 byte data
+     * Radar frame timing parameters:
+     * Octet [3:0] - BURST_PERIOD
+     *   Duration between the start of two consecutive Radar bursts in ms.
+     * Octet [5:4] - SWEEP_PERIOD
+     *   Duration between the start times of two consecutive Radar sweeps in
+     *   RSTU.
+     * Octet [6] - SWEEPS_PER_BURST
+     *   Number of Radar sweeps within the Radar burst.
+     */
+    RADAR_TIMING_PARAMS = 0x0,
+    /**
+     * 1 byte data
+     * The number of samples captured for each radar sweep. (default = 64)
+     */
+    SAMPLES_PER_SWEEP = 0x1,
+    /**
+     * 1 byte data
+     * Same as in FiRa UCI Session App Config.
+     * (default = 9)
+     */
+    RADAR_CHANNEL_NUMBER = 0x2,
+    /**
+     * 2 byte data
+     * Defines the start offset with respect to 0cm distance to limit the sweep
+     * range. Signed value and unit in samples.
+     * (default = 0)
+     */
+    SWEEP_OFFSET = 0x3,
+    /**
+     * 1 byte data
+     * Same as in FiRa UCI Session App Config.
+     * (default = 0x0)
+     */
+    RADAR_RFRAME_CONFIG = 0x4,
+    /**
+     * 1 byte data
+     * Same as in FiRa UCI Session App Config, but extended to 0xA.
+     * (default = 0x2 : 128 symbols)
+     */
+    RADAR_PREAMBLE_DURATION = 0x5,
+    /**
+     * 1 byte data
+     * Same as in FiRa UCI Session App Config, but extended to 127.
+     * (default = 25)
+     */
+    RADAR_PREAMBLE_CODE_INDEX = 0x6,
+    /**
+     * 1 byte data
+     * Same as in FiRa UCI Session App Config.
+     * (default = 50)
+     */
+    RADAR_SESSION_PRIORITY = 0x7,
+    /**
+     * 1 byte data
+     * Bits per sample in the radar sweep.
+     * 0x00 = 32 bits per sample (default)
+     * 0x01 = 48 bits per sample
+     * 0x02 = 64 bits per sample
+     */
+    BITS_PER_SAMPLE = 0x8,
+    /**
+     * 1 byte data
+     * Same as in FiRa UCI Session App Config.
+     * (default = 0x1)
+     */
+    RADAR_PRF_MODE = 0x9,
+    /**
+     * 2 byte data
+     * Maximum number of Radar bursts to be executed in the session. The
+     * session is stopped and moved to SESSION_STATE_IDLE Session State when
+     * configured radar bursts are elapsed.
+     * 0x00 = Unlimited (default)
+     */
+    NUMBER_OF_BURSTS = 0xA,
+    /**
+     * 2 byte data
+     * Type of radar data to be reported.
+     * 0x00: Radar Sweep Samples. Reported in RADAR_DATA_NTF. (default)
+     */
+    RADAR_DATA_TYPE = 0xB,
+}
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvValues.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvValues.aidl
new file mode 100644
index 0000000..81c0a4d
--- /dev/null
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorRadarAppConfigTlvValues.aidl
@@ -0,0 +1,29 @@
+/*
+ * 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.uwb.fira_android;
+
+/**
+ * Android specific radar app config values set/expected in UCI command:
+ * GID: 1100b (Android specific Group)
+ * OID: 010001b (RADAR_SET_APP_CONFIG_CMD)
+ * OID: 010010b (RADAR_GET_APP_CONFIG_CMD)
+ */
+@VintfStability
+@Backing(type="int")
+enum UwbVendorRadarAppConfigTlvValues {
+    RADAR_DATA_TYPE_RADAR_SWEEP_SAMPLES = 0x0,
+}
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionInitSessionType.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionInitSessionType.aidl
index 1e2c817..d3df672 100644
--- a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionInitSessionType.aidl
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionInitSessionType.aidl
@@ -29,4 +29,5 @@
 enum UwbVendorSessionInitSessionType {
     /** Added in vendor version 0. */
     CCC = 0xA0,
+    RADAR = 0xA1,
 }